You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by bt...@apache.org on 2019/12/17 01:55:21 UTC

[james-project] branch master updated (a2b3b28 -> 4bfb763)

This is an automated email from the ASF dual-hosted git repository.

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


    from a2b3b28  Merge remote-tracking branch 'mbaechler/revert-boundedElasticScheduler-use'
     new f0c2b9f  JAMES-2993 Package relocation
     new 774e96c  JAMES-2993 Provide a JsonSerializationVerifier
     new 6a583a3  JAMES-2993 Demonstrate JsonSerializationVerifier in DeletedMessagesVaultDeleteTaskSerializationTest
     new 464fcbf  [Refactoring] NamespaceResponse: simplify & test equals & hashCode
     new f9c4e17  [Refactoring] SearchResponse: simplify & test equals & hashCode
     new c5994df  [Refactoring] FlagsResponse: simplify & test equals & hashCode
     new 58b3e9b  [Refactoring] IMAP responses: avoid super constructor call
     new 3ee393e  [Refactoring] ContinuationResponse::data is always null
     new 2033c68  JAMES-3006 Add a TaskFactory for modular task registration in webadmin
     new dc69a93  JAMES-3006 Use Task factory in dead-letter routes
     new 81fbf90  JAMES-3006 Use Task factory in cassandra alias projection routes
     new 7151790  JAMES-3006 Use Task factory in deleted message vault routes
     new 93a560d  JAMES-3006 Use Task factory in reindexing routes
     new e61f8f8  JAMES-3006 Use Task factory in mail repositories routes
     new bea1b9e  JAMES-3006 Use Task generator in cassandra alias projection routes
     new 444bc03  JAMES-3006 Use Task generator in cassandra migration routes
     new 2ce2c48  JAMES-3006 Use Task generator in mail queue routes
     new 40042e9  JAMES-3006 Move TaskIdDTO in task package + visibility enhancements
     new b81e633  JAMES-3006 TaskIdDTO should not be responsible of its response encoding
     new 9677cbf  JAMES-3006 Shortcut for single-entry task factories
     new 8afb45e  JAMES-3006 Improve TaskFactory error message upon invalid query parameter
     new 83a5b96  JAMES-3006 s/TaskGenerator/TaskFromRequest
     new b456eb0  JAMES-2993 Factorize documentation for returned taskIds
     new 4bfb763  JAMES-2993 201 does only mean task generation success

The 24 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../org/apache/{ => james}/DTOConverterTest.java   |  16 +-
 .../{ => james}/JsonGenericSerializerTest.java     |  36 ++-
 .../apache/james/JsonSerializationVerifier.java    |  69 ++++++
 .../james/JsonSerializationVerifierTest.java       |  43 ++--
 .../org/apache/james/SerializationFixture.java     |  47 ++++
 .../java/org/apache/{ => james}/dto/BaseType.java  |   2 +-
 .../java/org/apache/{ => james}/dto/FirstDTO.java  |   2 +-
 .../apache/{ => james}/dto/FirstDomainObject.java  |   2 +-
 .../org/apache/{ => james}/dto/FirstNestedDTO.java |   2 +-
 .../apache/{ => james}/dto/FirstNestedType.java    |   2 +-
 .../org/apache/{ => james}/dto/NestedType.java     |   2 +-
 .../java/org/apache/{ => james}/dto/SecondDTO.java |   2 +-
 .../apache/{ => james}/dto/SecondDomainObject.java |   2 +-
 .../apache/{ => james}/dto/SecondNestedDTO.java    |   2 +-
 .../apache/{ => james}/dto/SecondNestedType.java   |   2 +-
 .../org/apache/{ => james}/dto/TestModule.java     |   2 +-
 .../org/apache/{ => james}/dto/TestModules.java    |   4 +-
 .../apache/{ => james}/dto/TestNestedModule.java   |   2 +-
 pom.xml                                            |   6 +
 .../imap/encode/ContinuationResponseEncoder.java   |   2 +-
 .../james/imap/message/response/ACLResponse.java   |   2 -
 .../message/response/AbstractListingResponse.java  |   2 -
 .../message/response/ContinuationResponse.java     |   9 -
 .../imap/message/response/ESearchResponse.java     |   2 -
 .../imap/message/response/ExistsResponse.java      |   1 -
 .../imap/message/response/ExpungeResponse.java     |   1 -
 .../james/imap/message/response/FetchResponse.java |  11 -
 .../james/imap/message/response/FlagsResponse.java |  46 ++--
 .../message/response/ImmutableStatusResponse.java  |   5 -
 .../james/imap/message/response/ListResponse.java  |   2 -
 .../imap/message/response/ListRightsResponse.java  |   1 -
 .../message/response/MailboxStatusResponse.java    |   7 -
 .../imap/message/response/MyRightsResponse.java    |   1 -
 .../imap/message/response/NamespaceResponse.java   |  98 ++------
 .../imap/message/response/QuotaRootResponse.java   |   1 -
 .../imap/message/response/RecentResponse.java      |   2 -
 .../imap/message/response/SearchResponse.java      |  33 +--
 .../imap/message/response/FlagsResponseTest.java   |  15 +-
 .../message/response/NamespaceResponseTest.java}   |  21 +-
 .../imap/message/response/SearchResponseTest.java  |  15 +-
 .../apache/james/webadmin/dto/ActionMappings.java  |  36 ---
 .../webadmin/routes/CassandraMappingsRoutes.java   |  21 +-
 .../webadmin/service/CassandraMappingsService.java |  12 +-
 .../routes/CassandraMappingsRoutesTest.java        |   4 +-
 .../routes/CassandraMailboxMergingRoutes.java      |  15 +-
 .../webadmin/routes/CassandraMigrationRoutes.java  |  23 +-
 .../TaskIdDto.java => tasks/TaskFromRequest.java}  |  48 ++--
 .../webadmin/tasks/TaskFromRequestRegistry.java    | 151 +++++++++++++
 .../org/apache/james/webadmin/tasks/TaskIdDto.java |  15 +-
 .../james/webadmin/tasks/TaskRegistrationKey.java  |  49 ++--
 .../tasks/TaskFromRequestRegistryTest.java         | 157 +++++++++++++
 .../TaskFromRequestTest.java}                      |  24 +-
 .../webadmin/tasks/TaskRegistrationKeyTest.java}   |  35 +--
 .../webadmin-mailbox-deleted-message-vault/pom.xml |   6 +
 .../routes/DeletedMessagesVaultDeleteTask.java     |  33 +++
 .../vault/routes/DeletedMessagesVaultRoutes.java   | 200 ++++-------------
 ...edMessagesVaultDeleteTaskSerializationTest.java |  54 ++---
 .../routes/DeletedMessagesVaultRoutesTest.java     |  22 +-
 .../apache/james/webadmin/dto/ActionEvents.java    |  37 ---
 .../webadmin/routes/EventDeadLettersRoutes.java    |  56 ++---
 .../webadmin/routes/MessageIdReindexingRoutes.java |  28 +--
 .../webadmin/routes/ReIndexingRoutesUtil.java      |  38 ----
 .../james/webadmin/routes/ReindexingRoutes.java    |  87 +++----
 .../routes/EventDeadLettersRoutesTest.java         |  12 +-
 .../webadmin/routes/ReindexingRoutesTest.java      |  39 ++--
 .../james/webadmin/routes/MailQueueRoutes.java     |  13 +-
 .../webadmin/routes/MailRepositoriesRoutes.java    |  69 +++---
 .../routes/MailRepositoriesRoutesTest.java         |  12 +-
 src/site/markdown/server/manage-webadmin.md        | 249 +++++++--------------
 69 files changed, 1052 insertions(+), 1015 deletions(-)
 rename json/src/test/java/org/apache/{ => james}/DTOConverterTest.java (93%)
 rename json/src/test/java/org/apache/{ => james}/JsonGenericSerializerTest.java (71%)
 create mode 100644 json/src/test/java/org/apache/james/JsonSerializationVerifier.java
 rename server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/dto/ActionMappingsTest.java => json/src/test/java/org/apache/james/JsonSerializationVerifierTest.java (54%)
 create mode 100644 json/src/test/java/org/apache/james/SerializationFixture.java
 rename json/src/test/java/org/apache/{ => james}/dto/BaseType.java (97%)
 rename json/src/test/java/org/apache/{ => james}/dto/FirstDTO.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/FirstDomainObject.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/FirstNestedDTO.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/FirstNestedType.java (98%)
 copy json/src/test/java/org/apache/{ => james}/dto/NestedType.java (97%)
 rename json/src/test/java/org/apache/{ => james}/dto/SecondDTO.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/SecondDomainObject.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/SecondNestedDTO.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/SecondNestedType.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/TestModule.java (98%)
 rename json/src/test/java/org/apache/{ => james}/dto/TestModules.java (97%)
 rename json/src/test/java/org/apache/{ => james}/dto/TestNestedModule.java (98%)
 copy json/src/test/java/org/apache/dto/NestedType.java => protocols/imap/src/test/java/org/apache/james/imap/message/response/FlagsResponseTest.java (80%)
 copy protocols/imap/src/{main/java/org/apache/james/imap/message/response/ExistsResponse.java => test/java/org/apache/james/imap/message/response/NamespaceResponseTest.java} (75%)
 copy json/src/test/java/org/apache/dto/NestedType.java => protocols/imap/src/test/java/org/apache/james/imap/message/response/SearchResponseTest.java (80%)
 delete mode 100644 server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/dto/ActionMappings.java
 rename server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/{dto/TaskIdDto.java => tasks/TaskFromRequest.java} (56%)
 create mode 100644 server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistry.java
 rename json/src/test/java/org/apache/dto/NestedType.java => server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java (83%)
 copy protocols/imap/src/main/java/org/apache/james/imap/message/response/QuotaRootResponse.java => server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskRegistrationKey.java (55%)
 create mode 100644 server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistryTest.java
 rename server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/{dto/TaskIdDtoTest.java => tasks/TaskFromRequestTest.java} (70%)
 rename server/protocols/webadmin/{webadmin-mailbox/src/test/java/org/apache/james/webadmin/dto/ActionEventsTest.java => webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskRegistrationKeyTest.java} (66%)
 delete mode 100644 server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/dto/ActionEvents.java
 delete mode 100644 server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReIndexingRoutesUtil.java


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


[james-project] 09/24: JAMES-3006 Add a TaskFactory for modular task registration in webadmin

Posted by bt...@apache.org.
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 2033c68721b77f5e96ce672377a92aeca9cce9f8
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:27:46 2019 +0100

    JAMES-3006 Add a TaskFactory for modular task registration in webadmin
---
 .../apache/james/webadmin/tasks/TaskFactory.java   | 145 +++++++++++++++++++
 .../apache/james/webadmin/tasks/TaskGenerator.java |  54 +++++++
 .../james/webadmin/tasks/TaskRegistrationKey.java  |  66 +++++++++
 .../james/webadmin/tasks/TaskFactoryTest.java      | 159 +++++++++++++++++++++
 .../webadmin/tasks/TaskRegistrationKeyTest.java    |  53 +++++++
 5 files changed, 477 insertions(+)

diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
new file mode 100644
index 0000000..7db9bef
--- /dev/null
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
@@ -0,0 +1,145 @@
+/****************************************************************
+ * 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.webadmin.tasks;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.james.task.Task;
+import org.apache.james.task.TaskManager;
+
+import com.github.fge.lambdas.Throwing;
+import com.github.steveash.guavate.Guavate;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+import spark.Request;
+import spark.Route;
+
+public class TaskFactory implements TaskGenerator {
+    private static final String DEFAULT_PARAMETER = "action";
+
+    public static class Builder {
+        private Optional<String> taskParameterName;
+        private ImmutableMap.Builder<TaskRegistrationKey, TaskGenerator> tasks;
+
+        public Builder() {
+            taskParameterName = Optional.empty();
+            tasks = ImmutableMap.builder();
+        }
+
+        public Builder parameterName(String parameterName) {
+            this.taskParameterName = Optional.of(parameterName);
+            return this;
+        }
+
+        public Builder registrations(TaskRegistration... taskRegistrations) {
+            this.tasks.putAll(Arrays.stream(taskRegistrations)
+                .collect(Guavate.toImmutableMap(
+                    TaskRegistration::registrationKey,
+                    Function.identity())));
+            return this;
+        }
+
+        public Builder register(TaskRegistrationKey key, TaskGenerator taskGenerator) {
+            this.tasks.put(key, taskGenerator);
+            return this;
+        }
+
+        public TaskFactory build() {
+            ImmutableMap<TaskRegistrationKey, TaskGenerator> registrations = tasks.build();
+            Preconditions.checkState(!registrations.isEmpty());
+            return new TaskFactory(
+                taskParameterName.orElse(DEFAULT_PARAMETER),
+                registrations);
+        }
+
+        public Route buildAsRoute(TaskManager taskManager) {
+            return build().asRoute(taskManager);
+        }
+    }
+
+    public static class TaskRegistration implements TaskGenerator {
+        private final TaskRegistrationKey taskRegistrationKey;
+        private final TaskGenerator taskGenerator;
+
+        public TaskRegistration(TaskRegistrationKey taskRegistrationKey, TaskGenerator taskGenerator) {
+            this.taskRegistrationKey = taskRegistrationKey;
+            this.taskGenerator = taskGenerator;
+        }
+
+        public TaskRegistrationKey registrationKey() {
+            return taskRegistrationKey;
+        }
+
+        @Override
+        public Task generate(Request request) throws Exception {
+            return taskGenerator.generate(request);
+        }
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    private final String taskParameterName;
+    private final Map<TaskRegistrationKey, TaskGenerator> taskGenerators;
+
+    private TaskFactory(String taskParameterName, Map<TaskRegistrationKey, TaskGenerator> taskGenerators) {
+        this.taskParameterName = taskParameterName;
+        this.taskGenerators = taskGenerators;
+    }
+
+    @Override
+    public Task generate(Request request) throws Exception {
+        TaskRegistrationKey registrationKey = parseRegistrationKey(request);
+        return Optional.ofNullable(taskGenerators.get(registrationKey))
+            .map(Throwing.<TaskGenerator, Task>function(taskGenerator -> taskGenerator.generate(request)).sneakyThrow())
+            .orElseThrow(() -> new IllegalArgumentException("Invalid value supplied for '" + taskParameterName + "': " + registrationKey.asString()
+                + ". " + supportedValueMessage()));
+    }
+
+    private TaskRegistrationKey parseRegistrationKey(Request request) {
+        return Optional.ofNullable(request.queryParams(taskParameterName))
+            .map(this::validateParameter)
+            .map(TaskRegistrationKey::of)
+            .orElseThrow(() -> new IllegalArgumentException("'" + taskParameterName + "' query parameter is compulsory. " + supportedValueMessage()));
+    }
+
+    private String validateParameter(String parameter) {
+        if (StringUtils.isBlank(parameter)) {
+            throw new IllegalArgumentException("'" + taskParameterName + "' query parameter cannot be empty or blank. " + supportedValueMessage());
+        }
+        return parameter;
+    }
+
+    private String supportedValueMessage() {
+        ImmutableList<String> supportedTasks = taskGenerators.keySet()
+            .stream()
+            .map(TaskRegistrationKey::asString)
+            .collect(Guavate.toImmutableList());
+        return "Supported values are [" + Joiner.on(", ").join(supportedTasks) + "]";
+    }
+}
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
new file mode 100644
index 0000000..09d759e
--- /dev/null
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
@@ -0,0 +1,54 @@
+/****************************************************************
+ * 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.webadmin.tasks;
+
+import org.apache.james.task.Task;
+import org.apache.james.task.TaskId;
+import org.apache.james.task.TaskManager;
+import org.apache.james.webadmin.dto.TaskIdDto;
+
+import spark.Request;
+import spark.Response;
+import spark.Route;
+
+public interface TaskGenerator {
+    class TaskRoute implements Route {
+        private final TaskGenerator taskGenerator;
+        private final TaskManager taskManager;
+
+        TaskRoute(TaskGenerator taskGenerator, TaskManager taskManager) {
+            this.taskGenerator = taskGenerator;
+            this.taskManager = taskManager;
+        }
+
+        @Override
+        public Object handle(Request request, Response response) throws Exception {
+            Task task = taskGenerator.generate(request);
+            TaskId taskId = taskManager.submit(task);
+            return TaskIdDto.respond(response, taskId);
+        }
+    }
+
+    Task generate(Request request) throws Exception;
+
+    default Route asRoute(TaskManager taskManager) {
+        return new TaskRoute(this, taskManager);
+    }
+}
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskRegistrationKey.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskRegistrationKey.java
new file mode 100644
index 0000000..cf1e55e
--- /dev/null
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskRegistrationKey.java
@@ -0,0 +1,66 @@
+/****************************************************************
+ * 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.webadmin.tasks;
+
+import java.util.Objects;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Preconditions;
+
+public class TaskRegistrationKey {
+    public static TaskRegistrationKey of(String value) {
+        Preconditions.checkNotNull(value, "TaskRegistrationKey cannot be null");
+        Preconditions.checkArgument(!value.isEmpty(), "TaskRegistrationKey cannot be empty");
+
+        return new TaskRegistrationKey(value);
+    }
+
+    private final String value;
+
+    private TaskRegistrationKey(String value) {
+        this.value = value;
+    }
+
+    public String asString() {
+        return value;
+    }
+
+    @Override
+    public final boolean equals(Object o) {
+        if (o instanceof TaskRegistrationKey) {
+            TaskRegistrationKey that = (TaskRegistrationKey) o;
+
+            return Objects.equals(this.value, that.value);
+        }
+        return false;
+    }
+
+    @Override
+    public final int hashCode() {
+        return Objects.hash(value);
+    }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(this)
+            .add("value", value)
+            .toString();
+    }
+}
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
new file mode 100644
index 0000000..648fc84
--- /dev/null
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
@@ -0,0 +1,159 @@
+/****************************************************************
+ * 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.webadmin.tasks;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.apache.james.task.Task;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import spark.Request;
+
+class TaskFactoryTest {
+    static final Task TASK_1 = mock(Task.class);
+    static final Task TASK_2 = mock(Task.class);
+    static final TaskRegistrationKey KEY_1 = TaskRegistrationKey.of("task1");
+    static final TaskRegistrationKey KEY_2 = TaskRegistrationKey.of("task2");
+
+    Request request;
+    TaskFactory taskFactory;
+    TaskFactory singleTaskFactory;
+
+    @BeforeEach
+    void setUp() {
+        request = mock(Request.class);
+        taskFactory = TaskFactory.builder()
+            .register(KEY_1, any -> TASK_1)
+            .register(KEY_2, any -> TASK_2)
+            .build();
+        singleTaskFactory = TaskFactory.builder()
+            .register(KEY_1, any -> TASK_1)
+            .build();
+    }
+
+    @Test
+    void buildShouldThrowWhenNoTasks() {
+        assertThatThrownBy(() -> TaskFactory.builder().build())
+            .isInstanceOf(IllegalStateException.class);
+    }
+
+    @Test
+    void generateShouldThrowFormattedMessageWhenNoTaskParamAndSeveralOptions() {
+        assertThatThrownBy(() -> taskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("'action' query parameter is compulsory. Supported values are [task1, task2]");
+    }
+
+    @Test
+    void generateShouldThrowFormattedMessageWhenNoTaskParam() {
+        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("'action' query parameter is compulsory. Supported values are [task1]");
+    }
+
+    @Test
+    void generateShouldThrowWhenCustomParameterValueIsInvalid() {
+        TaskFactory taskFactory = TaskFactory.builder()
+            .parameterName("custom")
+            .register(KEY_1, any -> TASK_1)
+            .build();
+
+        when(request.queryParams("custom")).thenReturn("unknown");
+
+        assertThatThrownBy(() -> taskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("Invalid value supplied for 'custom': unknown. Supported values are [task1]");
+    }
+
+    @Test
+    void generateShouldThrowWhenCustomParameterNotSpecified() {
+        TaskFactory taskFactory = TaskFactory.builder()
+            .parameterName("custom")
+            .register(KEY_1, any -> TASK_1)
+            .build();
+
+        when(request.queryParams("action")).thenReturn("unknown");
+
+        assertThatThrownBy(() -> taskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("'custom' query parameter is compulsory. Supported values are [task1]");
+    }
+
+    @Test
+    void generateShouldThrowFormattedMessageWhenUnknownTaskParamAndSeveralOptions() {
+        when(request.queryParams("action")).thenReturn("unknown");
+
+        assertThatThrownBy(() -> taskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("Invalid value supplied for 'action': unknown. Supported values are [task1, task2]");
+    }
+
+    @Test
+    void generateShouldThrowFormattedMessageWhenUnknownTaskParam() {
+        when(request.queryParams("action")).thenReturn("unknown");
+
+        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("Invalid value supplied for 'action': unknown. Supported values are [task1]");
+    }
+
+    @Test
+    void generateShouldThrowWhenEmptyTaskParam() {
+        when(request.queryParams("action")).thenReturn("");
+
+        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("'action' query parameter cannot be empty or blank. Supported values are [task1]");
+    }
+
+    @Test
+    void generateShouldThrowWhenBlankTaskParam() {
+        when(request.queryParams("action")).thenReturn(" ");
+
+        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+            .isInstanceOf(IllegalArgumentException.class)
+            .hasMessage("'action' query parameter cannot be empty or blank. Supported values are [task1]");
+    }
+
+    @Test
+    void generateShouldCreateCorrespondingTask() throws Exception {
+        when(request.queryParams("action")).thenReturn("task1");
+
+        assertThat(singleTaskFactory.generate(request))
+            .isSameAs(TASK_1);
+    }
+
+    @Test
+    void generateShouldHandleCustomTaskParameter() throws Exception {
+        TaskFactory taskFactory = TaskFactory.builder()
+            .parameterName("custom")
+            .register(KEY_1, any -> TASK_1)
+            .build();
+
+        when(request.queryParams("custom")).thenReturn("task1");
+
+        assertThat(taskFactory.generate(request))
+            .isSameAs(TASK_1);
+    }
+}
\ No newline at end of file
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskRegistrationKeyTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskRegistrationKeyTest.java
new file mode 100644
index 0000000..3d7babe
--- /dev/null
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskRegistrationKeyTest.java
@@ -0,0 +1,53 @@
+/****************************************************************
+ * 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.webadmin.tasks;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.junit.jupiter.api.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+
+class TaskRegistrationKeyTest {
+    @Test
+    void shouldMatchBeanContract() {
+        EqualsVerifier.forClass(TaskRegistrationKey.class)
+            .verify();
+    }
+
+    @Test
+    void ofShouldThrowWhenNull() {
+        assertThatThrownBy(() -> TaskRegistrationKey.of(null))
+            .isInstanceOf(NullPointerException.class);
+    }
+
+    @Test
+    void ofShouldThrowWhenEmpty() {
+        assertThatThrownBy(() -> TaskRegistrationKey.of(""))
+            .isInstanceOf(IllegalArgumentException.class);
+    }
+
+    @Test
+    void asStringShouldReturnRawValue() {
+        assertThat(TaskRegistrationKey.of("reindex").asString())
+            .isEqualTo("reindex");
+    }
+}
\ No newline at end of file


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


[james-project] 21/24: JAMES-3006 Improve TaskFactory error message upon invalid query parameter

Posted by bt...@apache.org.
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 8afb45e9321869cf197aa586b1385dc563899fd7
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 05:24:00 2019 +0100

    JAMES-3006 Improve TaskFactory error message upon invalid query parameter
---
 .../james/webadmin/routes/CassandraMappingsRoutesTest.java |  2 +-
 .../java/org/apache/james/webadmin/tasks/TaskFactory.java  |  2 +-
 .../org/apache/james/webadmin/tasks/TaskFactoryTest.java   |  6 +++---
 .../vault/routes/DeletedMessagesVaultRoutesTest.java       |  4 ++--
 .../james/webadmin/routes/EventDeadLettersRoutesTest.java  |  6 +++---
 .../apache/james/webadmin/routes/ReindexingRoutesTest.java | 14 +++++++-------
 .../james/webadmin/routes/MailRepositoriesRoutesTest.java  |  4 ++--
 7 files changed, 19 insertions(+), 19 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java b/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java
index 8215091..5c42462 100644
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java
@@ -140,7 +140,7 @@ class CassandraMappingsRoutesTest {
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
             .body("message", is("Invalid arguments supplied in the user request"))
-            .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [SolveInconsistencies]"));
+            .body("details", is("Invalid value supplied for query parameter 'action': invalid-action. Supported values are [SolveInconsistencies]"));
     }
 
     @Test
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
index a46c6c9..dcacc2f 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
@@ -123,7 +123,7 @@ public class TaskFactory implements TaskGenerator {
         TaskRegistrationKey registrationKey = parseRegistrationKey(request);
         return Optional.ofNullable(taskGenerators.get(registrationKey))
             .map(Throwing.<TaskGenerator, Task>function(taskGenerator -> taskGenerator.generate(request)).sneakyThrow())
-            .orElseThrow(() -> new IllegalArgumentException("Invalid value supplied for '" + taskParameterName + "': " + registrationKey.asString()
+            .orElseThrow(() -> new IllegalArgumentException("Invalid value supplied for query parameter '" + taskParameterName + "': " + registrationKey.asString()
                 + ". " + supportedValueMessage()));
     }
 
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
index 18b947f..d4a7707 100644
--- a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
@@ -81,7 +81,7 @@ class TaskFactoryTest {
 
         assertThatThrownBy(() -> taskFactory.generate(request))
             .isInstanceOf(IllegalArgumentException.class)
-            .hasMessage("Invalid value supplied for 'custom': unknown. Supported values are [task1]");
+            .hasMessage("Invalid value supplied for query parameter 'custom': unknown. Supported values are [task1]");
     }
 
     @Test
@@ -104,7 +104,7 @@ class TaskFactoryTest {
 
         assertThatThrownBy(() -> taskFactory.generate(request))
             .isInstanceOf(IllegalArgumentException.class)
-            .hasMessage("Invalid value supplied for 'action': unknown. Supported values are [task1, task2]");
+            .hasMessage("Invalid value supplied for query parameter 'action': unknown. Supported values are [task1, task2]");
     }
 
     @Test
@@ -113,7 +113,7 @@ class TaskFactoryTest {
 
         assertThatThrownBy(() -> singleTaskFactory.generate(request))
             .isInstanceOf(IllegalArgumentException.class)
-            .hasMessage("Invalid value supplied for 'action': unknown. Supported values are [task1]");
+            .hasMessage("Invalid value supplied for query parameter 'action': unknown. Supported values are [task1]");
     }
 
     @Test
diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java
index 02528fd..6f43b0e 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java
@@ -332,7 +332,7 @@ class DeletedMessagesVaultRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", startsWith("Invalid value supplied for 'scope': invalid action. Supported values are [expired]"));
+                .body("details", startsWith("Invalid value supplied for query parameter 'scope': invalid action. Supported values are [expired]"));
         }
 
         @Test
@@ -346,7 +346,7 @@ class DeletedMessagesVaultRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("Invalid value supplied for 'scope': EXPIRED. Supported values are [expired]"));
+                .body("details", is("Invalid value supplied for query parameter 'scope': EXPIRED. Supported values are [expired]"));
         }
 
         @ParameterizedTest
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java
index 9c56056..8db4d2c 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java
@@ -533,7 +533,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [reDeliver]"));
+                .body("details", is("Invalid value supplied for query parameter 'action': invalid-action. Supported values are [reDeliver]"));
         }
 
         @Test
@@ -721,7 +721,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [reDeliver]"));
+                .body("details", is("Invalid value supplied for query parameter 'action': invalid-action. Supported values are [reDeliver]"));
         }
 
         @Test
@@ -900,7 +900,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [reDeliver]"));
+                .body("details", is("Invalid value supplied for query parameter 'action': invalid-action. Supported values are [reDeliver]"));
         }
 
         @Test
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java
index f7b94e3..40ab5de 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java
@@ -143,7 +143,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
         }
 
@@ -304,7 +304,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -494,7 +494,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -684,7 +684,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -842,7 +842,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -1019,7 +1019,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -1035,7 +1035,7 @@ class ReindexingRoutesTest {
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                     .body("message", is("Invalid arguments supplied in the user request"))
-                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
+                    .body("details", is("Invalid value supplied for query parameter 'task': bad. Supported values are [reIndex]"));
             }
         }
 
diff --git a/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java b/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java
index 2568146..eb6998a 100644
--- a/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java
@@ -1076,7 +1076,7 @@ public class MailRepositoriesRoutesTest {
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
             .body("message", is("Invalid arguments supplied in the user request"))
-            .body("details", is("Invalid value supplied for 'action': invalid. Supported values are [reprocess]"));
+            .body("details", is("Invalid value supplied for query parameter 'action': invalid. Supported values are [reprocess]"));
     }
 
     @Test
@@ -1436,7 +1436,7 @@ public class MailRepositoriesRoutesTest {
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
             .body("message", is("Invalid arguments supplied in the user request"))
-            .body("details", is("Invalid value supplied for 'action': invalid. Supported values are [reprocess]"));
+            .body("details", is("Invalid value supplied for query parameter 'action': invalid. Supported values are [reprocess]"));
     }
 
     @Test


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


[james-project] 14/24: JAMES-3006 Use Task factory in mail repositories routes

Posted by bt...@apache.org.
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 e61f8f879d57d2e9ddf057080f7705029fbb3532
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:12:42 2019 +0100

    JAMES-3006 Use Task factory in mail repositories routes
---
 .../webadmin/routes/MailRepositoriesRoutes.java    | 71 +++++++++++-----------
 .../routes/MailRepositoriesRoutesTest.java         | 12 ++--
 2 files changed, 43 insertions(+), 40 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java b/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
index 4bd881f..4b3f123 100644
--- a/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
@@ -43,7 +43,6 @@ import org.apache.james.mailrepository.api.MailRepositoryPath;
 import org.apache.james.mailrepository.api.MailRepositoryStore;
 import org.apache.james.queue.api.MailQueueFactory;
 import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.util.streams.Limit;
 import org.apache.james.util.streams.Offset;
@@ -53,11 +52,14 @@ import org.apache.james.webadmin.dto.ExtendedMailRepositoryResponse;
 import org.apache.james.webadmin.dto.InaccessibleFieldException;
 import org.apache.james.webadmin.dto.MailDto;
 import org.apache.james.webadmin.dto.MailDto.AdditionalField;
-import org.apache.james.webadmin.dto.TaskIdDto;
 import org.apache.james.webadmin.service.MailRepositoryStoreService;
 import org.apache.james.webadmin.service.ReprocessingAllMailsTask;
 import org.apache.james.webadmin.service.ReprocessingOneMailTask;
 import org.apache.james.webadmin.service.ReprocessingService;
+import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.ErrorResponder.ErrorType;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -85,6 +87,8 @@ import spark.Service;
 public class MailRepositoriesRoutes implements Routes {
 
     public static final String MAIL_REPOSITORIES = "mailRepositories";
+    private static final TaskRegistrationKey REPROCESS_ACTION = TaskRegistrationKey.of("reprocess");
+    private static final String ACTION_PARAMETER = "action";
 
     private final JsonTransformer jsonTransformer;
     private final MailRepositoryStoreService repositoryStoreService;
@@ -389,12 +393,10 @@ public class MailRepositoriesRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - unknown action")
     })
     public void defineDeleteAll() {
-        service.delete(MAIL_REPOSITORIES + "/:encodedPath/mails", (request, response) -> {
+        TaskGenerator taskGenerator = request -> {
             MailRepositoryPath path = decodedRepositoryPath(request);
             try {
-                Task task = repositoryStoreService.createClearMailRepositoryTask(path);
-                TaskId taskId = taskManager.submit(task);
-                return TaskIdDto.respond(response, taskId);
+                return repositoryStoreService.createClearMailRepositoryTask(path);
             } catch (MailRepositoryStore.MailRepositoryStoreException | MessagingException e) {
                 throw ErrorResponder.builder()
                     .statusCode(HttpStatus.INTERNAL_SERVER_ERROR_500)
@@ -403,7 +405,8 @@ public class MailRepositoriesRoutes implements Routes {
                     .message("Error while deleting all mails")
                     .haltError();
             }
-        }, jsonTransformer);
+        };
+        service.delete(MAIL_REPOSITORIES + "/:encodedPath/mails", taskGenerator.asRoute(taskManager), jsonTransformer);
     }
 
     @PATCH
@@ -441,18 +444,17 @@ public class MailRepositoriesRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - unknown action")
     })
     public void defineReprocessAll() {
-        service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails", (request, response) -> {
-            Task task = toAllMailReprocessingTask(request);
-            TaskId taskId = taskManager.submit(task);
-            return TaskIdDto.respond(response, taskId);
-        }, jsonTransformer);
+        service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails",
+            TaskFactory.builder()
+                .register(REPROCESS_ACTION, this::reprocessAll)
+                .buildAsRoute(taskManager),
+            jsonTransformer);
     }
 
-    private Task toAllMailReprocessingTask(Request request) throws UnsupportedEncodingException, MailRepositoryStore.MailRepositoryStoreException, MessagingException {
+    private Task reprocessAll(Request request) throws UnsupportedEncodingException, MailRepositoryStore.MailRepositoryStoreException {
         MailRepositoryPath path = decodedRepositoryPath(request);
-        enforceActionParameter(request);
-        Optional<String> targetProcessor = Optional.ofNullable(request.queryParams("processor"));
-        String targetQueue = Optional.ofNullable(request.queryParams("queue")).orElse(MailQueueFactory.SPOOL);
+        Optional<String> targetProcessor = parseTargetProcessor(request);
+        String targetQueue = parseTargetQueue(request);
 
         Long repositorySize = repositoryStoreService.size(path).orElse(0L);
         return new ReprocessingAllMailsTask(reprocessingService, repositorySize, path, targetQueue, targetProcessor);
@@ -493,32 +495,21 @@ public class MailRepositoriesRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - unknown action")
     })
     public void defineReprocessOne() {
-        service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails/:key", (request, response) -> {
-            Task task = toOneMailReprocessingTask(request);
-            TaskId taskId = taskManager.submit(task);
-            return TaskIdDto.respond(response, taskId);
-        }, jsonTransformer);
+        service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails/:key",
+            TaskFactory.builder()
+                .register(REPROCESS_ACTION, this::reprocessOne)
+                .buildAsRoute(taskManager),
+            jsonTransformer);
     }
 
-    private Task toOneMailReprocessingTask(Request request) throws UnsupportedEncodingException {
+    private Task reprocessOne(Request request) throws UnsupportedEncodingException {
         MailRepositoryPath path = decodedRepositoryPath(request);
         MailKey key = new MailKey(request.params("key"));
-        enforceActionParameter(request);
-        Optional<String> targetProcessor = Optional.ofNullable(request.queryParams("processor"));
-        String targetQueue = Optional.ofNullable(request.queryParams("queue")).orElse(MailQueueFactory.SPOOL);
 
-        return new ReprocessingOneMailTask(reprocessingService, path, targetQueue, key, targetProcessor, Clock.systemUTC());
-    }
+        Optional<String> targetProcessor = parseTargetProcessor(request);
+        String targetQueue = parseTargetQueue(request);
 
-    private void enforceActionParameter(Request request) {
-        String action = request.queryParams("action");
-        if (!"reprocess".equals(action)) {
-            throw ErrorResponder.builder()
-                .statusCode(HttpStatus.BAD_REQUEST_400)
-                .type(ErrorType.INVALID_ARGUMENT)
-                .message("action query parameter is mandatory. The only supported value is `reprocess`")
-                .haltError();
-        }
+        return new ReprocessingOneMailTask(reprocessingService, path, targetQueue, key, targetProcessor, Clock.systemUTC());
     }
 
     private Set<AdditionalField> extractAdditionalFields(String additionalFieldsParam) throws IllegalArgumentException {
@@ -532,6 +523,14 @@ public class MailRepositoriesRoutes implements Routes {
             .collect(Guavate.toImmutableSet());
     }
 
+    private Optional<String> parseTargetProcessor(Request request) {
+        return Optional.ofNullable(request.queryParams("processor"));
+    }
+
+    private String parseTargetQueue(Request request) {
+        return Optional.ofNullable(request.queryParams("queue")).orElse(MailQueueFactory.SPOOL);
+    }
+
     private MailRepositoryPath decodedRepositoryPath(Request request) throws UnsupportedEncodingException {
         return MailRepositoryPath.fromEncoded(request.params("encodedPath"));
     }
diff --git a/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java b/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java
index 00aeef4..2568146 100644
--- a/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailrepository/src/test/java/org/apache/james/webadmin/routes/MailRepositoriesRoutesTest.java
@@ -1075,7 +1075,8 @@ public class MailRepositoriesRoutesTest {
             .statusCode(HttpStatus.BAD_REQUEST_400)
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-            .body("message", is("action query parameter is mandatory. The only supported value is `reprocess`"));
+            .body("message", is("Invalid arguments supplied in the user request"))
+            .body("details", is("Invalid value supplied for 'action': invalid. Supported values are [reprocess]"));
     }
 
     @Test
@@ -1086,7 +1087,8 @@ public class MailRepositoriesRoutesTest {
             .statusCode(HttpStatus.BAD_REQUEST_400)
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-            .body("message", is("action query parameter is mandatory. The only supported value is `reprocess`"));
+            .body("message", is("Invalid arguments supplied in the user request"))
+            .body("details", is("'action' query parameter is compulsory. Supported values are [reprocess]"));
     }
 
     @Test
@@ -1433,7 +1435,8 @@ public class MailRepositoriesRoutesTest {
             .statusCode(HttpStatus.BAD_REQUEST_400)
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-            .body("message", is("action query parameter is mandatory. The only supported value is `reprocess`"));
+            .body("message", is("Invalid arguments supplied in the user request"))
+            .body("details", is("Invalid value supplied for 'action': invalid. Supported values are [reprocess]"));
     }
 
     @Test
@@ -1449,7 +1452,8 @@ public class MailRepositoriesRoutesTest {
             .statusCode(HttpStatus.BAD_REQUEST_400)
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-            .body("message", is("action query parameter is mandatory. The only supported value is `reprocess`"));
+            .body("message", is("Invalid arguments supplied in the user request"))
+            .body("details", is("'action' query parameter is compulsory. Supported values are [reprocess]"));
     }
 
     @Test


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


[james-project] 01/24: JAMES-2993 Package relocation

Posted by bt...@apache.org.
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 f0c2b9fcead4f513ab10a2db0f958616965b4e8b
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Mon Dec 16 16:59:38 2019 +0700

    JAMES-2993 Package relocation
---
 .../java/org/apache/{ => james}/DTOConverterTest.java    | 16 ++++++++--------
 .../apache/{ => james}/JsonGenericSerializerTest.java    | 16 ++++++++--------
 .../test/java/org/apache/{ => james}/dto/BaseType.java   |  2 +-
 .../test/java/org/apache/{ => james}/dto/FirstDTO.java   |  2 +-
 .../org/apache/{ => james}/dto/FirstDomainObject.java    |  2 +-
 .../java/org/apache/{ => james}/dto/FirstNestedDTO.java  |  2 +-
 .../java/org/apache/{ => james}/dto/FirstNestedType.java |  2 +-
 .../test/java/org/apache/{ => james}/dto/NestedType.java |  2 +-
 .../test/java/org/apache/{ => james}/dto/SecondDTO.java  |  2 +-
 .../org/apache/{ => james}/dto/SecondDomainObject.java   |  2 +-
 .../java/org/apache/{ => james}/dto/SecondNestedDTO.java |  2 +-
 .../org/apache/{ => james}/dto/SecondNestedType.java     |  2 +-
 .../test/java/org/apache/{ => james}/dto/TestModule.java |  2 +-
 .../java/org/apache/{ => james}/dto/TestModules.java     |  2 +-
 .../org/apache/{ => james}/dto/TestNestedModule.java     |  2 +-
 15 files changed, 29 insertions(+), 29 deletions(-)

diff --git a/json/src/test/java/org/apache/DTOConverterTest.java b/json/src/test/java/org/apache/james/DTOConverterTest.java
similarity index 93%
rename from json/src/test/java/org/apache/DTOConverterTest.java
rename to json/src/test/java/org/apache/james/DTOConverterTest.java
index 1c34498..7182c6d 100644
--- a/json/src/test/java/org/apache/DTOConverterTest.java
+++ b/json/src/test/java/org/apache/james/DTOConverterTest.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache;
+package org.apache.james;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -26,13 +26,13 @@ import java.util.Optional;
 import java.util.UUID;
 import java.util.stream.Stream;
 
-import org.apache.dto.BaseType;
-import org.apache.dto.FirstDTO;
-import org.apache.dto.FirstDomainObject;
-import org.apache.dto.NestedType;
-import org.apache.dto.SecondDTO;
-import org.apache.dto.SecondDomainObject;
-import org.apache.dto.TestModules;
+import org.apache.james.dto.BaseType;
+import org.apache.james.dto.FirstDTO;
+import org.apache.james.dto.FirstDomainObject;
+import org.apache.james.dto.NestedType;
+import org.apache.james.dto.SecondDTO;
+import org.apache.james.dto.SecondDomainObject;
+import org.apache.james.dto.TestModules;
 import org.apache.james.json.DTO;
 import org.apache.james.json.DTOConverter;
 import org.junit.jupiter.api.Test;
diff --git a/json/src/test/java/org/apache/JsonGenericSerializerTest.java b/json/src/test/java/org/apache/james/JsonGenericSerializerTest.java
similarity index 95%
rename from json/src/test/java/org/apache/JsonGenericSerializerTest.java
rename to json/src/test/java/org/apache/james/JsonGenericSerializerTest.java
index 235d19d..6b179ba 100644
--- a/json/src/test/java/org/apache/JsonGenericSerializerTest.java
+++ b/json/src/test/java/org/apache/james/JsonGenericSerializerTest.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache;
+package org.apache.james;
 
 import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
 import static org.assertj.core.api.Assertions.assertThat;
@@ -28,13 +28,13 @@ import java.util.Optional;
 import java.util.UUID;
 import java.util.stream.Stream;
 
-import org.apache.dto.BaseType;
-import org.apache.dto.FirstDomainObject;
-import org.apache.dto.FirstNestedType;
-import org.apache.dto.NestedType;
-import org.apache.dto.SecondDomainObject;
-import org.apache.dto.SecondNestedType;
-import org.apache.dto.TestModules;
+import org.apache.james.dto.BaseType;
+import org.apache.james.dto.FirstDomainObject;
+import org.apache.james.dto.FirstNestedType;
+import org.apache.james.dto.NestedType;
+import org.apache.james.dto.SecondDomainObject;
+import org.apache.james.dto.SecondNestedType;
+import org.apache.james.dto.TestModules;
 import org.apache.james.json.DTO;
 import org.apache.james.json.JsonGenericSerializer;
 import org.junit.jupiter.api.Test;
diff --git a/json/src/test/java/org/apache/dto/BaseType.java b/json/src/test/java/org/apache/james/dto/BaseType.java
similarity index 97%
rename from json/src/test/java/org/apache/dto/BaseType.java
rename to json/src/test/java/org/apache/james/dto/BaseType.java
index b277f3c..54b519b 100644
--- a/json/src/test/java/org/apache/dto/BaseType.java
+++ b/json/src/test/java/org/apache/james/dto/BaseType.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 public interface BaseType {
 }
diff --git a/json/src/test/java/org/apache/dto/FirstDTO.java b/json/src/test/java/org/apache/james/dto/FirstDTO.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/FirstDTO.java
rename to json/src/test/java/org/apache/james/dto/FirstDTO.java
index 16c1041..6e88d39 100644
--- a/json/src/test/java/org/apache/dto/FirstDTO.java
+++ b/json/src/test/java/org/apache/james/dto/FirstDTO.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import java.time.ZonedDateTime;
 import java.util.Optional;
diff --git a/json/src/test/java/org/apache/dto/FirstDomainObject.java b/json/src/test/java/org/apache/james/dto/FirstDomainObject.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/FirstDomainObject.java
rename to json/src/test/java/org/apache/james/dto/FirstDomainObject.java
index 13e8462..e4db6f1 100644
--- a/json/src/test/java/org/apache/dto/FirstDomainObject.java
+++ b/json/src/test/java/org/apache/james/dto/FirstDomainObject.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import java.time.ZonedDateTime;
 import java.util.Objects;
diff --git a/json/src/test/java/org/apache/dto/FirstNestedDTO.java b/json/src/test/java/org/apache/james/dto/FirstNestedDTO.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/FirstNestedDTO.java
rename to json/src/test/java/org/apache/james/dto/FirstNestedDTO.java
index 9fd7498..3e24583 100644
--- a/json/src/test/java/org/apache/dto/FirstNestedDTO.java
+++ b/json/src/test/java/org/apache/james/dto/FirstNestedDTO.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import org.apache.james.json.DTO;
 
diff --git a/json/src/test/java/org/apache/dto/FirstNestedType.java b/json/src/test/java/org/apache/james/dto/FirstNestedType.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/FirstNestedType.java
rename to json/src/test/java/org/apache/james/dto/FirstNestedType.java
index 745a582..a4aa447 100644
--- a/json/src/test/java/org/apache/dto/FirstNestedType.java
+++ b/json/src/test/java/org/apache/james/dto/FirstNestedType.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import java.util.Objects;
 
diff --git a/json/src/test/java/org/apache/dto/NestedType.java b/json/src/test/java/org/apache/james/dto/NestedType.java
similarity index 97%
rename from json/src/test/java/org/apache/dto/NestedType.java
rename to json/src/test/java/org/apache/james/dto/NestedType.java
index 80145ee..f881c1d 100644
--- a/json/src/test/java/org/apache/dto/NestedType.java
+++ b/json/src/test/java/org/apache/james/dto/NestedType.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 public interface NestedType {
 }
diff --git a/json/src/test/java/org/apache/dto/SecondDTO.java b/json/src/test/java/org/apache/james/dto/SecondDTO.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/SecondDTO.java
rename to json/src/test/java/org/apache/james/dto/SecondDTO.java
index 91204a8..2549bad 100644
--- a/json/src/test/java/org/apache/dto/SecondDTO.java
+++ b/json/src/test/java/org/apache/james/dto/SecondDTO.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import java.util.Optional;
 import java.util.UUID;
diff --git a/json/src/test/java/org/apache/dto/SecondDomainObject.java b/json/src/test/java/org/apache/james/dto/SecondDomainObject.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/SecondDomainObject.java
rename to json/src/test/java/org/apache/james/dto/SecondDomainObject.java
index 5c20fc8..69fdd08 100644
--- a/json/src/test/java/org/apache/dto/SecondDomainObject.java
+++ b/json/src/test/java/org/apache/james/dto/SecondDomainObject.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import java.util.Objects;
 import java.util.Optional;
diff --git a/json/src/test/java/org/apache/dto/SecondNestedDTO.java b/json/src/test/java/org/apache/james/dto/SecondNestedDTO.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/SecondNestedDTO.java
rename to json/src/test/java/org/apache/james/dto/SecondNestedDTO.java
index 9b86497..dd5e77b 100644
--- a/json/src/test/java/org/apache/dto/SecondNestedDTO.java
+++ b/json/src/test/java/org/apache/james/dto/SecondNestedDTO.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import org.apache.james.json.DTO;
 
diff --git a/json/src/test/java/org/apache/dto/SecondNestedType.java b/json/src/test/java/org/apache/james/dto/SecondNestedType.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/SecondNestedType.java
rename to json/src/test/java/org/apache/james/dto/SecondNestedType.java
index 0bbbf2f..913e2fe 100644
--- a/json/src/test/java/org/apache/dto/SecondNestedType.java
+++ b/json/src/test/java/org/apache/james/dto/SecondNestedType.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import java.util.Objects;
 
diff --git a/json/src/test/java/org/apache/dto/TestModule.java b/json/src/test/java/org/apache/james/dto/TestModule.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/TestModule.java
rename to json/src/test/java/org/apache/james/dto/TestModule.java
index ef81042..16374bd 100644
--- a/json/src/test/java/org/apache/dto/TestModule.java
+++ b/json/src/test/java/org/apache/james/dto/TestModule.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import org.apache.james.json.DTO;
 import org.apache.james.json.DTOModule;
diff --git a/json/src/test/java/org/apache/dto/TestModules.java b/json/src/test/java/org/apache/james/dto/TestModules.java
similarity index 99%
rename from json/src/test/java/org/apache/dto/TestModules.java
rename to json/src/test/java/org/apache/james/dto/TestModules.java
index a8de0b3..88dbf79 100644
--- a/json/src/test/java/org/apache/dto/TestModules.java
+++ b/json/src/test/java/org/apache/james/dto/TestModules.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import org.apache.james.json.DTO;
 import org.apache.james.json.DTOConverter;
diff --git a/json/src/test/java/org/apache/dto/TestNestedModule.java b/json/src/test/java/org/apache/james/dto/TestNestedModule.java
similarity index 98%
rename from json/src/test/java/org/apache/dto/TestNestedModule.java
rename to json/src/test/java/org/apache/james/dto/TestNestedModule.java
index e67df12..e528159 100644
--- a/json/src/test/java/org/apache/dto/TestNestedModule.java
+++ b/json/src/test/java/org/apache/james/dto/TestNestedModule.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.dto;
+package org.apache.james.dto;
 
 import org.apache.james.json.DTO;
 import org.apache.james.json.DTOModule;


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


[james-project] 02/24: JAMES-2993 Provide a JsonSerializationVerifier

Posted by bt...@apache.org.
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 774e96cadd4c5b3ad05db0b7561b976f31a6703f
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Mon Dec 16 18:16:52 2019 +0700

    JAMES-2993 Provide a JsonSerializationVerifier
---
 .../apache/james/JsonGenericSerializerTest.java    | 30 ++++------
 .../apache/james/JsonSerializationVerifier.java    | 69 ++++++++++++++++++++++
 .../james/JsonSerializationVerifierTest.java       | 54 +++++++++++++++++
 .../org/apache/james/SerializationFixture.java     | 47 +++++++++++++++
 .../java/org/apache/james/dto/TestModules.java     |  2 +-
 5 files changed, 181 insertions(+), 21 deletions(-)

diff --git a/json/src/test/java/org/apache/james/JsonGenericSerializerTest.java b/json/src/test/java/org/apache/james/JsonGenericSerializerTest.java
index 6b179ba..14e528a 100644
--- a/json/src/test/java/org/apache/james/JsonGenericSerializerTest.java
+++ b/json/src/test/java/org/apache/james/JsonGenericSerializerTest.java
@@ -20,20 +20,22 @@
 package org.apache.james;
 
 import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
+import static org.apache.james.SerializationFixture.DUPLICATE_TYPE_JSON;
+import static org.apache.james.SerializationFixture.FIRST;
+import static org.apache.james.SerializationFixture.FIRST_JSON;
+import static org.apache.james.SerializationFixture.FIRST_JSON_WITH_NESTED;
+import static org.apache.james.SerializationFixture.FIRST_WITH_NESTED;
+import static org.apache.james.SerializationFixture.MISSING_TYPE_JSON;
+import static org.apache.james.SerializationFixture.SECOND;
+import static org.apache.james.SerializationFixture.SECOND_JSON;
+import static org.apache.james.SerializationFixture.SECOND_WITH_NESTED;
+import static org.apache.james.SerializationFixture.SECOND_WITH_NESTED_JSON;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
-import java.time.ZonedDateTime;
-import java.util.Optional;
-import java.util.UUID;
 import java.util.stream.Stream;
 
 import org.apache.james.dto.BaseType;
-import org.apache.james.dto.FirstDomainObject;
-import org.apache.james.dto.FirstNestedType;
-import org.apache.james.dto.NestedType;
-import org.apache.james.dto.SecondDomainObject;
-import org.apache.james.dto.SecondNestedType;
 import org.apache.james.dto.TestModules;
 import org.apache.james.json.DTO;
 import org.apache.james.json.JsonGenericSerializer;
@@ -43,18 +45,6 @@ import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.MethodSource;
 
 class JsonGenericSerializerTest {
-    private static final Optional<NestedType> NO_CHILD = Optional.empty();
-    private static final BaseType FIRST = new FirstDomainObject(Optional.of(1L), ZonedDateTime.parse("2016-04-03T02:01+07:00[Asia/Vientiane]"), "first payload", NO_CHILD);
-    private static final BaseType SECOND = new SecondDomainObject(UUID.fromString("4a2c853f-7ffc-4ce3-9410-a47e85b3b741"), "second payload", NO_CHILD);
-    private static final BaseType SECOND_WITH_NESTED = new SecondDomainObject(UUID.fromString("4a2c853f-7ffc-4ce3-9410-a47e85b3b741"), "second payload", Optional.of(new FirstNestedType(12)));
-    private static final BaseType FIRST_WITH_NESTED = new FirstDomainObject(Optional.of(1L), ZonedDateTime.parse("2016-04-03T02:01+07:00[Asia/Vientiane]"), "payload", Optional.of(new SecondNestedType("bar")));
-
-    private static final String MISSING_TYPE_JSON = "{\"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
-    private static final String DUPLICATE_TYPE_JSON = "{\"type\":\"first\", \"type\":\"second\", \"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
-    private static final String FIRST_JSON = "{\"type\":\"first\",\"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
-    private static final String FIRST_JSON_WITH_NESTED = "{\"type\":\"first\",\"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"payload\", \"child\": {\"bar\": \"bar\", \"type\": \"second-nested\"}}";
-    private static final String SECOND_JSON = "{\"type\":\"second\",\"id\":\"4a2c853f-7ffc-4ce3-9410-a47e85b3b741\",\"payload\":\"second payload\"}";
-    private static final String SECOND_WITH_NESTED_JSON = "{\"type\":\"second\",\"id\":\"4a2c853f-7ffc-4ce3-9410-a47e85b3b741\",\"payload\":\"second payload\", \"child\": {\"foo\": 12, \"type\": \"first-nested\"}}";
 
     @Test
     void shouldDeserializeKnownType() throws Exception {
diff --git a/json/src/test/java/org/apache/james/JsonSerializationVerifier.java b/json/src/test/java/org/apache/james/JsonSerializationVerifier.java
new file mode 100644
index 0000000..31eee87
--- /dev/null
+++ b/json/src/test/java/org/apache/james/JsonSerializationVerifier.java
@@ -0,0 +1,69 @@
+/****************************************************************
+ * 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;
+
+import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+
+import org.apache.james.json.DTO;
+import org.apache.james.json.DTOModule;
+import org.apache.james.json.JsonGenericSerializer;
+
+public class JsonSerializationVerifier<T, U extends DTO> {
+    @FunctionalInterface
+    public interface RequireBean<T, U extends DTO> {
+        RequireJson<T, U> bean(T bean);
+    }
+
+    @FunctionalInterface
+    public interface RequireJson<T, U extends DTO> {
+        JsonSerializationVerifier<T, U> json(String json);
+    }
+
+    public static <T, U extends DTO> RequireBean<T, U> dtoModule(DTOModule<T, U> dtoModule) {
+        return bean -> json -> new JsonSerializationVerifier<>(dtoModule, json, bean);
+    }
+
+    private final DTOModule<T, U> dtoModule;
+    private final String json;
+    private final T bean;
+
+    private JsonSerializationVerifier(DTOModule<T, U> dtoModule, String json, T bean) {
+        this.dtoModule = dtoModule;
+        this.json = json;
+        this.bean = bean;
+    }
+
+    public void verify() throws IOException {
+        JsonGenericSerializer<T, U> seriliazer = JsonGenericSerializer
+            .forModules(dtoModule)
+            .withoutNestedType();
+
+        assertThatJson(seriliazer.serialize(bean))
+            .describedAs("Serialization test")
+            .isEqualTo(json);
+
+        assertThat(seriliazer.deserialize(json))
+            .describedAs("Deserialization test")
+            .isEqualTo(bean);
+    }
+}
diff --git a/json/src/test/java/org/apache/james/JsonSerializationVerifierTest.java b/json/src/test/java/org/apache/james/JsonSerializationVerifierTest.java
new file mode 100644
index 0000000..4758ab8
--- /dev/null
+++ b/json/src/test/java/org/apache/james/JsonSerializationVerifierTest.java
@@ -0,0 +1,54 @@
+/****************************************************************
+ * 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;
+
+import static org.apache.james.SerializationFixture.FIRST;
+import static org.apache.james.SerializationFixture.FIRST_JSON;
+import static org.apache.james.SerializationFixture.FIRST_JSON_BAD;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.apache.james.dto.TestModules;
+import org.junit.jupiter.api.Test;
+import org.opentest4j.AssertionFailedError;
+
+class JsonSerializationVerifierTest {
+    @Test
+    void verifyShouldNotThrowWhenValid() {
+        assertThatCode(() ->
+            JsonSerializationVerifier.dtoModule(TestModules.FIRST_TYPE)
+                .bean(FIRST)
+                .json(FIRST_JSON)
+                .verify())
+            .doesNotThrowAnyException();
+    }
+
+    @Test
+    void verifyShouldThrowOnUnexpectedJson() {
+        assertThatThrownBy(() ->
+            JsonSerializationVerifier.dtoModule(TestModules.FIRST_TYPE)
+                .bean(FIRST)
+                .json(FIRST_JSON_BAD)
+                .verify())
+            .isInstanceOf(AssertionFailedError.class)
+            .hasMessageContaining("[Serialization test] JSON documents are different:\n" +
+                "Different value found in node \"id\"");
+    }
+}
diff --git a/json/src/test/java/org/apache/james/SerializationFixture.java b/json/src/test/java/org/apache/james/SerializationFixture.java
new file mode 100644
index 0000000..0a8eff0
--- /dev/null
+++ b/json/src/test/java/org/apache/james/SerializationFixture.java
@@ -0,0 +1,47 @@
+/****************************************************************
+ * 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;
+
+import java.time.ZonedDateTime;
+import java.util.Optional;
+import java.util.UUID;
+
+import org.apache.james.dto.BaseType;
+import org.apache.james.dto.FirstDomainObject;
+import org.apache.james.dto.FirstNestedType;
+import org.apache.james.dto.NestedType;
+import org.apache.james.dto.SecondDomainObject;
+import org.apache.james.dto.SecondNestedType;
+
+public interface SerializationFixture {
+    Optional<NestedType> NO_CHILD = Optional.empty();
+    FirstDomainObject FIRST = new FirstDomainObject(Optional.of(1L), ZonedDateTime.parse("2016-04-03T02:01+07:00[Asia/Vientiane]"), "first payload", NO_CHILD);
+    BaseType SECOND = new SecondDomainObject(UUID.fromString("4a2c853f-7ffc-4ce3-9410-a47e85b3b741"), "second payload", NO_CHILD);
+    BaseType SECOND_WITH_NESTED = new SecondDomainObject(UUID.fromString("4a2c853f-7ffc-4ce3-9410-a47e85b3b741"), "second payload", Optional.of(new FirstNestedType(12)));
+    BaseType FIRST_WITH_NESTED = new FirstDomainObject(Optional.of(1L), ZonedDateTime.parse("2016-04-03T02:01+07:00[Asia/Vientiane]"), "payload", Optional.of(new SecondNestedType("bar")));
+
+    String MISSING_TYPE_JSON = "{\"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
+    String DUPLICATE_TYPE_JSON = "{\"type\":\"first\", \"type\":\"second\", \"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
+    String FIRST_JSON = "{\"type\":\"first\",\"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
+    String FIRST_JSON_BAD = "{\"type\":\"first\",\"id\":2,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"first payload\"}";
+    String FIRST_JSON_WITH_NESTED = "{\"type\":\"first\",\"id\":1,\"time\":\"2016-04-03T02:01+07:00[Asia/Vientiane]\",\"payload\":\"payload\", \"child\": {\"bar\": \"bar\", \"type\": \"second-nested\"}}";
+    String SECOND_JSON = "{\"type\":\"second\",\"id\":\"4a2c853f-7ffc-4ce3-9410-a47e85b3b741\",\"payload\":\"second payload\"}";
+    String SECOND_WITH_NESTED_JSON = "{\"type\":\"second\",\"id\":\"4a2c853f-7ffc-4ce3-9410-a47e85b3b741\",\"payload\":\"second payload\", \"child\": {\"foo\": 12, \"type\": \"first-nested\"}}";
+}
diff --git a/json/src/test/java/org/apache/james/dto/TestModules.java b/json/src/test/java/org/apache/james/dto/TestModules.java
index 88dbf79..802573b 100644
--- a/json/src/test/java/org/apache/james/dto/TestModules.java
+++ b/json/src/test/java/org/apache/james/dto/TestModules.java
@@ -46,7 +46,7 @@ public interface TestModules {
 
     DTOConverter<NestedType, DTO> NESTED_CONVERTERS = DTOConverter.of(FIRST_NESTED, SECOND_NESTED);
 
-    TestModule<?, ?> FIRST_TYPE = DTOModule
+    TestModule<FirstDomainObject, FirstDTO> FIRST_TYPE = DTOModule
         .forDomainObject(FirstDomainObject.class)
         .convertToDTO(FirstDTO.class)
         .toDomainObjectConverter(dto -> dto.toDomainObject(NESTED_CONVERTERS))


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


[james-project] 03/24: JAMES-2993 Demonstrate JsonSerializationVerifier in DeletedMessagesVaultDeleteTaskSerializationTest

Posted by bt...@apache.org.
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 6a583a3de82daa63e821408b90a60a30714cbd34
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Mon Dec 16 18:17:42 2019 +0700

    JAMES-2993 Demonstrate JsonSerializationVerifier in DeletedMessagesVaultDeleteTaskSerializationTest
---
 pom.xml                                            |  6 +++
 .../webadmin-mailbox-deleted-message-vault/pom.xml |  6 +++
 .../routes/DeletedMessagesVaultDeleteTask.java     | 33 +++++++++++++
 ...edMessagesVaultDeleteTaskSerializationTest.java | 54 ++++++----------------
 4 files changed, 59 insertions(+), 40 deletions(-)

diff --git a/pom.xml b/pom.xml
index e674629..11464b0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1239,6 +1239,12 @@
             </dependency>
             <dependency>
                 <groupId>${james.groupId}</groupId>
+                <artifactId>james-json</artifactId>
+                <version>${project.version}</version>
+                <type>test-jar</type>
+            </dependency>
+            <dependency>
+                <groupId>${james.groupId}</groupId>
                 <artifactId>james-server-blob</artifactId>
                 <version>${project.version}</version>
             </dependency>
diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/pom.xml b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/pom.xml
index 2faf6dd..c2fc74e 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/pom.xml
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/pom.xml
@@ -84,6 +84,12 @@
         </dependency>
         <dependency>
             <groupId>${james.groupId}</groupId>
+            <artifactId>james-json</artifactId>
+            <scope>test</scope>
+            <type>test-jar</type>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
             <artifactId>james-server-data-api</artifactId>
         </dependency>
         <dependency>
diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTask.java b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTask.java
index 3b732d3..232cf89 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTask.java
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTask.java
@@ -21,6 +21,7 @@ package org.apache.james.webadmin.vault.routes;
 
 import java.time.Clock;
 import java.time.Instant;
+import java.util.Objects;
 import java.util.Optional;
 
 import javax.inject.Inject;
@@ -80,6 +81,23 @@ public class DeletedMessagesVaultDeleteTask implements Task {
         public Instant timestamp() {
             return timestamp;
         }
+
+        @Override
+        public final boolean equals(Object o) {
+            if (o instanceof AdditionalInformation) {
+                AdditionalInformation that = (AdditionalInformation) o;
+
+                return Objects.equals(this.username, that.username)
+                    && Objects.equals(this.deleteMessageId, that.deleteMessageId)
+                    && Objects.equals(this.timestamp, that.timestamp);
+            }
+            return false;
+        }
+
+        @Override
+        public final int hashCode() {
+            return Objects.hash(username, deleteMessageId, timestamp);
+        }
     }
 
     private final DeletedMessageVault vault;
@@ -119,4 +137,19 @@ public class DeletedMessagesVaultDeleteTask implements Task {
         return Optional.of(new AdditionalInformation(username, messageId, Clock.systemUTC().instant()));
     }
 
+    @Override
+    public final boolean equals(Object o) {
+        if (o instanceof DeletedMessagesVaultDeleteTask) {
+            DeletedMessagesVaultDeleteTask that = (DeletedMessagesVaultDeleteTask) o;
+
+            return Objects.equals(this.username, that.username)
+                && Objects.equals(this.messageId, that.messageId);
+        }
+        return false;
+    }
+
+    @Override
+    public final int hashCode() {
+        return Objects.hash(username, messageId);
+    }
 }
diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTaskSerializationTest.java b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTaskSerializationTest.java
index 38277cc..0b85ce6 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTaskSerializationTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultDeleteTaskSerializationTest.java
@@ -18,75 +18,49 @@
  ****************************************************************/
 package org.apache.james.webadmin.vault.routes;
 
