Java - create dynamic variable table that I can easily call back variables - java

I am a newbie programmer, very newbie..
I am trying to write a program to test our website and am using Java and Selenium.
The issue is I want to create a "table" or a "reference" that will allow me to store variables that can easily be called back and used in different calls.
I tried to use a HashMap but found it was no good because when I rerun my testing code there is a new hashmap each time. I want something that can store the values and remember them the next time I run the code.
I looked at creating a mysql table but I can't figure out how to recall the variables out of the table once they have been created.
I hope this makes some sense. :0) Pls check out below if an example would be more useful
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Here is an example of the hashmap that I was using:
HashMap idTable = new HashMap();
idTable.put("GroupName", new String("Group " +
Long.toHexString(Double.doubleToLongBits(Math.random()))));
element = driver.findElement(By.id("name"));
element.sendKeys((String)idTable.get("GroupName"));
FYI: The reason this doesn't work for me is that I want to be able to wrap it in an "if" statement; to tell the computer that if the variable called "GroupName" already exists then don't do it again.. however every time I run the script I make a call to the function [HashMap idTable = new HashMap();] and I don't know how to NOT make that call because the HashMap isn't saved anywhere.. it is created new each time.
Thanks,
Orli
not sure where to add this: but following the first suggestion here is what I did.
HashMap idTable;
try{
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("C:\Documents and Settings\My Documents\Selenium local\hashmap.dat"));
idTable = (HashMap) is.readObject();
}
catch(Exception e){
idTable = new HashMap();
}
AND then:
try{
ObjectOutputStream os = new ObjectOutputStream (
new FileOutputStream("C:\Documents and Settings\My Documents\Selenium local\hashmap.dat"));
os.writeObject(idTable);
os.close();
}
catch (Exception e){
}
It works. :0) Thanks for the help!

Use an instance of Properties for simple string key/value pairs. It is a Map, like HashMap but has load and store methods for reading/writing its contents to a file. This should be more than adequate for simple testing usage.
It is commonly used for loading configuration files.

You must store them somewhere not in the code, as the code goes bye-bye whenever the JVM shuts down. Two good options to do this are
Using SQL database, research this more via google if you want
Via files, simply writing your HashMap database to a file at the end of your program (Do Runtime.addShutdownHook, and pass it a thread whcih stores your hashmap to the file), and have it read from the file at the begining of the code (if the file is nonexistant, make a new one, and store an empty hashmap to it)

Related

How can I modify a particular line in a file without deleting the existing data using Java?

