re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / LifecycleServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.servlets;
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.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
28 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
29 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
30 import org.openecomp.sdc.be.config.BeEcompErrorManager;
31 import org.openecomp.sdc.be.dao.api.ActionStatus;
32 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
33 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
34 import org.openecomp.sdc.be.model.Component;
35 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
36 import org.openecomp.sdc.be.model.User;
37 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
38 import org.openecomp.sdc.be.ui.model.UiComponentMetadata;
39 import org.openecomp.sdc.common.api.Constants;
40 import org.openecomp.sdc.common.log.wrappers.Logger;
41 import org.openecomp.sdc.exception.ResponseFormat;
42
43 import javax.inject.Singleton;
44 import javax.servlet.ServletContext;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.ws.rs.*;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.MediaType;
49 import javax.ws.rs.core.Response;
50
51 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
52 @Path("/v1/catalog")
53 @Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet")
54 @Singleton
55 public class LifecycleServlet extends BeGenericServlet {
56
57     private static final Logger log = Logger.getLogger(LifecycleServlet.class);
58
59     @POST
60     @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
61     @Consumes(MediaType.APPLICATION_JSON)
62     @Produces(MediaType.APPLICATION_JSON)
63     @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
64     @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") })
65     public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo,
66             @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
67                     + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection,
68             @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification,  cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
69             @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request,
70             @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
71
72         ServletContext context = request.getSession().getServletContext();
73         LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
74
75         String url = request.getMethod() + " " + request.getRequestURI();
76         log.debug("Start handle request of {}", url);
77
78         Response response = null;
79
80         // get modifier from graph
81         log.debug("get modifier properties");
82         Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
83         if (eitherGetUser.isRight()) {
84             return buildErrorResponse(eitherGetUser.right().value());
85         }
86         User user = eitherGetUser.left().value();
87
88         String resourceIdLower = componentId.toLowerCase();
89         log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
90         Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
91         if (validateEnum.isRight()) {
92             return validateEnum.right().value();
93         }
94
95         LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
96
97         try {
98             if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
99                 ObjectMapper mapper = new ObjectMapper();
100                 changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
101             }
102         }
103
104         catch (Exception e) {
105             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
106             log.debug("failed to convert from json {}", jsonChangeInfo, e);
107             ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
108             return buildErrorResponse(responseFormat);
109         }
110
111         try {
112             LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
113             ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
114             if (componentType != null) {
115                 Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
116
117                 if (actionResponse.isRight()) {
118                     log.info("failed to change resource state");
119                     response = buildErrorResponse(actionResponse.right().value());
120                     return response;
121                 }
122
123                 log.debug("change state successful !!!");
124                 UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
125                 Object value = RepresentationUtils.toRepresentation(componentMetatdata);
126                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
127                 return response;
128             } else {
129                 log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
130                         ComponentTypeEnum.PRODUCT_PARAM_NAME);
131                 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
132                 return buildErrorResponse(error);
133             }
134         } catch (Exception e) {
135             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
136             log.debug("change lifecycle state failed with exception", e);
137             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
138             return response;
139
140         }
141     }
142
143     private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
144         LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
145         try {
146             transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
147         } catch (IllegalArgumentException e) {
148             log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
149             ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
150             return Either.right(buildErrorResponse(error));
151         }
152         return Either.left(transitionEnum);
153     }
154
155 }