ANTLR Error Recovery Causing a NullPointerException in Java - java

I have an ANTLR Grammar that is in the form:
A - B: more,things
However sometimes, either A or B can be missing such as:
- B: more, things //Skip
A - : some, other, things //Skip
C - D: yet, more, things //Read this one and following
E - F: things
I want ANTLR to skip over those lines (where either side of - is missing) and continue processing the rest.
Basically, something like that
- B: more, things {if (!hasBothParts()) { continueAtNextLine();} };
From the book, I provided a #rulecatch and this catch after my appropriate Parser block:
catch[RecognitionException re]{
reportError(re);
consumeUntil(input, NEWLINE);
input.consume();
}
EDIT 2 - I tried doing this instead:
while (input.LA(1) != 6){
input.consume();
}
This worked as expected. 6 is the token identifier for "NEWLINE" for me. I don't know how to do a comparison like input.LA(1) != "\n" or something similar. I know it's not correct to do it this way, I am just experimenting. If you know the right way, please tell me! :)
But this works, unlike the first loop. I suspect consumeUntil is perhaps not seeing the NEWLINE on channel Hidden.
The NullPointer seems to be caused by the input fast-forwarding to EOF, and hence, the tree grammar is hitting a Null when it's doing input.LT(1).
However, in doing so, I get a NullPointerException in my tree grammar:
Exception in thread "main" java.lang.NullPointerException
at org.antlr.runtime.tree.BaseTreeAdaptor.isNil(BaseTreeAdaptor.java:70)
at org.antlr.runtime.tree.CommonTreeNodeStream.nextElement(CommonTreeNodeStream.java:93)
at org.antlr.runtime.misc.LookaheadStream.fill(LookaheadStream.java:94)
at org.antlr.runtime.misc.LookaheadStream.sync(LookaheadStream.java:88)
at org.antlr.runtime.misc.LookaheadStream.LT(LookaheadStream.java:119)
....
The behavior I want is for the parser to skip over the lines missing components and proceed with the remaining lines. The tree parser should not be a problem, I assume?
The ANTLR book does not mention anything regarding this issue.
Also, I think the ANTLR Error Recovery mentions something along those lines but the solution provided is fairly complex/ugly and dates back to 2004. So, is there a better way of doing this relatively simple thing in ANTLR?
Thank you.
EDIT If this helps, the error was caused by this line in the generated tree grammar:
retval.start = input.LT(1);
Which is, I assume, being called with nothing. I.e. LT(1) is returning Null, since it skipped over.

Related

I cant find an error on Java code (11 lines) - Could you give some idea?

Packet packet = new Packet(slot, i+1, n+1);
noOfPacketsGenerated++;
if (queues[i][0].size()+queues[i][1].size()+queues[i][2].size()+queues[i]].size()+queues[i][4].size()+queues[i][5].size()+queues[i][6].size()+queues[i][7].size()<QUEUE_SIZE)
queues[i][n].add(packet);
else {
bufferFails[i]++;
if (debug)
System.out.println("BUFFER FULL # node "+(i+1));
}
errors in photo
I can't find where the errors are?. Any help is much appreciated.
Based on the image of the error, it looks like you put a duplicate ] in your code. i.e., you have
queues[i][0].size()+queues[i][1].size()+queues[i][2].size()+queues[i]] // ...
where you should have
queues[i][0].size()+queues[i][1].size()+queues[i][2].size()+queues[i] // ...
Compiler errors can be cryptic at times, especially if one misplaced character has a cascading effect, but in this case it drew an arrow right to the position where the error occurred.
P.S. that's a really long-winded line of code with lots of room for error. I would recommend either splitting it into a few lines, or making a few temporary values consisting of these separate statements and then putting a shorter, more concise if-statement in your code.

Finding xpath or cssSelector locations for all

