Search in sources :

Example 1 with CompilationResult

use of org.apache.sling.commons.compiler.CompilationResult 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());
}
Also used : CompilationUnit(org.apache.sling.commons.compiler.CompilationUnit) Options(org.apache.sling.commons.compiler.Options) CompilationResult(org.apache.sling.commons.compiler.CompilationResult)

Example 2 with CompilationResult

use of org.apache.sling.commons.compiler.CompilationResult 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);
    }
}
Also used : CompilationUnit(org.apache.sling.commons.compiler.CompilationUnit) Options(org.apache.sling.commons.compiler.Options) CompilationUnitWithSource(org.apache.sling.commons.compiler.CompilationUnitWithSource) CompilerMessage(org.apache.sling.commons.compiler.CompilerMessage) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JasperException(org.apache.sling.scripting.jsp.jasper.JasperException) BufferedReader(java.io.BufferedReader) CompilationResult(org.apache.sling.commons.compiler.CompilationResult)

Example 3 with CompilationResult

use of org.apache.sling.commons.compiler.CompilationResult in project sling by apache.

the class SightlyJavaCompilerServiceTest method getInstancePojoTest.

private void getInstancePojoTest(String className) throws Exception {
    RenderContextImpl renderContext = Mockito.mock(RenderContextImpl.class);
    JavaCompiler javaCompiler = Mockito.mock(JavaCompiler.class);
    CompilationResult compilationResult = Mockito.mock(CompilationResult.class);
    when(compilationResult.getErrors()).thenReturn(new ArrayList<CompilerMessage>());
    when(javaCompiler.compile(Mockito.any(CompilationUnit[].class), Mockito.any(Options.class))).thenReturn(compilationResult);
    when(classLoaderWriter.getClassLoader().loadClass(className)).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return MockPojo.class;
        }
    });
    Whitebox.setInternalState(compiler, "classLoaderWriter", classLoaderWriter);
    Whitebox.setInternalState(compiler, "javaCompiler", javaCompiler);
    Whitebox.setInternalState(compiler, "scriptingResourceResolverProvider", scriptingResourceResolverProvider);
    Object obj = compiler.getResourceBackedUseObject(renderContext, className);
    assertTrue("Expected to obtain a " + MockPojo.class.getName() + " object.", obj instanceof MockPojo);
}
Also used : Options(org.apache.sling.commons.compiler.Options) CompilerMessage(org.apache.sling.commons.compiler.CompilerMessage) InvocationOnMock(org.mockito.invocation.InvocationOnMock) RenderContextImpl(org.apache.sling.scripting.sightly.impl.engine.runtime.RenderContextImpl) JavaCompiler(org.apache.sling.commons.compiler.JavaCompiler) CompilationResult(org.apache.sling.commons.compiler.CompilationResult)

Example 4 with CompilationResult

use of org.apache.sling.commons.compiler.CompilationResult 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);
    }
}
Also used : CompilationUnit(org.apache.sling.commons.compiler.CompilationUnit) CompilerMessage(org.apache.sling.commons.compiler.CompilerMessage) Matcher(java.util.regex.Matcher) OutputStream(java.io.OutputStream) IOException(java.io.IOException) SightlyException(org.apache.sling.scripting.sightly.SightlyException) SightlyException(org.apache.sling.scripting.sightly.SightlyException) CompilationResult(org.apache.sling.commons.compiler.CompilationResult)

Example 5 with CompilationResult

use of org.apache.sling.commons.compiler.CompilationResult in project sling by apache.

the class ServletWrapper method compile.

/**
     * Compile the servlet java class. If the compiled class has
     * injected fields, don't create an instance of it.
     */
private void compile() throws Exception {
    logger.debug("Compiling {}", this.sourcePath);
    // clear exception
    this.compileException = null;
    try {
        final CompilerOptions opts = this.ioProvider.getForceCompileOptions();
        final CompilationUnit unit = new CompilationUnit(this.sourcePath, className, ioProvider);
        final CompilationResult result = this.ioProvider.getCompiler().compile(new org.apache.sling.commons.compiler.CompilationUnit[] { unit }, opts);
        final List<CompilerMessage> errors = result.getErrors();
        this.destroy();
        if (errors != null && errors.size() > 0) {
            throw CompilerException.create(errors, this.sourcePath);
        }
        final Servlet servlet = (Servlet) result.loadCompiledClass(this.className).newInstance();
        servlet.init(this.config);
        this.injectFields(servlet);
        this.theServlet = servlet;
    } catch (final Exception ex) {
        // store exception for futher access attempts
        this.compileException = ex;
        throw ex;
    }
}
Also used : CompilerMessage(org.apache.sling.commons.compiler.CompilerMessage) Servlet(javax.servlet.Servlet) CompilationResult(org.apache.sling.commons.compiler.CompilationResult) ServletException(javax.servlet.ServletException) UnavailableException(javax.servlet.UnavailableException)

Aggregations

CompilationResult (org.apache.sling.commons.compiler.CompilationResult)5 CompilerMessage (org.apache.sling.commons.compiler.CompilerMessage)4 CompilationUnit (org.apache.sling.commons.compiler.CompilationUnit)3 Options (org.apache.sling.commons.compiler.Options)3 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 Matcher (java.util.regex.Matcher)1 Servlet (javax.servlet.Servlet)1 ServletException (javax.servlet.ServletException)1 UnavailableException (javax.servlet.UnavailableException)1 CompilationUnitWithSource (org.apache.sling.commons.compiler.CompilationUnitWithSource)1 JavaCompiler (org.apache.sling.commons.compiler.JavaCompiler)1 JasperException (org.apache.sling.scripting.jsp.jasper.JasperException)1 SightlyException (org.apache.sling.scripting.sightly.SightlyException)1 RenderContextImpl (org.apache.sling.scripting.sightly.impl.engine.runtime.RenderContextImpl)1 InvocationOnMock (org.mockito.invocation.InvocationOnMock)1