Search in sources :

Example 1 with CompilationResult

use of org.kie.memorycompiler.CompilationResult in project drools by kiegroup.

the class CompilerBytecodeLoader method compileUnit.

public <T> T compileUnit(String cuPackage, String cuClass, CompilationUnit cu) {
    try {
        MemoryResourceReader pReader = new MemoryResourceReader();
        pReader.add(cuPackage.replaceAll("\\.", "/") + "/" + cuClass + ".java", cu.toString().getBytes());
        JavaCompiler compiler = createNativeCompiler();
        MemoryFileSystem pStore = new MemoryFileSystem();
        CompilationResult compilationResult = compiler.compile(new String[] { cuPackage.replaceAll("\\.", "/") + "/" + cuClass + ".java" }, pReader, pStore, this.getClass().getClassLoader());
        LOG.debug("{}", Arrays.asList(compilationResult.getErrors()));
        LOG.debug("{}", Arrays.asList(compilationResult.getWarnings()));
        String fqnClassName = cuPackage + "." + cuClass;
        Class<T> loaded = (Class<T>) new TemplateLoader(this.getClass().getClassLoader()).load(pStore, fqnClassName);
        return loaded.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : MemoryFileSystem(org.drools.compiler.compiler.io.memory.MemoryFileSystem) MemoryResourceReader(org.kie.memorycompiler.resources.MemoryResourceReader) JavaCompiler(org.kie.memorycompiler.JavaCompiler) CompilationResult(org.kie.memorycompiler.CompilationResult)

Example 2 with CompilationResult

use of org.kie.memorycompiler.CompilationResult in project drools by kiegroup.

the class NativeJavaCompiler method compile.

@Override
public CompilationResult compile(String[] pResourcePaths, ResourceReader pReader, ResourceStore pStore, ClassLoader pClassLoader, JavaCompilerSettings pSettings) {
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler compiler = NativeJavaCompiler.getJavaCompiler();
    try (StandardJavaFileManager jFileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
        try {
            jFileManager.setLocation(StandardLocation.CLASS_PATH, pSettings.getClasspathLocations());
            jFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(new File("target/classes")));
        } catch (IOException e) {
        // ignore if cannot set the classpath
        }
        try (MemoryFileManager fileManager = new MemoryFileManager(jFileManager, pClassLoader)) {
            final List<JavaFileObject> units = new ArrayList<JavaFileObject>();
            for (final String sourcePath : pResourcePaths) {
                units.add(new CompilationUnit(KiePath.of(sourcePath), pReader));
            }
            Iterable<String> options = new NativeJavaCompilerSettings(pSettings).toOptionsList();
            if (compiler.getTask(null, fileManager, diagnostics, options, null, units).call()) {
                for (CompilationOutput compilationOutput : fileManager.getOutputs()) {
                    pStore.write(compilationOutput.getBinaryName().replace('.', '/') + ".class", compilationOutput.toByteArray());
                }
                return new CompilationResult(new CompilationProblem[0]);
            }
        }
        List<Diagnostic<? extends JavaFileObject>> problems = diagnostics.getDiagnostics();
        CompilationProblem[] result = new CompilationProblem[problems.size()];
        for (int i = 0; i < problems.size(); i++) {
            result[i] = new NativeCompilationProblem((Diagnostic<JavaFileObject>) problems.get(i));
        }
        return new CompilationResult(result);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) AbstractJavaCompiler(org.kie.memorycompiler.AbstractJavaCompiler) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) IOException(java.io.IOException) CompilationProblem(org.kie.memorycompiler.CompilationProblem) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) CompilationResult(org.kie.memorycompiler.CompilationResult) File(java.io.File)

Example 3 with CompilationResult

use of org.kie.memorycompiler.CompilationResult in project drools by kiegroup.

the class CanonicalModelKieProject method writeProjectOutput.

