2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.so.apihandlerinfra.infra.rest.handler;
23 import java.io.IOException;
25 import java.sql.Timestamp;
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;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.stereotype.Component;
62 public abstract class AbstractRestHandler {
64 private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class);
66 public static final String CONFLICT_FAIL_MESSAGE = "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.";
71 protected CatalogDbClient catalogDbClient;
74 protected RequestsDbClient infraActiveRequestsClient;
77 protected RequestClientFactory reqClientFactory;
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);
87 public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
88 String requestId = null;
89 if (requestContext.getProperty("requestId") != null) {
90 requestId = requestContext.getProperty("requestId").toString();
92 if (UUIDChecker.isValidUUID(requestId)) {
95 ErrorLoggerInfo errorLoggerInfo =
96 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
97 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
98 throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
99 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
104 public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
105 MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
106 throws ApiException {
107 return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq);
110 public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
111 String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
112 InfraActiveRequests dup = null;
114 if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance
115 || action == Action.activateInstance || action == Action.assignInstance))) {
116 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
118 } catch (Exception e) {
119 ErrorLoggerInfo errorLoggerInfo =
120 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
121 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
122 RequestDbFailureException requestDbFailureException =
123 new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
124 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
125 .errorInfo(errorLoggerInfo).build();
126 updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
127 throw requestDbFailureException;
132 public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
133 throws RequestDbFailureException {
134 if ((aq != null) && ((status == Status.FAILED) || (status == Status.COMPLETE))) {
136 aq.setStatusMessage(errorMessage);
137 aq.setProgress(100L);
138 aq.setRequestStatus(status.toString());
139 Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
140 aq.setEndTime(endTimeStamp);
142 infraActiveRequestsClient.updateInfraActiveRequests(aq);
143 } catch (Exception e) {
144 logger.error("Error updating status", e);
152 public void callWorkflowEngine(RequestClientParameter requestClientParameter, String orchestrationUri)
153 throws WorkflowEngineConnectionException {
154 RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationUri);
156 requestClient.post(requestClientParameter);
157 } catch (IOException e) {
158 logger.error("Error Calling Workflow Engine", e);
159 throw new WorkflowEngineConnectionException("Error Calling Workflow Engine", e);
163 public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
164 Optional<URL> selfLinkUrl = Optional.empty();
167 URL aUrl = new URL(url);
168 String aPath = aUrl.getPath();
169 if (aPath.indexOf("/v") == -1) {
170 version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4);
172 version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4);
174 String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
175 selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
176 } catch (Exception e) {
177 selfLinkUrl = Optional.empty(); // ignore
178 logger.error(e.getMessage());
186 * @param requestContext
188 public ServiceInstancesResponse createResponse(String instanceId, String requestId,
189 ContainerRequestContext requestContext) {
190 ServiceInstancesResponse response = new ServiceInstancesResponse();
191 RequestReferences requestReferences = new RequestReferences();
192 requestReferences.setInstanceId(instanceId);
193 requestReferences.setRequestId(requestId);
194 Optional<URL> optionalUrl = buildSelfLinkUrl(getRequestUri(requestContext), requestId);
195 if (optionalUrl.isPresent()) {
196 requestReferences.setRequestSelfLink(optionalUrl.get());
198 response.setRequestReferences(requestReferences);
202 public void checkDuplicateRequest(Map<String, String> instanceIdMap, ModelType modelType, String instanceName,
203 String requestId) throws RequestConflictedException {
204 InfraActiveRequests conflictedRequest =
205 infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString());
206 if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) {
207 throw new RequestConflictedException(String.format(CONFLICT_FAIL_MESSAGE, modelType.toString(),
208 instanceName, conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId()));