KieMemoryCompiler { public static Map<String, Class<?>> compile(Map<String, String> classNameSourceMap, ClassLoader classLoader) { Map<String, KieMemoryCompilerSourceCode> sourceCodes = classNameSourceMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new KieMemoryCompilerSourceCode(entry.getKey(), entry.getValue()))); KieMemoryCompilerClassLoader kieMemoryCompilerClassLoader = new KieMemoryCompilerClassLoader(classLoader); DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>(); KieMemoryCompilerFileManager fileManager = new KieMemoryCompilerFileManager(JAVA_COMPILER.getStandardFileManager(null, null, null), kieMemoryCompilerClassLoader); JavaCompiler.CompilationTask task = JAVA_COMPILER.getTask(null, fileManager, collector, OPTIONS, null, sourceCodes.values()); boolean compilationSuccess = task.call(); boolean hasCompilerError = collector.getDiagnostics().stream().anyMatch(d -> d.getKind().equals(Diagnostic.Kind.ERROR)); if (!compilationSuccess || hasCompilerError) { compilerError(collector); } Map<String, Class<?>> toReturn = new HashMap<>(); for (String className : sourceCodes.keySet()) { try { toReturn.put(className, kieMemoryCompilerClassLoader.loadClass(className)); } catch (ClassNotFoundException e) { throw new KieMemoryCompilerException(e.getMessage(), e); } } return toReturn; } private  KieMemoryCompiler(); static Map<String, Class<?>> compile(Map<String, String> classNameSourceMap, ClassLoader classLoader);  }
@Test public void compileAndLoadClass() throws Exception { Map<String, String> source = singletonMap("org.kie.memorycompiler.ExampleClass", EXAMPLE_CLASS); Map<String, Class<?>> compiled = KieMemoryCompiler.compile(source, this.getClass().getClassLoader()); Class<?> exampleClazz = compiled.get("org.kie.memorycompiler.ExampleClass"); assertThat(exampleClazz, is(notNullValue())); Object instance = exampleClazz.getDeclaredConstructors()[0].newInstance(); Method sumMethod = exampleClazz.getMethod("sum", Integer.class, Integer.class); Object result = sumMethod.invoke(instance, 2, 3); assertThat(result, is(5)); }
@Test(expected = KieMemoryCompilerException.class) public void invalidClass() { Map<String, String> source = singletonMap("org.kie.memorycompiler.InvalidJavaClass", "Invalid Java Code"); KieMemoryCompiler.compile(source, this.getClass().getClassLoader()); }
@Test public void doNotFailOnWarning() throws Exception { Map<String, String> source = singletonMap("org.kie.memorycompiler.WarningClass", WARNING_CLASS); Map<String, Class<?>> compiled = KieMemoryCompiler.compile(source, this.getClass().getClassLoader()); Class<?> exampleClazz = compiled.get("org.kie.memorycompiler.WarningClass"); assertThat(exampleClazz, is(notNullValue())); Object instance = exampleClazz.getDeclaredConstructors()[0].newInstance(); Method minusMethod = exampleClazz.getMethod("minus", Integer.class, Integer.class); Object result = minusMethod.invoke(instance, 8, 4); assertThat(result, is(4)); }