How to replace XML with Java? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I don't understand worldwide fashion to use XML for storing settings, page or GUI layouts and even bean sets.
If we take into account the fact, that XML is not a single language, but a template to define multiple languages, the mass insanity become obvious.
Why use DOZENS of languages instead of using some ONE?
For example, Java.
It can define or declare any type of GUI hierarchy, setting tables and so on.
So why don't we use java files to store all things?
For example, one could provide settings file in java format like this:
class Properties {
String dbpassword = "password";
String database = "localhost";
String dbuser = "mkyong";
}
The this file could be compiled on the fly by runtime compiler and fields extracted by reflection.
So, why don't we do so?
The only reason coming in mind is security.
External file could contain not only properties but some constructor code, which could hack the application or crash it.
So. Is there any protection for this case? Can we limit possible functionality of runtime compiled files?
UPDATE
I don't mean namely Java. Java is just a sample. I need ways to use single language.
UPDATE 2
I claim, that it would be better to use one single language for entire project aspects.
Suppose that in MVC pattern we would use three separate languages for model, view and controller! This would be nonsense! We use single language. I mean we people use different languages, but each one programmer uses one single language still separating MVC. This is what configuration files are: the separation of one more concept. No any sense to use different language just because concept was separated.
This also applies to HTML / JavaScript / CSS. No sense to have three languages. No any damned sense!
Of course I understand historical reasons etc. But these are no sense, these are just pesky reasons.
So, why then we are seeing new and new projects with the same nature?
Why did MS created XAML for WPF? They made new fresh C# language, why not to put XAML into it too?
Why did Oracle created FXML for JavaFX? Thanks God they abandoned JavaFX script! Because they wanted to have THREE languages for just RIA!

