Example usage for org.springframework.messaging MessagingException MessagingException

List of usage examples for org.springframework.messaging MessagingException MessagingException

Introduction

In this page you can find the example usage for org.springframework.messaging MessagingException MessagingException.

Prototype

public MessagingException(String description) 

Source Link

Usage

From source file:org.createnet.raptor.auth.service.services.BrokerMessageHandler.java

public void handle(Message<?> message) {

    System.out.println(message.getPayload());
    JsonNode json;/*from   w  ww . j  av a 2  s .  c  o m*/
    try {
        json = mapper.readTree(message.getPayload().toString());
    } catch (IOException ex) {
        throw new MessagingException("Cannot convert JSON payload: " + message.getPayload().toString());
    }

    switch (json.get("type").asText()) {
    case "object":

        User user = userService.getByUuid(json.get("userId").asText());
        UserDetails details = new RaptorUserDetailsService.RaptorUserDetails(user);
        final Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(),
                user.getPassword(), details.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        SyncRequest req = new SyncRequest();
        req.userId = user.getUuid();
        req.operation = json.get("op").asText();
        req.objectId = json.get("object").get("id").asText();
        req.created = json.get("object").get("createdAt").asLong();

        deviceService.sync(user, req);

        SecurityContextHolder.getContext().setAuthentication(null);
        break;
    case "data":
        StreamPayload data = mapper.convertValue(json, StreamPayload.class);
        break;
    case "action":
        ActionPayload action = mapper.convertValue(json, ActionPayload.class);
        break;
    case "user":
        // TODO: Add event notification in auth service
        break;
    }

}

From source file:nz.co.senanque.database.Class1_3.java

@Transactional
public void saveObjects(ProcessInstance pi, Order o) {
    m_entityManager.persist(pi);/*  www  .  j  a v a  2s .c o m*/
    m_entityManager.flush();
    Object oo = getContextDAO().mergeContext(o);
    String contextDescriptor = getContextDAO().createContextDescriptor(oo);
    Order o1 = (Order) getContextDAO().getContext(contextDescriptor);

    Result result = m_resultFactory.createResult(o1);
    if (result == null) {
        throw new MessagingException("Unable to marshal payload, ResultFactory returned null.");
    }
    try {
        m_marshaller.marshal(o1, result);
    } catch (Exception e) {
        throw new WorkflowException("Failed to marshal payload", e);
    }
}

From source file:nz.co.senanque.messaging.springintegration.MessageSenderImpl.java

public boolean send(T graph, long correlationId) {

    Object payload = graph;// w  w  w  . j a  v  a  2s.  c o m

    if (m_marshaller != null) {
        Result result = m_resultFactory.createResult(graph);
        if (result == null) {
            throw new MessagingException("Unable to marshal payload, ResultFactory returned null.");
        }
        try {
            m_marshaller.marshal(graph, result);
        } catch (Exception e) {
            throw new WorkflowException("Failed to marshal payload", e);
        }
        Document doc = (Document) m_resultTransformer.transformResult(result);
        payload = doc;
    }

    MessageBuilder<?> messageBuilder = MessageBuilder.withPayload(payload);
    if (getReplyChannel() != null) {
        messageBuilder.setReplyChannel(getReplyChannel());
    }
    if (getErrorChannel() != null) {
        messageBuilder.setErrorChannel(getErrorChannel());
    }
    if (getMessagePriority() != null) {
        messageBuilder.setPriority(getMessagePriority());
    }
    messageBuilder.setCorrelationId(correlationId);
    Message<?> ret = messageBuilder.build();
    return getChannel().send(messageBuilder.build());
}

From source file:biz.c24.io.spring.integration.transformer.C24UnmarshallingTransformer.java

Source getSourceFor(Object payload) throws Exception {
    Source source = this.source.get();
    if (source == null) {
        source = sourceFactory.getSource();
        this.source.set(source);
    }//from w  w  w .  j  a  v  a  2s. co  m

    // Things that can be turned into a Reader
    if (payload instanceof Reader) {
        source.setReader((Reader) payload);
    } else if (payload instanceof String) {
        source.setReader(new StringReader((String) payload));
    }
    // Things that can be turned into an input stream
    else if (payload instanceof InputStream) {
        source.setInputStream((InputStream) payload);
    } else if (payload instanceof byte[]) {
        source.setInputStream(new ByteArrayInputStream((byte[]) payload));
    } else if (payload instanceof MultipartFile) {
        source.setInputStream(((MultipartFile) payload).getInputStream());
    } else if (payload instanceof File) {
        File file = (File) payload;
        source.setInputStream(new FileInputStream(file));
    } else {
        throw new MessagingException(
                "failed to transform message, payload not assignable from java.io.InputStream/Reader and no conversion possible");
    }

    return source;

}

From source file:org.springframework.batch.integration.x.RemoteFileToHadoopTasklet.java

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    final String filePath = chunkContext.getStepContext().getStepExecution().getExecutionContext()
            .getString("filePath");
    Assert.notNull(filePath);//ww w . j  av  a  2 s  .com
    if (logger.isDebugEnabled()) {
        logger.debug("Transferring " + filePath + " to HDFS");
    }
    boolean result = this.template.get(filePath, new InputStreamCallback() {

        @Override
        public void doWithInputStream(InputStream stream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(configuration,
                    new Path(hdfsDirectory + filePath), null);
            byte[] buff = new byte[1024];
            int len;
            while ((len = stream.read(buff)) > 0) {
                if (len == buff.length) {
                    writer.write(buff);
                } else {
                    writer.write(Arrays.copyOf(buff, len));
                }
            }
            writer.close();
        }

    });
    if (!result) {
        throw new MessagingException("Error during file transfer");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Transferred " + filePath + " to HDFS");
        }
        return RepeatStatus.FINISHED;
    }
}

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

