mapping data in properties files - java

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

Related

Java JSON editor / visualizer

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.

What is the best way to store data when a database could not be used?

I am designing a e-Diary application in which the user can store textual data EVERY DAY.
I thought of using a database but now I am looking for other alternatives , thought of encrypted files , but what if they get deleted ?
Could someone provide me ways of doing this.
BTW, I am using Java.(If this is important).
EDIT: Currently I am using files for acheiving this, for login I am using a file in which the username, password are stored in the format username:password, This is not a good approach, so I am looking for some secure approaches.
Serialize your Data and store it using flatfiles.
But why dont you want to use SQlite?
Serializing and storing to the disk is a database aswell.
If you want to serialize it there are a few tutorials and code examples around.
check How to serialize an object into a string
for example.
If you want to use a proper database (which is recommend!) you may check different databases and examples at Java and SQLite

Java saving strings

I have a RuneScape Private Server project coded in Java, and am trying to code a personal "tag" that players can use. I have managed to do this, but everytime there is a restart on the server, their "tag" gets reset to "null".
Their "tag" is initalized by doing a command ";;settag [name]". Their tag is then set to whatever they want. I have done this through a string:
if (command[0].equals("settag")) {
newTag = getCompleteString(command, 1);
newTag = player.yellTag
player.sendMessage("Your tag is now:" +newTag);
}
I am unsure what the most efficient way to fix this would be, I am thinking of just loading and saving through .xml/.txt files. By the way, player.yellTag is where the next command (::mytag) searches it from, which works fine, until there is a restart of the server.
it all depends on the context of your application. If you are planning on having less than a few hundreds players, then a xml file may be ok. You should look at JAXB, which is, afaict, the standard way to store your objects in Java. You can also store them as JSON files, using gson which is way simpler to use and implement than XML stuff.
But if you get to have more than thousands of players, you may want to get some more efficient way to serialize your tags by putting them in a database, and thus an ORM library like hibernate could help you do that.
You may want to make your own stuff, like a tag directory full of files named after unique ids of your players containing the players' tag... It's a lot more "hackish" but still quite efficient.

writing data in to files with java

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);

Best way to save data in a Java application?

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.

Categories

Resources