james-server-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From btell...@apache.org
Subject [james-project] 07/07: JAMES-2881 Add test for HeadersToHTTP/SerialiseToHTTP mailets
Date Tue, 24 Sep 2019 01:44:42 GMT
This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit f78ad40ad0309a5366e6a6adb9efa31ee3936422
Author: splainez <splainez@users.noreply.github.com>
AuthorDate: Thu Sep 12 00:36:17 2019 +0200

    JAMES-2881 Add test for HeadersToHTTP/SerialiseToHTTP mailets
    
    Added tests, and fixed errors in the request of SerialiseToHTTP
---
 mailet/standard/pom.xml                            |   4 +
 .../james/transport/mailets/SerialiseToHTTP.java   |  48 ++--
 .../james/transport/mailets/HeadersToHTTPTest.java | 241 +++++++++++++++++++
 .../transport/mailets/SerialiseToHTTPTest.java     | 262 +++++++++++++++++++++
 .../src/test/resources/mime/sendToRemoteHttp.mime  | 153 ++++++++++++
 5 files changed, 685 insertions(+), 23 deletions(-)

diff --git a/mailet/standard/pom.xml b/mailet/standard/pom.xml
index f07ea9e..5a23eb7 100644
--- a/mailet/standard/pom.xml
+++ b/mailet/standard/pom.xml
@@ -114,6 +114,10 @@
         </dependency>
         <dependency>
             <groupId>org.slf4j</groupId>
+            <artifactId>jcl-over-slf4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
         </dependency>
     </dependencies>
diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/SerialiseToHTTP.java
b/mailet/standard/src/main/java/org/apache/james/transport/mailets/SerialiseToHTTP.java
index 713e4d7..88bbca4 100644
--- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/SerialiseToHTTP.java
+++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/SerialiseToHTTP.java
@@ -16,11 +16,10 @@
  * specific language governing permissions and limitations      *
  * under the License.                                           *
  ****************************************************************/
+
 package org.apache.james.transport.mailets;
 
-import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
 import java.net.URL;
 
@@ -35,6 +34,7 @@ import org.apache.http.client.methods.RequestBuilder;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClientBuilder;
 import org.apache.http.message.BasicNameValuePair;
+import org.apache.james.util.MimeMessageUtil;
 import org.apache.mailet.Experimental;
 import org.apache.mailet.Mail;
 import org.apache.mailet.base.GenericMailet;
@@ -117,19 +117,28 @@ public class SerialiseToHTTP extends GenericMailet {
      */
     @Override
     public void service(Mail mail) {
+        MimeMessage message;
         try {
-            MimeMessage message = mail.getMessage();
-            String serialisedMessage = getSerialisedMessage(message);
-            NameValuePair[] nameValuePairs = getNameValuePairs(serialisedMessage);
-            String result = httpPost(nameValuePairs);
-            if (passThrough) {
-                addHeader(mail, (result == null || result.length() == 0), result);
-            } else {
-                mail.setState(Mail.GHOST);
-            }
-        } catch (MessagingException | IOException me) {
+            message = mail.getMessage();
+        } catch (MessagingException me) {
             LOGGER.error("Messaging exception", me);
             addHeader(mail, false, me.getMessage());
+            return;
+        }
+        String messageAsString;
+        try {
+            messageAsString = MimeMessageUtil.asString(message);
+        } catch (Exception e) {
+            LOGGER.error("Message to string exception", e);
+            addHeader(mail, false, e.getMessage());
+            return;
+        }
+
+        String result = httpPost(getNameValuePairs(messageAsString));
+        if (passThrough) {
+            addHeader(mail, (result == null || result.length() == 0), result);
+        } else {
+            mail.setState(Mail.GHOST);
         }
     }
 
@@ -146,20 +155,13 @@ public class SerialiseToHTTP extends GenericMailet {
         }
     }
 
