2 * ============LICENSE_START=======================================================
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
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.openecomp.sdc.be.servlets;
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.annotations.*;
26 import com.fasterxml.jackson.databind.ObjectMapper;
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.config.EcompErrorName;
41 import org.openecomp.sdc.exception.ResponseFormat;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 import javax.inject.Singleton;
46 import javax.servlet.ServletContext;
47 import javax.servlet.http.HttpServletRequest;
49 import javax.ws.rs.core.Context;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
52 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
54 @Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet")
56 public class LifecycleServlet extends BeGenericServlet {
58 private static final Logger log = LoggerFactory.getLogger(LifecycleServlet.class);
61 @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
62 @Consumes(MediaType.APPLICATION_JSON)
63 @Produces(MediaType.APPLICATION_JSON)
64 @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
65 @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") })
66 public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo,
67 @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
68 + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection,
69 @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
70 @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request,
71 @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
73 ServletContext context = request.getSession().getServletContext();
74 LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
76 String url = request.getMethod() + " " + request.getRequestURI();
77 log.debug("Start handle request of {}", url);
79 Response response = null;
81 // get modifier from graph
82 log.debug("get modifier properties");
83 Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
84 if (eitherGetUser.isRight()) {
85 return buildErrorResponse(eitherGetUser.right().value());
87 User user = eitherGetUser.left().value();
89 String resourceIdLower = componentId.toLowerCase();
90 log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
91 Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
92 if (validateEnum.isRight()) {
93 return validateEnum.right().value();
96 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
99 if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
100 ObjectMapper mapper = new ObjectMapper();
101 changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
105 catch (Exception e) {
106 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
107 log.debug("failed to convert from json {}", jsonChangeInfo, e);
108 ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
109 return buildErrorResponse(responseFormat);
113 LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
114 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
115 if (componentType != null) {
116 Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
118 if (actionResponse.isRight()) {
119 log.info("failed to change resource state");
120 response = buildErrorResponse(actionResponse.right().value());
124 log.debug("change state successful !!!");
125 UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
126 Object value = RepresentationUtils.toRepresentation(componentMetatdata);
127 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
130 log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
131 ComponentTypeEnum.PRODUCT_PARAM_NAME);
132 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
133 return buildErrorResponse(error);
135 } catch (Exception e) {
136 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
137 log.debug("change lifecycle state failed with exception", e);
138 response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
144 private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
145 LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
147 transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
148 } catch (IllegalArgumentException e) {
149 log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
150 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
151 return Either.right(buildErrorResponse(error));
153 return Either.left(transitionEnum);