[jboss-svn-commits] JBL Code SVN: r15281 - in labs/jbossrules/trunk/drools-compiler/src: main/java/org/drools/commons/jci/readers and 4 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Fri Sep 21 23:03:36 EDT 2007


Author: mark.proctor at jboss.com
Date: 2007-09-21 23:03:36 -0400 (Fri, 21 Sep 2007)
New Revision: 15281

Modified:
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/CompilationResult.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompilerSettings.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompiler.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompilerSettings.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JavaCompilerSettings.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/readers/MemoryResourceReader.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/stores/ResourceStore.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java
   labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
   labs/jbossrules/trunk/drools-compiler/src/test/resources/org/drools/integrationtests/test_functionCallingFunction.drl
Log:
JBRULES-1013 Two functions with Janino compiler end up with out of memory error
-Updated to janino 2.5.10 and latest JCI trunk
-created better unit tests for eclipse and janino

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/CompilationResult.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/CompilationResult.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/CompilationResult.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -56,10 +56,14 @@
     }
     
     public CompilationProblem[] getErrors() {
-        return errors;
+    	final CompilationProblem[] res = new CompilationProblem[errors.length];
+    	System.arraycopy(errors, 0, res, 0, res.length);
+        return res;
     }
 
     public CompilationProblem[] getWarnings() {
-        return warnings;
+    	final CompilationProblem[] res = new CompilationProblem[warnings.length];
+    	System.arraycopy(warnings, 0, res, 0, res.length);
+        return res;
     }
 }

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -25,10 +25,10 @@
 import java.util.Map;
 import java.util.StringTokenizer;
 
+import org.drools.util.ClassUtils;
 import org.drools.commons.jci.problems.CompilationProblem;
 import org.drools.commons.jci.readers.ResourceReader;
 import org.drools.commons.jci.stores.ResourceStore;
-import org.drools.util.ClassUtils;
 import org.eclipse.jdt.core.compiler.IProblem;
 import org.eclipse.jdt.internal.compiler.ClassFile;
 import org.eclipse.jdt.internal.compiler.CompilationResult;
@@ -54,89 +54,88 @@
     private final EclipseJavaCompilerSettings defaultSettings;
 
     public EclipseJavaCompiler() {
-        this( new EclipseJavaCompilerSettings() );
+        this(new EclipseJavaCompilerSettings());
     }
 
