Example usage for org.springframework.util Assert isNull

List of usage examples for org.springframework.util Assert isNull

Introduction

In this page you can find the example usage for org.springframework.util Assert isNull.

Prototype

public static void isNull(@Nullable Object object, Supplier<String> messageSupplier) 

Source Link

Document

Assert that an object is null .

Usage

From source file:org.springframework.integration.aws.s3.AmazonS3ObjectBuilder.java

/**
 * Sets the file which is to be read for uploading into S3
 * @param file/* www.  j  a v  a  2 s. c o  m*/
 */
public AmazonS3ObjectBuilder fromFile(File file) {
    Assert.notNull(file, "null 'file' object provided");
    Assert.isNull(in, "Cannot instantiate using both the InputStream and File");
    Assert.isTrue(file.exists(), "Provided File location \"" + file.getAbsolutePath() + "\" is invalid");
    Assert.isTrue(!file.isDirectory(), "Provided File location \"" + file.getAbsolutePath()
            + "\" is a directory path, please provide a valid file location");
    this.file = file;
    return this;
}

From source file:org.springframework.integration.aws.s3.AmazonS3ObjectBuilder.java

/**
 * Sets an InputStream from which the data to be uploaded to S3 will be read
 * @param in The provided {@link InputStream} must not be null
 *//*www  . j  a v  a  2s .  c o m*/
public AmazonS3ObjectBuilder fromInputStream(InputStream in) {
    Assert.notNull(in, "The Stream object provided is null");
    Assert.isNull(file, "Cannot instantiate using both the InputStream and File");
    this.in = in;
    return this;
}

From source file:org.springframework.integration.config.ConsumerEndpointFactoryBean.java

public void setHandler(MessageHandler handler) {
    Assert.notNull(handler, "handler must not be null");
    synchronized (this.handlerMonitor) {
        Assert.isNull(this.handler, "handler cannot be overridden");
        this.handler = handler;
    }/* w w  w.j a v  a  2  s.com*/
}

From source file:org.springframework.integration.config.ConsumerEndpointFactoryBean.java

private void initializeEndpoint() throws Exception {
    synchronized (this.initializationMonitor) {
        if (this.initialized) {
            return;
        }//from  w  ww  .j a v a2  s. co  m
        MessageChannel channel = null;
        if (StringUtils.hasText(this.inputChannelName)) {
            Assert.isTrue(this.beanFactory.containsBean(this.inputChannelName), "no such input channel '"
                    + this.inputChannelName + "' for endpoint '" + this.beanName + "'");
            channel = this.beanFactory.getBean(this.inputChannelName, MessageChannel.class);
        }
        if (this.inputChannel != null) {
            channel = this.inputChannel;
        }
        Assert.state(channel != null, "one of inputChannelName or inputChannel is required");
        if (channel instanceof SubscribableChannel) {
            Assert.isNull(this.pollerMetadata, "A poller should not be specified for endpoint '" + this.beanName
                    + "', since '" + channel + "' is a SubscribableChannel (not pollable).");
            this.endpoint = new EventDrivenConsumer((SubscribableChannel) channel, this.handler);
        } else if (channel instanceof PollableChannel) {
            PollingConsumer pollingConsumer = new PollingConsumer((PollableChannel) channel, this.handler);
            if (this.pollerMetadata == null) {
                this.pollerMetadata = PollerMetadata.getDefaultPollerMetadata(this.beanFactory);
                Assert.notNull(this.pollerMetadata, "No poller has been defined for endpoint '" + this.beanName
                        + "', and no default poller is available within the context.");
            }
            pollingConsumer.setTaskExecutor(this.pollerMetadata.getTaskExecutor());
            pollingConsumer.setTrigger(this.pollerMetadata.getTrigger());
            pollingConsumer.setAdviceChain(this.pollerMetadata.getAdviceChain());
            pollingConsumer.setMaxMessagesPerPoll(this.pollerMetadata.getMaxMessagesPerPoll());

            pollingConsumer.setErrorHandler(this.pollerMetadata.getErrorHandler());

            pollingConsumer.setReceiveTimeout(this.pollerMetadata.getReceiveTimeout());
            pollingConsumer.setTransactionSynchronizationFactory(
                    this.pollerMetadata.getTransactionSynchronizationFactory());
            pollingConsumer.setBeanClassLoader(beanClassLoader);
            pollingConsumer.setBeanFactory(beanFactory);
            this.endpoint = pollingConsumer;
        } else {
            throw new IllegalArgumentException("unsupported channel type: [" + channel.getClass() + "]");
        }
        this.endpoint.setBeanName(this.beanName);
        this.endpoint.setBeanFactory(this.beanFactory);
        this.endpoint.setAutoStartup(this.autoStartup);
        this.endpoint.afterPropertiesSet();
        this.initialized = true;
    }
}

