Example usage for org.springframework.expression Expression getExpressionString

List of usage examples for org.springframework.expression Expression getExpressionString

Introduction

In this page you can find the example usage for org.springframework.expression Expression getExpressionString.

Prototype

String getExpressionString();

Source Link

Document

Return the original string used to create this expression (unmodified).

Usage

From source file:de.itsvs.cwtrpc.security.DefaultRpcAuthenticationFailureHandler.java

@Override
public Exception lookupRemoteExceptionFor(HttpServletRequest request, AuthenticationException exception) {
    Expression remoteExceptionExpression = null;
    Exception remoteException = null;

    if (getExceptionExpressionMappings() != null) {
        final Class<? extends AuthenticationException> exceptionClass;

        exceptionClass = exception.getClass();
        for (Map.Entry<Class<? extends AuthenticationException>, Expression> entry : getExceptionExpressionMappings()
                .entrySet()) {//www . j  ava  2 s . c o m
            if (entry.getKey().isAssignableFrom(exceptionClass)) {
                if (log.isDebugEnabled()) {
                    log.debug("Exception mapping for class " + exceptionClass.getName() + " is: "
                            + entry.getValue().getExpressionString());
                }
                remoteExceptionExpression = entry.getValue();
                break;
            }
        }
    }
    if (remoteExceptionExpression == null) {
        if (log.isDebugEnabled()) {
            log.debug("Exception mapping does not contain mapping for class " + exception.getClass().getName()
                    + ", using default: " + getDefaultExceptionExpression().getExpressionString());
        }
        remoteExceptionExpression = getDefaultExceptionExpression();
    }

    try {
        remoteException = remoteExceptionExpression.getValue(createEvaluationContext(request, exception),
                Exception.class);
    } catch (EvaluationException e) {
        log.error("Could not create remote exception from expression: "
                + remoteExceptionExpression.getExpressionString(), e);
        remoteException = null;
    }
    return remoteException;
}

From source file:org.craftercms.security.impl.processors.UrlAccessRestrictionCheckingProcessor.java

/**
 * Matches the request URL against the keys of the {@code restriction} map, which are ANT-style path patterns. If
 * a key matches, the/*  w  w w .jav a 2 s  .c om*/
 * value is interpreted as a Spring EL expression, the expression is executed using an {@link
 * AccessRestrictionExpressionRoot}. with
 * the user profile, as root object, and if it returns true, the processor chain is continued,
 * if not an  {@link AccessDeniedException}
 * is thrown.
 *
 * @param context        the context which holds the current request and other security info pertinent to the
 *                       request
 * @param processorChain the processor chain, used to call the next processor
 * @throws Exception
 */
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain)
        throws Exception {
    if (MapUtils.isNotEmpty(urlRestrictions)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Checking URL access restrictions");
        }

        if (context.getAuthenticationToken() == null) {
            throw new IllegalArgumentException("Request context doesn't contain an authentication token");
        }
        if (context.getAuthenticationToken().getProfile() == null) {
            throw new IllegalArgumentException(
                    "Authentication token of request context doesn't contain a user " + "profile");
        }

        String requestUrl = getRequestUrl(context.getRequest());
        UserProfile profile = context.getAuthenticationToken().getProfile();

        for (Map.Entry<String, Expression> entry : urlRestrictions.entrySet()) {
            String urlPattern = entry.getKey();
            Expression expression = entry.getValue();

            if (pathMatcher.match(urlPattern, requestUrl)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Checking restriction ['" + requestUrl + "' => "
                            + expression.getExpressionString() + "] for user " + profile.getUserName());
                }

                if (isAccessAllowed(profile, expression)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Restriction ['" + requestUrl + "' => " + expression.getExpressionString()
                                + "] evaluated to " + "true for user " + profile.getUserName()
                                + ": access allowed");
                    }

                    break;
                } else {
                    throw new AccessDeniedException("Restriction ['" + requestUrl + "' => "
                            + expression.getExpressionString() + "] evaluated to false for user "
                            + profile.getUserName() + ": access denied");
                }
            }
        }
    }

    processorChain.processRequest(context);
}

From source file:org.craftercms.security.impl.processors.UrlAccessRestrictionCheckingProcessor.java

/**
 * Executes the Spring EL expression using an {@link AccessRestrictionExpressionRoot}, with the user profile,
 * as root object. The/*from  w ww  . j  a va  2  s .  co m*/
 * expression should return a boolean: true if access is allowed, false otherwise.
 */
protected boolean isAccessAllowed(UserProfile profile, Expression expression) {
    Object value = expression.getValue(createExpressionRoot(profile));
    if (!(value instanceof Boolean)) {
        throw new CrafterSecurityException(
                "Expression " + expression.getExpressionString() + " should return a " + "boolean value");
    }

    return (Boolean) value;
}

