This is an automated email from the ASF dual-hosted git repository. rouazana pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/james-project.git
The following commit(s) were added to refs/heads/master by this push: new 291a594 JAMES-2578 Fix warning using Mailet new API 291a594 is described below commit 291a594422a35197f4f8a8aab74936012649df32 Author: Gautier DI FOLCO <gdifo...@linagora.com> AuthorDate: Tue Feb 19 18:57:24 2019 +0100 JAMES-2578 Fix warning using Mailet new API --- .../api/src/main/java/org/apache/mailet/Mail.java | 5 +- .../matcher/IsX509CertificateSubject.java | 55 ++++++------- .../james/transport/mailets/ICALToHeader.java | 40 ++++----- .../transport/mailets/ICALToJsonAttribute.java | 78 +++++++++--------- .../james/transport/mailets/ICalendarParser.java | 39 +++++---- .../james/transport/mailets/ICALToHeadersTest.java | 4 +- .../transport/mailets/ICALToJsonAttributeTest.java | 60 +++++++------- .../transport/mailets/ICalendarParserTest.java | 8 +- .../apache/james/transport/mailets/ClamAVScan.java | 15 +++- .../mailets/MailAttributesListToMimeHeaders.java | 37 ++++++--- .../mailets/MailAttributesToMimeHeaders.java | 34 ++++++-- .../transport/mailets/MimeDecodingMailet.java | 54 +++++++----- .../james/transport/mailets/RecoverAttachment.java | 96 ++++++++++++---------- .../james/transport/mailets/StripAttachment.java | 34 ++++---- .../james/transport/matchers/HasMailAttribute.java | 13 +-- .../matchers/HasMailAttributeWithValue.java | 52 +++--------- .../matchers/HasMailAttributeWithValueRegex.java | 20 ++--- .../transport/matchers/SMTPIsAuthNetwork.java | 25 ++++-- .../james/transport/matchers/SentByMailet.java | 11 ++- .../MailAttributesListToMimeHeadersTest.java | 26 +++--- .../transport/matchers/SMTPIsAuthNetworkTest.java | 4 +- .../james/transport/matchers/SentByMailetTest.java | 6 +- .../apache/mailet/base/test/FakeMailContext.java | 2 +- .../mailetcontainer/impl/JamesMailetContext.java | 4 +- .../apache/james/transport/mailets/DSNBounce.java | 13 +-- .../mailets/delivery/SimpleMailStore.java | 9 +- .../transport/mailets/jsieve/ActionUtils.java | 29 ++++--- .../remote/delivery/DeliveryRetriesHelper.java | 27 +++--- .../remote/delivery/DeliveryRetryHelperTest.java | 8 +- .../remote/delivery/DeliveryRunnableTest.java | 18 ++-- .../AddDefaultAttributesMessageHook.java | 2 +- .../org/apache/james/queue/file/FileMailQueue.java | 16 ++-- 32 files changed, 453 insertions(+), 391 deletions(-) diff --git a/mailet/api/src/main/java/org/apache/mailet/Mail.java b/mailet/api/src/main/java/org/apache/mailet/Mail.java index 34b4e19..637edea 100644 --- a/mailet/api/src/main/java/org/apache/mailet/Mail.java +++ b/mailet/api/src/main/java/org/apache/mailet/Mail.java @@ -82,10 +82,10 @@ public interface Mail extends Serializable, Cloneable { String DEFAULT = "root"; String ERROR = "error"; String TRANSPORT = "transport"; - String SENT_BY_MAILET = "org.apache.james.SentByMailet"; AttributeName SMTP_AUTH_USER = AttributeName.of("org.apache.james.SMTPAuthUser"); AttributeName MAILET_ERROR = AttributeName.of("org.apache.james.MailetError"); + Attribute SENT_BY_MAILET_ATTRIBUTE = Attribute.convertToAttribute("org.apache.james.SentByMailet", true); @Deprecated String SMTP_AUTH_USER_ATTRIBUTE_NAME = SMTP_AUTH_USER.asString(); @@ -93,6 +93,9 @@ public interface Mail extends Serializable, Cloneable { @Deprecated String MAILET_ERROR_ATTRIBUTE_NAME = MAILET_ERROR.asString(); + @Deprecated + String SENT_BY_MAILET = SENT_BY_MAILET_ATTRIBUTE.getName().asString(); + /** * Returns the name of this message. * diff --git a/mailet/crypto/src/main/java/org/apache/james/transport/matcher/IsX509CertificateSubject.java b/mailet/crypto/src/main/java/org/apache/james/transport/matcher/IsX509CertificateSubject.java index db3dbf0..cfebc6c 100644 --- a/mailet/crypto/src/main/java/org/apache/james/transport/matcher/IsX509CertificateSubject.java +++ b/mailet/crypto/src/main/java/org/apache/james/transport/matcher/IsX509CertificateSubject.java @@ -30,6 +30,8 @@ import java.util.List; import javax.mail.MessagingException; import org.apache.james.core.MailAddress; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMatcher; @@ -49,7 +51,7 @@ import org.apache.mailet.base.GenericMatcher; * */ public class IsX509CertificateSubject extends GenericMatcher { - protected String sourceAttribute; + protected AttributeName sourceAttribute; protected String check; @Override @@ -60,44 +62,41 @@ public class IsX509CertificateSubject extends GenericMatcher { } int pos = condition.indexOf(";"); - sourceAttribute = condition.substring(0,pos).trim(); + sourceAttribute = AttributeName.of(condition.substring(0,pos).trim()); check = condition.substring(pos + 1, condition.length()); } @Override - @SuppressWarnings("unchecked") public Collection<MailAddress> match(Mail mail) throws MessagingException { - List<X509Certificate> certificates; - - Object obj = mail.getAttribute(sourceAttribute); - if (obj != null) { - if (obj instanceof X509Certificate) { - certificates = Collections.singletonList((X509Certificate)obj); - } else { - certificates = (List<X509Certificate>) obj; - } - boolean valid = false; + return AttributeUtils.getAttributeValueFromMail(mail, sourceAttribute) + .map(this::getCertificates) + .filter(this::hasCertificate) + .map(any -> mail.getRecipients()) + .orElse(null); + } - for (X509Certificate cert : certificates) { - // Here I should use the method getSubjectX500Principal, but - // that would break the compatibility with jdk13. - Principal prin = cert.getSubjectDN(); - // TODO: Maybe here a more strong check should be done ... - if ((prin.toString().indexOf(check)) > 0) { - valid = true; - } + private boolean hasCertificate(List<X509Certificate> certificates) { + for (X509Certificate cert : certificates) { + // Here I should use the method getSubjectX500Principal, but + // that would break the compatibility with jdk13. + Principal prin = cert.getSubjectDN(); + // TODO: Maybe here a more strong check should be done ... + if ((prin.toString().indexOf(check)) > 0) { + return true; } + } - if (valid) { - return mail.getRecipients(); - } else { - return null; - } + return false; + } + + @SuppressWarnings("unchecked") + private List<X509Certificate> getCertificates(Object attributeValue) { + if (attributeValue instanceof X509Certificate) { + return Collections.singletonList((X509Certificate) attributeValue); } else { - return null; + return (List<X509Certificate>) attributeValue; } } - } diff --git a/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToHeader.java b/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToHeader.java index 1087374..6be5782 100644 --- a/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToHeader.java +++ b/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToHeader.java @@ -24,6 +24,8 @@ import java.util.Map; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; @@ -59,6 +61,7 @@ import net.fortuna.ical4j.model.component.VEvent; */ public class ICALToHeader extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(ICALToHeader.class); + private static final Class<Map<String, Calendar>> MAP_STRING_CALENDAR = (Class<Map<String, Calendar>>) (Object) Map.class; public static final String ATTRIBUTE_PROPERTY = "attribute"; public static final String ATTRIBUTE_DEFAULT_NAME = "icalendar"; @@ -73,7 +76,7 @@ public class ICALToHeader extends GenericMailet { ICal4JConfigurator.configure(); } - private String attribute; + private AttributeName attribute; @Override public String getMailetInfo() { @@ -82,37 +85,36 @@ public class ICALToHeader extends GenericMailet { @Override public void init() throws MessagingException { - attribute = getInitParameter(ATTRIBUTE_PROPERTY, ATTRIBUTE_DEFAULT_NAME); - if (Strings.isNullOrEmpty(attribute)) { - throw new MessagingException("Attribute " + attribute + " can not be empty or null"); + String attributeRaw = getInitParameter(ATTRIBUTE_PROPERTY, ATTRIBUTE_DEFAULT_NAME); + if (Strings.isNullOrEmpty(attributeRaw)) { + throw new MessagingException("Attribute " + attributeRaw + " can not be empty or null"); } + attribute = AttributeName.of(attributeRaw); } @Override public void service(Mail mail) throws MessagingException { - if (mail.getAttribute(attribute) == null) { - return; - } try { - getCalendarMap(mail) - .values() - .stream() - .findAny() - .ifPresent(Throwing.<Calendar>consumer(calendar -> writeToHeaders(calendar, mail)) - .sneakyThrow()); + AttributeUtils + .getValueAndCastFromMail(mail, attribute, MAP_STRING_CALENDAR) + .ifPresent(calendarMap -> processCalendars(calendarMap, mail)); } catch (ClassCastException e) { LOGGER.error("Received a mail with {} not being an ICAL object for mail {}", attribute, mail.getName(), e); } } - @VisibleForTesting - String getAttribute() { - return attribute; + private void processCalendars(Map<String, Calendar> calendarMap, Mail mail) { + calendarMap + .values() + .stream() + .findAny() + .ifPresent(Throwing.<Calendar>consumer(calendar -> writeToHeaders(calendar, mail)) + .sneakyThrow()); } - @SuppressWarnings("unchecked") - private Map<String, Calendar> getCalendarMap(Mail mail) { - return (Map<String, Calendar>) mail.getAttribute(attribute); + @VisibleForTesting + AttributeName getAttribute() { + return attribute; } private void writeToHeaders(Calendar calendar, Mail mail) throws MessagingException { diff --git a/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToJsonAttribute.java b/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToJsonAttribute.java index 630e23c..2298002 100644 --- a/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToJsonAttribute.java +++ b/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICALToJsonAttribute.java @@ -19,7 +19,6 @@ package org.apache.james.transport.mailets; -import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; @@ -36,7 +35,10 @@ import org.apache.james.core.MailAddress; import org.apache.james.transport.mailets.model.ICAL; import org.apache.james.util.OptionalUtils; import org.apache.james.util.StreamUtils; +import org.apache.mailet.Attribute; import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; @@ -47,6 +49,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.github.fge.lambdas.Throwing; import com.github.steveash.guavate.Guavate; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import net.fortuna.ical4j.model.Calendar; @@ -84,6 +87,8 @@ import net.fortuna.ical4j.model.Calendar; */ public class ICALToJsonAttribute extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(ICALToJsonAttribute.class); + private static final Class<Map<String, byte[]>> MAP_STRING_BYTES_CLASS = (Class<Map<String, byte[]>>) (Object) Map.class; + private static final Class<Map<String, Calendar>> MAP_STRING_CALENDAR_CLASS = (Class<Map<String, Calendar>>) (Object) Map.class; public static final String SOURCE_ATTRIBUTE_NAME = "source"; public static final String RAW_SOURCE_ATTRIBUTE_NAME = "rawSource"; @@ -103,24 +108,27 @@ public class ICALToJsonAttribute extends GenericMailet { } private final ObjectMapper objectMapper; - private String sourceAttributeName; - private String rawSourceAttributeName; - private String destinationAttributeName; + private AttributeName sourceAttributeName; + private AttributeName rawSourceAttributeName; + private AttributeName destinationAttributeName; public ICALToJsonAttribute() { this.objectMapper = new ObjectMapper() .registerModule(new Jdk8Module()); } - public String getSourceAttributeName() { + @VisibleForTesting + AttributeName getSourceAttributeName() { return sourceAttributeName; } - public String getRawSourceAttributeName() { + @VisibleForTesting + AttributeName getRawSourceAttributeName() { return rawSourceAttributeName; } - public String getDestinationAttributeName() { + @VisibleForTesting + AttributeName getDestinationAttributeName() { return destinationAttributeName; } @@ -131,54 +139,46 @@ public class ICALToJsonAttribute extends GenericMailet { @Override public void init() throws MessagingException { - sourceAttributeName = getInitParameter(SOURCE_ATTRIBUTE_NAME, DEFAULT_SOURCE_ATTRIBUTE_NAME); - rawSourceAttributeName = getInitParameter(RAW_SOURCE_ATTRIBUTE_NAME, DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME); - destinationAttributeName = getInitParameter(DESTINATION_ATTRIBUTE_NAME, DEFAULT_DESTINATION_ATTRIBUTE_NAME); - if (Strings.isNullOrEmpty(sourceAttributeName)) { + String sourceAttributeNameRaw = getInitParameter(SOURCE_ATTRIBUTE_NAME, DEFAULT_SOURCE_ATTRIBUTE_NAME); + String rawSourceAttributeNameRaw = getInitParameter(RAW_SOURCE_ATTRIBUTE_NAME, DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME); + String destinationAttributeNameRaw = getInitParameter(DESTINATION_ATTRIBUTE_NAME, DEFAULT_DESTINATION_ATTRIBUTE_NAME); + if (Strings.isNullOrEmpty(sourceAttributeNameRaw)) { throw new MessagingException(SOURCE_ATTRIBUTE_NAME + " configuration parameter can not be null or empty"); } - if (Strings.isNullOrEmpty(rawSourceAttributeName)) { + sourceAttributeName = AttributeName.of(sourceAttributeNameRaw); + if (Strings.isNullOrEmpty(rawSourceAttributeNameRaw)) { throw new MessagingException(RAW_SOURCE_ATTRIBUTE_NAME + " configuration parameter can not be null or empty"); } - if (Strings.isNullOrEmpty(destinationAttributeName)) { + rawSourceAttributeName = AttributeName.of(rawSourceAttributeNameRaw); + if (Strings.isNullOrEmpty(destinationAttributeNameRaw)) { throw new MessagingException(DESTINATION_ATTRIBUTE_NAME + " configuration parameter can not be null or empty"); } + destinationAttributeName = AttributeName.of(destinationAttributeNameRaw); } @Override public void service(Mail mail) throws MessagingException { - if (mail.getAttribute(sourceAttributeName) == null) { - return; - } - if (mail.getAttribute(rawSourceAttributeName) == null) { - return; - } - Optional<String> sender = retrieveSender(mail); - if (!sender.isPresent()) { - LOGGER.info("Skipping {} because no sender and no from", mail.getName()); - return; - } try { - Map<String, Calendar> calendars = getCalendarMap(mail); - Map<String, byte[]> rawCalendars = getRawCalendarMap(mail); - Map<String, byte[]> jsonsInByteForm = calendars.entrySet() - .stream() - .flatMap(calendar -> toJson(calendar, rawCalendars, mail, sender.get())) - .collect(Guavate.toImmutableMap(Pair::getKey, Pair::getValue)); - mail.setAttribute(destinationAttributeName, (Serializable) jsonsInByteForm); + AttributeUtils.getValueAndCastFromMail(mail, sourceAttributeName, MAP_STRING_CALENDAR_CLASS) + .ifPresent(calendars -> AttributeUtils.getValueAndCastFromMail(mail, rawSourceAttributeName, MAP_STRING_BYTES_CLASS) + .ifPresent(Throwing.<Map<String, byte[]>>consumer(rawCalendars -> + setAttribute(mail, calendars, rawCalendars)).sneakyThrow())); } catch (ClassCastException e) { LOGGER.error("Received a mail with {} not being an ICAL object for mail {}", sourceAttributeName, mail.getName(), e); } } - @SuppressWarnings("unchecked") - private Map<String, Calendar> getCalendarMap(Mail mail) { - return (Map<String, Calendar>) mail.getAttribute(sourceAttributeName); - } - - @SuppressWarnings("unchecked") - private Map<String, byte[]> getRawCalendarMap(Mail mail) { - return (Map<String, byte[]>) mail.getAttribute(rawSourceAttributeName); + private void setAttribute(Mail mail, Map<String, Calendar> calendars, Map<String, byte[]> rawCalendars) throws MessagingException { + Optional<String> sender = retrieveSender(mail); + if (!sender.isPresent()) { + LOGGER.info("Skipping {} because no sender and no from", mail.getName()); + return; + } + Map<String, byte[]> jsonsInByteForm = calendars.entrySet() + .stream() + .flatMap(calendar -> toJson(calendar, rawCalendars, mail, sender.get())) + .collect(Guavate.toImmutableMap(Pair::getKey, Pair::getValue)); + mail.setAttribute(new Attribute(destinationAttributeName, AttributeValue.ofAny(jsonsInByteForm))); } private Stream<Pair<String, byte[]>> toJson(Map.Entry<String, Calendar> entry, Map<String, byte[]> rawCalendars, Mail mail, String sender) { diff --git a/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICalendarParser.java b/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICalendarParser.java index 650a530..62318b5 100644 --- a/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICalendarParser.java +++ b/mailet/icalendar/src/main/java/org/apache/james/transport/mailets/ICalendarParser.java @@ -20,7 +20,6 @@ package org.apache.james.transport.mailets; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.stream.Stream; @@ -28,6 +27,10 @@ import java.util.stream.Stream; import javax.mail.MessagingException; import org.apache.commons.lang3.tuple.Pair; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; @@ -65,6 +68,7 @@ import net.fortuna.ical4j.model.Calendar; */ public class ICalendarParser extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(ICalendarParser.class); + private static final Class<Map<String, byte[]>> MAP_STRING_BYTES_CLASS = (Class<Map<String, byte[]>>) (Object) Map.class; public static final String SOURCE_ATTRIBUTE_PARAMETER_NAME = "sourceAttribute"; public static final String DESTINATION_ATTRIBUTE_PARAMETER_NAME = "destinationAttribute"; @@ -76,46 +80,48 @@ public class ICalendarParser extends GenericMailet { ICal4JConfigurator.configure(); } - private String sourceAttributeName; - private String destinationAttributeName; + private AttributeName sourceAttributeName; + private AttributeName destinationAttributeName; @Override public void init() throws MessagingException { - sourceAttributeName = getInitParameter(SOURCE_ATTRIBUTE_PARAMETER_NAME, SOURCE_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); - if (Strings.isNullOrEmpty(sourceAttributeName)) { + String sourceAttributeNameRaw = getInitParameter(SOURCE_ATTRIBUTE_PARAMETER_NAME, SOURCE_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); + if (Strings.isNullOrEmpty(sourceAttributeNameRaw)) { throw new MessagingException("source attribute cannot be empty"); } - destinationAttributeName = getInitParameter(DESTINATION_ATTRIBUTE_PARAMETER_NAME, DESTINATION_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); - if (Strings.isNullOrEmpty(destinationAttributeName)) { + sourceAttributeName = AttributeName.of(sourceAttributeNameRaw); + + String destinationAttributeNameRaw = getInitParameter(DESTINATION_ATTRIBUTE_PARAMETER_NAME, DESTINATION_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); + if (Strings.isNullOrEmpty(destinationAttributeNameRaw)) { throw new MessagingException("destination attribute cannot be empty"); } + destinationAttributeName = AttributeName.of(destinationAttributeNameRaw); } @VisibleForTesting - public String getSourceAttributeName() { + AttributeName getSourceAttributeName() { return sourceAttributeName; } @VisibleForTesting - public String getDestinationAttributeName() { + AttributeName getDestinationAttributeName() { return destinationAttributeName; } @Override - @SuppressWarnings("unchecked") public void service(Mail mail) throws MessagingException { - Object icsAttachmentsObj = mail.getAttribute(sourceAttributeName); - if (icsAttachmentsObj == null || !(icsAttachmentsObj instanceof Map)) { - return; - } + AttributeUtils + .getValueAndCastFromMail(mail, sourceAttributeName, MAP_STRING_BYTES_CLASS) + .ifPresent(icsAttachments -> addCalendarsToAttribute(mail, icsAttachments)); + } - Map<String, byte[]> icsAttachments = (Map<String, byte[]>) icsAttachmentsObj; + private void addCalendarsToAttribute(Mail mail, Map<String, byte[]> icsAttachments) { Map<String, Calendar> calendars = icsAttachments.entrySet() .stream() .flatMap(entry -> createCalendar(entry.getKey(), entry.getValue())) .collect(Guavate.toImmutableMap(Pair::getKey, Pair::getValue)); - mail.setAttribute(destinationAttributeName, (Serializable) calendars); + mail.setAttribute(new Attribute(destinationAttributeName, AttributeValue.ofAny(calendars))); } @Override @@ -140,5 +146,4 @@ public class ICalendarParser extends GenericMailet { return Stream.of(); } } - } diff --git a/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToHeadersTest.java b/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToHeadersTest.java index a3ce271..1af80f1 100644 --- a/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToHeadersTest.java +++ b/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToHeadersTest.java @@ -60,7 +60,7 @@ public class ICALToHeadersTest { .mailetName("ICALToHeader") .build()); - assertThat(testee.getAttribute()).isEqualTo(ICALToHeader.ATTRIBUTE_DEFAULT_NAME); + assertThat(testee.getAttribute().asString()).isEqualTo(ICALToHeader.ATTRIBUTE_DEFAULT_NAME); } @Test @@ -71,7 +71,7 @@ public class ICALToHeadersTest { .setProperty(ICALToHeader.ATTRIBUTE_PROPERTY, attribute) .build()); - assertThat(testee.getAttribute()).isEqualTo(attribute); + assertThat(testee.getAttribute().asString()).isEqualTo(attribute); } @Test diff --git a/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToJsonAttributeTest.java b/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToJsonAttributeTest.java index 8588657..5b0a3be 100644 --- a/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToJsonAttributeTest.java +++ b/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICALToJsonAttributeTest.java @@ -34,7 +34,9 @@ import org.apache.james.core.MailAddress; import org.apache.james.core.builder.MimeMessageBuilder; import org.apache.james.util.ClassLoaderUtils; import org.apache.james.util.MimeMessageUtil; +import org.apache.mailet.Attribute; import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.base.MailAddressFixture; import org.apache.mailet.base.test.FakeMail; @@ -73,8 +75,8 @@ public class ICALToJsonAttributeTest { public void initShouldSetAttributesWhenAbsent() throws Exception { testee.init(FakeMailetConfig.builder().build()); - assertThat(testee.getSourceAttributeName()).isEqualTo(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME); - assertThat(testee.getDestinationAttributeName()).isEqualTo(ICALToJsonAttribute.DEFAULT_DESTINATION_ATTRIBUTE_NAME); + assertThat(testee.getSourceAttributeName()).isEqualTo(ICALToJsonAttribute.DEFAULT_SOURCE); + assertThat(testee.getDestinationAttributeName()).isEqualTo(ICALToJsonAttribute.DEFAULT_DESTINATION); } @Test @@ -115,9 +117,9 @@ public class ICALToJsonAttributeTest { .setProperty(ICALToJsonAttribute.RAW_SOURCE_ATTRIBUTE_NAME, raw) .build()); - assertThat(testee.getSourceAttributeName()).isEqualTo(source); - assertThat(testee.getDestinationAttributeName()).isEqualTo(destination); - assertThat(testee.getRawSourceAttributeName()).isEqualTo(raw); + assertThat(testee.getSourceAttributeName().asString()).isEqualTo(source); + assertThat(testee.getDestinationAttributeName().asString()).isEqualTo(destination); + assertThat(testee.getRawSourceAttributeName().asString()).isEqualTo(raw); } @Test @@ -141,7 +143,7 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(MailAddressFixture.OTHER_AT_JAMES) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, "wrong type") + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.of("wrong type"))) .build(); testee.service(mail); @@ -156,7 +158,7 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(MailAddressFixture.OTHER_AT_JAMES) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, "wrong type") + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.of("wrong type"))) .build(); testee.service(mail); @@ -172,7 +174,7 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(MailAddressFixture.OTHER_AT_JAMES) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, wrongParametrizedMap) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(wrongParametrizedMap))) .build(); testee.service(mail); @@ -188,7 +190,7 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(MailAddressFixture.OTHER_AT_JAMES) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, wrongParametrizedMap) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(wrongParametrizedMap))) .build(); testee.service(mail); @@ -205,8 +207,8 @@ public class ICALToJsonAttributeTest { ImmutableMap<String, Calendar> icals = ImmutableMap.of("key", calendar); Mail mail = FakeMail.builder() .recipient(MailAddressFixture.OTHER_AT_JAMES) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, icals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(icals))) .build(); testee.service(mail); @@ -225,8 +227,8 @@ public class ICALToJsonAttributeTest { ImmutableMap<String, byte[]> rawIcals = ImmutableMap.of("key", ics); Mail mail = FakeMail.builder() .sender(SENDER) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -247,8 +249,8 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(recipient) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -285,8 +287,8 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipients(MailAddressFixture.OTHER_AT_JAMES, MailAddressFixture.ANY_AT_JAMES2) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -333,8 +335,8 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(recipient) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -381,8 +383,8 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(recipient) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -419,8 +421,8 @@ public class ICALToJsonAttributeTest { Mail mail = FakeMail.builder() .sender(SENDER) .recipient(recipient) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -458,8 +460,8 @@ public class ICALToJsonAttributeTest { .recipient(recipient) .mimeMessage(MimeMessageBuilder.mimeMessageBuilder() .addFrom(from)) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -494,8 +496,8 @@ public class ICALToJsonAttributeTest { .sender(SENDER) .recipient(recipient) .mimeMessage(MimeMessageUtil.defaultMimeMessage()) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); @@ -531,8 +533,8 @@ public class ICALToJsonAttributeTest { .recipient(recipient) .mimeMessage(MimeMessageBuilder.mimeMessageBuilder() .addFrom(from)) - .attribute(ICALToJsonAttribute.DEFAULT_SOURCE_ATTRIBUTE_NAME, icals) - .attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE_ATTRIBUTE_NAME, rawIcals) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_SOURCE, AttributeValue.ofAny(icals))) + .attribute(new Attribute(ICALToJsonAttribute.DEFAULT_RAW_SOURCE, AttributeValue.ofAny(rawIcals))) .build(); testee.service(mail); diff --git a/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICalendarParserTest.java b/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICalendarParserTest.java index 9e57b09..801f20f 100644 --- a/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICalendarParserTest.java +++ b/mailet/icalendar/src/test/java/org/apache/james/transport/mailets/ICalendarParserTest.java @@ -70,7 +70,7 @@ public class ICalendarParserTest { .mailetName("ICalendarParser") .build()); - assertThat(mailet.getSourceAttributeName()).isEqualTo(ICalendarParser.SOURCE_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); + assertThat(mailet.getSourceAttributeName().asString()).isEqualTo(ICalendarParser.SOURCE_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); } @Test @@ -79,7 +79,7 @@ public class ICalendarParserTest { .mailetName("ICalendarParser") .build()); - assertThat(mailet.getDestinationAttributeName()).isEqualTo(ICalendarParser.DESTINATION_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); + assertThat(mailet.getDestinationAttributeName().asString()).isEqualTo(ICalendarParser.DESTINATION_ATTRIBUTE_PARAMETER_DEFAULT_VALUE); } @Test @@ -90,7 +90,7 @@ public class ICalendarParserTest { .setProperty(ICalendarParser.SOURCE_ATTRIBUTE_PARAMETER_NAME, sourceAttribute) .build()); - assertThat(mailet.getSourceAttributeName()).isEqualTo(sourceAttribute); + assertThat(mailet.getSourceAttributeName().asString()).isEqualTo(sourceAttribute); } @Test @@ -101,7 +101,7 @@ public class ICalendarParserTest { .setProperty(ICalendarParser.DESTINATION_ATTRIBUTE_PARAMETER_NAME, destinationAttribute) .build()); - assertThat(mailet.getDestinationAttributeName()).isEqualTo(destinationAttribute); + assertThat(mailet.getDestinationAttributeName().asString()).isEqualTo(destinationAttribute); } @Test diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/ClamAVScan.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/ClamAVScan.java index 79c6e53..cb009ad 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/ClamAVScan.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/ClamAVScan.java @@ -40,6 +40,9 @@ import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.james.core.MailAddress; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Experimental; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMailet; @@ -198,7 +201,7 @@ public class ClamAVScan extends GenericMailet { private static final String FOUND_STRING = "FOUND"; - private static final String MAIL_ATTRIBUTE_NAME = "org.apache.james.infected"; + private static final AttributeName MAIL_ATTRIBUTE_NAME = AttributeName.of("org.apache.james.infected"); private static final String HEADER_NAME = "X-MessageIsInfected"; @@ -588,7 +591,7 @@ public class ClamAVScan extends GenericMailet { public void service(Mail mail) throws MessagingException { // if already checked no action - if (mail.getAttribute(MAIL_ATTRIBUTE_NAME) != null) { + if (mail.getAttribute(MAIL_ATTRIBUTE_NAME).isPresent()) { return; } @@ -662,7 +665,7 @@ public class ClamAVScan extends GenericMailet { logMessageInfo(mimeMessage); // mark the mail with a mail attribute to check later on by other matchers/mailets - mail.setAttribute(MAIL_ATTRIBUTE_NAME, "true"); + mail.setAttribute(makeAttribute(true)); // sets the error message to be shown in any "notifyXxx" message mail.setErrorMessage(sb.toString()); @@ -674,7 +677,7 @@ public class ClamAVScan extends GenericMailet { if (isDebug()) { LOGGER.debug("OK (by CLAMD on {})", socket.getInetAddress()); } - mail.setAttribute(MAIL_ATTRIBUTE_NAME, "false"); + mail.setAttribute(makeAttribute(false)); // mark the message with a header string mimeMessage.setHeader(HEADER_NAME, "false"); @@ -694,6 +697,10 @@ public class ClamAVScan extends GenericMailet { } + private Attribute makeAttribute(boolean value) { + return new Attribute(MAIL_ATTRIBUTE_NAME, AttributeValue.of(value)); + } + /** * Tries to "ping" all the CLAMD daemons to * check if they are up and accepting requests. diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeaders.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeaders.java index 2b26a71..c485bfa 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeaders.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeaders.java @@ -29,11 +29,14 @@ import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.james.util.OptionalUtils; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.steveash.guavate.Guavate; import com.google.common.base.Strings; /** @@ -51,7 +54,7 @@ import com.google.common.base.Strings; public class MailAttributesListToMimeHeaders extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(MailAttributesListToMimeHeaders.class); - private Map<String, String> attributeNameToHeader; + private Map<AttributeName, String> attributeNameToHeader; @Override public void init() throws MessagingException { @@ -60,7 +63,14 @@ public class MailAttributesListToMimeHeaders extends GenericMailet { throw new MessagingException("simplemapping is required"); } - attributeNameToHeader = MappingArgument.parse(simpleMappings); + attributeNameToHeader = MappingArgument + .parse(simpleMappings) + .entrySet() + .stream() + .collect(Guavate.toImmutableMap( + entry -> AttributeName.of(entry.getKey()), + entry -> entry.getValue() + )); } @Override @@ -71,17 +81,18 @@ public class MailAttributesListToMimeHeaders extends GenericMailet { message.saveChanges(); } - private void addAttributeToHeader(Mail mail, MimeMessage message, Entry<String, String> entry) { - Serializable attribute = mail.getAttribute(entry.getKey()); - if (attribute instanceof Collection) { - @SuppressWarnings("unchecked") - Optional<Collection<Serializable>> values = Optional.of((Collection<Serializable>) attribute); - addCollectionToHeader(message, entry.getValue(), values); - } else { - if (attribute != null) { - LOGGER.warn("Can not add {} to headers. Expecting class Collection but got {}.", attribute, attribute.getClass()); - } - } + private void addAttributeToHeader(Mail mail, MimeMessage message, Entry<AttributeName, String> entry) { + AttributeUtils + .getAttributeValueFromMail(mail, entry.getKey()) + .ifPresent(attribute -> { + if (attribute instanceof Collection) { + @SuppressWarnings("unchecked") + Optional<Collection<Serializable>> values = Optional.of((Collection<Serializable>) attribute); + addCollectionToHeader(message, entry.getValue(), values); + } else { + LOGGER.warn("Can not add {} to headers. Expecting class Collection but got {}.", attribute, attribute.getClass()); + } + }); } private void addCollectionToHeader(MimeMessage message, String headerName, Optional<Collection<Serializable>> values) { diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesToMimeHeaders.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesToMimeHeaders.java index c1b37ee..f4f8f7f 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesToMimeHeaders.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/MailAttributesToMimeHeaders.java @@ -19,16 +19,20 @@ package org.apache.james.transport.mailets; -import java.util.Map; import java.util.Map.Entry; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMailet; +import com.github.fge.lambdas.Throwing; +import com.github.steveash.guavate.Guavate; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; /** * <p>Convert attributes of type String to headers</p> @@ -44,7 +48,7 @@ import com.google.common.base.Strings; */ public class MailAttributesToMimeHeaders extends GenericMailet { - private Map<String, String> mappings; + private ImmutableMap<AttributeName, String> mappings; @Override public void init() throws MessagingException { @@ -54,20 +58,32 @@ public class MailAttributesToMimeHeaders extends GenericMailet { throw new MessagingException("simplemapping is required"); } - mappings = MappingArgument.parse(simpleMappings); + mappings = MappingArgument + .parse(simpleMappings) + .entrySet() + .stream() + .collect(Guavate.toImmutableMap( + entry -> AttributeName.of(entry.getKey()), + entry -> entry.getValue())); } @Override public void service(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); - for (Entry<String, String> entry : mappings.entrySet()) { - String value = (String) mail.getAttribute(entry.getKey()); - if (value != null) { + mappings + .entrySet() + .stream() + .forEach(entry -> addHeader(entry, mail, message)); + message.saveChanges(); + } + + private void addHeader(Entry<AttributeName, String> entry, Mail mail, MimeMessage message) { + AttributeUtils + .getValueAndCastFromMail(mail, entry.getKey(), String.class) + .ifPresent(Throwing.<String>consumer(value -> { String headerName = entry.getValue(); message.addHeader(headerName, value); - } - } - message.saveChanges(); + }).sneakyThrow()); } } diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/MimeDecodingMailet.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/MimeDecodingMailet.java index b9402bd..1dc3a30 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/MimeDecodingMailet.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/MimeDecodingMailet.java @@ -20,19 +20,27 @@ package org.apache.james.transport.mailets; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.Serializable; import java.util.Map; import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Stream; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.james.util.OptionalUtils; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.MailetException; import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.fge.lambdas.Throwing; +import com.github.steveash.guavate.Guavate; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; @@ -52,42 +60,48 @@ public class MimeDecodingMailet extends GenericMailet { public static final String ATTRIBUTE_PARAMETER_NAME = "attribute"; - private String attribute; + private AttributeName attributeName; @Override public void init() throws MessagingException { - attribute = getInitParameter(ATTRIBUTE_PARAMETER_NAME); - if (Strings.isNullOrEmpty(attribute)) { + String attributeRaw = getInitParameter(ATTRIBUTE_PARAMETER_NAME); + if (Strings.isNullOrEmpty(attributeRaw)) { throw new MailetException("No value for " + ATTRIBUTE_PARAMETER_NAME + " parameter was provided."); } + + attributeName = AttributeName.of(attributeRaw); } @Override public void service(Mail mail) throws MessagingException { - if (mail.getAttribute(attribute) == null) { - return; - } + mail.getAttribute(attributeName) + .ifPresent(Throwing.<Attribute>consumer(attribute -> setAttribute(mail, attribute)).sneakyThrow()); + } - ImmutableMap.Builder<String, byte[]> extractedMimeContentByName = ImmutableMap.builder(); - for (Map.Entry<String, byte[]> entry: getAttributeContent(mail).entrySet()) { - Optional<byte[]> maybeContent = extractContent(entry.getValue()); - if (maybeContent.isPresent()) { - extractedMimeContentByName.put(entry.getKey(), maybeContent.get()); - } - } - mail.setAttribute(attribute, extractedMimeContentByName.build()); + private void setAttribute(Mail mail, Attribute attribute) throws MailetException { + Function<Map.Entry<String, byte[]>, Stream<Pair<String, byte[]>>> convertToMapContent = Throwing.<Map.Entry<String, byte[]>, Stream<Pair<String, byte[]>>>function(entry -> + OptionalUtils.toStream(extractContent(entry.getValue()) + .map(content -> Pair.of(entry.getKey(), content)))).sneakyThrow(); + + ImmutableMap<String, byte[]> extractedMimeContentByName = getAttributeContent(attribute) + .entrySet() + .stream() + .flatMap(convertToMapContent) + .collect(Guavate.toImmutableMap(Pair::getKey, Pair::getValue)); + + mail.setAttribute(new Attribute(attributeName, AttributeValue.ofAny(extractedMimeContentByName))); } @SuppressWarnings("unchecked") - private Map<String, byte[]> getAttributeContent(Mail mail) throws MailetException { - Serializable attributeContent = mail.getAttribute(attribute); - if (! (attributeContent instanceof Map)) { + private Map<String, byte[]> getAttributeContent(Attribute attribute) throws MailetException { + Object attributeValue = attribute.getValue().value(); + if (! (attributeValue instanceof Map)) { LOGGER.debug("Invalid attribute found into attribute {} class Map expected but {} found.", - attribute, attributeContent.getClass()); + attribute, attributeValue.getClass()); return ImmutableMap.of(); } - return (Map<String, byte[]>) attributeContent; + return (Map<String, byte[]>) attributeValue; } private Optional<byte[]> extractContent(Object rawMime) throws MessagingException { diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/RecoverAttachment.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/RecoverAttachment.java index 26d50b6..7e31ff1 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/RecoverAttachment.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/RecoverAttachment.java @@ -31,6 +31,8 @@ import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Experimental; import org.apache.mailet.Mail; import org.apache.mailet.MailetException; @@ -38,6 +40,8 @@ import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.fge.lambdas.Throwing; + /** * <p> * This mailet takes an attachment stored in an attribute and attach it back to @@ -61,21 +65,23 @@ import org.slf4j.LoggerFactory; @Experimental public class RecoverAttachment extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(RecoverAttachment.class); + private static final Class<Map<String, byte[]>> MAP_STRING_BYTES_CLASS = (Class<Map<String, byte[]>>) (Object) Map.class; - public static final String ATTRIBUTE_PARAMETER_NAME = "attribute"; + private static final String ATTRIBUTE_PARAMETER_NAME = "attribute"; - private String attributeName = null; + private AttributeName attributeName; @Override public void init() throws MailetException { - attributeName = getInitParameter(ATTRIBUTE_PARAMETER_NAME); + String attributeNameRaw = getInitParameter(ATTRIBUTE_PARAMETER_NAME); - if (attributeName == null) { + if (attributeNameRaw == null) { throw new MailetException(ATTRIBUTE_PARAMETER_NAME + " is a mandatory parameter"); } - LOGGER.debug("RecoverAttachment is initialised with attribute [{}]", attributeName); + LOGGER.debug("RecoverAttachment is initialised with attribute [{}]", attributeNameRaw); + attributeName = AttributeName.of(attributeNameRaw); } /** @@ -89,48 +95,50 @@ public class RecoverAttachment extends GenericMailet { */ @Override public void service(Mail mail) throws MailetException { - @SuppressWarnings("unchecked") - Map<String, byte[]> attachments = (Map<String, byte[]>) mail.getAttribute(attributeName); - if (attachments != null) { - - MimeMessage message; - try { - message = mail.getMessage(); - } catch (MessagingException e) { - throw new MailetException( - "Could not retrieve message from Mail object", e); - } + AttributeUtils + .getValueAndCastFromMail(mail, attributeName, MAP_STRING_BYTES_CLASS) + .ifPresent(Throwing.<Map<String, byte[]>>consumer(attachments -> + processAttachment(mail, attachments)).sneakyThrow()); + } + + private void processAttachment(Mail mail, Map<String, byte[]> attachments) throws MailetException { + MimeMessage message; + try { + message = mail.getMessage(); + } catch (MessagingException e) { + throw new MailetException( + "Could not retrieve message from Mail object", e); + } - Iterator<byte[]> i = attachments.values().iterator(); - try { - while (i.hasNext()) { - byte[] bytes = i.next(); - InputStream is = new BufferedInputStream( - new ByteArrayInputStream(bytes)); - MimeBodyPart p = new MimeBodyPart(is); - if (!(message.isMimeType("multipart/*") && (message - .getContent() instanceof MimeMultipart))) { - Object content = message.getContent(); - String contentType = message.getContentType(); - MimeMultipart mimeMultipart = new MimeMultipart(); - message.setContent(mimeMultipart); - // This saveChanges is required when the MimeMessage has - // been created from - // an InputStream, otherwise it is not saved correctly. - message.saveChanges(); - mimeMultipart.setParent(message); - MimeBodyPart bodyPart = new MimeBodyPart(); - mimeMultipart.addBodyPart(bodyPart); - bodyPart.setContent(content, contentType); - } - ((MimeMultipart) message.getContent()).addBodyPart(p); + Iterator<byte[]> i = attachments.values().iterator(); + try { + while (i.hasNext()) { + byte[] bytes = i.next(); + InputStream is = new BufferedInputStream( + new ByteArrayInputStream(bytes)); + MimeBodyPart p = new MimeBodyPart(is); + if (!(message.isMimeType("multipart/*") && (message + .getContent() instanceof MimeMultipart))) { + Object content = message.getContent(); + String contentType = message.getContentType(); + MimeMultipart mimeMultipart = new MimeMultipart(); + message.setContent(mimeMultipart); + // This saveChanges is required when the MimeMessage has + // been created from + // an InputStream, otherwise it is not saved correctly. + message.saveChanges(); + mimeMultipart.setParent(message); + MimeBodyPart bodyPart = new MimeBodyPart(); + mimeMultipart.addBodyPart(bodyPart); + bodyPart.setContent(content, contentType); } - message.saveChanges(); - } catch (MessagingException e) { - LOGGER.error("MessagingException in recoverAttachment", e); - } catch (IOException e) { - LOGGER.error("IOException in recoverAttachment", e); + ((MimeMultipart) message.getContent()).addBodyPart(p); } + message.saveChanges(); + } catch (MessagingException e) { + LOGGER.error("MessagingException in recoverAttachment", e); + } catch (IOException e) { + LOGGER.error("IOException in recoverAttachment", e); } } diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java index 45d23ae..36b2990 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/StripAttachment.java @@ -24,10 +24,8 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -60,9 +58,11 @@ import org.apache.mailet.base.GenericMailet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.fge.lambdas.Throwing; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; /** * <p> @@ -91,6 +91,7 @@ import com.google.common.collect.ImmutableList; */ public class StripAttachment extends GenericMailet { private static final Logger LOGGER = LoggerFactory.getLogger(StripAttachment.class); + private static final Class<Map<String, byte[]>> MAP_STRING_BYTES_CLASS = (Class<Map<String, byte[]>>) (Object) Map.class; @SuppressWarnings("unchecked") private static final Class<List<AttributeValue<String>>> LIST_OF_STRINGS = (Class<List<AttributeValue<String>>>)(Object) List.class; @@ -115,7 +116,7 @@ public class StripAttachment extends GenericMailet { @VisibleForTesting String removeAttachments; private String directoryName; - private String attributeName; + private Optional<AttributeName> attributeName; private Pattern regExPattern; private Pattern notRegExPattern; private String mimeType; @@ -140,7 +141,7 @@ public class StripAttachment extends GenericMailet { } directoryName = getInitParameter(DIRECTORY_PARAMETER_NAME); - attributeName = getInitParameter(ATTRIBUTE_PARAMETER_NAME); + attributeName = getInitParameterAsOptional(ATTRIBUTE_PARAMETER_NAME).map(AttributeName::of); removeAttachments = getInitParameter(REMOVE_ATTACHMENT_PARAMETER_NAME, REMOVE_NONE).toLowerCase(Locale.US); if (!removeAttachments.equals(REMOVE_MATCHED) && !removeAttachments.equals(REMOVE_ALL) && !removeAttachments.equals(REMOVE_NONE)) { @@ -201,11 +202,11 @@ public class StripAttachment extends GenericMailet { logMessage.append(directoryName); logMessage.append(']'); } - if (attributeName != null) { + attributeName.ifPresent(attributeName -> { logMessage.append(" and will store attachments to attribute ["); - logMessage.append(attributeName); + logMessage.append(attributeName.asString()); logMessage.append(']'); - } + }); LOGGER.debug(logMessage.toString()); } } @@ -352,21 +353,20 @@ public class StripAttachment extends GenericMailet { } private void storeBodyPartAsMailAttribute(BodyPart bodyPart, Mail mail, String fileName) throws IOException, MessagingException { - if (attributeName != null) { - addPartContent(bodyPart, mail, fileName); - } + attributeName.ifPresent(Throwing.<AttributeName>consumer(attributeName -> + addPartContent(bodyPart, mail, fileName, attributeName)).sneakyThrow()); } - private void addPartContent(BodyPart bodyPart, Mail mail, String fileName) throws IOException, MessagingException { - @SuppressWarnings("unchecked") - Map<String, byte[]> fileNamesToPartContent = (Map<String, byte[]>) mail.getAttribute(attributeName); - if (fileNamesToPartContent == null) { - fileNamesToPartContent = new LinkedHashMap<>(); - mail.setAttribute(attributeName, (Serializable) fileNamesToPartContent); - } + private void addPartContent(BodyPart bodyPart, Mail mail, String fileName, AttributeName attributeName) throws IOException, MessagingException { + ImmutableMap.Builder<String, byte[]> fileNamesToPartContent = AttributeUtils + .getValueAndCastFromMail(mail, attributeName, MAP_STRING_BYTES_CLASS) + .map(ImmutableMap.<String, byte[]>builder()::putAll) + .orElse(ImmutableMap.builder()); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bodyPart.writeTo(new BufferedOutputStream(byteArrayOutputStream)); fileNamesToPartContent.put(fileName, byteArrayOutputStream.toByteArray()); + mail.setAttribute(new Attribute(attributeName, AttributeValue.ofAny(fileNamesToPartContent.build()))); } private void storeFileNameAsAttribute(Mail mail, AttributeValue<String> fileName, boolean hasToBeStored) { diff --git a/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttribute.java b/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttribute.java index ffe6666..9b0f2c0 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttribute.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttribute.java @@ -26,6 +26,7 @@ import java.util.Collection; import javax.mail.MessagingException; import org.apache.james.core.MailAddress; +import org.apache.mailet.AttributeName; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMatcher; @@ -42,7 +43,7 @@ import org.apache.mailet.base.GenericMatcher; **/ public class HasMailAttribute extends GenericMatcher { - private String attributeName; + private AttributeName attributeName; @Override public String getMatcherInfo() { @@ -51,7 +52,7 @@ public class HasMailAttribute extends GenericMatcher { @Override public void init() throws MessagingException { - attributeName = getCondition(); + attributeName = AttributeName.of(getCondition()); } /** @@ -62,10 +63,10 @@ public class HasMailAttribute extends GenericMatcher { **/ @Override public Collection<MailAddress> match(Mail mail) throws MessagingException { - if (mail.getAttribute(attributeName) != null) { - return mail.getRecipients(); - } - return null; + return mail + .getAttribute(attributeName) + .map(any -> mail.getRecipients()) + .orElse(null); } } diff --git a/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValue.java b/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValue.java index ac02bee..e317699 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValue.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValue.java @@ -26,6 +26,8 @@ import java.util.Collection; import javax.mail.MessagingException; import org.apache.james.core.MailAddress; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMatcher; @@ -70,7 +72,7 @@ public class HasMailAttributeWithValue extends GenericMatcher { /** * The name of the attribute to match */ - private String fieldAttributeName; + private AttributeName fieldAttributeName; /** * The value of the attribute to match @@ -86,45 +88,11 @@ public class HasMailAttributeWithValue extends GenericMatcher { */ @Override public Collection<MailAddress> match(Mail mail) throws MessagingException { - Object attributeValue = mail.getAttribute(getAttributeName()); - - if (attributeValue != null - && attributeValue.toString().trim().equals(getAttributeValue())) { - return mail.getRecipients(); - } - return null; - } - - /** - * Returns the attributeName. - * @return String - */ - protected String getAttributeName() { - return fieldAttributeName; - } - - /** - * Returns the attributeValue. - * @return String - */ - protected String getAttributeValue() { - return fieldAttributeValue; - } - - /** - * Sets the attributeName. - * @param attributeName The attributeName to set - */ - protected void setAttributeName(String attributeName) { - fieldAttributeName = attributeName; - } - - /** - * Sets the attributeValue. - * @param attributeValue The attributeValue to set - */ - protected void setAttributeValue(String attributeValue) { - fieldAttributeValue = attributeValue; + return AttributeUtils + .getAttributeValueFromMail(mail, fieldAttributeName) + .filter(attributeValue -> attributeValue.toString().trim().equals(fieldAttributeValue)) + .map(any -> mail.getRecipients()) + .orElse(null); } @Override @@ -140,8 +108,8 @@ public class HasMailAttributeWithValue extends GenericMatcher { throw new MessagingException("Syntax Error. Missing attribute name."); } - setAttributeName(condition.substring(0, commaPosition).trim()); - setAttributeValue(condition.substring(commaPosition + 1).trim()); + fieldAttributeName = AttributeName.of(condition.substring(0, commaPosition).trim()); + fieldAttributeValue = condition.substring(commaPosition + 1).trim(); } @Override diff --git a/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValueRegex.java b/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValueRegex.java index 9dc822e..3a56f17 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValueRegex.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/matchers/HasMailAttributeWithValueRegex.java @@ -21,7 +21,6 @@ package org.apache.james.transport.matchers; -import java.io.Serializable; import java.util.Collection; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -29,6 +28,8 @@ import java.util.regex.PatternSyntaxException; import javax.mail.MessagingException; import org.apache.james.core.MailAddress; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.MatcherConfig; import org.apache.mailet.base.GenericMatcher; @@ -49,7 +50,7 @@ import org.apache.mailet.base.GenericMatcher; **/ public class HasMailAttributeWithValueRegex extends GenericMatcher { - private String attributeName; + private AttributeName attributeName; private Pattern pattern = null; @Override @@ -62,8 +63,8 @@ public class HasMailAttributeWithValueRegex extends GenericMatcher { String condition = conf.getCondition(); int idx = condition.indexOf(','); if (idx != -1) { - attributeName = condition.substring(0,idx).trim(); - String patternString = condition.substring(idx + 1, condition.length()).trim(); + attributeName = AttributeName.of(condition.substring(0,idx).trim()); + String patternString = condition.substring(idx + 1).trim(); try { pattern = Pattern.compile(patternString); } catch (PatternSyntaxException mpe) { @@ -83,12 +84,11 @@ public class HasMailAttributeWithValueRegex extends GenericMatcher { **/ @Override public Collection<MailAddress> match(Mail mail) throws MessagingException { - Serializable obj = mail.getAttribute(attributeName); - //to be a little more generic the toString of the value is what is matched against - if (obj != null && pattern.matcher(obj.toString()).matches()) { - return mail.getRecipients(); - } - return null; + return AttributeUtils + .getAttributeValueFromMail(mail, attributeName) + .filter(obj -> pattern.matcher(obj.toString()).matches()) + .map(any -> mail.getRecipients()) + .orElse(null); } } diff --git a/mailet/standard/src/main/java/org/apache/james/transport/matchers/SMTPIsAuthNetwork.java b/mailet/standard/src/main/java/org/apache/james/transport/matchers/SMTPIsAuthNetwork.java index e50b076..7ea745f 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/matchers/SMTPIsAuthNetwork.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/matchers/SMTPIsAuthNetwork.java @@ -20,9 +20,14 @@ package org.apache.james.transport.matchers; import java.util.Collection; -import java.util.Objects; +import java.util.function.Function; import org.apache.james.core.MailAddress; +import org.apache.james.util.FunctionalUtils; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMatcher; @@ -42,16 +47,18 @@ public class SMTPIsAuthNetwork extends GenericMatcher { /** * The mail attribute which is set if the client is allowed to relay */ - public static final String SMTP_AUTH_NETWORK_NAME = "org.apache.james.SMTPIsAuthNetwork"; + private static final AttributeName SMTP_AUTH_NETWORK_NAME = AttributeName.of("org.apache.james.SMTPIsAuthNetwork"); @Override public Collection<MailAddress> match(Mail mail) { - String relayingAllowed = (String) mail - .getAttribute(SMTP_AUTH_NETWORK_NAME); - if (Objects.equals(relayingAllowed, "true")) { - return mail.getRecipients(); - } else { - return ImmutableList.of(); - } + return AttributeUtils + .getValueAndCastFromMail(mail, SMTP_AUTH_NETWORK_NAME, Boolean.class) + .filter(FunctionalUtils.toPredicate(Function.identity())) + .map(any -> mail.getRecipients()) + .orElse(ImmutableList.of()); + } + + public static Attribute makeAttribute(Boolean value) { + return new Attribute(SMTP_AUTH_NETWORK_NAME, AttributeValue.of(value)); } } diff --git a/mailet/standard/src/main/java/org/apache/james/transport/matchers/SentByMailet.java b/mailet/standard/src/main/java/org/apache/james/transport/matchers/SentByMailet.java index 896a27d..e26844a 100644 --- a/mailet/standard/src/main/java/org/apache/james/transport/matchers/SentByMailet.java +++ b/mailet/standard/src/main/java/org/apache/james/transport/matchers/SentByMailet.java @@ -22,6 +22,7 @@ package org.apache.james.transport.matchers; import java.util.Collection; import org.apache.james.core.MailAddress; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.GenericMatcher; @@ -40,11 +41,9 @@ public class SentByMailet extends GenericMatcher { @Override public Collection<MailAddress> match(Mail mail) { - String authUser = (String) mail.getAttribute(Mail.SENT_BY_MAILET); - if (authUser != null) { - return mail.getRecipients(); - } else { - return ImmutableList.of(); - } + return AttributeUtils + .getAttributeValueFromMail(mail, Mail.SENT_BY_MAILET_ATTRIBUTE.getName()) + .map(any -> mail.getRecipients()) + .orElse(ImmutableList.of()); } } diff --git a/mailet/standard/src/test/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeadersTest.java b/mailet/standard/src/test/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeadersTest.java index 1849155..ddb4d12 100644 --- a/mailet/standard/src/test/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeadersTest.java +++ b/mailet/standard/src/test/java/org/apache/james/transport/mailets/MailAttributesListToMimeHeadersTest.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import javax.mail.MessagingException; import org.apache.james.core.builder.MimeMessageBuilder; +import org.apache.mailet.Attribute; import org.apache.mailet.Mailet; import org.apache.mailet.base.test.FakeMail; import org.apache.mailet.base.test.FakeMailetConfig; @@ -50,6 +51,9 @@ class MailAttributesListToMimeHeadersTest { private static final String HEADER_NAME1 = "JUNIT"; private static final String HEADER_NAME2 = "JUNIT2"; + private static final Attribute MAIL_ATTRIBUTE1 = Attribute.convertToAttribute(MAIL_ATTRIBUTE_NAME1, MAIL_ATTRIBUTE_VALUE1); + private static final Attribute MAIL_ATTRIBUTE2 = Attribute.convertToAttribute(MAIL_ATTRIBUTE_NAME2, MAIL_ATTRIBUTE_VALUE2); + private Mailet mailet; @BeforeEach @@ -92,8 +96,8 @@ class MailAttributesListToMimeHeadersTest { FakeMail mail = FakeMail.builder() .mimeMessage(MailUtil.createMimeMessage()) - .attribute(MAIL_ATTRIBUTE_NAME1, MAIL_ATTRIBUTE_VALUE1) - .attribute(MAIL_ATTRIBUTE_NAME2, MAIL_ATTRIBUTE_VALUE2) + .attribute(MAIL_ATTRIBUTE1) + .attribute(MAIL_ATTRIBUTE2) .build(); mailet.service(mail); @@ -112,7 +116,7 @@ class MailAttributesListToMimeHeadersTest { FakeMail mail = FakeMail.builder() .mimeMessage(MailUtil.createMimeMessage()) - .attribute(MAIL_ATTRIBUTE_NAME1, MAIL_ATTRIBUTE_VALUE1) + .attribute(MAIL_ATTRIBUTE1) .build(); mailet.service(mail); @@ -137,7 +141,7 @@ class MailAttributesListToMimeHeadersTest { listWithNull.add("2"); FakeMail mail = FakeMail.builder() .mimeMessage(MailUtil.createMimeMessage()) - .attribute(MAIL_ATTRIBUTE_NAME1, listWithNull) + .attribute(Attribute.convertToAttribute(MAIL_ATTRIBUTE_NAME1, listWithNull)) .build(); mailet.service(mail); @@ -159,9 +163,9 @@ class MailAttributesListToMimeHeadersTest { FakeMail mail = FakeMail.builder() .mimeMessage(MailUtil.createMimeMessage()) - .attribute(MAIL_ATTRIBUTE_NAME1, MAIL_ATTRIBUTE_VALUE1) - .attribute(MAIL_ATTRIBUTE_NAME2, MAIL_ATTRIBUTE_VALUE2) - .attribute("unmatched.attribute", "value") + .attribute(MAIL_ATTRIBUTE1) + .attribute(MAIL_ATTRIBUTE2) + .attribute(Attribute.convertToAttribute("unmatched.attribute", "value")) .build(); mailet.service(mail); @@ -185,7 +189,7 @@ class MailAttributesListToMimeHeadersTest { FakeMail mail = FakeMail.builder() .mimeMessage(MimeMessageBuilder.mimeMessageBuilder() .addHeader(HEADER_NAME1, firstValue)) - .attribute(MAIL_ATTRIBUTE_NAME1, MAIL_ATTRIBUTE_VALUE1) + .attribute(MAIL_ATTRIBUTE1) .build(); mailet.service(mail); @@ -206,8 +210,8 @@ class MailAttributesListToMimeHeadersTest { FakeMail mail = FakeMail.builder() .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()) - .attribute(MAIL_ATTRIBUTE_NAME1, 3L) - .attribute(MAIL_ATTRIBUTE_NAME2, MAIL_ATTRIBUTE_VALUE2) + .attribute(Attribute.convertToAttribute(MAIL_ATTRIBUTE_NAME1, 3L)) + .attribute(MAIL_ATTRIBUTE2) .build(); mailet.service(mail); @@ -229,7 +233,7 @@ class MailAttributesListToMimeHeadersTest { String value = "value"; FakeMail mail = FakeMail.builder() .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()) - .attribute(MAIL_ATTRIBUTE_NAME1, ImmutableList.of(3L, value)) + .attribute(Attribute.convertToAttribute(MAIL_ATTRIBUTE_NAME1, ImmutableList.of(3L, value))) .build(); mailet.service(mail); diff --git a/mailet/standard/src/test/java/org/apache/james/transport/matchers/SMTPIsAuthNetworkTest.java b/mailet/standard/src/test/java/org/apache/james/transport/matchers/SMTPIsAuthNetworkTest.java index 9860001..30b68a4 100644 --- a/mailet/standard/src/test/java/org/apache/james/transport/matchers/SMTPIsAuthNetworkTest.java +++ b/mailet/standard/src/test/java/org/apache/james/transport/matchers/SMTPIsAuthNetworkTest.java @@ -52,7 +52,7 @@ public class SMTPIsAuthNetworkTest { public void matchShouldReturnAddressesWhenAuthorizedNetwork() throws Exception { Mail mail = FakeMail.builder() .recipient(recipient) - .attribute(SMTPIsAuthNetwork.SMTP_AUTH_NETWORK_NAME, "true") + .attribute(SMTPIsAuthNetwork.makeAttribute(true)) .build(); assertThat(testee.match(mail)) @@ -63,7 +63,7 @@ public class SMTPIsAuthNetworkTest { public void matchShouldReturnEmptyWhenNonAuthorizedNetwork() throws Exception { Mail mail = FakeMail.builder() .recipient(recipient) - .attribute(SMTPIsAuthNetwork.SMTP_AUTH_NETWORK_NAME, "false") + .attribute(SMTPIsAuthNetwork.makeAttribute(false)) .build(); assertThat(testee.match(mail)) diff --git a/mailet/standard/src/test/java/org/apache/james/transport/matchers/SentByMailetTest.java b/mailet/standard/src/test/java/org/apache/james/transport/matchers/SentByMailetTest.java index 4b5ee71..a89754a 100644 --- a/mailet/standard/src/test/java/org/apache/james/transport/matchers/SentByMailetTest.java +++ b/mailet/standard/src/test/java/org/apache/james/transport/matchers/SentByMailetTest.java @@ -24,6 +24,8 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import org.apache.james.core.MailAddress; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.apache.mailet.base.MailAddressFixture; import org.apache.mailet.base.test.FakeMail; @@ -49,7 +51,7 @@ public class SentByMailetTest { MailAddress recipient = MailAddressFixture.ANY_AT_JAMES; FakeMail fakeMail = FakeMail.builder() .recipient(recipient) - .attribute(Mail.SENT_BY_MAILET, "true") + .attribute(Mail.SENT_BY_MAILET_ATTRIBUTE) .build(); Collection<MailAddress> results = testee.match(fakeMail); @@ -83,7 +85,7 @@ public class SentByMailetTest { public void matchShouldReturnEmptyCollectionWhenAuthUserAttributeIsPresentAndThereIsNoRecipient() throws Exception { FakeMail fakeMail = FakeMail.builder() .recipients() - .attribute(Mail.SENT_BY_MAILET, "true") + .attribute(Mail.SENT_BY_MAILET_ATTRIBUTE) .build(); Collection<MailAddress> results = testee.match(fakeMail); diff --git a/mailet/test/src/main/java/org/apache/mailet/base/test/FakeMailContext.java b/mailet/test/src/main/java/org/apache/mailet/base/test/FakeMailContext.java index 5794158..8dc8ce8 100644 --- a/mailet/test/src/main/java/org/apache/mailet/base/test/FakeMailContext.java +++ b/mailet/test/src/main/java/org/apache/mailet/base/test/FakeMailContext.java @@ -198,7 +198,7 @@ public class FakeMailContext implements MailetContext { public SentMail build() throws MessagingException { if (fromMailet.orElse(false)) { - this.attribute(Mail.SENT_BY_MAILET, "true"); + this.attribute(Mail.SENT_BY_MAILET_ATTRIBUTE); } return new SentMail(sender, recipients.orElse(ImmutableList.<MailAddress>of()), msg, ImmutableMap.copyOf(attributes), state.orElse(Mail.DEFAULT), delay); diff --git a/server/mailet/mailetcontainer-camel/src/main/java/org/apache/james/mailetcontainer/impl/JamesMailetContext.java b/server/mailet/mailetcontainer-camel/src/main/java/org/apache/james/mailetcontainer/impl/JamesMailetContext.java index 9e575cd..c8c495e 100644 --- a/server/mailet/mailetcontainer-camel/src/main/java/org/apache/james/mailetcontainer/impl/JamesMailetContext.java +++ b/server/mailet/mailetcontainer-camel/src/main/java/org/apache/james/mailetcontainer/impl/JamesMailetContext.java @@ -408,14 +408,14 @@ public class JamesMailetContext implements MailetContext, Configurable { @Override public void sendMail(Mail mail, String state) throws MessagingException { - mail.setAttribute(Mail.SENT_BY_MAILET, "true"); + mail.setAttribute(Mail.SENT_BY_MAILET_ATTRIBUTE); mail.setState(state); rootMailQueue.enQueue(mail); } @Override public void sendMail(Mail mail, String state, long delay, TimeUnit unit) throws MessagingException { - mail.setAttribute(Mail.SENT_BY_MAILET, "true"); + mail.setAttribute(Mail.SENT_BY_MAILET_ATTRIBUTE); mail.setState(state); rootMailQueue.enQueue(mail, delay, unit); } diff --git a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/DSNBounce.java b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/DSNBounce.java index 6f10b51..7849626 100755 --- a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/DSNBounce.java +++ b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/DSNBounce.java @@ -55,6 +55,8 @@ import org.apache.james.transport.util.ReplyToUtils; import org.apache.james.transport.util.SenderUtils; import org.apache.james.transport.util.SpecialAddressesUtils; import org.apache.james.transport.util.TosUtils; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.apache.mailet.base.DateFormats; import org.apache.mailet.base.GenericMailet; @@ -115,6 +117,7 @@ public class DSNBounce extends GenericMailet implements RedirectNotify { private static final Pattern DIAG_PATTERN = Patterns.compilePatternUncheckedException("^\\d{3}\\s.*$"); private static final String MACHINE_PATTERN = "[machine]"; private static final String LINE_BREAK = "\n"; + private static final AttributeName DELIVERY_ERROR = AttributeName.of("delivery-error"); private final DNSService dns; private final FastDateFormat dateFormatter; @@ -353,7 +356,7 @@ public class DSNBounce extends GenericMailet implements RedirectNotify { } buffer.append(LINE_BREAK).append(LINE_BREAK); buffer.append("Error message:").append(LINE_BREAK); - buffer.append((String) originalMail.getAttribute("delivery-error")).append(LINE_BREAK); + buffer.append(AttributeUtils.getValueAndCastFromMail(originalMail, DELIVERY_ERROR, String.class).orElse("")).append(LINE_BREAK); buffer.append(LINE_BREAK); MimeBodyPart bodyPart = new MimeBodyPart(); @@ -417,11 +420,9 @@ public class DSNBounce extends GenericMailet implements RedirectNotify { } private String getDeliveryError(Mail originalMail) { - String deliveryError = (String) originalMail.getAttribute("delivery-error"); - if (deliveryError != null) { - return deliveryError; - } - return "unknown"; + return AttributeUtils + .getValueAndCastFromMail(originalMail, DELIVERY_ERROR, String.class) + .orElse("unknown"); } private String getDiagnosticType(String diagnosticCode) { diff --git a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/delivery/SimpleMailStore.java b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/delivery/SimpleMailStore.java index 41708b8..15b2c09 100644 --- a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/delivery/SimpleMailStore.java +++ b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/delivery/SimpleMailStore.java @@ -26,6 +26,8 @@ import org.apache.james.mailbox.model.ComposedMessageId; import org.apache.james.metrics.api.Metric; import org.apache.james.user.api.UsersRepository; import org.apache.james.user.api.UsersRepositoryException; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; import org.apache.mailet.Mail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,10 +102,9 @@ public class SimpleMailStore implements MailStore { } private String locateFolder(String username, Mail mail) { - if (mail.getAttribute(DELIVERY_PATH_PREFIX + username) instanceof String) { - return (String) mail.getAttribute(DELIVERY_PATH_PREFIX + username); - } - return folder; + return AttributeUtils + .getValueAndCastFromMail(mail, AttributeName.of(DELIVERY_PATH_PREFIX + username), String.class) + .orElse(folder); } private String computeUsername(MailAddress recipient) { diff --git a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/jsieve/ActionUtils.java b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/jsieve/ActionUtils.java index 25a4002..960cb0c 100644 --- a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/jsieve/ActionUtils.java +++ b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/jsieve/ActionUtils.java @@ -22,10 +22,16 @@ package org.apache.james.transport.mailets.jsieve; import javax.mail.MessagingException; import org.apache.james.core.MailAddress; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.github.fge.lambdas.Throwing; + /** * Utility methods helpful for actions. */ @@ -65,16 +71,17 @@ public class ActionUtils { public static void detectAndHandleLocalLooping(Mail aMail, ActionContext context, String anAttributeSuffix) throws MessagingException { MailAddress thisRecipient = getSoleRecipient(aMail); - MailAddress lastRecipient = (MailAddress) aMail - .getAttribute(ATTRIBUTE_PREFIX + anAttributeSuffix); - if (null != lastRecipient && lastRecipient.equals(thisRecipient)) { - MessagingException ex = new MessagingException( - "This message is looping! Message ID: " - + aMail.getMessage().getMessageID()); - LOGGER.warn(ex.getMessage(), ex); - throw ex; - } - aMail.setAttribute(ATTRIBUTE_PREFIX + anAttributeSuffix, - thisRecipient); + AttributeName attributeName = AttributeName.of(ATTRIBUTE_PREFIX + anAttributeSuffix); + AttributeUtils + .getValueAndCastFromMail(aMail, attributeName, MailAddress.class) + .filter(lastRecipient -> lastRecipient.equals(thisRecipient)) + .ifPresent(Throwing.consumer(any -> { + MessagingException ex = new MessagingException( + "This message is looping! Message ID: " + + aMail.getMessage().getMessageID()); + LOGGER.warn(ex.getMessage(), ex); + throw ex; + }).sneakyThrow()); + aMail.setAttribute(new Attribute(attributeName, AttributeValue.ofSerializable(thisRecipient))); } } diff --git a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetriesHelper.java b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetriesHelper.java index 08071e5..d476366 100644 --- a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetriesHelper.java +++ b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetriesHelper.java @@ -19,32 +19,31 @@ package org.apache.james.transport.mailets.remote.delivery; -import java.io.Serializable; - +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; public class DeliveryRetriesHelper { - public static final String DELIVERY_RETRY_COUNT = "delivery_retry_count"; + public static final AttributeName DELIVERY_RETRY_COUNT = AttributeName.of("delivery_retry_count"); public static int retrieveRetries(Mail mail) { - try { - Serializable value = mail.getAttribute(DELIVERY_RETRY_COUNT); - if (value != null) { - return (Integer) value; - } - return 0; - } catch (ClassCastException e) { - return 0; - } + return AttributeUtils + .getValueAndCastFromMail(mail, DELIVERY_RETRY_COUNT, Integer.class) + .orElse(0); } public static void initRetries(Mail mail) { - mail.setAttribute(DELIVERY_RETRY_COUNT, 0); + mail.setAttribute(makeAttribute(0)); } public static void incrementRetries(Mail mail) { - mail.setAttribute(DELIVERY_RETRY_COUNT, retrieveRetries(mail) + 1); + mail.setAttribute(makeAttribute(retrieveRetries(mail) + 1)); } + public static Attribute makeAttribute(Integer value) { + return new Attribute(DELIVERY_RETRY_COUNT, AttributeValue.of(value)); + } } diff --git a/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetryHelperTest.java b/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetryHelperTest.java index 0348a74..66f4917 100644 --- a/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetryHelperTest.java +++ b/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRetryHelperTest.java @@ -22,11 +22,15 @@ package org.apache.james.transport.mailets.remote.delivery; import static org.assertj.core.api.Assertions.assertThat; import org.apache.james.transport.mailets.remote.delivery.DeliveryRetriesHelper; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeValue; import org.apache.mailet.base.test.FakeMail; import org.junit.Test; public class DeliveryRetryHelperTest { + private static final Attribute INVALID_ATTRIBUTE = new Attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, AttributeValue.of("invalid")); + @Test public void retrieveRetriesShouldBeZeroByDefault() throws Exception { assertThat(DeliveryRetriesHelper.retrieveRetries(FakeMail.defaultFakeMail())) @@ -66,7 +70,7 @@ public class DeliveryRetryHelperTest { @Test public void retrieveRetriesShouldBeZeroOnInvalidValue() throws Exception { - FakeMail mail = FakeMail.builder().attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, "invalid").build(); + FakeMail mail = FakeMail.builder().attribute(INVALID_ATTRIBUTE).build(); assertThat(DeliveryRetriesHelper.retrieveRetries(mail)) .isEqualTo(0); @@ -74,7 +78,7 @@ public class DeliveryRetryHelperTest { @Test public void incrementRetriesShouldWorkOnInvalidMails() throws Exception { - FakeMail mail = FakeMail.builder().attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, "invalid").build(); + FakeMail mail = FakeMail.builder().attribute(INVALID_ATTRIBUTE).build(); DeliveryRetriesHelper.incrementRetries(mail); diff --git a/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRunnableTest.java b/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRunnableTest.java index 6324f5e..622c929 100644 --- a/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRunnableTest.java +++ b/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remote/delivery/DeliveryRunnableTest.java @@ -142,7 +142,7 @@ public class DeliveryRunnableTest { testee.attemptDelivery(fakeMail); verify(mailQueue).enQueue(FakeMail.builder() - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 1) + .attribute(DeliveryRetriesHelper.makeAttribute(1)) .state(Mail.ERROR) .lastUpdated(FIXED_DATE) .build(), @@ -155,7 +155,7 @@ public class DeliveryRunnableTest { public void deliveryTemporaryFailureShouldRetryDeliveryWithRightDelay() throws Exception { FakeMail fakeMail = FakeMail.builder() .state(Mail.ERROR) - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 2) + .attribute(DeliveryRetriesHelper.makeAttribute(2)) .build(); Exception exception = new Exception(); when(mailDelivrer.deliver(fakeMail)).thenReturn(ExecutionResult.temporaryFailure(exception)); @@ -163,7 +163,7 @@ public class DeliveryRunnableTest { testee.attemptDelivery(fakeMail); verify(mailQueue).enQueue(FakeMail.builder() - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 3) + .attribute(DeliveryRetriesHelper.makeAttribute(3)) .state(Mail.ERROR) .lastUpdated(FIXED_DATE) .build(), @@ -176,7 +176,7 @@ public class DeliveryRunnableTest { public void deliveryTemporaryFailureShouldRetryDeliveryOnMaximumRetryNumber() throws Exception { FakeMail fakeMail = FakeMail.builder() .state(Mail.ERROR) - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 4) + .attribute(DeliveryRetriesHelper.makeAttribute(4)) .build(); Exception exception = new Exception(); when(mailDelivrer.deliver(fakeMail)).thenReturn(ExecutionResult.temporaryFailure(exception)); @@ -184,7 +184,7 @@ public class DeliveryRunnableTest { testee.attemptDelivery(fakeMail); verify(mailQueue).enQueue(FakeMail.builder() - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 5) + .attribute(DeliveryRetriesHelper.makeAttribute(5)) .state(Mail.ERROR) .lastUpdated(FIXED_DATE) .build(), @@ -197,7 +197,7 @@ public class DeliveryRunnableTest { public void deliveryTemporaryFailureShouldNotRetryDeliveryOverMaximumRetryNumber() throws Exception { FakeMail fakeMail = FakeMail.builder() .state(Mail.ERROR) - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 5) + .attribute(DeliveryRetriesHelper.makeAttribute(5)) .build(); Exception exception = new Exception(); when(mailDelivrer.deliver(fakeMail)).thenReturn(ExecutionResult.temporaryFailure(exception)); @@ -211,7 +211,7 @@ public class DeliveryRunnableTest { public void deliveryTemporaryFailureShouldBounceWhenRetryExceeded() throws Exception { FakeMail fakeMail = FakeMail.builder() .state(Mail.ERROR) - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 5) + .attribute(DeliveryRetriesHelper.makeAttribute(5)) .build(); Exception exception = new Exception(""); when(mailDelivrer.deliver(fakeMail)).thenReturn(ExecutionResult.temporaryFailure(exception)); @@ -226,7 +226,7 @@ public class DeliveryRunnableTest { public void deliveryTemporaryFailureShouldResetDeliveryCountOnNonErrorState() throws Exception { FakeMail fakeMail = FakeMail.builder() .state(Mail.DEFAULT) - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 5) + .attribute(DeliveryRetriesHelper.makeAttribute(5)) .build(); Exception exception = new Exception(); when(mailDelivrer.deliver(fakeMail)).thenReturn(ExecutionResult.temporaryFailure(exception)); @@ -234,7 +234,7 @@ public class DeliveryRunnableTest { testee.attemptDelivery(fakeMail); verify(mailQueue).enQueue(FakeMail.builder() - .attribute(DeliveryRetriesHelper.DELIVERY_RETRY_COUNT, 1) + .attribute(DeliveryRetriesHelper.makeAttribute(1)) .state(Mail.ERROR) .lastUpdated(FIXED_DATE) .build(), diff --git a/server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/AddDefaultAttributesMessageHook.java b/server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/AddDefaultAttributesMessageHook.java index 1412cdf..9b6a55d 100644 --- a/server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/AddDefaultAttributesMessageHook.java +++ b/server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/AddDefaultAttributesMessageHook.java @@ -59,7 +59,7 @@ public class AddDefaultAttributesMessageHook implements JamesMessageHook { } if (session.isRelayingAllowed()) { - mail.setAttribute(SMTP_AUTH_NETWORK_NAME, "true"); + mail.setAttribute(Attribute.convertToAttribute(SMTP_AUTH_NETWORK_NAME, true)); } } return HookResult.DECLINED; diff --git a/server/queue/queue-file/src/main/java/org/apache/james/queue/file/FileMailQueue.java b/server/queue/queue-file/src/main/java/org/apache/james/queue/file/FileMailQueue.java index a4d851a..613504b 100644 --- a/server/queue/queue-file/src/main/java/org/apache/james/queue/file/FileMailQueue.java +++ b/server/queue/queue-file/src/main/java/org/apache/james/queue/file/FileMailQueue.java @@ -54,6 +54,10 @@ import org.apache.james.queue.api.ManageableMailQueue; import org.apache.james.server.core.MimeMessageCopyOnWriteProxy; import org.apache.james.server.core.MimeMessageSource; import org.apache.james.util.concurrent.NamedThreadFactory; +import org.apache.mailet.Attribute; +import org.apache.mailet.AttributeName; +import org.apache.mailet.AttributeUtils; +import org.apache.mailet.AttributeValue; import org.apache.mailet.Mail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,7 +84,7 @@ public class FileMailQueue implements ManageableMailQueue { private final boolean sync; private static final String MSG_EXTENSION = ".msg"; private static final String OBJECT_EXTENSION = ".obj"; - private static final String NEXT_DELIVERY = "FileQueueNextDelivery"; + private static final AttributeName NEXT_DELIVERY = AttributeName.of("FileQueueNextDelivery"); private static final int SPLITCOUNT = 10; private static final SecureRandom RANDOM = new SecureRandom(); private final String queueName; @@ -163,11 +167,9 @@ public class FileMailQueue implements ManageableMailQueue { } private Optional<ZonedDateTime> getNextDelivery(Mail mail) { - Long next = (Long) mail.getAttribute(NEXT_DELIVERY); - if (next == null) { - return Optional.empty(); - } - return Optional.of(Instant.ofEpochMilli(next).atZone(ZoneId.systemDefault())); + return AttributeUtils + .getValueAndCastFromMail(mail, NEXT_DELIVERY, Long.class) + .map(next -> Instant.ofEpochMilli(next).atZone(ZoneId.systemDefault())); } @Override @@ -180,7 +182,7 @@ public class FileMailQueue implements ManageableMailQueue { final FileItem item = new FileItem(name + OBJECT_EXTENSION, name + MSG_EXTENSION); if (delay > 0) { - mail.setAttribute(NEXT_DELIVERY, System.currentTimeMillis() + unit.toMillis(delay)); + mail.setAttribute(new Attribute(NEXT_DELIVERY, AttributeValue.of(System.currentTimeMillis() + unit.toMillis(delay)))); } try (FileOutputStream foout = new FileOutputStream(item.getObjectFile()); ObjectOutputStream oout = new ObjectOutputStream(foout)) { --------------------------------------------------------------------- To unsubscribe, e-mail: server-dev-unsubscr...@james.apache.org For additional commands, e-mail: server-dev-h...@james.apache.org