Example usage for org.springframework.util ObjectUtils containsElement

List of usage examples for org.springframework.util ObjectUtils containsElement

Introduction

In this page you can find the example usage for org.springframework.util ObjectUtils containsElement.

Prototype

public static boolean containsElement(@Nullable Object[] array, Object element) 

Source Link

Document

Check whether the given array contains the given element.

Usage

From source file:jp.xet.uncommons.web.env.RemoteEnvironmentProfile.java

public static EnvironmentProfile toEnvironmentProfile(String[] activeProfiles) {
    for (RemoteEnvironmentProfile p : RemoteEnvironmentProfile.values()) {
        if (ObjectUtils.containsElement(activeProfiles, p.toString())) {
            return p;
        }// ww w  .  java2 s.c  o  m
    }
    if (ObjectUtils.isEmpty(activeProfiles)) {
        return DEVELOPMENT;
    } else {
        return new LocalEnvironmentProfile(activeProfiles[0]);
    }
}

From source file:lodsve.core.condition.OnWebApplicationCondition.java

private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata) {

    if (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) {
        return ConditionOutcome.noMatch("web application classes not found");
    }/*from www . jav a  2 s  . c om*/

    if (context.getBeanFactory() != null) {
        String[] scopes = context.getBeanFactory().getRegisteredScopeNames();
        if (ObjectUtils.containsElement(scopes, "session")) {
            return ConditionOutcome.match("found web application 'session' scope");
        }
    }

    if (context.getEnvironment() instanceof StandardServletEnvironment) {
        return ConditionOutcome.match("found web application StandardServletEnvironment");
    }

    if (context.getResourceLoader() instanceof WebApplicationContext) {
        return ConditionOutcome.match("found web application WebApplicationContext");
    }

    return ConditionOutcome.noMatch("not a web application");
}

From source file:jp.xet.uncommons.wicket.utils.ErrorReportRequestCycleListener.java

@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
    if (ex instanceof PageExpiredException || ex instanceof StalePageException) {
        return null;
    }//ww w.j av  a2  s  .c  om

    if (ex instanceof WicketRuntimeException) {
        Throwable rootCause = getRootCause(ex);
        if (rootCause == null) {
            rootCause = ex;
        }

        String environment = loadEnvironment();
        if (enabledEnvironments == null || environment == null
                || ObjectUtils.containsElement(enabledEnvironments, environment)) {
            String type = rootCause.getClass().getSimpleName();
            String message = rootCause.getMessage();
            String subject = MessageFormat.format(subjectPattern, environment, type, message);

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(from);
            mailMessage.setTo(to);
            mailMessage.setSubject(subject);
            mailMessage.setText(getStackTrace(ex));
            try {
                logger.debug("sending exception report mail...");
                mailSender.send(mailMessage);
                logger.debug("success to send exception report mail");
            } catch (MailException e) {
                logger.error("failed to send exception report mail", e);
            }
        } else {
            logger.debug(
                    "exception report mail was not sent, "
                            + "because enabledEnvironments{} does not contain environment[{}]",
                    new Object[] { Arrays.toString(enabledEnvironments), environment });
        }
    }
    return null;
}

From source file:org.springframework.cloud.stream.binding.BinderAwareChannelResolver.java

@SuppressWarnings("unchecked")
@Override/*  w  w w .  ja v  a 2  s .  c om*/
public MessageChannel resolveDestination(String channelName) {
    try {
        return super.resolveDestination(channelName);
    } catch (DestinationResolutionException e) {
        // intentionally empty; will check again while holding the monitor
    }
    synchronized (this) {
        BindingServiceProperties bindingServiceProperties = this.bindingService.getBindingServiceProperties();
        String[] dynamicDestinations = bindingServiceProperties.getDynamicDestinations();
        boolean dynamicAllowed = ObjectUtils.isEmpty(dynamicDestinations)
                || ObjectUtils.containsElement(dynamicDestinations, channelName);
        try {
            return super.resolveDestination(channelName);
        } catch (DestinationResolutionException e) {
            if (!dynamicAllowed) {
                throw e;
            }
        }

        MessageChannel channel = this.bindingTargetFactory.createOutput(channelName);
        this.beanFactory.registerSingleton(channelName, channel);

        //TODO: Investigate if the following call is necessary.
        //initializeBean call on the next line also calling the addMatchingInterceptors method in GlobalChannelInterceptorProcessor
        //this.instrumentChannelWithGlobalInterceptors(channel, channelName);

        channel = (MessageChannel) this.beanFactory.initializeBean(channel, channelName);
        if (this.newBindingCallback != null) {
            ProducerProperties producerProperties = bindingServiceProperties.getProducerProperties(channelName);
            Object extendedProducerProperties = this.bindingService.getExtendedProducerProperties(channel,
                    channelName);
            this.newBindingCallback.configure(channelName, channel, producerProperties,
                    extendedProducerProperties);
            bindingServiceProperties.updateProducerProperties(channelName, producerProperties);
        }
        Binding<MessageChannel> binding = this.bindingService.bindProducer(channel, channelName);
        this.dynamicDestinationsBindable.addOutputBinding(channelName, binding);

        return channel;
    }
}

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

