001/*
002 * Copyright 2006-2010 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.item.mail;
017
018import org.springframework.mail.MailException;
019import org.springframework.mail.MailMessage;
020import org.springframework.mail.MailSendException;
021
022/**
023 * This {@link MailErrorHandler} implementation simply rethrows the exception it
024 * receives.
025 * 
026 * @author Dan Garrette
027 * @author Dave Syer
028 * 
029 * @since 2.1
030 */
031public class DefaultMailErrorHandler implements MailErrorHandler {
032
033        private static final int DEFAULT_MAX_MESSAGE_LENGTH = 1024;
034
035        private int maxMessageLength = DEFAULT_MAX_MESSAGE_LENGTH;
036
037        /**
038         * The limit for the size of message that will be copied to the exception
039         * message. Output will be truncated beyond that. Default value is 1024.
040         * 
041         * @param maxMessageLength the maximum message length
042         */
043        public void setMaxMessageLength(int maxMessageLength) {
044                this.maxMessageLength = maxMessageLength;
045        }
046
047        /**
048         * Wraps the input exception with a runtime {@link MailException}. The
049         * exception message will contain the failed message (using toString).
050         * 
051         * @param message a failed message
052         * @param exception a MessagingException
053         * @throws MailException a translation of the Exception
054         * @see MailErrorHandler#handle(MailMessage, Exception)
055         */
056    @Override
057        public void handle(MailMessage message, Exception exception) throws MailException {
058                String msg = message.toString();
059                throw new MailSendException("Mail server send failed: "
060                                + msg.substring(0, Math.min(maxMessageLength, msg.length())), exception);
061        }
062}