Search in sources :

Example 1 with ScriptMacroParameters

use of org.xwiki.rendering.macro.script.ScriptMacroParameters in project xwiki-platform by xwiki.

the class ScriptClassLoaderHandlerListener method onEvent.

@Override
public void onEvent(Event event, Object source, Object data) {
    if (!(data instanceof ScriptMacroParameters)) {
        return;
    }
    if (event instanceof ScriptEvaluatingEvent) {
        // Set the context class loader to the script CL to ensure that any script engine using the context
        // classloader will work just fine.
        // Note: We must absolutely ensure that we always use the same context CL during the whole execution
        // request since JSR223 script engines (for example) that create internal class loaders need to
        // continue using these class loaders (where classes defined in scripts have been loaded for example).
        ScriptMacroParameters parameters = (ScriptMacroParameters) data;
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        this.execution.getContext().setProperty(EXECUTION_CONTEXT_ORIG_CLASSLOADER_KEY, originalClassLoader);
        try {
            ClassLoader newClassLoader = getClassLoader(parameters.getJars(), originalClassLoader);
            Thread.currentThread().setContextClassLoader(newClassLoader);
        } catch (Exception exception) {
            // abort execution
            ((CancelableEvent) event).cancel(exception.getMessage());
        }
    } else if (event instanceof ScriptEvaluatedEvent) {
        // Restore original class loader.
        ClassLoader originalClassLoader = (ClassLoader) this.execution.getContext().getProperty(EXECUTION_CONTEXT_ORIG_CLASSLOADER_KEY);
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
}
Also used : ScriptEvaluatedEvent(org.xwiki.script.event.ScriptEvaluatedEvent) ScriptMacroParameters(org.xwiki.rendering.macro.script.ScriptMacroParameters) ScriptEvaluatingEvent(org.xwiki.script.event.ScriptEvaluatingEvent) ExtendedURLClassLoader(org.xwiki.classloader.ExtendedURLClassLoader) MacroExecutionException(org.xwiki.rendering.macro.MacroExecutionException)

Aggregations

ExtendedURLClassLoader (org.xwiki.classloader.ExtendedURLClassLoader)1 MacroExecutionException (org.xwiki.rendering.macro.MacroExecutionException)1 ScriptMacroParameters (org.xwiki.rendering.macro.script.ScriptMacroParameters)1 ScriptEvaluatedEvent (org.xwiki.script.event.ScriptEvaluatedEvent)1 ScriptEvaluatingEvent (org.xwiki.script.event.ScriptEvaluatingEvent)1