Update vulnerable dependencies
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / ModelDistributionRequest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.apihandlerinfra.tenantisolation;
24
25 import java.io.IOException;
26 import java.util.List;
27 import javax.inject.Provider;
28 import javax.transaction.Transactional;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.PATCH;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.PathParam;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.Response;
36 import org.apache.commons.lang3.StringUtils;
37 import org.apache.http.HttpStatus;
38 import org.onap.so.apihandler.common.ErrorNumbers;
39 import org.onap.so.apihandlerinfra.MsoException;
40 import org.onap.so.apihandlerinfra.exceptions.ApiException;
41 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
42 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
43 import org.onap.so.apihandlerinfra.tenantisolationbeans.Action;
44 import org.onap.so.apihandlerinfra.tenantisolationbeans.Distribution;
45 import org.onap.so.apihandlerinfra.tenantisolationbeans.Status;
46 import org.onap.so.exceptions.ValidationException;
47 import org.onap.logging.filter.base.ErrorCode;
48 import org.onap.so.logger.MessageEnum;
49 import org.onap.so.serviceinstancebeans.RequestError;
50 import org.onap.so.serviceinstancebeans.ServiceException;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.stereotype.Component;
55 import com.fasterxml.jackson.annotation.JsonInclude.Include;
56 import com.fasterxml.jackson.core.JsonProcessingException;
57 import com.fasterxml.jackson.databind.ObjectMapper;
58 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
59 import io.swagger.v3.oas.annotations.Operation;
60 import io.swagger.v3.oas.annotations.info.Info;
61 import io.swagger.v3.oas.annotations.media.ArraySchema;
62 import io.swagger.v3.oas.annotations.media.Content;
63 import io.swagger.v3.oas.annotations.media.Schema;
64 import io.swagger.v3.oas.annotations.responses.ApiResponse;
65
66 @Component
67 @Path("/onap/so/infra/modelDistributions")
68 @OpenAPIDefinition(
69         info = @Info(title = "/onap/so/infra/modelDistributions", description = "API Requests for Model Distributions"))
70 public class ModelDistributionRequest {
71
72     private static Logger logger = LoggerFactory.getLogger(ModelDistributionRequest.class);
73     private static final ObjectMapper mapper = new ObjectMapper();
74
75     @Autowired
76     private Provider<TenantIsolationRunnable> tenantIsolationRunnable;
77
78     @PATCH
79     @Path("/{version:[vV][1]}/distributions/{distributionId}")
80     @Consumes(MediaType.APPLICATION_JSON)
81     @Produces(MediaType.APPLICATION_JSON)
82     @Operation(description = "Update model distribution status", responses = @ApiResponse(
83             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
84     @Transactional
85     public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version,
86             @PathParam("distributionId") String distributionId) throws ApiException {
87         Distribution distributionRequest;
88
89         try {
90             distributionRequest = mapper.readValue(requestJSON, Distribution.class);
91         } catch (IOException e) {
92             ErrorLoggerInfo errorLoggerInfo =
93                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
94                             .build();
95
96
97             ValidateException validateException =
98                     new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
99                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
100                                     .errorInfo(errorLoggerInfo).build();
101             throw validateException;
102
103         }
104
105         try {
106             parse(distributionRequest);
107         } catch (ValidationException e) {
108
109             ErrorLoggerInfo errorLoggerInfo =
110                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
111                             .build();
112
113
114             ValidateException validateException =
115                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
116                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
117             throw validateException;
118         }
119
120         CloudOrchestrationRequest cor = new CloudOrchestrationRequest();
121         cor.setDistribution(distributionRequest);
122         cor.setDistributionId(distributionId);
123
124         TenantIsolationRunnable runnable = tenantIsolationRunnable.get();
125         runnable.run(Action.distributionStatus, null, cor, null);
126
127         return Response.ok().build();
128     }
129
130     private void parse(Distribution distributionRequest) throws ValidationException {
131         if (distributionRequest.getStatus() == null) {
132             throw new ValidationException("status");
133         }
134
135         if (StringUtils.isBlank(distributionRequest.getErrorReason())
136                 && Status.DISTRIBUTION_COMPLETE_ERROR.equals(distributionRequest.getStatus())) {
137             throw new ValidationException("errorReason");
138         }
139     }
140
141     private Response buildServiceErrorResponse(int httpResponseCode, MsoException exceptionType, String text,
142             String messageId, List<String> variables) throws ApiException {
143         RequestError re = new RequestError();
144         ServiceException se = new ServiceException();
145         se.setMessageId(messageId);
146         se.setText(text);
147         if (variables != null) {
148             for (String variable : variables) {
149                 se.getVariables().add(variable);
150             }
151         }
152         re.setServiceException(se);
153
154         String requestErrorStr;
155         try {
156             ObjectMapper mapper = new ObjectMapper();
157             mapper.setSerializationInclusion(Include.NON_DEFAULT);
158             requestErrorStr = mapper.writeValueAsString(re);
159         } catch (JsonProcessingException e) {
160
161             ErrorLoggerInfo errorLoggerInfo =
162                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.DataError).build();
163
164
165             ValidateException validateException =
166                     new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
167                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
168                                     .errorInfo(errorLoggerInfo).build();
169             throw validateException;
170         }
171
172         return Response.status(httpResponseCode).entity(requestErrorStr).build();
173     }
174 }