String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
This throws a null pointer error if the user x's out of the optionpane
Firstly, why can't response hold a null value?
secondly, how do i handle this?
full code:
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:").trim() + ".xml";
if(response != null){
File newData = new File("src\\golfdatabase\\Databases\\" + response);
try {
newData.createNewFile();
databaseComboBox.addItem(response);
} catch (IOException ex) {
Logger.getLogger(GolfDriver.class.getName()).log(Level.SEVERE, null, ex);
}
databaseComboBox.setSelectedItem(response);
disableButtonsNullList(false);
}
You have to check the return value for null and then invoke the method trim
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
if(response!=null)
response = response.trim()+".xml";
It gives null back when you click on "Cancel" try something like that:
String response = javax.swing.JOptionPane.showInputDialog("Enter new database name:");
if(response != null){
response = response.trim() + ".xml";
}
Take note that: String response = JOptionPane.showInputDialog(....);
Would have been enough to create the JOptionPane.
Firstly: Yes responses CAN hold a null value, but your code snippet does not show how you handle the responses so there is no way for me to tell why it is throwing them.
Secondly: That again depends on how you are handling the responses, please elaborate more on your code.
EDIT: try adding a String cast as the java tutorial suggests you do:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
EDIT2: While Octopus found the problem in a piece of code (that I shamefully overlooked) please keep in mind the above points because they still hold true.
Related
I am using the OkHttp client and when I wrote the code to consume an API, I am getting a SonarLint warning about response.body().string() could be null.
However there is a chicken and egg problem with response in that it can only be consumed once, then it is de-referenced.
Which means I have had to structure my code like so:
Check the response object is not null
Then check the response body text is not null/empty
Which results in two separate but similar if statement/catches
try (var response = okHttpClient.newCall(siteMagicLinkRequest).execute()) {
if (response.body() == null) {
throw new ApiException("Unable to generate Magic Link: Null Response Body from site");
}
var responseString = response.body().string();
if (response.body() == null || StringUtils.isEmpty(responseString)) {
throw new ApiException("Unable to generate Magic Link: Empty Response Body From site");
}
if (response.isSuccessful()) {
return responseString;
} else {
final siteApiErrorResponse errorResponse = gson.fromJson(responseString, siteApiErrorResponse.class);
throw new ApiException(response.code(), errorResponse.getMessage());
}
} catch (IOException e) {
throw new AuthorizationException("Unable to generate Magic Link: " + e.getMessage());
}
I can't use a condensed if check as shown below, as it will lose the response body.
if (response.body() == null || StringUtils.isEmpty(responseString)) {
throw new ApiException("Unable to generate Magic Link: Empty Response Body From site");
}
Is there any OkHttp API or another pattern I can use to simplify this code and remove the extra if statement/trap?
You can write
if (response.body() == null || StringUtils.isEmpty(response.body().string())) {
throw new ApiException("Unable to generate Magic Link: Empty Response Body From site");
}
If the response.body() == null check before the or-operator is true, the check after the or-operator will not be executed. Instead, it will execute the code inside the if-statement right away. The second check will only be executed if the first check returns false.
That's why you will never get a NullPointerException with this if-statement. And this is what I think you are concerned about, right?
I am using the below code for sanitizing the JSON but still, I am getting the JSON injection while scanning from Fortify can you please help me out what is the problem or this is not an issue, maybe suppress. I have also looked out for the same question but those don't solve my problem . my problem is that I am sanitizing my JSON before converting it to java object but still I am getting JSON injection error in fortify
public String handleEventMessage(String jsonRequest) {
MonerisPaymentDetailsObject paymentObject = null;
if(null!=jsonRequest && jsonRequest.length()>0){
try{
paymentObject = mapper.readValue(JsonSanitizer.sanitize(jsonRequest), MonerisPaymentDetailsObject.class);
}catch(Exception ex){
logger.error("Error occured while converting MonerisPaymentDetailsObject json to Object :" , ex);
}
return "abc";
}
Fortify giving below description for this error
1. Data enters a program from an untrusted source.
In this case the data enters at readLine() in EPWFPaymentServicesServlet.java at line 49.
2. The data is written to a JSON stream.
In this case the JSON is written by readValue() in EPWFMonerisPaymentsServiceHandler.java at line 46.
EPWFPaymentServicesServlet.java code where data is entered
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CodeTimer timer = new CodeTimer("EPWFPaymentServicesServlet.doPost()", true);
response.setContentType("text/xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuffer requestBuffer = new StringBuffer(request.getContentLength());
String line = null;
while ((line = reader.readLine()) != null) {
requestBuffer.append(line).append('\n');
}
// read the POST request contents
String requestString = requestBuffer.toString();
if (logger.isDebugEnabled()) {
logger.debug("EPWF Payment Service POST Request: \n" + ((requestString == null) ? "Null" : requestString.substring(0, 9)));
}
PaymentServiceHandlerComposit paySvcHandler = new PaymentServiceHandlerComposit();
String responseString =paySvcHandler.handleEventMessage(requestString);//line no 49 where fortify is giving description for class where i am sanitizing the data
if (logger.isDebugEnabled()) {
logger.debug("EPWF Payment Service POST Response: \n" + ((responseString == null) ? "Null" : requestString));
}
response.getOutputStream().print(responseString);
timer.stopAndLogTiming("");
}
Given that you are using a new up-to-date version of jackson, there should be no need to pre-sanitise or alter your data at all before handing it off to jackson.
Jackson will only accept and parse valid JSON, as new exploits and vulnerabilities are discovered, the maintainers of Jackson fix and release new versions. and the best you can do is to keep up to date with these versions.
If the above conditions are met, you can safely suppress this error from fortify, the chance that there is a bug in your custom sanitizer is way higher than the chance of there being one in Jackson
I am working on a function that enables the user to check a single student's assessment result. I use try and catch, but when I run the code, the system runs directly to the catch part, and the file's content is blank. I am not sure the reason about this problem. Here is my code:
System.out.println('\n' + "Please enter the Student's uni that you would like to call. Type 'exit' to leave");
String studentInfo = s.nextLine();
if (studentInfo.equalsIgnoreCase("exit")) {
userSelection = "exit";
}
boolean studentFound = false;
for (int i = 0; i < students.size(); i++) {
if (studentInfo.equalsIgnoreCase(students.get(i).getStudentUI())) {
studentFound = true;
try {
File singleStudentList = new File(studentInfo + " .txt");
PrintWriter writer = new PrintWriter(singleStudentList);
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
writer.close();
} catch (Exception e) {
System.out.println("Problem writing the file. Please make sure the path is correct");
}
}
}
Thanks for helping!
My hunch is that your error is in one of these two lines:
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
You haven't included code as to what studentUniLists is, so there is some guesswork here.
My guess is that students.indexOf(studentInfo) could be returning -1, so then when you do studentUniLists.get(-1) on a List, this is going to give you an IndexOutOfBoundsException. You should really only be catching the IOException, so that you can detect this kind of issue
Probably index out of bounds somewhere, e.g:
System.out.println(studentUniLists.get(i));
Are you sure studentUniLists has the index i?
Since you wrote there is no output and it just goes directly to catch.
As commented elsewhere, printing the actual exception helps.
You catch ANY Exception and you print to the console that this is file related problem. It does not have to be.
I suggest you add into your catch clause e.printStackTrace() to print the real problem. Secondly you should consider avoiding catching Exception as it is too broad. It might be worth catching exception that is related to file problems in the first place and leaving the rest uncaught.
Looking at the documentation - PrintWriter will be unlikely to throw errors. Comstructor may throw FileNotFoundException or SecurityException. CheckErrors is the function you need for checking file related errors.
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#checkError(). Yet I believe you have non file related problem like NullPointerException or IndexOutOfBoundsException.
Hope this helps.
First, With Jdk 1.7 when you open the file use the try with ressources to let the jvm do the close automaticly.
File singleStudentList;
try (singleStudentList = new File(studentInfo + " .txt")) {
PrintWriter writer = new PrintWriter(singleStudentList);
}
Second, The error is getting by this : new File(studentInfo + " .txt")
you're always creating the empty file "true .txt"
Third, print the error by ex.printStackTrace();
I'm coming from this question.
The following code does not work well:
public static void main(String[] args) throws Exception {
for (int i = 0; i < 15; i++)
{
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = "test";
String charset = "UTF-8";
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
// Show title and URL of 1st result.
System.out.println(results.getResponseData().getResults().get(0).getTitle());
System.out.println(results.getResponseData().getResults().get(0).getUrl());
}
}
The search query works fine if I run it one time, however in this loop I get a null pointer exception.
Unfortunately I need my program to make several queries :( What can I do?
It returns a NullPointerException at the first results.getResponseData.
This is happening because Google actively blocks suspected terms of service abuse. See section 5.3 here:
http://www.google.com/accounts/TOS
If Google detects that you are issuing search requests via a program without their consent, they don't send back results. Your JSON response will contain this:
{"responseData": null, "responseDetails": "Suspected Terms of Service Abuse. Please see http://code.google.com/apis/errors", "responseStatus": 403}
Check to make sure results and other contained objects are not null before you use them.
if ((results != null) && (results.getResponseData() != null) &&
(results.getResponseData().getResults() != null) &&
(results.getResponseData().getResults().get(0) != null)) {
// Show title and URL of 1st result.
System.out.println(results.getResponseData().getResults().get(0).getTitle());
System.out.println(results.getResponseData().getResults().get(0).getUrl());
}
sorry for the stupid question but my knowledge of java net is terrible.
BAsically in my android application a call many php scripts to get data from a mysql db.
These data are returned in json format and i use Google json library to parse them.
Everything works fine but know in each php page i have to add a test. It the test is successfull, then the script continues and returns the json file, but if the test fails, the script return the string "false", or the value false (that's up to me) and my application instead of showing data has to redirect the user to a login page.
The code is the following:
URL url = new URL(Costanti.IP_SERVER+"myApps.php"+"?userId="+this.userId);
try
{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int status = conn.getResponseCode();
if (status >= 200 && status <= 299)
{
Reader r = new InputStreamReader(conn.getInputStream());
Applicazioni dati = new Applicazioni();
try
{
dati = gsonReader.fromJson(r, Applicazioni.class);
return dati;
}
catch (Exception e)
{
System.out.println("Ho fallito a prendere i dati");
Log.e("JSON_Parser",e.toString());
}
}
}
catch (IOException e)
{
System.out.println("Ho fallito la connnection");
e.printStackTrace();
}
}
So basically i use this google library to read the json file inside the imputStreamReader and fill the Applicazioni object with my data.
How can i check if the content of the imputStreamReader is the string "false" or the boolean false and if it's different parse it with the json library????
In the php at the end i do
echo json_encode($applicazione);
in one case or
echo "false" in the other case
Tnx
InputStream in = new URL(url).openStream();
Scanner scanner = new Scanner(new InputStreamReader(in));
String result = scanner.useDelimiter("\\Z").next(); // this reads the whole
// script output in a string
if(result.equals("false"))
handle the false value...
else
dati = gsonReader.fromJson(result, Applicazioni.class);
You can json encode the false result also like ["result"=>"false"] from PHP, This way you can always JSON decode in your Java program, and then look for result value.
You can put the result value in both cases in the output.