-import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
-import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
 
-import java.io.IOException;
 import java.time.Instant;
 
+import org.apache.james.JsonSerializationVerifier;
 import org.apache.james.core.Username;
 import org.apache.james.mailbox.model.MessageId;
 import org.apache.james.mailbox.model.TestMessageId;
-import org.apache.james.server.task.json.JsonTaskAdditionalInformationSerializer;
-import org.apache.james.server.task.json.JsonTaskSerializer;
 import org.apache.james.vault.DeletedMessageVault;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-import com.fasterxml.jackson.core.JsonProcessingException;
-
 class DeletedMessagesVaultDeleteTaskSerializationTest {
-
     private static final Instant TIMESTAMP = Instant.parse("2018-11-13T12:00:55Z");
 
-    private DeletedMessageVault deletedMessageVault;
-    private JsonTaskSerializer taskSerializer;
     private final Username username = Username.of("james");
-
     private final TestMessageId.Factory messageIdFactory = new TestMessageId.Factory();
     private final MessageId messageId = messageIdFactory.generate();
-
     private final String serializedDeleteMessagesVaultDeleteTask = "{\"type\": \"deleted-messages-delete\", \"userName\":\"james\", \"messageId\": \"" + messageId.serialize() + "\"}";
     private final String serializedAdditionalInformation = "{\"type\": \"deleted-messages-delete\", \"userName\":\"james\", \"messageId\": \"" + messageId.serialize() + "\", \"timestamp\":\"2018-11-13T12:00:55Z\"}";
 
-    private JsonTaskAdditionalInformationSerializer jsonAdditionalInformationSerializer;
+    private DeletedMessagesVaultDeleteTask.Factory factory;
+    private DeletedMessageVault deletedMessageVault;
 
     @BeforeEach
     void setUp() {
         deletedMessageVault = mock(DeletedMessageVault.class);
-        DeletedMessagesVaultDeleteTask.Factory factory = new DeletedMessagesVaultDeleteTask.Factory(deletedMessageVault, messageIdFactory);
-        taskSerializer = JsonTaskSerializer.of(DeletedMessagesVaultDeleteTaskDTO.module(factory));
-        jsonAdditionalInformationSerializer = JsonTaskAdditionalInformationSerializer.of(DeletedMessagesVaultDeleteTaskAdditionalInformationDTO.serializationModule(messageIdFactory));
+        factory = new DeletedMessagesVaultDeleteTask.Factory(deletedMessageVault, messageIdFactory);
     }
 
     @Test
-    void deleteMessagesVaultDeleteTaskShouldBeSerializable() throws JsonProcessingException {
-        DeletedMessagesVaultDeleteTask task = new DeletedMessagesVaultDeleteTask(deletedMessageVault, username, messageId);
-
-        assertThatJson(taskSerializer.serialize(task))
-            .isEqualTo(serializedDeleteMessagesVaultDeleteTask);
-    }
-
-    @Test
-    void deleteMessagesVaultDeleteTaskShouldBeDeserializable() throws IOException {
-        DeletedMessagesVaultDeleteTask task = new DeletedMessagesVaultDeleteTask(deletedMessageVault, username, messageId);
-
-        assertThat(taskSerializer.deserialize(serializedDeleteMessagesVaultDeleteTask))
-            .isEqualToComparingOnlyGivenFields(task, "username", "messageId");
-    }
-
-
-    @Test
-    void additionalInformationShouldBeSerializable() throws JsonProcessingException {
-        DeletedMessagesVaultDeleteTask.AdditionalInformation details = new DeletedMessagesVaultDeleteTask.AdditionalInformation(username, messageId, TIMESTAMP);
-        assertThatJson(jsonAdditionalInformationSerializer.serialize(details)).isEqualTo(serializedAdditionalInformation);
+    void deleteMessagesVaultDeleteTaskShouldBeSerializable() throws Exception {
+        JsonSerializationVerifier.dtoModule(DeletedMessagesVaultDeleteTaskDTO.module(factory))
+            .bean(new DeletedMessagesVaultDeleteTask(deletedMessageVault, username, messageId))
+            .json(serializedDeleteMessagesVaultDeleteTask)
+            .verify();
     }
 
     @Test
-    void additonalInformationShouldBeDeserializable() throws IOException {
-        DeletedMessagesVaultDeleteTask.AdditionalInformation details = new DeletedMessagesVaultDeleteTask.AdditionalInformation(username, messageId, TIMESTAMP);
-        assertThat(jsonAdditionalInformationSerializer.deserialize(serializedAdditionalInformation))
-            .isEqualToComparingFieldByField(details);
+    void additionalInformationShouldBeSerializable() throws Exception {
+        JsonSerializationVerifier.dtoModule(DeletedMessagesVaultDeleteTaskAdditionalInformationDTO.serializationModule(messageIdFactory))
+            .bean(new DeletedMessagesVaultDeleteTask.AdditionalInformation(username, messageId, TIMESTAMP))
+            .json(serializedAdditionalInformation)
+            .verify();
     }
 }
\ No newline at end of file


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


[james-project] 13/24: JAMES-3006 Use Task factory in reindexing routes

Posted by bt...@apache.org.
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 93a560d58f20dabef4c9a2876d4520e53f45fd93
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:14:28 2019 +0100

    JAMES-3006 Use Task factory in reindexing routes
---
 .../webadmin/routes/MessageIdReindexingRoutes.java | 28 +++----
 .../webadmin/routes/ReIndexingRoutesUtil.java      | 38 ----------
 .../james/webadmin/routes/ReindexingRoutes.java    | 87 ++++++++++++----------
 .../webadmin/routes/ReindexingRoutesTest.java      | 39 ++++++----
 4 files changed, 86 insertions(+), 106 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java
index d98206f..bc28e9a 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java
@@ -19,6 +19,8 @@
 
 package org.apache.james.webadmin.routes;
 
+import static org.apache.james.webadmin.routes.ReindexingRoutes.TASK_PARAMETER;
+
 import javax.inject.Inject;
 import javax.ws.rs.POST;
 import javax.ws.rs.Path;
@@ -26,17 +28,14 @@ import javax.ws.rs.Produces;
 
 import org.apache.james.mailbox.indexer.MessageIdReIndexer;
 import org.apache.james.mailbox.model.MessageId;
-import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.dto.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.JsonTransformer;
 import org.eclipse.jetty.http.HttpStatus;
 
-import com.github.fge.lambdas.supplier.ThrowingSupplier;
-
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
@@ -44,7 +43,7 @@ import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
 import spark.Request;
-import spark.Response;
+import spark.Route;
 import spark.Service;
 
 @Api(tags = "MessageIdReIndexing")
@@ -75,7 +74,7 @@ public class MessageIdReindexingRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        service.post(MESSAGE_PATH, this::reIndexMessage, jsonTransformer);
+        service.post(MESSAGE_PATH, reIndexMessage(), jsonTransformer);
     }
 
     @POST
@@ -103,8 +102,11 @@ public class MessageIdReindexingRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side."),
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - details in the returned error message")
     })
