Search in sources :

Example 61 with MessagingException

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

the class AbstractInboundFileSynchronizer method copyFileToLocalDirectory.

protected boolean copyFileToLocalDirectory(String remoteDirectoryPath, F remoteFile, File localDirectory, Session<F> session) throws IOException {
    String remoteFileName = this.getFilename(remoteFile);
    String localFileName = this.generateLocalFileName(remoteFileName);
    String remoteFilePath = remoteDirectoryPath != null ? (remoteDirectoryPath + this.remoteFileSeparator + remoteFileName) : remoteFileName;
    if (!this.isFile(remoteFile)) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("cannot copy, not a file: " + remoteFilePath);
        }
        return false;
    }
    long modified = getModified(remoteFile);
    File localFile = new File(localDirectory, localFileName);
    boolean exists = localFile.exists();
    if (!exists || (this.preserveTimestamp && modified != localFile.lastModified())) {
        if (!exists && localFileName.replaceAll("/", Matcher.quoteReplacement(File.separator)).contains(File.separator)) {
            // NOSONAR - will fail on the writing below
            localFile.getParentFile().mkdirs();
        }
        boolean transfer = true;
        if (exists && !localFile.delete()) {
            transfer = false;
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Cannot delete local file '" + localFile + "' in order to transfer modified remote file '" + remoteFile + "'. " + "The local file may be busy in some other process.");
            }
        }
        boolean renamed = false;
        if (transfer) {
            String tempFileName = localFile.getAbsolutePath() + this.temporaryFileSuffix;
            File tempFile = new File(tempFileName);
            OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
            try {
                session.read(remoteFilePath, outputStream);
            } catch (Exception e) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                } else {
                    throw new MessagingException("Failure occurred while copying '" + remoteFilePath + "' from the remote to the local directory", e);
                }
            } finally {
                try {
                    outputStream.close();
                } catch (Exception ignored2) {
                }
            }
            renamed = tempFile.renameTo(localFile);
            if (!renamed) {
                if (localFile.delete()) {
                    renamed = tempFile.renameTo(localFile);
                    if (!renamed && this.logger.isInfoEnabled()) {
                        this.logger.info("Cannot rename '" + tempFileName + "' to local file '" + localFile + "' after deleting. " + "The local file may be busy in some other process.");
                    }
                } else if (this.logger.isInfoEnabled()) {
                    this.logger.info("Cannot delete local file '" + localFile + "'. The local file may be busy in some other process.");
                }
            }
        }
        if (renamed) {
            if (this.deleteRemoteFiles) {
                session.remove(remoteFilePath);
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("deleted remote file: " + remoteFilePath);
                }
            }
            if (this.preserveTimestamp) {
                localFile.setLastModified(modified);
            }
            return true;
        } else if (this.filter instanceof ResettableFileListFilter) {
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Reverting the remote file '" + remoteFile + "' from the filter for a subsequent transfer attempt");
            }
            ((ResettableFileListFilter<F>) this.filter).remove(remoteFile);
        }
    } else if (this.logger.isWarnEnabled()) {
        this.logger.warn("The remote file '" + remoteFile + "' has not been transferred " + "to the existing local file '" + localFile + "'. Consider removing the local file.");
    }
    return false;
}
Also used : MessagingException(org.springframework.messaging.MessagingException) ResettableFileListFilter(org.springframework.integration.file.filters.ResettableFileListFilter) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) MessagingException(org.springframework.messaging.MessagingException) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException)

Example 62 with MessagingException

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

the class AbstractRemoteFileStreamingMessageSource method doReceive.

@Override
protected Object doReceive() {
    AbstractFileInfo<F> file = poll();
    if (file != null) {
        String remotePath = remotePath(file);
        Session<?> session = this.remoteFileTemplate.getSession();
        try {
            return getMessageBuilderFactory().withPayload(session.readRaw(remotePath)).setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session).setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()).setHeader(FileHeaders.REMOTE_FILE, file.getFilename()).setHeader(FileHeaders.REMOTE_FILE_INFO, this.fileInfoJson ? file.toJson() : file);
        } catch (IOException e) {
            throw new MessagingException("IOException when retrieving " + remotePath, e);
        }
    }
    return null;
}
Also used : MessagingException(org.springframework.messaging.MessagingException) IOException(java.io.IOException)

Example 63 with MessagingException

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

the class AbstractRemoteFileOutboundGateway method mGetWithoutRecursion.

