Search in sources :

Example 1 with MemoryResourceReader

use of org.kie.memorycompiler.resources.MemoryResourceReader 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 MemoryResourceReader

use of org.kie.memorycompiler.resources.MemoryResourceReader in project drools by kiegroup.

the class JavaCompilerI18NTest method testi18NFile.

@Test
public void testi18NFile() throws Exception {
    String fileStr = "com/myspace/test/あ.java";
    List<String> classes = new ArrayList<>();
    classes.add(fileStr);
    MemoryResourceReader reader = new MemoryResourceReader();
    MemoryResourceStore store = new MemoryResourceStore();
    String fileContents = "package com.myspace.test; public class あ { }";
    reader.add(fileStr, fileContents.getBytes());
    EclipseJavaCompilerSettings settings = new EclipseJavaCompilerSettings();
    settings.setSourceVersion("1.5");
    settings.setTargetVersion("1.5");
    EclipseJavaCompiler compiler = new EclipseJavaCompiler(settings, "");
    CompilationResult res = compiler.compile(classes.toArray(new String[classes.size()]), reader, store);
    assertEquals(res.getErrors().length, 0);
}
Also used : MemoryResourceStore(org.kie.memorycompiler.resources.MemoryResourceStore) MemoryResourceReader(org.kie.memorycompiler.resources.MemoryResourceReader) ArrayList(java.util.ArrayList) CompilationResult(org.kie.memorycompiler.CompilationResult) Test(org.junit.Test)

Example 3 with MemoryResourceReader

use of org.kie.memorycompiler.resources.MemoryResourceReader in project drools by kiegroup.

the class DroolsJaxbHelperProviderImpl method addXsdModel.

public static String[] addXsdModel(Resource resource, KnowledgeBuilderImpl kBuilder, Options xjcOpts, String systemId) throws IOException {
    InputSource source = new InputSource(new CachingRewindableReader(resource.getReader()));
    source.setSystemId(systemId.trim().startsWith(".") ? systemId : "." + systemId);
    xjcOpts.addGrammar(source);
    try {
        xjcOpts.parseArguments(new String[] { "-npa" });
    } catch (BadCommandLineException e) {
        throw new IllegalArgumentException("Unable to parse arguments", e);
    }
    ErrorReceiver errorReceiver = new JaxbErrorReceiver4Drools();
    Model model = ModelLoader.load(xjcOpts, new JCodeModel(), errorReceiver);
    model.generateCode(xjcOpts, errorReceiver);
    MapVfsCodeWriter codeWriter = new MapVfsCodeWriter();
    model.codeModel.build(xjcOpts.createCodeWriter(codeWriter));
    MemoryResourceReader src = new MemoryResourceReader();
    boolean useProjectClassLoader = kBuilder.getRootClassLoader() instanceof ProjectClassLoader;
    List<String> classNames = new ArrayList<String>();
    List<String> srcNames = new ArrayList<String>();
    for (Entry<String, byte[]> entry : codeWriter.getMap().entrySet()) {
        String name = entry.getKey();
        int dotPos = name.lastIndexOf('.');
        String pkgName = name.substring(0, dotPos);
        if (!name.endsWith("package-info.java")) {
            classNames.add(pkgName);
        }
        dotPos = pkgName.lastIndexOf('.');
        if (dotPos != -1) {
            pkgName = pkgName.substring(0, dotPos);
        }
        PackageRegistry pkgReg = kBuilder.getPackageRegistry(pkgName);
        if (pkgReg == null) {
            kBuilder.addPackage(new PackageDescr(pkgName));
            pkgReg = kBuilder.getPackageRegistry(pkgName);
        }
        if (useProjectClassLoader) {
            String srcName = convertToResource(entry.getKey());
            src.add(srcName, entry.getValue());
            srcNames.add(srcName);
        } else {
            Dialect dialect = pkgReg.getDialectCompiletimeRegistry().getDialect("java");
            dialect.addSrc(convertToResource(entry.getKey()), entry.getValue());
        }
    }
    if (useProjectClassLoader) {
        ProjectJavaCompiler compiler = new ProjectJavaCompiler(kBuilder.getBuilderConfiguration());
        List<KnowledgeBuilderResult> results = compiler.compileAll((ProjectClassLoader) kBuilder.getRootClassLoader(), srcNames, src);
        for (String className : classNames) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(className, true, kBuilder.getRootClassLoader());
            } catch (ClassNotFoundException e) {
                continue;
            }
            String pkgName = className.substring(0, className.lastIndexOf('.'));
            PackageRegistry pkgReg = kBuilder.getPackageRegistry(pkgName);
            pkgReg.getPackage().addTypeDeclaration(TypeDeclaration.createTypeDeclarationForBean(clazz));
        }
        kBuilder.updateResults(results);
    } else {
        kBuilder.compileAll();
        kBuilder.updateResults();
    }
    return classNames.toArray(new String[classNames.size()]);
}
Also used : InputSource(org.xml.sax.InputSource) ArrayList(java.util.ArrayList) ErrorReceiver(com.sun.tools.xjc.ErrorReceiver) MemoryResourceReader(org.kie.memorycompiler.resources.MemoryResourceReader) Dialect(org.drools.compiler.compiler.Dialect) PackageDescr(org.drools.drl.ast.descr.PackageDescr) ProjectClassLoader(org.drools.wiring.api.classloader.ProjectClassLoader) BadCommandLineException(com.sun.tools.xjc.BadCommandLineException) ProjectJavaCompiler(org.drools.compiler.compiler.ProjectJavaCompiler) JCodeModel(com.sun.codemodel.JCodeModel) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) Model(com.sun.tools.xjc.model.Model) JCodeModel(com.sun.codemodel.JCodeModel) KnowledgeBuilderResult(org.kie.internal.builder.KnowledgeBuilderResult)