-    private TaskIdDto reIndexMessage(Request request, Response response) {
-        return wrap(request, response, () -> reIndexer.reIndex(extractMessageId(request)));
+    private Route reIndexMessage() {
+        return TaskFactory.builder()
+            .parameterName(TASK_PARAMETER)
+            .register(ReindexingRoutes.RE_INDEX, request -> reIndexer.reIndex(extractMessageId(request)))
+            .buildAsRoute(taskManager);
     }
 
     private MessageId extractMessageId(Request request) {
@@ -119,12 +121,4 @@ public class MessageIdReindexingRoutes implements Routes {
                 .haltError();
         }
     }
-
-    private TaskIdDto wrap(Request request, Response response, ThrowingSupplier<Task> taskGenerator) {
-        ReIndexingRoutesUtil.enforceTaskParameter(request);
-
-        Task task = taskGenerator.get();
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
-    }
 }
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReIndexingRoutesUtil.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReIndexingRoutesUtil.java
deleted file mode 100644
index c82f055..0000000
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReIndexingRoutesUtil.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/****************************************************************
- * 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.webadmin.routes;
-
-import org.apache.james.webadmin.utils.ErrorResponder;
-import org.eclipse.jetty.http.HttpStatus;
-
-import spark.Request;
-
-class ReIndexingRoutesUtil {
-    static void enforceTaskParameter(Request request) {
-        String task = request.queryParams("task");
-        if (!"reIndex".equals(task)) {
-            throw ErrorResponder.builder()
-                .statusCode(HttpStatus.BAD_REQUEST_400)
-                .type(ErrorResponder.ErrorType.INVALID_ARGUMENT)
-                .message("task query parameter is mandatory. The only supported value is `reIndex`")
-                .haltError();
-        }
-    }
-}
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java
index d838339..75f0cdd 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java
@@ -36,8 +36,11 @@ import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.task.TaskNotFoundException;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.dto.TaskIdDto;
 import org.apache.james.webadmin.service.PreviousReIndexingService;
+import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.JsonTransformer;
 import org.eclipse.jetty.http.HttpStatus;
@@ -50,18 +53,16 @@ import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
+import spark.HaltException;
 import spark.Request;
-import spark.Response;
+import spark.Route;
 import spark.Service;
 
 @Api(tags = "ReIndexing (mailboxes)")
 @Path("/mailboxes")
 @Produces("application/json")
 public class ReindexingRoutes implements Routes {
-    @FunctionalInterface
-    interface TaskGenerator {
-        Task generate() throws MailboxException;
-    }
+
 
     private static final String BASE_PATH = "/mailboxes";
     private static final String USER_QUERY_PARAM = "user";
@@ -70,6 +71,8 @@ public class ReindexingRoutes implements Routes {
     private static final String UID_PARAM = ":uid";
     private static final String MAILBOX_PATH = BASE_PATH + "/" + MAILBOX_PARAM;
     private static final String MESSAGE_PATH = MAILBOX_PATH + "/mails/" + UID_PARAM;
+    static final TaskRegistrationKey RE_INDEX = TaskRegistrationKey.of("reIndex");
+    static final String TASK_PARAMETER = "task";
 
     private final TaskManager taskManager;
     private final PreviousReIndexingService previousReIndexingService;
@@ -93,9 +96,9 @@ public class ReindexingRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        service.post(BASE_PATH, this::reIndexAll, jsonTransformer);
-        service.post(MAILBOX_PATH, this::reIndexMailbox, jsonTransformer);
-        service.post(MESSAGE_PATH, this::reIndexMessage, jsonTransformer);
+        service.post(BASE_PATH, reIndexAll(), jsonTransformer);
+        service.post(MAILBOX_PATH, reIndexMailbox(), jsonTransformer);
+        service.post(MESSAGE_PATH, reIndexMessage(), jsonTransformer);
     }
 
     @POST
@@ -131,20 +134,27 @@ public class ReindexingRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side."),
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - details in the returned error message")
     })
-    private TaskIdDto reIndexAll(Request request, Response response) {
+    private Route reIndexAll() {
+        return TaskFactory.builder()
+            .parameterName(TASK_PARAMETER)
+            .register(RE_INDEX, wrap(this::reIndexAll))
+            .buildAsRoute(taskManager);
+    }
+
+    private Task reIndexAll(Request request) throws MailboxException {
         boolean userReIndexing = !Strings.isNullOrEmpty(request.queryParams(USER_QUERY_PARAM));
         boolean indexingCorrection = !Strings.isNullOrEmpty(request.queryParams(RE_INDEX_FAILED_MESSAGES_QUERY_PARAM));
         if (userReIndexing && indexingCorrection) {
-            return rejectInvalidQueryParameterCombination();
+            throw rejectInvalidQueryParameterCombination();
         }
         if (userReIndexing) {
-            return wrap(request, response, () -> reIndexer.reIndex(extractUser(request)));
+            return reIndexer.reIndex(extractUser(request));
         }
         if (indexingCorrection) {
             IndexingDetailInformation indexingDetailInformation = retrieveIndexingExecutionDetails(request);
-            return wrap(request, response, () -> reIndexer.reIndex(indexingDetailInformation.failures()));
+            return reIndexer.reIndex(indexingDetailInformation.failures());
         }
-        return wrap(request, response, reIndexer::reIndex);
+        return reIndexer.reIndex();
     }
 
     private IndexingDetailInformation retrieveIndexingExecutionDetails(Request request) {
@@ -182,8 +192,8 @@ public class ReindexingRoutes implements Routes {
         }
     }
 
-    private TaskIdDto rejectInvalidQueryParameterCombination() {
-        throw ErrorResponder.builder()
+    private HaltException rejectInvalidQueryParameterCombination() {
+        return ErrorResponder.builder()
             .statusCode(HttpStatus.BAD_REQUEST_400)
             .type(ErrorResponder.ErrorType.INVALID_ARGUMENT)
             .message("Can not specify '" + USER_QUERY_PARAM + "' and '" + RE_INDEX_FAILED_MESSAGES_QUERY_PARAM + "' query parameters at the same time")
@@ -223,9 +233,11 @@ public class ReindexingRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side."),
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - details in the returned error message")
     })
-    private TaskIdDto reIndexMailbox(Request request, Response response) {
-        return wrap(request, response,
-            () -> reIndexer.reIndex(extractMailboxId(request)));
+    private Route reIndexMailbox() {
+        return TaskFactory.builder()
+            .parameterName(TASK_PARAMETER)
+            .register(RE_INDEX, wrap(request -> reIndexer.reIndex(extractMailboxId(request))))
+            .buildAsRoute(taskManager);
     }
 
     @POST
@@ -263,27 +275,26 @@ public class ReindexingRoutes implements Routes {
             defaultValue = "none",
             value = "Compulsory. Needs to be a valid UID")
     })
-    private TaskIdDto reIndexMessage(Request request, Response response) {
-        return wrap(request, response,
-            () -> reIndexer.reIndex(extractMailboxId(request), extractUid(request)));
+    private Route reIndexMessage() {
+        return TaskFactory.builder()
+            .parameterName(TASK_PARAMETER)
+            .register(RE_INDEX, wrap(request -> reIndexer.reIndex(extractMailboxId(request), extractUid(request))))
+            .buildAsRoute(taskManager);
     }
 
-    private TaskIdDto wrap(Request request, Response response, TaskGenerator taskGenerator) {
-        ReIndexingRoutesUtil.enforceTaskParameter(request);
-        try {
-            Task task = taskGenerator.generate();
-            TaskId taskId = taskManager.submit(task);
-            return TaskIdDto.respond(response, taskId);
-        } catch (MailboxNotFoundException e) {
-            throw ErrorResponder.builder()
-                .statusCode(HttpStatus.NOT_FOUND_404)
-                .type(ErrorResponder.ErrorType.NOT_FOUND)
-                .message("mailbox not found")
-                .cause(e)
-                .haltError();
-        } catch (MailboxException e) {
-            throw new RuntimeException(e);
-        }
+    private TaskGenerator wrap(TaskGenerator toBeWrapped) {
+        return request -> {
+            try {
+                return toBeWrapped.generate(request);
+            } catch (MailboxNotFoundException e) {
+                throw ErrorResponder.builder()
+                    .statusCode(HttpStatus.NOT_FOUND_404)
+                    .type(ErrorResponder.ErrorType.NOT_FOUND)
+                    .message("mailbox not found")
+                    .cause(e)
+                    .haltError();
+            }
+        };
     }
 
     private Username extractUser(Request request) {
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java
index 6271909..f7b94e3 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ReindexingRoutesTest.java
@@ -130,7 +130,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("'task' query parameter is compulsory. Supported values are [reIndex]"));
             }
 
             @Test
@@ -141,7 +142,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
         }
 
@@ -286,7 +288,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("'task' query parameter is compulsory. Supported values are [reIndex]"));
             }
 
             @Test
@@ -300,7 +303,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -474,7 +478,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("'task' query parameter is compulsory. Supported values are [reIndex]"));
             }
 
             @Test
@@ -488,7 +493,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -662,7 +668,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("'task' query parameter is compulsory. Supported values are [reIndex]"));
             }
 
             @Test
@@ -676,7 +683,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -821,7 +829,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("'task' query parameter is compulsory. Supported values are [reIndex]"));
             }
 
             @Test
@@ -832,7 +841,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -961,7 +971,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("'task' query parameter is compulsory. Supported values are [reIndex]"));
             }
 
             @Test
@@ -1007,7 +1018,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("task query parameter is mandatory. The only supported value is `reIndex`"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
 
             @Test
@@ -1022,7 +1034,8 @@ class ReindexingRoutesTest {
                     .statusCode(HttpStatus.BAD_REQUEST_400)
                     .body("statusCode", is(400))
                     .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
-                    .body("message", is("TaskId bbdb69c9-082a-44b0-a85a-6e33e74287a5 does not exist"));
+                    .body("message", is("Invalid arguments supplied in the user request"))
+                    .body("details", is("Invalid value supplied for 'task': bad. Supported values are [reIndex]"));
             }
         }
 


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


[james-project] 22/24: JAMES-3006 s/TaskGenerator/TaskFromRequest

Posted by bt...@apache.org.
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 83a5b96a2ecf544b3dce777912f2f8c951894d7d
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 05:25:47 2019 +0100

    JAMES-3006 s/TaskGenerator/TaskFromRequest
---
 .../webadmin/routes/CassandraMappingsRoutes.java   |  4 +--
 .../routes/CassandraMailboxMergingRoutes.java      |  8 ++---
 .../webadmin/routes/CassandraMigrationRoutes.java  | 12 +++----
 .../{TaskGenerator.java => TaskFromRequest.java}   | 12 +++----
 ...skFactory.java => TaskFromRequestRegistry.java} | 38 +++++++++++-----------
 ...yTest.java => TaskFromRequestRegistryTest.java} | 38 +++++++++++-----------
 ...GeneratorTest.java => TaskFromRequestTest.java} |  6 ++--
 .../vault/routes/DeletedMessagesVaultRoutes.java   | 12 +++----
 .../webadmin/routes/EventDeadLettersRoutes.java    |  8 ++---
 .../webadmin/routes/MessageIdReindexingRoutes.java |  4 +--
 .../james/webadmin/routes/ReindexingRoutes.java    | 14 ++++----
 .../james/webadmin/routes/MailQueueRoutes.java     |  6 ++--
 .../webadmin/routes/MailRepositoriesRoutes.java    | 12 +++----
 13 files changed, 87 insertions(+), 87 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
index 5225f1c..9241953 100644
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
@@ -28,7 +28,7 @@ import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Constants;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.service.CassandraMappingsService;
-import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskFromRequestRegistry;
 import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -97,7 +97,7 @@ public class CassandraMappingsRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = ACTION_REQUEST_CAN_NOT_BE_DONE)
     })
     public Route performActionOnMappings() {
-        return TaskFactory.of(SOLVE_INCONSISTENCIES, request -> cassandraMappingsService.solveMappingsSourcesInconsistencies())
+        return TaskFromRequestRegistry.of(SOLVE_INCONSISTENCIES, request -> cassandraMappingsService.solveMappingsSourcesInconsistencies())
             .asRoute(taskManager);
     }
 }
diff --git a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java
index 38c37b5..17d660f 100644
--- a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java
@@ -32,8 +32,8 @@ import org.apache.james.task.Task;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.dto.MailboxMergingRequest;
-import org.apache.james.webadmin.dto.TaskIdDto;
-import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskFromRequest;
+import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.utils.JsonExtractException;
 import org.apache.james.webadmin.utils.JsonExtractor;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -84,8 +84,8 @@ public class CassandraMailboxMergingRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        TaskGenerator taskGenerator = this::mergeMailboxes;
-        service.post(BASE, taskGenerator.asRoute(taskManager), jsonTransformer);
+        TaskFromRequest taskFromRequest = this::mergeMailboxes;
+        service.post(BASE, taskFromRequest.asRoute(taskManager), jsonTransformer);
     }
 
     @POST
diff --git a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java
index ec1c2f7..a1beae7 100644
--- a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java
@@ -31,8 +31,8 @@ import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.dto.CassandraVersionRequest;
 import org.apache.james.webadmin.dto.CassandraVersionResponse;
-import org.apache.james.webadmin.dto.TaskIdDto;
-import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskFromRequest;
+import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.ErrorResponder.ErrorType;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -89,11 +89,11 @@ public class CassandraMigrationRoutes implements Routes {
 
         service.get(VERSION_BASE_LATEST, (request, response) -> getCassandraLatestVersion(), jsonTransformer);
 
-        TaskGenerator upgradeToVersionTaskGenerator = this::upgradeToVersion;
-        service.post(VERSION_UPGRADE_BASE, upgradeToVersionTaskGenerator.asRoute(taskManager), jsonTransformer);
+        TaskFromRequest upgradeToVersionTaskFromRequest = this::upgradeToVersion;
+        service.post(VERSION_UPGRADE_BASE, upgradeToVersionTaskFromRequest.asRoute(taskManager), jsonTransformer);
 
-        TaskGenerator upgradeToLatestTaskGenerator = request -> upgradeToLatest();
-        service.post(VERSION_UPGRADE_TO_LATEST_BASE, upgradeToLatestTaskGenerator.asRoute(taskManager), jsonTransformer);
+        TaskFromRequest upgradeToLatestTaskFromRequest = request -> upgradeToLatest();
+        service.post(VERSION_UPGRADE_TO_LATEST_BASE, upgradeToLatestTaskFromRequest.asRoute(taskManager), jsonTransformer);
     }
 
     @POST
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequest.java
similarity index 86%
rename from server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
rename to server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequest.java
index 913e742..f2560a7 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequest.java
@@ -31,19 +31,19 @@ import spark.Request;
 import spark.Response;
 import spark.Route;
 
-public interface TaskGenerator {
+public interface TaskFromRequest {
     class TaskRoute implements Route {
-        private final TaskGenerator taskGenerator;
+        private final TaskFromRequest taskFromRequest;
         private final TaskManager taskManager;
 
-        TaskRoute(TaskGenerator taskGenerator, TaskManager taskManager) {
-            this.taskGenerator = taskGenerator;
+        TaskRoute(TaskFromRequest taskFromRequest, TaskManager taskManager) {
+            this.taskFromRequest = taskFromRequest;
             this.taskManager = taskManager;
         }
 
         @Override
         public TaskIdDto handle(Request request, Response response) throws Exception {
-            Task task = taskGenerator.generate(request);
+            Task task = taskFromRequest.fromRequest(request);
             TaskId taskId = taskManager.submit(task);
             response.status(HttpStatus.CREATED_201);
             response.header(LOCATION.asString(), TasksRoutes.BASE + "/" + taskId.asString());
@@ -51,7 +51,7 @@ public interface TaskGenerator {
         }
     }
 
-    Task generate(Request request) throws Exception;
+    Task fromRequest(Request request) throws Exception;
 
     default Route asRoute(TaskManager taskManager) {
         return new TaskRoute(this, taskManager);
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistry.java
similarity index 78%
rename from server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
rename to server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistry.java
index dcacc2f..505e4f1 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistry.java
@@ -38,12 +38,12 @@ import com.google.common.collect.ImmutableMap;
 import spark.Request;
 import spark.Route;
 
-public class TaskFactory implements TaskGenerator {
+public class TaskFromRequestRegistry implements TaskFromRequest {
     private static final String DEFAULT_PARAMETER = "action";
 
     public static class Builder {
         private Optional<String> taskParameterName;
-        private ImmutableMap.Builder<TaskRegistrationKey, TaskGenerator> tasks;
+        private ImmutableMap.Builder<TaskRegistrationKey, TaskFromRequest> tasks;
 
         public Builder() {
             taskParameterName = Optional.empty();
@@ -63,15 +63,15 @@ public class TaskFactory implements TaskGenerator {
             return this;
         }
 
-        public Builder register(TaskRegistrationKey key, TaskGenerator taskGenerator) {
-            this.tasks.put(key, taskGenerator);
+        public Builder register(TaskRegistrationKey key, TaskFromRequest taskFromRequest) {
+            this.tasks.put(key, taskFromRequest);
             return this;
         }
 
-        public TaskFactory build() {
-            ImmutableMap<TaskRegistrationKey, TaskGenerator> registrations = tasks.build();
+        public TaskFromRequestRegistry build() {
+            ImmutableMap<TaskRegistrationKey, TaskFromRequest> registrations = tasks.build();
             Preconditions.checkState(!registrations.isEmpty());
-            return new TaskFactory(
+            return new TaskFromRequestRegistry(
                 taskParameterName.orElse(DEFAULT_PARAMETER),
                 registrations);
         }
@@ -81,13 +81,13 @@ public class TaskFactory implements TaskGenerator {
         }
     }
 
-    public static class TaskRegistration implements TaskGenerator {
+    public static class TaskRegistration implements TaskFromRequest {
         private final TaskRegistrationKey taskRegistrationKey;
-        private final TaskGenerator taskGenerator;
+        private final TaskFromRequest taskFromRequest;
 
-        public TaskRegistration(TaskRegistrationKey taskRegistrationKey, TaskGenerator taskGenerator) {
+        public TaskRegistration(TaskRegistrationKey taskRegistrationKey, TaskFromRequest taskFromRequest) {
             this.taskRegistrationKey = taskRegistrationKey;
-            this.taskGenerator = taskGenerator;
+            this.taskFromRequest = taskFromRequest;
         }
 
         public TaskRegistrationKey registrationKey() {
@@ -95,8 +95,8 @@ public class TaskFactory implements TaskGenerator {
         }
 
         @Override
-        public Task generate(Request request) throws Exception {
-            return taskGenerator.generate(request);
+        public Task fromRequest(Request request) throws Exception {
+            return taskFromRequest.fromRequest(request);
         }
     }
 
@@ -104,25 +104,25 @@ public class TaskFactory implements TaskGenerator {
         return new Builder();
     }
 
-    public static TaskFactory of(TaskRegistrationKey key, TaskGenerator generator) {
-        return TaskFactory.builder()
+    public static TaskFromRequestRegistry of(TaskRegistrationKey key, TaskFromRequest generator) {
+        return TaskFromRequestRegistry.builder()
             .register(key, generator)
             .build();
     }
 
     private final String taskParameterName;
-    private final Map<TaskRegistrationKey, TaskGenerator> taskGenerators;
+    private final Map<TaskRegistrationKey, TaskFromRequest> taskGenerators;
 
-    private TaskFactory(String taskParameterName, Map<TaskRegistrationKey, TaskGenerator> taskGenerators) {
+    private TaskFromRequestRegistry(String taskParameterName, Map<TaskRegistrationKey, TaskFromRequest> taskGenerators) {
         this.taskParameterName = taskParameterName;
         this.taskGenerators = taskGenerators;
     }
 
     @Override
-    public Task generate(Request request) throws Exception {
+    public Task fromRequest(Request request) throws Exception {
         TaskRegistrationKey registrationKey = parseRegistrationKey(request);
         return Optional.ofNullable(taskGenerators.get(registrationKey))
-            .map(Throwing.<TaskGenerator, Task>function(taskGenerator -> taskGenerator.generate(request)).sneakyThrow())
+            .map(Throwing.<TaskFromRequest, Task>function(taskGenerator -> taskGenerator.fromRequest(request)).sneakyThrow())
             .orElseThrow(() -> new IllegalArgumentException("Invalid value supplied for query parameter '" + taskParameterName + "': " + registrationKey.asString()
                 + ". " + supportedValueMessage()));
     }
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistryTest.java
similarity index 78%
rename from server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
rename to server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistryTest.java
index d4a7707..faaebe5 100644
--- a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestRegistryTest.java
@@ -30,70 +30,70 @@ import org.junit.jupiter.api.Test;
 
 import spark.Request;
 
-class TaskFactoryTest {
+class TaskFromRequestRegistryTest {
     static final Task TASK_1 = mock(Task.class);
     static final Task TASK_2 = mock(Task.class);
     static final TaskRegistrationKey KEY_1 = TaskRegistrationKey.of("task1");
     static final TaskRegistrationKey KEY_2 = TaskRegistrationKey.of("task2");
 
     Request request;
-    TaskFactory taskFactory;
-    TaskFactory singleTaskFactory;
+    TaskFromRequestRegistry taskFromRequestRegistry;
+    TaskFromRequestRegistry singleTaskFromRequestRegistry;
 
     @BeforeEach
     void setUp() {
         request = mock(Request.class);
-        taskFactory = TaskFactory.builder()
+        taskFromRequestRegistry = TaskFromRequestRegistry.builder()
             .register(KEY_1, any -> TASK_1)
             .register(KEY_2, any -> TASK_2)
             .build();
-        singleTaskFactory = TaskFactory.of(KEY_1, any -> TASK_1);
+        singleTaskFromRequestRegistry = TaskFromRequestRegistry.of(KEY_1, any -> TASK_1);
     }
 
     @Test
     void buildShouldThrowWhenNoTasks() {
-        assertThatThrownBy(() -> TaskFactory.builder().build())
+        assertThatThrownBy(() -> TaskFromRequestRegistry.builder().build())
             .isInstanceOf(IllegalStateException.class);
     }
 
     @Test
     void generateShouldThrowFormattedMessageWhenNoTaskParamAndSeveralOptions() {
-        assertThatThrownBy(() -> taskFactory.generate(request))
+        assertThatThrownBy(() -> taskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("'action' query parameter is compulsory. Supported values are [task1, task2]");
     }
 
     @Test
     void generateShouldThrowFormattedMessageWhenNoTaskParam() {
-        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+        assertThatThrownBy(() -> singleTaskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("'action' query parameter is compulsory. Supported values are [task1]");
     }
 
     @Test
     void generateShouldThrowWhenCustomParameterValueIsInvalid() {
-        TaskFactory taskFactory = TaskFactory.builder()
+        TaskFromRequestRegistry taskFromRequestRegistry = TaskFromRequestRegistry.builder()
             .parameterName("custom")
             .register(KEY_1, any -> TASK_1)
             .build();
 
         when(request.queryParams("custom")).thenReturn("unknown");
 
-        assertThatThrownBy(() -> taskFactory.generate(request))
+        assertThatThrownBy(() -> taskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("Invalid value supplied for query parameter 'custom': unknown. Supported values are [task1]");
     }
 
     @Test
     void generateShouldThrowWhenCustomParameterNotSpecified() {
-        TaskFactory taskFactory = TaskFactory.builder()
+        TaskFromRequestRegistry taskFromRequestRegistry = TaskFromRequestRegistry.builder()
             .parameterName("custom")
             .register(KEY_1, any -> TASK_1)
             .build();
 
         when(request.queryParams("action")).thenReturn("unknown");
 
-        assertThatThrownBy(() -> taskFactory.generate(request))
+        assertThatThrownBy(() -> taskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("'custom' query parameter is compulsory. Supported values are [task1]");
     }
@@ -102,7 +102,7 @@ class TaskFactoryTest {
     void generateShouldThrowFormattedMessageWhenUnknownTaskParamAndSeveralOptions() {
         when(request.queryParams("action")).thenReturn("unknown");
 
-        assertThatThrownBy(() -> taskFactory.generate(request))
+        assertThatThrownBy(() -> taskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("Invalid value supplied for query parameter 'action': unknown. Supported values are [task1, task2]");
     }
@@ -111,7 +111,7 @@ class TaskFactoryTest {
     void generateShouldThrowFormattedMessageWhenUnknownTaskParam() {
         when(request.queryParams("action")).thenReturn("unknown");
 
-        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+        assertThatThrownBy(() -> singleTaskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("Invalid value supplied for query parameter 'action': unknown. Supported values are [task1]");
     }
@@ -120,7 +120,7 @@ class TaskFactoryTest {
     void generateShouldThrowWhenEmptyTaskParam() {
         when(request.queryParams("action")).thenReturn("");
 
-        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+        assertThatThrownBy(() -> singleTaskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("'action' query parameter cannot be empty or blank. Supported values are [task1]");
     }
@@ -129,7 +129,7 @@ class TaskFactoryTest {
     void generateShouldThrowWhenBlankTaskParam() {
         when(request.queryParams("action")).thenReturn(" ");
 
-        assertThatThrownBy(() -> singleTaskFactory.generate(request))
+        assertThatThrownBy(() -> singleTaskFromRequestRegistry.fromRequest(request))
             .isInstanceOf(IllegalArgumentException.class)
             .hasMessage("'action' query parameter cannot be empty or blank. Supported values are [task1]");
     }
@@ -138,20 +138,20 @@ class TaskFactoryTest {
     void generateShouldCreateCorrespondingTask() throws Exception {
         when(request.queryParams("action")).thenReturn("task1");
 
-        assertThat(singleTaskFactory.generate(request))
+        assertThat(singleTaskFromRequestRegistry.fromRequest(request))
             .isSameAs(TASK_1);
     }
 
     @Test
     void generateShouldHandleCustomTaskParameter() throws Exception {
-        TaskFactory taskFactory = TaskFactory.builder()
+        TaskFromRequestRegistry taskFromRequestRegistry = TaskFromRequestRegistry.builder()
             .parameterName("custom")
             .register(KEY_1, any -> TASK_1)
             .build();
 
         when(request.queryParams("custom")).thenReturn("task1");
 
-        assertThat(taskFactory.generate(request))
+        assertThat(taskFromRequestRegistry.fromRequest(request))
             .isSameAs(TASK_1);
     }
 }
\ No newline at end of file
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskGeneratorTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestTest.java
similarity index 93%
rename from server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskGeneratorTest.java
rename to server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestTest.java
index a7995b8..4976a5a 100644
--- a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskGeneratorTest.java
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFromRequestTest.java
@@ -34,7 +34,7 @@ import org.junit.Test;
 import spark.Request;
 import spark.Response;
 
-public class TaskGeneratorTest {
+public class TaskFromRequestTest {
     static final Task TASK = mock(Task.class);
     static final String UUID_VALUE = "ce5316cb-c924-40eb-9ca0-c5828e276297";
 
@@ -43,11 +43,11 @@ public class TaskGeneratorTest {
         Request request = mock(Request.class);
         Response response = mock(Response.class);
 
-        TaskGenerator taskGenerator = any -> TASK;
+        TaskFromRequest taskFromRequest = any -> TASK;
         TaskManager taskManager = mock(TaskManager.class);
         when(taskManager.submit(TASK)).thenReturn(TaskId.fromString(UUID_VALUE));
 
-        taskGenerator.asRoute(taskManager).handle(request, response);
+        taskFromRequest.asRoute(taskManager).handle(request, response);
 
         verify(response).status(HttpStatus.CREATED_201);
         verify(response).header(LOCATION.asString(), "/tasks/" + UUID_VALUE);
diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java
index 0197c1d..e7c33a5 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java
@@ -44,8 +44,8 @@ import org.apache.james.vault.dto.query.QueryTranslator;
 import org.apache.james.vault.search.Query;
 import org.apache.james.webadmin.Constants;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.tasks.TaskFactory;
-import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskFromRequest;
+import org.apache.james.webadmin.tasks.TaskFromRequestRegistry;
 import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
@@ -120,8 +120,8 @@ public class DeletedMessagesVaultRoutes implements Routes {
         service.post(USER_PATH, userActions(), jsonTransformer);
         service.delete(ROOT_PATH, deleteWithScope(), jsonTransformer);
 
-        TaskGenerator deleteTaskGenerator = this::deleteMessage;
-        service.delete(DELETE_PATH, deleteTaskGenerator.asRoute(taskManager), jsonTransformer);
+        TaskFromRequest deleteTaskFromRequest = this::deleteMessage;
+        service.delete(DELETE_PATH, deleteTaskFromRequest.asRoute(taskManager), jsonTransformer);
     }
 
     @POST
@@ -159,7 +159,7 @@ public class DeletedMessagesVaultRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
     private Route userActions() {
-        return TaskFactory.builder()
+        return TaskFromRequestRegistry.builder()
             .register(EXPORT_REGISTRATION_KEY, this::export)
             .register(RESTORE_REGISTRATION_KEY, this::restore)
             .buildAsRoute(taskManager);
@@ -194,7 +194,7 @@ public class DeletedMessagesVaultRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
     private Route deleteWithScope() {
-        return TaskFactory.builder()
+        return TaskFromRequestRegistry.builder()
             .parameterName(SCOPE_QUERY_PARAM)
             .register(EXPIRED_REGISTRATION_KEY, request -> deletedMessageVault.deleteExpiredMessagesTask())
             .buildAsRoute(taskManager);
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
index cc1a9fe..601db57 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
@@ -35,7 +35,7 @@ import org.apache.james.mailbox.events.Group;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.service.EventDeadLettersService;
-import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskFromRequestRegistry;
 import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
@@ -118,7 +118,7 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
     public Route performActionOnAllEvents() {
-        return TaskFactory.of(RE_DELIVER, request -> eventDeadLettersService.redeliverAllEvents())
+        return TaskFromRequestRegistry.of(RE_DELIVER, request -> eventDeadLettersService.redeliverAllEvents())
             .asRoute(taskManager);
     }
 
@@ -184,7 +184,7 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
     public Route performActionOnGroupEvents() {
-        return TaskFactory.of(RE_DELIVER, request -> eventDeadLettersService.redeliverGroupEvents(parseGroup(request)))
+        return TaskFromRequestRegistry.of(RE_DELIVER, request -> eventDeadLettersService.redeliverGroupEvents(parseGroup(request)))
             .asRoute(taskManager);
     }
 
@@ -291,7 +291,7 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
     public Route performActionOnSingleEvent() {
-        return TaskFactory.of(RE_DELIVER,
+        return TaskFromRequestRegistry.of(RE_DELIVER,
                 request -> eventDeadLettersService.redeliverSingleEvent(parseGroup(request), parseInsertionId(request)))
             .asRoute(taskManager);
     }
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java
index bc28e9a..a283262 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/MessageIdReindexingRoutes.java
@@ -30,7 +30,7 @@ import org.apache.james.mailbox.indexer.MessageIdReIndexer;
 import org.apache.james.mailbox.model.MessageId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskFromRequestRegistry;
 import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -103,7 +103,7 @@ public class MessageIdReindexingRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - details in the returned error message")
     })
     private Route reIndexMessage() {
-        return TaskFactory.builder()
+        return TaskFromRequestRegistry.builder()
             .parameterName(TASK_PARAMETER)
             .register(ReindexingRoutes.RE_INDEX, request -> reIndexer.reIndex(extractMessageId(request)))
             .buildAsRoute(taskManager);
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java
index 75f0cdd..12dfcd6 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/ReindexingRoutes.java
@@ -37,8 +37,8 @@ import org.apache.james.task.TaskManager;
 import org.apache.james.task.TaskNotFoundException;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.service.PreviousReIndexingService;
-import org.apache.james.webadmin.tasks.TaskFactory;
-import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskFromRequest;
+import org.apache.james.webadmin.tasks.TaskFromRequestRegistry;
 import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
@@ -135,7 +135,7 @@ public class ReindexingRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - details in the returned error message")
     })
     private Route reIndexAll() {
-        return TaskFactory.builder()
+        return TaskFromRequestRegistry.builder()
             .parameterName(TASK_PARAMETER)
             .register(RE_INDEX, wrap(this::reIndexAll))
             .buildAsRoute(taskManager);
@@ -234,7 +234,7 @@ public class ReindexingRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - details in the returned error message")
     })
     private Route reIndexMailbox() {
-        return TaskFactory.builder()
+        return TaskFromRequestRegistry.builder()
             .parameterName(TASK_PARAMETER)
             .register(RE_INDEX, wrap(request -> reIndexer.reIndex(extractMailboxId(request))))
             .buildAsRoute(taskManager);
@@ -276,16 +276,16 @@ public class ReindexingRoutes implements Routes {
             value = "Compulsory. Needs to be a valid UID")
     })
     private Route reIndexMessage() {
-        return TaskFactory.builder()
+        return TaskFromRequestRegistry.builder()
             .parameterName(TASK_PARAMETER)
             .register(RE_INDEX, wrap(request -> reIndexer.reIndex(extractMailboxId(request), extractUid(request))))
             .buildAsRoute(taskManager);
     }
 
-    private TaskGenerator wrap(TaskGenerator toBeWrapped) {
+    private TaskFromRequest wrap(TaskFromRequest toBeWrapped) {
         return request -> {
             try {
-                return toBeWrapped.generate(request);
+                return toBeWrapped.fromRequest(request);
             } catch (MailboxNotFoundException e) {
                 throw ErrorResponder.builder()
                     .statusCode(HttpStatus.NOT_FOUND_404)
diff --git a/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java b/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java
index 05c5d51..335cd04 100644
--- a/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java
@@ -45,7 +45,7 @@ import org.apache.james.webadmin.dto.MailQueueDTO;
 import org.apache.james.webadmin.dto.MailQueueItemDTO;
 import org.apache.james.webadmin.service.ClearMailQueueTask;
 import org.apache.james.webadmin.service.DeleteMailsFromMailQueueTask;
-import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskFromRequest;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.ErrorResponder.ErrorType;
 import org.apache.james.webadmin.utils.JsonExtractException;
@@ -296,9 +296,9 @@ public class MailQueueRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
     public void deleteMails(Service service) {
-        TaskGenerator taskGenerator = this::deleteMails;
+        TaskFromRequest taskFromRequest = this::deleteMails;
         service.delete(BASE_URL + SEPARATOR + MAIL_QUEUE_NAME + MAILS,
-                taskGenerator.asRoute(taskManager),
+                taskFromRequest.asRoute(taskManager),
                 jsonTransformer);
     }
 
diff --git a/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java b/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
index 0b00416..f200a1d 100644
--- a/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
@@ -56,8 +56,8 @@ import org.apache.james.webadmin.service.MailRepositoryStoreService;
 import org.apache.james.webadmin.service.ReprocessingAllMailsTask;
 import org.apache.james.webadmin.service.ReprocessingOneMailTask;
 import org.apache.james.webadmin.service.ReprocessingService;
-import org.apache.james.webadmin.tasks.TaskFactory;
-import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskFromRequest;
+import org.apache.james.webadmin.tasks.TaskFromRequestRegistry;
 import org.apache.james.webadmin.tasks.TaskIdDto;
 import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
@@ -393,7 +393,7 @@ public class MailRepositoriesRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - unknown action")
     })
     public void defineDeleteAll() {
-        TaskGenerator taskGenerator = request -> {
+        TaskFromRequest taskFromRequest = request -> {
             MailRepositoryPath path = decodedRepositoryPath(request);
             try {
                 return repositoryStoreService.createClearMailRepositoryTask(path);
@@ -406,7 +406,7 @@ public class MailRepositoriesRoutes implements Routes {
                     .haltError();
             }
         };
-        service.delete(MAIL_REPOSITORIES + "/:encodedPath/mails", taskGenerator.asRoute(taskManager), jsonTransformer);
+        service.delete(MAIL_REPOSITORIES + "/:encodedPath/mails", taskFromRequest.asRoute(taskManager), jsonTransformer);
     }
 
     @PATCH
@@ -445,7 +445,7 @@ public class MailRepositoriesRoutes implements Routes {
     })
     public void defineReprocessAll() {
         service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails",
-            TaskFactory.of(REPROCESS_ACTION, this::reprocessAll)
+            TaskFromRequestRegistry.of(REPROCESS_ACTION, this::reprocessAll)
                 .asRoute(taskManager),
             jsonTransformer);
     }
@@ -495,7 +495,7 @@ public class MailRepositoriesRoutes implements Routes {
     })
     public void defineReprocessOne() {
         service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails/:key",
-            TaskFactory.of(REPROCESS_ACTION, this::reprocessOne)
+            TaskFromRequestRegistry.of(REPROCESS_ACTION, this::reprocessOne)
                 .asRoute(taskManager),
             jsonTransformer);
     }


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


[james-project] 08/24: [Refactoring] ContinuationResponse::data is always null

Posted by bt...@apache.org.
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 3ee393e4886812272affb78ed18396e38e609876
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 07:04:02 2019 +0100

    [Refactoring] ContinuationResponse::data is always null
---
 .../org/apache/james/imap/encode/ContinuationResponseEncoder.java | 2 +-
 .../apache/james/imap/message/response/ContinuationResponse.java  | 8 --------
 2 files changed, 1 insertion(+), 9 deletions(-)

diff --git a/protocols/imap/src/main/java/org/apache/james/imap/encode/ContinuationResponseEncoder.java b/protocols/imap/src/main/java/org/apache/james/imap/encode/ContinuationResponseEncoder.java
index 0fdbb2b..e93bd30 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/encode/ContinuationResponseEncoder.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/encode/ContinuationResponseEncoder.java
@@ -42,7 +42,7 @@ public class ContinuationResponseEncoder implements ImapResponseEncoder<Continua
 
     @Override
     public void encode(ContinuationResponse response, ImapResponseComposer composer) throws IOException {
-        String message = response.getData() != null ? response.getData() : asString(response.getTextKey());
+        String message = asString(response.getTextKey());
         composer.continuationResponse(message);
     }
 
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java
index 8215188..54d5397 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java
@@ -23,20 +23,12 @@ import org.apache.james.imap.api.display.HumanReadableText;
 import org.apache.james.imap.api.message.response.ImapResponseMessage;
 
 public class ContinuationResponse implements ImapResponseMessage {
-
-    private final String data;
-
     private final HumanReadableText textKey;
 
     public ContinuationResponse(HumanReadableText textKey) {
-        this.data = null;
         this.textKey = textKey;
     }
 
-    public String getData() {
-        return data;
-    }
-
     public HumanReadableText getTextKey() {
         return textKey;
     }


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


[james-project] 05/24: [Refactoring] SearchResponse: simplify & test equals & hashCode

Posted by bt...@apache.org.
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 f9c4e179b0b092895ec2e54ad31b5203733b83f3
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 06:56:48 2019 +0100

    [Refactoring] SearchResponse: simplify & test equals & hashCode
---
 .../imap/message/response/SearchResponse.java      | 33 ++++++++--------------
 .../imap/message/response/SearchResponseTest.java  | 32 +++++++++++++++++++++
 2 files changed, 43 insertions(+), 22 deletions(-)

diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/SearchResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/SearchResponse.java
index e11f8bb..422bf41 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/SearchResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/SearchResponse.java
@@ -20,6 +20,7 @@
 package org.apache.james.imap.message.response;
 
 import java.util.Arrays;
+import java.util.Objects;
 
 import org.apache.james.imap.api.message.response.ImapResponseMessage;
 import org.apache.james.mailbox.ModSeq;
@@ -35,10 +36,8 @@ public class SearchResponse implements ImapResponseMessage {
      * Constructs a <code>SEARCH</code> response.
      * 
      * @param ids ids, not null
-     * @param highestModSeq
      */
     public SearchResponse(long[] ids, ModSeq highestModSeq) {
-        super();
         this.ids = ids;
         this.highestModSeq = highestModSeq;
     }
