How to protect libgdx function fromJson against bad input? - java

I am in my app trying to load level which can be created by user and I want to protect my app against crash when it will get file with bad input. How should I do it?
This is my current code:
Json json = new Json();
json.setIgnoreUnknownFields(true);
JsonWorldValueCache jsonWrldCache = json.fromJson(JsonWorldValueCache.class, jsonWorld);

You can approach the problem on two fronts:
First, you can surround the Json#fromJson() call with a try-catch statement as #Elliott suggested. If you catch an exception, politely tell the player that there is something wrong with the level they created, and ask them if they want to try loading it again (presumably after they've fixed it) or go back.
Second, you can provide the user with a level editor so they don't have to modify the JSON file directly. While this won't remove the possibility of failure (users are pretty good at breaking things), it will remove the majority of issues since your editor can ensure the proper structures and values are adhered to in the level file.

Related

Java - Easy way to read/write/search separated data blocks on file

I searched thoroughly on the web about this issue but I didn't find anything. Sorry for my bad english, but it's also kinda difficult to explain.
I would like to know if there is a simple method or, perhaps, a library, which allows to read/write and identify data blocks (for example, strings) on a file without caring of low level details such as "read until you found this delimeter, then return what you've read" or "write everything, then put this delimeter".
In particular, given a text file like this:
//Data Block 1
//Some kind of delimiter automatically generated
//Data Block 2
...
//Data Block n
The application must automatically:
Write another data block after the last one on the file;
Iterate on all the data blocks and return each one of them;
Access a random datablock (i.e I want to read the third data block currently on file).
Maybe I just can use a data structure, put the data in separately, then serialize the object on file, but I wonder if exists a much cheaper way like the one described before.
Thanks in advance and, again, sorry for the possibly confused explanation.

Oracle-UCM service CHECKIN_UNIVERSAL is throwing errors when trying to checkin an existing file

I'm working on Java code that checks whether a file exists in the system and whether it's checked out. After these checks it calls the CHECKIN_UNIVERSAL service. This is where it stops. Checking in a new file works just fine, but it's the checking in of an existing file that's giving errors.
The specific error displayed (without making modifications to my original code) is !cscheckinitemexists. A bunch of googling turned up the solution to clear the data binder, yet then it comes up with the error that it cannot retrieve or use the security token.
Here's the code I use to clear and retrieve the data binder:
m_binder.clearResultSets();
m_binder.getLocalData().clear();
m_binder.setEnvironment(new IdcProperties(SharedObjects.getSecureEnvironment()));
What does the rest of your code look like? You can link to a Gist.
Generally, I have run into this due to data pollution (as you stated).
Is there a reason you are using m_binder instead of creating a brand new DataBinder?
After looking at your gist, you are using m_binder (the DataBinder from the service) to execute CHECKIN_UNIVERSAL. Don't do this. Use a separate DataBinder (as you did for the DOC_INFO_BY_NAME service call).
Either use requestBinder or a new DataBinder.
Another way to avoid this issue is to simply not look for the checkout. CHECKIN_UNIVERSAL supports a flag that checks out a content item if it's not already checked out.
Add the flag "isForceCheckout" to your binder, with a value of "1".

Notify when web content change

Im new to java and working on a simple application that monitor an url and notify me when a table is updated whit new items. Looking at the entire page will not work as there are commercials that change all the time and they would give false positives.
My thought was to fetch the url line by line looking for the elements. For each element I will check to see if the element is already in an arraylist. If not the element is added to the arraylist and a notification is send.
What I need support with is not the exact code but advice if this would be a good approach and if I should store the elements in an array list or if I should use a file instead as there are 2 lines of text in each element.
Also It would be good to get recomandation on what methods and libs there would be good to look at.
Thanks in advance
Sebastian
To check the site it'd probably be more stable to parse the HTML and work with an object representation of the DOM. I've never had to do this but in a question regarding how to do this another user suggested using JTidy, maybe you could have a look at that.
As for storing the information (what you currently do in your ArrayList): this really depends on what you use your application for. If you only want to be notified of changes that occur during the runtime of your program this is perfectly fine. If you want to have the information persist you should find a way to store the information in the file system or database.

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.

