Eclipse Antlr Interpreter failure - antlr

The following grammar successfully generates a parser for treating the string 'ccdunion'. But when I try with the interpreter, I have NoViableAltException error, why?
grammar SimpleCalc;
options {
k = 2;
output = AST;
backtrack = true;
}
tokens {
UNION = 'union';
}
#header {
package myPack;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
}
#lexer::header {
package myPack;
}
#members {
public static void main(String[] args) throws Exception {
File fileOut = new File("src/ARFF.arff");
FileWriter fw = new FileWriter(fileOut);
PrintWriter pw = new PrintWriter(fw);
pw.print("a ");
pw.println("b");
pw.println(12);
fw.close();
SimpleCalcLexer lex = new SimpleCalcLexer(new ANTLRFileStream(args[0]));
CommonTokenStream tokens = new CommonTokenStream(lex);
SimpleCalcParser parser = new SimpleCalcParser(tokens);
try {
parser.expr();
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}
expr
: filsPiquets EOF
{
System.out.println("base mono: ");
}
;
filsPiquets
: chars UNION
{
System.out.println("TXTunionII"+$chars.text);
}
;
chars
: CHAR
| . chars
;
CHAR
: .
;

... when I try with the interpreter, I have NoViableAltException error, why?
Because the interpreter is buggy: don't use it. Use the debugger instead. The same goes for ANTLRWorks.

Related

How do I get rid of depreciated code in this class file for java antlr?

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import java.io.FileInputStream;
import java.io.InputStream;
public class Calc {
public static void main(String[] args) throws Exception {
String inputFile = null;
if ( args.length>0 ) inputFile = args[0];
InputStream is = System.in;
if ( inputFile!=null ) is = new FileInputStream(inputFile);
ANTLRInputStream input = new ANTLRInputStream(is);
CalculatorLexer lexer = new CalculatorLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CalculatorParser parser = new CalculatorParser(tokens);
ParseTree tree = parser.program(); // parse
CalcVisitor calcc = new CalcVisitor();
calcc.visit(tree);
}
}
As far as I know, I am pretty sure the ANTLRFileStream is what is depricated, but I have tried replacing it with CharStreams, but the code I try and run keeps resulting in an error. How can I fix this?
Try something like this:
public static void main(String[] args) throws Exception {
CharStream charStream = args.length > 0
? CharStreams.fromFileName(args[0])
: CharStreams.fromStream(System.in);
CalculatorLexer lexer = new CalculatorLexer(charStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CalculatorParser parser = new CalculatorParser(tokens);
ParseTree tree = parser.program(); // parse
CalcVisitor calcc = new CalcVisitor();
calcc.visit(tree);
}

C3P0, rawConnectionOperation() & java.lang.IllegalArgumentException

I am attempting to use a non-standard method, getServerJobIdentifier(), that is part of the IBM Java Tool Box (jt400.jar) and class com.ibm.as400.access.AS400JDBCConnection with C3P0 & rawConnectionOperation(). I am getting "java.lang.IllegalArgumentException: object is not an instance of declaring class". I have tried numerous options but have not stumbled upon the correct parameters to pass. I am using C3P0 0.9.5.4. Code snippet follows:
// The method I want to call.
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
String m_DatabaseConnectionString = "jdbc:db2:*local;naming=sql;extended metadata=true";
Connection m_dbConnection;
ComboPooledDataSource m_cpds;
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
m_dbConnection = m_cpds.getConnection();
String qualifiedName = "";
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
Method m = AS400JDBCConnection.class.getDeclaredMethod("getServerJobIdentifier");
// This does return what I want. getServerJobIdentified() has no parameters.
System.out.println("method=" + m.toString());
Object[] args = new Object[] {};
System.out.println("calling rawConnectionOperation");
qualifiedName = (String) castCon.rawConnectionOperation(m, C3P0ProxyConnection.RAW_CONNECTION, args);
// never gets here
System.out.println("qualifiedName=" + qualifiedName);
I know I'm that close or I think I am. Thanks!
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import com.mchange.v2.c3p0.*;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCConnection;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.db2.jdbc.app.DB2Connection;
// javac -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main.java
// /QIBM/ProdData/OS400/jt400/lib/jt400Native.jar
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main
// or
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:/QIBM/ProdData/OS400/jt400/lib/jt400Native.jar C3P0Main
// c3p0.acquireRetryAttempts=0
// c3p0.acquireRetryDelay=5000
// c3p0.breakAfterAcquireFailure=false
// c3p0.maxConnectionAge=10800
// c3p0.maxIdleTime=3600
// c3p0.maxIdleTimeExcessConnections=600
// c3p0.automaticTestTable=c3p0test
// c3p0.idleConnectionTestPeriod=600
// c3p0.testConnectionOnCheckout=true
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar -Dc3p0.acquireRetryAttempts=0 -Dc3p0.acquireRetryDelay=5000 -Dc3p0.breakAfterAcquireFailure=false -Dc3p0.maxConnectionAge=10800 -Dc3p0.maxIdleTime=3600 -Dc3p0.maxIdleTimeExcessConnections=600 -Dc3p0.automaticTestTable=c3p0test -Dc3p0.idleConnectionTestPeriod=600 -Dc3p0.testConnectionOnCheckout=true C3P0Main
public class C3P0Main {
private Connection m_dbConnection;
private ComboPooledDataSource m_cpds;
private String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
//private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true;user=beak;password=roatan12";
private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true";
private String m_databaseServerJobID;
public C3P0Main() throws SQLException
{
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
}
public void run(String[] args) throws Exception
{
m_dbConnection = m_cpds.getConnection();
System.out.println("m_dbConnection=" + m_dbConnection.toString());
String qualifiedName = "";
try {
// To use it, first cast the returned Connection to a C3P0ProxyConnection.
// Then call the method rawConnectionOperation, supplying the java.lang.reflect.Method object
// for the non-standard method you wish to call as an argument. The Method you supply will
// be invoked on the target you provide on the second argument (null for static methods),
// and using the arguments you supply in the third argument to that function. For the target,
// and for any of the method arguments, you can supply the special token
// C3P0ProxyConnection.RAW_CONNECTION, which will be replaced with the
// underlying vendor-specific Connection object before the Method is invoked.
//
// C3P0ProxyConnection castCon = (C3P0ProxyConnection) c3p0DataSource.getConnection();
// Method m = CLOB.class.getMethod("createTemporary", new Class[]{Connection.class, boolean.class, int.class});
// Object[] args = new Object[] {C3P0ProxyConnection.RAW_CONNECTION, Boolean.valueOf( true ), new Integer( 10 )};
// CLOB oracleCLOB = (CLOB) castCon.rawConnectionOperation(m, null, args);
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
System.out.println("Is a wrapper for DB2Connection=" + m_dbConnection.isWrapperFor(com.ibm.db2.jdbc.app.DB2Connection.class));
System.out.println("Is a wrapper for AS400JDBCConnection=" + m_dbConnection.isWrapperFor(AS400JDBCConnection.class));
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
System.out.println("C3P0ProxyConnection.RAW_CONNECTION=" + C3P0ProxyConnection.RAW_CONNECTION.getClass().getName());
Method method = AS400JDBCConnection.class.getMethod("getServerJobIdentifier");
System.out.println("method=" + method.toString());
Object[] method_args = new Object[] {};
System.out.println("calling rawConnectionOperation");
try {
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #1.");
}
try {
Object[] method_args = new Object[] {};
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #2.");
}
if (castCon instanceof AS400JDBCConnection) {
System.out.println("YES");
qualifiedName = ((AS400JDBCConnection)C3P0ProxyConnection.RAW_CONNECTION).getServerJobIdentifier();
String jobName = qualifiedName.substring(0, 10).trim();
String jobUser = qualifiedName.substring(10, 20).trim();
String jobNumber = qualifiedName.substring(20).trim();
m_databaseServerJobID = jobNumber + '/' + jobUser + '/' + jobName;
System.out.println("SQL Server Job ID: " + m_databaseServerJobID);
}
else {
System.out.println("m_dbConnection is not an instance of DB2Connection.");
}
}
catch (IllegalArgumentException | SQLException | NoSuchMethodException e) {
System.out.println(e);
System.out.println("oh well.");
}
}
public static void main(java.lang.String args[])
{
try {
C3P0Main app = new C3P0Main();
app.run(args);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

how to compare text on web page with text in external file in web driver?

I am trying it by below code:-
BufferedReader in = new BufferedReader(new FileReader("TC5_data.txt"));
String str;
while ((str = in .readLine()) != null) {
System.out.println(str); {
String str1 = driver.findElement(By.xpath("//*[#id='content']/div[2]/table/tbody/tr/td[1]")).getText();
if (str.equals(str1)) {
System.out.println("Data is Matching");
} else {
System.out.println("Data is not Matching");
}
But above code is not working for me... need help urgntly
These are the necersary imports:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
To compare the String you need to use equalsIgnoreCase function
Use below code for condition :-
if(str.equalsIgnoreCase(str1))
{
System.out.println("Equal");
}else{
System.out.println("Not Equal");
}
Hope it will help you :)

Write in a file in ANTLRWorks

I am writing a parser using the ANTLR framework. I want to write in a file, so I use this code, but I do not know where I should close the file?
#header
{
import java.io.*;
}
main:{
BufferedWriter out = null;
try{
FileWriter fstream = new FileWriter("output.txt");
out = new BufferedWriter(fstream);
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
};
p1 : p2 {out.write("this is p1");}
;
p2 ......
If main is the entry point of your grammar, you would close the stream at the end of that rule:
grammar T;
#header {
import java.io.*;
}
#members {
OutputStream out = null;
void before() {
// initialize 'out' here
}
void after() {
// close 'out' here
}
}
main
: {before();}
p1 EOF
{after();}
;
p1
: p2 {out.write("this is p1");}
;
p2
: ...
;
You could even provide empty implementations of your methods inside the #members block:
#members {
OutputStream out;
void before() {}
void after() {}
}
and override/implement them in the listener/visitor classes to minimize target specific code inside the grammar itself.

junit test with Eclipse

Hi i am trying to use junit and it does not work s well.
Here is my code.
package safe;
import java.lang.reflect.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import safe.SafetyException;
public class SafetyInspector {
public static boolean isSafe(Class<?> clazz) throws SafetyException{
if (clazz.equals(Object.class)) return true;
if (clazz == null ) {
throw new SafetyException();
}
Field fields[] = clazz.getDeclaredFields();
for(Field f: fields){
f.setAccessible(true);
int mod = f.getModifiers();
if (Modifier.isFinal(mod)){
continue;
}
else if (Modifier.isPrivate(mod)){
Class<?> typeArray[] = new Class<?>[1] ;
typeArray[0] = f.getType();
try {
Method mSet = clazz.getMethod("set" + f.getName().substring(0, 0).toUpperCase() + f.getName().substring(1),typeArray );
int modMet = mSet.getModifiers();
if(!Modifier.isPublic(modMet)) return false;
if(!mSet.getReturnType().equals(void.class)) return false;
}
catch (SecurityException e) {
throw new SafetyException();
}
catch (NoSuchMethodException e) {
return false;
}
try {
Class<?> typeArray2[] = new Class<?>[1] ;
Method mGet = clazz.getMethod("get" + f.getName().substring(0, 0).toUpperCase() + f.getName().substring(1),typeArray2);
int modMet2 = mGet.getModifiers();
if(!Modifier.isPublic(modMet2)) return false;
if(!mGet.getReturnType().equals(f.getType())) return false;
}
catch (SecurityException e) {
throw new SafetyException() ;
}
catch (NoSuchMethodException e) {
return false;
}
}
}
return isSafe(clazz.getSuperclass());
}
public static void sort(List<Class<?>> classes) throws SafetyException{
for (int i = 1; i < classes.size(); i++) {
for (int j = 0; j < classes.size() - i; j++) {
if (compare(classes.get(j), classes.get(j + 1)) > 0) {
swap(classes, j);
}
}
}
}
public static void reset(Object object) throws SafetyException{
Class c = object.getClass();
Field fields[] = c.getDeclaredFields();
for(Field f :fields ){
if (!isSafe(f.getClass()))
{
f.setAccessible(true);
try{
if(!f.getClass().isPrimitive()){
}
else if(f.getClass().equals(boolean.class)){
f.setBoolean(object, false);
}
else{
f.set(object, 0);
}
}
catch(Exception e)
{
throw new SafetyException();
}
}
}
}
private static int compare(Class<?> o1, Class<?> o2) throws SafetyException {
Field[] fields1 = o1.getDeclaredFields();
int count1 = 0;
for (Field f : fields1){
if (isSafe(f.getClass())) count1++;
}
Field[] fields2 = o2.getDeclaredFields();
int count2 = 0;
for (Field f : fields2){
if (isSafe(f.getClass())) count2++;
}
if (count1 == count2)
return o1.getName().compareTo(o2.getName());
else return count1- count2;
}
private static void swap(List<Class<?>> list, int j) {
Class<?> temp = list.get(j);
list.set(j, list.get(j+1));
list.set(j + 1, temp);
}
};
and here is the code junit test that they gave me.
package test;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import safe.SafetyException;
import safe.SafetyInspector;
public class SafetyInspectorTest {
#Test
public void testIsSafeEmployee() throws SafetyException {
assertEquals(false, SafetyInspector.isSafe(Employee.class));
}
#Test
public void testResetEmployee() throws SafetyException {
Employee e = new Employee(123,3000);
SafetyInspector.reset(e);
assertEquals(0, e.id);
assertEquals(3000, e.getSalary());
}
#Test
public void testSort() throws SafetyException {
List<Class<?>> sortedClasses = new LinkedList<Class<?>>();
sortedClasses.add(Employee.class);
List<Class<?>> classes = new LinkedList<Class<?>>(sortedClasses);
Collections.shuffle(classes);
SafetyInspector.sort(classes);
assertEquals(sortedClasses, classes);
}
}
and when I run the safetyInspectorTest as a junitTESTCLASS i get an initialization error. I work with eclipse if it helps and I put Junit as a library of the project.
An initialization error in JUnit is generally caused by a bad classpath. See this related question which also suffered from initialization error:
Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window
The most likely cause is as that question addressed, you are using a version of JUnit 4 which requires the hamcrest jar to be added. Instead of adding the junit and hamcrest jars you should be able to add the JUnit 4 library on your project's Java Build Path.
Your imports largely look benign but you should confirm safe.SafetyException is on your classpath.
Finally, the initialization error could be caused by a static initialization failure in code that loads before your test runs. The code you've posted looks safe but SafetyException class could possibly have an initialization block to check.