[SO] Release so 1.13.0 image
[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     @Autowired
74     private Provider<TenantIsolationRunnable> tenantIsolationRunnable;
75
76     @PATCH
77     @Path("/{version:[vV][1]}/distributions/{distributionId}")
78     @Consumes(MediaType.APPLICATION_JSON)
79     @Produces(MediaType.APPLICATION_JSON)
80     @Operation(description = "Update model distribution status", responses = @ApiResponse(
81             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
82     @Transactional
83     public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version,
84             @PathParam("distributionId") String distributionId) throws ApiException {
85         Distribution distributionRequest;
86
87         try {
88             ObjectMapper mapper = new ObjectMapper();
89             distributionRequest = mapper.readValue(requestJSON, Distribution.class);
90         } catch (IOException e) {
91             ErrorLoggerInfo errorLoggerInfo =
92                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
93                             .build();
94
95
96             ValidateException validateException =
97                     new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
98                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
99                                     .errorInfo(errorLoggerInfo).build();
100             throw validateException;
101
102         }
103
104         try {
105             parse(distributionRequest);
106         } catch (ValidationException e) {
107
108             ErrorLoggerInfo errorLoggerInfo =
109                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
110                             .build();
111
112
113             ValidateException validateException =
114                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
115                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
116             throw validateException;
117         }
118
119         CloudOrchestrationRequest cor = new CloudOrchestrationRequest();
120         cor.setDistribution(distributionRequest);
121         cor.setDistributionId(distributionId);
122
123         TenantIsolationRunnable runnable = tenantIsolationRunnable.get();
124         runnable.run(Action.distributionStatus, null, cor, null);
125
126         return Response.ok().build();
127     }
128
129     private void parse(Distribution distributionRequest) throws ValidationException {
130         if (distributionRequest.getStatus() == null) {
131             throw new ValidationException("status");
132         }
133
134         if (StringUtils.isBlank(distributionRequest.getErrorReason())
135                 && Status.DISTRIBUTION_COMPLETE_ERROR.equals(distributionRequest.getStatus())) {
136             throw new ValidationException("errorReason");
137         }
138     }
139
140     private Response buildServiceErrorResponse(int httpResponseCode, MsoException exceptionType, String text,
141             String messageId, List<String> variables) throws ApiException {
142         RequestError re = new RequestError();
143         ServiceException se = new ServiceException();
144         se.setMessageId(messageId);
145         se.setText(text);
146         if (variables != null) {
147             for (String variable : variables) {
148                 se.getVariables().add(variable);
149             }
150         }
151         re.setServiceException(se);
152
153         String requestErrorStr;
154         try {
155             ObjectMapper mapper = new ObjectMapper();
156             mapper.setSerializationInclusion(Include.NON_DEFAULT);
157             requestErrorStr = mapper.writeValueAsString(re);
158         } catch (JsonProcessingException e) {
159
160             ErrorLoggerInfo errorLoggerInfo =
161                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.DataError).build();
162
163
164             ValidateException validateException =
165                     new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
166                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
167                                     .errorInfo(errorLoggerInfo).build();
168             throw validateException;
169         }
170
171         return Response.status(httpResponseCode).entity(requestErrorStr).build();
172     }
173 }