Search in sources :

Example 46 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class FileOutboundChannelAdapterIntegrationTests method saveToSubWithFileExpressionNull.

@Test
public void saveToSubWithFileExpressionNull() throws Exception {
    final File directory = null;
    final Message<File> messageWithFileHeader = MessageBuilder.fromMessage(message).setHeader("subDirectory", directory).build();
    try {
        this.inputChannelSaveToSubDirWithFile.send(messageWithFileHeader);
    } catch (MessageHandlingException e) {
        Assert.assertEquals("The provided Destination Directory expression " + "(headers['subDirectory']) must not evaluate to null.", e.getCause().getMessage());
        return;
    }
    Assert.fail("Was expecting a MessageHandlingException to be thrown");
}
Also used : File(java.io.File) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Example 47 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class AbstractRemoteFileOutboundGateway method get.

/**
 * Copy a remote file to the configured local directory.
 * @param message the message.
 * @param session the session.
 * @param remoteDir the remote directory.
 * @param remoteFilePath the remote file path.
 * @param remoteFilename the remote file name.
 * @param fileInfoParam the remote file info; if null we will execute an 'ls' command
 * first.
 * @return The file.
 * @throws IOException Any IOException.
 */
protected File get(Message<?> message, Session<F> session, String remoteDir, String remoteFilePath, String remoteFilename, F fileInfoParam) throws IOException {
    F fileInfo = fileInfoParam;
    if (fileInfo == null) {
        F[] files = session.list(remoteFilePath);
        if (files == null) {
            throw new MessagingException("Session returned null when listing " + remoteFilePath);
        }
        if (files.length != 1 || files[0] == null || isDirectory(files[0]) || isLink(files[0])) {
            throw new MessagingException(remoteFilePath + " is not a file");
        }
        fileInfo = files[0];
    }
    File localFile = new File(generateLocalDirectory(message, remoteDir), generateLocalFileName(message, remoteFilename));
    FileExistsMode fileExistsMode = this.fileExistsMode;
    boolean appending = FileExistsMode.APPEND.equals(fileExistsMode);
    boolean exists = localFile.exists();
    boolean replacing = FileExistsMode.REPLACE.equals(fileExistsMode) || (exists && FileExistsMode.REPLACE_IF_MODIFIED.equals(fileExistsMode) && localFile.lastModified() != getModified(fileInfo));
    if (!exists || appending || replacing) {
        OutputStream outputStream;
        String tempFileName = localFile.getAbsolutePath() + this.remoteFileTemplate.getTemporaryFileSuffix();
        File tempFile = new File(tempFileName);
        if (appending) {
            outputStream = new BufferedOutputStream(new FileOutputStream(localFile, true));
        } else {
            outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
        }
        if (replacing) {
            localFile.delete();
        }
        try {
            session.read(remoteFilePath, outputStream);
        } catch (Exception e) {
            /* Some operation systems acquire exclusive file-lock during file processing
				and the file can't be deleted without closing streams before.
				*/
            outputStream.close();
            tempFile.delete();
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new MessagingException("Failure occurred while copying from remote to local directory", e);
            }
        } finally {
            try {
                outputStream.close();
            } catch (Exception ignored2) {
            // Ignore it
            }
        }
        if (!appending && !tempFile.renameTo(localFile)) {
            throw new MessagingException("Failed to rename local file");
        }
        if (this.options.contains(Option.PRESERVE_TIMESTAMP) || FileExistsMode.REPLACE_IF_MODIFIED.equals(fileExistsMode)) {
            localFile.setLastModified(getModified(fileInfo));
        }
        if (this.options.contains(Option.DELETE)) {
            boolean result = session.remove(remoteFilePath);
            if (!result) {
                logger.error("Failed to delete: " + remoteFilePath);
            } else if (logger.isDebugEnabled()) {
                logger.debug(remoteFilePath + " deleted");
            }
        }
    } else if (FileExistsMode.REPLACE_IF_MODIFIED.equals(fileExistsMode)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Local file '" + localFile + "' has the same modified timestamp, ignored");
        }
        if (this.command.equals(Command.MGET)) {
            localFile = null;
        }
    } else if (!FileExistsMode.IGNORE.equals(fileExistsMode)) {
        throw new MessageHandlingException(message, "Local file " + localFile + " already exists");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Existing file skipped: " + localFile);
        }
        if (this.command.equals(Command.MGET)) {
            localFile = null;
        }
    }
    return localFile;
}
Also used : MessagingException(org.springframework.messaging.MessagingException) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) IOException(java.io.IOException) PartialSuccessException(org.springframework.integration.support.PartialSuccessException) FileNotFoundException(java.io.FileNotFoundException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) FileOutputStream(java.io.FileOutputStream) FileExistsMode(org.springframework.integration.file.support.FileExistsMode) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 48 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class AbstractRemoteFileOutboundGateway method doGet.