-    public EclipseJavaCompiler(final Map pSettings) {
-        this.defaultSettings = new EclipseJavaCompilerSettings( pSettings );
+    public EclipseJavaCompiler( final Map pSettings ) {
+        defaultSettings = new EclipseJavaCompilerSettings(pSettings);
     }
 
-    public EclipseJavaCompiler(final EclipseJavaCompilerSettings pSettings) {
-        this.defaultSettings = pSettings;
+    public EclipseJavaCompiler( final EclipseJavaCompilerSettings pSettings ) {
+        defaultSettings = pSettings;
     }
 
-    final class CompilationUnit
-        implements
-        ICompilationUnit {
+    final class CompilationUnit implements ICompilationUnit {
 
-        final private String         clazzName;
-        final private String         fileName;
-        final private char[]         typeName;
-        final private char[][]       packageName;
+        final private String clazzName;
+        final private String fileName;
+        final private char[] typeName;
+        final private char[][] packageName;
         final private ResourceReader reader;
 
-        CompilationUnit(final ResourceReader pReader,
-                        final String pSourceFile) {
-            this.reader = pReader;
-            this.clazzName = ClassUtils.convertResourceToClassName( pSourceFile );
-            this.fileName = pSourceFile;
-            final int dot = this.clazzName.lastIndexOf( '.' );
-            if ( dot > 0 ) {
-                this.typeName = this.clazzName.substring( dot + 1 ).toCharArray();
+        CompilationUnit( final ResourceReader pReader, final String pSourceFile ) {
+            reader = pReader;
+            clazzName = ClassUtils.convertResourceToClassName(pSourceFile);
+            fileName = pSourceFile;
+            int dot = clazzName.lastIndexOf('.');
+            if (dot > 0) {
+                typeName = clazzName.substring(dot + 1).toCharArray();
             } else {
-                this.typeName = this.clazzName.toCharArray();
+                typeName = clazzName.toCharArray();
             }
-
-            final StringTokenizer izer = new StringTokenizer( this.clazzName,
-                                                              "." );
-            this.packageName = new char[izer.countTokens() - 1][];
-            for ( int i = 0; i < this.packageName.length; i++ ) {
-                this.packageName[i] = izer.nextToken().toCharArray();
+            
+            final StringTokenizer izer = new StringTokenizer(clazzName, ".");
+            packageName = new char[izer.countTokens() - 1][];
+            for (int i = 0; i < packageName.length; i++) {
+                packageName[i] = izer.nextToken().toCharArray();
             }
         }
 
         public char[] getFileName() {
-            return this.fileName.toCharArray();
+            return fileName.toCharArray();
         }
 
         public char[] getContents() {
-            final byte[] content = this.reader.getBytes( this.fileName );
+            final byte[] content = reader.getBytes(fileName);
 
-            if ( content == null ) {
+            if (content == null) {
                 return null;
                 //throw new RuntimeException("resource " + fileName + " could not be found");
             }
 
-            return new String( content ).toCharArray();
+            return new String(content).toCharArray();
         }
 
         public char[] getMainTypeName() {
-            return this.typeName;
+            return typeName;
         }
 
         public char[][] getPackageName() {
-            return this.packageName;
+            return packageName;
         }
     }
 
-    public org.drools.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
-                                                                      final ResourceReader pReader,
-                                                                      final ResourceStore pStore,
-                                                                      final ClassLoader pClassLoader,
-                                                                      final JavaCompilerSettings pSettings) {
+    
+    public org.drools.commons.jci.compilers.CompilationResult compile(
+            final String[] pSourceFiles,
+            final ResourceReader pReader,
+            final ResourceStore pStore,
+            final ClassLoader pClassLoader,
+            final JavaCompilerSettings pSettings
+            ) {
 
-        final Map settingsMap = ((EclipseJavaCompilerSettings) pSettings).getMap();
-
+        final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();
+        
         final Collection problems = new ArrayList();
-
+        
         final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
-        for ( int i = 0; i < compilationUnits.length; i++ ) {
+        for (int i = 0; i < compilationUnits.length; i++) {
             final String sourceFile = pSourceFiles[i];
-
-            if ( pReader.isAvailable( sourceFile ) ) {
-                compilationUnits[i] = new CompilationUnit( pReader,
-                                                           sourceFile );
+            
+            if (pReader.isAvailable(sourceFile)) {            
+                compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
             } else {
+                // log.error("source not found " + sourceFile);
 
                 final CompilationProblem problem = new CompilationProblem() {
 
@@ -167,104 +166,93 @@
                     public boolean isError() {
                         return true;
                     }
-
+                    
                     public String toString() {
                         return getMessage();
                     }
                 };
 
-                if ( this.problemHandler != null ) {
-                    this.problemHandler.handle( problem );
+                if (problemHandler != null) {
+                    problemHandler.handle(problem);
                 }
-
-                problems.add( problem );
+                
+                problems.add(problem);
             }
         }
 
-        if ( problems.size() > 0 ) {
+        if (problems.size() > 0) {
             final CompilationProblem[] result = new CompilationProblem[problems.size()];
-            problems.toArray( result );
-            return new org.drools.commons.jci.compilers.CompilationResult( result );
+            problems.toArray(result);
+            return new org.drools.commons.jci.compilers.CompilationResult(result);
         }
-
+        
         final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
-        final IProblemFactory problemFactory = new DefaultProblemFactory( Locale.getDefault() );
+        final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
         final INameEnvironment nameEnvironment = new INameEnvironment() {
 
-            public NameEnvironmentAnswer findType(final char[][] pCompoundTypeName) {
+            public NameEnvironmentAnswer findType( final char[][] pCompoundTypeName ) {
                 final StringBuffer result = new StringBuffer();
-                for ( int i = 0; i < pCompoundTypeName.length; i++ ) {
-                    if ( i != 0 ) {
-                        result.append( '.' );
+                for (int i = 0; i < pCompoundTypeName.length; i++) {
+                    if (i != 0) {
+                        result.append('.');
                     }
-                    result.append( pCompoundTypeName[i] );
+                    result.append(pCompoundTypeName[i]);
                 }
 
                 //log.debug("finding compoundTypeName=" + result.toString());
 
-                return findType( result.toString() );
+                return findType(result.toString());
             }
 
-            public NameEnvironmentAnswer findType(final char[] pTypeName,
-                                                  final char[][] pPackageName) {
+            public NameEnvironmentAnswer findType( final char[] pTypeName, final char[][] pPackageName ) {
                 final StringBuffer result = new StringBuffer();
-                for ( int i = 0; i < pPackageName.length; i++ ) {
-                    result.append( pPackageName[i] );
-                    result.append( '.' );
+                for (int i = 0; i < pPackageName.length; i++) {
+                    result.append(pPackageName[i]);
+                    result.append('.');
                 }
+                
+//                log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());
 
-                //                log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());
-
-                result.append( pTypeName );
-                return findType( result.toString() );
+                result.append(pTypeName);
+                return findType(result.toString());
             }
 
-            private NameEnvironmentAnswer findType(final String pClazzName) {
-
-                if ( isPackage( pClazzName ) ) {
+            private NameEnvironmentAnswer findType( final String pClazzName ) {
+                
+                if (isPackage(pClazzName)) {
                     return null;
-                }
-
-                final String resourceName = ClassUtils.convertClassToResourcePath( pClazzName );
-
-                final byte[] clazzBytes = pStore.read( pClazzName );
-                if ( clazzBytes != null ) {
-
+                }                
+                
+                final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);
+                
+                final byte[] clazzBytes = pStore.read(pClazzName);
+                if (clazzBytes != null) {
                     final char[] fileName = pClazzName.toCharArray();
                     try {
-                        final ClassFileReader classFileReader = new ClassFileReader( clazzBytes,
-                                                                                     fileName,
-                                                                                     true );
-                        return new NameEnvironmentAnswer( classFileReader,
-                                                          null );
-                    } catch ( final ClassFormatException e ) {
+                        final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
+                        return new NameEnvironmentAnswer(classFileReader, null);
+                    } catch (final ClassFormatException e) {
                         throw new RuntimeException( "ClassFormatException in loading class '" + fileName + "' with JCI." );
                     }
                 }
-
-                final InputStream is = pClassLoader.getResourceAsStream( resourceName );
-                if ( is == null ) {
+                
+                
+                final InputStream is = pClassLoader.getResourceAsStream(resourceName);
+                if (is == null) {
                     return null;
                 }
 
                 final byte[] buffer = new byte[8192];
-                final ByteArrayOutputStream baos = new ByteArrayOutputStream( buffer.length );
+                final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length);
                 int count;
                 try {
-                    while ( (count = is.read( buffer,
-                                              0,
-                                              buffer.length )) > 0 ) {
-                        baos.write( buffer,
-                                    0,
-                                    count );
+                    while ((count = is.read(buffer, 0, buffer.length)) > 0) {
+                        baos.write(buffer, 0, count);
                     }
                     baos.flush();
                     final char[] fileName = pClazzName.toCharArray();
-                    final ClassFileReader classFileReader = new ClassFileReader( baos.toByteArray(),
-                                                                                 fileName,
-                                                                                 true );
-                    return new NameEnvironmentAnswer( classFileReader,
-                                                      null );
+                    final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true);
+                    return new NameEnvironmentAnswer(classFileReader, null);
                 } catch ( final IOException e ) {
                     throw new RuntimeException( "could not read class",
                                                 e );
@@ -287,42 +275,40 @@
                 }
             }
 
-            private boolean isPackage(final String pClazzName) {
-
-                final InputStream is = pClassLoader.getResourceAsStream( ClassUtils.convertClassToResourcePath( pClazzName ) );
-                if ( is != null ) {
+            private boolean isPackage( final String pClazzName ) {
+                
+                final InputStream is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));
+                if (is != null) {
                     return false;
                 }
-
+                
                 // FIXME: this should not be tied to the extension
-                final String source = pClazzName.replace( '.',
-                                                          '/' ) + ".java";
-                if ( pReader.isAvailable( source ) ) {
+                final String source = pClazzName.replace('.', '/') + ".java";
+                if (pReader.isAvailable(source)) {
                     return false;
                 }
-
+                
                 return true;
             }
 
-            public boolean isPackage(char[][] parentPackageName,
-                                     char[] pPackageName) {
+            public boolean isPackage( char[][] parentPackageName, char[] pPackageName ) {
                 final StringBuffer result = new StringBuffer();
-                if ( parentPackageName != null ) {
-                    for ( int i = 0; i < parentPackageName.length; i++ ) {
-                        if ( i != 0 ) {
-                            result.append( '.' );
+                if (parentPackageName != null) {
+                    for (int i = 0; i < parentPackageName.length; i++) {
+                        if (i != 0) {
+                            result.append('.');
                         }
-                        result.append( parentPackageName[i] );
+                        result.append(parentPackageName[i]);
                     }
                 }
-
-                //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));
-
-                if ( parentPackageName != null && parentPackageName.length > 0 ) {
-                    result.append( '.' );
+                
+//                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));
+                
+                if (parentPackageName != null && parentPackageName.length > 0) {
+                    result.append('.');
                 }
-                result.append( pPackageName );
-                return isPackage( result.toString() );
+                result.append(pPackageName);
+                return isPackage(result.toString());
             }
 
             public void cleanup() {
@@ -330,50 +316,43 @@
         };
 
         final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
-            public void acceptResult(final CompilationResult pResult) {
-                if ( pResult.hasProblems() ) {
+            public void acceptResult( final CompilationResult pResult ) {
+                if (pResult.hasProblems()) {
                     final IProblem[] iproblems = pResult.getProblems();
-                    for ( int i = 0; i < iproblems.length; i++ ) {
+                    for (int i = 0; i < iproblems.length; i++) {
                         final IProblem iproblem = iproblems[i];
-                        final CompilationProblem problem = new EclipseCompilationProblem( iproblem );
-                        if ( EclipseJavaCompiler.this.problemHandler != null ) {
-                            EclipseJavaCompiler.this.problemHandler.handle( problem );
+                        final CompilationProblem problem = new EclipseCompilationProblem(iproblem); 
+                        if (problemHandler != null) {
+                            problemHandler.handle(problem);
                         }
-                        problems.add( problem );
+                        problems.add(problem);
                     }
                 }
-                if ( !pResult.hasErrors() ) {
+                if (!pResult.hasErrors()) {
                     final ClassFile[] clazzFiles = pResult.getClassFiles();
-                    for ( int i = 0; i < clazzFiles.length; i++ ) {
+                    for (int i = 0; i < clazzFiles.length; i++) {
                         final ClassFile clazzFile = clazzFiles[i];
                         final char[][] compoundName = clazzFile.getCompoundName();
                         final StringBuffer clazzName = new StringBuffer();
-                        for ( int j = 0; j < compoundName.length; j++ ) {
-                            if ( j != 0 ) {
-                                clazzName.append( '.' );
+                        for (int j = 0; j < compoundName.length; j++) {
+                            if (j != 0) {
+                                clazzName.append('.');
                             }
-                            clazzName.append( compoundName[j] );
+                            clazzName.append(compoundName[j]);
                         }
-                        pStore.write( clazzName.toString().replace( '.',
-                                                                    '/' ) + ".class",
-                                      clazzFile.getBytes() );
+                        pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
                     }
                 }
             }
         };
 
-        final Compiler compiler = new Compiler( nameEnvironment,
-                                                policy,
-                                                settingsMap,
-                                                compilerRequestor,
-                                                problemFactory,
-                                                false );
+        final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory, false);
 
-        compiler.compile( compilationUnits );
+        compiler.compile(compilationUnits);
 
         final CompilationProblem[] result = new CompilationProblem[problems.size()];
-        problems.toArray( result );
-        return new org.drools.commons.jci.compilers.CompilationResult( result );
+        problems.toArray(result);
+        return new org.drools.commons.jci.compilers.CompilationResult(result);
     }
 
     public JavaCompilerSettings createDefaultSettings() {

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompilerSettings.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompilerSettings.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompilerSettings.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -32,36 +32,58 @@
     final private Map defaultEclipseSettings = new HashMap();
 
     public EclipseJavaCompilerSettings() {
-        defaultEclipseSettings.put( CompilerOptions.OPTION_LineNumberAttribute,
-                                    CompilerOptions.GENERATE );
-        defaultEclipseSettings.put( CompilerOptions.OPTION_SourceFileAttribute,
-                                    CompilerOptions.GENERATE );
-        defaultEclipseSettings.put( CompilerOptions.OPTION_ReportUnusedImport,
-                                    CompilerOptions.IGNORE );
-        defaultEclipseSettings.put( CompilerOptions.OPTION_LocalVariableAttribute,
-                                    CompilerOptions.GENERATE );
+        defaultEclipseSettings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
+        defaultEclipseSettings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
+        defaultEclipseSettings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
+        defaultEclipseSettings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
     }
+    
+    public EclipseJavaCompilerSettings( final JavaCompilerSettings pSettings ) {
+    	super(pSettings);
+    	
+    	if (pSettings instanceof EclipseJavaCompilerSettings) {
+    		defaultEclipseSettings.putAll(((EclipseJavaCompilerSettings)pSettings).toNativeSettings());
+    	}
+    }
+    
+    public EclipseJavaCompilerSettings( final Map pMap ) {
+        defaultEclipseSettings.putAll(pMap);
+    }
 
-    public EclipseJavaCompilerSettings(final Map pMap) {
-        defaultEclipseSettings.putAll( pMap );
+    private static Map nativeVersions = new HashMap() {
+		private static final long serialVersionUID = 1L;
+	{
+    	put("1.1", CompilerOptions.VERSION_1_1);
+    	put("1.2", CompilerOptions.VERSION_1_2);
+    	put("1.3", CompilerOptions.VERSION_1_3);
+    	put("1.4", CompilerOptions.VERSION_1_4);
+    	put("1.5", CompilerOptions.VERSION_1_5);
+    	put("1.6", CompilerOptions.VERSION_1_6);
+    }};
+    
+    private String toNativeVersion( final String pVersion ) {
+    	final String nativeVersion = (String) nativeVersions.get(pVersion);
+    	
+    	if (nativeVersion == null) {
+    		throw new RuntimeException("unknown version " + pVersion);
+    	}
+    	
+    	return nativeVersion;
     }
+    
+    Map toNativeSettings() {
+        final Map map = new HashMap(defaultEclipseSettings);
 
-    public Map getMap() {
-        final Map map = new HashMap( defaultEclipseSettings );
+        map.put(CompilerOptions.OPTION_SuppressWarnings, isWarnings()?CompilerOptions.GENERATE:CompilerOptions.DO_NOT_GENERATE);
+        map.put(CompilerOptions.OPTION_ReportDeprecation, isDeprecations()?CompilerOptions.GENERATE:CompilerOptions.DO_NOT_GENERATE);
+        map.put(CompilerOptions.OPTION_TargetPlatform, toNativeVersion(getTargetVersion()));
+        map.put(CompilerOptions.OPTION_Source, toNativeVersion(getSourceVersion()));
+        map.put(CompilerOptions.OPTION_Encoding, getSourceEncoding());
 
-        map.put( CompilerOptions.OPTION_ReportDeprecation,
-                 CompilerOptions.GENERATE ); // Not sure what we put here from JavaCompilerSettings
-        map.put( CompilerOptions.OPTION_TargetPlatform,
-                 (getTargetVersion() != null) ? getTargetVersion() : CompilerOptions.VERSION_1_4 );
-        map.put( CompilerOptions.OPTION_Source,
-                 (getSourceVersion() != null) ? getSourceVersion() : CompilerOptions.VERSION_1_4 );
-        map.put( CompilerOptions.OPTION_Encoding,
-                 (getSourceEncoding() != null) ? getSourceEncoding() : "UTF-8" );
-
         return map;
     }
-
+    
     public String toString() {
-        return defaultEclipseSettings.toString();
+        return toNativeSettings().toString();
     }
 }

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompiler.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompiler.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompiler.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -17,155 +17,178 @@
 
 package org.drools.commons.jci.compilers;
 
-import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
+import java.io.InputStream;
+import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
 
 import org.codehaus.janino.ClassLoaderIClassLoader;
 import org.codehaus.janino.CompileException;
+import org.codehaus.janino.Compiler;
 import org.codehaus.janino.DebuggingInformation;
-import org.codehaus.janino.Descriptor;
-import org.codehaus.janino.IClass;
-import org.codehaus.janino.IClassLoader;
-import org.codehaus.janino.Java;
+import org.codehaus.janino.FilterWarningHandler;
 import org.codehaus.janino.Location;
-import org.codehaus.janino.Parser;
-import org.codehaus.janino.Scanner;
-import org.codehaus.janino.UnitCompiler;
 import org.codehaus.janino.WarningHandler;
-import org.codehaus.janino.Scanner.LocatedException;
+import org.codehaus.janino.Parser.ParseException;
+import org.codehaus.janino.Scanner.ScanException;
 import org.codehaus.janino.UnitCompiler.ErrorHandler;
-import org.codehaus.janino.util.ClassFile;
+import org.codehaus.janino.util.StringPattern;
+import org.codehaus.janino.util.resource.Resource;
+import org.codehaus.janino.util.resource.ResourceCreator;
+import org.codehaus.janino.util.resource.ResourceFinder;
 import org.drools.commons.jci.problems.CompilationProblem;
 import org.drools.commons.jci.readers.ResourceReader;
 import org.drools.commons.jci.stores.ResourceStore;
-import org.drools.util.ClassUtils;
 
 /**
- * @author art at gramlich-net.com
+ * @author tcurdt
  */
 public final class JaninoJavaCompiler extends AbstractJavaCompiler {
 
-    private class CompilingIClassLoader extends IClassLoader {
+    private final JaninoJavaCompilerSettings defaultSettings;
 
-        private final Map types = new HashMap();
-        private final ResourceReader resourceReader;
-        private final Map classes;
-        private final Collection problems = new ArrayList();
+    public JaninoJavaCompiler() {
+    	this(new JaninoJavaCompilerSettings());
+    }
+    
+    public JaninoJavaCompiler( final JaninoJavaCompilerSettings pSettings ) {
+    	defaultSettings = pSettings;
+    }
+    
+    private final static class JciResource implements Resource {
 
-        private CompilingIClassLoader(final ResourceReader pResourceReader, final Map pClasses, final ClassLoader classLoader) {
-            super( new ClassLoaderIClassLoader( classLoader ) );
-            resourceReader = pResourceReader;
-            classes = pClasses;
-            super.postConstruct();
-        }
+    	private final String name;
+    	private final byte[] bytes;
+    	
+    	public JciResource( final String pName, final byte[] pBytes ) {
+    		name = pName;
+    		bytes = pBytes;
+    	}
+    	
+		public String getFileName() {
+			return name;
+		}
 
-        protected Collection getProblems() {
-            return problems;
-        }
-        
-        protected IClass findIClass(final String pType) {
-            final String className = Descriptor.toClassName(pType);
-            if (types.containsKey(pType)) {
-                return (IClass) types.get(pType);
-            }
-            
-            // FIXME: should not be tied to the extension            
-            final String resourceNameFromClass = className.replace('.', '/') + ".java";
+		public long lastModified() {
+			return 0;
+		}
 
-            final byte[] content = resourceReader.getBytes(resourceNameFromClass);
-            if (content == null) {
-                return null;
-            }
-            final Reader reader = new BufferedReader(new StringReader(new String(content)));
-            Scanner scanner = null;
-            try {
-                scanner = new Scanner(resourceNameFromClass, reader);
-                final Java.CompilationUnit unit = new Parser(scanner).parseCompilationUnit();
-                final UnitCompiler uc = new UnitCompiler(unit, this);
-                uc.setCompileErrorHandler(new ErrorHandler() {
-                    public void handleError(final String pMessage, final Location pOptionalLocation) throws CompileException {
-                        final CompilationProblem problem = new JaninoCompilationProblem(pOptionalLocation, pMessage, true);
-                        if (problemHandler != null) {
-                            problemHandler.handle(problem);
-                        }
-                        problems.add(problem);
-                    }
-                });
-                uc.setWarningHandler(new WarningHandler() {
-                    public void handleWarning(final String pHandle, final String pMessage, final Location pOptionalLocation) {
-                        final CompilationProblem problem = new JaninoCompilationProblem(pOptionalLocation, pMessage, false);
-                        if (problemHandler != null) {
-                            problemHandler.handle(problem);
-                        }
-                        problems.add(problem);
-                    }
-                });
-                
-                final ClassFile[] classFiles = uc.compileUnit(DebuggingInformation.ALL);
-                for (int i = 0; i < classFiles.length; i++) {
-                    classes.put(classFiles[i].getThisClassName(), classFiles[i].toByteArray());
-                }
-                final IClass ic = uc.findClass(className);
-                if (null != ic) {
-                    types.put(pType, ic);
-                }
-                return ic;
-            } catch (final LocatedException e) {
-                problems.add(new JaninoCompilationProblem(e));
-            } catch (final IOException e) {
-                problems.add(new JaninoCompilationProblem(resourceNameFromClass, "IOException:" + e.getMessage(), true));
-            } catch (final Exception e) {
-                problems.add(new JaninoCompilationProblem(resourceNameFromClass, "Exception:" + e.getMessage(), true));
-            } finally {
-                if (scanner != null) {
-                    try {
-                        scanner.close();
-                    } catch (IOException e) {
-                    	throw new RuntimeException( "IOException occured while compiling " + className, e );
-                    }
-                }
-            }
-            return null;
-        }
+		public InputStream open() throws IOException {
+			return new ByteArrayInputStream(bytes);
+		}
     }
 
+    private final class JciOutputStream extends ByteArrayOutputStream {
+
+    	private final String name;
+    	private final ResourceStore store;
+
+    	public JciOutputStream( final String pName, final ResourceStore pStore ) {
+    		name = pName;
+    		store = pStore;
+    	}
+
+		public void close() throws IOException {
+			super.close();
+
+			final byte[] bytes = toByteArray();		
+
+			store.write(name, bytes);
+		}
+    }
+    
     public CompilationResult compile( final String[] pSourceNames, final ResourceReader pResourceReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings ) {
 
-        final Map classFilesByName = new HashMap();       
-        
-        final CompilingIClassLoader icl = new CompilingIClassLoader(pResourceReader, classFilesByName, pClassLoader);
+    	final Collection problems = new ArrayList();
+    	
+    	final StringPattern[] pattern = StringPattern.PATTERNS_NONE;
+
+    	final Compiler compiler = new Compiler(
+    			new ResourceFinder() {
+					public Resource findResource( final String pSourceName ) {
+						final byte[] bytes = pResourceReader.getBytes(pSourceName);
+						
+						if (bytes == null) {
+							return null;
+						}						
+						
+						return new JciResource(pSourceName, bytes);
+					}    		
+    			},
+    			new ClassLoaderIClassLoader(pClassLoader),
+    			new ResourceFinder() {
+					public Resource findResource( final String pResourceName ) {
+						final byte[] bytes = pStore.read(pResourceName);
+						
+						if (bytes == null) {
+							return null;
+						}
+						
+						return new JciResource(pResourceName, bytes);
+					}    		
+    			},
+    			new ResourceCreator() {
+					public OutputStream createResource( final String pResourceName ) throws IOException {
+						return new JciOutputStream(pResourceName, pStore);
+					}
+
+					public boolean deleteResource( final String pResourceName ) {
+						pStore.remove(pResourceName);
+						return true;
+					}    				
+    			},
+    			pSettings.getSourceEncoding(),
+    			false,
+    			pSettings.isDebug()?DebuggingInformation.ALL:DebuggingInformation.NONE,
+    			new FilterWarningHandler(pattern, new WarningHandler() {
+						public void handleWarning( final String pHandle, final String pMessage, final Location pLocation ) {
+							final CompilationProblem problem = new JaninoCompilationProblem(pLocation.getFileName(), pLocation, pMessage, false);
+							if (problemHandler != null) {
+								problemHandler.handle(problem);
+							}
+							problems.add(problem);
+						}    		
+			    	})    			
+    			);            	
+    	
+    	compiler.setCompileErrorHandler(new ErrorHandler() {
+			public void handleError( final String pMessage, final Location pLocation ) throws CompileException {
+				final CompilationProblem problem = new JaninoCompilationProblem(pLocation.getFileName(), pLocation, pMessage, true);
+				if (problemHandler != null) {
+					problemHandler.handle(problem);
+				}
+				problems.add(problem);
+			}
+    	});
+    	
+
+    	final Resource[] resources = new Resource[pSourceNames.length];
         for (int i = 0; i < pSourceNames.length; i++) {
-        	try {
-        		icl.loadIClass(Descriptor.fromClassName(ClassUtils.convertResourceToClassName(pSourceNames[i])));
-            } catch ( final ClassNotFoundException e ) {
-                // @TODO: if an exception is thrown here, how do we handle it?
-                e.printStackTrace();
-            }        		
+            final byte[] source = pResourceReader.getBytes(pSourceNames[i]);
+            resources[i] = new JciResource(pSourceNames[i], source);
         }
-        
-        // Store all fully compiled classes
-        for (Iterator i = classFilesByName.entrySet().iterator(); i.hasNext();) {
-            final Map.Entry entry = (Map.Entry)i.next();
-            final String clazzName = (String)entry.getKey(); 
-            pStore.write(ClassUtils.convertClassToResourcePath(clazzName), (byte[])entry.getValue());
+        try {
+            compiler.compile(resources);
+        } catch ( ScanException e ) {
+            problems.add(new JaninoCompilationProblem(e));
+        } catch ( ParseException e ) {
+            problems.add(new JaninoCompilationProblem(e));
+        } catch ( IOException e ) {
+            // I'm hoping the existing compiler problems handler catches these            
+        } catch ( CompileException e ) {
+            // I'm hoping the existing compiler problems handler catches these
         }
         
-        final Collection problems = icl.getProblems();
         final CompilationProblem[] result = new CompilationProblem[problems.size()];
         problems.toArray(result);
         return new CompilationResult(result);
     }
 
     public JavaCompilerSettings createDefaultSettings() {
-        // FIXME
-        return null;
+        return this.defaultSettings;
     }
     
 }

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompilerSettings.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompilerSettings.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JaninoJavaCompilerSettings.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -19,4 +19,13 @@
 
 public final class JaninoJavaCompilerSettings extends JavaCompilerSettings {
     // TODO: implement the native janino compiler settings
+
+	public JaninoJavaCompilerSettings() {
+		
+	}
+
+	public JaninoJavaCompilerSettings( final JaninoJavaCompilerSettings pSettings ) {
+		super(pSettings);		
+	}
+
 }

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JavaCompilerSettings.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JavaCompilerSettings.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/compilers/JavaCompilerSettings.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -18,6 +18,7 @@
 package org.drools.commons.jci.compilers;
 
 
+
 /**
  * Most common denominator for JavaCompiler settings.
  * 
@@ -29,14 +30,28 @@
  */
 public class JavaCompilerSettings {
 
-    private String targetVersion;
-    private String sourceVersion;
-    private String sourceEncoding;
-    private boolean warnings;
-    private boolean deprecations;
-    private boolean verbose;
+    private String targetVersion = "1.4";
+    private String sourceVersion = "1.4";
+    private String sourceEncoding = "UTF-8";
+    private boolean warnings = false;
+    private boolean deprecations = false;
+    private boolean debug = false;
 
+    /** @deprecated */
+    private boolean verbose = false;
 
+    public JavaCompilerSettings() {    	
+    }
+    
+    public JavaCompilerSettings( final JavaCompilerSettings pSettings ) {
+    	targetVersion = pSettings.targetVersion;
+    	sourceVersion = pSettings.sourceVersion;
+    	sourceEncoding = pSettings.sourceEncoding;
+    	warnings = pSettings.warnings;
+    	deprecations = pSettings.deprecations;
+    	debug = pSettings.debug;
+    }
+    
     public void setTargetVersion( final String pTargetVersion ) {
         targetVersion = pTargetVersion;
     }
@@ -81,11 +96,20 @@
         return deprecations;
     }
 
+    public void setDebug( final boolean pDebug )  {
+        debug = pDebug;
+    }
 
+    public boolean isDebug() {
+        return debug;
+    }
+
+    /** @deprecated */
     public void setVerbose( final boolean pVerbose ) {
         verbose = pVerbose;
     }
 
+    /** @deprecated */
     public boolean isVerbose() {
         return verbose;
     }

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/readers/MemoryResourceReader.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/readers/MemoryResourceReader.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/readers/MemoryResourceReader.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -17,8 +17,8 @@
 
 package org.drools.commons.jci.readers;
 
+import java.util.Map;
 import java.util.HashMap;
-import java.util.Map;
 
 /**
  * A memory based reader to compile from memory
@@ -27,7 +27,7 @@
  */
 public class MemoryResourceReader implements ResourceReader {
     
-    private Map resources;
+    private Map resources = null;
 
     public boolean isAvailable( final String pResourceName ) {
         if (resources == null) {

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/stores/ResourceStore.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/stores/ResourceStore.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/commons/jci/stores/ResourceStore.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -25,5 +25,6 @@
 
     void write( final String pResourceName, final byte[] pResourceData );
     byte[] read( final String pResourceName );
+    //FIXME: return the result of the remove
     void remove( final String pResourceName );
 }

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -429,6 +429,7 @@
     public void addFunction(final FunctionDescr functionDescr,
                             final TypeResolver typeResolver) {
 
+        //System.out.println( functionDescr + " : " + typeResolver );
         final String functionClassName = this.pkg.getName() + "." + StringUtils.ucFirst( functionDescr.getName() );
         this.pkg.addFunction( functionDescr.getName() );
 

Modified: labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java	2007-09-22 03:03:36 UTC (rev 15281)
@@ -3306,8 +3306,12 @@
 
     }
 
-    public void testFunctionCallingFunction() throws Exception {
-        final PackageBuilder builder = new PackageBuilder();
+    public void testFunctionCallingFunctionWithEclipse() throws Exception {
+        PackageBuilderConfiguration packageBuilderConfig = new PackageBuilderConfiguration();
+        ((JavaDialectConfiguration) packageBuilderConfig.getDialectConfiguration( "java" )).setCompiler( JavaDialectConfiguration.ECLIPSE );
+        
+        final PackageBuilder builder = new PackageBuilder( packageBuilderConfig );
+        
         builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_functionCallingFunction.drl" ) ) );
         final Package pkg = builder.getPackage();
 
@@ -3323,8 +3327,34 @@
 
         assertEquals( 1,
                       list.size() );
+        
+        assertEquals( 10, ( (Integer)list.get( 0 ) ).intValue() );        
     }
+    
+    public void testFunctionCallingFunctionWithJanino() throws Exception {
+        PackageBuilderConfiguration packageBuilderConfig = new PackageBuilderConfiguration();
+        ((JavaDialectConfiguration) packageBuilderConfig.getDialectConfiguration( "java" )).setCompiler( JavaDialectConfiguration.JANINO );
+        
+        final PackageBuilder builder = new PackageBuilder( packageBuilderConfig );
+        builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_functionCallingFunction.drl" ) ) );
+        final Package pkg = builder.getPackage();
 
+        final RuleBase ruleBase = getRuleBase();
+        ruleBase.addPackage( pkg );
+        final WorkingMemory workingMemory = ruleBase.newStatefulSession();
+
+        final List list = new ArrayList();
+        workingMemory.setGlobal( "results",
+                                 list );
+
+        workingMemory.fireAllRules();
+
+        assertEquals( 1,
+                      list.size() );
+        
+        assertEquals( 10, ( (Integer)list.get( 0 ) ).intValue() );
+    }    
+
     public void testSelfReference2() throws Exception {
         final PackageBuilder builder = new PackageBuilder();
         builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_SelfReference2.drl" ) ) );

Modified: labs/jbossrules/trunk/drools-compiler/src/test/resources/org/drools/integrationtests/test_functionCallingFunction.drl
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/resources/org/drools/integrationtests/test_functionCallingFunction.drl	2007-09-22 02:49:15 UTC (rev 15280)
+++ labs/jbossrules/trunk/drools-compiler/src/test/resources/org/drools/integrationtests/test_functionCallingFunction.drl	2007-09-22 03:03:36 UTC (rev 15281)
@@ -2,17 +2,49 @@
 
 global java.util.List results;
 
-function boolean f1() {
-    return f2();
+function int f1(int i) {
+    return f2(i+1);
 }
 
-function boolean f2() {
-    return true;
+function int f2(int i) {
+    return f3(i+1);
 }
 
+function int f3(int i) {
+    return f4(i+1);
+}
+
+function int f4(int i) {
+    return f5(i+1);
+}
+
+function int f5(int i) {
+    return f6(i+1);
+}
+
+function int f6(int i) {
+    return f7(i+1);
+}
+
+function int f7(int i) {
+    return f8(i+1);
+}
+
+function int f8(int i) {
+    return f9(i+1);
+}
+
+function int f9(int i) {
+    return f10(i+1);
+}
+
+function int f10(int i) {
+    return i+1;
+}
+
 rule "X"
 when
-    eval( f1() )
+    eval( f1(0) == 10 )
 then
-    results.add( "OK" );
+    results.add( new Integer( f1(0) ) );
 end
\ No newline at end of file




More information about the jboss-svn-commits mailing list