I need to change the values in a file which has more than 30 lines and each line has a data like:
ENABLE_TLS=true
PSWD_MIN_LENGTH=8
Here, let us consider this as a key and value pair, and I needed to change only the value for the 2nd line alone, without deleting the 1st line. Can someone help me how can I do this??
I have tried bufferedwriter, but it is replacing all the lines.
My expectation is:
I need to modify only a particular key's value and the remaining lines should not get deleted
Your description of the data sounds like Java Properties. If you are certain that all the data in that file takes the form key=value you could read it in as a Properties object, update the value for the key in question, and write it back to the file.
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream("/path/to/file")) {
properties.load(inputStream);
}
properties.put("PSWD_MIN_LENGTH", 12);
try (FileOutputStream outputStream = new FileOutputStream("/path/to/file")) {
properties.store(outputStream, null);
}
BEWARE: there is no guarantee that the order of the key/value entries in the file will be maintained (they probably won't). If you are looking for a Properties implementation that will maintain the order, maybe this SO answer will do the trick (UNTESTED!) How maintain the order of keys in Java properties file?

How to create JSON file from java without duplicating element?

I'm trying to make a simple dictionary program based on server-client socket communication. I'm trying to save user word and meaning input as a JSON file (which is dictionary data to search later on) but when I do add query it ends up with having duplicated JSON objects
for example, if I add happy and then weather and hello, the result written in JSON file is
like below
{"hello":"greeting"}{"happy":"joy","hello":"greeting"}
{"happy":"joy","weather":"cold","hello":"greeting"}`
instead of getting
{"hello":"greeting"}{"happy":"joy"}{"weather":"cold"} like I wanted
how can I fix this problem?
my code for that function is
case "add":{
FileWriter dictionaryWriter = new FileWriter("dictionary.json",true);
//split command again into 2 part now using delimiter ","
String break2[] = msgBreak[1].split(",");
String word = break2[0];
String meaning = break2[1];
dictionary.put(word, meaning);
System.out.println("Writing... " + word+":"+meaning);
dictionaryWriter.write(dictionary.toString());
//flush remain byte
dictionaryWriter.flush();
//close writer
dictionaryWriter.close();
break;}
this function is in while(true) loop with other dictionary functions
I tried to remove the appending file part, but when I remove the (,true) part the duplication error stopped but whenever I get a new connection, new dictionary file is created instead of having all data saved.
If anyone can help me solve this problem, I would appreciate it a lot!
Thanks you in advance.
You can try to create a new dictionary every time instead of using the existing one
Map<String, String> dictionary = new HashMap<>();
dictionary.put(word, meaning);
...

saving and encrypting java class

I've written my own 3D Game Engine and started writing a game. I am using OBJ-Models that use the TurboSquid Royalty Free License
Basically, it says that I can use their OBJ-Files but have to implement something that avoids the users to extract the OBJ-Files out of my program.
I've written a converter that extracts the information out of the OBJ-File and creates several float/integer arrays [vertices, vertexCoords, normals, tangents..., indices]
These arrays will be used later for creating the VAOs / VBOs. So my idea was to create a Java class called OBJModelData that contains these arrays. OBJModelDataimplements Serializable. My attempt was to save the class into a file and use them instead of the OBJ-File so that the user cannot see and use the content.
My attempt looks like this:
public void writeToFile(String file){
File f = new File(OBJLoader.RES_LOC+ file +".dat");
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(this);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This results in a file called modelName.dat and looks like this:
Obviously reverse engineering must be done the recreate my arrays. I just do not like the way its written. For example the class that has been serialized is written in the first line. If someone somehow manages the get the source files of my engine by doing some reverse engineering on that he could easily read the file.
Is my method save enough to avoid recreating the obj files and can I still use this method to fulfill the license conditions or is there any other way that is normally used (e.g. in other games/engines) ?
The end of your quote says: "without reverse engineering", so you do not need carry about reverse engineering. You need only "translate" from OBJ to another format of your creation, like you do.

Saving variable state in between sessions?

So I'm in the process of developing a Java IRC bot as a bit of a side project for a friend of mine, and while development is going well, I'm a little unsure as how to save the current state of certain variables in between sessions. It doesn't have a GUI, so I didn't think that it would be too complex, but my searching efforts have been futile thus far.
Thanks.
It will depend on the sort of variables you want to keep, but all methods will require you to write some sort data to a file.
If you only need to keep a handful of variables, you could consider implementing a .config file that could be a simple delimited text file.
If it's an entire object that you want to keep track of, say, a player in an irc game, one option you have is to parse the object into JSON, and save it to a textfile, for reading later. You can use Gson for this
example for a 'player' object:
public String savePlayer(String playerName){
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String playerFile = System.getProperty("user.dir")+"\\players\\"+playerName;
String jsonplayers = gsonPretty.toJson(players.get(playerName));
try{
FileWriter writer = new FileWriter(playerFile+".json");
writer.write(jsonplayers);
writer.close();
return "Player file saved successfully!";
}catch(Exception e){
e.printStackTrace();
}
return "Something went wrong";
}
you can then create a load method that either has the file name hard coded, or a string input to determine which file to load, and use something like:
playerFromJson = gson.fromJson(jsonString, Player.class);
to use that object in the code

How to change the Properties.store() divider symbol from "=" to ":"?

I recently found out about java.util.Properties, which allows me to write and read from a config without writing my own function for it.
I was excited since it is so easy to use, but later noticed a flaw when I stored the modified config file.
Here is my code, quite simple for now:
FileWriter writer = null;
Properties configFile = new Properties();
configFile.load(ReadFileTest.class.getClassLoader().getResourceAsStream("config.txt"));
String screenwidth = configFile.getProperty("screenwidth");
String screenheight = configFile.getProperty("screenheight");
System.out.println(screenwidth);
System.out.println(screenheight);
configFile.setProperty("screenwidth", "1024");
configFile.setProperty("screenheight", "600");
try {
writer = new FileWriter("config.txt" );
configFile.store(writer, null);
} catch (IOException e) {
e.printStackTrace();
}
writer.flush();
writer.close();
The problem I noticed was that the config file I try to edit is stored like this:
foo: bar
bar: foo
foobar: barfoo
However, the output after properties.store(writer, null) is this:
foo=bar
bar=foo
foobar=barfoo
The config file I edit is not for my program, it is for an other application that needs the config file to be in the format shown above with : as divider or else it will reset the configuration to default.
Does anybody know how to easily change this?
I searched through the first 5 Google pages now but found noone with a similar problem.
I also checked the Javadoc and found no function that allows me to change it without writing a class for myself.
I would like to use Properties for now since it is there and quite easy to use.
I also got the idea of just replacing all = with : after I saved the file but maybe someone got a better suggestion?
Don't use a tool that isn't designed for the task - don't use Properties here. Instead, I'd just write your own - should be easy enough.
You can still use a Properties instance as your "store", but don't use it for serializing the properties to text. Instead, just use a FileWriter, iterate through the properties, and write the lines yourself - as key + ": " + value.
New idea here
Your comment about converting the = to : got me thinking: Properties.store() writes to a Stream. You could use an in-memory ByteArrayOutputStream, convert as appropriate in memory before you write to a file, then write the file. Likewise for Properties.load(). Or you could insert FilterXXXs instead. (I'd probably do it in memory).
I was looking into how hard it would be to subclass. It's nearly impossible. :-(
If you look at the source code for Properties, (I'm looking at Java 6) store() calls store0(). Now, unfortunately, store0 is private, not protected, and the "=" is given as a magic constant, not something read from a property. And it calls another private method called saveConvert() that also has a lot of magic constants.
Overall, I rate this code as D- quality. It breaks almost all the rules of good code and good style.
But, it's open source, so, theoretically, you could copy and paste (and improve!) a bunch of code into your own BetterProperties class.

Categories

Resources