From source file:org.springframework.integration.handler.LambdaMessageProcessor.java

public LambdaMessageProcessor(Object target, Class<?> payloadType) {
    Assert.notNull(target, "'target' must not be null");
    this.target = target;
    final AtomicReference<Method> methodValue = new AtomicReference<>();
    ReflectionUtils.doWithMethods(target.getClass(), methodValue::set, methodCandidate -> {
        boolean isCandidate = !methodCandidate.isBridge() && !methodCandidate.isDefault()
                && methodCandidate.getDeclaringClass() != Object.class
                && Modifier.isPublic(methodCandidate.getModifiers())
                && !Modifier.isStatic(methodCandidate.getModifiers());
        if (isCandidate) {
            Assert.isNull(methodValue.get(), "LambdaMessageProcessor is applicable for inline or lambda "
                    + "classes with single method - functional interface implementations.");
        }/*from  w ww  .  jav  a  2 s . c  om*/
        return isCandidate;
    });

    Assert.notNull(methodValue.get(), "LambdaMessageProcessor is applicable for inline or lambda "
            + "classes with single method - functional interface implementations.");

    this.method = methodValue.get();
    this.method.setAccessible(true);
    this.parameterTypes = this.method.getParameterTypes();
    this.payloadType = payloadType;
}

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 {/*from w w  w. j  a  v a  2  s.  c o m*/
            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.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Registers a TcpListener to receive messages after
 * the payload has been converted from the input data.
 * @param listener the TcpListener.//ww  w  . j  a v a2  s. c o  m
 */
public void registerListener(TcpListener listener) {
    Assert.isNull(this.listener, this.getClass().getName() + " may only be used by one inbound adapter");
    this.listener = listener;
}

From source file:org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Registers a TcpSender; for server sockets, used to 
 * provide connection information so a sender can be used
 * to reply to incoming messages.//from  w ww  .  j a v  a2s. co  m
 * @param sender The sender
 */
public void registerSender(TcpSender sender) {
    Assert.isNull(this.sender, this.getClass().getName() + " may only be used by one outbound adapter");
    this.sender = sender;
}

From source file:org.springframework.integration.mail.config.MailReceiverFactoryBean.java

private MailReceiver createReceiver() {
    this.verifyProtocol();
    boolean isPop3 = this.protocol.toLowerCase().startsWith("pop3");
    boolean isImap = this.protocol.toLowerCase().startsWith("imap");
    Assert.isTrue(isPop3 || isImap, "the store URI must begin with 'pop3' or 'imap'");
    AbstractMailReceiver receiver = isPop3 ? new Pop3MailReceiver(this.storeUri)
            : new ImapMailReceiver(this.storeUri);
    if (this.session != null) {
        Assert.isNull(this.javaMailProperties,
                "JavaMail Properties are not allowed when a Session has been provided.");
        Assert.isNull(this.authenticator,
                "A JavaMail Authenticator is not allowed when a Session has been provied.");
        receiver.setSession(this.session);
    }/*from   w  w w.  jav  a  2s.co  m*/
    if (this.searchTermStrategy != null) {
        Assert.isTrue(isImap, "searchTermStrategy is only allowed with imap");
        ((ImapMailReceiver) receiver).setSearchTermStrategy(this.searchTermStrategy);
    }
    if (this.javaMailProperties != null) {
        receiver.setJavaMailProperties(this.javaMailProperties);
    }
    if (this.authenticator != null) {
        receiver.setJavaMailAuthenticator(this.authenticator);
    }
    if (this.shouldDeleteMessages != null) {
        // always set the value if configured explicitly
        // otherwise, the default is true for POP3 but false for IMAP
        receiver.setShouldDeleteMessages(this.shouldDeleteMessages);
    }
    receiver.setMaxFetchSize(this.maxFetchSize);
    receiver.setSelectorExpression(selectorExpression);

    if (isPop3) {
        if (this.isShouldMarkMessagesAsRead() && this.logger.isWarnEnabled()) {
            logger.warn("Setting 'should-mark-messages-as-read' to 'true' while using POP3 has no effect");
        }
    } else if (isImap) {
        ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(this.shouldMarkMessagesAsRead);
    }
    if (this.beanFactory != null) {
        receiver.setBeanFactory(this.beanFactory);
    }
    receiver.afterPropertiesSet();
    return receiver;
}

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

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

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>();
    final Map<Class<?>, HandlerMethod> fallbackMethods = new HashMap<Class<?>, HandlerMethod>();
    final AtomicReference<Class<?>> ambiguousFallbackType = new AtomicReference<Class<?>>();
    final Class<?> targetClass = this.getTargetClass(targetObject);
    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            boolean matchesAnnotation = false;
            if (method.isBridge()) {
                return;
            }/*from www . j  a v a  2  s . com*/
            if (isMethodDefinedOnObjectClass(method)) {
                return;
            }
            if (method.getDeclaringClass().equals(Proxy.class)) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (requiresReply && void.class.equals(method.getReturnType())) {
                return;
            }
            if (methodName != null && !methodName.equals(method.getName())) {
                return;
            }
            if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) {
                matchesAnnotation = true;
            }
            HandlerMethod handlerMethod = null;
            try {
                handlerMethod = new HandlerMethod(method, canProcessMessageList);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Method [" + method + "] is not eligible for Message handling.", e);
                }
                return;
            }
            Class<?> targetParameterType = handlerMethod.getTargetParameterType().getObjectType();
            if (matchesAnnotation || annotationType == null) {
                Assert.isTrue(!candidateMethods.containsKey(targetParameterType),
                        "Found more than one method match for type [" + targetParameterType + "]");
                candidateMethods.put(targetParameterType, handlerMethod);
            } 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, handlerMethod);
            }
        }
    }, methodFilter);
    if (!candidateMethods.isEmpty()) {
        return candidateMethods;
    }
    if ((fallbackMethods.isEmpty() || ambiguousFallbackType.get() != null)
            && ServiceActivator.class.equals(annotationType)) {
        // a Service Activator can fallback to either MessageHandler.handleMessage(m) or RequestReplyExchanger.exchange(m)
        List<Method> frameworkMethods = new ArrayList<Method>();
        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));
                } else if ("org.springframework.integration.core.MessageHandler".equals(iface.getName())
                        && !requiresReply) {
                    frameworkMethods.add(targetClass.getMethod("handleMessage", Message.class));
                }
            } catch (Exception e) {
                // should never happen (but would fall through to errors below)
            }
        }
        if (frameworkMethods.size() == 1) {
            HandlerMethod handlerMethod = new HandlerMethod(frameworkMethods.get(0), canProcessMessageList);
            return Collections.<Class<?>, HandlerMethod>singletonMap(Object.class, handlerMethod);
        }
    }
    Assert.notEmpty(fallbackMethods, "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());
    return fallbackMethods;
}