private Map<String, Map<Class<?>, HandlerMethod>> findHandlerMethodsForTarget(final Object targetObject,
        final Class<? extends Annotation> annotationType, final String methodNameToUse,
        final boolean requiresReply) {

    Map<String, Map<Class<?>, HandlerMethod>> handlerMethods = new HashMap<>();

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<>();
    final Map<Class<?>, HandlerMethod> candidateMessageMethods = new HashMap<>();
    final Map<Class<?>, HandlerMethod> fallbackMethods = new HashMap<>();
    final Map<Class<?>, HandlerMethod> fallbackMessageMethods = new HashMap<>();
    final AtomicReference<Class<?>> ambiguousFallbackType = new AtomicReference<>();
    final AtomicReference<Class<?>> ambiguousFallbackMessageGenericType = new AtomicReference<>();
    final Class<?> targetClass = getTargetClass(targetObject);

    final String methodName;

    if (methodNameToUse == null) {
        if (Function.class.isAssignableFrom(targetClass)) {
            methodName = "apply";
        } else if (Consumer.class.isAssignableFrom(targetClass)) {
            methodName = "accept";
        } else {/*www .  java 2  s . com*/
            methodName = null;
        }
    } else {
        methodName = methodNameToUse;
    }

    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, method1 -> {
        boolean matchesAnnotation = false;
        if (method1.isBridge()) {
            return;
        }
        if (isMethodDefinedOnObjectClass(method1)) {
            return;
        }
        if (method1.getDeclaringClass().equals(Proxy.class)) {
            return;
        }
        if (annotationType != null && AnnotationUtils.findAnnotation(method1, annotationType) != null) {
            matchesAnnotation = true;
        } else if (!Modifier.isPublic(method1.getModifiers())) {
            return;
        }
        if (requiresReply && void.class.equals(method1.getReturnType())) {
            return;
        }
        if (methodName != null && !methodName.equals(method1.getName())) {
            return;
        }
        if (methodName == null && ObjectUtils.containsElement(new String[] { "start", "stop", "isRunning" },
                method1.getName())) {
            return;
        }
        HandlerMethod handlerMethod1;
        try {
            method1 = AopUtils.selectInvocableMethod(method1,
                    org.springframework.util.ClassUtils.getUserClass(targetObject));
            InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory
                    .createInvocableHandlerMethod(targetObject, method1);
            handlerMethod1 = new HandlerMethod(invocableHandlerMethod, this.canProcessMessageList);
            checkSpelInvokerRequired(targetClass, method1, handlerMethod1);
        } catch (IneligibleMethodException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Method [" + method1 + "] is not eligible for Message handling " + e.getMessage()
                        + ".");
            }
            return;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Method [" + method1 + "] is not eligible for Message handling.", e);
            }
            return;
        }
        if (AnnotationUtils.getAnnotation(method1, Default.class) != null) {
            Assert.state(this.defaultHandlerMethod == null,
                    () -> "Only one method can be @Default, but there are more for: " + targetObject);
            this.defaultHandlerMethod = handlerMethod1;
        }
        Class<?> targetParameterType = handlerMethod1.getTargetParameterType();
        if (matchesAnnotation || annotationType == null) {
            if (handlerMethod1.isMessageMethod()) {
                if (candidateMessageMethods.containsKey(targetParameterType)) {
                    throw new IllegalArgumentException("Found more than one method match for type "
                            + "[Message<" + targetParameterType + ">]");
                }
                candidateMessageMethods.put(targetParameterType, handlerMethod1);
            } else {
                if (candidateMethods.containsKey(targetParameterType)) {
                    String exceptionMessage = "Found more than one method match for ";
                    if (Void.class.equals(targetParameterType)) {
                        exceptionMessage += "empty parameter for 'payload'";
                    } else {
                        exceptionMessage += "type [" + targetParameterType + "]";
                    }
                    throw new IllegalArgumentException(exceptionMessage);
                }
                candidateMethods.put(targetParameterType, handlerMethod1);
            }
        } else {
            if (handlerMethod1.isMessageMethod()) {
                if (fallbackMessageMethods.containsKey(targetParameterType)) {
                    // we need to check for duplicate type matches,
                    // but only if we end up falling back
                    // and we'll only keep track of the first one
                    ambiguousFallbackMessageGenericType.compareAndSet(null, targetParameterType);
                }
                fallbackMessageMethods.put(targetParameterType, handlerMethod1);
            } else {
                if (fallbackMethods.containsKey(targetParameterType)) {
                    // we need to check for duplicate type matches,
                    // but only if we end up falling back
                    // and we'll only keep track of the first one
                    ambiguousFallbackType.compareAndSet(null, targetParameterType);
                }
                fallbackMethods.put(targetParameterType, handlerMethod1);
            }
        }
    }, methodFilter);

    if (candidateMethods.isEmpty() && candidateMessageMethods.isEmpty() && fallbackMethods.isEmpty()
            && fallbackMessageMethods.isEmpty()) {
        findSingleSpecifMethodOnInterfacesIfProxy(targetObject, methodName, candidateMessageMethods,
                candidateMethods);
    }

    if (!candidateMethods.isEmpty() || !candidateMessageMethods.isEmpty()) {
        handlerMethods.put(CANDIDATE_METHODS, candidateMethods);
        handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods);
        return handlerMethods;
    }
    if ((ambiguousFallbackType.get() != null || ambiguousFallbackMessageGenericType.get() != null)
            && ServiceActivator.class.equals(annotationType)) {
        /*
         * When there are ambiguous fallback methods,
         * a Service Activator can finally fallback to RequestReplyExchanger.exchange(m).
         * Ambiguous means > 1 method that takes the same payload type, or > 1 method
         * that takes a Message with the same generic type.
         */
        List<Method> frameworkMethods = new ArrayList<>();
        Class<?>[] allInterfaces = org.springframework.util.ClassUtils.getAllInterfacesForClass(targetClass);
        for (Class<?> iface : allInterfaces) {
            try {
                if ("org.springframework.integration.gateway.RequestReplyExchanger".equals(iface.getName())) {
                    frameworkMethods.add(targetClass.getMethod("exchange", Message.class));
                    if (logger.isDebugEnabled()) {
                        logger.debug(targetObject.getClass()
                                + ": Ambiguous fallback methods; using RequestReplyExchanger.exchange()");
                    }
                }
            } catch (Exception e) {
                // should never happen (but would fall through to errors below)
            }
        }
        if (frameworkMethods.size() == 1) {
            Method method = org.springframework.util.ClassUtils.getMostSpecificMethod(frameworkMethods.get(0),
                    targetObject.getClass());
            InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory
                    .createInvocableHandlerMethod(targetObject, method);
            HandlerMethod handlerMethod = new HandlerMethod(invocableHandlerMethod, this.canProcessMessageList);
            checkSpelInvokerRequired(targetClass, method, handlerMethod);
            handlerMethods.put(CANDIDATE_METHODS, Collections.singletonMap(Object.class, handlerMethod));
            handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods);
            return handlerMethods;
        }
    }

    Assert.state(!fallbackMethods.isEmpty() || !fallbackMessageMethods.isEmpty(), "Target object of type ["
            + this.targetObject.getClass() + "] has no eligible methods for handling Messages.");

    Assert.isNull(ambiguousFallbackType.get(), "Found ambiguous parameter type [" + ambiguousFallbackType
            + "] for method match: " + fallbackMethods.values());
    Assert.isNull(ambiguousFallbackMessageGenericType.get(), "Found ambiguous parameter type ["
            + ambiguousFallbackMessageGenericType + "] for method match: " + fallbackMethods.values());

    handlerMethods.put(CANDIDATE_METHODS, fallbackMethods);
    handlerMethods.put(CANDIDATE_MESSAGE_METHODS, fallbackMessageMethods);
    return handlerMethods;
}