@Override
public void writeProjectOutput(MemoryFileSystem trgMfs, BuildContext buildContext) {
    MemoryFileSystem srcMfs = new MemoryFileSystem();
    ModelWriter modelWriter = new ModelWriter();
    Collection<String> modelFiles = new HashSet<>();
    Collection<String> sourceFiles = new HashSet<>();
    Map<String, List<String>> modelsByKBase = new HashMap<>();
    for (Map.Entry<String, ModelBuilderImpl> modelBuilder : modelBuilders.entrySet()) {
        ModelWriter.Result result = modelWriter.writeModel(srcMfs, modelBuilder.getValue().getPackageSources());
        modelFiles.addAll(result.getModelFiles());
        sourceFiles.addAll(result.getSourceFiles());
        List<String> modelFilesForKieBase = new ArrayList<>();
        modelFilesForKieBase.addAll(result.getModelFiles());
        modelFilesForKieBase.addAll(((CanonicalModelBuildContext) buildContext).getNotOwnedModelFiles(modelBuilders, modelBuilder.getKey()));
        modelsByKBase.put(modelBuilder.getKey(), modelFilesForKieBase);
    }
    InternalKieModule kieModule = getInternalKieModule();
    ModelSourceClass modelSourceClass = new ModelSourceClass(kieModule.getReleaseId(), kieModule.getKieModuleModel().getKieBaseModels(), modelsByKBase, hasDynamicClassLoader());
    String projectSourcePath = modelWriter.getBasePath().asString() + "/" + modelSourceClass.getName();
    srcMfs.write(projectSourcePath, modelSourceClass.generate().getBytes());
    sourceFiles.add(projectSourcePath);
    Set<KiePath> origFileNames = new HashSet<>(trgMfs.getFilePaths());
    String[] sources = sourceFiles.toArray(new String[sourceFiles.size()]);
    if (sources.length != 0) {
        CompilationResult res = getCompiler().compile(sources, srcMfs, trgMfs, getClassLoader());
        Stream.of(res.getErrors()).collect(groupingBy(CompilationProblem::getFileName)).forEach((name, errors) -> {
            errors.forEach(m -> buildContext.getMessages().addMessage(new CompilationProblemAdapter(m)));
            File srcFile = srcMfs.getFile(name);
            if (srcFile instanceof MemoryFile) {
                String src = new String(srcMfs.getFileContents((MemoryFile) srcFile));
                buildContext.getMessages().addMessage(Message.Level.ERROR, name, "Java source of " + name + " in error:\n" + src);
            }
        });
        for (CompilationProblem problem : res.getWarnings()) {
            buildContext.getMessages().addMessage(new CompilationProblemAdapter(problem));
        }
    }
    if (ProjectClassLoader.isEnableStoreFirst()) {
        Set<KiePath> generatedClassPaths = new HashSet<>(trgMfs.getFilePaths());
        generatedClassPaths.removeAll(origFileNames);
        Set<String> generatedClassNames = generatedClassPaths.stream().map(KiePath::asString).map(ClassUtils::convertResourceToClassName).collect(Collectors.toSet());
        modelWriter.writeGeneratedClassNamesFile(generatedClassNames, trgMfs, getInternalKieModule().getReleaseId());
    }
    modelWriter.writeModelFile(modelFiles, trgMfs, getInternalKieModule().getReleaseId());
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CompilationProblem(org.kie.memorycompiler.CompilationProblem) MemoryFileSystem(org.drools.compiler.compiler.io.memory.MemoryFileSystem) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) MemoryFile(org.drools.compiler.compiler.io.memory.MemoryFile) KiePath(org.kie.memorycompiler.resources.KiePath) CompilationResult(org.kie.memorycompiler.CompilationResult) HashMap(java.util.HashMap) Map(java.util.Map) MemoryFile(org.drools.compiler.compiler.io.memory.MemoryFile) File(org.drools.compiler.compiler.io.File) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule) CompilationProblemAdapter(org.drools.compiler.kie.builder.impl.CompilationProblemAdapter)

Example 4 with CompilationResult

use of org.kie.memorycompiler.CompilationResult in project drools by kiegroup.

the class JavaDialect method compileAll.

/**
 * This actually triggers the compiling of all the resources.
 * Errors are mapped back to the element that originally generated the semantic
 * code.
 */
