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);
}
}
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);
}
}
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);
}
}
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);
}
}
}
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();
}
}
}
Aggregations