From source file:org.springframework.integration.http.support.DefaultHttpHeaderMapper.java

/**
 * Map from an HttpHeaders instance to integration MessageHeaders.
 * Depending on which type of adapter is using this mapper, the HttpHeaders might be
 * from an HTTP request (inbound adapter) or from an HTTP response (outbound adapter).
 *///w w w  .  ja  v  a 2  s.c  o  m
public Map<String, Object> toHeaders(HttpHeaders source) {
    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format("inboundHeaderNames={0}",
                CollectionUtils.arrayToList(inboundHeaderNames)));
    }
    Map<String, Object> target = new HashMap<String, Object>();
    Set<String> headerNames = source.keySet();
    for (String name : headerNames) {
        if (this.shouldMapInboundHeader(name)) {
            if (!ObjectUtils.containsElement(HTTP_REQUEST_HEADER_NAMES, name)
                    && !ObjectUtils.containsElement(HTTP_RESPONSE_HEADER_NAMES, name)) {
                String prefixedName = StringUtils.startsWithIgnoreCase(name, this.userDefinedHeaderPrefix)
                        ? name
                        : this.userDefinedHeaderPrefix + name;
                Object value = source.containsKey(prefixedName) ? this.getHttpHeader(source, prefixedName)
                        : this.getHttpHeader(source, name);
                if (value != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(MessageFormat.format("setting headerName=[{0}], value={1}", name, value));
                    }
                    this.setMessageHeader(target, name, value);
                }
            } else {
                Object value = this.getHttpHeader(source, name);
                if (value != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(MessageFormat.format("setting headerName=[{0}], value={1}", name, value));
                    }
                    this.setMessageHeader(target, name, value);
                }
            }
        }
    }
    return target;
}

