Drools: NullPointerException when addPackageFromDrl(source) is called - java

I'm trying to execute a simple HelloWorld rule within an OSGi application. During parsing and compiling however, the following exception occurs:
java.lang.NullPointerException
at org.drools.rule.builder.RuleBuilder.build(RuleBuilder.java:47)
at org.drools.compiler.PackageBuilder.addRule(PackageBuilder.java:446)
at org.drools.compiler.PackageBuilder.addPackage(PackageBuilder.java:304)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(PackageBuilder.java:167)
The DRL file is found by the application, since introducing syntax errors results in a failed compilation warning. I guess I'm overlooking something trivial, but haven't found it yet...
I'm using Drools 4.0.7, since this one was available on the Springsource Enterprise Bundle Repository. Here are my application code and drl:
//read in the source
Reader source = new InputStreamReader( getClass().getResourceAsStream( "hello.drl" ) );
PackageBuilder builder = new PackageBuilder();
//this wil parse and compile in one step
builder.addPackageFromDrl( source );
// Check the builder for errors
if ( builder.hasErrors() ) {
System.out.println( builder.getErrors().toString() );
throw new RuntimeException( "Unable to compile \"hello.drl\".");
}
//get the compiled package (which is serializable)
org.drools.rule.Package pkg = builder.getPackage();
//add the package to a rulebase (deploy the rule package).
RuleBase ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage( pkg );
StatefulSession session = ruleBase.newStatefulSession();
session.fireAllRules();
#created on: May 1, 2011
package test
rule "A stand alone rule"
when
eval(true)
then
System.out.println("hello world");
end
As always, help is highly appreciated.
KR,
Niels
EDIT: During debugging I noticed that the internal builder object within the PackageBuilder was null, as were the package and packagedescription. I got around the original problem by adding this description manually:
PackageBuilder builder = new PackageBuilder();
PackageDescr packageDescr = new PackageDescr("be.ugent.intec.doctr.processor.job.fever");
builder.addPackage(packageDescr);
//this will parse and compile in one step
builder.addPackageFromDrl( source );
My rule was edited to the following form:
package be.ugent.intec.doctr.processor.job.fever
rule "hello"
when
eval( true )
then
System.out.println("hello there");
end
This however results in a compile failure:
BR.recoverFromMismatchedToken
[1,0]: unknown:1:0 mismatched token: [#0,0:6='println',<7>,1:0];
java.lang.RuntimeException: Unable to compile "hello.drl".
at be.ugent.intec.doctr.processor.job.fever.FeverJob.execute(FeverJob.java:45)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:525)
When removing the package line from the rule, then my example goes all the way through, without printing anything however. Am I again overlooking anything? I guess this is related to an issue within the drl itself, considering everything stands or falls with the declaration of the package. Just to be clear, the drl is loaded in a class contained in the package be.ugent.intec.doctr.processor.job.fever.
Thx!

A NullPointerException shouldn't happen during compilation: either you get a clear compilation error during parsing (which includes line number) or it works. Drools 4.0.7 is old. This is probably already fixed in a newer version of drools. If it isn't, raise a JIRA issue.
Try a more up-to-date version of drools, preferably even a 5.2 version (5.2.0.CR1 will be out later today or tomorrow), which uses the new, better parser.

Related

Suddenly cannot run/compile java program