/**
 * Build a {@code Throwable payload} based on the provided context
 * for future {@link ErrorMessage} when there is original {@code Throwable}.
 * @param context the {@link AttributeAccessor} to use for exception properties.
 * @return the {@code Throwable} for an {@link ErrorMessage} payload.
 * @see ErrorMessageUtils// w  w w.jav a  2 s.  c  o m
 */
protected Throwable payloadWhenNull(AttributeAccessor context) {
    Message<?> message = (Message<?>) context.getAttribute(ErrorMessageUtils.FAILED_MESSAGE_CONTEXT_KEY);
    return message == null ? new MessagingException("No root cause exception available")
            : new MessagingException(message, "No root cause exception available");
}

From source file:org.springframework.integration.file.remote.RemoteFileTemplate.java

private void sendFileToRemoteDirectory(InputStream inputStream, String temporaryRemoteDirectory,
        String remoteDirectory, String fileName, Session<F> session, FileExistsMode mode) throws IOException {

    remoteDirectory = this.normalizeDirectoryPath(remoteDirectory);
    temporaryRemoteDirectory = this.normalizeDirectoryPath(temporaryRemoteDirectory);

    String remoteFilePath = remoteDirectory + fileName;
    String tempRemoteFilePath = temporaryRemoteDirectory + fileName;
    // write remote file first with temporary file extension if enabled

    String tempFilePath = tempRemoteFilePath + (this.useTemporaryFileName ? this.temporaryFileSuffix : "");

    if (this.autoCreateDirectory) {
        try {/*from   w  ww  .ja  v a2 s  .c  om*/
            RemoteFileUtils.makeDirectories(remoteDirectory, session, this.remoteFileSeparator, this.logger);
        } catch (IllegalStateException e) {
            // Revert to old FTP behavior if recursive mkdir fails, for backwards compatibility
            session.mkdir(remoteDirectory);
        }
    }

    try {
        boolean rename = this.useTemporaryFileName;
        if (FileExistsMode.REPLACE.equals(mode)) {
            session.write(inputStream, tempFilePath);
        } else if (FileExistsMode.APPEND.equals(mode)) {
            session.append(inputStream, tempFilePath);
        } else {
            if (exists(remoteFilePath)) {
                if (FileExistsMode.FAIL.equals(mode)) {
                    throw new MessagingException(
                            "The destination file already exists at '" + remoteFilePath + "'.");
                } else {
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("File not transferred to '" + remoteFilePath + "'; already exists.");
                    }
                }
                rename = false;
            } else {
                session.write(inputStream, tempFilePath);
            }
        }
        // then rename it to its final name if necessary
        if (rename) {
            session.rename(tempFilePath, remoteFilePath);
        }
    } catch (Exception e) {
        throw new MessagingException("Failed to write to '" + tempFilePath + "' while uploading the file", e);
    } finally {
        inputStream.close();
    }
}

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

@Before
public void setup() {
    this.handler = new AbstractReplyProducingMessageHandler() {

        @Override/*from  ww  w  .  j av a2  s  . co  m*/
        protected Object handleRequestMessage(Message<?> requestMessage) {
            final SettableListenableFuture<String> future = new SettableListenableFuture<String>();
            Executors.newSingleThreadExecutor().execute(() -> {
                try {
                    latch.await(10, TimeUnit.SECONDS);
                    switch (whichTest) {
                    case 0:
                        future.set("reply");
                        break;
                    case 1:
                        future.setException(new RuntimeException("foo"));
                        break;
                    case 2:
                        future.setException(new MessagingException(requestMessage));
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            return future;
        }

    };
    this.handler.setAsync(true);
    this.handler.setOutputChannel(this.output);
    this.handler.setBeanFactory(mock(BeanFactory.class));
    this.latch = new CountDownLatch(1);
    Log logger = spy(TestUtils.getPropertyValue(this.handler, "logger", Log.class));
    new DirectFieldAccessor(this.handler).setPropertyValue("logger", logger);
    doAnswer(invocation -> {
        failedCallbackMessage = invocation.getArgument(0);
        failedCallbackException = invocation.getArgument(1);
        exceptionLatch.countDown();
        return null;
    }).when(logger).error(anyString(), any(Throwable.class));
}

From source file:org.springframework.messaging.handler.invocation.reactive.AbstractEncoderMethodReturnValueHandler.java

@SuppressWarnings("unchecked")
private <T> DataBuffer encodeValue(Object element, ResolvableType elementType, @Nullable Encoder<T> encoder,
        DataBufferFactory bufferFactory, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

    if (encoder == null) {
        encoder = getEncoder(ResolvableType.forInstance(element), mimeType);
        if (encoder == null) {
            throw new MessagingException(
                    "No encoder for " + elementType + ", current value type is " + element.getClass());
        }/*  www . j av a2s.c  o  m*/
    }
    return encoder.encodeValue((T) element, bufferFactory, elementType, mimeType, hints);
}