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