Search in sources :

Example 31 with Bindings

use of javax.script.Bindings in project OpenAM by OpenRock.

the class Scripted method process.

/**
     * {@inheritDoc}
     */
@Override
public int process(Callback[] callbacks, int state) throws LoginException {
    switch(state) {
        case ISAuthConstants.LOGIN_START:
            substituteUIStrings();
            return STATE_RUN_SCRIPT;
        case STATE_RUN_SCRIPT:
            Bindings scriptVariables = new SimpleBindings();
            scriptVariables.put(REQUEST_DATA_VARIABLE_NAME, getScriptHttpRequestWrapper());
            String clientScriptOutputData = getClientScriptOutputData(callbacks);
            scriptVariables.put(CLIENT_SCRIPT_OUTPUT_DATA_VARIABLE_NAME, clientScriptOutputData);
            scriptVariables.put(LOGGER_VARIABLE_NAME, DEBUG);
            scriptVariables.put(STATE_VARIABLE_NAME, state);
            scriptVariables.put(SHARED_STATE, sharedState);
            scriptVariables.put(USERNAME_VARIABLE_NAME, userName);
            scriptVariables.put(SUCCESS_ATTR_NAME, SUCCESS_VALUE);
            scriptVariables.put(FAILED_ATTR_NAME, FAILURE_VALUE);
            scriptVariables.put(HTTP_CLIENT_VARIABLE_NAME, httpClient);
            scriptVariables.put(IDENTITY_REPOSITORY, identityRepository);
            try {
                scriptEvaluator.evaluateScript(getServerSideScript(), scriptVariables);
            } catch (ScriptException e) {
                DEBUG.message("Error running server side scripts", e);
                throw new AuthLoginException("Error running script", e);
            }
            state = ((Number) scriptVariables.get(STATE_VARIABLE_NAME)).intValue();
            userName = (String) scriptVariables.get(USERNAME_VARIABLE_NAME);
            sharedState.put(CLIENT_SCRIPT_OUTPUT_DATA_VARIABLE_NAME, clientScriptOutputData);
            if (state != SUCCESS_VALUE) {
                throw new AuthLoginException("Authentication failed");
            }
            return state;
        default:
            throw new AuthLoginException("Invalid state");
    }
}
Also used : ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings)

Example 32 with Bindings

use of javax.script.Bindings in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class WCMUsePojoBaseTest method getResourceBackedBindings.

/**
     * <p>
     * Creates a {@link Bindings} map initialised with the following default bindings available to Sightly use objects based on {@link
     * WCMUsePojo}:
     * </p>
     * <ul>
     * <li>{@link SlingBindings#RESOURCE}</li>
     * <li>{@link SlingBindings#REQUEST}</li>
     * <li>{@link SlingBindings#RESPONSE}</li>
     * <li>{@link WCMBindings#PROPERTIES}</li>
     * <li>{@link WCMBindings#WCM_MODE}</li>
     * <li>{@link WCMBindings#PAGE_MANAGER}</li>
     * <li>{@link WCMBindings#RESOURCE_PAGE}</li>
     * <li>{@link WCMBindings#CURRENT_PAGE}</li>
     * <li>{@link WCMBindings#PAGE_PROPERTIES}</li>
     * </ul>
     *
     * @param resourcePath the path to a resource already loaded in the testing context
     * @return the bindings map
     */
protected Bindings getResourceBackedBindings(String resourcePath) {
    Bindings bindings = getDefaultSlingBindings();
    Resource resource = context.resourceResolver().getResource(resourcePath);
    if (resource != null) {
        ValueMap properties = resource.adaptTo(ValueMap.class);
        bindings.put(SlingBindings.RESOURCE, resource);
        bindings.put(WCMBindings.PROPERTIES, properties);
        bindings.put(WCMBindings.WCM_MODE, new SightlyWCMMode(context.request()));
        PageManager pageManager = context.pageManager();
        bindings.put(WCMBindings.PAGE_MANAGER, pageManager);
        context.request().setResource(resource);
        Page resourcePage = pageManager.getContainingPage(resource);
        if (resourcePage != null) {
            bindings.put(WCMBindings.RESOURCE_PAGE, resourcePage);
            bindings.put(WCMBindings.CURRENT_PAGE, resourcePage);
            bindings.put(WCMBindings.PAGE_PROPERTIES, properties);
        }
    } else {
        throw new IllegalArgumentException("Cannot find a resource at " + resourcePath);
    }
    return bindings;
}
Also used : PageManager(com.day.cq.wcm.api.PageManager) ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) Page(com.day.cq.wcm.api.Page) SightlyWCMMode(com.adobe.cq.sightly.SightlyWCMMode) Bindings(javax.script.Bindings) SlingBindings(org.apache.sling.api.scripting.SlingBindings) SimpleBindings(javax.script.SimpleBindings) WCMBindings(com.adobe.cq.sightly.WCMBindings)

Example 33 with Bindings

use of javax.script.Bindings in project enhydrator by AdamBien.

the class ScriptingEnvironmentProviderTest method emptyRowHasMemory.

