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