Initialising my Lexer throws an error in Antlr4 - java

Hi Team,
I'm new to Antlr and I have spent 4 days trying to learn, install, run tutorials and integrate with my IDE. :(
I can run this [tutorial][1] in the Terminal successfully. My goal now is to run the same tutorial in Netbeans with AntlrWorks2 I have cannibalised the Main from [Here][2].
The code compiles, but when I run I get an "java.lang.ExceptionInInitializerError" from init of the Lexer.
1: http://www.antlr.org/wiki/display/ANTLR4/Getting+Started+with+ANTLR+v4
2: http://www.certpal.com/blogs/2011/01/antlr-tutorial-hello-antlr/)
Grammar:
grammar Split;
#header {
package PlayGround.AutoGen;
}
hi : HELLO ID ; // match keyword hello followed by an identifier
ID : [a-z]+ | [A-Z]+; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
HELLO : '[H|h]ello';
Main:
public class MyMain {
public static void main(String args[]) {
new MyMain().MyAttempt();
}
public void MyAttempt() {
try {
String string = "Hello World";
CharStream charStream = new ANTLRInputStream(string);
/*Line 28*/ SplitLexer lex = new SplitLexer(charStream); /*Line 28*/
org.antlr.v4.runtime.CommonTokenStream tokens;
tokens = new org.antlr.v4.runtime.CommonTokenStream(lex);
SplitParser parser = new SplitParser(tokens);
SplitParser.HiContext split = parser.hi();
String toString = split.toString();
System.out.println(toString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error:
run:
Exception in thread "main" java.lang.ExceptionInInitializerError
at PlayGround.MyMain.MyAttempt(MyMain.java:28)
at PlayGround.MyMain.main(MyMain.java:21)
Caused by: java.lang.UnsupportedOperationException: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with version 2 (expected 3).
at org.antlr.v4.runtime.atn.ATNSimulator.deserialize(ATNSimulator.java:132)
at PlayGround.AutoGen.SplitLexer.<clinit>(SplitLexer.java:78)
... 2 more
Caused by: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with version 2 (expected 3).
... 4 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
ANSWER: antlr4: ATN version 2 expected 3

It sounds like there might be a version issue. ANTLR generates serialized ATN (augmented transition networks) that have a special format that can change from version to version like 4.0 to 4.1. it's possible that your loading source code generated from the command line in one version and the latest AW2 in NetBeans is trying to read it with a different version.

"Your parser was generated with ANTLR 4.0, but you are trying to execute it with ANTLR 4.1. The most likely cause of this is using ANTLRWorks 2.0 to generate the parser, which internally uses ANTLR 4.0. I'm in the process of releasing ANTLRWorks 2.1 which will correct this mismatch." - 280Z28
Answer is Here

Related

Why wont this .jar file run when I try to start it on C#? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm very new to the coding space and was wondering if someone could help me start a .jar file. BTW This is using C#. My issue is this wont run the file. I got it to work with .txt files though, so I'm just a bit confused.
private void button1_Click(object sender, EventArgs e)
{
Process.Start("java" , "server.jar");
}
In short, for the answer, add -jar right before the JAR file name.
The accepted answer is not 100% correct for several reasons: it does not recognize whitespace-delimited and whitespace-containing arguments, and may mess up with quote characters that must be passed (therefore properly escaped) to the delegated Java app. In short, do not use Arguments if the string is not known to be a constant (having spaces will require manual escaping anyway), but merely prefer ArgumentList that handles each argument properly.
Here is an example Java application to deal with command line arguments:
public final class SayHello {
private SayHello() {}
public static void main(final String... names) {
for ( final String name : names ) {
System.out.printf("hello %s!\n", name);
}
}
}
The manifest for the JAR file:
Manifest-Version: 1.0
Main-Class: SayHello
Making a JAR file out of it is simple:
javac SayHello.java
jar cfm SayHello.jar MANIFEST.MF SayHello.class
Example of use:
java -jar SayHello.jar 'John Doe' Anonymous
that gives:
hello John Doe!
hello Anonymous!
Now, an example C# program that passes the -jar argument to the java process so that it recognizes the given file as a JAR file and demonstrates what can go wrong with Arguments if passed as a string.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
using System.Diagnostics;
public static class SayHello {
public static void Main() {
// interprets 3 names: John, Doe, Anonymous (wrong)
RunJavaJarBadly1("SayHello.jar", "John Doe Anonymous");
// interprets 1 name: John Doe Anonymous (wrong)
RunJavaJarBadly2("SayHello.jar", "John Doe Anonymous");
// interprets 2 names: John Doe, Anonymous (correct, but bad: requires the first name to be quoted at the call-site)
RunJavaJarBadly1("SayHello.jar", "\"John Doe\" Anonymous");
// interprets 1 name: "John Doe" Anonymous (wrong: interprets everything as a single name)
RunJavaJarBadly2("SayHello.jar", "\"John Doe\" Anonymous");
// interprets 2 names, no ambiguous call, each name is recognized properly, does not require quoting at the call site
RunJavaJar("SayHello.jar", "John Doe", "Anonymous");
}
private static void RunJavaJarBadly1(string jarPath, string argumentsFortheJarFile) {
var process = new Process();
process.StartInfo.FileName = "java";
process.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
process.Start();
process.WaitForExit();
}
private static void RunJavaJarBadly2(string jarPath, string jarArgs) {
var process = new Process();
process.StartInfo = new ProcessStartInfo("java") {
ArgumentList = { "-jar", jarPath, jarArgs }
};
process.Start();
process.WaitForExit();
}
private static void RunJavaJar(string jarPath, params string[] jarArgs) {
var process = new Process();
process.StartInfo = new ProcessStartInfo("java") {
ArgumentList = { "-jar", jarPath }
};
foreach ( var jarArg in jarArgs ) {
process.StartInfo.ArgumentList.Add(jarArg);
}
process.Start();
process.WaitForExit();
}
}
The code above produces (no legend in the output, but added for explanation):
hello John! \_ #1/1: incorrect, the space is ignored
hello Doe! /
hello Anonymous! -- #1/2: correct, no spaces in-between
hello John Doe Anonymous! -- #2/1|2: incorrect
hello John Doe! -- #3/1: correct, but requires the call site to escape the argument
hello Anonymous! -- #3/2: correct, no need to escape, thanks to no spaces
hello "John Doe" Anonymous! -- #4/1|2: incorrect, similar to #2/1|2
hello John Doe! -- #5/1: correct, let the framework do its job
hello Anonymous! -- #5/2: correct, let the framework do its job
In order to get it to work, the file name needs to be "java" and contain the file location in the arguments.
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
Taken from similar question here
Optional way using ArgumentList:
System.Diagnostics.Process clientProcess = new Process();
var info = new System.Diagnostics.ProcessStartInfo("java.exe")
{
ArgumentList = {
"-jar",
jarPath,
jarArgs
}
};
info.FileName = "java";
clientProcess.StartInfo = info;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;
Here are some options for you to check out.
Also similar question with a working result: here
Paraphrasing from links:
In order to get it to work, the file name needs to be "java" and contain the file location in the arguments.
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;

Error Creating TokenRegex Rules

I am creating a TokenRegex Rules list. This is what I have:
$STARTING_SEQUENCE = (/start/|/begin/)
{
ruleType: "tokens",
pattern: ([{lemma:$STARTING_SEQUENCE}]),
result: "START"
}
When I compile my code, the compiler gives me this error:
Reading TokensRegex rules from tr.txt
Exception in thread "main" java.lang.RuntimeException: Error parsing file: tr.txt
at edu.stanford.nlp.ling.tokensregex.CoreMapExpressionExtractor.createExtractorFromFile(CoreMapExpressionExtractor.java:258)
at MedicalTranscript.x(MedicalTranscript.java:37)
at MedicalTranscript.main(MedicalTranscript.java:76)
Caused by: java.lang.ClassCastException: edu.stanford.nlp.ling.tokensregex.TokenSequencePattern cannot be cast to java.lang.String
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.CoreMapVarValue(TokenSequenceParser.java:1673)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.AttrValue(TokenSequenceParser.java:1534)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.CoreMapNode(TokenSequenceParser.java:1434)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.NodeBasic(TokenSequenceParser.java:1411)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.NodeGroup(TokenSequenceParser.java:1378)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.NodeDisjConj(TokenSequenceParser.java:1317)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.BracketedNode(TokenSequenceParser.java:1178)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.SeqRegexBasic(TokenSequenceParser.java:884)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.SeqRegexDisjConj(TokenSequenceParser.java:1071)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.SeqRegex(TokenSequenceParser.java:841)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.BasicValue(TokenSequenceParser.java:383)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.ValueExpression(TokenSequenceParser.java:292)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.Expression(TokenSequenceParser.java:210)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.FieldValue(TokenSequenceParser.java:345)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.CompositeFieldValue(TokenSequenceParser.java:333)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.Rule(TokenSequenceParser.java:122)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.RuleList(TokenSequenceParser.java:107)
at edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser.getExpressionExtractor(TokenSequenceParser.java:22)
at edu.stanford.nlp.ling.tokensregex.CoreMapExpressionExtractor.createExtractorFromFile(CoreMapExpressionExtractor.java:254)
... 2 more
What am I doing wrong?
Try
$STARTING_SEQUENCE = "/start|begin/"
Because it is a regular expression for matching the string field lemma, it needs to be a string expressing a normal regular expression over string.
You may also want to do something with the result or use actions to do some annotation:
Example:
{
ruleType: "tokens",
pattern: ([{lemma:$STARTING_SEQUENCE}]),
action: ( Annotate($0, ner, "START") )
}

Unable to call an instance method from Clojure.

I'm completely new to Java and clojure. But with previous experience in common lisp, I thought I would give clojure a try. I'm unable to figure out few very basic things.
This is the actual Java code.
import syntaxtree.*;
import visitor.*;
public class Main {
public static void main(String [] args) {
try {
Node root = new MicroJavaParser(System.in).Goal();
System.out.println("Program parsed successfully");
}
catch (ParseException e) {
System.out.println(e.toString());
}
}
}
When I run this code, the outcome is as expected.
└──╼ java Main < ../input/Factorial.java
Program parsed successfully
In Clojure I tried this :
(ns clj-assign2.core)
(defn -main
[]
(def root
(.Goal
(MicroJavaParser. (. System in))))
(println "Successfully parsed"))
But when this code is run, the following exception is raised :
└──╼ lein run < ../assign2/input/Factorial.java
Exception in thread "main" java.lang.IllegalArgumentException: No matching field found: Goal for class MicroJavaParser
at clojure.lang.Reflector.getInstanceField(Reflector.java:271)
at clojure.lang.Reflector.invokeNoArgInstanceMember(Reflector.java:300)
at clj_assign2.core$_main.invoke(core.clj:7)
< --- snipped --- >
What am I doing wrong here?
Maybe you are missing an import statement in your clojure program?

Protobuf / Protocol Buffers - IndexOutOfBoundsException

I am developing a Client-Server-application which uses Google Protocol Buffers.
Unfortunatelly when I am building the protocol buffer response on the server side using the builder pattern I get a IndexOutOfBoundsException:
This is the line where I build the protobuf file:
Builder getVGResonseBuilder = App_getVGResponse.GetVGResponse.newBuilder().getVGBuilder(0);
[some more code that uses the builder patterns]
getVGResponseBuilder.set...
getVGResponseBuilder.set...
the error occures in the first line of code.
here is the protobuf definition (ofc I have compiled it! The compiled calss is App_getVGResponse):
message GetVGResponse {
message VG {
optional string id = 1;
optional string g_id = 2;
optional int64 f_id = 3;
optional string g_name = 4;
}
repeated VG v_gp = 1;
}
Here is a excerpt of my stacktrace
Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: **Protocol message tag had invalid wire type.**
at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:78)
at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:498)
at com.google.protobuf.GeneratedMessage$Builder.parseUnknownField(GeneratedMessage.java:439)
and the debugger at runtime shows ma the variable:
e
-> cause: IndexOutOfBoundsException (id=12291)
-> detaiMessage: Index: 0, Size: 0 (id=12324)
-> stackTrace null
personally I create the "child builder" then add it to the parent builder. i.e.
App_GetVGResponse.GetVGResponse.Builder bldr = App_GetVGResponse.GetVGResponse.newBuilder();
App_GetVGResponse.GetVGResponse.VG.Builder childBldr = App_GetVGResponse.GetVGResponse.VG.newBuilder();
childBldr.setId(value);
...........
bldr.addVGp(childBldr);
I think the error is because you get the "child" builder before adding one

bean validation- hibernate error

I am getting following exception when trying to run my command line application:
java.lang.ExceptionInInitializerError
at org.hibernate.validator.engine.ConfigurationImpl.<clinit>(ConfigurationImpl.java:52)
at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(String.java:1937)
at org.hibernate.validator.util.Version.<clinit>(Version.java:39)
... 34 more
Am I doing anything wrong? Please suggest.
This is strange. I pasted the relevant parts of the static initialization block of o.h.v.u.Version in a class with a main and added some poor man's logging traces:
public class VersionTest {
public static void main(String[] args) {
Class clazz = org.hibernate.validator.util.Version.class;
String classFileName = clazz.getSimpleName() + ".class";
System.out.println(String.format("%-16s: %s", "classFileName", classFileName));
String classFilePath = clazz.getCanonicalName().replace('.', '/') + ".class";
System.out.println(String.format("%-16s: %s", "classFilePath", classFilePath));
String pathToThisClass = clazz.getResource(classFileName).toString();
System.out.println(String.format("%-16s: %s", "pathToThisClass", pathToThisClass));
// This is line 39 of `org.hibernate.validator.util.Version`
String pathToManifest = pathToThisClass.substring(0, pathToThisClass.indexOf(classFilePath) - 1)
+ "/META-INF/MANIFEST.MF";
System.out.println(String.format("%-16s: %s", "pathToManifest", pathToManifest));
}
}
And here the output I get when running it:
classFileName : Version.class
classFilePath : org/hibernate/validator/util/Version.class
pathToThisClass : jar:file:/home/pascal/.m2/repository/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar!/org/hibernate/validator/util/Version.class
pathToManifest : jar:file:/home/pascal/.m2/repository/org/hibernate/hibernate-validator/4.0.2.GA/hibernate-validator-4.0.2.GA.jar!/META-INF/MANIFEST.MF
In your case, the StringIndexOutOfBoundsException: String index out of range: -2 suggests that:
pathToThisClass.indexOf( classFilePath )
is returning -1, making the pathToThisClass.substring(0, -2) call indeed erroneous.
And this means that org/hibernate/validator/util/Version.class is somehow not part of the pathToThisClass that you get. I don't have a full explanation but this must be related to the fact that you're using One-Jar.
Could you run the above test class and update your question with the output?
So, as you use One-JAR, the problem probably is in incompatibility between One-JAR and Hibernate Validator. However, in the latest version of One-JAR (0.97) it works fine, therefore use the latest version.

Categories