Everything worked perfectly until I had to brute-force restart notebook with opened java project ( 1 java class which was compiled ). After the reboot i opened intellij created a new project ( the old was not saved ) , then in src folder created a java class but whenever I want to Run it I get only "Edit the configuration" and do not know what to do.
Also when i write some piece of code like:
import java.util.*;
public class Main
{
public static void main( String[] args )
{
List<String> list = new ArrayList<String>();
list.add( "Example" );
}
}
The add method is red and it says Cannot resolve the symbol add().
This happens with every method even to System.out.println()
I will be very thankful for your suggestions. ( Btw I'm using intellij ultimate version, Linux Mint 17 ).
Please read compiler messages more carefully.
List<String> list = new String<String>();
Doesnt work - try:
List<String> list = new ArrayList<>();
for example!
So, the real lesson here is not that you made a little typo. It is about the fact that you can trust on compiler error messages to a high degree! So, before you think "is my project broken"; you look at your source code and any error message really really carefully.
Stop Intellij, remove the .idea folder and .iml file from the directory, then restart. You'll have to create a new project from the code, but it should work. If you continue to have problems, go to the File menu and selected "Invalidate caches/restart". Choose "Invalidate and restart."

Running XSLT to RDF framework fails because of Saxon

I´m using Krextor to convert XML to RDF. It runs fine from the command line.
I try to run it from Java (Eclipse) using this code.
private static void XMLToRDF() throws KrextorException, ValidityException, ParsingException, IOException, XSLException{
Element root = new Element("person");
Attribute friend = new Attribute("friends", "http://van-houten.name/milhouse");
root.addAttribute(friend);
Element name = new Element("name");
name.appendChild("Bart Simpson");
root.appendChild(name);
nu.xom.Document inputDocument = new nu.xom.Document(root);
System.out.println(inputDocument.toXML());
Element root1 = inputDocument.getRootElement();
System.out.println(root1);
Krextor k = new Krextor();
nu.xom.Document outputDocument = k.extract("socialnetwork","turtle",inputDocument);
System.out.println(outputDocument.toString());
}
I have the following problem problem
Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/saxon/CollectionURIResolver
Caused by: java.lang.ClassNotFoundException: net.sf.saxon.CollectionURIResolver
I have included Saxon9he in the classpath, and I have also added manually as a library in the project but the error is the same.
I am the main developer of Krextor. And, #Michael Kay, actually a colleague of Grangel, so I will resolve the concrete problem with him locally.
So indeed the last Saxon version with which I did serious testing was 9.1; after that I haven't used Krextor integrated into Java but mainly used Krextor from the command line.
#Grangel, could you please file an issue for Krextor, and then we can work on fixing it together.
Indeed, #Michael Kay, for a while I had been including more recent Saxon versions with Krextor and updated the command line wrapper to use them (such as to add different JARs to the classpath), but I have not necessarily updated the Java wrapper code.

Groovy - Eclipse reporting BUG! (following Java update)

I am completely at a loss over this - updated my Java (to version 8, build 91) and now my Groovy project, in an early development stage, simply will not run. (See answer The update was a co-incidence)
BUG! exception in phase 'semantic analysis' in source unit 'Simul.groovy' unexpected NullpointerException
Caused by: java.lang.NullPointerException
Here is an example piece of code:
package simul
class Simulation {
def globalMemory
def signalNetwork
def processors
def blueTree
def coreArray
def outputDevice
def endian
def coreCount
static CORE_COUNT = 256
static TOTAL_MEM_SIZE = 0x100000000
static DEFAULT_ENDIAN = 0
static LOCAL_MEM_SIZE = 16
static LOCAL_MEM_START = 0xA0000000
Simulation(def cores = this.CORE_COUNT, def memSize = this.TOTAL_MEM_SIZE,
def endianess = this.DEFAULT_ENDIAN)
{
//0 for little endian, 1 for big endian
endian = endianess
globalMemory = new MemoryArray(this, memSize, 0)
coreCount = cores
}
}
def stuff = new Simulation()
stuff.coreArray = []
for (coreNumb in 1..stuff.coreCount) {
stuff.coreArray << new Core(stuff, coreNumb - 1)
}
Eclipse merely flags an error on the package line (and does the same for other class files).
I assume this is a problem caused by the Java update but I can find nobody else referencing this issue online (and unfortunately the Groovy email lists seem to be unavailable due to a DNS problem).
Any clues?
Update
If I try to run one of the files on its own eg groovyConsole Simul.groovy it will execute but then complain it cannot see other files in the package. In fact I can do the same inside the IDE (and this error is repeated in ggts also) if I change the package name for the Simul.groovy file. But if I try to compile/run the code with the package names properly specified it fails with this BUG! error.
(This means the problem is similar - in terms of symptoms - to this: https://answers.atlassian.com/questions/327479/scriptrunner-bug-exception-in-phase-semantic-analysis-in-source-unit-script40-groovy-bundle-is-uninstalled)
This is the stack trace:
BUG! exception in phase 'semantic analysis' in source unit '/Users/adrian/groovy_stuff/simul/src/simul/Simul.groovy' unexpected NullpointerException
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1226)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:651)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:629)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:606)
at org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.processToPhase(GroovyCompilationUnitDeclaration.java:201)
at org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.resolve(GroovyCompilationUnitDeclaration.java:2206)
at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1084)
at org.eclipse.jdt.internal.compiler.Compiler.resolve(Compiler.java:1129)
at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:215)
at org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.process(CompilationUnitProblemFinder.java:281)
at org.codehaus.jdt.groovy.model.GroovyReconcileWorkingCopyOperation.makeConsistent(GroovyReconcileWorkingCopyOperation.java:80)
at org.eclipse.jdt.internal.core.ReconcileWorkingCopyOperation.executeOperation(ReconcileWorkingCopyOperation.java:90)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:729)
at org.eclipse.jdt.internal.core.JavaModelOperation.runOperation(JavaModelOperation.java:789)
at org.codehaus.jdt.groovy.model.GroovyCompilationUnit.reconcile(GroovyCompilationUnit.java:440)
at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:126)
at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.access$0(JavaReconcilingStrategy.java:108)
at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy$1.run(JavaReconcilingStrategy.java:89)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:87)
at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconcile(JavaReconcilingStrategy.java:151)
at org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy.reconcile(CompositeReconcilingStrategy.java:86)
at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile(JavaCompositeReconcilingStrategy.java:104)
at org.eclipse.jface.text.reconciler.MonoReconciler.process(MonoReconciler.java:77)
at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run(AbstractReconciler.java:206)
Caused by: java.lang.NullPointerException
at org.codehaus.groovy.control.StaticVerifier$1.visitVariableExpression(StaticVerifier.java:84)
at org.codehaus.groovy.ast.expr.VariableExpression.visit(VariableExpression.java:70)
at org.codehaus.groovy.ast.CodeVisitorSupport.visitPropertyExpression(CodeVisitorSupport.java:251)
at org.codehaus.groovy.ast.expr.PropertyExpression.visit(PropertyExpression.java:55)
at org.codehaus.groovy.control.StaticVerifier.visitConstructorOrMethod(StaticVerifier.java:79)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitConstructor(ClassCodeVisitorSupport.java:121)
at org.codehaus.groovy.ast.ClassNode.visitContents(ClassNode.java:1214)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClass(ClassCodeVisitorSupport.java:52)
at org.codehaus.groovy.control.StaticVerifier.visitClass(StaticVerifier.java:42)
at org.codehaus.groovy.control.CompilationUnit$13.call(CompilationUnit.java:235)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1221)
... 24 more
Well, the answer is I was referring to static members of the class Simulation in the form of this.STATIC_MEMBER as parameters to the class constructor.
As this doesn't exist at this point (and is superfluous in any case) this does raise a NullPointerException though it is highly confusing that it's flagged at the point of the package command.