The comments have identified one possible explanation:
A Java syntax would be hard to deal with from other languages.
... though for the configuration properties of Java program, this seems a bit of a stretch. (Why would you read a Java program's config properties from a non-Java program?)
I think the real reason nobody does what you propose is that it introduces some new problems which make your solution as bad as doing XML configs the "hard way".
The person writing the configs needs to understand Java syntax.
If they make a mistake, the application has to deal with a Java compilation error in the middle of starting the application.
Accessing the properties would entail the application programmer writing of reflective code. This code is typically fragile, and writing it would be as hard as writing a bunch of DOM-walking code to read stuff from a parsed XML configuration file.
Now maybe XML is not the best choice for configuration files. These days, I'd prefer classic "Properties" file syntax or JSON.
But it XML is OK too, if you do it the right way. For example:
If you use a Java / XML binding library (e.g. JAXB) you don't need to write an XML parser, or a bunch of gnarly DOM-walking code to pick information out a parse tree.
You can uses a DTD or XML schema driven editor so that the user doesn't need to write (or even see) raw XML files.
If your configs are really complicated, you could use something like EMF to model them and then generate DTDs / Schemas and all of the Java code for the config accessor libraries and customizable application-specific config editors.
For the record, the approach that you proposed is commonly used in scripting languages like Perl, Ruby, Python and even "sh". It just that it tends to be problematic in statically compiled languages.
Re your followup "Why did XXX do YYY" questions:
I don't know. I wasn't in the room.
My opinions would be pure speculation.
It doesn't make any difference why they did it anyway.
And in response to your general "it doesn't make sense" comment/complaint, the IT world is rife with pragmatic compromises / clunky solutions. Complaining about it doesn't achieve anything. If you want to achieve something, try your way out, and show us the evidence that it really works in Java.

Using executable code for configuration is a recipe for disaster. Consider:
class Properties
{
String dbpassword = "password";
String database = "localhost";
String dbuser = "mkyong";
static
{
File userDir = new File("c:\\users\\mkyong");
userDir.delete();
//etc...
}
}
You can try to counter this by using a security manager to limit damage, but they are not perfect. Or you could write your own parser that only accepts a sub-set of what a full Java program can do (limited API, no APIs, etc. similar to JSON vs full Javascript). But at the end of the day, is the Java syntax any better than the other configuration file formats?

Related

Save values to file(e.g yml) in java

First of all this might be a dumb question and I searched for some days but didn't find an answer. So if there is an existing answer concerning my question, I would be grateful for a link.
I don't know if anyone of you ever coded Spigot, Paper or Bukkit, but there was a class called YamlConfiguration which had the following methods:
public FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
cfg.set(path.path2, "hello");
cfg.getInt/String/...(path.path2); (which obviously returns "hello")
cfg.save(file);
The produced file then looks like this:
path:
path2: "hello"
So you could basically save any value in those files and reuse them even if your program has been restarted.
I know have moved forward from Spigot/Paper to native Java and I'm missing something like that Yaml-thing. The only thing I found was a kind of a config file, where every time the whole file is overwritten, when I try to add values.
Can you show me a proper way of saving values to a file? (would be nice without libraries)
I'm missing sth like that Yaml-thing
SnakeYAML should have you covered. Without knowing anything about your use-case, it makes no sense to discuss its usage here since its documentation already does cover the general topics.
The only thing I found was a kind of a config file, where everytime the whole file is overwritten, when I try to add values.
Saving as YAML will always overwrite the complete file as well. Serialization does not really work with append-only. (Serialization is the term to search for when you want functionality like this, by the way.)
If you mean that previous values were deleted, that probably was because you didn't load the file's content before or some other coding error, but since you don't show your code, we can only speculate.
Can you show me a proper way of saving values to a file?
People will have quite different opinions on what would be a proper way and therefore it is not a good question to ask here. It also heavily depends on your use-case.
would be nice without libraries
So you're basically saying „previously I used a library which had a nice feature but I want to have that feature without using a library“. This stance won't get you far in today's increasingly modular software world.
For example, JAXB which offers (de)serialization from/to XML was previously part of Java SE, but has been removed as of Java SE 11 and is a separate library now.

Design pattern for parameter settings that is maintainable in decent size java project

I am looking for concrete ideas of how to manage a lot of different parameter settings for my java program. I know this question is a bit diffuse but I need some ideas about the big picture so that my code becomes more maintainable.
What my project does is to perform many processing steps on data, mostly text. These processing steps are algorithms of varying complexity that often have many settings. I would also like to change which processing steps are used by e.g. configuration files.
The reason for my program is to do repeatable experiments, and because of this I need to be able to get a complete view of all the parameters used in the different parts of the code, preferably in a nice format.
At this (prototype) stage I have the settings in source code like:
public static final param1=0.35;
and each class that is responsible for some processing step has its own hard coded settings. It is actually quite scary because there is no simple way to change things or to even see what is done and with what parameters/settings.
My idea is to have a central key/value store for all settings that also supports a dump of all settings. Example:
k:"classA_parameter1",v:"0.35"
k:"classC_parameter5",v:"false"
However, I would not really like to just store the parameters as strings but have them associated to an actual java class or object.
Is it smarter to have a singleton "SettingsManager" that manages everything. Or to have a SettingsManager object in each class that main has access to? I don't really like storing string descriptions of the settings but I cant see any other way (Lets say one setting is a SAXparser implementation that is used and another parameter is a double, e.g. percentage) since I really don't want to store them as Objects and cast them.
Experience and links to pages about relevant design patterns is greatly appreciated.
To clarify, my experiments could be viewed as a series of algorithms that are working on data from files/databases. These algorithms are grouped into different classes depending on their task in the whole process, e.g.
Experiment //main
InternetLookup //class that controls e.g. web scraping
ThreadedWebScraper
LanguageDetection //from "text analysis" package
Statistics //Calculate and store statistics
DatabaseAccess
DecisionMaking //using the data that we have processed earlier, make decisions (machine learning)
BuildModel
Evaluate
Each of the lowest level classes have parameters and are different but I still want a to get a view of everything that is going on.
You have the following options, starting with the simplest one:
A Properties file
Apache Commons Configuration
Spring Framework
The latter allows creation of any Java object from an XML config file but note that it's a framework, not a library: this means that it affects the design of the whole application (it promotes the Inversion of Control pattern).
This wheel has been invented multiple times already.
From the most basic java.util.Properties to the more advanced frameworks like Spring, which offers advanced features like value injection and type conversion.
Building it yourself is probably the worst approach.
Maybe not a complete answer to your question, but some points to consider:
Storing values as strings (and parsing the strings into other types via your SettingsManager) is the usual approach. If your configuration value is too complex to do this then it's probably not really a configuration value, but part of your implementation.
Consider injecting the individual configuration values required by each class via constructor arguments, rather than just passing in the whole SettingsManager object (see Law of Demeter)
Avoid creating a Singleton SettingsManager if possible, singletons harm testability and damage the design of your application in various ways.
If the number of parameters is big I would split them to several config files. Apache Commons Configuration, as mentioned by #Pino is really a nice library to handle them.
On the Java-side I would probably create one config-class per file and wrap Commons Configuration config to load settings, eg:
class StatisticsConfig {
private Configuration config = ... ;
public double getParameter1() {
return config.getDouble("classA_parameter1");
}
}
This may need quite a lot of boilerplate code if the number of parameters is big but I think it is quite clean solution (and easy to refactor).

Evaluating creation of GUI via file vs coding

I'm working on a utility that will be used to test the project I'm currently working on. What the utility will do is allow user to provide various inputs and it will sends out requests and provide the response as output.
However, at this point the exact format (which input is required and what is optional) has yet to be fleshed out. In addition, coding in Swing is somewhat repetitive since the overall work is simple though this should be the safest route to go as I have more or less full control and every component can be tweaked as I want. I'm considering using a configuration file that's in XML to describe the GUI (at least one part of it) and then coding the event handling part (in addition to validation, etc). The GUI itself shouldn't be too complicated. For each type of request to make there's a tab for the request and within each tab are various inputs.
There seems to be quite a few questions about this already but I'm not asking for a 3rd party library to do this. I'm looking to do this myself, since I don't think it'll be too overly complicated (hopefully). My main consideration for using this is re-usability (later on, for other projects) and for simplifying the GUI work. My question is: are there other pros/cons that I'm overlooking? Is it worth the (unknown) time to do this?
I've built GUI in VB.NET and with Flex3 before.
XML is so 2000. It's code, put it in real source files. If it really is so simple that it could be XML, all you are doing is removing the XML handling step and using a clearer syntax. If it turns out to be a little more complicated than you first expected, then you have the full power of your favourite programming language to hand.
In my experience, if your layout really is simple, something like the non-visual builders in FormLayout can lead to really concise code with a minimum of repetition.
If you have to specify the precise location of every control you might look at a declarative swing helper toolkit that can minimize boilerplate and simplify layout. Groovy supports this as does JavaFX, and both are simple library extensions to Java (give or take).
If the form is laid out in a pattern, using a definition file in a format like XML or YAML will work. I've done that and have even set up data bindings in that file so that you don't even have to deal with listeners or initial values...
If you are sure you want XML, I'd seriously consider YAML though, it's really close but instead of:
<outer>
<inner a=1> abc </inner>
</outer>
I think it's a lot more like:
outer
inner a=1
abc
(I may have that a bit wrong, but that's close I think. Anyway, you should never force anyone to type XML--if you are set on XML, provide a GUI with which to edit it!)

What are the lightweight options one has to persist Java objects [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What are the lightweight options one has to persist Java objects ?
I'm looking for the easiest possible solution. I don't want anything fancy featurewise just something simple that works with reasonnably simple objects (some collections, relationships and simple inheritance) and doesn't bring too much apparent complexity (if any) to the existing codebase.
The options I'm aware of include Hibernate and frameworks such as EMF but they sound (and have been experienced to be) too complex and time-consuming. I'd like something out of the box, preferably file oriented than dababase oriented, that I can just put on top of my plain old java objects.
This is a newbie question, thanks in advance for any tutorial-like, context clarifying guidance.
db4o is an object database so there's no schema setup and it adapts well to changes in object structure over time.
If you are looking at something simple you might also want the data in a format you can read (not a binary file or database). If that is the case, you should look at JAXB (Java's XML Binding) that is part of Java 6 and later. There are other technologies that may be able to do this better such as XML Beans but this one is built in.
Take a look at this page from Java's API. It is pretty straight forward to serializing and deserializing Java objects.
http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXBContext.html
Basically you use the following:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
// unmarshal from foo.xml
Unmarshaller u = jc.createUnmarshaller();
FooObject fooObj = (FooObject)u.unmarshal( new File( "foo.xml" ) );
// marshal to System.out
Marshaller m = jc.createMarshaller();
m.marshal( fooObj, System.out );
Just make sure your FooObject has the #XmlRootElement annotation. Java bean properties are automatically interpreted but you can use other annotations to control how the XML looks and model more complex objects.
The ObjectOutputStream and ObjectInputStream can do this. It's built into Java and allows you to serialize/deserialize objects quite easily.
The bad thing about these is that if you change your objects you can't import existing old objects. You'll have to think of a way to stay compatible with existing objects that might already be saved on a user's computer, such as adding a version number to your classes and creating the ability to convert old objects to new ones.
More info here:
http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectOutputStream.html
http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectInputStream.html
EDIT:
You may also consider adding the following attribute to all your classes right off the bat. This may allow you to then add attributes to classes and still be able to load old Object files. In RMI-land this works, but I'm not sure about files. Don't ever remove attributes though.
static final long serialVersionUID = 1L;
Try Simple XML persistence http://simple.sourceforge.net. Its really simple and requires no configuration. Just take your existing POJOs and annotate them, then you can read and write them to a file. Cyclical object graphs are supported as well as all Java collections. It can be used like so.
Serializer serializer = new Persister();
MyObject object = serializer.read(MyObject.class, new File("file.xml));
and writing is just as easy
serializer.write(myInstance, new File("file.xml"));
This is an extremely lightweight approach, no dependancies other than standard Java 1.5. Compared with other object to XML technologies such as JAXB, XStream, Castor, which are dependant on a whole host of other projects Simple XML is very lightweight and memory efficient.
See this similar question Light-weight alternative to hibernate. The most light weight framework I know of is iBatis
You could try XStream which is an open source library. All it does is turn your POJOs into XML which you can then saved to disk. It is very easy to use and requires only a few lines of code to use.
One simple approach is to serialize (as in Serializable) your objects to disk.
http://www.devx.com/Java/Article/9931/1954
The simplest option I know of is using Xstream to make an xml file out of ANY java obect.
I have to say the initial learning curve for Hibernate is relatively shallow. You should be able to get a test system up and running in less than a day. It's only when you want the more advanced features where it starts to get steeper. I would recommend you definitely take a look, I mean what's a day if you end up not choosing it?
Having said that, have you considered just serializing your objects directly to disk if you just want something quick n dirty?
I have used PersistentObject extensively in production code and it serves my needs well.

Why do people use Velocity and/or NVelocity?

Over the past year I have heard alot about Velocity and NVelocity. Reading their documentation and doing searches on the net hasn't given me the answers I was looking for.
In what situation would I use this library in my development? What problem does it solve that didn't already have a solution?
Since the dawn of web apps, people started to think about separation of concerns in many applications, including web applications. The challenge is to separate what is view code from what is business code, or logic code. When jsps first arrived, many people where coding lots of logic in jsps directly (stuff like db access and other), breaking the basic principle of separation of concerns (jsps should be responsible for the presentation, not for the logic).
Velocity, Freemarker and others are templating engines that allows the separation of UI logic and business logic, thus facilitating changes in the presentation while minimizing the changes on the business side. These template engines have facilities for doing common UI tasks such as showing a block of html if some condition holds true, or iterating over a list while maintaining logic code outside of the view. This is fundamental for maintaining a complex application in the long run.
I think it's important to point out that compared to JSP/ASP.NET as a templating mechanisim, Velocity/NVelocity really 'ENFORCE' the seperation of concern.
With <% .. %> of JSP/ASP.NET, any Java/.NET code is allowed. Which is why sometimes you do see business logic code in these files.
With Velocity/NVelocity you can't embed long series of code. Instead you are really forced to pass in computed values, which Velocity/NVelocity picks up and displays them according to the way the template is designed.
Another point would be that they can work outside of a Web Container environment (at least Velocity can AFAIK). Imagine that you had designed a report template with JSP/ASP.NET. It works fine from the web. And then suddenly there is a change request to have it be done from a Desktop application. Rather than embed a Web Container in it, you could initialize Velocity/NVelocity, compute the values, then render the template.
It's a template engine. If you have a lot of static text with variable content mixed in, templates are a great way to reduce the amount of work you have to do.
It's a whole lot better than String.Format or loads of concatenation because it's not as repetitive or error prone, and far more maintainable since you can figure out exactly what your template does just by looking at it.
We use templating to generate configuration files for production, UAT, system test, contingency systems etc.
We have a master Spring configuration file into which we inject a property file. We have a master property file that is parsed by Velocity and this allows us to keep all system settings in one file.
As a bonus, for the ones interested, I recommend reading the following:
http://www.artima.com/lejava/articles/stringtemplate.html
http://www.cs.usfca.edu/~parrt/papers/ST.pdf
These are links about StringTemplate, a templating engine by Terence Parr who wrote antlr, a parser that's been used everywhere (ex: hibernate uses antlr).
1 - Velocity engine actually merges the real time data with the xyz.vm file which holds the static information 2 - The vm file uses Velocity Template Language(VTL)
(It can iterate over the java iterable java objects placed on the context , can call the methods accessible by the objects placed on the context) Situations to use Velocity - Brings the power of java to html not only to html 1-When you have to generate report mails often with varying data and constant style.(foreach support)
2-When you want to merge a real time data with dummy place-Holder in deeply nested contents
3-When you want to decide style information based on the value of the data (if else support)and many more
Refer - http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html

Categories