Example usage for org.springframework.expression Expression getValue

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

Introduction

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

Prototype

@Nullable
<T> T getValue(EvaluationContext context, @Nullable Class<T> desiredResultType) throws EvaluationException;

Source Link

Document

Evaluate the expression in a specified context which can resolve references to properties, methods, types, etc.

Usage

From source file:com.vedri.mtp.frontend.support.stomp.DefaultSubscriptionRegistry.java

private MultiValueMap<String, String> filterSubscriptions(MultiValueMap<String, String> allMatches,
        Message<?> message) {/*from w w  w  .j av a 2 s  .c o  m*/

    if (!this.selectorHeaderInUse) {
        return allMatches;
    }
    EvaluationContext context = null;
    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(allMatches.size());
    for (String sessionId : allMatches.keySet()) {
        for (String subId : allMatches.get(sessionId)) {
            SessionSubscriptionInfo info = this.subscriptionRegistry.getSubscriptions(sessionId);
            if (info == null) {
                continue;
            }
            Subscription sub = info.getSubscription(subId);
            if (sub == null) {
                continue;
            }
            Expression expression = sub.getSelectorExpression();
            if (expression == null) {
                result.add(sessionId, subId);
                continue;
            }
            if (context == null) {
                context = new StandardEvaluationContext(message);
                context.getPropertyAccessors().add(new SimpMessageHeaderPropertyAccessor());
            }
            try {
                if (expression.getValue(context, boolean.class)) {
                    result.add(sessionId, subId);
                }
            } catch (SpelEvaluationException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to evaluate selector: " + ex.getMessage());
                }
            } catch (Throwable ex) {
                logger.debug("Failed to evaluate selector", ex);
            }
        }
    }
    return result;
}

From source file:fr.xebia.management.statistics.ProfileAspect.java

