Search in sources :

Example 16 with SlingScriptHelper

use of org.apache.sling.api.scripting.SlingScriptHelper in project acs-aem-commons by Adobe-Consulting-Services.

the class AvailableProcessDefinitions method activate.

@Override
@SuppressWarnings("checkstyle:parametername")
public void activate() throws Exception {
    SlingScriptHelper sling = getSlingScriptHelper();
    User user = sling.getRequest().getResourceResolver().adaptTo(User.class);
    ProcessDefinitionFactory[] allDefinitionFactories = sling.getServices(ProcessDefinitionFactory.class, null);
    definitions = Stream.of(allDefinitionFactories).filter(o -> o.isAllowed(user)).collect(Collectors.toMap(ProcessDefinitionFactory::getName, o -> o, (a, b) -> a, TreeMap::new));
    String processDefinitionName = get("processDefinition", String.class);
    if (StringUtils.isEmpty(processDefinitionName)) {
        processDefinitionName = getRequest().getParameter("processDefinition");
    }
    if (StringUtils.isNotEmpty(processDefinitionName) && definitions.containsKey(processDefinitionName)) {
        Class clazz = definitions.get(processDefinitionName).createProcessDefinition().getClass();
        fieldComponents = AnnotatedFieldDeserializer.getFormFields(clazz, sling);
    }
}
Also used : User(org.apache.jackrabbit.api.security.user.User) ProcessDefinitionFactory(com.adobe.acs.commons.mcp.ProcessDefinitionFactory) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) TreeMap(java.util.TreeMap)

Example 17 with SlingScriptHelper

use of org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.

the class XProcScriptEngine method eval.

public Object eval(Reader reader, ScriptContext scriptContext) throws ScriptException {
    Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
    SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
    if (helper == null) {
        throw new ScriptException("SlingScriptHelper missing from bindings");
    }
    String scriptName = helper.getScript().getScriptResource().getPath();
    try {
        XplBuilder xplBuilder = new XplBuilder();
        Pipeline xpl = (Pipeline) xplBuilder.build(reader);
        xpl.getEnv().setSling(helper);
        xpl.eval();
    } catch (Throwable t) {
        log.error("Failure running XProc script.", t);
        final ScriptException se = new ScriptException("Failure running XProc script " + scriptName);
        se.initCause(t);
        throw se;
    }
    return null;
}
Also used : ScriptException(javax.script.ScriptException) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) Bindings(javax.script.Bindings) SlingBindings(org.apache.sling.api.scripting.SlingBindings) XplBuilder(org.apache.sling.scripting.xproc.xpl.XplBuilder) Pipeline(org.apache.sling.scripting.xproc.xpl.api.Pipeline)

Example 18 with SlingScriptHelper

use of org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.

the class JavaUseProvider method provide.

@Override
public ProviderOutcome provide(String identifier, RenderContext renderContext, Bindings arguments) {
    if (!JAVA_PATTERN.matcher(identifier).matches()) {
        LOG.debug("Identifier {} does not match a Java class name pattern.", identifier);
        return ProviderOutcome.failure();
    }
    Bindings globalBindings = renderContext.getBindings();
    SlingScriptHelper sling = BindingsUtils.getHelper(globalBindings);
    SlingHttpServletRequest request = BindingsUtils.getRequest(globalBindings);
    Map<String, Object> overrides = setRequestAttributes(request, arguments);
    Object result;
    try {
        result = sightlyJavaCompilerService.getResourceBackedUseObject(renderContext, identifier);
        if (result != null) {
            if (result instanceof Use) {
                ((Use) result).init(BindingsUtils.merge(globalBindings, arguments));
            }
            return ProviderOutcome.success(result);
        } else {
            LOG.debug("Attempting to load class {} from the classloader cache.", identifier);
            Class<?> cls = classLoaderWriter.getClassLoader().loadClass(identifier);
            // attempt OSGi service load
            result = sling.getService(cls);
            if (result != null) {
                return ProviderOutcome.success(result);
            }
            result = request.adaptTo(cls);
            if (result == null) {
                Resource resource = BindingsUtils.getResource(globalBindings);
                result = resource.adaptTo(cls);
            }
            if (result != null) {
                return ProviderOutcome.success(result);
            } else {
                /*
                     * the object was cached by the class loader but it's not adaptable from {@link Resource} or {@link
                     * SlingHttpServletRequest}; attempt to load it like a regular POJO that optionally could implement {@link Use}
                     */
                result = cls.newInstance();
                if (result instanceof Use) {
                    ((Use) result).init(BindingsUtils.merge(globalBindings, arguments));
                }
                return ProviderOutcome.notNullOrFailure(result);
            }
        }
    } catch (Exception e) {
        // any other exception is an error
        return ProviderOutcome.failure(e);
    } finally {
        resetRequestAttribute(request, overrides);
    }
}
Also used : SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) Use(org.apache.sling.scripting.sightly.pojo.Use) Resource(org.apache.sling.api.resource.Resource) Bindings(javax.script.Bindings) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest)

Example 19 with SlingScriptHelper

use of org.apache.sling.api.scripting.SlingScriptHelper in project sling by apache.

the class I18nRuntimeExtension method get.

private String get(final Bindings bindings, String text, String locale, String basename, String hint) {
    final SlingScriptHelper slingScriptHelper = BindingsUtils.getHelper(bindings);
    final SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
    final ResourceBundleProvider resourceBundleProvider = slingScriptHelper.getService(ResourceBundleProvider.class);
    if (resourceBundleProvider != null) {
        String key = text;
        if (StringUtils.isNotEmpty(hint)) {
            key += " ((" + hint + "))";
        }
        if (StringUtils.isEmpty(locale)) {
            Enumeration<Locale> requestLocales = request.getLocales();
            while (requestLocales.hasMoreElements()) {
                Locale l = requestLocales.nextElement();
                String translation = getTranslation(resourceBundleProvider, basename, key, l);
                if (translation != null) {
                    return translation;
                }
            }
        } else {
            try {
                Locale l = LocaleUtils.toLocale(locale);
                String translation = getTranslation(resourceBundleProvider, basename, key, l);
                if (translation != null) {
                    return translation;
                }
            } catch (IllegalArgumentException e) {
                LOG.warn("Invalid locale detected: {}.", locale);
                return text;
            }
        }
    }
    LOG.warn("No translation found for string '{}' using expression provided locale '{}' or default locale '{}'", text, locale, request.getLocale().getLanguage());
    return text;
}
Also used : Locale(java.util.Locale) ResourceBundleProvider(org.apache.sling.i18n.ResourceBundleProvider) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest)

Example 20 with SlingScriptHelper

use of org.apache.sling.api.scripting.SlingScriptHelper 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

SlingScriptHelper (org.apache.sling.api.scripting.SlingScriptHelper)26 SlingBindings (org.apache.sling.api.scripting.SlingBindings)15 Resource (org.apache.sling.api.resource.Resource)12 Bindings (javax.script.Bindings)10 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)9 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)8 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)5 ScriptException (javax.script.ScriptException)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 InputStreamReader (java.io.InputStreamReader)3 Servlet (javax.servlet.Servlet)3 ServletResolver (org.apache.sling.api.servlets.ServletResolver)3 SightlyException (org.apache.sling.scripting.sightly.SightlyException)3 Test (org.junit.Test)3 BufferedReader (java.io.BufferedReader)2 Reader (java.io.Reader)2 Locale (java.util.Locale)2 JspException (javax.servlet.jsp.JspException)2 BodyContent (javax.servlet.jsp.tagext.BodyContent)2