in src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompiler.java [305:366]
private Object compileSource(SourceIdentifier sourceIdentifier, String sourceCode) {
Lock lock;
final String fqcn = sourceIdentifier.getFullyQualifiedClassName();
synchronized (compilationLocks) {
lock = compilationLocks.get(fqcn);
if (lock == null) {
lock = new ReentrantLock();
compilationLocks.put(fqcn, lock);
}
}
lock.lock();
try {
if (sightlyEngineConfiguration.keepGenerated()) {
String path = "/" + fqcn.replace(".", "/") + JAVA_EXTENSION;
OutputStream os = classLoaderWriter.getOutputStream(path);
IOUtils.write(sourceCode, os, StandardCharsets.UTF_8);
IOUtils.closeQuietly(os);
}
String[] sourceCodeLines = sourceCode.split("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
boolean foundPackageDeclaration = false;
for (String line : sourceCodeLines) {
Matcher matcher = Patterns.JAVA_PACKAGE_DECLARATION.matcher(line);
if (matcher.matches()) {
/*
* This matching might return false positives like:
* // package a.b.c;
*
* where from a syntactic point of view the source code doesn't have a package declaration and the expectancy is that our
* SightlyJavaCompilerService will add one.
*/
foundPackageDeclaration = true;
break;
}
}
if (!foundPackageDeclaration) {
sourceCode = "package " + sourceIdentifier.getPackageName() + ";\n" + sourceCode;
}
org.apache.sling.commons.compiler.CompilationUnit
compilationUnit = new SightlyCompilationUnit(sourceCode, fqcn);
long start = System.currentTimeMillis();
org.apache.sling.commons.compiler.CompilationResult
compilationResult = javaCompiler.compile(new org.apache.sling.commons.compiler.CompilationUnit[]{compilationUnit}, options);
long end = System.currentTimeMillis();
List<org.apache.sling.commons.compiler.CompilerMessage> errors = compilationResult.getErrors();
if (errors != null && !errors.isEmpty()) {
throw new SightlyException(createErrorMsg(errors));
}
if (compilationResult.didCompile()) {
LOGGER.debug("Class {} was compiled in {}ms.", fqcn, end - start);
}
/*
* the class loader might have become dirty, so let the {@link ClassLoaderWriter} decide which class loader to return
*/
return classLoaderWriter.getClassLoader().loadClass(fqcn).getDeclaredConstructor().newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException | NoSuchMethodException | InvocationTargetException e) {
throw new SightlyException(e);
} finally {
lock.unlock();
}
}