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.fasterxml.jackson.databind.ObjectMapper;
24 import com.jcabi.aspects.Loggable;
25 import fj.data.Either;
26 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
27 import io.swagger.v3.oas.annotations.Operation;
28 import io.swagger.v3.oas.annotations.Parameter;
29 import io.swagger.v3.oas.annotations.info.Info;
30 import io.swagger.v3.oas.annotations.media.ArraySchema;
31 import io.swagger.v3.oas.annotations.media.Content;
32 import io.swagger.v3.oas.annotations.media.Schema;
33 import io.swagger.v3.oas.annotations.responses.ApiResponse;
34 import io.swagger.v3.oas.annotations.responses.ApiResponses;
35 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
36 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
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.impl.ComponentsUtils;
45 import org.openecomp.sdc.be.model.Component;
46 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
47 import org.openecomp.sdc.be.model.User;
48 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
49 import org.openecomp.sdc.be.ui.model.UiComponentMetadata;
50 import org.openecomp.sdc.be.user.UserBusinessLogic;
51 import org.openecomp.sdc.common.api.Constants;
52 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
53 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
54 import org.openecomp.sdc.common.log.enums.StatusCode;
55 import org.openecomp.sdc.common.log.wrappers.Logger;
56 import org.openecomp.sdc.exception.ResponseFormat;
57 import org.springframework.stereotype.Controller;
59 import javax.inject.Inject;
60 import javax.servlet.http.HttpServletRequest;
61 import javax.ws.rs.Consumes;
62 import javax.ws.rs.HeaderParam;
63 import javax.ws.rs.POST;
64 import javax.ws.rs.Path;
65 import javax.ws.rs.PathParam;
66 import javax.ws.rs.Produces;
67 import javax.ws.rs.core.Context;
68 import javax.ws.rs.core.MediaType;
69 import javax.ws.rs.core.Response;
70 import java.io.IOException;
72 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
74 @OpenAPIDefinition(info = @Info(title = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet"))
76 public class LifecycleServlet extends BeGenericServlet {
78 private static final Logger log = Logger.getLogger(LifecycleServlet.class);
79 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(LifecycleServlet.class.getName());
80 private LifecycleBusinessLogic lifecycleBusinessLogic;
83 public LifecycleServlet(UserBusinessLogic userBusinessLogic,
84 ComponentsUtils componentsUtils,
85 LifecycleBusinessLogic lifecycleBusinessLogic) {
86 super(userBusinessLogic, componentsUtils);
87 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
92 @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
93 @Consumes(MediaType.APPLICATION_JSON)
94 @Produces(MediaType.APPLICATION_JSON)
95 @Operation(description = "Change Resource lifecycle State", method = "POST", responses = @ApiResponse(
96 content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
97 @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Resource state changed"),
98 @ApiResponse(responseCode = "403", description = "Restricted operation"),
99 @ApiResponse(responseCode = "409", description = "Resource already exist")})
100 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
101 public Response changeResourceState(
103 description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification",
104 required = false) String jsonChangeInfo,
105 @Parameter(description = "validValues: resources / services / products",
106 schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
107 ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(
108 value = "componentCollection") final String componentCollection,
109 @Parameter(schema = @Schema(allowableValues = {
110 "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify"}),
111 required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
112 @Parameter(description = "id of component to be changed") @PathParam(
113 value = "componentId") final String componentId,
114 @Context final HttpServletRequest request,
115 @Parameter(description = "id of user initiating the operation") @HeaderParam(
116 value = Constants.USER_ID_HEADER) String userId) throws IOException {
118 String url = request.getMethod() + " " + request.getRequestURI();
119 log.debug("Start handle request of {}", url);
120 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,"Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId);
122 Response response = null;
124 // get modifier from graph
125 log.debug("get modifier properties");
126 Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
127 if (eitherGetUser.isRight()) {
128 return buildErrorResponse(eitherGetUser.right().value());
130 User user = eitherGetUser.left().value();
132 String resourceIdLower = componentId.toLowerCase();
133 log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
134 Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
135 if (validateEnum.isRight()) {
136 return validateEnum.right().value();
139 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
142 if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
143 ObjectMapper mapper = new ObjectMapper();
144 changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
148 catch (Exception e) {
149 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
150 log.debug("failed to convert from json {}", jsonChangeInfo, e);
151 getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
155 LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
156 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
157 if (componentType != null) {
158 Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
160 if (actionResponse.isRight()) {
161 log.info("failed to change resource state");
162 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,"failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId);
163 response = buildErrorResponse(actionResponse.right().value());
167 log.debug("change state successful !!!");
168 UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
171 value = RepresentationUtils.toRepresentation(componentMetatdata);
172 } catch (IOException e) {
175 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
176 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE,actionResponse.left().value().getComponentMetadataForSupportLog(),StatusCode.COMPLETE," change state to " + lifecycleTransition + " was successful by user" + userId);
179 log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
180 ComponentTypeEnum.PRODUCT_PARAM_NAME);
181 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
182 return buildErrorResponse(error);
186 private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
187 LifeCycleTransitionEnum transitionEnum;
189 transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
190 } catch (IllegalArgumentException e) {
191 log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
192 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
193 return Either.right(buildErrorResponse(error));
195 return Either.left(transitionEnum);