Example usage for org.springframework.util Assert isInstanceOf

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

Introduction

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

Prototype

public static void isInstanceOf(Class<?> type, @Nullable Object obj, Supplier<String> messageSupplier) 

Source Link

Document

Assert that the provided object is an instance of the provided class.

Usage

From source file:org.springframework.data.hadoop.scripting.HdfsScriptRunner.java

private boolean hasBinding(Map<String, Object> args, String key, Class<?> type) {
    if (args.containsKey(key)) {
        Assert.isInstanceOf(type, args.get(key), "Invalid property '" + key + "' ");
    }//from  w  ww  .j  a  v a 2  s.  com
    return false;
}

From source file:org.springframework.flex.config.RemotingAnnotationPostProcessor.java

/**
 * //w  w w  . j  a va2  s  .c om
 * {@inheritDoc}
 */
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    Set<RemotingDestinationMetadata> remoteBeans = findRemotingDestinations(beanFactory);

    if (remoteBeans.size() > 0) {
        Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory,
                "In order for services to be exported via the @RemotingDestination annotation, the current BeanFactory must be a BeanDefinitionRegistry.");
    }

    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    for (RemotingDestinationMetadata remotingDestinationConfig : remoteBeans) {

        BeanDefinitionBuilder exporterBuilder = BeanDefinitionBuilder
                .rootBeanDefinition(RemotingDestinationExporter.class);
        exporterBuilder.getRawBeanDefinition().setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

        RemotingDestination remotingDestination = remotingDestinationConfig.getRemotingDestination();

        String messageBrokerId = StringUtils.hasText(remotingDestination.messageBroker())
                ? remotingDestination.messageBroker()
                : BeanIds.MESSAGE_BROKER;
        String destinationId = StringUtils.hasText(remotingDestination.value()) ? remotingDestination.value()
                : remotingDestinationConfig.getBeanName();

        String[] channels = null;
        for (String channelValue : remotingDestination.channels()) {
            channelValue = beanFactory.resolveEmbeddedValue(channelValue);
            String[] parsedChannels = StringUtils
                    .trimArrayElements(StringUtils.commaDelimitedListToStringArray(channelValue));
            channels = StringUtils.mergeStringArrays(channels, parsedChannels);
        }

        exporterBuilder.addPropertyReference(MESSAGE_BROKER_PROPERTY, messageBrokerId);
        exporterBuilder.addPropertyValue(SERVICE_PROPERTY, remotingDestinationConfig.getBeanName());
        exporterBuilder.addDependsOn(remotingDestinationConfig.getBeanName());
        exporterBuilder.addPropertyValue(DESTINATION_ID_PROPERTY, destinationId);
        exporterBuilder.addPropertyValue(CHANNELS_PROPERTY, channels);
        exporterBuilder.addPropertyValue(INCLUDE_METHODS_PROPERTY,
                remotingDestinationConfig.getIncludeMethods());
        exporterBuilder.addPropertyValue(EXCLUDE_METHODS_PROPERTY,
                remotingDestinationConfig.getExcludeMethods());
        exporterBuilder.addPropertyValue(SERVICE_ADAPTER_PROPERTY, remotingDestination.serviceAdapter());

        BeanDefinitionReaderUtils.registerWithGeneratedName(exporterBuilder.getBeanDefinition(), registry);
    }

}

From source file:org.springframework.flex.remoting.RemotingDestinationExporter.java

/**
 * /*from   w  w  w .  jav a2 s. com*/
 * {@inheritDoc}
 */
@Override
protected void initializeDestination(Destination destination) {
    destination.start();

    Assert.isInstanceOf(ServiceAdapter.class, destination.getAdapter(),
            "Spring beans exported as a RemotingDestination require a ServiceAdapter.");

    configureIncludes(destination);
    configureExcludes(destination);

    if (log.isInfoEnabled()) {
        log.info("Remoting destination '" + destination.getId() + "' has been started started successfully.");
    }
}

From source file:org.springframework.flex.servlet.MessageBrokerHandlerAdapter.java

/**
 * /*from  w w  w .  j av  a 2  s .  c o  m*/
 * {@inheritDoc}
 */
public ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    MessageBroker broker = (MessageBroker) handler;

    try {
        // Update thread locals
        broker.initThreadLocals();

        // Set this first so it is in place for the session creation event.
        FlexContext.setThreadLocalObjects(null, null, broker, req, res, this.servletConfig);

        Object providerToCheck = broker.getFlexSessionManager().getFlexSessionProvider(HttpFlexSession.class);
        Assert.isInstanceOf(HttpFlexSessionProvider.class, providerToCheck,
                "MessageBrokerHandlerAdapter requires an instance of " + HttpFlexSessionProvider.class.getName()
                        + " to have been registered with the MessageBroker.");
        HttpFlexSessionProvider provider = (HttpFlexSessionProvider) providerToCheck;
        provider.getOrCreateSession(req);

        String contextPath = req.getContextPath();
        String pathInfo = req.getPathInfo();
        String endpointPath = req.getServletPath();
        if (pathInfo != null) {
            endpointPath = endpointPath + pathInfo;
        }
        Endpoint endpoint = null;
        try {
            endpoint = broker.getEndpoint(endpointPath, contextPath);
        } catch (MessageException me) {
            if (logger.isErrorEnabled()) {
                logger.error("Received invalid request for endpoint path '" + endpointPath + "'.");
            }

            if (!res.isCommitted()) {
                res.sendError(HttpServletResponse.SC_NOT_FOUND);
            }

            return null;
        }

        try {
            if (logger.isInfoEnabled()) {
                logger.info("Channel endpoint " + endpoint.getId() + " received request.");
            }
            endpoint.service(req, res);
        } catch (UnsupportedOperationException ue) {
            if (logger.isErrorEnabled()) {
                logger.error("Channel endpoint " + endpoint.getId()
                        + " received request for an unsupported operation.", ue);
            }

            if (!res.isCommitted()) {
                res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
    } finally {
        FlexContext.clearThreadLocalObjects();
        SerializationContext.clearThreadLocalObjects();
    }

    return null;
}

From source file:org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.java

public void setReleasePartialSequences(boolean releasePartialSequences) {
    Assert.isInstanceOf(SequenceSizeReleaseStrategy.class, this.releaseStrategy, "Release strategy of type ["
            + this.releaseStrategy.getClass().getSimpleName()
            + "] cannot release partial sequences. Use the default SequenceSizeReleaseStrategy instead.");
    ((SequenceSizeReleaseStrategy) this.releaseStrategy).setReleasePartialSequences(releasePartialSequences);
}

From source file:org.springframework.integration.channel.MessagePublishingErrorHandler.java

private MessageChannel resolveErrorChannel(Throwable t) {
    Message<?> failedMessage = (t instanceof MessagingException) ? ((MessagingException) t).getFailedMessage()
            : null;/*from  ww w  . jav  a 2s  . c om*/
    if (this.defaultErrorChannel == null && this.channelResolver != null) {
        this.defaultErrorChannel = this.channelResolver
                .resolveChannelName(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);
    }

    if (failedMessage == null || failedMessage.getHeaders().getErrorChannel() == null) {
        return this.defaultErrorChannel;
    }
    Object errorChannelHeader = failedMessage.getHeaders().getErrorChannel();
    if (errorChannelHeader instanceof MessageChannel) {
        return (MessageChannel) errorChannelHeader;
    }
    Assert.isInstanceOf(String.class, errorChannelHeader,
            "Unsupported error channel header type. Expected MessageChannel or String, but actual type is ["
                    + errorChannelHeader.getClass() + "]");
    return this.channelResolver.resolveChannelName((String) errorChannelHeader);
}

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

public void setBeanFactory(BeanFactory beanFactory) {
    Assert.isInstanceOf(ConfigurableBeanFactory.class, beanFactory, "a ConfigurableBeanFactory is required");
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;
}

From source file:org.springframework.integration.core.MessagingTemplate.java

public <P> Message<P> receive(String channelName) {
    MessageChannel channel = this.resolveChannelName(channelName);
    Assert.isInstanceOf(PollableChannel.class, channel,
            "A PollableChannel is required for receive operations. ");
    return this.receive((PollableChannel) channel);
}

From source file:org.springframework.integration.file.transformer.AbstractFilePayloadTransformer.java

public final Message<?> transform(Message<?> message) {
    try {/*from  w  w w.ja  v a  2  s .c  o m*/
        Assert.notNull(message, "Message must not be null");
        Object payload = message.getPayload();
        Assert.notNull(payload, "Mesasge payload must not be null");
        Assert.isInstanceOf(File.class, payload, "Message payload must be of type [java.io.File]");
        File file = (File) payload;
        T result = this.transformFile(file);
        Message<?> transformedMessage = MessageBuilder.withPayload(result).copyHeaders(message.getHeaders())
                .setHeaderIfAbsent(FileHeaders.ORIGINAL_FILE, file)
                .setHeaderIfAbsent(FileHeaders.FILENAME, file.getName()).build();
        if (this.deleteFiles) {
            if (!file.delete() && this.logger.isWarnEnabled()) {
                this.logger.warn("failed to delete File '" + file + "'");
            }
        }
        return transformedMessage;
    } catch (Exception e) {
        throw new MessagingException(message, "failed to transform File Message", e);
    }
}

From source file:org.springframework.integration.gateway.GatewayMethodInboundMessageMapper.java

private Message<?> mapArgumentsToMessage(Object[] arguments) {
    Object messageOrPayload = null;
    boolean foundPayloadAnnotation = false;
    Map<String, Object> headers = new HashMap<String, Object>();
    EvaluationContext methodInvocationEvaluationContext = createMethodInvocationEvaluationContext(arguments);
    if (this.payloadExpression != null) {
        messageOrPayload = this.payloadExpression.getValue(methodInvocationEvaluationContext);
    }//ww w .  j  av a  2s. c o m
    for (int i = 0; i < this.parameterList.size(); i++) {
        Object argumentValue = arguments[i];
        MethodParameter methodParameter = this.parameterList.get(i);
        Annotation annotation = this.findMappingAnnotation(methodParameter.getParameterAnnotations());
        if (annotation != null) {
            if (annotation.annotationType().equals(Payload.class)) {
                if (messageOrPayload != null) {
                    this.throwExceptionForMultipleMessageOrPayloadParameters(methodParameter);
                }
                String expression = ((Payload) annotation).value();
                if (!StringUtils.hasText(expression)) {
                    messageOrPayload = argumentValue;
                } else {
                    messageOrPayload = this.evaluatePayloadExpression(expression, argumentValue);
                }
                foundPayloadAnnotation = true;
            } else if (annotation.annotationType().equals(Header.class)) {
                Header headerAnnotation = (Header) annotation;
                String headerName = this.determineHeaderName(headerAnnotation, methodParameter);
                if (headerAnnotation.required() && argumentValue == null) {
                    throw new IllegalArgumentException(
                            "Received null argument value for required header: '" + headerName + "'");
                }
                headers.put(headerName, argumentValue);
            } else if (annotation.annotationType().equals(Headers.class)) {
                if (argumentValue != null) {
                    if (!(argumentValue instanceof Map)) {
                        throw new IllegalArgumentException(
                                "@Headers annotation is only valid for Map-typed parameters");
                    }
                    for (Object key : ((Map<?, ?>) argumentValue).keySet()) {
                        Assert.isInstanceOf(String.class, key,
                                "Invalid header name [" + key + "], name type must be String.");
                        Object value = ((Map<?, ?>) argumentValue).get(key);
                        headers.put((String) key, value);
                    }
                }
            }
        } else if (messageOrPayload == null) {
            messageOrPayload = argumentValue;
        } else if (Map.class.isAssignableFrom(methodParameter.getParameterType())) {
            if (messageOrPayload instanceof Map && !foundPayloadAnnotation) {
                if (payloadExpression == null) {
                    throw new MessagingException("Ambiguous method parameters; found more than one "
                            + "Map-typed parameter and neither one contains a @Payload annotation");
                }
            }
            this.copyHeaders((Map<?, ?>) argumentValue, headers);
        } else if (this.payloadExpression == null) {
            this.throwExceptionForMultipleMessageOrPayloadParameters(methodParameter);
        }
    }
    Assert.isTrue(messageOrPayload != null,
            "unable to determine a Message or payload parameter on method [" + method + "]");
    MessageBuilder<?> builder = (messageOrPayload instanceof Message)
            ? MessageBuilder.fromMessage((Message<?>) messageOrPayload)
            : MessageBuilder.withPayload(messageOrPayload);
    builder.copyHeadersIfAbsent(headers);
    if (!CollectionUtils.isEmpty(this.headerExpressions)) {
        Map<String, Object> evaluatedHeaders = new HashMap<String, Object>();
        for (Map.Entry<String, Expression> entry : this.headerExpressions.entrySet()) {
            Object value = entry.getValue().getValue(methodInvocationEvaluationContext);
            if (value != null) {
                evaluatedHeaders.put(entry.getKey(), value);
            }
        }
        builder.copyHeaders(evaluatedHeaders);
    }
    return builder.build();
}