From source file:org.craftercms.security.processors.impl.UrlAccessRestrictionCheckingProcessor.java

/**
 * Matches the request URL against the keys of the {@code restriction} map, which are ANT-style path patterns. If
 * a key matches, the value is interpreted as a Spring EL expression, the expression is executed, and if it returns
 * true, the processor chain is continued, if not an {@link AccessDeniedException} is thrown.
 *
 * @param context        the context which holds the current request and response
 * @param processorChain the processor chain, used to call the next processor
 *///from  w  ww  .  j ava2s. co m
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain)
        throws Exception {
    Map<String, Expression> urlRestrictions = getUrlRestrictions();

    if (MapUtils.isNotEmpty(urlRestrictions)) {
        HttpServletRequest request = context.getRequest();
        String requestUrl = getRequestUrl(context.getRequest());

        logger.debug("Checking access restrictions for URL {}", requestUrl);

        for (Map.Entry<String, Expression> entry : urlRestrictions.entrySet()) {
            String urlPattern = entry.getKey();
            Expression expression = entry.getValue();

            if (pathMatcher.match(urlPattern, requestUrl)) {
                logger.debug("Checking restriction [{} => {}]", requestUrl, expression.getExpressionString());

                if (isAccessAllowed(request, expression)) {
                    logger.debug("Restriction [{}' => {}] evaluated to true for user: access allowed",
                            requestUrl, expression.getExpressionString());

                    break;
                } else {
                    throw new AccessDeniedException(
                            "Restriction ['" + requestUrl + "' => " + expression.getExpressionString()
                                    + "] evaluated to false " + "for user: access denied");
                }
            }
        }
    }

    processorChain.processRequest(context);
}

From source file:org.springframework.batch.integration.samples.payments.util.SpringIntegrationUtils.java

/**
 * Helper Method to dynamically determine and display input and output
 * directories as defined in the Spring Integration context.
 *
 * @param context Spring Application Context
 *//*from  w  w w  . j a  v a2s.c o  m*/
public static void displayDirectories(final ApplicationContext context) {

    final Map<String, FileReadingMessageSource> fileReadingMessageSources = context
            .getBeansOfType(FileReadingMessageSource.class);
    final List<String> inputDirectories = new ArrayList<String>();

    for (final FileReadingMessageSource messageHandler : fileReadingMessageSources.values()) {
        final File inDir = (File) new DirectFieldAccessor(messageHandler).getPropertyValue("directory");
        inputDirectories.add(inDir.getAbsolutePath());
    }

    final Map<String, FileWritingMessageHandler> fileWritingMessageHandlers = context
            .getBeansOfType(FileWritingMessageHandler.class);
    final List<String> outputDirectories = new ArrayList<String>();

    for (final FileWritingMessageHandler messageHandler : fileWritingMessageHandlers.values()) {
        final Expression outDir = (Expression) new DirectFieldAccessor(messageHandler)
                .getPropertyValue("destinationDirectoryExpression");
        outputDirectories.add(outDir.getExpressionString());
    }

    final StringBuilder stringBuilder = new StringBuilder();

    for (final String inputDirectory : inputDirectories) {
        stringBuilder.append("\n    Input directory is : '" + inputDirectory + "'");
    }

    for (final String outputDirectory : outputDirectories) {
        stringBuilder.append("\n    Output directory is: '" + outputDirectory + "'");
    }

    stringBuilder.append("\n\n=========================================================");

    logger.info(stringBuilder.toString());

}

From source file:org.springframework.cloud.stream.binder.ExpressionSerializer.java

@Override
public void serialize(Expression expression, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
    if (expression != null) {
        jsonGenerator.writeString(expression.getExpressionString());
    }/* www  .j av a 2 s . com*/
}

From source file:org.springframework.integration.handler.support.MessagingMethodInvokerHelper.java