@Test
public void emptyRowHasMemory() {
    Row row = new Row();
    Memory expected = new Memory();
    row.useMemory(expected);
    Bindings bindings = ScriptingEnvironmentProvider.create(new ScriptEngineManager(), null, row);
    Object actual = bindings.get("$MEMORY");
    assertNotNull(actual);
    assertThat(actual, is(expected));
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) Row(com.airhacks.enhydrator.in.Row) Bindings(javax.script.Bindings) Test(org.junit.Test)

Example 34 with Bindings

use of javax.script.Bindings in project enhydrator by AdamBien.

the class FilterExpression method execute.

public Boolean execute(Row columns, String expression) {
    Bindings bindings = ScriptingEnvironmentProvider.create(this.manager, this.scriptEngineBindings, columns);
    try {
        this.expressionListener.accept("Executing: " + expression);
        Object result = this.engine.eval(expression, bindings);
        this.expressionListener.accept("Got result: " + result);
        if (!(result instanceof Boolean)) {
            return Boolean.FALSE;
        } else {
            return (Boolean) result;
        }
    } catch (ScriptException ex) {
        throw new IllegalStateException(ex.getMessage(), ex);
    }
}
Also used : ScriptException(javax.script.ScriptException) Bindings(javax.script.Bindings)

Example 35 with Bindings

use of javax.script.Bindings in project midpoint by Evolveum.

the class Jsr223ScriptEvaluator method evaluate.

@Override
public <T, V extends PrismValue> List<V> evaluate(ScriptExpressionEvaluatorType expressionType, ExpressionVariables variables, ItemDefinition outputDefinition, Function<Object, Object> additionalConvertor, ScriptExpressionReturnTypeType suggestedReturnType, ObjectResolver objectResolver, Collection<FunctionLibrary> functions, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException {
    Bindings bindings = convertToBindings(variables, objectResolver, functions, contextDescription, task, result);
    String codeString = expressionType.getCode();
    if (codeString == null) {
        throw new ExpressionEvaluationException("No script code in " + contextDescription);
    }
    boolean allowEmptyValues = false;
    if (expressionType.isAllowEmptyValues() != null) {
        allowEmptyValues = expressionType.isAllowEmptyValues();
    }
    CompiledScript compiledScript = createCompiledScript(codeString, contextDescription);
    Object evalRawResult;
    try {
        InternalMonitor.recordScriptExecution();
        evalRawResult = compiledScript.eval(bindings);
    } catch (Throwable e) {
        throw new ExpressionEvaluationException(e.getMessage() + " in " + contextDescription, e);
    }
    if (outputDefinition == null) {
        // No outputDefinition means "void" return type, we can return right now
        return null;
    }
    QName xsdReturnType = outputDefinition.getTypeName();
    Class<T> javaReturnType = XsdTypeMapper.toJavaType(xsdReturnType);
    if (javaReturnType == null) {
        javaReturnType = prismContext.getSchemaRegistry().getCompileTimeClass(xsdReturnType);
    }
    if (javaReturnType == null) {
        // TODO quick and dirty hack - because this could be because of enums defined in schema extension (MID-2399)
        // ...and enums (xsd:simpleType) are not parsed into ComplexTypeDefinitions
        javaReturnType = (Class) String.class;
    }
    List<V> pvals = new ArrayList<V>();
    // PrismProperty?
    if (evalRawResult instanceof Collection) {
        for (Object evalRawResultElement : (Collection) evalRawResult) {
            T evalResult = convertScalarResult(javaReturnType, additionalConvertor, evalRawResultElement, contextDescription);
            if (allowEmptyValues || !ExpressionUtil.isEmpty(evalResult)) {
                pvals.add((V) ExpressionUtil.convertToPrismValue(evalResult, outputDefinition, contextDescription, prismContext));
            }
        }
    } else if (evalRawResult instanceof PrismProperty<?>) {
        pvals.addAll((Collection<? extends V>) PrismPropertyValue.cloneCollection(((PrismProperty<T>) evalRawResult).getValues()));
    } else {
        T evalResult = convertScalarResult(javaReturnType, additionalConvertor, evalRawResult, contextDescription);
        if (allowEmptyValues || !ExpressionUtil.isEmpty(evalResult)) {
            pvals.add((V) ExpressionUtil.convertToPrismValue(evalResult, outputDefinition, contextDescription, prismContext));
        }
    }
    return pvals;
}
Also used : CompiledScript(javax.script.CompiledScript) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Bindings(javax.script.Bindings) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) Collection(java.util.Collection)

Aggregations

Bindings (javax.script.Bindings)150 SimpleBindings (javax.script.SimpleBindings)77 Test (org.junit.Test)36 ScriptException (javax.script.ScriptException)30 ScriptContext (javax.script.ScriptContext)26 SimpleScriptContext (javax.script.SimpleScriptContext)24 ScriptEngine (javax.script.ScriptEngine)20 SlingBindings (org.apache.sling.api.scripting.SlingBindings)18 Test (org.testng.annotations.Test)17 CompiledScript (javax.script.CompiledScript)14 Resource (org.apache.sling.api.resource.Resource)11 Map (java.util.Map)10 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)10 SlingScriptHelper (org.apache.sling.api.scripting.SlingScriptHelper)10 IOException (java.io.IOException)9 HashMap (java.util.HashMap)9 ScriptEngineManager (javax.script.ScriptEngineManager)9 PrintWriter (java.io.PrintWriter)8 StringWriter (java.io.StringWriter)8 ArrayList (java.util.ArrayList)7