Create Java 8 AST with ANTLR4 programmatically

I'm trying to figure out just how exactly to use ANTLR, but I'm having a really difficult time digesting the things I've found. So far, here are my resources:
How to create AST with ANTLR4?
How can I import an ANTLR lexer grammar into another grammar using Gradle 2.10?
https://github.com/antlr/grammars-v4/tree/master/java8
https://dzone.com/articles/parsing-any-language-in-java-in-5-minutes-using-an
https://raw.githubusercontent.com/antlr/antlr4/master/doc/getting-started.md
A little bit of background
I'm experimenting with moving from JavaParse to ANTLR because I want to handle ASTs of languages besides Java. My understanding of ANTLR and the predefined grammars (linked above) is that this is feasible.
Setup
IntelliJ 15 CE
Gradle
Java 1.8
This ANTLR resource
I created a very simple and standard gradle project in IntelliJ and I'm still encountering issues:
The problem
I'm missing the Java8Lexer and Java8Parser classes. I have no idea where to find these.
build.gradle
group 'com.antlr-demo'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile 'org.antlr:antlr4-master:4.5'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
Test.java
Even in this very trivialized example, none of the two classes I need are not being imported.
public static void parseFile(String f) { // found in Test.java:257
try {
if ( !quiet ) System.err.println(f);
// Create a scanner that reads from the input stream passed to us
Lexer lexer = new Java8Lexer(new ANTLRFileStream(f)); // missing
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser that reads from the scanner
Java8Parser parser = new Java8Parser(tokens); // missing
if ( diag ) parser.addErrorListener(new DiagnosticErrorListener());
if ( bail ) parser.setErrorHandler(new BailErrorStrategy());
if ( SLL ) parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
// start parsing at the compilationUnit rule
ParserRuleContext t = parser.compilationUnit();
if ( notree ) parser.setBuildParseTree(false);
if ( gui ) t.inspect(parser);
if ( printTree ) System.out.println(t.toStringTree(parser));
}
catch (Exception e) {
System.err.println("parser exception: "+e);
e.printStackTrace(); // so we can get stack trace
}
}
It's not described in the pom file...
I have created an open source project on github that does the parser/lexer generation and the AST creation automatically and in-memory. You can find it on github https://github.com/julianthome/inmemantlr.
The code for getting the AST from a JAVA program is pretty simple:
// the ANTLR grammar
File f = new File("src/test/ressources/Java.g4");
// plug the ANTLR grammar in
GenericParser gp = new GenericParser(f, "Java");
// load the file that we'd like to parse into a String variable
String s = FileUtils.loadFileContent("src/test/ressources/HelloWorld.java");
// this listener will create an AST from the java file
gp.setListener(new DefaultTreeListener());
// compile Parser/Lexer
gp.compile();
ParserRuleContext ctx = ctx = gp.parse(s);
// get access to AST
Ast ast = dlist.getAst();
// print AST in dot format
System.out.println(ast.toDot());
If you are interested, you could have a closer look at the test cases in the repository.
You are missing one step. You got the java8 grammar but you haven't yet created a a parser from it. This usually involves running the antlr4 jar on the grammar file (FAQs and more), which is very simple (example taken from the Getting Started page):
$ antlr4 Hello.g4
$ javac Hello*.java
There is a gradle plugin whose name is antlr to translate g4 files into java files. You can get details of antlr plugin at https://docs.gradle.org/current/userguide/antlr_plugin.html
In addition, you can see the real project using gradle + antlr: https://github.com/todylu/xcodeprojectParser
the dependency in antlr grammar project : antlr "org.antlr:antlr4:4.5.3"
the dependency in demo project : compile "org.antlr:antlr4-runtime:4.5.3"
By the way, It's better to install ANTLR v4 grammar plugin into Intellij Idea to assist you edit g4 file.