I am relatively new to development so please forgive me if some of this seems rather amateurish. Part of my reason for posting the question is to help nudge me to the answer, part is to make sure I'm following good coding practice.
The challenge -
I'm using Java & Selenium to check a very large, dynamically populated table. I need to find a specific list of elements where the text matches a case-sensitive String -
List<WebElement> AllPaths = getCurrentDriver().findElements(By.xpath("//*[text()[contains(.,'" + fixedString + "')]]"));
The table I'm checking is basically a large calendar-style grid. If I don't find evidence of fixedString, I then want to iterate back one month at a time until I DO find the fixedString.
The problem -
The code above returns an exception if it cannot find an element. My first thought was to setup a while loop, trying/catching the exception and then repeating until exceptions stopped. However this feels wrong to me - I don't think I should be essentially "swallowing" exceptions. That said, I'm not sure what the correct way of trying to find this element is that doesn't lead to an exception if it fails to locate it.
Am I right in thinking it's a bad idea to write code that you know causes an exception and then simply swallow it and move on?
Hope this makes sense, as I say I'm a beginner so please be gentle :)
You can try something like -
if(AllPaths.size()>0){
//logic when elements found with fixed string
}else{
//logic to iterate over another month
}
Also, your statement seems wrong to me. It should be -
List<WebElement> AllPaths = getCurrentDriver().findElements(By.xpath("//*[contains(text(),'" + fixedString + "')]"));
findElements doesn't throw exception this way. It will return empty if no elements located. The exception seems due to incorrect statement that you are using to find elements.
The code above returns an exception if it cannot find an element.
The documentation says findElements returns an empty list when no elements are found. It should not throw any exception in this case. Is it possible that you by mistake used findElement instead of findElements? What type of exception is thrown and what is the message?
You shouldn't need to catch exceptions here. You are right though that control flow using exceptions should be avoided and that swallowing exceptions is bad. On the other hand frameworks don't always let you write code the way you want so sometimes exceptions have to be made.

Checking error output is on my errorlist