@Around(value = "execution(* *(..)) && @annotation(profiled)", argNames = "pjp,profiled")
public Object profileInvocation(ProceedingJoinPoint pjp, Profiled profiled) throws Throwable {

    logger.trace("> profileInvocation({},{}", pjp, profiled);

    MethodSignature jointPointSignature = (MethodSignature) pjp.getStaticPart().getSignature();

    // COMPUTE SERVICE STATISTICS NAME
    Expression nameAsExpression = profiledMethodNameAsExpressionByMethod.get(jointPointSignature.getMethod());
    if (nameAsExpression == null) {
        if (StringUtils.hasLength(profiled.name())) {
            String nameAsStringExpression = profiled.name();
            nameAsExpression = expressionParser.parseExpression(nameAsStringExpression, parserContext);
        } else {/*from   w  w  w . j  a v  a 2s  . c o  m*/
            String fullyQualifiedMethodName = getFullyQualifiedMethodName(//
                    jointPointSignature.getDeclaringTypeName(), //
                    jointPointSignature.getName(), //
                    this.classNameStyle);
            nameAsExpression = new LiteralExpression(fullyQualifiedMethodName);
        }
    }

    String serviceStatisticsName;
    if (nameAsExpression instanceof LiteralExpression) {
        // Optimization : prevent useless objects instantiations
        serviceStatisticsName = nameAsExpression.getExpressionString();
    } else {
        serviceStatisticsName = nameAsExpression.getValue(new RootObject(pjp), String.class);
    }

    // LOOKUP SERVICE STATISTICS
    ServiceStatistics serviceStatistics = serviceStatisticsByName.get(serviceStatisticsName);

    if (serviceStatistics == null) {
        // INSTIANCIATE NEW SERVICE STATISTICS
        ServiceStatistics newServiceStatistics = new ServiceStatistics(//
                new ObjectName(this.jmxDomain + ":type=ServiceStatistics,name=" + serviceStatisticsName), //
                profiled.businessExceptionsTypes(), profiled.communicationExceptionsTypes());

        newServiceStatistics.setSlowInvocationThresholdInMillis(profiled.slowInvocationThresholdInMillis());
        newServiceStatistics
                .setVerySlowInvocationThresholdInMillis(profiled.verySlowInvocationThresholdInMillis());
        int maxActive;
        if (StringUtils.hasLength(profiled.maxActiveExpression())) {
            maxActive = expressionParser.parseExpression(profiled.maxActiveExpression(), parserContext)
                    .getValue(new RootObject(pjp), Integer.class);
        } else {
            maxActive = profiled.maxActive();
        }
        newServiceStatistics.setMaxActive(maxActive);
        newServiceStatistics.setMaxActiveSemaphoreAcquisitionMaxTimeInNanos(TimeUnit.NANOSECONDS
                .convert(profiled.maxActiveSemaphoreAcquisitionMaxTimeInMillis(), TimeUnit.MILLISECONDS));

        ServiceStatistics previousServiceStatistics = serviceStatisticsByName.putIfAbsent(serviceStatisticsName,
                newServiceStatistics);
        if (previousServiceStatistics == null) {
            serviceStatistics = newServiceStatistics;
            mbeanExporter.registerManagedResource(serviceStatistics);
        } else {
            serviceStatistics = previousServiceStatistics;
        }
    }

    // INVOKE AND PROFILE INVOCATION
    long nanosBefore = System.nanoTime();

    Semaphore semaphore = serviceStatistics.getMaxActiveSemaphore();
    if (semaphore != null) {
        boolean acquired = semaphore.tryAcquire(
                serviceStatistics.getMaxActiveSemaphoreAcquisitionMaxTimeInNanos(), TimeUnit.NANOSECONDS);
        if (!acquired) {
            serviceStatistics.incrementServiceUnavailableExceptionCount();
            throw new ServiceUnavailableException("Service '" + serviceStatisticsName + "' is unavailable: "
                    + serviceStatistics.getCurrentActive() + " invocations of are currently running");
        }
    }
    serviceStatistics.incrementCurrentActiveCount();
    try {

        Object returned = pjp.proceed();

        return returned;
    } catch (Throwable t) {
        serviceStatistics.incrementExceptionCount(t);
        throw t;
    } finally {
        if (semaphore != null) {
            semaphore.release();
        }
        serviceStatistics.decrementCurrentActiveCount();
        long deltaInNanos = System.nanoTime() - nanosBefore;
        serviceStatistics.incrementInvocationCounterAndTotalDurationWithNanos(deltaInNanos);
        if (logger.isDebugEnabled()) {
            logger.debug("< profileInvocation({}): {}ns", serviceStatisticsName, deltaInNanos);
        }
    }
}

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()) {//from   w  w  w.j  a v a2s.  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:it.geosolutions.geoserver.sira.security.expression.ExpressionRuleEngine.java

/**
 *
 * @param expressionString/*w w w .j a  va2s.c o m*/
 * @param expectedResultType
 * @return
 */
private <T> T evaluateExpression(String expressionString, Class<T> expectedResultType) {
    final Expression expression = this.parser.parseExpression(expressionString, getTemplateExpression());

    return expression.getValue(this.evalContext, expectedResultType);
}

From source file:org.apereo.portal.portlet.PortletSpELServiceImpl.java

@Override
public <T> T getValue(String expressionString, PortletRequest request, Class<T> desiredResultType) {
    final Expression expression = parseExpression(expressionString);
    final EvaluationContext evaluationContext = getEvaluationContext(request);
    return expression.getValue(evaluationContext, desiredResultType);
}

From source file:org.apereo.portal.portlets.backgroundpreference.RoleBasedBackgroundSetSelectionStrategy.java

private String evaluateImagePath(String pathBeforeProcessing) {
    final Expression x = portalSpELService.parseExpression(pathBeforeProcessing,
            PortalSpELServiceImpl.TemplateParserContext.INSTANCE);
    final String rslt = x.getValue(evaluationContext, String.class);
    return rslt;/*from   www . j av  a  2 s  . com*/
}

From source file:org.apereo.portal.spring.spel.PortalSpELServiceImpl.java

@Override
public <T> T getValue(Expression expression, WebRequest request, Class<T> desiredResultType) {
    final EvaluationContext evaluationContext = this.getEvaluationContext(request);
    return expression.getValue(evaluationContext, desiredResultType);
}

From source file:org.apereo.portal.spring.spel.PortalSpELServiceImpl.java

@Override
public String getValue(String expressionString, Object spelEnvironment) {
    final StandardEvaluationContext context = new StandardEvaluationContext(spelEnvironment);
    context.setBeanResolver(this.beanResolver);
    final Expression expression = this.parseCachedExpression(expressionString, TemplateParserContext.INSTANCE);
    return expression.getValue(context, String.class);
}

From source file:org.finra.dm.app.security.SecurityHelper.java

/**
 * Checks whether security is enabled based on SpEL expression defined in environment.
 * /*  w  w w. j  a v a  2s.  c o  m*/
 * @param request {@link HttpServletRequest} to determine whether security is enabled.
 * @return true if security is enabled, false if disabled.
 */
public boolean isSecurityEnabled(HttpServletRequest request) {
    Boolean isSecurityEnabled = true;

    String enableSecuritySpelExpression = configurationHelper
            .getProperty(ConfigurationValue.SECURITY_ENABLED_SPEL_EXPRESSION);

    if (StringUtils.isNotBlank(enableSecuritySpelExpression)) {
        EvaluationContext evaluationContext = new StandardEvaluationContext();
        evaluationContext.setVariable("request", request);

        Expression expression = expressionParser.parseExpression(enableSecuritySpelExpression);

        isSecurityEnabled = expression.getValue(evaluationContext, Boolean.class);
    }

    return isSecurityEnabled;
}

From source file:org.kaaproject.kaa.server.admin.services.KaaAdminServiceImpl.java

@Override
public boolean testProfileFilter(RecordField endpointProfile, RecordField serverProfile, String filterBody)
        throws KaaAdminServiceException {
    checkAuthority(KaaAuthorityDto.TENANT_DEVELOPER, KaaAuthorityDto.TENANT_USER);
    try {//from   w ww .  jav a 2  s .  c  o m
        GenericRecord endpointProfileRecord = null;
        GenericRecord serverProfileRecord = null;
        try {
            if (endpointProfile != null) {
                endpointProfileRecord = FormAvroConverter.createGenericRecordFromRecordField(endpointProfile);
            }
            if (serverProfile != null) {
                serverProfileRecord = FormAvroConverter.createGenericRecordFromRecordField(serverProfile);
            }
        } catch (Exception e) {
            throw Utils.handleException(e);
        }
        try {
            Expression expression = new SpelExpressionParser().parseExpression(filterBody);
            StandardEvaluationContext evaluationContext;
            if (endpointProfileRecord != null) {
                evaluationContext = new StandardEvaluationContext(endpointProfileRecord);
                evaluationContext.setVariable(DefaultFilterEvaluator.CLIENT_PROFILE_VARIABLE_NAME,
                        endpointProfileRecord);
            } else {
                evaluationContext = new StandardEvaluationContext();
            }
            evaluationContext.addPropertyAccessor(new GenericRecordPropertyAccessor());
            evaluationContext.setVariable(DefaultFilterEvaluator.EP_KEYHASH_VARIABLE_NAME, "test");
            if (serverProfileRecord != null) {
                evaluationContext.setVariable(DefaultFilterEvaluator.SERVER_PROFILE_VARIABLE_NAME,
                        serverProfileRecord);
            }
            return expression.getValue(evaluationContext, Boolean.class);
        } catch (Exception e) {
            throw new KaaAdminServiceException("Invalid profile filter: " + e.getMessage(), e,
                    ServiceErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}