You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by GitBox <gi...@apache.org> on 2021/04/01 14:25:04 UTC

[GitHub] [james-project] chibenwa commented on a change in pull request #351: JAMES-3520 Implement JMAP MDN draft - Parser

chibenwa commented on a change in pull request #351:
URL: https://github.com/apache/james-project/pull/351#discussion_r605688167



##########
File path: mdn/src/main/java/org/apache/james/mdn/MDN.java
##########
@@ -52,6 +60,7 @@
     public static class Builder {
         private String humanReadableText;
         private MDNReport report;
+        private boolean includeOriginalMessage;

Review comment:
       There is no such mention of a RFC. If anything we should have an `Optional<Message>` instead.
   
   I will see with you tomorrow why you do need this, and help you get rid of it.

##########
File path: mdn/src/main/java/org/apache/james/mdn/fields/ReportingUserAgent.java
##########
@@ -87,8 +87,11 @@ public String getUserAgentName() {
 
     @Override
     public String formattedValue() {
-        return FIELD_NAME + ": " + userAgentName + "; "
-            + userAgentProduct.orElse("");
+        return FIELD_NAME + ": " + fieldValue();
+    }
+
+    public String fieldValue() {
+        return userAgentName + userAgentProduct.map(e -> (": " + e)).orElse("");

Review comment:
       Should be a semicolon here? `;`
   
   Also let me propose 
   
   ```
   Joiner.on("; ")
       .skipNulls
       .join(userAgentName, userAgentProduct.orElse(null));
   ```

##########
File path: server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/mail/MDNParse.scala
##########
@@ -0,0 +1,166 @@
+/****************************************************************
+ * 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.jmap.mail
+
+import eu.timepit.refined.api.Refined
+import eu.timepit.refined.collection.NonEmpty
+import org.apache.james.jmap.core.AccountId
+import org.apache.james.jmap.mail.MDNParse._
+import org.apache.james.jmap.method.WithAccountId
+import org.apache.james.mdn.MDN
+import org.apache.james.mdn.fields.{Disposition => JavaDisposition}
+import org.apache.james.mime4j.dom.Message
+
+import scala.jdk.CollectionConverters._
+import scala.jdk.OptionConverters._
+
+object MDNParse {
+  type UnparsedBlobIdConstraint = NonEmpty
+  type UnparsedBlobId = String Refined UnparsedBlobIdConstraint
+}
+
+case class BlobIds(value: Seq[UnparsedBlobId])
+
+case class RequestTooLargeException(description: String) extends Exception
+
+case object MDNParseRequest {
+  val MAXIMUM_NUMBER_OF_BLOB_IDS: 16 = 16
+}
+
+case class MDNParseRequest(accountId: AccountId,
+                           blobIds: BlobIds) extends WithAccountId {
+
+  import MDNParseRequest._
+
+  def validate: Either[RequestTooLargeException, MDNParseRequest] = {
+    if (blobIds.value.length > MAXIMUM_NUMBER_OF_BLOB_IDS) {
+      Left(RequestTooLargeException("The number of ids requested by the client exceeds the maximum number the server is willing to process in a single method call"))
+    } else {
+      scala.Right(this)
+    }
+  }
+}
+
+case class MDNNotFound(value: Set[UnparsedBlobId]) {
+  def merge(other: MDNNotFound): MDNNotFound = MDNNotFound(this.value ++ other.value)
+}
+
+object MDNNotParsable {
+  def merge(notParsable1: MDNNotParsable, notParsable2: MDNNotParsable): MDNNotParsable = MDNNotParsable(notParsable1.value ++ notParsable2.value)
+}
+
+case class MDNNotParsable(value: Set[UnparsedBlobId]) {
+  def merge(other: MDNNotParsable): MDNNotParsable = MDNNotParsable(this.value ++ other.value)
+}
+
+object MDNDisposition {
+  def fromJava(javaDisposition: JavaDisposition): MDNDisposition =
+    MDNDisposition(actionMode = javaDisposition.getActionMode.getValue,
+      sendingMode = javaDisposition.getSendingMode.getValue,
+      `type` = javaDisposition.getType.getValue)
+}
+
+case class MDNDisposition(actionMode: String,
+                          sendingMode: String,
+                          `type`: String)
+
+case class ForEmailIdField(value: String) extends AnyVal
+
+case class SubjectField(value: String) extends AnyVal
+
+case class TextBodyField(value: String) extends AnyVal
+
+case class ReportUAField(value: String) extends AnyVal
+
+case class FinalRecipientField(value: String) extends AnyVal
+
+case class OriginalMessageIdField(value: String) extends AnyVal
+
+case class ErrorField(value: String) extends AnyVal
+
+object IncludeOriginalMessageField {
+  def default: IncludeOriginalMessageField = IncludeOriginalMessageField(false)
+}
+
+case class IncludeOriginalMessageField(value: Boolean) extends AnyVal
+
+object MDNParsed {
+  def fromMDN(mdn: MDN, message: Message): MDNParsed = {
+    val report = mdn.getReport
+    MDNParsed(forEmailId = None,
+      subject = Option(message.getSubject).map(SubjectField),
+      textBody = Some(TextBodyField(mdn.getHumanReadableText)),
+      reportingUA = report.getReportingUserAgentField
+        .map(userAgent => ReportUAField(userAgent.fieldValue()))
+        .toScala,
+      finalRecipient = FinalRecipientField(report.getFinalRecipientField.fieldValue()),
+      originalMessageId = report.getOriginalMessageIdField
+        .map(originalMessageId => OriginalMessageIdField(originalMessageId.getOriginalMessageId))
+        .toScala,
+      includeOriginalMessage = IncludeOriginalMessageField(mdn.isIncludeOriginalMessage),
+      disposition = MDNDisposition.fromJava(report.getDispositionField),
+      error = Option(report.getErrorFields.asScala
+        .map(error => ErrorField(error.getText.formatted()))
+        .toSeq)
+        .filter(error => error.nonEmpty),
+      extensionFields = Option(report.getExtensionFields.asScala
+        .map(extension => (extension.getFieldName, extension.getRawValue))
+        .toMap).filter(_.nonEmpty))

Review comment:
       The indent looks weird on this line. Ctrl + L maybe?

##########
File path: server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/method/MDNParseMethod.scala
##########
@@ -0,0 +1,106 @@
+/** **************************************************************
+ * 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   *
+ * *

Review comment:
       We need to fix the spaces in this license.

##########
File path: server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/MDNParseMethodContract.scala
##########
@@ -0,0 +1,538 @@
+/** **************************************************************
+ * 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.jmap.rfc8621.contract
+
+import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT
+import io.restassured.RestAssured._
+import io.restassured.http.ContentType.JSON
+import net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson
+import org.apache.http.HttpStatus.SC_OK
+import org.apache.james.GuiceJamesServer
+import org.apache.james.jmap.core.ResponseObject.SESSION_STATE
+import org.apache.james.jmap.http.UserCredential
+import org.apache.james.jmap.rfc8621.contract.Fixture._
+import org.apache.james.mailbox.MessageManager.AppendCommand
+import org.apache.james.mailbox.model.{MailboxPath, MessageId}
+import org.apache.james.mime4j.dom.Message
+import org.apache.james.mime4j.message.MultipartBuilder
+import org.apache.james.modules.MailboxProbeImpl
+import org.apache.james.util.ClassLoaderUtils
+import org.apache.james.utils.DataProbeImpl
+import org.awaitility.Awaitility
+import org.awaitility.Durations.ONE_HUNDRED_MILLISECONDS
+import org.junit.jupiter.api.{BeforeEach, Test}
+import play.api.libs.json._
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.TimeUnit
+
+trait MDNParseMethodContract {
+  private lazy val slowPacedPollInterval = ONE_HUNDRED_MILLISECONDS
+  private lazy val calmlyAwait = Awaitility.`with`
+    .pollInterval(slowPacedPollInterval)
+    .and.`with`.pollDelay(slowPacedPollInterval)
+    .await
+
+  private lazy val awaitAtMostTenSeconds = calmlyAwait.atMost(5, TimeUnit.SECONDS)
+  @BeforeEach
+  def setUp(server: GuiceJamesServer): Unit = {
+    server.getProbe(classOf[DataProbeImpl])
+      .fluent()
+      .addDomain(DOMAIN.asString())
+      .addUser(BOB.asString(), BOB_PASSWORD)
+
+    requestSpecification = baseRequestSpecBuilder(server)
+      .setAuth(authScheme(UserCredential(BOB, BOB_PASSWORD)))
+      .build()
+  }
+
+  def randomMessageId: MessageId
+
+  @Test
+  def mdnParseHasValidBodyFormatShouldSucceed(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val messageId: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.from(
+        ClassLoaderUtils.getSystemResourceAsSharedStream("eml/mdn.eml")))
+      .getMessageId
+
+    val request: String =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${messageId.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post.prettyPeek()
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response)
+      .isEqualTo(
+        s"""{
+           |    "sessionState": "${SESSION_STATE.value}",
+           |    "methodResponses": [
+           |      [ "MDN/parse", {
+           |         "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+           |         "parsed": {
+           |           "${messageId.serialize()}": {
+           |             "subject": "Read: test",
+           |             "textBody": "To: magiclan@linagora.com\\r\\nSubject: test\\r\\nMessage was displayed on Tue Mar 30 2021 10:31:50 GMT+0700 (Indochina Time)",
+           |             "reportingUA": "OpenPaaS Unified Inbox; ",
+           |             "disposition": {
+           |               "actionMode": "manual-action",
+           |               "sendingMode": "MDN-sent-manually",
+           |               "type": "displayed"
+           |             },
+           |             "finalRecipient": "rfc822; tungexplorer@linagora.com",
+           |             "originalMessageId": "<63...@linagora.com>",
+           |             "error": [
+           |                "Message1",
+           |                "Message2"
+           |             ],
+           |             "extension": {
+           |                "X-OPENPAAS-IP" : " 177.177.177.77",
+           |                "X-OPENPAAS-PORT" : " 8000"
+           |             }
+           |           }
+           |         }
+           |      }, "c1" ]]
+           |}""".stripMargin)
+  }
+
+  @Test
+  def mdnParseShouldFailWhenWrongAccountId(): Unit = {
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "unknownAccountId",
+         |      "blobIds": [ "0f9f65ab-dc7b-4146-850f-6e4881093965" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |            "error",
+         |            {
+         |                "type": "accountNotFound"
+         |            },
+         |            "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def mdnParseShouldFailWhenNumberOfBlobIdsTooLarge(): Unit = {
+    val blogIds = LazyList.continually(randomMessageId.serialize()).take(201).toArray;
+    val blogIdsJson = Json.stringify(Json.arr(blogIds)).replace("[[", "[").replace("]]", "]");
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds":  ${blogIdsJson}
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response)
+      .whenIgnoringPaths("methodResponses[0][1].description")
+      .isEqualTo(
+        s"""{
+           |  "sessionState": "${SESSION_STATE.value}",
+           |  "methodResponses": [[
+           |    "error",
+           |    {
+           |          "type": "requestTooLarge",
+           |          "description": "The number of ids requested by the client exceeds the maximum number the server is willing to process in a single method call"
+           |    },
+           |    "c1"]]
+           |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldReturnNotParseableWhenNotAnMDN(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val messageId: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.builder()
+        .build(Message.Builder
+          .of
+          .setSubject("Subject MDN")
+          .setSender(ANDRE.asString())
+          .setFrom(ANDRE.asString())
+          .setBody(MultipartBuilder.create("report")
+            .addTextPart("This is body of text part", StandardCharsets.UTF_8)
+            .build)
+          .build))
+      .getMessageId
+
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${messageId.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |      "MDN/parse",
+         |      {
+         |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |        "notParsable": ["${messageId.serialize()}"]
+         |      },
+         |      "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldReturnNotFoundWhenBlobDoNotExist(): Unit = {
+    val blobIdShouldNotFound = randomMessageId.serialize()
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "$blobIdShouldNotFound" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |      "MDN/parse",
+         |      {
+         |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |        "notFound": ["$blobIdShouldNotFound"]
+         |      },
+         |      "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldReturnNotFoundWhenBadBlobId(): Unit = {
+    val blobIdShouldNotFound = randomMessageId.serialize()
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "invalid" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |      "MDN/parse",
+         |      {
+         |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |        "notFound": ["invalid"]
+         |      },
+         |      "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def parseAndNotFoundAndNotParsableCanBeMixed(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val blobIdParsable: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.from(
+        ClassLoaderUtils.getSystemResourceAsSharedStream("eml/mdn.eml")))
+      .getMessageId
+
+    val blobIdNotParsable: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.builder()
+        .build(Message.Builder
+          .of
+          .setSubject("Subject MDN")
+          .setSender(ANDRE.asString())
+          .setFrom(ANDRE.asString())
+          .setBody(MultipartBuilder.create("report")
+            .addTextPart("This is body of text part", StandardCharsets.UTF_8)
+            .build)
+          .build))
+      .getMessageId
+    val blobIdNotFound = randomMessageId
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${blobIdParsable.serialize()}", "${blobIdNotParsable.serialize()}", "${blobIdNotFound.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    awaitAtMostTenSeconds.untilAsserted{
+      () => {
+        val response = `given`
+          .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+          .body(request)
+        .when
+          .post.prettyPeek()
+        .`then`
+          .statusCode(SC_OK)
+          .contentType(JSON)
+          .extract
+          .body
+          .asString
+        assertThatJson(response).isEqualTo(
+          s"""{
+             |    "sessionState": "${SESSION_STATE.value}",
+             |    "methodResponses": [[
+             |      "MDN/parse",
+             |      {
+             |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+             |        "notFound": ["${blobIdNotFound.serialize()}"],
+             |        "notParsable": ["${blobIdNotParsable.serialize()}"],
+             |        "parsed": {
+             |           "${blobIdParsable.serialize()}": {
+             |             "subject": "Read: test",
+             |             "textBody": "To: magiclan@linagora.com\\r\\nSubject: test\\r\\nMessage was displayed on Tue Mar 30 2021 10:31:50 GMT+0700 (Indochina Time)",
+             |             "reportingUA": "OpenPaaS Unified Inbox; ",
+             |             "disposition": {
+             |               "actionMode": "manual-action",
+             |               "sendingMode": "MDN-sent-manually",
+             |               "type": "displayed"
+             |             },
+             |             "finalRecipient": "rfc822; tungexplorer@linagora.com",
+             |             "originalMessageId": "<63...@linagora.com>",
+             |             "error": [
+             |                "Message1",
+             |                "Message2"
+             |             ],
+             |             "extension": {
+             |                "X-OPENPAAS-IP" : " 177.177.177.77",
+             |                "X-OPENPAAS-PORT" : " 8000"
+             |             }
+             |          }
+             |        }
+             |      },
+             |      "c1"
+             |        ]]
+             |}""".stripMargin)
+      }
+    }
+  }
+
+
+  @Test
+  def mdnParseShouldReturnUnknownMethodWhenMissingOneCapability(): Unit = {
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "123" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |  "sessionState": "${SESSION_STATE.value}",
+         |  "methodResponses": [[
+         |    "error",
+         |    {
+         |      "type": "unknownMethod",
+         |      "description": "Missing capability(ies): urn:ietf:params:jmap:mdn"
+         |    },
+         |    "c1"]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def mdnParseShouldReturnUnknownMethodWhenMissingAllCapabilities(): Unit = {
+    val request =
+      s"""{
+         |  "using": [],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "123" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |  "sessionState": "${SESSION_STATE.value}",
+         |  "methodResponses": [[
+         |    "error",
+         |    {
+         |      "type": "unknownMethod",
+         |      "description": "Missing capability(ies): urn:ietf:params:jmap:mdn, urn:ietf:params:jmap:mail"
+         |    },
+         |    "c1"]]
+         |}""".stripMargin)
+  }
+}

Review comment:
       I still miss these tests:
   
    - Demonstrating that we succeed to parse a MDN with all properties
    - Demonstrate that we succeed to parse a MDN with only minimal fields
    - A test with a third mime part and `includeOriginalMessage=true`
    - Can we have a test parsing (say 5 MDN ?)
     

##########
File path: mdn/src/test/java/org/apache/james/mdn/MDNTest.java
##########
@@ -215,6 +229,196 @@ void mime4JMessageExportShouldGenerateExpectedContentType() throws Exception {
             .containsPattern(Pattern.compile("Content-Type: multipart/report;.*(\r\n.+)*report-type=disposition-notification.*(\r\n.+)*\r\n\r\n"));
     }
 
+    @Test
+    public void parseShouldThrowWhenNonMultipartMessage() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody("content", StandardCharsets.UTF_8)
+            .build();
+        assertThatThrownBy(() -> MDN.parse(message))
+            .isInstanceOf(MDN.MDNParseContentTypeException.class)
+            .hasMessage("MDN Message must be multipart");
+    }
+
+    @Test
+    public void parseShouldThrowWhenMultipartWithSinglePart() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody(MultipartBuilder.create()
+                .setSubType("report")
+                .addTextPart("content", StandardCharsets.UTF_8)
+                .build())
+            .build();
+        assertThatThrownBy(() -> MDN.parse(message))
+            .isInstanceOf(MDN.MDNParseBodyPartInvalidException.class)
+            .hasMessage("MDN Message must contain at least two parts");
+    }
+
+    @Test
+    public void parseShouldThrowWhenSecondPartWithBadContentType() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody(MultipartBuilder.create()
+                .setSubType("report")
+                .addTextPart("first", StandardCharsets.UTF_8)
+                .addTextPart("second", StandardCharsets.UTF_8)
+                .build())
+            .build();
+        assertThatThrownBy(() -> MDN.parse(message))
+            .isInstanceOf(MDN.MDNParseException.class)
+            .hasMessage("MDN can not extract");

Review comment:
       `Can not extract MDN` and you miss the explanation in the error message...

##########
File path: mdn/src/test/java/org/apache/james/mdn/MDNTest.java
##########
@@ -215,6 +229,196 @@ void mime4JMessageExportShouldGenerateExpectedContentType() throws Exception {
             .containsPattern(Pattern.compile("Content-Type: multipart/report;.*(\r\n.+)*report-type=disposition-notification.*(\r\n.+)*\r\n\r\n"));
     }
 
+    @Test
+    public void parseShouldThrowWhenNonMultipartMessage() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody("content", StandardCharsets.UTF_8)
+            .build();
+        assertThatThrownBy(() -> MDN.parse(message))
+            .isInstanceOf(MDN.MDNParseContentTypeException.class)
+            .hasMessage("MDN Message must be multipart");
+    }
+
+    @Test
+    public void parseShouldThrowWhenMultipartWithSinglePart() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody(MultipartBuilder.create()
+                .setSubType("report")
+                .addTextPart("content", StandardCharsets.UTF_8)
+                .build())
+            .build();
+        assertThatThrownBy(() -> MDN.parse(message))
+            .isInstanceOf(MDN.MDNParseBodyPartInvalidException.class)
+            .hasMessage("MDN Message must contain at least two parts");
+    }
+
+    @Test
+    public void parseShouldThrowWhenSecondPartWithBadContentType() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody(MultipartBuilder.create()
+                .setSubType("report")
+                .addTextPart("first", StandardCharsets.UTF_8)
+                .addTextPart("second", StandardCharsets.UTF_8)
+                .build())
+            .build();
+        assertThatThrownBy(() -> MDN.parse(message))
+            .isInstanceOf(MDN.MDNParseException.class)
+            .hasMessage("MDN can not extract");
+    }
+
+    @Test
+    public void parseShouldFailWhenMDNMissingMustBeProperties() throws Exception {
+        Message message = Message.Builder.of()
+            .setBody(MultipartBuilder.create("report")
+                .addTextPart("first", StandardCharsets.UTF_8)
+                .addBodyPart(BodyPartBuilder
+                    .create()
+                    .setBody(SingleBodyBuilder.create()
+                        .setText("Final-Recipient: rfc822; final_recipient\r\n" +
+                            "".replace(System.lineSeparator(), "\r\n").strip())

Review comment:
       That looks complicated. Is `"".replace(System.lineSeparator(), "\r\n").strip()` needed?

##########
File path: mdn/src/main/java/org/apache/james/mdn/fields/FinalRecipient.java
##########
@@ -79,7 +79,11 @@ public AddressType getAddressType() {
 
     @Override
     public String formattedValue() {
-        return FIELD_NAME + ": " + addressType.getType() + "; " + finalRecipient.formatted();
+        return FIELD_NAME + ": " + fieldValue();
+    }
+
+    public String fieldValue() {

Review comment:
       No tests for this method?

##########
File path: mdn/src/main/java/org/apache/james/mdn/fields/ReportingUserAgent.java
##########
@@ -87,8 +87,11 @@ public String getUserAgentName() {
 
     @Override
     public String formattedValue() {
-        return FIELD_NAME + ": " + userAgentName + "; "
-            + userAgentProduct.orElse("");
+        return FIELD_NAME + ": " + fieldValue();
+    }
+
+    public String fieldValue() {

Review comment:
       No tests for this method?

##########
File path: server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/method/MDNParseMethod.scala
##########
@@ -0,0 +1,106 @@
+/** **************************************************************
+ * 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.jmap.method
+
+import eu.timepit.refined.auto._
+import org.apache.james.jmap.core.CapabilityIdentifier.{CapabilityIdentifier, JMAP_CORE, JMAP_MAIL, JMAP_MDN}
+import org.apache.james.jmap.core.Invocation
+import org.apache.james.jmap.core.Invocation._
+import org.apache.james.jmap.json.{MDNParseSerializer, ResponseSerializer}
+import org.apache.james.jmap.mail.{BlobId, MDNParseRequest, MDNParseResponse, MDNParseResults, MDNParsed}
+import org.apache.james.jmap.routes.{BlobNotFoundException, BlobResolvers, SessionSupplier}
+import org.apache.james.mailbox.MailboxSession
+import org.apache.james.mdn.MDN
+import org.apache.james.metrics.api.MetricFactory
+import org.apache.james.mime4j.message.DefaultMessageBuilder
+import play.api.libs.json.{JsError, JsObject, JsSuccess, Json}
+import reactor.core.scala.publisher.{SFlux, SMono}
+
+import java.io.InputStream
+import javax.inject.Inject
+import scala.util.Try
+
+class MDNParseMethod @Inject()(val blobResolvers: BlobResolvers,
+                               val metricFactory: MetricFactory,
+                               val sessionSupplier: SessionSupplier) extends MethodRequiringAccountId[MDNParseRequest] {
+  override val methodName: MethodName = MethodName("MDN/parse")
+  override val requiredCapabilities: Set[CapabilityIdentifier] = Set(JMAP_MDN, JMAP_MAIL, JMAP_CORE)
+
+  def doProcess(capabilities: Set[CapabilityIdentifier],
+                invocation: InvocationWithContext,
+                mailboxSession: MailboxSession,
+                request: MDNParseRequest): SMono[InvocationWithContext] =
+    computeResponseInvocation(request, invocation.invocation, mailboxSession)
+      .map(InvocationWithContext(_, invocation.processingContext))
+
+  override def getRequest(mailboxSession: MailboxSession, invocation: Invocation): Either[Exception, MDNParseRequest] =
+    MDNParseSerializer.deserializeMDNParseRequest(invocation.arguments.value) match {
+      case JsSuccess(emailGetRequest, _) => emailGetRequest.validate
+      case errors: JsError => Left(new IllegalArgumentException(Json.stringify(ResponseSerializer.serialize(errors))))
+    }
+
+  def computeResponseInvocation(request: MDNParseRequest,
+                                invocation: Invocation,
+                                mailboxSession: MailboxSession): SMono[Invocation] =
+    computeResponse(request, mailboxSession)
+      .map(res => Invocation(
+        methodName,
+        Arguments(MDNParseSerializer.serialize(res).as[JsObject]),
+        invocation.methodCallId))
+
+  private def computeResponse(request: MDNParseRequest,
+                              mailboxSession: MailboxSession): SMono[MDNParseResponse] = {
+    val validations: Seq[Either[MDNParseResults, BlobId]] = request.blobIds.value
+      .map(id => BlobId.of(id)
+        .toEither
+        .left
+        .map(_ => MDNParseResults.notFound(id)))
+    val parsedIds: Seq[BlobId] = validations.flatMap(_.toOption)
+    val invalid: Seq[MDNParseResults] = validations.map(_.left).flatMap(_.toOption)
+
+    val parsed: SFlux[MDNParseResults] = SFlux.fromIterable(parsedIds)
+      .flatMap(blobId => toParseResults(blobId, mailboxSession))
+      .map(_.fold(e => MDNParseResults.notFound(e.blobId), result => result))
+
+    SFlux.merge(Seq(parsed, SFlux.fromIterable(invalid)))
+      .reduce(MDNParseResults.empty())(MDNParseResults.merge)
+      .map(_.asResponse(request.accountId))
+  }
+
+  private def toParseResults(blobId: BlobId, mailboxSession: MailboxSession): SMono[Either[BlobNotFoundException, MDNParseResults]] = {

Review comment:
       `{}` not needed here

##########
File path: server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/MDNParseMethodContract.scala
##########
@@ -0,0 +1,610 @@
+/****************************************************************
+ * 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.jmap.rfc8621.contract
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.TimeUnit
+import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT
+import io.restassured.RestAssured._
+import io.restassured.http.ContentType.JSON
+import net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson
+import org.apache.http.HttpStatus.SC_OK
+import org.apache.james.GuiceJamesServer
+import org.apache.james.jmap.core.ResponseObject.SESSION_STATE
+import org.apache.james.jmap.http.UserCredential
+import org.apache.james.jmap.mail.MDNParseRequest
+import org.apache.james.jmap.rfc8621.contract.Fixture._
+import org.apache.james.mailbox.MessageManager.AppendCommand
+import org.apache.james.mailbox.model.{MailboxPath, MessageId}
+import org.apache.james.mime4j.dom.Message
+import org.apache.james.mime4j.message.MultipartBuilder
+import org.apache.james.modules.MailboxProbeImpl
+import org.apache.james.util.ClassLoaderUtils
+import org.apache.james.utils.DataProbeImpl
+import org.awaitility.Awaitility
+import org.awaitility.Durations.ONE_HUNDRED_MILLISECONDS
+import org.junit.jupiter.api.{BeforeEach, Test}
+import play.api.libs.json._
+
+trait MDNParseMethodContract {
+  private lazy val slowPacedPollInterval = ONE_HUNDRED_MILLISECONDS
+  private lazy val calmlyAwait = Awaitility.`with`
+    .pollInterval(slowPacedPollInterval)
+    .and.`with`.pollDelay(slowPacedPollInterval)
+    .await
+
+  private lazy val awaitConditionFactory = calmlyAwait.atMost(5, TimeUnit.SECONDS)
+
+  @BeforeEach
+  def setUp(server: GuiceJamesServer): Unit = {
+    server.getProbe(classOf[DataProbeImpl])
+      .fluent()
+      .addDomain(DOMAIN.asString())
+      .addUser(BOB.asString(), BOB_PASSWORD)
+
+    requestSpecification = baseRequestSpecBuilder(server)
+      .setAuth(authScheme(UserCredential(BOB, BOB_PASSWORD)))
+      .build()
+  }
+
+  def randomMessageId: MessageId
+
+  @Test
+  def parseShouldSuccessWithMDNHasAllProperties(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val messageId: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.from(
+        ClassLoaderUtils.getSystemResourceAsSharedStream("eml/mdn_complex.eml")))
+      .getMessageId
+
+    val request: String =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${messageId.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response)
+      .isEqualTo(
+        s"""{
+           |    "sessionState": "${SESSION_STATE.value}",
+           |    "methodResponses": [
+           |      [ "MDN/parse", {
+           |         "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+           |         "parsed": {
+           |           "${messageId.serialize()}": {
+           |             "subject": "Read: test",
+           |             "textBody": "To: magiclan@linagora.com\\r\\nSubject: test\\r\\nMessage was displayed on Tue Mar 30 2021 10:31:50 GMT+0700 (Indochina Time)",
+           |             "reportingUA": "OpenPaaS Unified Inbox",
+           |             "disposition": {
+           |               "actionMode": "manual-action",
+           |               "sendingMode": "MDN-sent-manually",
+           |               "type": "displayed"
+           |             },
+           |             "finalRecipient": "rfc822; tungexplorer@linagora.com",
+           |             "originalMessageId": "<63...@linagora.com>",
+           |             "includeOriginalMessage": true,
+           |             "error": [
+           |                "Message1",
+           |                "Message2"
+           |             ],
+           |             "extensionFields": {
+           |                "X-OPENPAAS-IP" : " 177.177.177.77",
+           |                "X-OPENPAAS-PORT" : " 8000"
+           |             }
+           |           }
+           |         }
+           |      }, "c1" ]]
+           |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldSuccessWithMDNHasMinimalProperties(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val messageId: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.from(
+        ClassLoaderUtils.getSystemResourceAsSharedStream("eml/mdn_simple.eml")))
+      .getMessageId
+
+    val request: String =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${messageId.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response)
+      .isEqualTo(
+        s"""{
+           |    "sessionState": "${SESSION_STATE.value}",
+           |    "methodResponses": [
+           |      [ "MDN/parse", {
+           |         "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+           |         "parsed": {
+           |           "${messageId.serialize()}": {
+           |             "subject": "Read: test",
+           |             "textBody": "This is simple body of human-readable part",
+           |             "disposition": {
+           |               "actionMode": "manual-action",
+           |               "sendingMode": "MDN-sent-manually",
+           |               "type": "displayed"
+           |             },
+           |             "finalRecipient": "rfc822; tungexplorer@linagora.com",
+           |             "includeOriginalMessage": false
+           |           }
+           |         }
+           |      }, "c1" ]]
+           |}""".stripMargin)
+  }
+
+
+  @Test
+  def mdnParseShouldFailWhenWrongAccountId(): Unit = {
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "unknownAccountId",
+         |      "blobIds": [ "0f9f65ab-dc7b-4146-850f-6e4881093965" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |            "error",
+         |            {
+         |                "type": "accountNotFound"
+         |            },
+         |            "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def mdnParseShouldFailWhenNumberOfBlobIdsTooLarge(): Unit = {
+    val blogIds = LazyList.continually(randomMessageId.serialize()).take(MDNParseRequest.MAXIMUM_NUMBER_OF_BLOB_IDS + 1).toArray;
+    val blogIdsJson = Json.stringify(Json.arr(blogIds)).replace("[[", "[").replace("]]", "]");
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds":  ${blogIdsJson}
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response)
+      .whenIgnoringPaths("methodResponses[0][1].description")
+      .isEqualTo(
+        s"""{
+           |  "sessionState": "${SESSION_STATE.value}",
+           |  "methodResponses": [[
+           |    "error",
+           |    {
+           |          "type": "requestTooLarge",
+           |          "description": "The number of ids requested by the client exceeds the maximum number the server is willing to process in a single method call"
+           |    },
+           |    "c1"]]
+           |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldReturnNotParseableWhenNotAnMDN(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val messageId: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.builder()
+        .build(Message.Builder
+          .of
+          .setSubject("Subject MDN")
+          .setSender(ANDRE.asString())
+          .setFrom(ANDRE.asString())
+          .setBody(MultipartBuilder.create("report")
+            .addTextPart("This is body of text part", StandardCharsets.UTF_8)
+            .build)
+          .build))
+      .getMessageId
+
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${messageId.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |      "MDN/parse",
+         |      {
+         |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |        "notParsable": ["${messageId.serialize()}"]
+         |      },
+         |      "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldReturnNotFoundWhenBlobDoNotExist(): Unit = {
+    val blobIdShouldNotFound = randomMessageId.serialize()
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "$blobIdShouldNotFound" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |      "MDN/parse",
+         |      {
+         |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |        "notFound": ["$blobIdShouldNotFound"]
+         |      },
+         |      "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def parseShouldReturnNotFoundWhenBadBlobId(): Unit = {
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "invalid" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |    "sessionState": "${SESSION_STATE.value}",
+         |    "methodResponses": [[
+         |      "MDN/parse",
+         |      {
+         |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |        "notFound": ["invalid"]
+         |      },
+         |      "c1"
+         |        ]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def parseAndNotFoundAndNotParsableCanBeMixed(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val blobIdParsable: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.from(
+        ClassLoaderUtils.getSystemResourceAsSharedStream("eml/mdn_complex.eml")))
+      .getMessageId
+
+    val blobIdNotParsable: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.builder()
+        .build(Message.Builder
+          .of
+          .setSubject("Subject MDN")
+          .setSender(ANDRE.asString())
+          .setFrom(ANDRE.asString())
+          .setBody(MultipartBuilder.create("report")
+            .addTextPart("This is body of text part", StandardCharsets.UTF_8)
+            .build)
+          .build))
+      .getMessageId
+    val blobIdNotFound = randomMessageId
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${blobIdParsable.serialize()}", "${blobIdNotParsable.serialize()}", "${blobIdNotFound.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    awaitConditionFactory.untilAsserted{
+      () => {
+        val response = `given`
+          .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+          .body(request)
+        .when
+          .post
+        .`then`
+          .statusCode(SC_OK)
+          .contentType(JSON)
+          .extract
+          .body
+          .asString
+        assertThatJson(response).isEqualTo(
+          s"""{
+             |    "sessionState": "${SESSION_STATE.value}",
+             |    "methodResponses": [[
+             |      "MDN/parse",
+             |      {
+             |        "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+             |        "notFound": ["${blobIdNotFound.serialize()}"],
+             |        "notParsable": ["${blobIdNotParsable.serialize()}"],
+             |        "parsed": {
+             |           "${blobIdParsable.serialize()}": {
+             |             "subject": "Read: test",
+             |             "textBody": "To: magiclan@linagora.com\\r\\nSubject: test\\r\\nMessage was displayed on Tue Mar 30 2021 10:31:50 GMT+0700 (Indochina Time)",
+             |             "reportingUA": "OpenPaaS Unified Inbox",
+             |             "disposition": {
+             |               "actionMode": "manual-action",
+             |               "sendingMode": "MDN-sent-manually",
+             |               "type": "displayed"
+             |             },
+             |             "finalRecipient": "rfc822; tungexplorer@linagora.com",
+             |             "originalMessageId": "<63...@linagora.com>",
+             |             "includeOriginalMessage": true,
+             |             "error": [
+             |                "Message1",
+             |                "Message2"
+             |             ],
+             |             "extensionFields": {
+             |                "X-OPENPAAS-IP" : " 177.177.177.77",
+             |                "X-OPENPAAS-PORT" : " 8000"
+             |             }
+             |          }
+             |        }
+             |      },
+             |      "c1"
+             |        ]]
+             |}""".stripMargin)
+      }
+    }
+  }
+
+  @Test
+  def mdnParseShouldReturnUnknownMethodWhenMissingOneCapability(): Unit = {
+    val request =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:core",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "123" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |  "sessionState": "${SESSION_STATE.value}",
+         |  "methodResponses": [[
+         |    "error",
+         |    {
+         |      "type": "unknownMethod",
+         |      "description": "Missing capability(ies): urn:ietf:params:jmap:mdn"
+         |    },
+         |    "c1"]]
+         |}""".stripMargin)
+  }
+
+  @Test
+  def mdnParseShouldReturnUnknownMethodWhenMissingAllCapabilities(): Unit = {
+    val request =
+      s"""{
+         |  "using": [],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "123" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response).isEqualTo(
+      s"""{
+         |  "sessionState": "${SESSION_STATE.value}",
+         |  "methodResponses": [[
+         |    "error",
+         |    {
+         |      "type": "unknownMethod",
+         |      "description": "Missing capability(ies): urn:ietf:params:jmap:mdn, urn:ietf:params:jmap:mail, urn:ietf:params:jmap:core"

Review comment:
       We do not need `urn:ietf:params:jmap:mail`, let's not require it.

##########
File path: server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/MDNParseMethodContract.scala
##########
@@ -0,0 +1,538 @@
+/** **************************************************************
+ * 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.jmap.rfc8621.contract
+
+import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT
+import io.restassured.RestAssured._
+import io.restassured.http.ContentType.JSON
+import net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson
+import org.apache.http.HttpStatus.SC_OK
+import org.apache.james.GuiceJamesServer
+import org.apache.james.jmap.core.ResponseObject.SESSION_STATE
+import org.apache.james.jmap.http.UserCredential
+import org.apache.james.jmap.rfc8621.contract.Fixture._
+import org.apache.james.mailbox.MessageManager.AppendCommand
+import org.apache.james.mailbox.model.{MailboxPath, MessageId}
+import org.apache.james.mime4j.dom.Message
+import org.apache.james.mime4j.message.MultipartBuilder
+import org.apache.james.modules.MailboxProbeImpl
+import org.apache.james.util.ClassLoaderUtils
+import org.apache.james.utils.DataProbeImpl
+import org.awaitility.Awaitility
+import org.awaitility.Durations.ONE_HUNDRED_MILLISECONDS
+import org.junit.jupiter.api.{BeforeEach, Test}
+import play.api.libs.json._
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.TimeUnit
+
+trait MDNParseMethodContract {
+  private lazy val slowPacedPollInterval = ONE_HUNDRED_MILLISECONDS
+  private lazy val calmlyAwait = Awaitility.`with`
+    .pollInterval(slowPacedPollInterval)
+    .and.`with`.pollDelay(slowPacedPollInterval)
+    .await
+
+  private lazy val awaitAtMostTenSeconds = calmlyAwait.atMost(5, TimeUnit.SECONDS)
+  @BeforeEach
+  def setUp(server: GuiceJamesServer): Unit = {
+    server.getProbe(classOf[DataProbeImpl])
+      .fluent()
+      .addDomain(DOMAIN.asString())
+      .addUser(BOB.asString(), BOB_PASSWORD)
+
+    requestSpecification = baseRequestSpecBuilder(server)
+      .setAuth(authScheme(UserCredential(BOB, BOB_PASSWORD)))
+      .build()
+  }
+
+  def randomMessageId: MessageId
+
+  @Test
+  def mdnParseHasValidBodyFormatShouldSucceed(guiceJamesServer: GuiceJamesServer): Unit = {
+    val path: MailboxPath = MailboxPath.inbox(BOB)
+    val mailboxProbe: MailboxProbeImpl = guiceJamesServer.getProbe(classOf[MailboxProbeImpl])
+    mailboxProbe.createMailbox(path)
+
+    val messageId: MessageId = mailboxProbe
+      .appendMessage(BOB.asString(), path, AppendCommand.from(
+        ClassLoaderUtils.getSystemResourceAsSharedStream("eml/mdn.eml")))
+      .getMessageId
+
+    val request: String =
+      s"""{
+         |  "using": [
+         |    "urn:ietf:params:jmap:mdn",
+         |    "urn:ietf:params:jmap:mail"],
+         |  "methodCalls": [[
+         |    "MDN/parse",
+         |    {
+         |      "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+         |      "blobIds": [ "${messageId.serialize()}" ]
+         |    },
+         |    "c1"]]
+         |}""".stripMargin
+
+    val response = `given`
+      .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
+      .body(request)
+    .when
+      .post.prettyPeek()
+    .`then`
+      .statusCode(SC_OK)
+      .contentType(JSON)
+      .extract
+      .body
+      .asString
+
+    assertThatJson(response)
+      .isEqualTo(
+        s"""{
+           |    "sessionState": "${SESSION_STATE.value}",
+           |    "methodResponses": [
+           |      [ "MDN/parse", {
+           |         "accountId": "29883977c13473ae7cb7678ef767cbfbaffc8a44a6e463d971d23a65c1dc4af6",
+           |         "parsed": {
+           |           "${messageId.serialize()}": {
+           |             "subject": "Read: test",
+           |             "textBody": "To: magiclan@linagora.com\\r\\nSubject: test\\r\\nMessage was displayed on Tue Mar 30 2021 10:31:50 GMT+0700 (Indochina Time)",
+           |             "reportingUA": "OpenPaaS Unified Inbox; ",
+           |             "disposition": {
+           |               "actionMode": "manual-action",
+           |               "sendingMode": "MDN-sent-manually",
+           |               "type": "displayed"
+           |             },
+           |             "finalRecipient": "rfc822; tungexplorer@linagora.com",
+           |             "originalMessageId": "<63...@linagora.com>",

Review comment:
       originalRecipient filed should appear in the complex MDN. Can you add it?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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