Replaced all tabs with spaces in java and pom.xml
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / CloudResourcesOrchestration.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.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import javax.transaction.Transactional;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.GET;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.MultivaluedMap;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriInfo;
42 import org.apache.http.HttpStatus;
43 import org.onap.so.apihandler.common.ErrorNumbers;
44 import org.onap.so.apihandler.common.ResponseBuilder;
45 import org.onap.so.apihandlerinfra.Constants;
46 import org.onap.so.apihandlerinfra.exceptions.ApiException;
47 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
48 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
49 import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationRequestList;
50 import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationResponse;
51 import org.onap.so.apihandlerinfra.tenantisolationbeans.InstanceReferences;
52 import org.onap.so.apihandlerinfra.tenantisolationbeans.Request;
53 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails;
54 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestStatus;
55 import org.onap.so.db.request.beans.InfraActiveRequests;
56 import org.onap.so.db.request.client.RequestsDbClient;
57 import org.onap.so.exceptions.ValidationException;
58 import org.onap.so.logger.ErrorCode;
59 import org.onap.so.logger.MessageEnum;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Component;
64 import com.fasterxml.jackson.databind.ObjectMapper;
65 import io.swagger.annotations.Api;
66 import io.swagger.annotations.ApiOperation;
67
68 @Component
69 @Path("onap/so/infra/cloudResourcesRequests")
70 @Api(value = "onap/so/infra/cloudResourcesRequests",
71         description = "API GET Requests for cloud resources - Tenant Isolation")
72 public class CloudResourcesOrchestration {
73
74     private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class);
75
76     @Autowired
77     RequestsDbClient requestDbClient;
78
79     @Autowired
80     private ResponseBuilder builder;
81
82     @POST
83     @Path("/{version: [vV][1]}/{requestId}/unlock")
84     @Consumes(MediaType.APPLICATION_JSON)
85     @Produces(MediaType.APPLICATION_JSON)
86     @ApiOperation(value = "Unlock CloudOrchestration requests for a specified requestId")
87     @Transactional
88     public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId,
89             @PathParam("version") String version) throws ApiException {
90         TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId);
91         InfraActiveRequests infraActiveRequest = null;
92
93         CloudOrchestrationRequest cor = null;
94
95         logger.debug("requestId is: " + requestId);
96
97         try {
98             ObjectMapper mapper = new ObjectMapper();
99             cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
100         } catch (IOException e) {
101             ErrorLoggerInfo errorLoggerInfo =
102                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
103                             .build();
104
105             ValidateException validateException =
106                     new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
107                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
108                                     .errorInfo(errorLoggerInfo).build();
109             throw validateException;
110         }
111
112         try {
113             msoRequest.parseOrchestration(cor);
114         } catch (ValidationException e) {
115             ErrorLoggerInfo errorLoggerInfo =
116                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
117                             .build();
118             ValidateException validateException =
119                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
120                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
121             throw validateException;
122         }
123         try {
124             infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
125         } catch (Exception e) {
126             ValidateException validateException = new ValidateException.Builder(e.getMessage(),
127                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build();
128             throw validateException;
129         }
130         if (infraActiveRequest == null) {
131
132             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
133                     ErrorCode.BusinessProcesssError).build();
134             ValidateException validateException =
135                     new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
136                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
137                                     .errorInfo(errorLoggerInfo).build();
138
139             throw validateException;
140
141         } else {
142             String status = infraActiveRequest.getRequestStatus();
143             if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING")
144                     || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) {
145                 infraActiveRequest.setRequestStatus("UNLOCKED");
146                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
147                 infraActiveRequest.setRequestId(requestId);
148                 requestDbClient.save(infraActiveRequest);
149             } else {
150                 ErrorLoggerInfo errorLoggerInfo =
151                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
152                                 .build();
153                 ValidateException validateException = new ValidateException.Builder(
154                         "Orchestration RequestId " + requestId + " has a status of " + status
155                                 + " and can not be unlocked",
156                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
157                                 .build();
158
159                 throw validateException;
160             }
161         }
162
163         return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build();
164     }
165
166     @GET
167     @Path("/{version:[vV][1]}")
168     @Consumes(MediaType.APPLICATION_JSON)
169     @Produces(MediaType.APPLICATION_JSON)
170     @ApiOperation(value = "Get status of an Operational Environment based on filter criteria",
171             response = Response.class)
172     @Transactional
173     public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version)
174             throws ApiException {
175
176         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
177         List<String> requestIdKey = queryParams.get("requestId");
178         String apiVersion = version.substring(1);
179
180         if (queryParams.size() == 1 && requestIdKey != null) {
181             String requestId = requestIdKey.get(0);
182
183             CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
184             TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest(requestId);
185             InfraActiveRequests requestDB = null;
186
187             try {
188                 requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
189             } catch (Exception e) {
190                 ErrorLoggerInfo errorLoggerInfo =
191                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError)
192                                 .build();
193                 ValidateException validateException =
194                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
195                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
196                 throw validateException;
197             }
198
199             if (requestDB == null) {
200                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
201                         ErrorCode.BusinessProcesssError).build();
202                 ValidateException validateException =
203                         new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
204                                 HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
205                                         .errorInfo(errorLoggerInfo).build();
206
207                 throw validateException;
208             }
209
210             Request request = mapInfraActiveRequestToRequest(requestDB);
211             cloudOrchestrationGetResponse.setRequest(request);
212             return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
213
214         } else {
215             TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest();
216             List<InfraActiveRequests> activeRequests = null;
217             CloudOrchestrationRequestList orchestrationList = null;
218
219
220             Map<String, String> orchestrationMap;
221             try {
222                 orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
223             } catch (ValidationException ex) {
224                 ErrorLoggerInfo errorLoggerInfo =
225                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
226                                 .build();
227                 ValidateException validateException =
228                         new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
229                                 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
230
231                 throw validateException;
232
233             }
234             activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
235             orchestrationList = new CloudOrchestrationRequestList();
236             List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
237
238             for (InfraActiveRequests infraActive : activeRequests) {
239
240                 Request request = mapInfraActiveRequestToRequest(infraActive);
241                 CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
242                 requestList.setRequest(request);
243                 requestLists.add(requestList);
244             }
245             orchestrationList.setRequestList(requestLists);
246
247             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
248         }
249     }
250
251     private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
252         Request request = new Request();
253         request.setRequestId(iar.getRequestId());
254         request.setRequestScope(iar.getRequestScope());
255         request.setRequestType(iar.getRequestAction());
256
257         InstanceReferences ir = new InstanceReferences();
258
259         if (iar.getOperationalEnvId() != null)
260             ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
261         if (iar.getOperationalEnvName() != null)
262             ir.setOperationalEnvName(iar.getOperationalEnvName());
263         if (iar.getRequestorId() != null)
264             ir.setRequestorId(iar.getRequestorId());
265
266         request.setInstanceReferences(ir);
267         String requestBody = iar.getRequestBody();
268         RequestDetails requestDetails = null;
269
270         if (requestBody != null) {
271             try {
272                 ObjectMapper mapper = new ObjectMapper();
273                 requestDetails = mapper.readValue(requestBody, RequestDetails.class);
274             } catch (IOException e) {
275                 ErrorLoggerInfo errorLoggerInfo =
276                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
277                                 .build();
278                 ValidateException validateException =
279                         new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
280                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
281                                         .errorInfo(errorLoggerInfo).build();
282                 throw validateException;
283             }
284         }
285
286         request.setRequestDetails(requestDetails);
287         String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
288         request.setStartTime(startTimeStamp);
289
290         RequestStatus status = new RequestStatus();
291         if (iar.getStatusMessage() != null) {
292             status.setStatusMessage(iar.getStatusMessage());
293         }
294
295         if (iar.getEndTime() != null) {
296             String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
297             status.setTimeStamp(endTimeStamp);
298         }
299
300         if (iar.getRequestStatus() != null) {
301             status.setRequestState(iar.getRequestStatus());
302         }
303
304         if (iar.getProgress() != null) {
305             status.setPercentProgress(iar.getProgress().toString());
306         }
307
308         request.setRequestStatus(status);
309
310         return request;
311     }
312
313 }