I have the following code for logging all the errors after every command I run in cmd with my tool. (It runs p4 integrate commands, about 1000-1500/task)
if (errorArrayList.size() > 0) {
LoggerSingleton.I.writeDebugInfoTimeStampedLog("[INFO-CMD] CommandExecuter.java -> runAndGetResults: errors happened while running the following command: [ " + commandResultBean.getCommand() + " ]");
for (int i = 0; i < errorArrayList.size(); i++) {
LoggerSingleton.I.writeDebugErrorTimeStampedLog(errorArrayList.get(i));
commandResultBean.addToCLI_Error(errorArrayList.get(i));
}
LoggerSingleton.I.writeDebugInfoTimeStampedLog("[INFO-CMD] CommandExecuter.java -> runAndGetResults: Listing errors of command [" + commandResultBean.getCommand() + "] finished");
}
The feature that I'm working on right now is check the error I get, and if that's on a predefined error list (list of errors that doesn't matter, and in fact not real errors, for example "all revision(s) already integrated") do nothing else, but when it's a "real" error, write it to an other log file too (Because these debug logs way too long for the users of the tool, it's made for the developers more likely).
The question is, what is the best way for this?
I want to avoid big deceleration. I have many commands, but the number of errors less then the commands, but that is not unusual at all that I get 700-800 "irrelevant" errors in one task.
I will use another class to make the I/O part, and that is not a problem to extend the running time in case we catch a "real" error.
The list is constant, it is okay if it can be modified only by coding.
At the moment I don't know what type to use (2-3 single Strings, List, Array ...). What type should I use? I never used enums in Java before, in this one should I?
I guess a for or foreach and errorArrayList.get(i).contains(<myVariable>)in a method is the only option for the checking.
If I'm wrong, there is a better way to do this?
EDIT
If I have an ArrayList<String>called knownErrors with the irrelevant errors (can define only parts of it), and I use the following code will better performance than a method wrote above? Also, can I use it if I have only parts of the String? How?
if (errorArrayList.removeAll(knownErrors) {
//do the logging and stuff
}
ArrayList itself has a method removeAll(Collection c) which removes all the elements which are matching with input collection elements. Below program show it evidently. So if you have the known error to be skipped in arraylist and pass it to removeall method it will remove the known errors and errorArrayList will have only new errors.

Syntax error insert "}" to complete classBody, new at coding

I have looked around and could not seem to find a solution to this. I'm not sure what is wrong with my code here. Link to my code http://pastebin.com/8z7rjVVK
Error received while compiling:
===== COMPILING - PLEASE WAIT... =====
src\server\model\players\packets\ClickingButtons.java:1313: error: reached end o
f file while parsing
}
^
1 error
=============== DONE ===================
Press any key to continue . . .
Sorry, I know there are other questions regarding the same error, but I can't seem to fix this. Thanks. This is Java.
The problem (or at least one of them) is that you have an if statement inside a switch block. It's almost at the end of the code:
if (c.isAutoButton(actionButtonId))
c.assignAutocast(actionButtonId);
You can't have code directly as a "child" of a switch statement, it must be placed inside a case block.
From the look of it, you define the switch statement and open it with a {, but then you never close it off.
switch (actionButtonId) {
case 118098:
So I added an extra } close bracket at the end of the whole class and the only errors I'm left with are ones for the missing classes. (I don't have your server directory classes)
I would advise using an IDE (like eclipse) or rewriting this class to use an individual method for each case.
Also, using { } for if-else statements will help avoid this type of issue in the future.
EDIT: Final Solution
Once you've got the final close bracket in place, you also needed to move the if statement above the break key word.
The following if statement (around line 1285) became unreachable once the final close bracket was in place
break;
if (c.isAutoButton(actionButtonId))
c.assignAutocast(actionButtonId);

How to find nested conditons count in java

I have to read java file by java code and to determine the greatest nested count of if statements in it.
for example:
if (someCondition)
{
if (someCondition)
{
// Expression
}
}
In this case program should display greatest nested if depth is 2.
Now the problem is that position of curly brace after if is uncertain.
for example it can be like :
Curly brace start and end comes in same line
if (someCondition){}
OR
Curly brace start in next line
if (someCondition)
{
}
OR
Conditions without curly brace
if (someCondition)
if (someCondition) // Single line without curly brace
Can anybody suggest what will be the best way to get the required nested count?
You'll need to parse the Abstract Syntax Tree (AST) of the Java source code. See Java library for code analysis. Once you have the AST, you can do a search to find the longest path of nested conditionals.
As the answer already said, you should rely on the AST rather than viewing code manually for this. The AST will never be wrong, your own reading abilities most often will.
I don't know a complete solution right now, but I suggest you spend some time looking at existing tools for computing software metrics. Nesting depth is a typical metric and there should be tools around.
If you can't find anything, you can at least fall back to writing something like an Eclipse plugin. In that case, you could simply load the Java file in the Eclipse editor, and Eclipse performs all the hard work for you and gives you the AST for free. Determining the nesting depth of a given AST is then rendered a simple task. Developing a prototype for that shouldn't take more than a few hours. And it's easy to extend it to cover your whole project and have it answer questions like "which java file in our project has the maximum nesting depth and what depth is that?". But then again.. someone else will surely point out an existing tool that already does this and much more.
I82Much's answer will certainly get you there, but feels a little like cheating.
Knowing little about your project, I would think that a simple stack mechanism with a max value record would do the trick push on { and pop on }. Once you have that basic model working, simply add the special case of control statements with one line bodies (this is valid for if, for, while ...). In those cases, you'll be looking for those keywords, followed by ( and a ). Once you've encountered that combination, if the scan encounters either another control statement or a semi-colon before it encounters a { then this is one of those special cases and you should push (using a special marker indicating to pop on ; rather than }).

Categories