private Object doGet(final Message<?> requestMessage) {
    final String remoteFilePath = this.fileNameProcessor.processMessage(requestMessage);
    final String remoteFilename = getRemoteFilename(remoteFilePath);
    final String remoteDir = getRemoteDirectory(remoteFilePath, remoteFilename);
    Session<F> session = null;
    Object payload;
    if (this.options.contains(Option.STREAM)) {
        session = this.remoteFileTemplate.getSessionFactory().getSession();
        try {
            payload = session.readRaw(remoteFilePath);
        } catch (IOException e) {
            throw new MessageHandlingException(requestMessage, "Failed to get the remote file [" + remoteFilePath + "] as a stream", e);
        }
    } else {
        payload = this.remoteFileTemplate.execute(session1 -> get(requestMessage, session1, remoteDir, remoteFilePath, remoteFilename, null));
    }
    return getMessageBuilderFactory().withPayload(payload).setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir).setHeader(FileHeaders.REMOTE_FILE, remoteFilename).setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session);
}
Also used : MessagingException(org.springframework.messaging.MessagingException) Arrays(java.util.Arrays) SessionFactory(org.springframework.integration.file.remote.session.SessionFactory) FileHeaders(org.springframework.integration.file.FileHeaders) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) FileExistsMode(org.springframework.integration.file.support.FileExistsMode) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ValueExpression(org.springframework.integration.expression.ValueExpression) FileListFilter(org.springframework.integration.file.filters.FileListFilter) MessageHandlingException(org.springframework.messaging.MessageHandlingException) RemoteFileUtils(org.springframework.integration.file.remote.RemoteFileUtils) Session(org.springframework.integration.file.remote.session.Session) FunctionExpression(org.springframework.integration.expression.FunctionExpression) AbstractFileInfo(org.springframework.integration.file.remote.AbstractFileInfo) MessageSessionCallback(org.springframework.integration.file.remote.MessageSessionCallback) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) MutableMessage(org.springframework.integration.support.MutableMessage) Message(org.springframework.messaging.Message) RemoteFileTemplate(org.springframework.integration.file.remote.RemoteFileTemplate) OutputStream(java.io.OutputStream) RemoteFileOperations(org.springframework.integration.file.remote.RemoteFileOperations) Iterator(java.util.Iterator) Collection(java.util.Collection) ObjectUtils(org.springframework.util.ObjectUtils) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) ExpressionUtils(org.springframework.integration.expression.ExpressionUtils) IOException(java.io.IOException) PartialSuccessException(org.springframework.integration.support.PartialSuccessException) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ExpressionEvaluatingMessageProcessor(org.springframework.integration.handler.ExpressionEvaluatingMessageProcessor) EvaluationContext(org.springframework.expression.EvaluationContext) List(java.util.List) Expression(org.springframework.expression.Expression) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) IOException(java.io.IOException) MessageHandlingException(org.springframework.messaging.MessageHandlingException)

Example 49 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class FileOutboundGatewayParserTests method gatewayWithFailModeLowercase.

/**
 * Test is exactly the same as {@link #gatewayWithFailMode()}. However, the
 * mode is provided in lower-case ensuring that the mode can be provided
 * in an case-insensitive fashion.
 *
 * Instead a {@link MessageHandlingException} will be thrown.
 */
@Test
public void gatewayWithFailModeLowercase() throws Exception {
    final MessagingTemplate messagingTemplate = new MessagingTemplate();
    messagingTemplate.setDefaultDestination(this.gatewayWithFailModeLowercaseChannel);
    String expectedFileContent = "Initial File Content:";
    File testFile = new File("test/fileToAppend.txt");
    if (testFile.exists()) {
        testFile.delete();
    }
    messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
    final String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
    assertEquals(expectedFileContent, actualFileContent);
    try {
        messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
    } catch (MessageHandlingException e) {
        assertTrue(e.getMessage().startsWith("The destination file already exists at '"));
        return;
    }
    fail("Was expecting a MessageHandlingException to be thrown.");
}
Also used : MessagingTemplate(org.springframework.integration.core.MessagingTemplate) File(java.io.File) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Example 50 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class FileOutboundGatewayParserTests method gatewayWithFailMode.

/**
 * Test uses the Fail mode of the File Outbound Gateway. When persisting
 * a payload using the File Outbound Gateway and the mode is set to Fail,
 * then the destination {@link File} will be created and written if it does
 * not yet exist. BUT if the destination {@link File} already exists, a
 * {@link MessageHandlingException} will be thrown.
 */
@Test
public void gatewayWithFailMode() throws Exception {
    final MessagingTemplate messagingTemplate = new MessagingTemplate();
    messagingTemplate.setDefaultDestination(this.gatewayWithFailModeChannel);
    String expectedFileContent = "Initial File Content:";
    File testFile = new File("test/fileToAppend.txt");
    if (testFile.exists()) {
        testFile.delete();
    }
    messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
    final String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
    assertEquals(expectedFileContent, actualFileContent);
    try {
        messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
    } catch (MessageHandlingException e) {
        assertTrue(e.getMessage().startsWith("The destination file already exists at '"));
        return;
    }
    fail("Was expecting a MessageHandlingException to be thrown.");
}
Also used : MessagingTemplate(org.springframework.integration.core.MessagingTemplate) File(java.io.File) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Aggregations

MessageHandlingException (org.springframework.messaging.MessageHandlingException)65 Test (org.junit.Test)34 ErrorMessage (org.springframework.messaging.support.ErrorMessage)14 IOException (java.io.IOException)12 GenericMessage (org.springframework.messaging.support.GenericMessage)12 Message (org.springframework.messaging.Message)10 File (java.io.File)9 MessagingException (org.springframework.messaging.MessagingException)9 Matchers.containsString (org.hamcrest.Matchers.containsString)6 BeanFactory (org.springframework.beans.factory.BeanFactory)6 FileNotFoundException (java.io.FileNotFoundException)4 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)4 MessageRejectedException (org.springframework.integration.MessageRejectedException)4 QueueChannel (org.springframework.integration.channel.QueueChannel)4 AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)4 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 IntegrationMessageHeaderAccessor (org.springframework.integration.IntegrationMessageHeaderAccessor)3