"Storing" an object for future use in Java - java

I have an XML file that has certain properties and mappings defined in it. These properties change very rarely. I don't want to reload and evaluate the properties/mappings every time I call use my jar file. Is there any way I can pre-compile my XML file into an object, so that the XML values get stored in the object? Whenever I change the XML file, if ever, I just need to recompile it once.

You could just use a Java file to define these properties and mappings to begin with. No need to mess with XML if you aren't going to take advantage of loading changes to it without recompiling.

After you've read your XML data into an object you could write it to a file using Serialization and check next time, before you load your XML source whether it has been changed (by comparing their timestamps). In cases the XML source hasn't changed you could simply restore the configuration object by de-serialization from the file system.

Couple a questions that might help you find an approach are:
How big is your XML file?
How long does it take for you to parse it and turn it into an object?
Is it prohibitive to have this process (load + parse + convert to object) every time your library loads?
Spring does exactly this; you configure the context with XML and when you boot your application it loads, parses and creates the objects according to your configuration. I've been dealing with big XML files in Spring and I can say it's pretty fast - and considering it's only done once, at boot, it's hardly ever a problem.
Spring also has an alternative in which your configuration is actual code, but I'm guessing you want to stick to XML configuration.
Another approach is having a tool to read the XML, convert it to an object and then storing this object to a file using object serialization. You can then load this file as a de-serialized object.

This might not be regarded as the best practice in the world... but if you're wanting to do this outside of any particular framework, you can always just use plain vanilla Java serialization. It's exactly what you're talking about... storing an object to disk (or whatever) and restoring it to memory later. Check out this tutorial if the subject is unfamiliar.

You can read the data from XML into a java object and then serialize that object. You should even be able to have your object check the timestamp of the xml file and automatically reread it when it changes.

Related

Should I use an application.properties or create an alone file for huge fields?

We work on a huge application and it is integrated with more external APIs.
So we use more static fields
key <=> value
To integrate with only one system like PayPal payment for instance.
Fields
payment.paypal.live-mode=false
payment.paypal.url.charge=xxxxxxx
payment.paypal.url.redirect=xxxx
payment.paypal.url.exchange=xxxx
payment.paypal.secret-key= xxxx
payment.paypal.publishable-key= xxxxx
payment.paypal.sources=xxxx,xxx,xxx,xxx
and more fields
What is the best practice to use?
Application.properties or create a new JSON file that handles all these fields.
Note that:-
The application has more than one profile.
Maybe in your case, it makes sense to have a separate file to handle long and specific configurations that are somewhat core to your application. The downside of this is that you would need to handle its parsing on your own (with the help of Jackson for example).
You might also consider using yaml files instead of properties since at least it would avoid repetitions such as payment.paypal.url and it is easier to read and organize.
Putting the data in the application.properties and having a component a class to set the data using the #Value annotation. This ensures sensitive data can be feed in through the environment.
You can use #Configuration with #Profile if you want to but that might be complicating stuff. You can instead document these properties maybe in a JSON file in the your resource directory.

Java Serialization and references

Say I have a serialized class that is used to save the state of my game. This serialized text is stored in a text file. If I restart my computer, reinstall java, etc. If I try to deserialize that text, will it save everything that it is referenced? For the purpose of question, assume the class has multiple ArrayList's of entitys and map elements.
Class -> Serialization - > text
Text - > Deserialization - > Class
As long as the serialized classes don't change its definition, there won't be any problem. You may even move these serialized files into another OS which deserializes to the same classes definition and it will work with no problem (unless you use libraries specific to an OS, thus breaking portability).
The serialized file will retain it's state regardless of whether or not you reinstall Java or restart your machine. It would be pretty useless otherwise: the point of serialization is to capture state in a persistent form for archival or transport in a fashion that can be to recreate that state later.
So, assuming the serialization method you are using originally saves all the references you care about, then you'll always be able to restore that object and all its references from that serialized data. Unless, perhaps, you try in five years using a new version of Java that no longer supports that serialization format or something.
Are you about standart java serialization mechanism? Java serialization mechanism will serialize data to binary format, not text. Java guarantees serialization/deserialization between versions until you use standart java library. So yes in your case serialization will work good.
But, I don't sure that standart java serialization good for your purposes. Because:
It's fully unreadable format.
If you'll change language later you must fully reimplement saving format.
As alternative you can use some of xml serialization libraries for java. In this case, save file will have readable format (good for debugging).

