25ae6fb4b91cdb8a6087ce1296245489a972f3f2
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / externalapi / servlet / ServiceActivationServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 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.openecomp.sdc.be.externalapi.servlet;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.jcabi.aspects.Loggable;
25 import fj.data.Either;
26 import io.swagger.annotations.*;
27 import org.apache.commons.lang3.StringUtils;
28 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
29 import org.openecomp.sdc.be.config.BeEcompErrorManager;
30 import org.openecomp.sdc.be.dao.api.ActionStatus;
31 import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
32 import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo;
33 import org.openecomp.sdc.be.model.User;
34 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
35 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
36 import org.openecomp.sdc.be.servlets.RepresentationUtils;
37 import org.openecomp.sdc.common.api.Constants;
38 import org.openecomp.sdc.common.datastructure.Wrapper;
39 import org.openecomp.sdc.common.log.wrappers.Logger;
40 import org.openecomp.sdc.exception.ResponseFormat;
41
42 import javax.inject.Singleton;
43 import javax.servlet.ServletContext;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.ws.rs.*;
46 import javax.ws.rs.core.Context;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.Response;
49 import java.io.IOException;
50
51 /**
52  * Created by chaya on 10/17/2017.
53  */
54 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
55 @Path("/v1/catalog")
56 @Api(value = "Service Activation External Servlet", description = "This Servlet serves external users for activating a specific service")
57 @Singleton
58 public class ServiceActivationServlet extends AbstractValidationsServlet {
59
60     @Context
61     private HttpServletRequest request;
62
63     private static final Logger log = Logger.getLogger(ServiceActivationServlet.class);
64
65     /**
66      * Activates a service on a specific environment
67      *
68      * @param serviceUUID
69      * @param opEnvId
70      * @param userId
71      * @param instanceIdHeader
72      * @return
73      */
74     @POST
75     @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate")
76     @Consumes(MediaType.APPLICATION_JSON)
77     @Produces(MediaType.APPLICATION_JSON)
78     @ApiOperation(value = "activate a service", httpMethod = "POST", notes = "Activates a service")
79     @ApiResponses(value = {
80             @ApiResponse(code = 202, message = "ECOMP component is authenticated and required service may be distributed"),
81             @ApiResponse(code = 400, message = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
82             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
83             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
84             @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
85             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
86             @ApiResponse(code = 500, message = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
87             @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
88             @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"),
89             @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"),
90             @ApiResponse(code = 409, message = "Service state is invalid for this action"),
91             @ApiResponse(code = 502, message = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})
92     public Response activateServiceExternal(
93             @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
94             @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
95             @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
96             @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
97             @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
98             @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
99             @ApiParam(value = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID,
100             @ApiParam(value = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId,
101             String data) {
102
103         init();
104
105         ResponseFormat responseFormat = null;
106         String requestURI = request.getRequestURI();
107         String url = request.getMethod() + " " + requestURI;
108         log.debug("Start handle request of {}", url);
109
110         ServletContext context = request.getSession().getServletContext();
111         User modifier = new User();
112
113         try {
114
115             Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId);
116
117             if (responseWrapper.isEmpty()) {
118                 modifier.setUserId(userId);
119                 log.debug("modifier id is {}", userId);
120
121                 ServiceBusinessLogic businessLogic = getServiceBL(context);
122                 ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data);
123                 Either<String, ResponseFormat> distResponse = businessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);
124
125                 if (distResponse.isRight()) {
126                     log.debug("failed to activate service distribution");
127                     responseFormat = distResponse.right().value();
128                     return buildErrorResponse(responseFormat);
129                 }
130                 String distributionId = distResponse.left().value();
131                 Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId));
132                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED);
133                 return buildOkResponse(responseFormat, result);
134             } else {
135                 log.debug("request instanceId/userId header validation failed");
136                 responseFormat = responseWrapper.getInnerElement();
137                 return buildErrorResponse(responseFormat);
138             }
139         } catch (Exception e) {
140             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
141             log.debug("activate distribution failed with exception", e);
142             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
143             return buildErrorResponse(responseFormat);
144         } finally {
145             getComponentsUtils().auditExternalActivateService(responseFormat,
146                     new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier);
147         }
148     }
149
150     private Wrapper<ResponseFormat> validateRequestHeaders(String instanceIdHeader, String userId) {
151         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
152         if (responseWrapper.isEmpty()) {
153             validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
154         }
155         if (responseWrapper.isEmpty()) {
156             validateHttpCspUserIdHeader(userId, responseWrapper);
157         }
158         return responseWrapper;
159     }
160
161     private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) {
162         ObjectMapper mapper = new ObjectMapper();
163         try {
164             return mapper.readValue(data, ServiceDistributionReqInfo.class);
165         } catch (IOException e) {
166             log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e);
167             return new ServiceDistributionReqInfo(null);
168         }
169     }
170
171     @Override
172     protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
173         ResponseFormat responseFormat;
174         if( StringUtils.isEmpty(header)){
175             log.debug("MissingUSER_ID");
176             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
177             responseWrapper.setInnerElement(responseFormat);
178         }
179     }
180 }
181
182
183