private List<File> mGetWithoutRecursion(Message<?> message, Session<F> session, String remoteDirectory, String remoteFilename) throws IOException {
    List<File> files = new ArrayList<File>();
    String remotePath = buildRemotePath(remoteDirectory, remoteFilename);
    @SuppressWarnings("unchecked") List<AbstractFileInfo<F>> remoteFiles = (List<AbstractFileInfo<F>>) ls(message, session, remotePath);
    if (remoteFiles.size() == 0 && this.options.contains(Option.EXCEPTION_WHEN_EMPTY)) {
        throw new MessagingException("No files found at " + (remoteDirectory != null ? remoteDirectory : "Client Working Directory") + " with pattern " + remoteFilename);
    }
    try {
        for (AbstractFileInfo<F> lsEntry : remoteFiles) {
            if (lsEntry.isDirectory()) {
                continue;
            }
            String fullFileName = remoteDirectory != null ? remoteDirectory + getFilename(lsEntry) : getFilename(lsEntry);
            /*
				 * With recursion, the filename might contain subdirectory information
				 * normalize each file separately.
				 */
            String fileName = this.getRemoteFilename(fullFileName);
            String actualRemoteDirectory = this.getRemoteDirectory(fullFileName, fileName);
            File file = get(message, session, actualRemoteDirectory, fullFileName, fileName, lsEntry.getFileInfo());
            if (file != null) {
                files.add(file);
            }
        }
    } catch (Exception e) {
        if (files.size() > 0) {
            throw new PartialSuccessException(message, "Partially successful recursive 'mget' operation on " + (remoteDirectory != null ? remoteDirectory : "Client Working Directory"), e, files, remoteFiles);
        } else if (e instanceof MessagingException) {
            throw (MessagingException) e;
        } else if (e instanceof IOException) {
            throw (IOException) e;
        }
    }
    return files;
}
Also used : MessagingException(org.springframework.messaging.MessagingException) ArrayList(java.util.ArrayList) PartialSuccessException(org.springframework.integration.support.PartialSuccessException) IOException(java.io.IOException) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) IOException(java.io.IOException) PartialSuccessException(org.springframework.integration.support.PartialSuccessException) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) AbstractFileInfo(org.springframework.integration.file.remote.AbstractFileInfo)

Example 64 with MessagingException

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

the class MailUtils method extractStandardHeaders.

/**
 * Map the message headers to a Map using {@link MailHeaders} keys; specifically
 * maps the address headers and the subject.
 * @param source the message.
 * @return the map.
 */
public static Map<String, Object> extractStandardHeaders(Message source) {
    Map<String, Object> headers = new HashMap<String, Object>();
    try {
        headers.put(MailHeaders.FROM, convertToString(source.getFrom()));
        headers.put(MailHeaders.BCC, convertToStringArray(source.getRecipients(RecipientType.BCC)));
        headers.put(MailHeaders.CC, convertToStringArray(source.getRecipients(RecipientType.CC)));
        headers.put(MailHeaders.TO, convertToStringArray(source.getRecipients(RecipientType.TO)));
        headers.put(MailHeaders.REPLY_TO, convertToString(source.getReplyTo()));
        headers.put(MailHeaders.SUBJECT, source.getSubject());
        return headers;
    } catch (Exception e) {
        throw new MessagingException("conversion of MailMessage headers failed", e);
    }
}
Also used : HashMap(java.util.HashMap) MessagingException(org.springframework.messaging.MessagingException) MessagingException(org.springframework.messaging.MessagingException)

Example 65 with MessagingException

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

the class DefaultMailHeaderMapper method toHeaders.

@Override
public Map<String, Object> toHeaders(MimeMessage source) {
    Map<String, Object> headers = MailUtils.extractStandardHeaders(source);
    try {
        Enumeration<?> allHeaders = source.getAllHeaders();
        MultiValueMap<String, String> rawHeaders = new LinkedMultiValueMap<String, String>();
        while (allHeaders.hasMoreElements()) {
            Object headerInstance = allHeaders.nextElement();
            if (headerInstance instanceof Header) {
                Header header = (Header) headerInstance;
                rawHeaders.add(header.getName(), header.getValue());
            }
        }
        headers.put(MailHeaders.RAW_HEADERS, rawHeaders);
        headers.put(MailHeaders.FLAGS, source.getFlags());
        int lineCount = source.getLineCount();
        if (lineCount > 0) {
            headers.put(MailHeaders.LINE_COUNT, lineCount);
        }
        Date receivedDate = source.getReceivedDate();
        if (receivedDate != null) {
            headers.put(MailHeaders.RECEIVED_DATE, receivedDate);
        }
        int size = source.getSize();
        if (size > 0) {
            headers.put(MailHeaders.SIZE, size);
        }
        headers.put(MailHeaders.EXPUNGED, source.isExpunged());
        headers.put(MailHeaders.CONTENT_TYPE, source.getContentType());
    } catch (Exception e) {
        throw new MessagingException("Failed to map message headers", e);
    }
    return headers;
}
Also used : Header(javax.mail.Header) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MessagingException(org.springframework.messaging.MessagingException) Date(java.util.Date) MessagingException(org.springframework.messaging.MessagingException)

Aggregations

MessagingException (org.springframework.messaging.MessagingException)143 Test (org.junit.Test)60 IOException (java.io.IOException)25 Message (org.springframework.messaging.Message)23 QueueChannel (org.springframework.integration.channel.QueueChannel)22 ErrorMessage (org.springframework.messaging.support.ErrorMessage)21 CountDownLatch (java.util.concurrent.CountDownLatch)17 BeanFactory (org.springframework.beans.factory.BeanFactory)15 MessageChannel (org.springframework.messaging.MessageChannel)15 MessageHandlingException (org.springframework.messaging.MessageHandlingException)15 GenericMessage (org.springframework.messaging.support.GenericMessage)15 MessageHandler (org.springframework.messaging.MessageHandler)14 File (java.io.File)12 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)12 Matchers.containsString (org.hamcrest.Matchers.containsString)12 DirectChannel (org.springframework.integration.channel.DirectChannel)12 ArrayList (java.util.ArrayList)11 PollableChannel (org.springframework.messaging.PollableChannel)11 Lock (java.util.concurrent.locks.Lock)8 MessageDeliveryException (org.springframework.messaging.MessageDeliveryException)8