public void compileAll() {
    if (this.generatedClassList.isEmpty()) {
        this.errorHandlers.clear();
        return;
    }
    final String[] classes = new String[this.generatedClassList.size()];
    this.generatedClassList.toArray(classes);
    File dumpDir = this.configuration.getPackageBuilderConfiguration().getDumpDir();
    if (dumpDir != null) {
        dumpResources(classes, dumpDir);
    }
    final CompilationResult result = this.compiler.compile(classes, this.src, this.packageStoreWrapper, rootClassLoader);
    // this will sort out the errors based on what class/file they happened in
    if (result.getErrors().length > 0) {
        for (int i = 0; i < result.getErrors().length; i++) {
            final CompilationProblem err = new CompilationProblemAdapter(result.getErrors()[i]);
            final ErrorHandler handler = this.errorHandlers.get(err.getFileName());
            handler.addError(err);
        }
        final Collection errors = this.errorHandlers.values();
        for (Object error : errors) {
            final ErrorHandler handler = (ErrorHandler) error;
            if (handler.isInError()) {
                this.results.add(handler.getError());
            }
        }
    }
    // We've compiled everthing, so clear it for the next set of additions
    this.generatedClassList.clear();
    this.errorHandlers.clear();
}
Also used : RuleErrorHandler(org.drools.compiler.builder.impl.errors.RuleErrorHandler) SrcErrorHandler(org.drools.compiler.builder.impl.errors.SrcErrorHandler) FunctionErrorHandler(org.drools.compiler.builder.impl.errors.FunctionErrorHandler) ErrorHandler(org.drools.compiler.builder.impl.errors.ErrorHandler) RuleInvokerErrorHandler(org.drools.compiler.builder.impl.errors.RuleInvokerErrorHandler) Collection(java.util.Collection) CompilationResult(org.kie.memorycompiler.CompilationResult) CompilationProblem(org.kie.internal.jci.CompilationProblem) File(java.io.File) CompilationProblemAdapter(org.drools.compiler.kie.builder.impl.CompilationProblemAdapter)

Example 5 with CompilationResult

use of org.kie.memorycompiler.CompilationResult in project drools by kiegroup.

the class KieBuilderImpl method compileJavaClasses.

private void compileJavaClasses(JavaConfiguration javaConf, ClassLoader classLoader, List<String> javaFiles, String rootFolder) {
    if (!javaFiles.isEmpty()) {
        String[] sourceFiles = javaFiles.toArray(new String[javaFiles.size()]);
        JavaCompiler javaCompiler = createCompiler(javaConf, rootFolder);
        CompilationResult res = javaCompiler.compile(sourceFiles, srcMfs, trgMfs, classLoader);
        for (CompilationProblem problem : res.getErrors()) {
            results.addMessage(new CompilationProblemAdapter(problem));
        }
        for (CompilationProblem problem : res.getWarnings()) {
            results.addMessage(new CompilationProblemAdapter(problem));
        }
    }
}
Also used : JavaCompiler(org.kie.memorycompiler.JavaCompiler) CompilationResult(org.kie.memorycompiler.CompilationResult) CompilationProblem(org.kie.memorycompiler.CompilationProblem)

Aggregations

CompilationResult (org.kie.memorycompiler.CompilationResult)10 ArrayList (java.util.ArrayList)6 CompilationProblem (org.kie.memorycompiler.CompilationProblem)5 CompilationProblemAdapter (org.drools.compiler.kie.builder.impl.CompilationProblemAdapter)4 MemoryFileSystem (org.drools.compiler.compiler.io.memory.MemoryFileSystem)3 JavaCompiler (org.kie.memorycompiler.JavaCompiler)3 File (java.io.File)2 IOException (java.io.IOException)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ErrorHandler (org.drools.compiler.builder.impl.errors.ErrorHandler)2 SrcErrorHandler (org.drools.compiler.builder.impl.errors.SrcErrorHandler)2 CompilationProblem (org.kie.internal.jci.CompilationProblem)2 AbstractJavaCompiler (org.kie.memorycompiler.AbstractJavaCompiler)2 KiePath (org.kie.memorycompiler.resources.KiePath)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URLDecoder (java.net.URLDecoder)1