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 javax.inject.Singleton;
24 import javax.servlet.ServletContext;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.HeaderParam;
28 import javax.ws.rs.POST;
29 import javax.ws.rs.Path;
30 import javax.ws.rs.PathParam;
31 import javax.ws.rs.Produces;
32 import javax.ws.rs.core.Context;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
36 import org.codehaus.jackson.map.ObjectMapper;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
39 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
40 import org.openecomp.sdc.be.config.BeEcompErrorManager;
41 import org.openecomp.sdc.be.dao.api.ActionStatus;
42 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
43 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
44 import org.openecomp.sdc.be.model.Component;
45 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
46 import org.openecomp.sdc.be.model.User;
47 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
48 import org.openecomp.sdc.be.ui.model.UiComponentMetadata;
49 import org.openecomp.sdc.common.api.Constants;
50 import org.openecomp.sdc.common.config.EcompErrorName;
51 import org.openecomp.sdc.exception.ResponseFormat;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import com.jcabi.aspects.Loggable;
56 import com.wordnik.swagger.annotations.Api;
57 import com.wordnik.swagger.annotations.ApiOperation;
58 import com.wordnik.swagger.annotations.ApiParam;
59 import com.wordnik.swagger.annotations.ApiResponse;
60 import com.wordnik.swagger.annotations.ApiResponses;
62 import fj.data.Either;
64 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
66 @Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet")
68 public class LifecycleServlet extends BeGenericServlet {
70 private static Logger log = LoggerFactory.getLogger(LifecycleServlet.class.getName());
73 @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
74 @Consumes(MediaType.APPLICATION_JSON)
75 @Produces(MediaType.APPLICATION_JSON)
76 @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
77 @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") })
78 public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo,
79 @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
80 + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection,
81 @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
82 @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request,
83 @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
85 ServletContext context = request.getSession().getServletContext();
86 LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
88 String url = request.getMethod() + " " + request.getRequestURI();
89 log.debug("Start handle request of {}", url);
91 Response response = null;
93 // get modifier from graph
94 log.debug("get modifier properties");
95 Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
96 if (eitherGetUser.isRight()) {
97 return buildErrorResponse(eitherGetUser.right().value());
99 User user = eitherGetUser.left().value();
101 String resourceIdLower = componentId.toLowerCase();
102 log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
103 Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
104 if (validateEnum.isRight()) {
105 return validateEnum.right().value();
108 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
111 if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
112 // Either<LifecycleChangeInfo, ResponseFormat > changeInfoResult
114 // getComponentsUtils().convertJsonToObjectUsingObjectMapper(jsonChangeInfo,
115 // user, LifecycleChangeInfo.class,
116 // AuditingActionEnum.CHECKOUT_RESOURCE, null);
117 ObjectMapper mapper = new ObjectMapper();
118 changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
122 catch (Exception e) {
123 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
124 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
125 log.debug("failed to convert from json {}", jsonChangeInfo, e);
126 ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
127 return buildErrorResponse(responseFormat);
131 LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
132 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
133 if (componentType != null) {
134 Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
136 if (actionResponse.isRight()) {
137 log.info("failed to change resource state");
138 response = buildErrorResponse(actionResponse.right().value());
142 log.debug("change state successful !!!");
143 UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
144 Object value = RepresentationUtils.toRepresentation(componentMetatdata);
145 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
148 log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
149 ComponentTypeEnum.PRODUCT_PARAM_NAME);
150 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
151 return buildErrorResponse(error);
153 } catch (Exception e) {
154 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State");
155 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
156 log.debug("change lifecycle state failed with exception", e);
157 response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
163 private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
164 LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
166 transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
167 } catch (IllegalArgumentException e) {
168 log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
169 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
170 return Either.right(buildErrorResponse(error));
172 return Either.left(transitionEnum);
175 // private LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
176 // WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
177 // WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
178 // LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class);
179 // return resourceBl;
182 // protected Either<User, Response> getUser(final HttpServletRequest request, String userId) {
184 // Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
185 // if (eitherCreator.isRight()) {
186 // log.info("createResource method - user is not listed. userId= {}", userId);
187 // ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
188 // User user = new User("", "", userId, "", null, null);
190 // getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null);
191 // return Either.right(buildErrorResponse(errorResponse));
193 // return Either.left(eitherCreator.left().value());