Search in sources :

Example 1 with CompilationResult

use of org.apache.sling.scripting.sightly.compiler.CompilationResult in project sling by apache.

the class SightlyCompilerTest method testMissingExplicitContext.

private void testMissingExplicitContext(String script) {
    CompilationResult result = compile(script);
    List<CompilerMessage> warnings = result.getWarnings();
    assertTrue(script + ": Expected compilation warnings.", warnings.size() == 1);
    CompilerMessage warningMessage = warnings.get(0);
    assertEquals(script + ": Expected warning on a different line.", 18, warningMessage.getLine());
    assertEquals(script + ": Expected warning on a different column.", 14, warningMessage.getColumn());
    assertTrue(script.equals(warningMessage.getScriptName()));
    assertEquals("${some.value}: Element script requires that all expressions have an explicit context specified. The expression will" + " be replaced with an empty string.", warningMessage.getMessage());
}
Also used : CompilerMessage(org.apache.sling.scripting.sightly.compiler.CompilerMessage) CompilationResult(org.apache.sling.scripting.sightly.compiler.CompilationResult)

Example 2 with CompilationResult

use of org.apache.sling.scripting.sightly.compiler.CompilationResult in project sling by apache.

the class SightlyCompilerTest method testSensitiveAttributes.

@Test
public void testSensitiveAttributes() {
    String script = "/sensitive-attributes.html";
    CompilationResult result = compile(script);
    List<CompilerMessage> warnings = result.getWarnings();
    assertTrue("Expected compilation warnings.", warnings.size() == 2);
    CompilerMessage _1stWarning = warnings.get(0);
    CompilerMessage _2ndWarning = warnings.get(1);
    assertEquals(script, _1stWarning.getScriptName());
    assertEquals("Expected warning on a different line.", 17, _1stWarning.getLine());
    assertEquals("Expected warning on a different line.", 18, _2ndWarning.getLine());
    assertEquals(script, _2ndWarning.getScriptName());
    assertEquals("${style.string}: Expressions within the value of attribute style need to have an explicit context option. The " + "expression will be replaced with an empty string.", _1stWarning.getMessage());
    assertEquals("${onclick.action}: Expressions within the value of attribute onclick need to have an explicit context option. The " + "expression will be replaced with an empty string.", _2ndWarning.getMessage());
}
Also used : CompilerMessage(org.apache.sling.scripting.sightly.compiler.CompilerMessage) CompilationResult(org.apache.sling.scripting.sightly.compiler.CompilationResult) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with CompilationResult

use of org.apache.sling.scripting.sightly.compiler.CompilationResult in project sling by apache.

the class ValidateMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().info("Skipping validation.");
        return;
    }
    long start = System.currentTimeMillis();
    if (!sourceDirectory.isAbsolute()) {
        sourceDirectory = new File(project.getBasedir(), sourceDirectory.getPath());
    }
    if (!sourceDirectory.exists()) {
        getLog().info("Source directory does not exist, skipping.");
        return;
    }
    if (!sourceDirectory.isDirectory()) {
        throw new MojoExecutionException(String.format("Configured sourceDirectory={%s} is not a directory.", sourceDirectory.getAbsolutePath()));
    }
    if (!buildContext.hasDelta(sourceDirectory)) {
        getLog().info("No files found to validate, skipping.");
        return;
    }
    // don't fail execution in Eclipse as it generates an error marker in the POM file, which is not desired
    boolean mayFailExecution = !buildContext.getClass().getName().startsWith("org.eclipse.m2e");
    sourceDirectoryLength = sourceDirectory.getAbsolutePath().length();
    processedIncludes = processIncludes();
    processedExcludes = processExcludes();
    try {
        SightlyCompiler compiler = new SightlyCompiler();
        Scanner scanner = buildContext.newScanner(sourceDirectory);
        scanner.setExcludes(new String[] { processedExcludes });
        scanner.setIncludes(new String[] { processedIncludes });
        scanner.scan();
        String[] includedFiles = scanner.getIncludedFiles();
        processedFiles = new ArrayList<>(includedFiles.length);
        for (String includedFile : includedFiles) {
            processedFiles.add(new File(sourceDirectory, includedFile));
        }
        Map<File, CompilationResult> compilationResults = new HashMap<>();
        for (File script : processedFiles) {
            compilationResults.put(script, compiler.compile(getCompilationUnit(script)));
        }
        for (Map.Entry<File, CompilationResult> entry : compilationResults.entrySet()) {
            File script = entry.getKey();
            CompilationResult result = entry.getValue();
            buildContext.removeMessages(script);
            if (result.getWarnings().size() > 0) {
                for (CompilerMessage message : result.getWarnings()) {
                    buildContext.addMessage(script, message.getLine(), message.getColumn(), message.getMessage(), BuildContext.SEVERITY_WARNING, null);
                }
                hasWarnings = true;
            }
            if (result.getErrors().size() > 0) {
                for (CompilerMessage message : result.getErrors()) {
                    String messageString = message.getMessage().replaceAll(System.lineSeparator(), "");
                    buildContext.addMessage(script, message.getLine(), message.getColumn(), messageString, BuildContext.SEVERITY_ERROR, null);
                }
                hasErrors = true;
            }
        }
        getLog().info("Processed " + processedFiles.size() + " files in " + (System.currentTimeMillis() - start) + " milliseconds");
        if (mayFailExecution && hasWarnings && failOnWarnings) {
            throw new MojoFailureException("Compilation warnings were configured to fail the build.");
        }
        if (mayFailExecution && hasErrors) {
            throw new MojoFailureException("Please check the reported syntax errors.");
        }
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Cannot filter files from {%s} with includes {%s} and excludes {%s}.", sourceDirectory.getAbsolutePath(), processedIncludes, processedExcludes), e);
    }
}
Also used : Scanner(org.codehaus.plexus.util.Scanner) CompilerMessage(org.apache.sling.scripting.sightly.compiler.CompilerMessage) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) SightlyCompiler(org.apache.sling.scripting.sightly.compiler.SightlyCompiler) CompilationResult(org.apache.sling.scripting.sightly.compiler.CompilationResult) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with CompilationResult