Where to handle an Exception

I'm currently working on a project and I've come upon a bit of a head scratcher. I've been programming in Java for about two years, and I've covered exceptions, but never properly understood them.
In my current situation I've got my main method which initializes a class
WikiGraph wiki = wiki = new WikiGraph(getFile());
The Wikigraph constructor takes a filename which I get via a DialogBox in the getFile() method.
The constructor for wikigraph then calls a method called loadfile(filename) which attemps to load and parse the file given.
The loadfile() method is where I will throw an IncorrectFileTypeError.
My question is, where should I handle this?
At the moment I catch it in the loadfile() method
try {
//load file
} catch (IncorrectFileTypeError e){
System.out.println("Incorrect file type: "+filename+": "+e.getMessage());
throw new IncorrectFileTypeError();
}
But I also catch it at the WikiGraph initialization like so:
while(wiki==null){ //While There is no valid file to add to the wikigraph
try {
wiki = new WikiGraph(getFile()); //Try to load file
} catch (IncorrectFileTypeError e) { //If file cannot be loaded
JOptionPane.showMessageDialog(null, "Incorrect File Type Given. Please Choose another file."); //Display error message
getFile(); //Prompt user for another file
}
}
Now is the way I've handled the error the correct/best way? Or should it be handled elsewhere, such as in the getFile() method?
EDIT: I suppose I should make the file issue a bit clearer.
The File extension is not what the IncorrestFileTypeError is based on, and thus it may be a misleading error name.
The file given may have pretty much any extension, its the contents of that must be well formed.
In this case, I would avoid using exceptions as your primary method of dealing with incorrect file types. If an exception can regularly be triggered by user input, it really shouldn't be treated as an exception. Here's the approach I would take:
Check the file type and alert the user if the file type is invalid, through standard control flow. You might consider a static method on WikiGraph like IsFileValid(filename)
In the WikiGraph initialization, throw an exception if the file type is invalid.
This approach gives you the best of both worlds - you have the opportunity to alert users when invalid data is provided, while still ensuring from WikiGraphs perspective that the information provided is accurate. It gives developers working against a WikiGraph a way to ensure their input is valid without necessarily requiring exception handling.
One of the main benefits of exceptions is that they give you convenient means to handle an exception far from where it occurs. In languages that don't support it, you would have had to have each call on the path check the return value, break and return, so that you are manually propagating.
It makes sense to handle the exception where you feel you can either recover from it or best report it and cancel the operation.
My understanding is that the interaction starts with UI input and that if the file type is inappropriate, you cannot really recover. Therefore, I would have whatever UI task that initiated the file open catch the exception, report to the user that an error occurred, and either cancel or ask for a different input.
On a second reading, it seems like you are opening the dialog after you've already started trying to create the graph. I personally like to isolate UI interaction. I would therefore personally first handle all UI input, get the expected file name, verifies that it meets my needs, report to the user if not, and only continue further if the file is ok, then reporting only critical and unexpected errors.
I don't think it makes sense to catch it in loadfile. You can still write a log message (use System.err), just do it before throwing the exception. You're on the right track with catching the exception where you can do something about it (in this case prompting the user again).
If the problem is that the user has choosen a file of the wrong type then I don't think you should let the code proceed that far at all. This does not really seem like it should be an Exception at all but more a path in the program. If the user has selected an incorrect file type then he should be presented with the choice of choosing the file again. Obviously you should limit the choices in the JFileChooser to files of the correct type if it is as easy as looking at the extension.
I think this is the type of situation that checked exceptions are designed for (whether you agree with them or not.) I assume IncorrectFileTypeError extends Error? Extending RuntimeException would be more appropriate, and extending IOException would be better still, because this kind of error can be triggered by valid user input (i.e. typing the name of a file that exists but has the wrong type.)
I believe this type of error (IncorrectFileTypeError) can be resolved in the User Input Form avoiding an unnecessary roundtrip to filesystem service layer.

Categories

Resources