Sonar fix in mso-adapter-utils
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / infra / rest / handler / AbstractRestHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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.infra.rest.handler;
22
23 import java.io.IOException;
24 import java.net.URL;
25 import java.sql.Timestamp;
26 import java.util.HashMap;
27 import java.util.Optional;
28 import javax.ws.rs.container.ContainerRequestContext;
29 import org.apache.http.HttpStatus;
30 import org.onap.so.apihandler.common.ErrorNumbers;
31 import org.onap.so.apihandler.common.RequestClient;
32 import org.onap.so.apihandler.common.RequestClientFactory;
33 import org.onap.so.apihandler.common.RequestClientParameter;
34 import org.onap.so.apihandlerinfra.Action;
35 import org.onap.so.apihandlerinfra.Actions;
36 import org.onap.so.apihandlerinfra.Constants;
37 import org.onap.so.apihandlerinfra.MsoRequest;
38 import org.onap.so.apihandlerinfra.exceptions.ApiException;
39 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
40 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
41 import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException;
42 import org.onap.so.apihandlerinfra.infra.rest.exception.WorkflowEngineConnectionException;
43 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
44 import org.onap.so.constants.Status;
45 import org.onap.so.db.catalog.client.CatalogDbClient;
46 import org.onap.so.db.request.beans.InfraActiveRequests;
47 import org.onap.so.db.request.client.RequestsDbClient;
48 import org.onap.so.logger.ErrorCode;
49 import org.onap.so.logger.LogConstants;
50 import org.onap.so.logger.MessageEnum;
51 import org.onap.so.serviceinstancebeans.ModelType;
52 import org.onap.so.serviceinstancebeans.RequestReferences;
53 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
54 import org.onap.so.utils.UUIDChecker;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.slf4j.MDC;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.stereotype.Component;
60
61 @Component
62 public abstract class AbstractRestHandler {
63
64     private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class);
65
66     public static final String conflictFailMessage = "Error: Locked instance - This %s (%s) "
67             + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
68
69
70     @Autowired
71     protected CatalogDbClient catalogDbClient;
72
73     @Autowired
74     protected RequestsDbClient infraActiveRequestsClient;
75
76     @Autowired
77     protected RequestClientFactory reqClientFactory;
78
79     public String getRequestUri(ContainerRequestContext context) {
80         String requestUri = context.getUriInfo().getPath();
81         String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
82         MDC.put(LogConstants.HTTP_URL, httpUrl);
83         requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22);
84         return requestUri;
85     }
86
87     public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
88         String requestId = null;
89         if (requestContext.getProperty("requestId") != null) {
90             requestId = requestContext.getProperty("requestId").toString();
91         }
92         if (UUIDChecker.isValidUUID(requestId)) {
93             return requestId;
94         } else {
95             ErrorLoggerInfo errorLoggerInfo =
96                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
97                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
98             ValidateException validateException =
99                     new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
100                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
101                                     .errorInfo(errorLoggerInfo).build();
102
103             throw validateException;
104         }
105     }
106
107     public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
108             MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
109             throws ApiException {
110         return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq);
111     }
112
113     public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
114             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
115         InfraActiveRequests dup = null;
116         try {
117             if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance
118                     || action == Action.activateInstance || action == Action.assignInstance))) {
119                 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
120             }
121         } catch (Exception e) {
122             ErrorLoggerInfo errorLoggerInfo =
123                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
124                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
125             RequestDbFailureException requestDbFailureException =
126                     new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
127                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
128                                     .errorInfo(errorLoggerInfo).build();
129             updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
130             throw requestDbFailureException;
131         }
132         return dup;
133     }
134
135     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
136             throws RequestDbFailureException {
137         if (aq != null) {
138             if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
139                 aq.setStatusMessage(errorMessage);
140                 aq.setProgress(100L);
141                 aq.setRequestStatus(status.toString());
142                 Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
143                 aq.setEndTime(endTimeStamp);
144                 try {
145                     infraActiveRequestsClient.updateInfraActiveRequests(aq);
146                 } catch (Exception e) {
147                     logger.error("Error updating status", e);
148                 }
149             }
150         }
151     }
152
153
154
155     public void callWorkflowEngine(RequestClientParameter requestClientParameter, String orchestrationUri)
156             throws WorkflowEngineConnectionException {
157         RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationUri);
158         try {
159             requestClient.post(requestClientParameter);
160         } catch (IOException e) {
161             logger.error("Error Calling Workflow Engine", e);
162             throw new WorkflowEngineConnectionException("Error Calling Workflow Engine", e);
163         }
164     }
165
166     public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
167         Optional<URL> selfLinkUrl = Optional.empty();
168         String version = "";
169         try {
170             URL aUrl = new URL(url);
171             String aPath = aUrl.getPath();
172             if (aPath.indexOf("/v") == -1) {
173                 version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4);
174             } else {
175                 version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4);
176             }
177             String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
178             selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
179         } catch (Exception e) {
180             selfLinkUrl = Optional.empty(); // ignore
181             logger.info(e.getMessage());
182         }
183         return selfLinkUrl;
184     }
185
186     /**
187      * @param vfmoduleInstanceId
188      * @param requestId
189      * @param response
190      */
191     public ServiceInstancesResponse createResponse(String instanceId, String requestId,
192             ContainerRequestContext requestContext) {
193         ServiceInstancesResponse response = new ServiceInstancesResponse();
194         RequestReferences requestReferences = new RequestReferences();
195         requestReferences.setInstanceId(instanceId);
196         requestReferences.setRequestId(requestId);
197         Optional<URL> optionalUrl = buildSelfLinkUrl(getRequestUri(requestContext), requestId);
198         if (optionalUrl.isPresent()) {
199             requestReferences.setRequestSelfLink(optionalUrl.get());
200         }
201         response.setRequestReferences(requestReferences);
202         return response;
203     }
204
205     public void checkDuplicateRequest(HashMap<String, String> instanceIdMap, ModelType modelType, String instanceName,
206             String requestId) throws RequestConflictedException {
207         InfraActiveRequests conflictedRequest =
208                 infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString());
209         if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) {
210             throw new RequestConflictedException(String.format(conflictFailMessage, modelType.toString(), instanceName,
211                     conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId()));
212         }
213     }
214
215
216
217 }