Exception in use of OpenCV

Following is code which i am running :
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class Main_Extraction
{
public static void main( String[] args )
{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Mat mat = Mat.eye( 3, 3, CvType.CV_8UC1 );
System.out.println( "mat = " + mat.dump() );
}
}
this code is having no compile time error.
but, it's giving me run-time exception which is :
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at Main_Extraction.main(Main_Extraction.java:9) Java Result: 1
please, suggest the solution to remove this exception.
I had the same problem. Here is the solution, add this paths in your environment variable CLASSPATH. this will work.
C:\javacv\javacv.jar;
C:\javacv\javacpp.jar;
C:\javacv\javacv-windows-x86.jar;
C:\javacv\jna.jar;C:\javacv;
c:\opencv2.4\build\x86\vc10\bin;
set this according to your javacv installed folder.
You have attempted run a program that has compilation error in it. Fix the compilation errors BEFORE you try to run your program!!
this code is having no compile time error.
That is not true. The actual "compiled" bytecode file you are attempting to run is throwing an exception that says clearly that there was a compilation error of some kind.
Perhaps you are trying to compile a stale version ...
Perhaps you are compiling against a corrupted copy of the OpenCV JAR.
Perhaps you are using a buggy compiler ... and it crashed, giving you a bogus ".class" file.
Please check if the PATH variable is set correctly and opencv libraries are included, there is nothing wrong in the code.
Please follow this tutorial here for step by step installation of opencv in eclipse
http://nenadbulatovic.blogspot.de/2013/07/configuring-opencv-245-eclipse-cdt-juno.html

Categories