1   /*
2    * Copyright 2018 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package com.linecorp.centraldogma.server.internal.api.converter;
18  
19  import static com.google.common.base.Preconditions.checkArgument;
20  import static com.google.common.base.Strings.isNullOrEmpty;
21  
22  import java.lang.reflect.ParameterizedType;
23  
24  import javax.annotation.Nullable;
25  
26  import com.fasterxml.jackson.databind.JsonNode;
27  
28  import com.linecorp.armeria.common.AggregatedHttpRequest;
29  import com.linecorp.armeria.server.ServiceRequestContext;
30  import com.linecorp.armeria.server.annotation.JacksonRequestConverterFunction;
31  import com.linecorp.armeria.server.annotation.RequestConverterFunction;
32  import com.linecorp.centraldogma.internal.Jackson;
33  import com.linecorp.centraldogma.internal.api.v1.CommitMessageDto;
34  
35  /**
36   * A request converter that converts to {@link CommitMessageDto}.
37   */
38  public final class CommitMessageRequestConverter implements RequestConverterFunction {
39  
40      private final JacksonRequestConverterFunction delegate = new JacksonRequestConverterFunction();
41  
42      @Override
43      public CommitMessageDto convertRequest(
44              ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
45              @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {
46  
47          if (expectedResultType == CommitMessageDto.class) {
48              final JsonNode node = (JsonNode) delegate.convertRequest(ctx, request, JsonNode.class, null);
49              if (node == null || node.get("commitMessage") == null) {
50                  throw new IllegalArgumentException("commitMessage should be non-null.");
51              }
52  
53              return convertCommitMessage(node.get("commitMessage"));
54          }
55          return RequestConverterFunction.fallthrough();
56      }
57  
58      private static CommitMessageDto convertCommitMessage(JsonNode jsonNode) {
59          final CommitMessageDto commitMessage = Jackson.convertValue(jsonNode, CommitMessageDto.class);
60          checkArgument(!isNullOrEmpty(commitMessage.summary()), "summary should be non-null");
61          return commitMessage;
62      }
63  }