I wrote an application that takes a JSON file as configuration. Up to this point, I wrote the JSON config by hand. However, now I want to allow other users who are not familiar with JSON format to make their own configurations. There's only 3 types of objects that the configuration needs to store, but the user should be allowed to add multiple copies of these objects. I want to write a configuration application where the user can press a button such as "Add Type A" and an object of type A is populated with default values and visualized so that the user can select properties and edit them. I know how to write an application that does this, but I feel like I'm re-inventing the wheel. Does anyone know of an open-source Java library that I can use inside my config application to handle visualization and editing a JSON file? If I'm approaching this from completely the wrong direction, please let me know.
I'm tempted to say "don't fear to reinvent the wheel".
But the fact is that there a bunch solutions available :
How do I convert an object to JSON representation (and vice-versa)
Java representation of JSON Object
Javascript to Java using JSON
among them, GSON looks fine.
For my personal experience, Yaml turned out to be an appropriate solution.
Related
I am developing a program which has three JTextBox which my users can enter and check some text for right rule.
So I want add a ablitiy to my program that my users can add or remove their favorite text to a Favorite List and can create folder in Favorite list and put some text in it, such as Bookmark library in FireFox or other web browser.
I want use RandomAccessFile to save favorite list as a favorite source.
How do I implemet it? is there beter way to implement it? is there beter way from RandomAccessFile?
Can any one help me?
Thanks.
There could be lots of approaches. It all depends on what you want to achieve.
Consider using Java serialization mechanism. You can serialize a collection of bookmarks to a file. When your app starts, you deserialize it, and get the same collection data.
The advantages are: simple and easy implementation. The disadvantages: you can't look through stored bookmarks in a text editor or something. The same class hierarchy is to be used to load the serialized version.
XML is human-readable and provides easy interoperability. Other applications would be able to handle your list of bookmarks.
It usually takes more resources to parse the XML and load it to memory and then to create the internal object structures. Though you can use the DOM to traverse the tree all the time, it could be not as convenient as the internal data structure using specialized classes.
Random Access Files work best with fixed record sizes. It means all the fields of your bookmarks must be fixed-length. For example, the name of a bookmark is String. When you write it out to a file, you store it like an array of a fixed length, let's say 20. This automatically implies that if users give a bookmark the name which length is greater than 20, the remaining characters would be lost.
It is also easy to implement with the caveats above. Of course the records could be of variable length, but then you lose the random access to file because you cannot easily calculate the position of a specific record.
Firefox uses JSON for storing bookmarks and allows exporting to HTML. You can explore this too.
You can also store bookmarks, and things you want to keep between sessions in the Preferences,
see http://download.oracle.com/javase/6/docs/api/java/util/prefs/Preferences.html
Im a novice java-programer, whos trying to create a small java app.
In the program im working on, I want to load the configurations from different ini-files.
The basic idea is, that I would have a library containing all the config files, the parser should read all of them and make configurations named after their filenames.
The parser should be created to work dynamicly, so it can read different types of configs.
example
House.ini
-> type0
-> id name height witdh length price_based_on_dimensions
-> id1 name1 height witdh length price_based_on_dimensions
These data should be saved to a config object named config.house. The tricky part is that a different config file, can have its type = type0 but with a different number of attributtes.
I realise that there is no simply solution to this, but any help and or guides to create a dynamic parser is welcome
I'm not really clear on the output you want to produce, but a Java INI parsing library might be a good place to start. For that, you should use ini4j.
Other then ini4j (which is a really good library) I personally prefer to use xml config files. To me they are easier to use and allow for easier configuration
I am writing a server in java that allows clients to play a game similar to 20 questions. The game itself is basically a binary tree with nodes that are questions about an object and leaves that are guesses at the object's identity. When the game guesses wrong it needs to be able to get the right answer from the player and add it to the tree. This data is then saved to a random access file.
The question is: How do you go about representing a tree within a file so that the data can be reaccessed as a tree at a later time.
If you know where I can find information on keeping data structures like trees organized as such when writing/reading to files then please link it. Thanks a lot.
Thanks for the quick answers everyone. This is a school project so it has some odd requirements like using random access files and telnet.
This data is then saved to a random access file.
That's the hard way to solve your problem (the "random access" bit, I mean).
The problem you are really trying to solve is how to persist a "complicated" data structure. In fact, there are a number of ways that this can be done. Here are some of them ...
Use Java persistence. This is simple to implement; make sure that your data structure is serializable, and then its just a few lines of code to serialize and few more lines to deserialize. The downsides are:
Serialized objects can be fragile in the face of code changes.
Serialization is not incremental. You write/read the whole graph each time.
If you have multiple separate serialized graphs, you need some scheme to name and manage them.
Use XML. This is more work to implement than Java persistence, but it has the advantage of being less fragile. And if something does go wrong, there's a chance you can fix it with XSLT or a text editor. (There are XML "binding" libraries that eliminate a lot of the glue coding.)
Use an SQL database. This addresses all of the downsides of Java persistence, but involves more coding ... and using a different computational model to access the persistent data (query versus graph navigation).
Use a database and an Object Relational Mapping technology; e.g. a JPA or JDO implementation. (Hibernate is a popular choice). These bridge between the database and in-memory views of data in a more or less transparent fashion, and avoids a lot of the glue code that you need to write in the SQL database and XML cases.
I think you're looking for serialization. Try this:
http://java.sun.com/developer/technicalArticles/Programming/serialization/
As mentioned, serialization is what you are looking for. It allows you to write an object to a file, and read it back later with minimal effort. The file will automatically be read back in as your object type. This makes things much easier than trying to store the object yourself using XML.
Java serialization has some pitfalls (like when you update your class). I would serialize in a text format. Json is my first choice here but xml and yaml would work as well.
This way you would have a file that doesn't rely on the binary version of your class.
There are several java libraries: http://www.json.org
Some examples:
http://code.google.com/p/json-simple/wiki/DecodingExamples
http://code.google.com/p/json-simple/wiki/EncodingExamples
And to save and read from the file you can use the Commons Io:
import org.apache.commons.io.FileUtis;
import java.io.File;
...
File dataFile = new File("yourfile.json");
String data = FileUtils.readFileToString(dataFile);
FileUtils.writeStringToFile(dataFile, content);
I have the following data:
User System SubSystem
user1 System1 SubSystem1
user2 System1 SubSystem2
user3 N/A N/A
and i need to be able to determine the system/subsystem tuple from the user. I must be able to add users at any time without rebuilding and redeploying the system.
I know the database would be the best option here but I cannot use a database table.
I currently have it mapped using a hash map but I don't want it to be hard-coded. I was thinking about using a properties file but I can't visualize how I would implement it. Anyone else have any suggestion?
Not that it matters but I'm using JAVA, on weblogic 10.3.
You could do this using a HashMap (as you do now) and store it using XStream.
XStream allows you to serialise/deserialise Java objects to/from readable/editable XML. You can then write this to (say) a filesystem, and the result is editable by hand.
The downside is that it's a serialisation in XML of a Java object, so not as immediately obvious as a properties file to edit. However it's still very readable, and easily understood by anyone remotely technical. Whether this is an appropriate solution depends on the audience of this file.
Sounds like something you could very well use YAML for..
SnakeYAML looks to be a workable Java implementation.
I would go for something as simple as :
user1 = userValue
user1.system = systemValue
user1.system.subsystem= subsystemValue
user2 = userValue
user2.system = systemValue
user2.system.subsystem= subsystemValue
user(id) is used as "primary" key in your properties, and a very simple concatenation of your fields to store your table values.
I use this very often : trust me, it's much more powerfull than it may appear :)
For this project i've gone with the solution proposed by Olivier. Some project contrainst (legacy of the project) prevent me for going with a probably better solution of using XStream.
Thx for the feed back guys
I'm trying to find the best way to save the state of a simple application.
From a DB point-of-view there are 4/5 tables with date fields and relationships off course.
Because the app is simple, and I want the user to have the option of moving the data around (usb pen, dropbox, etc), I wanted to put all data in a single file.
What is the best way/lib to do this?
XML usually is the best format for this (readability & openness), but I haven't found any great lib for this without doing SAX/DOM.
If you want to use XML, take a look at XStream for simple serialization of Java objects into XML. Here is "Two minute tutorial".
If you want something simple, standard Java Properties format can be also a way to store/load some small data.
consider using plain JAXB annotations that come with the JDK:
#XmlRootElement
private class Foo {
#XmlAttribute
private String text = "bar";
}
here's a blog-post of mine that gives more details on this simple usage of JAXB (it also mentiones a more "classy" JAXB-based approach -- in case you need better control over your XML schema, e.g. to guarantee backwards compatibility)
2 other options you might consider -
Hsqldb is a small sql db written in
java. More relevant for your
purposes, it can be configured to
simply write to a csv file as it's
data store, so you could conceivably
use it's text output as a portable
datastore and still use sql, if
that's what you prefer.
A second option might be to write the
datastore directly to a serialized
file either directly or through a
library like prevayler. Very good
performance and simple to implement,
cons are the fragility and opacity of
the format.
But if the data is small enough, xml is probably much less bother.
If you don't need to provide semantic meaning to your data then XML is probably a wrong choice. I would recommend using the fat-free alternative JSON, which is much more naturally built for data structures.