I write applications that need alot of options. These options can be handed to the application by a xml file. Theses files are quite big with some levels and a few dependancies not modelable in a schema.
So the file passes the jdom schema check. Now I want to create some config object for the application and set some variables in some classes.
I don't really see any way not hardcoding the names of the elements and attributes and then looping over these elements and creating new objects.
This makes a 20kLoc application have 25 classes only holding configurations for other classes.
Is there some golden hammer rule how to use xml and customize applications. It comes down to putting the information in the file into some lists, hashtables and attributes of objects.
Can that be done easier? Some awesome framework, maybe? Reflection? Beans? Beans is just a hype word for java programming, or am I missing something?
Who controls the schema of the configuration files? If you can change it, you can simplify it enough to limit the number of classes needed.
If they are imposed from the outside, you might get some traction with Apache Commons BeanUtils and Betwixt.
Related
I create internationalization for my application and am wondering if I can create several files to create translated messages. I do not think it's advisable, but I prefer to ask.
The thing is that I have a 'messages.properties' file where I have some text already
http s://pastebin.com/WdyE0Aaj
And this is just the beginning. What if I will have dozens of pages and for each page I will have to declare here translation. After all, this file will go on in the hundreds and then thousands. Can it be somehow divided into more files?
Of course you can (and probably should, to keep things maintainable).
The Spring-boot reference says:
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
So, just add as many basenames as you want to your spring boot properties/yaml file, and they will all be agregated in a single MessageSource. Just make sure to avoid conflicts in the i18n property names.
This question already has answers here:
Xml configuration versus Annotation based configuration [closed]
(16 answers)
Closed 9 years ago.
i am new to java here, I was reading about annotations and xml, personally I find out xml has lot of advantages like it can be put outside application, changes can be made without recompiling class files. If i use annotations if I need to make changes need to go to source code and recompiling should be done. If this is the case why should we use annotations
Advantages of the annotation:
1) All the information is in a single file (no need to open two files to configure a given behavior)
2) When the class changes, no need to modify the xml file
Advantages of xml file:
1) Clear separation between the POJO and its behavior
2) When you do not know which POJO is responsible for the behavior, it is easier to find that POJO (searching in a subset of files rather than all the source code)
First of all we use annotations for many more things, than just configuration.
Now: Some advantages of using annotations for configuration
Readability. For example in JPA configuration its much more cleaner to declare new entities by Annotations instead of hbm.xml files. These things change only in development stage so there is no problem with recompiling code. When You use xml files You have to often open both- entity and hbm file to make changes.. That can cause some errors.
Flexibility. In XML files you have to write all configs in "only one proper way". It is advantage and disadvantage at the same time.
Length. XML-based configs are often very long (like pom's, or hbm's). Annotations are much simpler to use.
The question is actually a difficult one to answer in a short answer.
Basically, there are pros and cons to all forms of configuration. Annotations, xml or Java Based Configuration. All the pros and cons are 100% valid. The main goal them becomes consistency. Making sure everyone on your project follows the same rules.
It is also NOT a question of either or, which one over the other. Because you can use any combination of configuration options in your application. One or all three combined. You just have to make your rules and stick to them
So my personal opinion is. Remember this is all my opinion and not fact.
1) Annotations over all other because I can configure and code much faster
2) Java Based configuration for those beans I can't annotate (They aren't my classes so I don't have the source to add an Annotation)
3) xml with what is left, or I need it complete externalized outside the package of my classes and I don't want to recompile and repackage. (Extremely rare, like it has never happened to me yet that I needed this)
I had written a lot of java bean classes using my IDE. Another person suggests a different approach. He suggests that I put an xml file with bean definitions in them. Then I either use jaxb or xslt to dynamically generate the classes during build time. Though its a novel and interesting approach, I do not see any major benefit in it.
I see only one benefit in this suggested approach : The java bean classes need not be maintained in configuration control. Any bean changes is going to require only an update in the xml file.
Are there any major benefits in dynamically generating java classes ? Is there any other reason why this approach is taken ?
I agree with #Akhilss. My experiences have been in large scale Java EE projects where code generation is common.
It all depends on your project. If you are coding only a few beans and only need basic functionality then I don't see the need to start with XML (Which is often over used anyway). Especially if you actually don't need the XML as well.
However if you are building a system which needs the XML, an example being a SOAP web service WSDL and schema, then generation is a good idea because it saves you from manually keep schemas and beans in sync. As well as providing factory classes and other support code.
As a counter argument, with EJB3 and similar standards, it's now often easier to write the beans and generate the messy XML stuff on the fly. Ie. let the server do the grunt work.
Another reason to consider code generation is if you require more complex functionality in your beans because they represent data structures. A few years ago I trialled the Apache Tuscany project for generating SDO beans from XML. The nice thing about that was that I could generate functionality like property change notifications so when I modified any of the bean's properties (including collections), other parts of your program could be notified automatically. Generated functionality like that can save you a lot of time and money if you need it.
Ultimately, I'd suggest adhering to the KISS principle. So don't add what you don't need. Generated code from XML is useful if it helps you in the long run. But like any technology, be sure you are adding it for the right reasons.
I have used Jibx and its generator in my project. My experience has been mixed.
The usual case for using JAXB's (XJC) generator is referred to in http://static.springsource.org/spring-ws/site/reference/html/why-contract-first.html
Conversion to and from XML maked it possible to store in the DB and retrieve for future use as well as use for test case input for functional tests.
Using any kind of generator (Jaxb,Jibx,XMLBeans,Custom) might make sense for large sized projects. It allows for standardization of data types (like BigDecimal for financial amounts, like ArrayList for all lists), forcing interfaces (like Serializable or Cloneable). This enforces good practices and reduce the need for reviews of generated files.
It allows for injection of code through XSLT or post processing of generated java file. Example is to inject Rounding code to a specific decimal size(2,6,9) with a specific policy (UP,DOWN,NEAR) within the setter method for each field of type financialAmount. Forcing such behavior does reduce the instance of bugs(for incorrect financial values which companies are liable for).
The disadvantage are
Usually each java class can be only a bean class. Any customization made will be overwritten. Since (in my case) the generator is tied in to the build process. The classes get generated with every build.
You cannot do implementation of your custom interfaces on a bean class or add annotations for your own or third party frameworks.
You cannot easily implement patterns like a factory method since default constructors are usually generated. Refactoring is usually difficult since generators do not usually support it.
You may(not sure now, was true a couple of years ago for Jibx) not be able to generated ENUMS when it would be most applicable.
You may not be able to override the default datatype with your own regardless of the need. CopyOnWrite list and not ArrayList for a variable shared across threads or a custom implementation of a List which also implements the Observer pattern.
The benefits of a generator outweigh the costs for large sized (in persons and not code, think 150 developers in three locations) distributed projects. You can work around the disadvantages by defining your custom classes which contain the bean and implements behaviour or post processing (adding additional code) with further metadata picked up from XSD annotations or another configuration file. Remember support and Maintenance of the generator become critical since the entire project depends on it. Use it with CAUTION.
For smaller sized projects I personally would write my own classes. For larger sized projects I personally would not use it in the middle tier mostly because of the lack of refactoring support. It can be used for simple beans meant to be bound to UI frameworks.
I am new to Java and I came across a statement in a Java project which says:
Digester digester = DigesterLoader.createDigester(getClass()
.getClassLoader().getResource("rules.xml"));
rules.xml file contains various patterns and every pattern has different attributes like classname, methodname and some another properties.
i googled about digester but couldn't found anything useful that could help me with the statement above. can anyone just tell me what are the steps followed in executing above statement ? In fact what is the advantage of this XML stuff ?
swapnil, as a user of Digester back in my Struts days I can honestly say it's tricky to learn/debug. It's a tough library to familiarize yourself with, essentially you are setting up event handlers for certain elements kinda like a SAX parser (in fact it's using SAX in behind the scenes). So you feed a rules engine some XPath for nodes you are interested in and setup rules which will instantiate, and set properties on some POJOs with data it finds in the XML file.
Great idea, and once you get used to it it's good, however if you have an xsd for your input xml file I'd sooner recommend you use JAXB.
The one thing that is nice about Digester is it will only do things with elements you are interested in, so memory footprint ends up being nice and low.
This is the method that's getting called here. Xml is used commonly in Java for configurations, since xml files do not need to be compiled. Having the same configuration in a java file would mean you have to compile the file.
I assume you understand how the rules file is being loaded using the class loader? It's basically looking in the same package as the class itself and creating a URL that gives the file's absolute location.
As for the Digester, I've not used it but a quick read of this (http://commons.apache.org/digester/) should explain all.
They used it at my last gig and all I remember is that it was extremely slow.
What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?
The easiest way here is to serialize the object graph.
Java 1.4 has built in support for serialization as XML.
A solution I have used successfully is XStream (http://x-stream.github.io/)- it's a small library that will easily allow you to serialize and deserialize to and from XML.
The downside is you can only very limited define the resulting XML; which might not be neccessary in your case.
Apache digester is fairly easy: http://commons.apache.org/digester/
JAXB is newer and comes with annotation goodness: https://jaxb.dev.java.net
XStream by the folks at Thoughtworks has a simple API and even deals with things like duplicate and circular references. It seems to be actively developed and is well documented.
http://x-stream.github.io/
Use java.beans.XMLEncoder. Its API is very simple (actually a little too simple; it'd be nice to wire it to a SAX ContentHandler), but it works on many graphs out of the box, and it's easy to create your own persistence delegate for any odd-ball classes you might encounter.
The syntax used by XMLDecoder allows
you to invoke any method, instance
or static, including constructors,
so it's extremely flexible.
Other encoders name
elements and attributes after class
and field names, so there's no fixed schema for the result. The XMLEncoder's
XML follows a simple DTD and can
easily be validated or transformed,
even when you've never seen the
types it uses.
You can assign objects an
identifier, and reference them
throughout the graph.
You can refer to constants defined
in classes or interfaces.
And, it's built into Java SE, so you don't need to ship an extra library.
Simple
Although XStream and JAXB can serialize an some object graphs succssfully they can not handle very complex graphs. The most powerful solution for large complex graphs is Simple XML Serialization. It can handle any graph. Also, it’s fast and simple to use without any dependencies.
To quote the Simple project page:
Simple is a high performance XML serialization and configuration framework for Java. Its goal is to provide an XML framework that enables rapid development of XML configuration and communication systems. This framework aids the development of XML systems with minimal effort and reduced errors. It offers full object serialization and deserialization, maintaining each reference encountered. In essence it is similar to C# XML serialization for the Java platform, but offers additional features for interception and manipulation.
The Simple API is, well, simple! It's really good. http://simple.sourceforge.net/
You can also use XStream: http://www.ibm.com/developerworks/library/x-xstream/index.html
JAX-B is part of the standard APIs and really easy to use.
If you need control over the XML that gets generated, I recommend taking a look at Betwixt (http://commons.apache.org/betwixt/) - it adds a lot of functionality to Apache's digester (Digester is good for building object graphs from XML, but is not so good for generating them).
If you really don't care about the XML that gets generated (just that it can be deserialized in the future), then the XMLEncoder/Decoder classes built into Java or good - as long as the objects you are serializing follow the JavaBean specification. The biggest area I've run into problems with the XMLEncoder/Decoder solution is if you have a bean that returns an immutable list for one of it's properties - the encoder doesn't handle that situation very well.
If you need to control the structure of the XML, the XStream is a good choice. You can use annotations to define precisely the structure/mapping of the XML and your objects.
I'd second (or third) XStream. It reads and writes XML without needing any special binding configuration or placing lots of extraneous syntax in the XML.
I put together a list with a lot of xml serialization libraries and its license
XStream is very simple http://x-stream.github.io/
XStream is a simple library to serialize objects to XML and back again.
java.beans.XMLEncoder perhaps?
Jackson
The Jackson Project is a processing and binding library for XML, JSON, and some other formats.
… Jackson is a suite of data-processing tools for Java (and the JVM platform), including the flagship streaming JSON parser / generator library, matching data-binding library (POJOs to and from JSON) and additional data format modules to process data encoded in Avro, BSON, CBOR, CSV, Smile, (Java) Properties, Protobuf, XML or YAML; and even the large set of data format modules to support data types of widely used data types such as Guava, Joda, PCollections and many, many more…
If you are really only interested in serializing your objects to a file and then deserializing them later, then you might check out YAML instead of XML. YAML is much easier to work with than XML and the output files are very human-readable (which may or may not be a requirement). Check out yaml.org for more information. I've used JYAML successfully on a recent project.