-    private String getSerialisedMessage(MimeMessage message)
-            throws IOException, MessagingException {
-        ByteArrayOutputStream os = new ByteArrayOutputStream();
-        message.writeTo(os);
-        return os.toString();
-    }
-
     private String httpPost(NameValuePair[] data) {
 
         RequestBuilder requestBuilder = RequestBuilder.post(url);
 
-        if (data.length > 1 && data[1] != null) {
-            requestBuilder.addParameter(data[1].getName(),data[1].getValue());
-            LOGGER.debug("{}::{}", data[1].getName(), data[1].getValue());
+        for (NameValuePair parameter : data) {
+            requestBuilder.addParameter(parameter);
+            LOGGER.debug("{}::{}", parameter.getName(), parameter.getValue());
         }
 
 
@@ -180,7 +182,7 @@ public class SerialiseToHTTP extends GenericMailet {
         }
     }
 
-    private NameValuePair[] getNameValuePairs(String message) throws UnsupportedEncodingException
{
+    private NameValuePair[] getNameValuePairs(String message) {
 
         int l = 1;
         if (parameterKey != null && parameterKey.length() > 0) {
diff --git a/mailet/standard/src/test/java/org/apache/james/transport/mailets/HeadersToHTTPTest.java
b/mailet/standard/src/test/java/org/apache/james/transport/mailets/HeadersToHTTPTest.java
new file mode 100644
index 0000000..c6e6f16
--- /dev/null
+++ b/mailet/standard/src/test/java/org/apache/james/transport/mailets/HeadersToHTTPTest.java
@@ -0,0 +1,241 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import javax.mail.MessagingException;
+
+import org.apache.http.ExceptionLogger;
+import org.apache.http.HttpStatus;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.utils.URLEncodedUtils;
+import org.apache.http.config.SocketConfig;
+import org.apache.http.entity.BasicHttpEntity;
+import org.apache.http.impl.bootstrap.HttpServer;
+import org.apache.http.impl.bootstrap.ServerBootstrap;
+import org.apache.http.message.BasicHttpEntityEnclosingRequest;
+import org.apache.http.protocol.UriHttpRequestHandlerMapper;
+import org.apache.http.util.EntityUtils;
+import org.apache.james.util.MimeMessageUtil;
+import org.apache.mailet.Mail;
+import org.apache.mailet.Mailet;
+import org.apache.mailet.base.test.FakeMailetConfig;
+import org.apache.mailet.base.test.MailUtil;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class HeadersToHTTPTest {
+
+    private static HttpServer server;
+    private static UriHttpRequestHandlerMapper mapper;
+    private Mail mail;
+
+    private String urlTestPattern;
+
+    @BeforeAll
+    static void setupServer() throws MessagingException, IOException {
+        mapper = new UriHttpRequestHandlerMapper();
+
+        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(50000).build();
+        server = ServerBootstrap.bootstrap().setListenerPort(0).setSocketConfig(socketConfig)
+                .setExceptionLogger(ExceptionLogger.NO_OP).setHandlerMapper(mapper).create();
+
+        server.start();
+
+    }
+
+    @AfterAll
+    static void shutdown() {
+        server.shutdown(5L, TimeUnit.SECONDS);
+    }
+
+    @BeforeEach
+    void setup() throws MessagingException, IOException {
+        mail = MailUtil.createMockMail2Recipients(MimeMessageUtil.mimeMessageFromStream(
+                ClassLoader.getSystemResourceAsStream("mime/sendToRemoteHttp.mime")));
+    }
+
+    @AfterEach
+    void cleanMapper() throws MessagingException, IOException {
+        mapper.unregister(urlTestPattern);
+    }
+
+    @Test
+    void shouldBeFailedWhenServiceNotExists() throws Exception {
+
+        urlTestPattern = "/path/to/service/failed";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("url", "http://qwerty.localhost:123456" + urlTestPattern).build();
+
+        Mailet mailet = new HeadersToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-headerToHTTP")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isEqualTo("Failed"));
+        assertThat(mail.getMessage().getHeader("X-headerToHTTPFailure")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isNotBlank());
+
+    }
+
+    @Test
+    void shouldBeSucceededWhenServiceResponseIsOk() throws Exception {
+
+        urlTestPattern = "/path/to/service/succeeded";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("url", "http://" + server.getInetAddress().getHostAddress()
+ ":"
+                        + server.getLocalPort() + urlTestPattern)
+                .build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+            response.setStatusCode(HttpStatus.SC_OK);
+        });
+
+        Mailet mailet = new HeadersToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-headerToHTTP")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isEqualTo("Succeeded"));
+
+    }
+
+    @Test
+    void serviceShouldNotModifyHeadersContent() throws Exception {
+
+        urlTestPattern = "/path/to/service/succeeded";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("url", "http://" + server.getInetAddress().getHostAddress()
+ ":"
+                        + server.getLocalPort() + urlTestPattern)
+                .build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+
+            assertThat(request.getRequestLine().getMethod()).isEqualTo("POST");
+
+            BasicHttpEntityEnclosingRequest basicRequest = (BasicHttpEntityEnclosingRequest)
request;
+            BasicHttpEntity entity = (BasicHttpEntity) basicRequest.getEntity();
+
+            try {
+                List<NameValuePair> params = URLEncodedUtils.parse(entity);
+                assertThat(params).hasSize(5).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("pKey");
+                    assertThat(param.getValue()).isEqualTo("pValue");
+                }).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("subject");
+                    assertThat(param.getValue()).isEqualTo("Fwd: Invitation: (Aucun objet)
- "
+                            + "ven. 20 janv. 2017 14:00 - 15:00 (CET) (aduprat@linagora.com)");
+                }).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("message_id");
+                    assertThat(param.getValue())
+                            .isEqualTo("<f18fa52e-2e9d-1125-327d-2100b23f8a6b@linagora.com>");
+                }).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("reply_to");
+                    assertThat(param.getValue()).isEqualTo("[aduprat <duprat@linagora.com>]");
+                }).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("size");
+                    assertThat(param.getValue()).isEqualTo("5242");
+                });
+
+            } finally {
+                EntityUtils.consume(basicRequest.getEntity());
+            }
+            response.setStatusCode(HttpStatus.SC_OK);
+        });
+
+        Mailet mailet = new HeadersToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+    }
+
+    @Test
+    void shouldSetTheMailStateWhenPassThroughIsFalse() throws Exception {
+
+        urlTestPattern = "/path/to/service/PassThroughIsFalse";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("url",
+                        "http://" + server.getInetAddress().getHostAddress() + ":"
+                                + server.getLocalPort() + urlTestPattern)
+                .setProperty("passThrough", "false").build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+            response.setStatusCode(HttpStatus.SC_OK);
+        });
+
+        Mailet mailet = new HeadersToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-headerToHTTP")).isNull();
+
+        assertThat(mail.getState()).isEqualTo(Mail.GHOST);
+    }
+
+    @Test
+    void shouldThrowMessagingExceptionWhenInvalidUrl() throws Exception {
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("url", "qwerty://invalid.url").build();
+
+        assertThatThrownBy(() -> {
+            new HeadersToHTTP().init(mailetConfig);
+        }).isExactlyInstanceOf(MessagingException.class)
+                .hasMessageContaining("Unable to contruct URL object from url");
+
+    }
+
+    @Test
+    void shouldThrowMessagingExceptionWhenUrlIsNull() throws Exception {
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .build();
+
+        assertThatThrownBy(() -> {
+            new HeadersToHTTP().init(mailetConfig);
+        }).isExactlyInstanceOf(MessagingException.class)
+                .hasMessageContaining("Please configure a targetUrl (\"url\")");
+
+    }
+
+}
diff --git a/mailet/standard/src/test/java/org/apache/james/transport/mailets/SerialiseToHTTPTest.java
b/mailet/standard/src/test/java/org/apache/james/transport/mailets/SerialiseToHTTPTest.java
new file mode 100644
index 0000000..51fdf3a
--- /dev/null
+++ b/mailet/standard/src/test/java/org/apache/james/transport/mailets/SerialiseToHTTPTest.java
@@ -0,0 +1,262 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.james.transport.mailets;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import javax.mail.MessagingException;
+
+import org.apache.http.ExceptionLogger;
+import org.apache.http.HttpStatus;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.utils.URLEncodedUtils;
+import org.apache.http.config.SocketConfig;
+import org.apache.http.entity.BasicHttpEntity;
+import org.apache.http.impl.bootstrap.HttpServer;
+import org.apache.http.impl.bootstrap.ServerBootstrap;
+import org.apache.http.message.BasicHttpEntityEnclosingRequest;
+import org.apache.http.protocol.UriHttpRequestHandlerMapper;
+import org.apache.http.util.EntityUtils;
+import org.apache.james.util.MimeMessageUtil;
+import org.apache.mailet.Mail;
+import org.apache.mailet.Mailet;
+import org.apache.mailet.base.test.FakeMailetConfig;
+import org.apache.mailet.base.test.MailUtil;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class SerialiseToHTTPTest {
+
+    private static HttpServer server;
+    private static UriHttpRequestHandlerMapper mapper;
+    private Mail mail;
+
+    private String urlTestPattern;
+
+    @BeforeAll
+    static void setupServer() throws MessagingException, IOException {
+        mapper = new UriHttpRequestHandlerMapper();
+
+        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(50000).build();
+        server = ServerBootstrap.bootstrap().setListenerPort(0).setSocketConfig(socketConfig)
+                .setExceptionLogger(ExceptionLogger.NO_OP).setHandlerMapper(mapper).create();
+
+        server.start();
+
+    }
+
+    @AfterAll
+    static void shutdown() {
+        server.shutdown(5L, TimeUnit.SECONDS);
+    }
+
+    @BeforeEach
+    void setup() throws MessagingException, IOException {
+        mail = MailUtil.createMockMail2Recipients(MimeMessageUtil.mimeMessageFromStream(
+                ClassLoader.getSystemResourceAsStream("mime/sendToRemoteHttp.mime")));
+    }
+
+    @AfterEach
+    void cleanMapper() throws MessagingException, IOException {
+        mapper.unregister(urlTestPattern);
+    }
+
+    @Test
+    void shouldBeFailedWhenServiceResponseIsNotOk() throws Exception {
+
+        urlTestPattern = "/path/to/service/internal/error";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey")
+                .setProperty("url", "http://" + server.getInetAddress().getHostAddress()
+ ":"
+                        + server.getLocalPort() + urlTestPattern)
+                .build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+            response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+        });
+        Mailet mailet = new SerialiseToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-toHTTP")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isEqualTo("Failed"));
+        assertThat(mail.getMessage().getHeader("X-toHTTPFailure")).hasSize(1).allSatisfy(
+                (header) -> assertThat(header).isEqualTo("HTTP/1.1 500 Internal Server
Error"));
+    }
+
+    @Test
+    void shouldBeFailedWhenServiceNotExists() throws Exception {
+
+        urlTestPattern = "/path/to/service/failed";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey")
+                .setProperty("url", "ftp://" + server.getInetAddress().getHostAddress() +
":"
+                        + server.getLocalPort() + urlTestPattern)
+                .build();
+
+        Mailet mailet = new SerialiseToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-toHTTP")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isEqualTo("Failed"));
+        assertThat(mail.getMessage().getHeader("X-toHTTPFailure")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isNotBlank());
+    }
+
+    @Test
+    void shouldBeSucceededWhenServiceResponseIsOk() throws Exception {
+
+        urlTestPattern = "/path/to/service/succeeded";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey")
+                .setProperty("url", "http://" + server.getInetAddress().getHostAddress()
+ ":"
+                        + server.getLocalPort() + urlTestPattern)
+                .build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+            response.setStatusCode(HttpStatus.SC_OK);
+        });
+
+        Mailet mailet = new SerialiseToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-toHTTP")).hasSize(1)
+                .allSatisfy((header) -> assertThat(header).isEqualTo("Succeeded"));
+
+    }
+
+    @Test
+    void serviceShouldNotModifyMessageContent() throws Exception {
+
+        urlTestPattern = "/path/to/service/succeeded";
+
+        final String originalMessage = MimeMessageUtil.asString(mail.getMessage());
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey")
+                .setProperty("url", "http://" + server.getInetAddress().getHostAddress()
+ ":"
+                        + server.getLocalPort() + urlTestPattern)
+                .build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+            assertThat(request.getRequestLine().getMethod()).isEqualTo("POST");
+
+            BasicHttpEntityEnclosingRequest basicRequest = (BasicHttpEntityEnclosingRequest)
request;
+            BasicHttpEntity entity = (BasicHttpEntity) basicRequest.getEntity();
+
+            try {
+                List<NameValuePair> params = URLEncodedUtils.parse(entity);
+                assertThat(params).hasSize(2).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("pKey");
+                    assertThat(param.getValue()).isEqualTo("pValue");
+                }).anySatisfy((param) -> {
+                    assertThat(param.getName()).isEqualTo("message");
+                    assertThat(param.getValue()).isEqualTo(originalMessage);
+                });
+            } finally {
+                EntityUtils.consume(basicRequest.getEntity());
+            }
+            response.setStatusCode(HttpStatus.SC_OK);
+        });
+
+        Mailet mailet = new SerialiseToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+    }
+
+    @Test
+    void shouldSetTheMailStateWhenPassThroughIsFalse() throws Exception {
+
+        urlTestPattern = "/path/to/service/PassThroughIsFalse";
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey")
+                .setProperty("url",
+                        "http://" + server.getInetAddress().getHostAddress() + ":"
+                                + server.getLocalPort() + urlTestPattern)
+                .setProperty("passThrough", "false").build();
+
+        mapper.register(urlTestPattern, (request, response, context) -> {
+            response.setStatusCode(HttpStatus.SC_OK);
+        });
+
+        Mailet mailet = new SerialiseToHTTP();
+        mailet.init(mailetConfig);
+
+        mailet.service(mail);
+
+        assertThat(mail.getMessage().getHeader("X-toHTTP")).isNull();
+
+        assertThat(mail.getState()).isEqualTo(Mail.GHOST);
+    }
+
+    @Test
+    void shouldThrowMessagingExceptionWhenInvalidUrl() throws Exception {
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey").setProperty("url", "qwerty://invalid.url")
+                .build();
+
+        assertThatThrownBy(() -> {
+            new SerialiseToHTTP().init(mailetConfig);
+        }).isExactlyInstanceOf(MessagingException.class)
+                .hasMessageContaining("Unable to contruct URL object from url");
+
+    }
+
+    @Test
+    void shouldThrowMessagingExceptionWhenUrlIsNull() throws Exception {
+
+        FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
+                .setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
+                .setProperty("messageKey", "mKey").build();
+
+        assertThatThrownBy(() -> {
+            new SerialiseToHTTP().init(mailetConfig);
+        }).isExactlyInstanceOf(MessagingException.class)
+                .hasMessageContaining("Please configure a targetUrl (\"url\")");
+
+    }
+
+}
\ No newline at end of file
diff --git a/mailet/standard/src/test/resources/mime/sendToRemoteHttp.mime b/mailet/standard/src/test/resources/mime/sendToRemoteHttp.mime
new file mode 100644
index 0000000..9ef251f
--- /dev/null
+++ b/mailet/standard/src/test/resources/mime/sendToRemoteHttp.mime
@@ -0,0 +1,153 @@
+Return-Path: <aduprat@linagora.com>
+Subject: Fwd: Invitation: (Aucun objet) - ven. 20 janv. 2017 14:00 - 15:00
+ (CET) (aduprat@linagora.com)
+To: =?UTF-8?Q?Beno=c3=aet_TELLIER?= <tellier@linagora.com>
+From: aduprat <duprat@linagora.com>
+X-Forwarded-Message-Id: <001a114380a6a260d105467765ab@google.com>
+Message-ID: <f18fa52e-2e9d-1125-327d-2100b23f8a6b@linagora.com>
+Date: Thu, 19 Jan 2017 20:36:37 +0100
+MIME-Version: 1.0
+In-Reply-To: <001a114380a6a260d105467765ab@google.com>
+Content-Type: multipart/mixed;
+ boundary="------------17D96D411CBD55D8239A8C1F"
+
+This is a multi-part message in MIME format.
+--------------17D96D411CBD55D8239A8C1F
+Content-Type: multipart/alternative;
+ boundary="------------64D716A3DDAEC185D3E67448"
+
+
+--------------64D716A3DDAEC185D3E67448
+Content-Type: text/plain; charset=utf-8; format=flowed
+Content-Transfer-Encoding: 8bit
+
+
+
+
+-------- Message transéré --------
+Sujet : 	Invitation: (Aucun objet) - ven. 20 janv. 2017 14:00 - 15:00
+(CET) (duprat@linagora.com)
+Date : 	Thu, 19 Jan 2017 19:18:23 +0000
+De : 	Antoine Duprat <duprat@gmail.com>
+Répondre à : 	antduprat@gmail.com
+Pour : 	aduprat@linagora.com
+
+
+
+
+--------------64D716A3DDAEC185D3E67448
+Content-Type: text/html; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+<html>
+  <head>
+
+    <meta http-equiv="content-type" content="text/html; charset=utf-8">
+  </head>
+  <body bgcolor="#FFFFFF" text="#000000">
+    <p><br>
+    </p>
+    <div class="moz-forward-container"><br>
+      <br>
+      -------- Message transéré --------
+      <table class="moz-email-headers-table" border="0" cellpadding="0"
+        cellspacing="0">
+        <tbody>
+          <tr>
+            <th align="RIGHT" valign="BASELINE" nowrap="nowrap">Sujet :
+            </th>
+            <td>Invitation: (Aucun objet) - ven. 20 janv. 2017 14:00 -
+              15:00 (CET) (<a class="moz-txt-link-abbreviated" href="mailto:aduprat@linagora.com">aduprat@linagora.com</a>)</td>
+          </tr>
+          <tr>
+            <th align="RIGHT" valign="BASELINE" nowrap="nowrap">Date : </th>
+            <td>Thu, 19 Jan 2017 19:18:23 +0000</td>
+          </tr>
+          <tr>
+            <th align="RIGHT" valign="BASELINE" nowrap="nowrap">De : </th>
+            <td>Antoine Duprat <a class="moz-txt-link-rfc2396E" href="mailto:antduprat@gmail.com">&lt;antduprat@gmail.com&gt;</a></td>
+          </tr>
+          <tr>
+            <th align="RIGHT" valign="BASELINE" nowrap="nowrap">Répondre
+              Ã Â : </th>
+            <td><a class="moz-txt-link-abbreviated" href="mailto:antduprat@gmail.com">antduprat@gmail.com</a></td>
+          </tr>
+          <tr>
+            <th align="RIGHT" valign="BASELINE" nowrap="nowrap">Pour : </th>
+            <td><a class="moz-txt-link-abbreviated" href="mailto:aduprat@linagora.com">aduprat@linagora.com</a></td>
+          </tr>
+        </tbody>
+      </table>
+      <br>
+      <br>
+    </div>
+  </body>
+</html>
+
+--------------64D716A3DDAEC185D3E67448--
+
+--------------17D96D411CBD55D8239A8C1F
+Content-Type: text/calendar;
+ name="Portion de message joint"
+Content-Transfer-Encoding: 8bit
+Content-Disposition: attachment;
+ filename="Portion de message joint"
+
+BEGIN:VCALENDAR
+PRODID:-//Google Inc//Google Calendar 70.9054//EN
+VERSION:2.0
+CALSCALE:GREGORIAN
+METHOD:REQUEST
+BEGIN:VEVENT
+DTSTART:20170120T130000Z
+DTEND:20170120T140000Z
+DTSTAMP:20170119T191823Z
+ORGANIZER;CN=Antoine Duprat:mailto:duprat@gmail.com
+UID:ah86k5m342bmcrbe9khkkhln00@google.com
+ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
+ TRUE;CN=aduprat@linagora.com;X-NUM-GUESTS=0:mailto:duprat@linagora.com
+ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE
+ ;CN=Antoine Duprat;X-NUM-GUESTS=0:mailto:duprat@gmail.com
+CREATED:20170119T191823Z
+DESCRIPTION:Affichez votre evenement sur la page https://www.google.com/cal
+ endar/event?action=VIEW&eid=YWg4Nms1bTM0MmJtY3JiZTlraGtraGxuMDAgYWR1cHJhdEB
+ saW5hZ29yYS5jb20&tok=MTkjYW50ZHVwcmF0QGdtYWlsLmNvbTg1OTM5NWM4MGRlYmE1YTI4Nz
+ RjN2UyNjU0M2YyZmQ4NzRkNThhYTQ&ctz=Europe/Paris&hl=fr.
+LAST-MODIFIED:20170119T191823Z
+LOCATION:
+SEQUENCE:0
+STATUS:CONFIRMED
+SUMMARY:
+TRANSP:OPAQUE
+END:VEVENT
+END:VCALENDAR
+
+
+--------------17D96D411CBD55D8239A8C1F
+Content-Type: application/ics;
+ name="invite.ics"
+Content-Transfer-Encoding: base64
+Content-Disposition: attachment;
+ filename="invite.ics"
+
+QkVHSU46VkNBTEVOREFSDQpQUk9ESUQ6LS8vR29vZ2xlIEluYy8vR29vZ2xlIENhbGVuZGFy
+IDcwLjkwNTQvL0VODQpWRVJTSU9OOjIuMA0KQ0FMU0NBTEU6R1JFR09SSUFODQpNRVRIT0Q6
+UkVRVUVTVA0KQkVHSU46VkVWRU5UDQpEVFNUQVJUOjIwMTcwMTIwVDEzMDAwMFoNCkRURU5E
+OjIwMTcwMTIwVDE0MDAwMFoNCkRUU1RBTVA6MjAxNzAxMTlUMTkxODIzWg0KT1JHQU5JWkVS
+O0NOPUFudG9pbmUgRHVwcmF0Om1haWx0bzphbnRkdXByYXRAZ21haWwuY29tDQpVSUQ6YWg4
+Nms1bTM0MmJtY3JiZTlraGtraGxuMDBAZ29vZ2xlLmNvbQ0KQVRURU5ERUU7Q1VUWVBFPUlO
+RElWSURVQUw7Uk9MRT1SRVEtUEFSVElDSVBBTlQ7UEFSVFNUQVQ9TkVFRFMtQUNUSU9OO1JT
+VlA9DQogVFJVRTtDTj1hZHVwcmF0QGxpbmFnb3JhLmNvbTtYLU5VTS1HVUVTVFM9MDptYWls
+dG86YWR1cHJhdEBsaW5hZ29yYS5jb20NCkFUVEVOREVFO0NVVFlQRT1JTkRJVklEVUFMO1JP
+TEU9UkVRLVBBUlRJQ0lQQU5UO1BBUlRTVEFUPUFDQ0VQVEVEO1JTVlA9VFJVRQ0KIDtDTj1B
+bnRvaW5lIER1cHJhdDtYLU5VTS1HVUVTVFM9MDptYWlsdG86YW50ZHVwcmF0QGdtYWlsLmNv
+bQ0KQ1JFQVRFRDoyMDE3MDExOVQxOTE4MjNaDQpERVNDUklQVElPTjpBZmZpY2hleiB2b3Ry
+ZSDDqXbDqW5lbWVudCBzdXIgbGEgcGFnZSBodHRwczovL3d3dy5nb29nbGUuY29tL2NhbA0K
+IGVuZGFyL2V2ZW50P2FjdGlvbj1WSUVXJmVpZD1ZV2c0Tm1zMWJUTTBNbUp0WTNKaVpUbHJh
+R3RyYUd4dU1EQWdZV1IxY0hKaGRFQg0KIHNhVzVoWjI5eVlTNWpiMjAmdG9rPU1Ua2pZVzUw
+WkhWd2NtRjBRR2R0WVdsc0xtTnZiVGcxT1RNNU5XTTRNR1JsWW1FMVlUSTROeg0KIFJqTjJV
+eU5qVTBNMll5Wm1RNE56UmtOVGhoWVRRJmN0ej1FdXJvcGUvUGFyaXMmaGw9ZnIuDQpMQVNU
+LU1PRElGSUVEOjIwMTcwMTE5VDE5MTgyM1oNCkxPQ0FUSU9OOg0KU0VRVUVOQ0U6MA0KU1RB
+VFVTOkNPTkZJUk1FRA0KU1VNTUFSWToNClRSQU5TUDpPUEFRVUUNCkVORDpWRVZFTlQNCkVO
+RDpWQ0FMRU5EQVINCg==
+--------------17D96D411CBD55D8239A8C1F--


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


Mime
View raw message