I have written following code snippet:-
public Collection<?> constructResponse (...........) throws RemoteException {
while (keyIterator.hasNext())
{
String keyValue = (String) keyIterator.next();
keyString = new StringBuilder(); // since multiple keys will be there in map need to ensure every time keyString and valueString is created
valueString = new StringBuilder();
keyString.append(keyValue + ";" + "name");
List<CustomValuePOJO> customPOJOlist = employeeValuesMap.get(keyValue );
for (CustomValuePOJO customPOJO : customPOJOlist )
{
if (protocol == null || protocol.equals(""))
{
valueString.append(rpNatPOJO.getDcnPort() + ":"+ rpNatPOJO.getProtocol() + ";");
}
else if (customPOJO .getProtocol().equals(protocol))
{
valueString.append(customPOJO .getPort() + ":"+ protocol + ";");
}
else
{ throw new RemoteException("Invalid Argument: Unsupported protocol "+ protocol);
}
}
if (valueString.length() == 0)
{
return generateErrorResponse("No info found");
}
responseMap.put(keyString.toString(), valueString.toString());
}
}
The weird behavior which is happening is that while iterating through the customPOJO its coming inside elseIf and also setting the value in valueString by executing below code:
else if (customPOJO .getProtocol().equals(protocol))
{
valueString.append(customPOJO .getPort() + ":"+ protocol + ";");
}
After this elseif its coming directly on line
throw new RemoteException("Invalid Argument: Unsupported protocol "+ protocol);
There is no error which is coming in append operation and checked in debug perspective the value is getting appended successfully in valueString.
Please tell what i am missing
Figure I should put this as an answer instead of just a comment...
This sort of behavior can occur when your code (what you are stepping through in the debugger) is out of sync with the compiled class files (that are actually running). Since debug information is associated with line numbers, the lines may be different in the class files than in the source code you see.
Try running a clean build and make sure that there are no duplicate jars on your classpath that may be causing this.
Related
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.
I have a logging function in CSharp and Java that I use in walking the stack. How do I make each log print to a new line only. Below are my Java and CSharp Functions.
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters );
}
the java version is this
public static void LogFunctionCall(string parameters,
[System.Runtime.CompilerServices.CallerMemberName] string methodName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
var stackFrame = new StackFrame(1);
var callerMethod = stackFrame.GetMethod();
var className = callerMethod.DeclaringType;
System.Diagnostics.Trace.WriteLine("CCCCCCCCCCCCCCCC" + " " + className + " " + methodName + " " + sourceLineNumber + " " + parameters + "\n");
}
I code on a windows machine.
Please where exactly do I need to place the new line character. I tried this
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters + "\n" );
}
but I still saw some of the logs being clumped up on a single line.
Instead of \n, try \r\n (carriage return and newline). Some text editors will display differently, so the newline may be in there, but whatever app you're using to read the logs might not be displaying it correctly.
You could also try
System.lineSeparator();
I've seen instances where the /n won't work but the lineSep does.
Also, because it hasn't been mentioned, Environment.NewLine will give you the new line character that is configured for the current environment.
I am having a piece of if-else code to check if a string is displayed, to my surprise the Else part is not getting executed at all.
For eg: If the error string is shown, the IF part works fine. In cases where the error string is not shown, the Else part is not getting executed. Kindly help
if(getErrText.length() > 0) {
System.out.println(getErrText + " For "+ readerIterator);
} else {
System.out.println(" Error is not displayed - Err Cell" + " For "+ readerIterator);
}
When I make a few assumptions,
public static void main(String[] args) {
String getErrText = ""; // <--------------- To trigger else.
String readerIterator = "Yes it is"; // <-- To display a message.
if (getErrText.length() > 0) { // <-------- else means that getErrText **must** be ""
System.out.println(getErrText + " For "
+ readerIterator);
} else {
System.out.println("Error is not displayed "
+ "- Err Cell For " + readerIterator);
}
}
Output is
Error is not displayed - Err Cell For Yes it is
As I would expect.
Edit
As per comment(s), your actual problem is likely to be one of
// trim() the String!
if (getErrText != null && getErrText.trim().length() > 0) {
// as before...
}
or silently swallowing your exception. Please don't do that.
try {
getErrText = toSearch.errorCell.getText();
getErrText = (getErrText != null) ? getErrText.trim() : "";
}catch(Exception e){
e.printStackTrace();
}
You are probably enclosing this within a block where error is set which is why your getErrText length is always greater than zero.
Could you please add your enclosing code for getting the error text please
In case you else is not getting executed, print the if part of your code and debug.
If both your if and else dont get executed, then the flow is not reaching your if-else at all for those scenarios .
To find out your problem, print the error on your else:
System.out.println(" Error is not displayed - Err Cell" + " For "+ readerIterator+" The getErrText is ["+getErrText+"]);
Hi I have been struggling to get the 'getenv' to work. it will keep on returning "Exception in thread "main" java.lang.UnsupportedOperationException". I have been reading about the ProcessBuilder but i am not quite sure on how and where to implement it based on my code below.
What I want to exactly do is, to set a variable ("REGRESSION_STATUS", "UPDATED") and ("REGRESSION_STATUS", "OUTDATED") when the condition is met, and return the value "UPDATED" and "OUTDATED" as appropriate when executed through the cmd in Windows.
public static void main(String[] args) throws ClassNotFoundException {
String run_type = args[0];
String inputFile = args[1];
System.out.println("RUN TYPE = " + run_type);
System.out.println("INPUT FILE = " + inputFile);
MiniData data = getValue(run_type, "LEM");
if(run_type.equals("BUILD")){
System.out.println("Script = " + data.getScript());
}
else if (run_type.equals("DEPLOY")){
System.out.println("Script = " + data.getScript());
}
else if (run_type.equals("REGRESSION")){
System.out.println("Runtime Version (DB) = " + data.getRuntime());
String file_name =inputFile;
if(data.getRuntime().equals(getRuntimeVersion(file_name)))
{
System.out.println("The version is up-to-date");
System.getenv().put("REGRESSION_STATUS", "UPDATED");
System.getenv().put("REGRESSION_VER", data.getRuntime());
}
else
{
System.out.println("This version is outdated");
System.getenv().put("REGRESSION_STATUS", "OUTDATED");
System.getenv().put("REGRESSION_VER", data.getRuntime() );
}
}
else {
System.out.println("You have not the correct value. Enter either BUILD/DEPLOY/REGRESSION");
}
}
Thanks!
The System.getenv() method returns an unmodifiable view of the environment variables. You cannot use it to set environment variables like you're doing here.
The only time you can "set" environment variables is when you are creating an environment for a child process, using the ProcessBuilder class or the Runtime.exec method, but even then you are not modifying your copy of the environment.
You must use C putenv and JNI, there is no way to do that from Java.
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);