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