JavaObjectModel. What is it?

Simply stated : What is a Java Object Model. I want to create one for a XML file. I am sure it is different than the Java Application. SO what is it.
Obviously, i tried google but to my surprise didnot get any specific or clear answer.
I guess an Object Model is some java POJO whose properties reflect the structure of the xml file you are parsing.
A "simple" way to achieve this transformation is to use JAXB.
An object model is a set of classes (with their properties and methods) used to represent a particular collection of information. A Java object model is simply an object model in which the language used to describe those classes is Java. If you want to create a Java object model for an XML file, then you need to analyze what information is held in your XML file and design Java classes to represent the same information. There are tools that can automate this process, though the representation they come up with will not always be optimal.
Any model is essentially the way you represent data. So your Java Object Model is your data represented as Java Objects. An XML Model would be your data represented as XML. JSON is your data represented as JavaScript "Objects", etc.

Are properties the best way to get specific parameters and data into a java program?

I can understand using properties for messages and international settings but I feel there has to be a better way to get specific parameters of a program like background color, resolution, floating point numbers, etc.
Every time I load a set of properties I have to have a wrapper class to convert all those into something meaningful to my program. Say I want to load a color, I have to read the color as a string and then convert it to a color in my program. Everything in a property is a string. So numbers have to get converted too.
I feel like there should be some sortof of library that can detect(or maybe it's specified in the file) what it is and you would automatically get the correct data type when you load it in.
Is there anything like this? Thanks.
You could use XMLEncoder/XMLDecoder. They are text-based serialize alternatives for java beans.
As KitsuneYMG mentioned, you can use an XML deserializer to more easily handle the unmarshalling of configurable, typed values; XStream is an excellent library to simplify the object field mapping process. Also consider the YAML and JSON serialization formats as alternatives to XML, they are more concise and potentially easier to manage and both have fine Java bindings.
Moreover, by accessing these configurable objects via the Factory pattern you can have better control for loading special cases (such as automated tests) as well as XML documents from the filesystem or classloader resources.
Why is there no reference on the preference api? I believe using XmlEncoder or any other serialization mechanism is a round about way of doing it. I use java preference api for storing custom application specific info. The only problem was there is no default putObject and getObject method.But there is a good workaround. See this link for on how to store objects in preference.

Serialize Java objects into Java code

Does somebody know a Java library which serializes a Java object hierarchy into Java code which generates this object hierarchy? Like Object/XML serialization, only that the output format is not binary/XML but Java code.
Serialised data represents the internal data of objects. There isn't enough information to work out what methods you would need to call on the objects to reproduce the internal state.
There are two obvious approaches:
Encode the serialised data in a literal String and deserialise that.
Use java.beans XML persistence, which should be easy enough to process with your favourite XML->Java source technique.
I am not aware of any libraries that will do this out of the box but you should be able to take one of the many object to XML serialisation libraries and customise the backend code to generate Java. Would probably not be much code.
For example a quick google turned up XStream. I've never used it but is seems to support multiple backends other than XML - e.g. JSON. You can implement your own writer and just write out the Java code needed to recreate the hierarchy.
I'm sure you could do the same with other libraries, in particular if you can hook into a SAX event stream.
See:
HierarchicalStreamWriter
Great question. I was thinking about serializing objects into java code to make testing easier. The use case would be to load some data into a db, then generate the code creating an object and later use this code in test methods to initialize data without the need to access the DB.
It is somehow true that the object state doesn't contain enough info to know how it's been created and transformed, however, for simple java beans there is no reason why this shouldn't be possible.
Do you feel like writing a small library for this purpose? I'll start coding soon!
XStream is a serialization library I used for serialization to XML. It should be possible and rather easy to extend it so that it writes Java code.

Categories