From source file:org.springframework.integration.mapping.AbstractHeaderMapper.java

private boolean shouldMapHeader(String headerName, List<String> patterns) {
    if (!StringUtils.hasText(headerName) || ObjectUtils.containsElement(TRANSIENT_HEADER_NAMES, headerName)) {
        return false;
    }/* ww  w .  jav a  2s . com*/
    if (patterns != null && patterns.size() > 0) {
        for (String pattern : patterns) {
            if (PatternMatchUtils.simpleMatch(pattern.toLowerCase(), headerName.toLowerCase())) {
                if (logger.isDebugEnabled()) {
                    logger.debug(MessageFormat.format("headerName=[{0}] WILL be mapped, matched pattern={1}",
                            headerName, pattern));
                }
                return true;
            } else if (STANDARD_REQUEST_HEADER_NAME_PATTERN.equals(pattern)
                    && this.containsElementIgnoreCase(this.getStandardRequestHeaderNames(), headerName)) {
                if (logger.isDebugEnabled()) {
                    logger.debug(MessageFormat.format("headerName=[{0}] WILL be mapped, matched pattern={1}",
                            headerName, pattern));
                }
                return true;
            } else if (STANDARD_REPLY_HEADER_NAME_PATTERN.equals(pattern)
                    && this.containsElementIgnoreCase(this.getStandardReplyHeaderNames(), headerName)) {
                if (logger.isDebugEnabled()) {
                    logger.debug(MessageFormat.format("headerName=[{0}] WILL be mapped, matched pattern={1}",
                            headerName, pattern));
                }
                return true;
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format("headerName=[{0}] WILL NOT be mapped", headerName));
    }
    return false;
}

From source file:org.springframework.web.servlet.support.DefaultFlashMapManager.java

/**
 * Whether the given FlashMap matches the current request.
 * The default implementation uses the target request path and query params 
 * saved in the FlashMap.//from   w  ww.  j av  a 2 s .  c  om
 */
protected boolean isFlashMapForRequest(FlashMap flashMap, HttpServletRequest request) {
    if (flashMap.getTargetRequestPath() != null) {
        String requestUri = this.urlPathHelper.getOriginatingRequestUri(request);
        if (!requestUri.equals(flashMap.getTargetRequestPath())
                && !requestUri.equals(flashMap.getTargetRequestPath() + "/")) {
            return false;
        }
    }
    MultiValueMap<String, String> targetParams = flashMap.getTargetRequestParams();
    for (String paramName : targetParams.keySet()) {
        for (String targetValue : targetParams.get(paramName)) {
            if (!ObjectUtils.containsElement(request.getParameterValues(paramName), targetValue)) {
                return false;
            }
        }
    }
    return true;
}

From source file:org.springframework.yarn.test.context.YarnClusterInjectingAnnotationConfigContextLoader.java

@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {

    String[] activeProfiles = context.getEnvironment().getActiveProfiles();
    log.info("Active profiles: " + StringUtils.arrayToCommaDelimitedString(activeProfiles));

    // let parent do its magic
    super.loadBeanDefinitions(context, mergedConfig);
    if (!ObjectUtils.containsElement(activeProfiles, YarnTestSystemConstants.PROFILE_ID_NOMINICLUSTER)) {
        YarnClusterInjectUtils.handleClusterInject(context, mergedConfig);
    }/*from   w  w w  .  j  av a  2s.c o  m*/
}