Example 4 with MemoryResourceReader

use of org.kie.memorycompiler.resources.MemoryResourceReader in project drools by kiegroup.

the class KieMemoryCompiler method compileNoLoad.

/**
 * Compile the given sources and returns the generated byte codes.
 * Additional compiler settings can be provided using JavaCompilerSettings
 *
 * @param classNameSourceMap
 * @param classLoader
 * @param compilerSettings
 * @return
 */
public static Map<String, byte[]> compileNoLoad(Map<String, String> classNameSourceMap, ClassLoader classLoader, JavaCompilerSettings compilerSettings, JavaConfiguration.CompilerType compilerType) {
    MemoryResourceReader reader = new MemoryResourceReader();
    MemoryResourceStore store = new MemoryResourceStore();
    String[] classNames = new String[classNameSourceMap.size()];
    int i = 0;
    for (Map.Entry<String, String> entry : classNameSourceMap.entrySet()) {
        classNames[i] = toJavaSource(entry.getKey());
        reader.add(classNames[i], entry.getValue().getBytes());
        i++;
    }
    JavaConfiguration javaConfiguration = new JavaConfiguration();
    javaConfiguration.setCompiler(compilerType);
    javaConfiguration.setJavaLanguageLevel(findJavaVersion());
    JavaCompiler compiler = JavaCompilerFactory.loadCompiler(javaConfiguration);
    CompilationResult res = compilerSettings == null ? compiler.compile(classNames, reader, store, classLoader) : compiler.compile(classNames, reader, store, classLoader, compilerSettings);
    if (res.getErrors().length > 0) {
        throw new KieMemoryCompilerException(Arrays.toString(res.getErrors()));
    }
    Map<String, byte[]> toReturn = new HashMap<>();
    for (Map.Entry<KiePath, byte[]> entry : store.getResources().entrySet()) {
        toReturn.put(toClassName(entry.getKey().asString()), entry.getValue());
    }
    return toReturn;
}
Also used : HashMap(java.util.HashMap) MemoryResourceStore(org.kie.memorycompiler.resources.MemoryResourceStore) MemoryResourceReader(org.kie.memorycompiler.resources.MemoryResourceReader) KiePath(org.kie.memorycompiler.resources.KiePath) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

MemoryResourceReader (org.kie.memorycompiler.resources.MemoryResourceReader)4 ArrayList (java.util.ArrayList)2 CompilationResult (org.kie.memorycompiler.CompilationResult)2 MemoryResourceStore (org.kie.memorycompiler.resources.MemoryResourceStore)2 JCodeModel (com.sun.codemodel.JCodeModel)1 BadCommandLineException (com.sun.tools.xjc.BadCommandLineException)1 ErrorReceiver (com.sun.tools.xjc.ErrorReceiver)1 Model (com.sun.tools.xjc.model.Model)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Dialect (org.drools.compiler.compiler.Dialect)1 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)1 ProjectJavaCompiler (org.drools.compiler.compiler.ProjectJavaCompiler)1 MemoryFileSystem (org.drools.compiler.compiler.io.memory.MemoryFileSystem)1 PackageDescr (org.drools.drl.ast.descr.PackageDescr)1 ProjectClassLoader (org.drools.wiring.api.classloader.ProjectClassLoader)1 Test (org.junit.Test)1 KnowledgeBuilderResult (org.kie.internal.builder.KnowledgeBuilderResult)1 JavaCompiler (org.kie.memorycompiler.JavaCompiler)1 KiePath (org.kie.memorycompiler.resources.KiePath)1