Java handling null Strings with error log [duplicate] - java

This question already has answers here:
Java null check why use == instead of .equals()
(16 answers)
Closed 5 years ago.
I want to initialize a String variable and later assign a value to it using
if (){} else if(){}
This is what I have done:
String roleName;
// A and B are string constants
if (userRoleslist.contains(A)) {
roleName = A;
} else if (userRoleslist.contains(B)) {
roleName = B;
}
if (!roleName.equals(null)) {
audit.info("User: " + userName + " successfully authorized as " +
roleName + " to perform JMX operations.");
return roleName;
} else {
String msg = "User: " + userName + " not authorized to perform JMX operations.";
log.error(msg);
throw new NullPointerException();
}
The problem is that the error is not logged to the console. Only the NullPointerException is thrown and point the line if
(!roleName.equals(null)) {
Also, additionally can I leave out the NullPointerException and a log.error only?

if (!roleName.equals(null)) {
must be
if (roleName != null) {
When you do a null check you should do like this.
As roleName is null, calling a method on it will give you a null pointer exception.

roleName.equals(null) will give you nullpointer exception instead use roleName!=null .

Related

java: unable to cast an Integer object to String

I'm trying to concatenate multiple objects inside a String variable called 'update' from a 'data' array within the method 'addClient' below:
public int addClient(Object[] data) {
try {
if (((String)data[0]).trim().isEmpty() || ((String)data[1]).trim().isEmpty() || ((int)data[2] < 0) || ((int)data[3] <= 0)) {
return StatusBar.ERR_INVALID_INPUT_CODE;
}
// the line below is causing the exception
String update = "INSERT INTO Client VALUES(" + ((String)data[0]).trim() + "," + ((String)data[1]).trim() + "," + ((Integer)data[3]).intValue() + "," + ((Integer)data[4]).intValue() + "," + ((Boolean)data[2]).booleanValue() + "," + ((String)data[5]).trim() + ")";
if (statement.executeUpdate(update) != 1) {
return StatusBar.ERR_INTERNAL_CODE;
}
}
catch (Exception e) {
e.printStackTrace();
return StatusBar.ERR_INTERNAL_CODE;
}
return StatusBar.ERR_SUCCESS_CODE;
}
However when the code above executes; an exception gets raised showing the following message:
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.String
at Model.addClient(Model.java:43)
The 'data' object array is obtained through the call of the following method:
public Object[] getFields() {
return new Object[]{jTextFieldName.getText(), jTextFieldAddress.getText(),
jComboBoxType.getSelectedIndex(),
jSpinnerPhone.getValue(), jSpinnerFax.getValue(),
jTextFieldWebsite.getText()};
}
I did many searches and tried many methods including String.valueOf and Integer.toString, but without any success ..
Why I'm getting such behavior? How can it be solved?
You have a lot of options casting to String.
You chose the "simple" option that will work only if the object is really a String, and you just need to down-cast it (from Object) to String.
Try using one of the following options:
new String (your-Integer-here);
(your-Integer-here).toString();
(your-Integer-here) + "";
Let me know if it's working now :)
The elements of your data array can be of any reference type. Therefore you can't cast them to String without checking their type first.
Luckily, you can simply call their toString method instead.
Change
((String)data[0])
to
data[0].toString()
Instead of casting to String, you can call .toString() method on object, if that is your intention.
You are casting your object
i.e
if (((String)data[0]).trim().isEmpty() || ((String)data[1]).trim().isEmpty() || ((int)data[2] < 0) || ((int)data[3] <= 0)) to
if (data[0].toString().trim().isEmpty() || (data[1].toString().trim().isEmpty() || ((int)data[2] < 0) || ((int)data[3] <= 0))
Assuming data[3] and data[2] are of type Integers.
*PS:You can also log the values, to make sure what the values are.
You can try as below and let me know how it goes.
private static void concater(){
String[] data={"abc","def","23","45","true","xyz"};
String update = "INSERT INTO Client VALUES(" + ((String)data[0]).trim() + "," + ((String)data[1]).trim() + "," + Integer.parseInt(data[2]) + "," +
Integer.parseInt(data[3]) + "," + Boolean.parseBoolean(data[4]) + "," + ((String)data[5]).trim() + ")";
System.out.println(update); //INSERT INTO Client VALUES(abc,def,23,45,true,xyz)
}

NPE in a do/while loop due to EOF...catching the EOF earlier to avoid the NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have written this program to compare 2 files. They are 500mb to 2.8gb in size and are created every 6 hours. I have 2 files from 2 sources (NMD and XMP). They are broken up into lines of text that have fields separated by the pipe(|) character. Each line is a single record and may be up to 65,000 characters long. The data is about TV shows and movies, showing times and descriptive content. I have determined that any particular show or movie has a minimum of 3 pieces of data that will uniquely identify that show or movie. IE: CallSign, ProgramId and StartLong. The two sources for this data are systems called NMD and XMP hence that acronym added to various variables. So my goal is to compare a file created by NMD and one created by XMP and confirm that everything that NMD produces is also produced by XMP and that the data in each matched record is the same.
What I am trying to accomplish here is this: 1. Read the NMD file record by record for the 3 unique data fields. 2. Read the XMP file record by record and look for a match for the current record in the NMD file. 3.The NMD file should iterate one record at a time. Each NMD record should then be searched for in the entire XMD file, record by record for that same record. 4. Write a log entry in one of 2 files indicating success or failure and what that data was.
I have an NPE issue when I reach the end of the testdataXMP.txt file. I assume the same thing will happen for testdataNMD.txt. I'm trying to break out of the loop right after the readLine since the epgsRecordNMD or epgsRecordXMP will have just reached the end of the file if it at that point in the file. The original NPE was for trying to do a string split on null data at the end of the file. Now I'm getting an NPE here according to the debugger.
if (epgsRecordXMP.equals(null)) {
break;
}
Am I doing this wrong? If I'm really at the end of the file, the readLine ought to return null right?
I did it this way too, but to my limited experience they feel like they are effectively the same thing. It too threw an NPE.
if (epgsRecordXMP.equals(null)) break;
Here's the code...
public static void main(String[] args) throws java.io.IOException {
String epgsRecordNMD = null;
String epgsRecordXMP = null;
BufferedWriter logSuccessWriter = null;
BufferedWriter logFailureWriter = null;
BufferedReader readXMP = null;
BufferedReader readNMD = null;
int successCount = 0;
readNMD = new BufferedReader(new FileReader("d:testdataNMD.txt"));
readXMP = new BufferedReader(new FileReader("d:testdataXMP.txt"));
do {
epgsRecordNMD = readNMD.readLine();
if (epgsRecordNMD.equals(null)) {
break;
}
String[] epgsSplitNMD = epgsRecordNMD.split("\\|");
String epgsCallSignNMD = epgsSplitNMD[0];
String epgsProgramIdNMD = epgsSplitNMD[2];
String epgsStartLongNMD = epgsSplitNMD[9];
System.out.println("epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD );
do {
epgsRecordXMP = readXMP.readLine();
if (epgsRecordXMP.equals(null)) {
break;
}
String[] epgsSplitXMP = epgsRecordXMP.split("\\|");
String epgsCallSignXMP = epgsSplitXMP[0];
String epgsProgramIdXMP = epgsSplitXMP[2];
String epgsStartLongXMP = epgsSplitXMP[9];
System.out.println("epgsCallsignXMP: " + epgsCallSignXMP + " epgsProgramIdXMP: " + epgsProgramIdXMP + " epgsStartLongXMP: " + epgsStartLongXMP);
if (epgsCallSignXMP.equals(epgsCallSignNMD) && epgsProgramIdXMP.equals(epgsProgramIdNMD) && epgsStartLongXMP.equals(epgsStartLongNMD)) {
logSuccessWriter = new BufferedWriter (new FileWriter("d:success.log", true));
logSuccessWriter.write("NMD match found in XMP " + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logSuccessWriter.write("\n");
successCount++;
logSuccessWriter.write("Successful matches: " + successCount);
logSuccessWriter.write("\n");
logSuccessWriter.close();
System.out.println ("Match found");
System.out.println ("Successful matches: " + successCount);
}
} while (epgsRecordXMP != null);
readXMP.close();
if (successCount == 0) {
logFailureWriter = new BufferedWriter (new FileWriter("d:failure.log", true));
logFailureWriter.write("NMD match not found in XMP" + "epgsCallsignNMD: " + epgsCallSignNMD + " epgsProgramIdNMD: " + epgsProgramIdNMD + " epgsStartLongNMD: " + epgsStartLongNMD);
logFailureWriter.write("\n");
logFailureWriter.close();
System.out.println ("Match NOT found");
}
} while (epgsRecordNMD != null);
readNMD.close();
}
}
You should not make this:
if (epgsRecordXMP.equals(null)) {
break;
}
If you want to know if epgsRecordXMPis null then the if should be like this:
if (epgsRecordXMP == null) {
break;
}
To sum up: your app throws NPE when try to call equals method in epgsRecordXMP.

Why is my string doesn't accept null?

I need the String receive the null value if it is not found in mapper.getChave is what is returned. What I do? If I only get nullPointerException
for(String chave : linha.keySet()) {
//Processa chave
String novaChave = mapper.getChave(chave.trim());
if (!(novaChave == null || novaChave.isEmpty())) {
//Processa valor
String novoValor = linha.getString(chave);
temp.append(novaChave, novoValor);
}
else {
extras.append(chave, linha.getString(chave));
}
}
Log
java.lang.NullPointerException
at oknok.validacao.readers.PlanilhaReader.processaAtributosPlanilha(PlanilhaReader.java:237)
Line 237 is
String novaChave = mapper.getChave(chave.trim());
**UPDATE: The first time the loop runs, i have a Nullpointer and chave contains a value
System.out.println(chave.isEmpty() + "\t" + chave + "\t" + chave.trim());
Output
false Veículo Veículo
You need to add null check for mapper as well as chave.
if (mapper!= null && chave != null && !"".equals(chave) {
// do something
}
mapper.getChave(chave.trim())
^ ^ possible places for NPE.
Most probably value of chave or mapper would be null and you are calling trim() and .getChave() on them respectively causing nullpointer
You need to check whether chave is null before trimming it or doing anything else (I'm assuming that mapper is pre-initialised and not null, but you should check that too)
e.g.
if (chave != null && !"".equals(chave.trim()) {
// now do something
}
You may find it easier (more intuitive) to use something like Apache Commons StringUtils.isNotBlank(String). See here for the doc.
There is a null string reference in linha.keySet().
Follow code change null string to "" : you can change "" to anything you like
String novaChave = mapper.getChave((chave == null ? "" : chave).trim());

not printing to textbox

I am trying to create a way of retrieving from a hashtable an authorID for the articleName that the user enters. Here is the code that is activated on the client's side when the user presses a button:
public String getAuthorID() // returns a String
{
try
{
articleName = txtArticleName.getText();
argAuthorID = new Vector();// create vector for the args
argAuthorID.addElement(articleName);// name to search for to get AuthorID
// make the call to the server
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
System.out.println(argAuthorID);
}
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
} catch (Exception exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" + exception.toString());
}
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
return StrAuthorID;
}
This is the method on the server side:
public int sendAuthorID(String articleNameRequest) {
// get info from the hashtable
aNumber = (Integer) theHashtable.getAuthorID(articleNameRequest); // was this.
return aNumber;
}
This is the code in the class that contains the hashtable:
public int getAuthorID(String articleName)
{
int intfoundit;
String foundit = (String)hashtab.get(articleName);
System.out.print(foundit);
intfoundit = Integer.parseInt(foundit);
System.out.print(foundit);
System.out.print(intfoundit);
return intfoundit;
}
The program can retrieve the AuthorID but won't input it into the textbox. Via testing I discovered that the exception was thrown by this code:
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
This is the error that is given:
'JavaClient: XML-RPC Consumer Fault #0:
nullorg.apache.xmlrpc.XmlRpcException: java.lang.Exception:
java.lang.NumberFormatException: For input string: " 3377"'
UPDATE: removed the space before the ID number in the hashtable and it doesn't throw an error anymore but it still isn't inputting the ID number into the textbox instead it just inputs a '0'
It seems to be failing in cases when you have spaces in your string. As we can see in your exception trace that parseInt failed to parse " 3377" and it threw NumberFormatException while executing:
intfoundit = Integer.parseInt(foundit);
So you may try to trim the string and see whether it solves your problem:
intfoundit = Integer.parseInt(foundit.trim());
Better you should do the trim where you are saving/putting the key/value in the hashtable.
The answer to the first problem was space before ID number on the hashtable because the space couldn't be converted to an Integer.
The answer to the second problem was that the following line was trying to convert the wrong variable
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
because the Integer was in the AuthorID variable
I corrected this by changing
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
to
authorID = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);

Custom exception message using JUnit assertEquals?

I'm using assert equals to compare two numbers
Assert.assertEquals("My error message", First , Second);
Then, when I generate the Test Report I get
"My error message expected (First) was (Second)"
How can I customize the part I've put in italic? And the format of the numbers?
You can use something like this:
int a=1, b=2;
String str = "Failure: I was expecting %d to be equal to %d";
assertTrue(String.format(str, a, b), a == b);
The message is hard-coded in the Assert class. You will have to write your own code to produce a custom message:
if (!first.equals(second)) {
throw new AssertionFailedError(
String.format("bespoke message here", first, second));
}
(Note: the above is a rough example - you'll want to check for nulls etc. See the code of Assert.java to see how it's done).
Thanks to your answer I've found in the Assert class this
static String format(String message, Object expected, Object actual) {
String formatted= "";
if (message != null && !message.equals(""))
formatted= message + " ";
String expectedString= String.valueOf(expected);
String actualString= String.valueOf(actual);
if (expectedString.equals(actualString))
return formatted + "expected: "
+ formatClassAndValue(expected, expectedString)
+ " but was: " + formatClassAndValue(actual, actualString);
else
return formatted + "expected:<" + expectedString + "> but was:<"
+ actualString + ">";
}
I guess I can't modify Junit Assert class, but I can create a new class in my project with the same name, just changing format, am I right? Or I can just change format in my class and it will affect the Exception thrown?

Categories