use of org.apache.sling.scripting.sightly.compiler.CompilationResult in project sling by apache.

the class SightlyScriptEngine method internalCompile.

private SightlyCompiledScript internalCompile(final Reader script, ScriptContext scriptContext) throws ScriptException {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(((SightlyScriptEngineFactory) getFactory()).getClassLoader());
    try {
        String sName = NO_SCRIPT;
        if (script instanceof ScriptNameAware) {
            sName = ((ScriptNameAware) script).getScriptName();
        }
        if (sName.equals(NO_SCRIPT)) {
            sName = getScriptName(scriptContext);
        }
        final String scriptName = sName;
        CompilationUnit compilationUnit = new CompilationUnit() {

            @Override
            public String getScriptName() {
                return scriptName;
            }

            @Override
            public Reader getScriptReader() {
                return script;
            }
        };
        JavaClassBackendCompiler javaClassBackendCompiler = new JavaClassBackendCompiler();
        GlobalShadowCheckBackendCompiler shadowCheckBackendCompiler = null;
        if (scriptContext != null) {
            Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
            Set<String> globals = bindings.keySet();
            shadowCheckBackendCompiler = new GlobalShadowCheckBackendCompiler(javaClassBackendCompiler, globals);
        }
        CompilationResult result = shadowCheckBackendCompiler == null ? sightlyCompiler.compile(compilationUnit, javaClassBackendCompiler) : sightlyCompiler.compile(compilationUnit, shadowCheckBackendCompiler);
        if (result.getWarnings().size() > 0) {
            for (CompilerMessage warning : result.getWarnings()) {
                LOGGER.warn("Script {} {}:{}: {}", new Object[] { warning.getScriptName(), warning.getLine(), warning.getColumn(), warning.getMessage() });
            }
        }
        if (result.getErrors().size() > 0) {
            CompilerMessage error = result.getErrors().get(0);
            throw new ScriptException(error.getMessage(), error.getScriptName(), error.getLine(), error.getColumn());
        }
        SourceIdentifier sourceIdentifier = new SourceIdentifier(configuration, scriptName);
        String javaSourceCode = javaClassBackendCompiler.build(sourceIdentifier);
        Object renderUnit = javaCompilerService.compileSource(sourceIdentifier, javaSourceCode);
        if (renderUnit instanceof RenderUnit) {
            return new SightlyCompiledScript(this, (RenderUnit) renderUnit);
        } else {
            throw new SightlyException("Expected a RenderUnit.");
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : CompilationUnit(org.apache.sling.scripting.sightly.compiler.CompilationUnit) ScriptNameAware(org.apache.sling.scripting.api.ScriptNameAware) CompilerMessage(org.apache.sling.scripting.sightly.compiler.CompilerMessage) JavaClassBackendCompiler(org.apache.sling.scripting.sightly.java.compiler.JavaClassBackendCompiler) RenderUnit(org.apache.sling.scripting.sightly.java.compiler.RenderUnit) GlobalShadowCheckBackendCompiler(org.apache.sling.scripting.sightly.java.compiler.GlobalShadowCheckBackendCompiler) SourceIdentifier(org.apache.sling.scripting.sightly.impl.engine.compiled.SourceIdentifier) Bindings(javax.script.Bindings) SlingBindings(org.apache.sling.api.scripting.SlingBindings) ScriptException(javax.script.ScriptException) SightlyException(org.apache.sling.scripting.sightly.SightlyException) CompilationResult(org.apache.sling.scripting.sightly.compiler.CompilationResult)

Example 5 with CompilationResult

use of org.apache.sling.scripting.sightly.compiler.CompilationResult in project sling by apache.

the class SightlyCompilerTest method testEmptyExpression.

@Test
public void testEmptyExpression() {
    CompilationResult result = compile("/empty-expression.html");
    assertTrue("Didn't expect any warnings or errors.", result.getErrors().size() == 0 && result.getWarnings().size() == 0);
}
Also used : CompilationResult(org.apache.sling.scripting.sightly.compiler.CompilationResult) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

CompilationResult (org.apache.sling.scripting.sightly.compiler.CompilationResult)6 CompilerMessage (org.apache.sling.scripting.sightly.compiler.CompilerMessage)5 Test (org.junit.Test)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 File (java.io.File)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Bindings (javax.script.Bindings)1 ScriptException (javax.script.ScriptException)1 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 SlingBindings (org.apache.sling.api.scripting.SlingBindings)1 ScriptNameAware (org.apache.sling.scripting.api.ScriptNameAware)1 SightlyException (org.apache.sling.scripting.sightly.SightlyException)1 CompilationUnit (org.apache.sling.scripting.sightly.compiler.CompilationUnit)1 SightlyCompiler (org.apache.sling.scripting.sightly.compiler.SightlyCompiler)1 SourceIdentifier (org.apache.sling.scripting.sightly.impl.engine.compiled.SourceIdentifier)1 GlobalShadowCheckBackendCompiler (org.apache.sling.scripting.sightly.java.compiler.GlobalShadowCheckBackendCompiler)1 JavaClassBackendCompiler (org.apache.sling.scripting.sightly.java.compiler.JavaClassBackendCompiler)1