@@ -63,29 +62,19 @@ public class SearchResponse implements ImapResponseMessage {
     }
 
     @Override
-    public int hashCode() {
-        return ids.length;
+    public final boolean equals(Object o) {
+        if (o instanceof SearchResponse) {
+            SearchResponse that = (SearchResponse) o;
+
+            return Arrays.equals(this.ids, that.ids)
+                && Objects.equals(this.highestModSeq, that.highestModSeq);
+        }
+        return false;
     }
 
     @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        final SearchResponse other = (SearchResponse) obj;
-        if (!Arrays.equals(ids, other.ids)) {
-            return false;
-        }
-        if (highestModSeq != other.highestModSeq) {
-            return false;
-        }
-        return true;
+    public final int hashCode() {
+        return Objects.hash(Arrays.hashCode(ids), highestModSeq);
     }
 
     /**
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/message/response/SearchResponseTest.java b/protocols/imap/src/test/java/org/apache/james/imap/message/response/SearchResponseTest.java
new file mode 100644
index 0000000..fb97581
--- /dev/null
+++ b/protocols/imap/src/test/java/org/apache/james/imap/message/response/SearchResponseTest.java
@@ -0,0 +1,32 @@
+/****************************************************************
+ * 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.imap.message.response;
+
+import org.junit.jupiter.api.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+
+class SearchResponseTest {
+    @Test
+    void shouldMatchBeanContract() {
+        EqualsVerifier.forClass(SearchResponse.class)
+            .verify();
+    }
+}
\ No newline at end of file


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


[james-project] 10/24: JAMES-3006 Use Task factory in dead-letter routes

Posted by bt...@apache.org.
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 dc69a933f2a335d045edf57c4c7084300910e85f
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:15:14 2019 +0100

    JAMES-3006 Use Task factory in dead-letter routes
---
 .../apache/james/webadmin/dto/ActionEvents.java    | 37 --------------
 .../webadmin/routes/EventDeadLettersRoutes.java    | 59 ++++++++--------------
 .../james/webadmin/dto/ActionEventsTest.java       | 50 ------------------
 .../routes/EventDeadLettersRoutesTest.java         | 12 ++---
 4 files changed, 27 insertions(+), 131 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/dto/ActionEvents.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/dto/ActionEvents.java
deleted file mode 100644
index 6861f51..0000000
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/dto/ActionEvents.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/****************************************************************
- * 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.webadmin.dto;
-
-import java.util.Optional;
-
-import com.google.common.base.Preconditions;
-
-public enum ActionEvents {
-    REDELIVER;
-
-    public static Optional<ActionEvents> find(String action) {
-        Preconditions.checkArgument(action != null, "'action' url parameter is mandatory");
-
-        if (action.equalsIgnoreCase(ActionEvents.REDELIVER.toString())) {
-            return Optional.of(ActionEvents.REDELIVER);
-        }
-        return Optional.empty();
-    }
-}
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
index 6f21a88..c877a50 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
@@ -20,7 +20,6 @@
 package org.apache.james.webadmin.routes;
 
 import java.util.List;
-import java.util.Optional;
 
 import javax.inject.Inject;
 import javax.ws.rs.DELETE;
@@ -33,13 +32,12 @@ import org.apache.james.event.json.EventSerializer;
 import org.apache.james.mailbox.events.Event;
 import org.apache.james.mailbox.events.EventDeadLetters;
 import org.apache.james.mailbox.events.Group;
-import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.dto.ActionEvents;
-import org.apache.james.webadmin.dto.TaskIdDto;
 import org.apache.james.webadmin.service.EventDeadLettersService;
+import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.JsonTransformer;
 import org.apache.james.webadmin.utils.Responses;
@@ -54,6 +52,7 @@ import io.swagger.annotations.ApiResponses;
 import io.swagger.annotations.ResponseHeader;
 import spark.Request;
 import spark.Response;
+import spark.Route;
 import spark.Service;
 
 @Api(tags = "EventDeadLetter")
@@ -65,6 +64,7 @@ public class EventDeadLettersRoutes implements Routes {
     private static final String INSERTION_ID_PARAMETER = ":insertionId";
 
     private static final String INTERNAL_SERVER_ERROR = "Internal server error - Something went bad on the server side.";
+    private static final TaskRegistrationKey RE_DELIVER = TaskRegistrationKey.of("reDeliver");
 
     private final EventDeadLettersService eventDeadLettersService;
     private final EventSerializer eventSerializer;
@@ -87,13 +87,13 @@ public class EventDeadLettersRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        service.post(BASE_PATH, this::performActionOnAllEvents, jsonTransformer);
+        service.post(BASE_PATH, performActionOnAllEvents(), jsonTransformer);
         service.get(BASE_PATH + "/groups", this::listGroups, jsonTransformer);
         service.get(BASE_PATH + "/groups/" + GROUP_PARAM, this::listFailedEvents, jsonTransformer);
-        service.post(BASE_PATH + "/groups/" + GROUP_PARAM, this::performActionOnGroupEvents, jsonTransformer);
+        service.post(BASE_PATH + "/groups/" + GROUP_PARAM, performActionOnGroupEvents(), jsonTransformer);
         service.get(BASE_PATH + "/groups/" + GROUP_PARAM + "/" + INSERTION_ID_PARAMETER, this::getEventDetails);
         service.delete(BASE_PATH + "/groups/" + GROUP_PARAM + "/" + INSERTION_ID_PARAMETER, this::deleteEvent);
-        service.post(BASE_PATH + "/groups/" + GROUP_PARAM + "/" + INSERTION_ID_PARAMETER, this::performActionOnSingleEvent, jsonTransformer);
+        service.post(BASE_PATH + "/groups/" + GROUP_PARAM + "/" + INSERTION_ID_PARAMETER, performActionOnSingleEvent(), jsonTransformer);
     }
 
     @POST
@@ -117,12 +117,10 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Invalid action argument"),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
-    public TaskIdDto performActionOnAllEvents(Request request, Response response) {
-        assertValidActionParameter(request);
-
-        Task task = eventDeadLettersService.redeliverAllEvents();
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
+    public Route performActionOnAllEvents() {
+        return TaskFactory.builder()
+            .register(RE_DELIVER, request -> eventDeadLettersService.redeliverAllEvents())
+            .buildAsRoute(taskManager);
     }
 
     @GET
@@ -186,13 +184,10 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Invalid group name or action argument"),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
-    public TaskIdDto performActionOnGroupEvents(Request request, Response response) {
-        Group group = parseGroup(request);
-        assertValidActionParameter(request);
-
-        Task task = eventDeadLettersService.redeliverGroupEvents(group);
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
+    public Route performActionOnGroupEvents() {
+        return TaskFactory.builder()
+            .register(RE_DELIVER, request -> eventDeadLettersService.redeliverGroupEvents(parseGroup(request)))
+            .buildAsRoute(taskManager);
     }
 
     @GET
@@ -297,23 +292,11 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "No event with this insertionId"),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
-    public TaskIdDto performActionOnSingleEvent(Request request, Response response) {
-        Group group = parseGroup(request);
-        EventDeadLetters.InsertionId insertionId = parseInsertionId(request);
-        assertValidActionParameter(request);
-
-        Task task = eventDeadLettersService.redeliverSingleEvent(group, insertionId);
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
-    }
-
-    private void assertValidActionParameter(Request request) {
-        String action = request.queryParams("action");
-        Optional<ActionEvents> actionEvent = ActionEvents.find(action);
-
-        if (!actionEvent.isPresent()) {
-            throw new IllegalArgumentException(action + " is not a supported action");
-        }
+    public Route performActionOnSingleEvent() {
+        return TaskFactory.builder()
+            .register(RE_DELIVER,
+                request -> eventDeadLettersService.redeliverSingleEvent(parseGroup(request), parseInsertionId(request)))
+            .buildAsRoute(taskManager);
     }
 
     private Group parseGroup(Request request) {
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/dto/ActionEventsTest.java b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/dto/ActionEventsTest.java
deleted file mode 100644
index f4a572a..0000000
--- a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/dto/ActionEventsTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************
- * 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.webadmin.dto;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-import java.util.Optional;
-
-import org.junit.jupiter.api.Test;
-
-class ActionEventsTest {
-    private static final String ACTION = "redeliver";
-
-    @Test
-    void parseShouldSucceedWithCorrectActionEventsArgument() {
-        assertThat(ActionEvents.find(ACTION))
-            .isEqualTo(Optional.of(ActionEvents.REDELIVER));
-    }
-
-    @Test
-    void parseShouldFailWithIncorrectActionEventsArgument() {
-        assertThat(ActionEvents.find("incorrect-action"))
-            .isEqualTo(Optional.empty());
-    }
-
-    @Test
-    void parseShouldFailWithMissingActionEventsArgument() {
-        assertThatThrownBy(() -> ActionEvents.find(null))
-            .isInstanceOf(IllegalArgumentException.class)
-            .hasMessage("'action' url parameter is mandatory");
-    }
-}
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java
index 2b4d51a..9c56056 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/EventDeadLettersRoutesTest.java
@@ -533,7 +533,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("invalid-action is not a supported action"));
+                .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [reDeliver]"));
         }
 
         @Test
@@ -548,7 +548,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("'action' url parameter is mandatory"));
+                .body("details", is("'action' query parameter is compulsory. Supported values are [reDeliver]"));
         }
     }
 
@@ -721,7 +721,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("invalid-action is not a supported action"));
+                .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [reDeliver]"));
         }
 
         @Test
@@ -736,7 +736,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("'action' url parameter is mandatory"));
+                .body("details", is("'action' query parameter is compulsory. Supported values are [reDeliver]"));
         }
 
         @Test
@@ -900,7 +900,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("invalid-action is not a supported action"));
+                .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [reDeliver]"));
         }
 
         @Test
@@ -915,7 +915,7 @@ class EventDeadLettersRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("'action' url parameter is mandatory"));
+                .body("details", is("'action' query parameter is compulsory. Supported values are [reDeliver]"));
         }
 
         @Test


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


[james-project] 12/24: JAMES-3006 Use Task factory in deleted message vault routes

Posted by bt...@apache.org.
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 71517901f49091b6cef72bb24c5ecbecd2849d0c
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:18:37 2019 +0100

    JAMES-3006 Use Task factory in deleted message vault routes
---
 .../vault/routes/DeletedMessagesVaultRoutes.java   | 200 +++++----------------
 .../routes/DeletedMessagesVaultRoutesTest.java     |  22 ++-
 2 files changed, 58 insertions(+), 164 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java
index 81ed6d0..0197c1d 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/main/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutes.java
@@ -21,10 +21,7 @@ package org.apache.james.webadmin.vault.routes;
 
 import static org.apache.james.webadmin.Constants.SEPARATOR;
 
-import java.util.List;
 import java.util.Optional;
-import java.util.function.Function;
-import java.util.stream.Stream;
 
 import javax.inject.Inject;
 import javax.mail.internet.AddressException;
@@ -33,13 +30,11 @@ import javax.ws.rs.POST;
 import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 
-import org.apache.commons.lang3.NotImplementedException;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.james.core.MailAddress;
 import org.apache.james.core.Username;
 import org.apache.james.mailbox.model.MessageId;
 import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
@@ -49,93 +44,35 @@ import org.apache.james.vault.dto.query.QueryTranslator;
 import org.apache.james.vault.search.Query;
 import org.apache.james.webadmin.Constants;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.dto.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskGenerator;
+import org.apache.james.webadmin.tasks.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.JsonExtractException;
 import org.apache.james.webadmin.utils.JsonExtractor;
 import org.apache.james.webadmin.utils.JsonTransformer;
 import org.eclipse.jetty.http.HttpStatus;
 
-import com.github.steveash.guavate.Guavate;
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
+
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
-import spark.HaltException;
 import spark.Request;
-import spark.Response;
+import spark.Route;
 import spark.Service;
 
 @Api(tags = "Deleted Messages Vault")
 @Path(DeletedMessagesVaultRoutes.ROOT_PATH)
 @Produces(Constants.JSON_CONTENT_TYPE)
 public class DeletedMessagesVaultRoutes implements Routes {
-
-    enum VaultAction {
-        RESTORE("restore"),
-        EXPORT("export");
-
-        static Optional<VaultAction> getAction(String value) {
-            Preconditions.checkNotNull(value, "action cannot be null");
-            Preconditions.checkArgument(StringUtils.isNotBlank(value), "action cannot be empty or blank");
-
-            return Stream.of(values())
-                .filter(action -> action.value.equals(value))
-                .findFirst();
-        }
-
-        @VisibleForTesting
-        static List<String> plainValues() {
-            return Stream.of(values())
-                .map(VaultAction::getValue)
-                .collect(Guavate.toImmutableList());
-        }
-
-        private final String value;
-
-        VaultAction(String value) {
-            this.value = value;
-        }
-
-        public String getValue() {
-            return value;
-        }
-    }
-
-    enum VaultScope {
-        EXPIRED("expired");
-
-        static Optional<VaultScope> getScope(String value) {
-            Preconditions.checkNotNull(value, "scope cannot be null");
-            Preconditions.checkArgument(StringUtils.isNotBlank(value), "scope cannot be empty or blank");
-
-            return Stream.of(values())
-                .filter(action -> action.value.equals(value))
-                .findFirst();
-        }
-
-        @VisibleForTesting
-        static List<String> plainValues() {
-            return Stream.of(values())
-                .map(VaultScope::getValue)
-                .collect(Guavate.toImmutableList());
-        }
-
-        private final String value;
-
-        VaultScope(String value) {
-            this.value = value;
-        }
-
-        public String getValue() {
-            return value;
-        }
-    }
+    private static final TaskRegistrationKey EXPORT_REGISTRATION_KEY = TaskRegistrationKey.of("export");
+    private static final TaskRegistrationKey RESTORE_REGISTRATION_KEY = TaskRegistrationKey.of("restore");
+    private static final TaskRegistrationKey EXPIRED_REGISTRATION_KEY = TaskRegistrationKey.of("expired");
 
     public static final String ROOT_PATH = "deletedMessages";
     public static final String USERS = "users";
@@ -145,7 +82,6 @@ public class DeletedMessagesVaultRoutes implements Routes {
     static final String USER_PATH = ROOT_PATH + SEPARATOR + USERS + SEPARATOR + USER_PATH_PARAM;
     private static final String DELETE_PATH = ROOT_PATH + SEPARATOR + USERS + SEPARATOR + USER_PATH_PARAM + SEPARATOR + MESSAGE_PATH_PARAM + SEPARATOR + MESSAGE_ID_PARAM;
     private static final String SCOPE_QUERY_PARAM = "scope";
-    private static final String ACTION_QUERY_PARAM = "action";
     private static final String EXPORT_TO_QUERY_PARAM = "exportTo";
 
     private final RestoreService vaultRestore;
@@ -181,9 +117,11 @@ public class DeletedMessagesVaultRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        service.post(USER_PATH, this::userActions, jsonTransformer);
-        service.delete(ROOT_PATH, this::deleteWithScope, jsonTransformer);
-        service.delete(DELETE_PATH, this::deleteMessage, jsonTransformer);
+        service.post(USER_PATH, userActions(), jsonTransformer);
+        service.delete(ROOT_PATH, deleteWithScope(), jsonTransformer);
+
+        TaskGenerator deleteTaskGenerator = this::deleteMessage;
+        service.delete(DELETE_PATH, deleteTaskGenerator.asRoute(taskManager), jsonTransformer);
     }
 
     @POST
@@ -220,13 +158,23 @@ public class DeletedMessagesVaultRoutes implements Routes {
         @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "Not found - requested user does not exist"),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
-    private TaskIdDto userActions(Request request, Response response) throws JsonExtractException {
-        VaultAction requestedAction = extractParam(request, ACTION_QUERY_PARAM, this::getVaultAction);
-        validateAction(requestedAction, VaultAction.RESTORE, VaultAction.EXPORT);
+    private Route userActions() {
+        return TaskFactory.builder()
+            .register(EXPORT_REGISTRATION_KEY, this::export)
+            .register(RESTORE_REGISTRATION_KEY, this::restore)
+            .buildAsRoute(taskManager);
+    }
 
-        Task requestedTask = generateUserTask(requestedAction, request);
-        TaskId taskId = taskManager.submit(requestedTask);
-        return TaskIdDto.respond(response, taskId);
+    private Task export(Request request) throws JsonExtractException {
+        Username username = extractUser(request);
+        validateUserExist(username);
+        return new DeletedMessagesVaultExportTask(vaultExport, username, extractQuery(request), extractMailAddress(request));
+    }
+
+    private Task restore(Request request) throws JsonExtractException {
+        Username username = extractUser(request);
+        validateUserExist(username);
+        return new DeletedMessagesVaultRestoreTask(vaultRestore, username, extractQuery(request));
     }
 
     @DELETE
@@ -234,7 +182,7 @@ public class DeletedMessagesVaultRoutes implements Routes {
     @ApiImplicitParams({
         @ApiImplicitParam(
             required = true,
-            name = "action",
+            name = "scope",
             dataType = "String",
             paramType = "query",
             example = "?scope=expired",
@@ -245,10 +193,11 @@ public class DeletedMessagesVaultRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - action is invalid"),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
-    private TaskIdDto deleteWithScope(Request request, Response response) {
-        Task vaultTask = generateVaultScopeTask(request);
-        TaskId taskId = taskManager.submit(vaultTask);
-        return TaskIdDto.respond(response, taskId);
+    private Route deleteWithScope() {
+        return TaskFactory.builder()
+            .parameterName(SCOPE_QUERY_PARAM)
+            .register(EXPIRED_REGISTRATION_KEY, request -> deletedMessageVault.deleteExpiredMessagesTask())
+            .buildAsRoute(taskManager);
     }
 
     @DELETE
@@ -277,42 +226,12 @@ public class DeletedMessagesVaultRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Bad request - messageId param is invalid"),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
-    private TaskIdDto deleteMessage(Request request, Response response) {
+    private Task deleteMessage(Request request) {
         Username username = extractUser(request);
         validateUserExist(username);
         MessageId messageId = parseMessageId(request);
 
-        TaskId taskId = taskManager.submit(new DeletedMessagesVaultDeleteTask(deletedMessageVault, username, messageId));
-        return TaskIdDto.respond(response, taskId);
-    }
-
-    private Task generateVaultScopeTask(Request request) {
-        VaultScope scope = extractParam(request, SCOPE_QUERY_PARAM, this::getVaultScope);
-        if (!scope.equals(VaultScope.EXPIRED)) {
-            throw ErrorResponder.builder()
-                .statusCode(HttpStatus.BAD_REQUEST_400)
-                .type(ErrorResponder.ErrorType.INVALID_ARGUMENT)
-                .message(String.format("'%s' is not a valid scope. Supported values are: %s",
-                    scope.value,
-                    VaultScope.plainValues()))
-                .haltError();
-        }
-        return deletedMessageVault.deleteExpiredMessagesTask();
-    }
-
-    private Task generateUserTask(VaultAction requestedAction, Request request) throws JsonExtractException {
-        Username username = extractUser(request);
-        validateUserExist(username);
-        Query query = translate(jsonExtractor.parse(request.body()));
-
-        switch (requestedAction) {
-            case RESTORE:
-                return new DeletedMessagesVaultRestoreTask(vaultRestore, username, query);
-            case EXPORT:
-                return new DeletedMessagesVaultExportTask(vaultExport, username, query, extractMailAddress(request));
-            default:
-                throw new NotImplementedException(requestedAction + " is not yet handled.");
-        }
+        return new DeletedMessagesVaultDeleteTask(deletedMessageVault, username, messageId);
     }
 
     private void validateUserExist(Username username) {
@@ -358,8 +277,9 @@ public class DeletedMessagesVaultRoutes implements Routes {
         }
     }
 
-    private Query translate(QueryElement queryElement) {
+    private Query extractQuery(Request request) throws JsonExtractException {
         try {
+            QueryElement queryElement = jsonExtractor.parse(request.body());
             return queryTranslator.translate(queryElement);
         } catch (QueryTranslator.QueryTranslatorException e) {
             throw ErrorResponder.builder()
@@ -384,46 +304,6 @@ public class DeletedMessagesVaultRoutes implements Routes {
         }
     }
 
-    private <T> T extractParam(Request request, String queryParam, Function<String, T> mapper) {
-        String param = request.queryParams(queryParam);
-        return Optional.ofNullable(param)
-            .map(mapper)
-            .orElseThrow(() -> new IllegalArgumentException("parameter is missing"));
-    }
-
-    private VaultAction getVaultAction(String actionString) {
-        return VaultAction.getAction(actionString)
-            .orElseThrow(() -> new IllegalArgumentException(String.format("'%s' is not a valid action. Supported values are: (%s)",
-                actionString,
-                Joiner.on(",").join(VaultAction.plainValues()))));
-    }
-
-    private VaultScope getVaultScope(String scopeString) {
-        return VaultScope.getScope(scopeString)
-            .orElseThrow(() -> new IllegalArgumentException(String.format("'%s' is not a valid scope. Supported values are: (%s)",
-                scopeString,
-                Joiner.on(",").join(VaultScope.plainValues()))));
-    }
-
-    private void validateAction(VaultAction requestedAction, VaultAction... validActions) {
-        Stream.of(validActions)
-            .filter(action -> action.equals(requestedAction))
-            .findFirst()
-            .orElseThrow(() -> throwNotSupportedAction(requestedAction, validActions));
-    }
-
-    private HaltException throwNotSupportedAction(VaultAction requestAction, VaultAction... validActions) {
-        return ErrorResponder.builder()
-            .statusCode(HttpStatus.BAD_REQUEST_400)
-            .type(ErrorResponder.ErrorType.INVALID_ARGUMENT)
-            .message(String.format("'%s' is not a valid action. Supported values are: %s",
-                requestAction.getValue(),
-                Joiner.on(", ").join(Stream.of(validActions)
-                    .map(action -> String.format("'%s'", action.getValue()))
-                    .collect(Guavate.toImmutableList()))))
-            .haltError();
-    }
-
     private MessageId parseMessageId(Request request) {
         String messageIdAsString = request.params(MESSAGE_ID_PARAM);
         try {
diff --git a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java
index 4025a5b..02528fd 100644
--- a/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-mailbox-deleted-message-vault/src/test/java/org/apache/james/webadmin/vault/routes/DeletedMessagesVaultRoutesTest.java
@@ -290,7 +290,7 @@ class DeletedMessagesVaultRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("parameter is missing"));
+                .body("details", is("'scope' query parameter is compulsory. Supported values are [expired]"));
         }
 
         @Test
@@ -304,7 +304,21 @@ class DeletedMessagesVaultRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", is("scope cannot be empty or blank"));
+                .body("details", is("'scope' query parameter cannot be empty or blank. Supported values are [expired]"));
+        }
+
+        @Test
+        void purgeAPIShouldReturnInvalidWhenPassingBlankScope() {
+            given()
+                .queryParam("scope", "  ")
+            .when()
+                .delete()
+            .then()
+                .statusCode(HttpStatus.BAD_REQUEST_400)
+                .body("statusCode", is(400))
+                .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
+                .body("message", is("Invalid arguments supplied in the user request"))
+                .body("details", is("'scope' query parameter cannot be empty or blank. Supported values are [expired]"));
         }
 
         @Test
@@ -318,7 +332,7 @@ class DeletedMessagesVaultRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", startsWith("'invalid action' is not a valid scope."));
+                .body("details", startsWith("Invalid value supplied for 'scope': invalid action. Supported values are [expired]"));
         }
 
         @Test
@@ -332,7 +346,7 @@ class DeletedMessagesVaultRoutesTest {
                 .body("statusCode", is(400))
                 .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
                 .body("message", is("Invalid arguments supplied in the user request"))
-                .body("details", startsWith("'EXPIRED' is not a valid scope."));
+                .body("details", is("Invalid value supplied for 'scope': EXPIRED. Supported values are [expired]"));
         }
 
         @ParameterizedTest


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


[james-project] 06/24: [Refactoring] FlagsResponse: simplify & test equals & hashCode

Posted by bt...@apache.org.
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 c5994dfc98d449e447e1da5b8fce87ba49cded92
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 06:59:07 2019 +0100

    [Refactoring] FlagsResponse: simplify & test equals & hashCode
---
 .../james/imap/message/response/FlagsResponse.java | 46 +++++++----------
 .../imap/message/response/FlagsResponseTest.java}  | 57 +++-------------------
 2 files changed, 25 insertions(+), 78 deletions(-)

diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java
index 7c58a93..1925c4b 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java
@@ -19,6 +19,8 @@
 
 package org.apache.james.imap.message.response;
 
+import java.util.Objects;
+
 import javax.mail.Flags;
 
 import org.apache.james.imap.api.message.response.ImapResponseMessage;
@@ -30,44 +32,30 @@ public class FlagsResponse implements ImapResponseMessage {
     private final Flags flags;
 
     public FlagsResponse(Flags flags) {
-        super();
         this.flags = flags;
     }
 
-    public String toString() {
-        return "Flags: " + flags;
-    }
-
     public Flags getFlags() {
         return flags;
     }
 
-    public int hashCode() {
-        final int PRIME = 31;
-        int result = 1;
-        result = PRIME * result + ((flags == null) ? 0 : flags.hashCode());
-        return result;
-    }
+    @Override
+    public final boolean equals(Object o) {
+        if (o instanceof FlagsResponse) {
+            FlagsResponse that = (FlagsResponse) o;
 
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj == null) {
-            return false;
+            return Objects.equals(this.flags, that.flags);
         }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        final FlagsResponse other = (FlagsResponse) obj;
-        if (flags == null) {
-            if (other.flags != null) {
-                return false;
-            }
-        } else if (!flags.equals(other.flags)) {
-            return false;
-        }
-        return true;
+        return false;
+    }
+
+    @Override
+    public final int hashCode() {
+        return Objects.hash(flags);
     }
 
+    @Override
+    public String toString() {
+        return "Flags: " + flags;
+    }
 }
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java b/protocols/imap/src/test/java/org/apache/james/imap/message/response/FlagsResponseTest.java
similarity index 51%
copy from protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java
copy to protocols/imap/src/test/java/org/apache/james/imap/message/response/FlagsResponseTest.java
index 7c58a93..650079d 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/FlagsResponse.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/message/response/FlagsResponseTest.java
@@ -19,55 +19,14 @@
 
 package org.apache.james.imap.message.response;
 
-import javax.mail.Flags;
+import org.junit.jupiter.api.Test;
 
-import org.apache.james.imap.api.message.response.ImapResponseMessage;
+import nl.jqno.equalsverifier.EqualsVerifier;
 
-/**
- * Carries a RFC3501 <code>Flags</code> response.
- */
-public class FlagsResponse implements ImapResponseMessage {
-    private final Flags flags;
-
-    public FlagsResponse(Flags flags) {
-        super();
-        this.flags = flags;
-    }
-
-    public String toString() {
-        return "Flags: " + flags;
-    }
-
-    public Flags getFlags() {
-        return flags;
+class FlagsResponseTest {
+    @Test
+    void shouldMatchBeanContract() {
+        EqualsVerifier.forClass(FlagsResponse.class)
+            .verify();
     }
-
-    public int hashCode() {
-        final int PRIME = 31;
-        int result = 1;
-        result = PRIME * result + ((flags == null) ? 0 : flags.hashCode());
-        return result;
-    }
-
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        final FlagsResponse other = (FlagsResponse) obj;
-        if (flags == null) {
-            if (other.flags != null) {
-                return false;
-            }
-        } else if (!flags.equals(other.flags)) {
-            return false;
-        }
-        return true;
-    }
-
-}
+}
\ No newline at end of file


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


[james-project] 11/24: JAMES-3006 Use Task factory in cassandra alias projection routes

Posted by bt...@apache.org.
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 81fbf90179f5dddc0c58e6ebd9a4640e10fb80b1
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:16:21 2019 +0100

    JAMES-3006 Use Task factory in cassandra alias projection routes
---
 .../apache/james/webadmin/dto/ActionMappings.java  | 36 ----------------
 .../webadmin/routes/CassandraMappingsRoutes.java   | 22 +++++-----
 .../webadmin/service/CassandraMappingsService.java | 12 +-----
 .../james/webadmin/dto/ActionMappingsTest.java     | 49 ----------------------
 .../routes/CassandraMappingsRoutesTest.java        |  4 +-
 5 files changed, 13 insertions(+), 110 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/dto/ActionMappings.java b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/dto/ActionMappings.java
deleted file mode 100644
index 7ca05b1..0000000
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/dto/ActionMappings.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/****************************************************************
- * 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.webadmin.dto;
-
-import java.util.Arrays;
-
-import com.google.common.base.Preconditions;
-
-public enum ActionMappings {
-    SolveInconsistencies;
-
-    public static ActionMappings parse(String action) {
-        Preconditions.checkArgument(action != null, "'action' url parameter is mandatory");
-        return Arrays.stream(ActionMappings.values())
-            .filter(element -> element.toString().equalsIgnoreCase(action))
-            .findAny()
-            .orElseThrow(() -> new IllegalArgumentException("'" + action + "' is not a valid action query parameter"));
-    }
-}
\ No newline at end of file
diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
index 15c3d4e..5a4aa8d 100644
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
@@ -24,14 +24,13 @@ import javax.ws.rs.POST;
 import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 
-import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Constants;
 import org.apache.james.webadmin.Routes;
-import org.apache.james.webadmin.dto.ActionMappings;
-import org.apache.james.webadmin.dto.TaskIdDto;
 import org.apache.james.webadmin.service.CassandraMappingsService;
+import org.apache.james.webadmin.tasks.TaskFactory;
+import org.apache.james.webadmin.tasks.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskRegistrationKey;
 import org.apache.james.webadmin.utils.JsonTransformer;
 import org.eclipse.jetty.http.HttpStatus;
 
@@ -42,8 +41,7 @@ import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
 import io.swagger.annotations.ResponseHeader;
-import spark.Request;
-import spark.Response;
+import spark.Route;
 import spark.Service;
 
 @Api(tags = "Cassandra Mappings Operations")
@@ -51,6 +49,7 @@ import spark.Service;
 @Produces(Constants.JSON_CONTENT_TYPE)
 public class CassandraMappingsRoutes implements Routes {
     public static final String ROOT_PATH = "cassandra/mappings";
+    private static final TaskRegistrationKey SOLVE_INCONSISTENCIES = TaskRegistrationKey.of("SolveInconsistencies");
 
     private final CassandraMappingsService cassandraMappingsService;
     private final TaskManager taskManager;
@@ -73,7 +72,7 @@ public class CassandraMappingsRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        service.post(ROOT_PATH, this::performActionOnMappings, jsonTransformer);
+        service.post(ROOT_PATH, performActionOnMappings(), jsonTransformer);
     }
 
     @POST
@@ -97,10 +96,9 @@ public class CassandraMappingsRoutes implements Routes {
         @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = INVALID_ACTION_ARGUMENT_REQUEST),
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = ACTION_REQUEST_CAN_NOT_BE_DONE)
     })
-    public TaskIdDto performActionOnMappings(Request request, Response response) {
-        ActionMappings action = ActionMappings.parse(request.queryParams("action"));
-        Task task = cassandraMappingsService.createActionTask(action);
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
+    public Route performActionOnMappings() {
+        return TaskFactory.builder()
+            .register(SOLVE_INCONSISTENCIES, request -> cassandraMappingsService.solveMappingsSourcesInconsistencies())
+            .buildAsRoute(taskManager);
     }
 }
diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/service/CassandraMappingsService.java b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/service/CassandraMappingsService.java
index e1733ef..5edcaf9 100644
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/service/CassandraMappingsService.java
+++ b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/service/CassandraMappingsService.java
@@ -24,7 +24,6 @@ import javax.inject.Inject;
 import org.apache.james.rrt.cassandra.CassandraMappingsSourcesDAO;
 import org.apache.james.rrt.cassandra.migration.MappingsSourcesMigration;
 import org.apache.james.task.Task;
-import org.apache.james.webadmin.dto.ActionMappings;
 
 public class CassandraMappingsService {
     private final MappingsSourcesMigration mappingsSourcesMigration;
@@ -37,16 +36,7 @@ public class CassandraMappingsService {
         this.cassandraMappingsSourcesDAO = cassandraMappingsSourcesDAO;
     }
 
-    public Task createActionTask(ActionMappings action) {
-        switch (action) {
-            case SolveInconsistencies:
-                return solveMappingsSourcesInconsistencies();
-            default:
-                throw new IllegalArgumentException(action + " is not a supported action");
-        }
-    }
-
-    private Task solveMappingsSourcesInconsistencies() {
+    public Task solveMappingsSourcesInconsistencies() {
         return new CassandraMappingsSolveInconsistenciesTask(mappingsSourcesMigration, cassandraMappingsSourcesDAO);
     }
 }
diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/dto/ActionMappingsTest.java b/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/dto/ActionMappingsTest.java
deleted file mode 100644
index 3cfe691..0000000
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/dto/ActionMappingsTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************
- * 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.webadmin.dto;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-import org.junit.jupiter.api.Test;
-
-class ActionMappingsTest {
-    private static final String ACTION = "SolveInconsistencies";
-
-    @Test
-    void parseShouldSucceedWithCorrectActionMappingsArgument() {
-        assertThat(ActionMappings.parse(ACTION)).isEqualTo(ActionMappings.SolveInconsistencies);
-    }
-
-    @Test
-    void parseShouldFailWithIncorrectActionMappingsArgument() {
-        assertThatThrownBy(() -> ActionMappings.parse("incorrect-action"))
-            .isInstanceOf(IllegalArgumentException.class)
-            .hasMessage("'incorrect-action' is not a valid action query parameter");
-    }
-
-    @Test
-    void parseShouldFailWithMissingActionMappingsArgument() {
-        assertThatThrownBy(() -> ActionMappings.parse(null))
-            .isInstanceOf(IllegalArgumentException.class)
-            .hasMessage("'action' url parameter is mandatory");
-    }
-
-}
diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java b/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java
index 22a0a22..8215091 100644
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-cassandra-data/src/test/java/org/apache/james/webadmin/routes/CassandraMappingsRoutesTest.java
@@ -140,7 +140,7 @@ class CassandraMappingsRoutesTest {
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
             .body("message", is("Invalid arguments supplied in the user request"))
-            .body("details", is("'invalid-action' is not a valid action query parameter"));
+            .body("details", is("Invalid value supplied for 'action': invalid-action. Supported values are [SolveInconsistencies]"));
     }
 
     @Test
@@ -152,7 +152,7 @@ class CassandraMappingsRoutesTest {
             .body("statusCode", is(400))
             .body("type", is(ErrorResponder.ErrorType.INVALID_ARGUMENT.getType()))
             .body("message", is("Invalid arguments supplied in the user request"))
-            .body("details", is("'action' url parameter is mandatory"));
+            .body("details", is("'action' query parameter is compulsory. Supported values are [SolveInconsistencies]"));
     }
 
     @Test


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


[james-project] 17/24: JAMES-3006 Use Task generator in mail queue routes

Posted by bt...@apache.org.
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 2ce2c48426e7aedd84685b8e9fa73a0a98b12728
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:19:05 2019 +0100

    JAMES-3006 Use Task generator in mail queue routes
---
 .../org/apache/james/webadmin/routes/MailQueueRoutes.java   | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java b/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java
index cd1631f..05c5d51 100644
--- a/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailqueue/src/main/java/org/apache/james/webadmin/routes/MailQueueRoutes.java
@@ -36,7 +36,6 @@ import org.apache.james.queue.api.MailQueue.MailQueueException;
 import org.apache.james.queue.api.MailQueueFactory;
 import org.apache.james.queue.api.ManageableMailQueue;
 import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.util.streams.Iterators;
 import org.apache.james.util.streams.Limit;
@@ -44,9 +43,9 @@ import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.dto.ForceDelivery;
 import org.apache.james.webadmin.dto.MailQueueDTO;
 import org.apache.james.webadmin.dto.MailQueueItemDTO;
-import org.apache.james.webadmin.dto.TaskIdDto;
 import org.apache.james.webadmin.service.ClearMailQueueTask;
 import org.apache.james.webadmin.service.DeleteMailsFromMailQueueTask;
+import org.apache.james.webadmin.tasks.TaskGenerator;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.ErrorResponder.ErrorType;
 import org.apache.james.webadmin.utils.JsonExtractException;
@@ -297,14 +296,15 @@ public class MailQueueRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
     })
     public void deleteMails(Service service) {
+        TaskGenerator taskGenerator = this::deleteMails;
         service.delete(BASE_URL + SEPARATOR + MAIL_QUEUE_NAME + MAILS,
-                this::deleteMails,
+                taskGenerator.asRoute(taskManager),
                 jsonTransformer);
     }
 
-    private Object deleteMails(Request request, Response response) {
+    private Task deleteMails(Request request) {
         String mailQueueName = request.params(MAIL_QUEUE_NAME);
-        Task task = mailQueueFactory.getQueue(mailQueueName)
+        return mailQueueFactory.getQueue(mailQueueName)
             .map(name -> deleteMailsTask(name,
                     sender(request.queryParams(SENDER_QUERY_PARAM)),
                     name(request.queryParams(NAME_QUERY_PARAM)),
@@ -315,9 +315,6 @@ public class MailQueueRoutes implements Routes {
                     .statusCode(HttpStatus.NOT_FOUND_404)
                     .type(ErrorResponder.ErrorType.NOT_FOUND)
                     .haltError());
-
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
     }
 
     private Optional<MailAddress> sender(String senderAsString) throws HaltException {


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


[james-project] 19/24: JAMES-3006 TaskIdDTO should not be responsible of its response encoding

Posted by bt...@apache.org.
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 b81e633174d2d1c00b1ad1d7be1d39821e7ba664
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 10:54:56 2019 +0100

    JAMES-3006 TaskIdDTO should not be responsible of its response encoding
---
 .../apache/james/webadmin/tasks/TaskGenerator.java | 10 ++++++++--
 .../org/apache/james/webadmin/tasks/TaskIdDto.java | 16 +---------------
 .../{TaskIdDtoTest.java => TaskGeneratorTest.java} | 22 +++++++++++++++-------
 3 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
index 8cd139b..913e742 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
@@ -19,9 +19,13 @@
 
 package org.apache.james.webadmin.tasks;
 
+import static org.eclipse.jetty.http.HttpHeader.LOCATION;
+
 import org.apache.james.task.Task;
 import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
+import org.apache.james.webadmin.routes.TasksRoutes;
+import org.eclipse.jetty.http.HttpStatus;
 
 import spark.Request;
 import spark.Response;
@@ -38,10 +42,12 @@ public interface TaskGenerator {
         }
 
         @Override
-        public Object handle(Request request, Response response) throws Exception {
+        public TaskIdDto handle(Request request, Response response) throws Exception {
             Task task = taskGenerator.generate(request);
             TaskId taskId = taskManager.submit(task);
-            return TaskIdDto.respond(response, taskId);
+            response.status(HttpStatus.CREATED_201);
+            response.header(LOCATION.asString(), TasksRoutes.BASE + "/" + taskId.asString());
+            return new TaskIdDto(taskId.getValue());
         }
     }
 
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java
index ab8a1b2..074ec87 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java
@@ -19,26 +19,12 @@
 
 package org.apache.james.webadmin.tasks;
 
-import static org.eclipse.jetty.http.HttpHeader.LOCATION;
-
 import java.util.UUID;
 
-import org.apache.james.task.TaskId;
-import org.apache.james.webadmin.routes.TasksRoutes;
-import org.eclipse.jetty.http.HttpStatus;
-
-import spark.Response;
-
 public class TaskIdDto {
-    static TaskIdDto respond(Response response, TaskId taskId) {
-        response.status(HttpStatus.CREATED_201);
-        response.header(LOCATION.asString(), TasksRoutes.BASE + "/" + taskId.asString());
-        return new TaskIdDto(taskId.getValue());
-    }
-
     private final UUID uuid;
 
-    private TaskIdDto(UUID uuid) {
+    TaskIdDto(UUID uuid) {
         this.uuid = uuid;
     }
 
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskIdDtoTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskGeneratorTest.java
similarity index 71%
rename from server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskIdDtoTest.java
rename to server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskGeneratorTest.java
index 1e41f5e..a7995b8 100644
--- a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskIdDtoTest.java
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskGeneratorTest.java
@@ -23,26 +23,34 @@ import static org.eclipse.jetty.http.HttpHeader.LOCATION;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
 
+import org.apache.james.task.Task;
 import org.apache.james.task.TaskId;
+import org.apache.james.task.TaskManager;
 import org.eclipse.jetty.http.HttpStatus;
 import org.junit.Test;
 
+import spark.Request;
 import spark.Response;
 
-public class TaskIdDtoTest {
-    private static final String UID_VALUE = "ce5316cb-c924-40eb-9ca0-c5828e276297";
+public class TaskGeneratorTest {
+    static final Task TASK = mock(Task.class);
+    static final String UUID_VALUE = "ce5316cb-c924-40eb-9ca0-c5828e276297";
 
     @Test
-    public void respondShouldReturnCreatedWithTaskIdHeader() {
+    public void handleShouldReturnCreatedWithTaskIdHeader() throws Exception {
+        Request request = mock(Request.class);
         Response response = mock(Response.class);
-        TaskId taskId = TaskId.fromString(UID_VALUE);
 
-        TaskIdDto.respond(response, taskId);
+        TaskGenerator taskGenerator = any -> TASK;
+        TaskManager taskManager = mock(TaskManager.class);
+        when(taskManager.submit(TASK)).thenReturn(TaskId.fromString(UUID_VALUE));
+
+        taskGenerator.asRoute(taskManager).handle(request, response);
 
         verify(response).status(HttpStatus.CREATED_201);
-        verify(response).header(LOCATION.asString(), "/tasks/" + UID_VALUE);
+        verify(response).header(LOCATION.asString(), "/tasks/" + UUID_VALUE);
         verifyNoMoreInteractions(response);
     }
-
 }
\ No newline at end of file


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


[james-project] 15/24: JAMES-3006 Use Task generator in cassandra alias projection routes

Posted by bt...@apache.org.
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 bea1b9ee9906d47b2f0ca475df680a9d267a7aea
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:17:14 2019 +0100

    JAMES-3006 Use Task generator in cassandra alias projection routes
---
 .../webadmin/routes/CassandraMailboxMergingRoutes.java      | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java
index 4086076..38c37b5 100644
--- a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMailboxMergingRoutes.java
@@ -28,11 +28,12 @@ import org.apache.james.mailbox.cassandra.ids.CassandraId;
 import org.apache.james.mailbox.cassandra.mail.CassandraMailboxCounterDAO;
 import org.apache.james.mailbox.cassandra.mail.task.MailboxMergingTask;
 import org.apache.james.mailbox.cassandra.mail.task.MailboxMergingTaskRunner;
-import org.apache.james.task.TaskId;
+import org.apache.james.task.Task;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.dto.MailboxMergingRequest;
 import org.apache.james.webadmin.dto.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskGenerator;
 import org.apache.james.webadmin.utils.JsonExtractException;
 import org.apache.james.webadmin.utils.JsonExtractor;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -48,7 +49,6 @@ import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
 import io.swagger.annotations.ResponseHeader;
 import spark.Request;
-import spark.Response;
 import spark.Service;
 
 @Api(tags = "Mailbox merging route for fixing Ghost mailbox bug described in MAILBOX-322")
@@ -84,7 +84,8 @@ public class CassandraMailboxMergingRoutes implements Routes {
 
     @Override
     public void define(Service service) {
-        service.post(BASE, this::mergeMailboxes, jsonTransformer);
+        TaskGenerator taskGenerator = this::mergeMailboxes;
+        service.post(BASE, taskGenerator.asRoute(taskManager), jsonTransformer);
     }
 
     @POST
@@ -106,15 +107,13 @@ public class CassandraMailboxMergingRoutes implements Routes {
             }),
             @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Error with supplied data (JSON parsing or invalid mailbox ids)")
         })
-    public Object mergeMailboxes(Request request, Response response) throws JsonExtractException {
+    public Task mergeMailboxes(Request request) throws JsonExtractException {
         LOGGER.debug("Cassandra upgrade launched");
         MailboxMergingRequest mailboxMergingRequest = jsonExtractor.parse(request.body());
         CassandraId originId = mailboxIdFactory.fromString(mailboxMergingRequest.getMergeOrigin());
         CassandraId destinationId = mailboxIdFactory.fromString(mailboxMergingRequest.getMergeDestination());
 
         long totalMessagesToMove = counterDAO.countMessagesInMailbox(originId).defaultIfEmpty(0L).block();
-        MailboxMergingTask task = new MailboxMergingTask(mailboxMergingTaskRunner, totalMessagesToMove, originId, destinationId);
-        TaskId taskId = taskManager.submit(task);
-        return TaskIdDto.respond(response, taskId);
+        return new MailboxMergingTask(mailboxMergingTaskRunner, totalMessagesToMove, originId, destinationId);
     }
 }


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


[james-project] 20/24: JAMES-3006 Shortcut for single-entry task factories

Posted by bt...@apache.org.
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 9677cbf6fecc73a1fb06fcf6c9d74f8042781804
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 05:11:15 2019 +0100

    JAMES-3006 Shortcut for single-entry task factories
---
 .../james/webadmin/routes/CassandraMappingsRoutes.java    |  5 ++---
 .../java/org/apache/james/webadmin/tasks/TaskFactory.java |  6 ++++++
 .../org/apache/james/webadmin/tasks/TaskFactoryTest.java  |  4 +---
 .../james/webadmin/routes/EventDeadLettersRoutes.java     | 15 ++++++---------
 .../james/webadmin/routes/MailRepositoriesRoutes.java     | 10 ++++------
 5 files changed, 19 insertions(+), 21 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
index 5a4aa8d..5225f1c 100644
--- a/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra-data/src/main/java/org/apache/james/webadmin/routes/CassandraMappingsRoutes.java
@@ -97,8 +97,7 @@ public class CassandraMappingsRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = ACTION_REQUEST_CAN_NOT_BE_DONE)
     })
     public Route performActionOnMappings() {
-        return TaskFactory.builder()
-            .register(SOLVE_INCONSISTENCIES, request -> cassandraMappingsService.solveMappingsSourcesInconsistencies())
-            .buildAsRoute(taskManager);
+        return TaskFactory.of(SOLVE_INCONSISTENCIES, request -> cassandraMappingsService.solveMappingsSourcesInconsistencies())
+            .asRoute(taskManager);
     }
 }
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
index 7db9bef..a46c6c9 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskFactory.java
@@ -104,6 +104,12 @@ public class TaskFactory implements TaskGenerator {
         return new Builder();
     }
 
+    public static TaskFactory of(TaskRegistrationKey key, TaskGenerator generator) {
+        return TaskFactory.builder()
+            .register(key, generator)
+            .build();
+    }
+
     private final String taskParameterName;
     private final Map<TaskRegistrationKey, TaskGenerator> taskGenerators;
 
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
index 648fc84..18b947f 100644
--- a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskFactoryTest.java
@@ -47,9 +47,7 @@ class TaskFactoryTest {
             .register(KEY_1, any -> TASK_1)
             .register(KEY_2, any -> TASK_2)
             .build();
-        singleTaskFactory = TaskFactory.builder()
-            .register(KEY_1, any -> TASK_1)
-            .build();
+        singleTaskFactory = TaskFactory.of(KEY_1, any -> TASK_1);
     }
 
     @Test
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
index c877a50..cc1a9fe 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/main/java/org/apache/james/webadmin/routes/EventDeadLettersRoutes.java
@@ -118,9 +118,8 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
     public Route performActionOnAllEvents() {
-        return TaskFactory.builder()
-            .register(RE_DELIVER, request -> eventDeadLettersService.redeliverAllEvents())
-            .buildAsRoute(taskManager);
+        return TaskFactory.of(RE_DELIVER, request -> eventDeadLettersService.redeliverAllEvents())
+            .asRoute(taskManager);
     }
 
     @GET
@@ -185,9 +184,8 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
     public Route performActionOnGroupEvents() {
-        return TaskFactory.builder()
-            .register(RE_DELIVER, request -> eventDeadLettersService.redeliverGroupEvents(parseGroup(request)))
-            .buildAsRoute(taskManager);
+        return TaskFactory.of(RE_DELIVER, request -> eventDeadLettersService.redeliverGroupEvents(parseGroup(request)))
+            .asRoute(taskManager);
     }
 
     @GET
@@ -293,10 +291,9 @@ public class EventDeadLettersRoutes implements Routes {
         @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = INTERNAL_SERVER_ERROR)
     })
     public Route performActionOnSingleEvent() {
-        return TaskFactory.builder()
-            .register(RE_DELIVER,
+        return TaskFactory.of(RE_DELIVER,
                 request -> eventDeadLettersService.redeliverSingleEvent(parseGroup(request), parseInsertionId(request)))
-            .buildAsRoute(taskManager);
+            .asRoute(taskManager);
     }
 
     private Group parseGroup(Request request) {
diff --git a/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java b/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
index 4b3f123..0b00416 100644
--- a/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
+++ b/server/protocols/webadmin/webadmin-mailrepository/src/main/java/org/apache/james/webadmin/routes/MailRepositoriesRoutes.java
@@ -445,9 +445,8 @@ public class MailRepositoriesRoutes implements Routes {
     })
     public void defineReprocessAll() {
         service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails",
-            TaskFactory.builder()
-                .register(REPROCESS_ACTION, this::reprocessAll)
-                .buildAsRoute(taskManager),
+            TaskFactory.of(REPROCESS_ACTION, this::reprocessAll)
+                .asRoute(taskManager),
             jsonTransformer);
     }
 
@@ -496,9 +495,8 @@ public class MailRepositoriesRoutes implements Routes {
     })
     public void defineReprocessOne() {
         service.patch(MAIL_REPOSITORIES + "/:encodedPath/mails/:key",
-            TaskFactory.builder()
-                .register(REPROCESS_ACTION, this::reprocessOne)
-                .buildAsRoute(taskManager),
+            TaskFactory.of(REPROCESS_ACTION, this::reprocessOne)
+                .asRoute(taskManager),
             jsonTransformer);
     }
 


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


[james-project] 07/24: [Refactoring] IMAP responses: avoid super constructor call

Posted by bt...@apache.org.
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 58b3e9bb5064935e71406ad2f2a0831f4784fd4d
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 07:02:48 2019 +0100

    [Refactoring] IMAP responses: avoid super constructor call
    
    They are referencing the one from Object and thus are not needed.
---
 .../org/apache/james/imap/message/response/ACLResponse.java   |  2 --
 .../james/imap/message/response/AbstractListingResponse.java  |  2 --
 .../james/imap/message/response/ContinuationResponse.java     |  1 -
 .../apache/james/imap/message/response/ESearchResponse.java   |  2 --
 .../apache/james/imap/message/response/ExistsResponse.java    |  1 -
 .../apache/james/imap/message/response/ExpungeResponse.java   |  1 -
 .../org/apache/james/imap/message/response/FetchResponse.java | 11 -----------
 .../james/imap/message/response/ImmutableStatusResponse.java  |  5 -----
 .../org/apache/james/imap/message/response/ListResponse.java  |  2 --
 .../james/imap/message/response/ListRightsResponse.java       |  1 -
 .../james/imap/message/response/MailboxStatusResponse.java    |  7 -------
 .../apache/james/imap/message/response/MyRightsResponse.java  |  1 -
 .../apache/james/imap/message/response/NamespaceResponse.java |  1 -
 .../apache/james/imap/message/response/QuotaRootResponse.java |  1 -
 .../apache/james/imap/message/response/RecentResponse.java    |  2 --
 15 files changed, 40 deletions(-)

diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ACLResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ACLResponse.java
index 29c2ae2..ba41f39 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ACLResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ACLResponse.java
@@ -34,11 +34,9 @@ import org.apache.james.mailbox.model.MailboxACL.Rfc4314Rights;
  */
 public final class ACLResponse implements ImapResponseMessage {
     private final MailboxACL acl;
-
     private final String mailboxName;
 
     public ACLResponse(String mailboxName, MailboxACL acl) {
-        super();
         this.mailboxName = mailboxName;
         this.acl = acl;
     }
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/AbstractListingResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/AbstractListingResponse.java
index ca198dd..c50a882 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/AbstractListingResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/AbstractListingResponse.java
@@ -27,7 +27,6 @@ import org.apache.james.mailbox.model.MailboxMetaData;
 import com.google.common.base.MoreObjects;
 
 public abstract class AbstractListingResponse {
-
     private final MailboxMetaData.Children children;
     private final MailboxMetaData.Selectability selectability;
     private final String name;
@@ -37,7 +36,6 @@ public abstract class AbstractListingResponse {
     public AbstractListingResponse(MailboxMetaData.Children children,
                                    MailboxMetaData.Selectability selectability,
                                    String name, char hierarchyDelimiter, MailboxType type) {
-        super();
         this.children = children;
         this.selectability = selectability;
         this.name = name;
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java
index da8b5f0..8215188 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ContinuationResponse.java
@@ -29,7 +29,6 @@ public class ContinuationResponse implements ImapResponseMessage {
     private final HumanReadableText textKey;
 
     public ContinuationResponse(HumanReadableText textKey) {
-        super();
         this.data = null;
         this.textKey = textKey;
     }
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ESearchResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ESearchResponse.java
index b45ac89..89e0437 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ESearchResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ESearchResponse.java
@@ -29,7 +29,6 @@ import org.apache.james.imap.api.message.response.ImapResponseMessage;
 import org.apache.james.mailbox.ModSeq;
 
 public class ESearchResponse implements ImapResponseMessage {
-
     private final long minUid;
     private final long maxUid;
     private final long count;
@@ -41,7 +40,6 @@ public class ESearchResponse implements ImapResponseMessage {
     private UidRange[] allUids;
 
     public ESearchResponse(long minUid, long maxUid, long count, IdRange[] all, UidRange[] allUids, ModSeq highestModSeq, Tag tag, boolean useUid, List<SearchResultOption> options) {
-        super();
         this.options = options;
         this.minUid = minUid;
         this.maxUid = maxUid;
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExistsResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExistsResponse.java
index 18a8fca..185a200 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExistsResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExistsResponse.java
@@ -25,7 +25,6 @@ public final class ExistsResponse implements ImapResponseMessage {
     private final long numberOfMessages;
 
     public ExistsResponse(long numberOfMessages) {
-        super();
         this.numberOfMessages = numberOfMessages;
     }
 
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExpungeResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExpungeResponse.java
index 323152a..2d13203 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExpungeResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ExpungeResponse.java
@@ -26,7 +26,6 @@ public final class ExpungeResponse implements ImapResponseMessage {
     private final int messageSequenceNumber;
 
     public ExpungeResponse(int messageSequenceNumber) {
-        super();
         this.messageSequenceNumber = messageSequenceNumber;
     }
 
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/FetchResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/FetchResponse.java
index aaa5cc1..0d64091 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/FetchResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/FetchResponse.java
@@ -30,29 +30,18 @@ import org.apache.james.mailbox.MessageUid;
 import org.apache.james.mailbox.ModSeq;
 
 public final class FetchResponse implements ImapResponseMessage {
-
     private final int messageNumber;
-
     private final Flags flags;
-
     private final MessageUid uid;
-
     private final Date internalDate;
-
     private final Long size;
-
     private final List<BodyElement> elements;
-
     private final Envelope envelope;
-
     private final Structure body;
-
     private final Structure bodystructure;
-
     private final ModSeq modSeq;
 
     public FetchResponse(int messageNumber, Flags flags, MessageUid uid, ModSeq modSeq, Date internalDate, Long size, Envelope envelope, Structure body, Structure bodystructure, List<BodyElement> elements) {
-        super();
         this.messageNumber = messageNumber;
         this.flags = flags;
         this.uid = uid;
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ImmutableStatusResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ImmutableStatusResponse.java
index e502348..df67936 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ImmutableStatusResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ImmutableStatusResponse.java
@@ -30,15 +30,10 @@ import com.google.common.base.MoreObjects;
  * Immutable status response. Suitable for unpooled usage.
  */
 public class ImmutableStatusResponse implements StatusResponse {
-
     private final ResponseCode responseCode;
-
     private final Type serverResponseType;
-
     private final Tag tag;
-
     private final HumanReadableText textKey;
-
     private final ImapCommand command;
 
     public ImmutableStatusResponse(Type serverResponseType, Tag tag, ImapCommand command, HumanReadableText textKey, ResponseCode responseCode) {
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListResponse.java
index 62efa61..cde9f35 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListResponse.java
@@ -26,9 +26,7 @@ import org.apache.james.mailbox.model.MailboxMetaData;
  * Values an IMAP4rev1 <code>LIST</code> response.
  */
 public final class ListResponse extends AbstractListingResponse implements ImapResponseMessage {
-
     public ListResponse(MailboxMetaData.Children children, MailboxMetaData.Selectability selectability, String name, char hierarchyDelimiter) {
         super(children, selectability, name, hierarchyDelimiter, MailboxType.OTHER);
     }
-
 }
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListRightsResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListRightsResponse.java
index 970491d..5bba8a8 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListRightsResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/ListRightsResponse.java
@@ -30,7 +30,6 @@ import org.apache.james.mailbox.model.MailboxACL;
  * LISTRIGHTS Response.
  */
 public final class ListRightsResponse implements ImapResponseMessage {
-
     private final String identifier;
     private final String mailboxName;
     private final MailboxACL.Rfc4314Rights[] rights;
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/MailboxStatusResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/MailboxStatusResponse.java
index 9608625..c7798b3 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/MailboxStatusResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/MailboxStatusResponse.java
@@ -27,19 +27,12 @@ import org.apache.james.mailbox.ModSeq;
  * Represents a <code>STATUS</code> response. See <code>RFC3501 7.2.4</code>.
  */
 public class MailboxStatusResponse implements ImapResponseMessage {
-
     private final Long messages;
-
     private final Long recent;
-
     private final MessageUid uidNext;
-
     private final Long uidValidity;
-
     private final Long unseen;
-
     private final String mailbox;
-
     private final ModSeq highestModSeq;
 
     public MailboxStatusResponse(Long messages, Long recent, MessageUid uidNext, ModSeq highestModSeq, Long uidValidity, Long unseen, String mailbox) {
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/MyRightsResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/MyRightsResponse.java
index 2468cdc..10628f0 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/MyRightsResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/MyRightsResponse.java
@@ -33,7 +33,6 @@ public final class MyRightsResponse implements ImapResponseMessage {
     private final MailboxACL.Rfc4314Rights myRights;
 
     public MyRightsResponse(String mailboxName, MailboxACL.Rfc4314Rights myRights) {
-        super();
         this.mailboxName = mailboxName;
         this.myRights = myRights;
     }
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java
index 92191f9..6c20bd0 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java
@@ -27,7 +27,6 @@ import org.apache.james.imap.api.message.response.ImapResponseMessage;
  * Describes a NAMESPACE response.
  */
 public class NamespaceResponse implements ImapResponseMessage {
-
     private final List<Namespace> personal;
     private final List<Namespace> users;
     private final List<Namespace> shared;
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/QuotaRootResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/QuotaRootResponse.java
index 8ed9498..a4bb28f 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/QuotaRootResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/QuotaRootResponse.java
@@ -30,7 +30,6 @@ public class QuotaRootResponse implements ImapResponseMessage {
     private final String mailboxName;
 
     public QuotaRootResponse(String mailboxName, String quotaRoot) {
-        super();
         this.mailboxName = mailboxName;
         this.quotaRoot = quotaRoot;
     }
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/RecentResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/RecentResponse.java
index 8725e40..43b42c8 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/RecentResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/RecentResponse.java
@@ -22,11 +22,9 @@ package org.apache.james.imap.message.response;
 import org.apache.james.imap.api.message.response.ImapResponseMessage;
 
 public final class RecentResponse implements ImapResponseMessage {
-
     private final int numberFlaggedRecent;
 
     public RecentResponse(int numberFlaggedRecent) {
-        super();
         this.numberFlaggedRecent = numberFlaggedRecent;
     }
 


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


[james-project] 04/24: [Refactoring] NamespaceResponse: simplify & test equals & hashCode

Posted by bt...@apache.org.
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 464fcbf2b92c0933b58d0f4f274f88aa4e92f1fb
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Dec 13 06:54:38 2019 +0100

    [Refactoring] NamespaceResponse: simplify & test equals & hashCode
---
 .../imap/message/response/NamespaceResponse.java   | 97 +++++-----------------
 .../message/response/NamespaceResponseTest.java    | 38 +++++++++
 2 files changed, 61 insertions(+), 74 deletions(-)

diff --git a/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java b/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java
index 274e078..92191f9 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/message/response/NamespaceResponse.java
@@ -19,6 +19,7 @@
 package org.apache.james.imap.message.response;
 
 import java.util.List;
+import java.util.Objects;
 
 import org.apache.james.imap.api.message.response.ImapResponseMessage;
 
@@ -28,13 +29,10 @@ import org.apache.james.imap.api.message.response.ImapResponseMessage;
 public class NamespaceResponse implements ImapResponseMessage {
 
     private final List<Namespace> personal;
-
     private final List<Namespace> users;
-
     private final List<Namespace> shared;
 
     public NamespaceResponse(List<Namespace> personal, List<Namespace> users, List<Namespace> shared) {
-        super();
         this.personal = personal;
         this.users = users;
         this.shared = shared;
@@ -72,11 +70,9 @@ public class NamespaceResponse implements ImapResponseMessage {
      */
     public static final class Namespace {
         private final String prefix;
-
         private final char delimiter;
 
         public Namespace(String prefix, char delimiter) {
-            super();
             this.prefix = prefix;
             this.delimiter = delimiter;
         }
@@ -100,37 +96,19 @@ public class NamespaceResponse implements ImapResponseMessage {
         }
 
         @Override
-        public int hashCode() {
-            final int PRIME = 31;
-            int result = 1;
-            result = PRIME * result + delimiter;
-            result = PRIME * result + ((prefix == null) ? 0 : prefix.hashCode());
-            return result;
+        public final boolean equals(Object o) {
+            if (o instanceof Namespace) {
+                Namespace namespace = (Namespace) o;
+
+                return Objects.equals(this.delimiter, namespace.delimiter)
+                    && Objects.equals(this.prefix, namespace.prefix);
+            }
+            return false;
         }
 
         @Override
-        public boolean equals(Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            final Namespace other = (Namespace) obj;
-            if (delimiter != other.delimiter) {
-                return false;
-            }
-            if (prefix == null) {
-                if (other.prefix != null) {
-                    return false;
-                }
-            } else if (!prefix.equals(other.prefix)) {
-                return false;
-            }
-            return true;
+        public final int hashCode() {
+            return Objects.hash(prefix, delimiter);
         }
 
         @Override
@@ -140,49 +118,20 @@ public class NamespaceResponse implements ImapResponseMessage {
     }
 
     @Override
-    public int hashCode() {
-        final int PRIME = 31;
-        int result = 1;
-        result = PRIME * result + ((personal == null) ? 0 : personal.hashCode());
-        result = PRIME * result + ((shared == null) ? 0 : shared.hashCode());
-        result = PRIME * result + ((users == null) ? 0 : users.hashCode());
-        return result;
+    public final boolean equals(Object o) {
+        if (o instanceof NamespaceResponse) {
+            NamespaceResponse that = (NamespaceResponse) o;
+
+            return Objects.equals(this.personal, that.personal)
+                && Objects.equals(this.users, that.users)
+                && Objects.equals(this.shared, that.shared);
+        }
+        return false;
     }
 
     @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        final NamespaceResponse other = (NamespaceResponse) obj;
-        if (personal == null) {
-            if (other.personal != null) {
-                return false;
-            }
-        } else if (!personal.equals(other.personal)) {
-            return false;
-        }
-        if (shared == null) {
-            if (other.shared != null) {
-                return false;
-            }
-        } else if (!shared.equals(other.shared)) {
-            return false;
-        }
-        if (users == null) {
-            if (other.users != null) {
-                return false;
-            }
-        } else if (!users.equals(other.users)) {
-            return false;
-        }
-        return true;
+    public final int hashCode() {
+        return Objects.hash(personal, users, shared);
     }
 
     /**
@@ -191,6 +140,6 @@ public class NamespaceResponse implements ImapResponseMessage {
      * @return a <code>String</code> representation of this object.
      */
     public String toString() {
-        return "NamespaceResponse [" + "personal = " + this.personal + " " + "users = " + this.users + " " + "shared = " + this.shared + " " + " ]";
+        return "NamespaceResponse [personal = " + this.personal + " users = " + this.users + " shared = " + this.shared + "  ]";
     }
 }
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/message/response/NamespaceResponseTest.java b/protocols/imap/src/test/java/org/apache/james/imap/message/response/NamespaceResponseTest.java
new file mode 100644
index 0000000..85179b8
--- /dev/null
+++ b/protocols/imap/src/test/java/org/apache/james/imap/message/response/NamespaceResponseTest.java
@@ -0,0 +1,38 @@
+/****************************************************************
+ * 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.imap.message.response;
+
+import org.junit.jupiter.api.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+
+class NamespaceResponseTest {
+    @Test
+    void namespaceResponseShouldMatchBeanContract() {
+        EqualsVerifier.forClass(NamespaceResponse.class)
+            .verify();
+    }
+
+    @Test
+    void namespaceShouldMatchBeanContract() {
+        EqualsVerifier.forClass(NamespaceResponse.Namespace.class)
+            .verify();
+    }
+}
\ No newline at end of file


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


[james-project] 23/24: JAMES-2993 Factorize documentation for returned taskIds

Posted by bt...@apache.org.
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 b456eb049fea2f2913c12a97f3bc77c935edcaad
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Mon Dec 16 11:27:46 2019 +0700

    JAMES-2993 Factorize documentation for returned taskIds
---
 src/site/markdown/server/manage-webadmin.md | 225 +++++++++-------------------
 1 file changed, 71 insertions(+), 154 deletions(-)

diff --git a/src/site/markdown/server/manage-webadmin.md b/src/site/markdown/server/manage-webadmin.md
index a4ad547..14c133b 100644
--- a/src/site/markdown/server/manage-webadmin.md
+++ b/src/site/markdown/server/manage-webadmin.md
@@ -1108,12 +1108,9 @@ Response codes:
 curl -XPOST http://ip:port/cassandra/version/upgrade -d '3'
 ```
 
+Will schedule the run of the migrations you need to reach schema version 3.
 
-Will schedule the run of the migrations you need to reach schema version 3. The `taskId` will allow you to monitor and manage this process.
-
-```
-{"taskId":"3294a976-ce63-491e-bd52-1b6f465ed7a2"}
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -1138,19 +1135,9 @@ The scheduled task will have the following type `cassandra-migration` and the fo
 curl -XPOST http://ip:port/cassandra/version/upgrade/latest
 ```
 
-Will schedule the run of the migrations you need to reach the latest schema version. The `taskId` will allow you to monitor and manage this process.
-
-```
-{"taskId":"3294a976-ce63-491e-bd52-1b6f465ed7a2"}
-```
+Will schedule the run of the migrations you need to reach the latest schema version.
 
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -1183,19 +1170,7 @@ Will scedule a task for :
  - Move it's messages into `id2` mailbox
  - Union the rights of both mailboxes
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2009,19 +1984,7 @@ Resource name `encodedPathOfTheRepository` should be the resource path of an exi
 curl -XDELETE http://ip:port/mailRepositories/var%2Fmail%2Ferror%2F/mails
 ```
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2069,20 +2032,7 @@ curl -XPATCH http://ip:port/mailRepositories/var%2Fmail%2Ferror%2F/mails?action=
 
 Note that the `action` query parameter is compulsary and can only take value `reprocess`.
 
-
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2132,20 +2082,7 @@ curl -XPATCH http://ip:port/mailRepositories/var%2Fmail%2Ferror%2F/mails/name1?a
 
 Note that the `action` query parameter is compulsary and can only take value `reprocess`.
 
-
-The response to that request will be the scheduled `taskId`:
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2251,6 +2188,7 @@ This request should have exactly one query parameter from the following list:
 
 The mails from the given mail queue matching the query parameter will be deleted.
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2279,6 +2217,7 @@ curl -XDELETE http://ip:port/mailQueues/mailQueueName/mails
 
 All mails from the given mail queue will be deleted.
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2309,6 +2248,8 @@ and it performs a flush.
 
 The mails delayed in the given mail queue will be flushed.
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response codes:
 
  - 204: Success (No content)
@@ -2585,19 +2526,7 @@ curl -XPOST http://ip:port/mailboxes?task=reIndex
 
 Will schedule a task for reIndexing all the mails stored on this James server.
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2632,19 +2561,7 @@ curl -XPOST http://ip:port/mailboxes?task=reIndex,user=bob%40domain.com
 
 Will schedule a task for reIndexing all the mails in "bob@domain.com" mailboxes (encoded above).
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2682,19 +2599,7 @@ Will schedule a task for reIndexing all the mails in one mailbox.
 
 Note that 'mailboxId' path parameter needs to be a (implementation dependent) valid mailboxId.
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2732,19 +2637,7 @@ curl -XPOST http://ip:port/mailboxes?task=reIndex&reIndexFailedMessagesOf=bbdb69
 
 Will schedule a task for reIndexing all the mails that this task failed to reIndex.
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positioned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2774,19 +2667,7 @@ Will schedule a task for reIndexing a single email.
 
 Note that 'mailboxId' path parameter needs to be a (implementation dependent) valid mailboxId.
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2816,19 +2697,7 @@ Will schedule a task for reIndexing a single email in all the mailboxes containi
 
 Note that 'messageId' path parameter needs to be a (implementation dependent) valid messageId.
 
-The response to that request will be the scheduled `taskId` :
-
-```
-{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
-```
-
-Positionned headers:
-
- - Location header indicates the location of the resource associated with the scheduled task. Example:
-
-```
-Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
-```
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 Response codes:
 
@@ -2935,6 +2804,8 @@ curl -XPOST http://ip:port/events/deadLetter
 Will create a task that will attempt to redeliver all events stored in "Event Dead Letter".
 If successful, redelivered events will then be removed from "Dead Letter".
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response codes:
 
  - 201: the taskId of the created task
@@ -2949,6 +2820,8 @@ curl -XPOST http://ip:port/events/deadLetter/groups/org.apache.james.mailbox.eve
 Will create a task that will attempt to redeliver all events of a particular group stored in "Event Dead Letter".
 If successful, redelivered events will then be removed from "Dead Letter".
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response codes:
 
  - 201: the taskId of the created task
@@ -2963,6 +2836,8 @@ curl -XPOST http://ip:port/events/deadLetter/groups/org.apache.james.mailbox.eve
 Will create a task that will attempt to redeliver a single event of a particular group stored in "Event Dead Letter".
 If successful, redelivered event will then be removed from "Dead Letter".
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response codes:
 
  - 201: the taskId of the created task
@@ -3110,6 +2985,8 @@ Response code:
    - Json query object contains unsupported operator, fieldName
    - Json query object values violate parsing rules 
  - 404: User not found
+ 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
 
 The scheduled task will have the following type `deleted-messages-restore` and the following `additionalInformation`:
 
@@ -3151,6 +3028,8 @@ Response code:
    - Json query object values violate parsing rules 
  - 404: User not found
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 The scheduled task will have the following type `deleted-messages-export` and the following `additionalInformation`:
 
 ```
@@ -3173,9 +3052,11 @@ You can overwrite 'retentionPeriod' configuration in 'deletedMessageVault' confi
 Purge all deleted messages older than the configured 'retentionPeriod'
 
 ```
-curl -XDEL http://ip:port/deletedMessages?scope=expired
+curl -XDELETE http://ip:port/deletedMessages?scope=expired
 ```
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response code:
 
  - 201: Task for purging has been created
@@ -3190,9 +3071,11 @@ You may want to call this endpoint on a regular basis.
 Delete a Deleted Message with MessageId
 
 ```
-curl -XDEL http://ip:port/deletedMessages/users/user@domain.ext/messages/3294a976-ce63-491e-bd52-1b6f465ed7a2
+curl -XDELETE http://ip:port/deletedMessages/users/user@domain.ext/messages/3294a976-ce63-491e-bd52-1b6f465ed7a2
 ```
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response code:
 
  - 201: Task for deleting message has been created
@@ -3201,14 +3084,14 @@ Response code:
    - messageId parameter is invalid
  - 404: User not found
  
- The scheduled task will have the following type `deleted-messages-delete` and the following `additionalInformation`:
+The scheduled task will have the following type `deleted-messages-delete` and the following `additionalInformation`:
  
- ```
+```
  {
    "user": "user@domain.ext",
    "deleteMessageId": "3294a976-ce63-491e-bd52-1b6f465ed7a2"
  }
- ```
+```
  
 while:
  - user: delete deleted messages from this user
@@ -3224,6 +3107,7 @@ Note that the `taskId` used in the following APIs is returned by other WebAdmin
  - [Awaiting a task](#Awaiting_a_task)
  - [Cancelling a task](#Cancelling_a_task)
  - [Listing tasks](#Listing_tasks)
+ - [Endpoints returning a task](#Endpoints_returning_a_task)
 
 ### Getting a task details
 
@@ -3330,6 +3214,37 @@ Response codes:
 
  - 200: A list of corresponding tasks is returned
  - 400: Invalid status value
+ 
+### Endpoints returning a task
+
+Many endpoints do generate a task.
+
+Example:
+
+```
+curl -XPOST /endpoint?action=XXX
+```
+
+The response to these requests will be the scheduled `taskId` :
+
+```
+{"taskId":"5641376-02ed-47bd-bcc7-76ff6262d92a"}
+```
+
+Positionned headers:
+
+ - Location header indicates the location of the resource associated with the scheduled task. Example:
+
+```
+Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
+```
+
+Response codes:
+
+ - 201: Success. Corresponding task id is returned.
+ - Other response codes might be returned depending on the endpoint
+
+The additional information returned depends on the scheduled task type and is documented in the endpoint documentation.
 
 ## Cassandra extra operations
 
@@ -3358,6 +3273,8 @@ For example :
 curl -XPOST /cassandra/mappings?action=SolveInconsistencies
 ```
 
+[More details about endpoints returning a task](#Endpoints_returning_a_task).
+
 Response codes :
 
  - 201: the taskId of the created task


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


[james-project] 18/24: JAMES-3006 Move TaskIdDTO in task package + visibility enhancements

Posted by bt...@apache.org.
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 40042e9442e38891cff6306b283d7ba29e5e0bb7
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:19:41 2019 +0100

    JAMES-3006 Move TaskIdDTO in task package + visibility enhancements
    
    This enforce the usage of TaskGenerator for returning tasks to the caller
---
 .../java/org/apache/james/webadmin/tasks/TaskGenerator.java |  1 -
 .../org/apache/james/webadmin/{dto => tasks}/TaskIdDto.java | 13 ++++---------
 .../apache/james/webadmin/{dto => tasks}/TaskIdDtoTest.java |  2 +-
 3 files changed, 5 insertions(+), 11 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
index 09d759e..8cd139b 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskGenerator.java
@@ -22,7 +22,6 @@ package org.apache.james.webadmin.tasks;
 import org.apache.james.task.Task;
 import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
-import org.apache.james.webadmin.dto.TaskIdDto;
 
 import spark.Request;
 import spark.Response;
diff --git a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/dto/TaskIdDto.java b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java
similarity index 85%
rename from server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/dto/TaskIdDto.java
rename to server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java
index fbb74f0..ab8a1b2 100644
--- a/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/dto/TaskIdDto.java
+++ b/server/protocols/webadmin/webadmin-core/src/main/java/org/apache/james/webadmin/tasks/TaskIdDto.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.james.webadmin.dto;
+package org.apache.james.webadmin.tasks;
 
 import static org.eclipse.jetty.http.HttpHeader.LOCATION;
 
@@ -30,20 +30,15 @@ import org.eclipse.jetty.http.HttpStatus;
 import spark.Response;
 
 public class TaskIdDto {
-
-    public static TaskIdDto respond(Response response, TaskId taskId) {
+    static TaskIdDto respond(Response response, TaskId taskId) {
         response.status(HttpStatus.CREATED_201);
         response.header(LOCATION.asString(), TasksRoutes.BASE + "/" + taskId.asString());
-        return TaskIdDto.from(taskId);
-    }
-
-    public static TaskIdDto from(TaskId id) {
-        return new TaskIdDto(id.getValue());
+        return new TaskIdDto(taskId.getValue());
     }
 
     private final UUID uuid;
 
-    public TaskIdDto(UUID uuid) {
+    private TaskIdDto(UUID uuid) {
         this.uuid = uuid;
     }
 
diff --git a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/dto/TaskIdDtoTest.java b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskIdDtoTest.java
similarity index 97%
rename from server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/dto/TaskIdDtoTest.java
rename to server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskIdDtoTest.java
index 3a593eb..1e41f5e 100644
--- a/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/dto/TaskIdDtoTest.java
+++ b/server/protocols/webadmin/webadmin-core/src/test/java/org/apache/james/webadmin/tasks/TaskIdDtoTest.java
@@ -17,7 +17,7 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.james.webadmin.dto;
+package org.apache.james.webadmin.tasks;
 
 import static org.eclipse.jetty.http.HttpHeader.LOCATION;
 import static org.mockito.Mockito.mock;


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


[james-project] 24/24: JAMES-2993 201 does only mean task generation success

Posted by bt...@apache.org.
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 4bfb763a941ddac6dbc56055144313c4a64f931d
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Mon Dec 16 15:29:21 2019 +0700

    JAMES-2993 201 does only mean task generation success
---
 src/site/markdown/server/manage-webadmin.md | 26 +++++++++++++-------------
 1 file changed, 13 insertions(+), 13 deletions(-)

diff --git a/src/site/markdown/server/manage-webadmin.md b/src/site/markdown/server/manage-webadmin.md
index 14c133b..d339699 100644
--- a/src/site/markdown/server/manage-webadmin.md
+++ b/src/site/markdown/server/manage-webadmin.md
@@ -1174,7 +1174,7 @@ Will scedule a task for :
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Unable to parse the body.
 
 The scheduled task will have the following type `mailbox-merging` and the following `additionalInformation`:
@@ -1988,7 +1988,7 @@ curl -XDELETE http://ip:port/mailRepositories/var%2Fmail%2Ferror%2F/mails
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 404: Could not find that mail repository
 
 The scheduled task will have the following type `clear-mail-repository` and the following `additionalInformation`:
@@ -2036,7 +2036,7 @@ Note that the `action` query parameter is compulsary and can only take value `re
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 404: Could not find that mail repository
 
 The scheduled task will have the following type `reprocessing-all` and the following `additionalInformation`:
@@ -2086,7 +2086,7 @@ Note that the `action` query parameter is compulsary and can only take value `re
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 404: Could not find that mail repository
 
 The scheduled task will have the following type `reprocessing-one` and the following `additionalInformation`:
@@ -2192,7 +2192,7 @@ The mails from the given mail queue matching the query parameter will be deleted
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Invalid request
  - 404: The mail queue does not exist
 
@@ -2221,7 +2221,7 @@ All mails from the given mail queue will be deleted.
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Invalid request
  - 404: The mail queue does not exist
 
@@ -2530,7 +2530,7 @@ Will schedule a task for reIndexing all the mails stored on this James server.
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Error in the request. Details can be found in the reported error.
 
 The scheduled task will have the following type `full-reindexing` and the following `additionalInformation`:
@@ -2565,7 +2565,7 @@ Will schedule a task for reIndexing all the mails in "bob@domain.com" mailboxes
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Error in the request. Details can be found in the reported error.
 
 The scheduled task will have the following type `user-reindexing` and the following `additionalInformation`:
@@ -2603,7 +2603,7 @@ Note that 'mailboxId' path parameter needs to be a (implementation dependent) va
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Error in the request. Details can be found in the reported error.
 
 The scheduled task will have the following type `mailbox-reindexing` and the following `additionalInformation`:
@@ -2641,7 +2641,7 @@ Will schedule a task for reIndexing all the mails that this task failed to reInd
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Error in the request. Details can be found in the reported error.
 
 The scheduled task will have the following type `error-recovery-indexation` and the following `additionalInformation`:
@@ -2671,7 +2671,7 @@ Note that 'mailboxId' path parameter needs to be a (implementation dependent) va
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Error in the request. Details can be found in the reported error.
 
 The scheduled task will have the following type `message-reindexing` and the following `additionalInformation`:
@@ -2701,7 +2701,7 @@ Note that 'messageId' path parameter needs to be a (implementation dependent) va
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - 400: Error in the request. Details can be found in the reported error.
 
 The scheduled task will have the following type `messageId-reindexing` and the following `additionalInformation`:
@@ -3241,7 +3241,7 @@ Location: /tasks/3294a976-ce63-491e-bd52-1b6f465ed7a2
 
 Response codes:
 
- - 201: Success. Corresponding task id is returned.
+ - 201: Task generation succeeded. Corresponding task id is returned.
  - Other response codes might be returned depending on the endpoint
 
 The additional information returned depends on the scheduled task type and is documented in the endpoint documentation.


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


[james-project] 16/24: JAMES-3006 Use Task generator in cassandra migration routes

Posted by bt...@apache.org.
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 444bc034d031824c0566ca5a80b61669599be44f
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Thu Dec 12 08:17:50 2019 +0100

    JAMES-3006 Use Task generator in cassandra migration routes
---
 .../webadmin/routes/CassandraMigrationRoutes.java   | 21 +++++++++------------
 1 file changed, 9 insertions(+), 12 deletions(-)

diff --git a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java
index c690059..ec1c2f7 100644
--- a/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java
+++ b/server/protocols/webadmin/webadmin-cassandra/src/main/java/org/apache/james/webadmin/routes/CassandraMigrationRoutes.java
@@ -27,12 +27,12 @@ import javax.ws.rs.Produces;
 
 import org.apache.james.backends.cassandra.migration.CassandraMigrationService;
 import org.apache.james.task.Task;
-import org.apache.james.task.TaskId;
 import org.apache.james.task.TaskManager;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.dto.CassandraVersionRequest;
 import org.apache.james.webadmin.dto.CassandraVersionResponse;
 import org.apache.james.webadmin.dto.TaskIdDto;
+import org.apache.james.webadmin.tasks.TaskGenerator;
 import org.apache.james.webadmin.utils.ErrorResponder;
 import org.apache.james.webadmin.utils.ErrorResponder.ErrorType;
 import org.apache.james.webadmin.utils.JsonTransformer;
@@ -48,7 +48,6 @@ import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
 import io.swagger.annotations.ResponseHeader;
 import spark.Request;
-import spark.Response;
 import spark.Service;
 
 @Api(tags = "Cassandra migration")
@@ -90,9 +89,11 @@ public class CassandraMigrationRoutes implements Routes {
 
         service.get(VERSION_BASE_LATEST, (request, response) -> getCassandraLatestVersion(), jsonTransformer);
 
-        service.post(VERSION_UPGRADE_BASE, this::upgradeToVersion, jsonTransformer);
+        TaskGenerator upgradeToVersionTaskGenerator = this::upgradeToVersion;
+        service.post(VERSION_UPGRADE_BASE, upgradeToVersionTaskGenerator.asRoute(taskManager), jsonTransformer);
 
-        service.post(VERSION_UPGRADE_TO_LATEST_BASE, (request, response) -> upgradeToLatest(response), jsonTransformer);
+        TaskGenerator upgradeToLatestTaskGenerator = request -> upgradeToLatest();
+        service.post(VERSION_UPGRADE_TO_LATEST_BASE, upgradeToLatestTaskGenerator.asRoute(taskManager), jsonTransformer);
     }
 
     @POST
@@ -105,11 +106,9 @@ public class CassandraMigrationRoutes implements Routes {
             }),
         @ApiResponse(code = HttpStatus.CONFLICT_409, message = "Migration can not be done")
     })
-    public Object upgradeToLatest(Response response) {
+    public Task upgradeToLatest() {
         try {
-            Task migration = cassandraMigrationService.upgradeToLastVersion();
-            TaskId taskId = taskManager.submit(migration);
-            return TaskIdDto.respond(response, taskId);
+            return cassandraMigrationService.upgradeToLastVersion();
         } catch (IllegalStateException e) {
             LOGGER.info(MIGRATION_REQUEST_CAN_NOT_BE_DONE, e);
             throw ErrorResponder.builder()
@@ -139,12 +138,10 @@ public class CassandraMigrationRoutes implements Routes {
         }),
         @ApiResponse(code = HttpStatus.CONFLICT_409, message = "Migration can not be done")
     })
-    public Object upgradeToVersion(Request request, Response response) {
+    public Task upgradeToVersion(Request request) {
         LOGGER.debug("Cassandra upgrade launched");
         CassandraVersionRequest cassandraVersionRequest = CassandraVersionRequest.parse(request.body());
-        Task migration = cassandraMigrationService.upgradeToVersion(cassandraVersionRequest.getValue());
-        TaskId taskId = taskManager.submit(migration);
-        return TaskIdDto.respond(response, taskId);
+        return cassandraMigrationService.upgradeToVersion(cassandraVersionRequest.getValue());
     }
 
     @GET


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