use of org.apache.sling.commons.compiler.CompilationUnit in project sling by apache.
the class CompilerJava5Test method testJava5Support.
public void testJava5Support() throws Exception {
String sourceFile = "Java5Test";
CompilationUnit unit = createCompileUnit(sourceFile);
final Options options = new Options();
options.put(Options.KEY_SOURCE_VERSION, Options.VERSION_1_5);
options.put(Options.KEY_CLASS_LOADER_WRITER, this);
options.put(Options.KEY_CLASS_LOADER, this.getClass().getClassLoader());
final CompilationResult result = new EclipseJavaCompiler().compile(new CompilationUnit[] { unit }, options);
assertNotNull(result);
assertNull(result.getErrors());
}
use of org.apache.sling.commons.compiler.CompilationUnit in project sling by apache.
the class JDTCompiler method generateClass.
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
final String sourceFile = ctxt.getServletJavaFileName();
final String packageName = ctxt.getServletPackageName();
final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName();
final CompilationUnit unit = new CompilationUnitWithSource() {
/**
* @see org.apache.sling.commons.compiler.CompilationUnit#getLastModified()
*/
public long getLastModified() {
return -1;
}
/**
* @see org.apache.sling.commons.compiler.CompilationUnit#getMainClassName()
*/
public String getMainClassName() {
return targetClassName;
}
/**
* @see org.apache.sling.commons.compiler.CompilationUnit#getSource()
*/
public Reader getSource() throws IOException {
return new BufferedReader(new InputStreamReader(ctxt.getInputStream(sourceFile), ctxt.getOptions().getJavaEncoding()));
}
/**
* @see org.apache.sling.commons.compiler.CompilationUnitWithSource#getFileName()
*/
public String getFileName() {
return sourceFile;
}
};
final Options options = new Options();
options.put(Options.KEY_CLASS_LOADER_WRITER, ctxt.getRuntimeContext().getIOProvider().getClassLoaderWriter());
options.put(Options.KEY_GENERATE_DEBUG_INFO, ctxt.getOptions().getClassDebugInfo());
// Source JVM
if (ctxt.getOptions().getCompilerSourceVM() != null) {
options.put(Options.KEY_SOURCE_VERSION, ctxt.getOptions().getCompilerSourceVM());
} else {
// Default to 1.6
options.put(Options.KEY_SOURCE_VERSION, Options.VERSION_1_6);
}
// Target JVM
if (ctxt.getOptions().getCompilerTargetVM() != null) {
options.put(Options.KEY_TARGET_VERSION, ctxt.getOptions().getCompilerTargetVM());
} else {
// Default to 1.6
options.put(Options.KEY_TARGET_VERSION, Options.VERSION_1_6);
}
final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>();
final CompilationResult result = this.ctxt.getRuntimeContext().getIOProvider().getJavaCompiler().compile(new CompilationUnit[] { unit }, options);
if (result.getErrors() != null) {
for (final CompilerMessage cm : result.getErrors()) {
final String name = cm.getFile();
try {
problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuffer(cm.getMessage()), cm.getLine(), ctxt));
} catch (JasperException e) {
log.error("Error visiting node", e);
}
}
}
if (!ctxt.keepGenerated()) {
ctxt.delete(ctxt.getServletJavaFileName());
}
if (!problemList.isEmpty()) {
JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
errDispatcher.javacError(jeds);
}
if (log.isDebugEnabled()) {
long t2 = System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
}
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (!this.options.isSmapSuppressed()) {
SmapUtil.installSmap(getCompilationContext(), smap);
}
}
use of org.apache.sling.commons.compiler.CompilationUnit in project sling by apache.
the class EclipseJavaCompiler method compile.
/**
* @see org.apache.sling.commons.compiler.JavaCompiler#compile(org.apache.sling.commons.compiler.CompilationUnit[], org.apache.sling.commons.compiler.Options)
*/
@Override
public CompilationResult compile(final CompilationUnit[] units, final Options compileOptions) {
// make sure we have an options object (to avoid null checks all over the place)
final Options options = (compileOptions != null ? compileOptions : EMPTY_OPTIONS);
// get classloader and classloader writer
final ClassLoaderWriter writer = this.getClassLoaderWriter(options);
if (writer == null) {
return new CompilationResultImpl("Class loader writer for compilation is not available.");
}
final ClassLoader loader = this.getClassLoader(options, writer);
if (loader == null) {
return new CompilationResultImpl("Class loader for compilation is not available.");
}
// check sources for compilation
boolean needsCompilation = isForceCompilation(options);
if (!needsCompilation) {
for (final CompilationUnit unit : units) {
if (this.isOutDated(unit, writer)) {
needsCompilation = true;
break;
}
}
}
if (!needsCompilation) {
logger.debug("All source files are recent - no compilation required.");
return new CompilationResultImpl(writer);
}
// delete old class files
for (final CompilationUnit unit : units) {
final String name = '/' + unit.getMainClassName().replace('.', '/') + ".class";
writer.delete(name);
}
// create properties for the settings object
final Map<String, String> props = new HashMap<>();
if (options.isGenerateDebugInfo()) {
props.put(CompilerOptions.OPTION_LocalVariableAttribute, "generate");
props.put(CompilerOptions.OPTION_LineNumberAttribute, "generate");
props.put(CompilerOptions.OPTION_SourceFileAttribute, "generate");
}
if (options.getSourceVersion() != null) {
props.put(CompilerOptions.OPTION_Source, options.getSourceVersion());
props.put(CompilerOptions.OPTION_Compliance, options.getSourceVersion());
}
if (options.getTargetVersion() != null) {
props.put(CompilerOptions.OPTION_TargetPlatform, options.getTargetVersion());
}
props.put(CompilerOptions.OPTION_Encoding, "UTF8");
// create the settings
final CompilerOptions settings = new CompilerOptions(props);
logger.debug("Compiling with settings {}.", settings);
// create the result
final CompilationResultImpl result = new CompilationResultImpl(isIgnoreWarnings(options), writer);
// create the context
final CompileContext context = new CompileContext(units, result, writer, loader);
// create the compiler
final org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(context, this.policy, settings, context, this.problemFactory, null, null);
// compile
compiler.compile(context.getSourceUnits());
return result;
}
use of org.apache.sling.commons.compiler.CompilationUnit in project sling by apache.
the class SightlyJavaCompilerService method compileSource.
/**
* Compiles a class using the passed fully qualified class name and its source code.
*
* @param sourceIdentifier the source identifier
* @param sourceCode the source code from which to generate the class
* @return object instance of the class to compile
*/
public Object compileSource(SourceIdentifier sourceIdentifier, String sourceCode) {
try {
String fqcn = sourceIdentifier.getFullyQualifiedClassName();
if (sightlyEngineConfiguration.keepGenerated()) {
String path = "/" + fqcn.replaceAll("\\.", "/") + ".java";
OutputStream os = classLoaderWriter.getOutputStream(path);
IOUtils.write(sourceCode, os, "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 = PACKAGE_DECL_PATTERN.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;
}
CompilationUnit compilationUnit = new SightlyCompilationUnit(sourceCode, fqcn);
long start = System.currentTimeMillis();
CompilationResult compilationResult = javaCompiler.compile(new CompilationUnit[] { compilationUnit }, options);
long end = System.currentTimeMillis();
List<CompilerMessage> errors = compilationResult.getErrors();
if (errors != null && errors.size() > 0) {
throw new SightlyException(createErrorMsg(errors));
}
if (compilationResult.didCompile()) {
LOG.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).newInstance();
} catch (Exception e) {
throw new SightlyException(e);
}
}
Aggregations