@SuppressWarnings("unchecked")
private T invokeHandlerMethod(HandlerMethod handlerMethod, ParametersWrapper parameters) throws Exception {
    try {/*from   w w w .  j av  a 2s.  co m*/
        return (T) handlerMethod.invoke(parameters);
    } catch (MethodArgumentResolutionException | MessageConversionException | IllegalStateException e) {
        if (e instanceof MessageConversionException) {
            if (e.getCause() instanceof ConversionFailedException
                    && !(e.getCause().getCause() instanceof ConverterNotFoundException)) {
                throw e;
            }
        } else if (e instanceof IllegalStateException) {
            if (!(e.getCause() instanceof IllegalArgumentException)
                    || !e.getStackTrace()[0].getClassName().equals(InvocableHandlerMethod.class.getName())
                    || (!"argument type mismatch".equals(e.getCause().getMessage()) &&
                    // JVM generates GeneratedMethodAccessor### after several calls with less error checking
                            !e.getCause().getMessage().startsWith("java.lang.ClassCastException@"))) {
                throw e;
            }
        }

        Expression expression = handlerMethod.expression;

        if (++handlerMethod.failedAttempts >= FAILED_ATTEMPTS_THRESHOLD) {
            handlerMethod.spelOnly = true;
            if (logger.isInfoEnabled()) {
                logger.info("Failed to invoke [ " + handlerMethod.invocableHandlerMethod
                        + "] with provided arguments [ " + parameters + " ]. \n"
                        + "Falling back to SpEL invocation for expression [ " + expression.getExpressionString()
                        + " ]");
            }
        }

        return invokeExpression(expression, parameters);
    }
}

From source file:org.springframework.integration.samples.zip.SpringIntegrationUtils.java

/**
 * Helper Method to dynamically determine and display input and output
 * directories as defined in the Spring Integration context.
 *
 * @param context Spring Application Context
 *//*from   w w  w  . ja  v  a  2  s.  c o m*/
public static void displayDirectories(final ApplicationContext context) {

    final Map<String, FileReadingMessageSource> fileReadingMessageSources = context
            .getBeansOfType(FileReadingMessageSource.class);

    final List<String> inputDirectories = new ArrayList<String>();

    for (FileReadingMessageSource source : fileReadingMessageSources.values()) {
        final File inDir = (File) new DirectFieldAccessor(source).getPropertyValue("directory");
        inputDirectories.add(inDir.getAbsolutePath());
    }

    final Map<String, FileWritingMessageHandler> fileWritingMessageHandlers = context
            .getBeansOfType(FileWritingMessageHandler.class);

    final List<String> outputDirectories = new ArrayList<String>();

    for (final FileWritingMessageHandler messageHandler : fileWritingMessageHandlers.values()) {
        final Expression outDir = (Expression) new DirectFieldAccessor(messageHandler)
                .getPropertyValue("destinationDirectoryExpression");
        outputDirectories.add(outDir.getExpressionString());
    }

    final StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append("\n=========================================================");
    stringBuilder.append("\n");

    for (final String inputDirectory : inputDirectories) {
        stringBuilder.append("\n    Intput directory is: '" + inputDirectory + "'");
    }

    for (final String outputDirectory : outputDirectories) {
        stringBuilder.append("\n    Output directory is: '" + outputDirectory + "'");
    }

    stringBuilder.append("\n\n=========================================================");

    logger.info(stringBuilder.toString());

}

From source file:org.springframework.integration.util.AbstractExpressionEvaluator.java

protected <T> T evaluateExpression(Expression expression, Message<?> message, Class<T> expectedType) {
    try {// ww w  . j  av  a 2  s .co m
        return evaluateExpression(expression, (Object) message, expectedType);
    } catch (EvaluationException e) {
        Throwable cause = e.getCause();
        if (this.logger.isDebugEnabled()) {
            logger.debug("SpEL Expression evaluation failed with EvaluationException.", e);
        }
        throw new MessageHandlingException(message,
                "Expression evaluation failed: " + expression.getExpressionString(), cause == null ? e : cause);
    } catch (Exception e) {
        if (this.logger.isDebugEnabled()) {
            logger.debug("SpEL Expression evaluation failed with Exception." + e);
        }
        throw new MessageHandlingException(message,
                "Expression evaluation failed: " + expression.getExpressionString(), e);
    }
}

From source file:org.springframework.integration.xml.transformer.XsltPayloadTransformer.java

private Transformer buildTransformer(Message<?> message) throws TransformerException {
    // process individual mappings
    Transformer transformer = this.templates.newTransformer();
    if (this.xslParameterMappings != null) {
        for (String parameterName : this.xslParameterMappings.keySet()) {
            Expression expression = this.xslParameterMappings.get(parameterName);
            try {
                Object value = expression.getValue(this.evaluationContext, message);
                transformer.setParameter(parameterName, value);
            } catch (Exception e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Evaluation of header expression '" + expression.getExpressionString()
                            + "' failed. The XSLT parameter '" + parameterName + "' will be skipped.");
                }/*from   w w  w  .j  a v  a2  s . c  o m*/
            }
        }
    }
    // process xslt-parameter-headers
    MessageHeaders headers = message.getHeaders();
    if (!ObjectUtils.isEmpty(this.xsltParamHeaders)) {
        for (String headerName : headers.keySet()) {
            if (PatternMatchUtils.simpleMatch(this.xsltParamHeaders, headerName)) {
                transformer.setParameter(headerName, headers.get(headerName));
            }
        }
    }
    return transformer;
}