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