Search in sources :

Example 11 with SightlyException

use of org.apache.sling.scripting.sightly.SightlyException 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 12 with SightlyException

use of org.apache.sling.scripting.sightly.SightlyException 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 13 with SightlyException

use of org.apache.sling.scripting.sightly.SightlyException in project sling by apache.

the class ResourceRuntimeExtension method includeResource.

private void includeResource(final Bindings bindings, PrintWriter out, String path, String dispatcherOptions, String resourceType) {
    if (StringUtils.isEmpty(path)) {
        throw new SightlyException("Resource path cannot be empty");
    } else {
        SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
        Resource includeRes = request.getResourceResolver().resolve(path);
        if (ResourceUtil.isNonExistingResource(includeRes)) {
            includeRes = new SyntheticResource(request.getResourceResolver(), path, resourceType);
        }
        includeResource(bindings, out, includeRes, dispatcherOptions, resourceType);
    }
}
Also used : SightlyException(org.apache.sling.scripting.sightly.SightlyException) Resource(org.apache.sling.api.resource.Resource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest)

Example 14 with SightlyException

use of org.apache.sling.scripting.sightly.SightlyException in project sling by apache.

the class ResourceRuntimeExtension method includeResource.

private void includeResource(final Bindings bindings, PrintWriter out, Resource includeRes, String dispatcherOptions, String resourceType) {
    if (includeRes == null) {
        throw new SightlyException("Resource cannot be null");
    } else {
        SlingHttpServletResponse customResponse = new PrintWriterResponseWrapper(out, BindingsUtils.getResponse(bindings));
        SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
        RequestDispatcherOptions opts = new RequestDispatcherOptions(dispatcherOptions);
        if (StringUtils.isNotEmpty(resourceType)) {
            opts.setForceResourceType(resourceType);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(includeRes, opts);
        try {
            if (dispatcher != null) {
                dispatcher.include(request, customResponse);
            } else {
                throw new SightlyException("Failed to include resource " + includeRes.getPath());
            }
        } catch (Exception e) {
            throw new SightlyException("Failed to include resource " + includeRes.getPath(), e);
        }
    }
}
Also used : SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) RequestDispatcherOptions(org.apache.sling.api.request.RequestDispatcherOptions) SightlyException(org.apache.sling.scripting.sightly.SightlyException) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) RequestDispatcher(javax.servlet.RequestDispatcher) SightlyException(org.apache.sling.scripting.sightly.SightlyException)

Example 15 with SightlyException

use of org.apache.sling.scripting.sightly.SightlyException in project sling by apache.

the class JsUseProvider method provide.

@Override
public ProviderOutcome provide(String identifier, RenderContext renderContext, Bindings arguments) {
    Bindings globalBindings = renderContext.getBindings();
    if (!Utils.isJsScript(identifier)) {
        return ProviderOutcome.failure();
    }
    ScriptEngine jsEngine = scriptEngineManager.getEngineByName(JS_ENGINE_NAME);
    if (jsEngine == null) {
        return ProviderOutcome.failure(new SightlyException("No JavaScript engine was defined."));
    }
    SlingScriptHelper scriptHelper = Utils.getHelper(globalBindings);
    JsEnvironment environment = null;
    try {
        environment = new JsEnvironment(jsEngine);
        environment.initialize();
        ResourceResolver slingScriptingResolver = scriptingResourceResolverProvider.getRequestScopedResourceResolver();
        Resource callerScript = slingScriptingResolver.getResource(scriptHelper.getScript().getScriptResource().getPath());
        Resource scriptResource = Utils.getScriptResource(callerScript, identifier, globalBindings);
        globalBindings.put(ScriptEngine.FILENAME, scriptResource.getPath());
        proxyAsyncScriptableFactory.registerProxies(globalBindings);
        AsyncContainer asyncContainer = environment.runResource(scriptResource, globalBindings, arguments);
        return ProviderOutcome.success(jsValueAdapter.adapt(asyncContainer));
    } finally {
        if (environment != null) {
            environment.cleanup();
        }
    }
}
Also used : SightlyException(org.apache.sling.scripting.sightly.SightlyException) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) AsyncContainer(org.apache.sling.scripting.sightly.js.impl.async.AsyncContainer) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine)

Aggregations

SightlyException (org.apache.sling.scripting.sightly.SightlyException)17 Bindings (javax.script.Bindings)6 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)6 Resource (org.apache.sling.api.resource.Resource)5 SimpleBindings (javax.script.SimpleBindings)3 SlingBindings (org.apache.sling.api.scripting.SlingBindings)3 SlingScriptHelper (org.apache.sling.api.scripting.SlingScriptHelper)3 Function (org.mozilla.javascript.Function)3 ScriptableObject (org.mozilla.javascript.ScriptableObject)3 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 ScriptException (javax.script.ScriptException)2 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)2 RenderUnit (org.apache.sling.scripting.sightly.java.compiler.RenderUnit)2 AsyncContainer (org.apache.sling.scripting.sightly.js.impl.async.AsyncContainer)2 TimingFunction (org.apache.sling.scripting.sightly.js.impl.async.TimingFunction)2 HybridObject (org.apache.sling.scripting.sightly.js.impl.rhino.HybridObject)2 Context (org.mozilla.javascript.Context)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1