added generic fabric support to SO
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / OrchestrationRequests.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;
22
23 import java.io.IOException;
24 import java.text.SimpleDateFormat;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
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
43 import org.apache.commons.lang.StringUtils;
44 import org.apache.http.HttpStatus;
45 import org.onap.so.apihandler.common.ErrorNumbers;
46 import org.onap.so.apihandler.common.ResponseBuilder;
47 import org.onap.so.apihandlerinfra.exceptions.ApiException;
48 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
49 import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo;
50 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
51 import org.onap.so.db.request.beans.InfraActiveRequests;
52 import org.onap.so.db.request.beans.RequestProcessingData;
53 import org.onap.so.db.request.client.RequestsDbClient;
54 import org.onap.so.exceptions.ValidationException;
55 import org.onap.so.logger.MessageEnum;
56 import org.onap.so.logger.MsoAlarmLogger;
57 import org.onap.so.logger.MsoLogger;
58 import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse;
59 import org.onap.so.serviceinstancebeans.GetOrchestrationResponse;
60 import org.onap.so.serviceinstancebeans.InstanceReferences;
61 import org.onap.so.serviceinstancebeans.Request;
62 import org.onap.so.serviceinstancebeans.RequestDetails;
63 import org.onap.so.serviceinstancebeans.RequestList;
64 import org.onap.so.serviceinstancebeans.RequestStatus;
65 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.stereotype.Component;
68
69 import com.fasterxml.jackson.databind.ObjectMapper;
70
71 import io.swagger.annotations.Api;
72 import io.swagger.annotations.ApiOperation;
73
74 @Path("onap/so/infra/orchestrationRequests")
75 @Api(value="onap/so/infra/orchestrationRequests",description="API Requests for Orchestration requests")
76 @Component
77 public class OrchestrationRequests {
78
79     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, OrchestrationRequests.class);
80     
81
82     @Autowired
83         private RequestsDbClient requestsDbClient;
84
85     @Autowired
86     private MsoRequest msoRequest;
87     
88         @Autowired
89         private ResponseBuilder builder;
90
91         @GET
92         @Path("/{version:[vV][4-7]}/{requestId}")
93         @ApiOperation(value="Find Orchestrated Requests for a given requestId",response=Response.class)
94         @Produces(MediaType.APPLICATION_JSON)
95         @Transactional
96         public Response getOrchestrationRequest(@PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
97
98                 String apiVersion = version.substring(1);
99                 GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse();
100
101
102                 InfraActiveRequests infraActiveRequest = null;
103                 List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null;
104                 try {
105                         infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
106                 requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId);
107
108                 } catch (Exception e) {
109                     msoLogger.error(e);
110                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build();
111                         AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build();
112
113
114
115                         ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup",
116                                         HttpStatus.SC_NOT_FOUND,ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e).errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build();
117
118                         throw validateException;
119
120                 }
121                 
122         if(infraActiveRequest == null) {
123
124             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
125
126
127             ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
128                     HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
129
130             throw validateException;
131         }
132         
133         Request request = mapInfraActiveRequestToRequest(infraActiveRequest);
134         if(!requestProcessingData.isEmpty()){
135             request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
136         }
137                 request.setRequestId(requestId);
138         orchestrationResponse.setRequest(request);
139         
140         return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion);
141         }
142
143         @GET
144         @Path("/{version:[vV][4-7]}")
145         @ApiOperation(value="Find Orchestrated Requests for a URI Information",response=Response.class)
146         @Produces(MediaType.APPLICATION_JSON)
147         @Transactional
148         public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) throws ApiException{
149
150                 long startTime = System.currentTimeMillis ();
151                 
152                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
153
154                 List<InfraActiveRequests> activeRequests = null;
155
156                 GetOrchestrationListResponse orchestrationList = null;
157                 Map<String, List<String>> orchestrationMap;
158                 String apiVersion = version.substring(1);
159                 
160                 try {
161                         orchestrationMap = msoRequest.getOrchestrationFilters(queryParams);
162                         if (orchestrationMap.isEmpty()) {
163                                 throw new ValidationException("At least one filter query param must be specified");
164                         }
165                 }catch(ValidationException ex){
166                     msoLogger.error(ex);
167                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.DataError).build();
168                         ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
169                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
170                         throw validateException;
171
172                 }
173                         
174                 activeRequests = requestsDbClient.getOrchestrationFiltersFromInfraActive(orchestrationMap);
175
176                 orchestrationList = new GetOrchestrationListResponse();
177                 List<RequestList> requestLists = new ArrayList<>();
178                 
179                 for(InfraActiveRequests infraActive : activeRequests){
180                         List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId());
181                         RequestList requestList = new RequestList();
182                         Request request = mapInfraActiveRequestToRequest(infraActive);
183                         if(!requestProcessingData.isEmpty()){
184                                 request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
185                 }
186                         requestList.setRequest(request);
187                         requestLists.add(requestList);
188                 }
189
190                 orchestrationList.setRequestList(requestLists);
191                 return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
192         }
193
194
195         @POST
196         @Path("/{version: [vV][4-7]}/{requestId}/unlock")
197         @Consumes(MediaType.APPLICATION_JSON)
198         @Produces(MediaType.APPLICATION_JSON)
199         @ApiOperation(value="Unlock Orchestrated Requests for a given requestId",response=Response.class)
200         @Transactional
201         public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
202
203                 long startTime = System.currentTimeMillis ();
204                 msoLogger.debug ("requestId is: " + requestId);
205                 ServiceInstancesRequest sir = null;
206
207                 InfraActiveRequests infraActiveRequest = null;
208                 Request request = null;
209                 
210                 try{
211                         ObjectMapper mapper = new ObjectMapper();
212                         sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
213                 } catch(IOException e){
214                     msoLogger.error(e);
215             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
216             ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
217                     HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
218
219             throw validateException;
220
221                 }
222                 try{
223                         msoRequest.parseOrchestration(sir);
224                 } catch (Exception e) {
225                     msoLogger.error(e);
226                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
227                          ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
228                          .errorInfo(errorLoggerInfo).build();
229             throw validateException;
230                 }
231
232                 infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
233                 if(infraActiveRequest == null) {
234                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MsoLogger.ErrorCode.BusinessProcesssError).build();
235
236
237                         ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId",
238                                         HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
239
240                         throw validateException;
241
242                 }else{
243                         String status = infraActiveRequest.getRequestStatus();
244                         if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){
245                                 infraActiveRequest.setRequestStatus("UNLOCKED");
246                                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
247                                 infraActiveRequest.setRequestId(requestId);
248                                 requestsDbClient.save(infraActiveRequest);
249                         }else{
250
251                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MsoLogger.ErrorCode.DataError).build();
252
253
254                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
255                                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
256
257                                 throw validateException;
258                         }
259                 }
260                 return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
261         }
262
263     private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar)  throws ApiException{
264
265         String requestBody = iar.getRequestBody();
266         Request request = new Request();
267         
268         ObjectMapper mapper = new ObjectMapper();      
269
270        request.setRequestId(iar.getRequestId());
271        request.setRequestScope(iar.getRequestScope());
272        request.setRequestType(iar.getRequestAction());
273
274        InstanceReferences ir = new InstanceReferences();
275        if(iar.getNetworkId() != null)
276         ir.setNetworkInstanceId(iar.getNetworkId());
277        if(iar.getNetworkName() != null)
278         ir.setNetworkInstanceName(iar.getNetworkName());
279        if(iar.getServiceInstanceId() != null)
280         ir.setServiceInstanceId(iar.getServiceInstanceId());
281        if(iar.getServiceInstanceName() != null)
282         ir.setServiceInstanceName(iar.getServiceInstanceName());
283        if(iar.getVfModuleId() != null)
284         ir.setVfModuleInstanceId(iar.getVfModuleId());
285        if(iar.getVfModuleName() != null)
286         ir.setVfModuleInstanceName(iar.getVfModuleName());
287        if(iar.getVnfId() != null)
288         ir.setVnfInstanceId(iar.getVnfId());
289        if(iar.getVnfName() != null)
290         ir.setVnfInstanceName(iar.getVnfName());
291        if(iar.getVolumeGroupId() != null)
292         ir.setVolumeGroupInstanceId(iar.getVolumeGroupId());
293        if(iar.getVolumeGroupName() != null)
294         ir.setVolumeGroupInstanceName(iar.getVolumeGroupName());
295                 if(iar.getRequestorId() != null)
296                         ir.setRequestorId(iar.getRequestorId());
297
298
299                 request.setInstanceReferences(ir);
300
301        RequestDetails requestDetails = null;
302
303        if(StringUtils.isNotBlank(requestBody)) {
304                    try {
305                            if(requestBody.contains("\"requestDetails\":")){
306                                    ServiceInstancesRequest sir = mapper.readValue(requestBody, ServiceInstancesRequest.class);
307                                    requestDetails = sir.getRequestDetails();
308                            } else {
309                                    requestDetails = mapper.readValue(requestBody, RequestDetails.class);
310                            }
311                    } catch (IOException e) {
312                        msoLogger.error(e);
313                            ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
314                            ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : ",
315                                            HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
316
317                            throw validateException;
318                    }
319            }
320        request.setRequestDetails(requestDetails);
321        
322        if(iar.getStartTime() != null) {
323                String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
324                request.setStartTime(startTimeStamp);
325        }
326
327        RequestStatus status = new RequestStatus();
328        if(iar.getStatusMessage() != null){
329            status.setStatusMessage(iar.getStatusMessage());
330        }
331
332        if(iar.getEndTime() != null){
333            String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
334            status.setFinishTime(endTimeStamp);
335        }
336
337
338        if(iar.getRequestStatus() != null){
339            status.setRequestState(iar.getRequestStatus());
340        }
341
342        if(iar.getProgress() != null){
343            status.setPercentProgress(iar.getProgress().intValue());
344        }
345
346        request.setRequestStatus(status);
347
348        return request;
349    }
350    
351    public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData(List<org.onap.so.db.request.beans.RequestProcessingData> processingData){
352            List<org.onap.so.serviceinstancebeans.RequestProcessingData> addedRequestProcessingData = new ArrayList<>();
353            org.onap.so.serviceinstancebeans.RequestProcessingData finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData();
354            String currentGroupingId = null;
355            HashMap<String, String> tempMap = new HashMap<>();
356            List<HashMap<String, String>> tempList = new ArrayList<>();
357            for(RequestProcessingData data : processingData){
358                    String groupingId = data.getGroupingId();
359                    String tag = data.getTag();
360                    if(currentGroupingId == null || !currentGroupingId.equals(groupingId)){
361                            if(!tempMap.isEmpty()){
362                                    tempList.add(tempMap);
363                                    finalProcessingData.setDataPairs(tempList);
364                                    addedRequestProcessingData.add(finalProcessingData);
365                            }
366                            finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData();
367                            if(groupingId != null){
368                                    finalProcessingData.setGroupingId(groupingId);
369                            }
370                            if(tag != null){
371                                    finalProcessingData.setTag(tag);
372                            }
373                            currentGroupingId = groupingId;
374                            tempMap = new HashMap<>();
375                            tempList = new ArrayList<>();
376                            if(data.getName() != null && data.getValue() != null){
377                                    tempMap.put(data.getName(), data.getValue());
378                            }
379                    }else{
380                            if(data.getName() != null && data.getValue() != null){
381                                    tempMap.put(data.getName(), data.getValue());
382                            }
383                    }
384            }
385            if(tempMap.size() > 0){
386                    tempList.add(tempMap);
387                    finalProcessingData.setDataPairs(tempList);
388            }
389            addedRequestProcessingData.add(finalProcessingData);
390            return addedRequestProcessingData;
391    }
392  }