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=========================================================
20 package org.openecomp.sdc.be.servlets;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.v3.oas.annotations.Operation;
26 import io.swagger.v3.oas.annotations.Parameter;
27 import io.swagger.v3.oas.annotations.media.ArraySchema;
28 import io.swagger.v3.oas.annotations.media.Content;
29 import io.swagger.v3.oas.annotations.media.Schema;
30 import io.swagger.v3.oas.annotations.responses.ApiResponse;
31 import io.swagger.v3.oas.annotations.servers.Server;
32 import io.swagger.v3.oas.annotations.servers.Servers;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34 import io.swagger.v3.oas.annotations.tags.Tags;
35 import java.io.IOException;
36 import javax.inject.Inject;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.ws.rs.Consumes;
39 import javax.ws.rs.HeaderParam;
40 import javax.ws.rs.POST;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.PathParam;
43 import javax.ws.rs.Produces;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
48 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
49 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
52 import org.openecomp.sdc.be.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.model.Component;
58 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
59 import org.openecomp.sdc.be.model.User;
60 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
61 import org.openecomp.sdc.be.ui.model.UiComponentMetadata;
62 import org.openecomp.sdc.common.api.Constants;
63 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
64 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
65 import org.openecomp.sdc.common.log.enums.StatusCode;
66 import org.openecomp.sdc.common.log.wrappers.Logger;
67 import org.openecomp.sdc.common.util.ValidationUtils;
68 import org.openecomp.sdc.exception.ResponseFormat;
69 import org.springframework.stereotype.Controller;
71 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
73 @Tags({@Tag(name = "SDCE-4 APIs")})
74 @Servers({@Server(url = "/sdc2/rest")})
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(ComponentsUtils componentsUtils, LifecycleBusinessLogic lifecycleBusinessLogic) {
84 super(componentsUtils);
85 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
89 @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
90 @Consumes(MediaType.APPLICATION_JSON)
91 @Produces(MediaType.APPLICATION_JSON)
92 @Operation(description = "Change Resource lifecycle State", method = "POST", responses = {
93 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
94 @ApiResponse(responseCode = "200", description = "Resource state changed"),
95 @ApiResponse(responseCode = "403", description = "Restricted operation"),
96 @ApiResponse(responseCode = "409", description = "Resource already exist")})
97 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
98 public Response changeResourceState(
99 @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification") String jsonChangeInfo,
100 @Parameter(description = "validValues: resources / services / products", schema = @Schema(allowableValues = {
101 ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
102 ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(value = "componentCollection") final String componentCollection,
103 @Parameter(schema = @Schema(allowableValues = {
104 "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
105 @Parameter(description = "id of component to be changed") @PathParam(value = "componentId") final String componentId,
106 @Context final HttpServletRequest request,
107 @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
109 String url = request.getMethod() + " " + request.getRequestURI();
110 log.debug("Start handle request of {}", url);
111 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,
112 "Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId);
113 Response response = null;
114 // get modifier from graph
115 log.debug("get modifier properties");
116 Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
117 if (eitherGetUser.isRight()) {
118 return buildErrorResponse(eitherGetUser.right().value());
120 User user = eitherGetUser.left().value();
121 String resourceIdLower = componentId.toLowerCase();
122 log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
123 Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
124 if (validateEnum.isRight()) {
125 return validateEnum.right().value();
127 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
129 if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
130 ObjectMapper mapper = new ObjectMapper();
131 changeInfo = new LifecycleChangeInfoWithAction(
132 mapper.readValue(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class).getUserRemarks());
134 } catch (Exception e) {
135 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
136 log.debug("failed to convert from json {}", jsonChangeInfo, e);
137 getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
140 LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
141 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
142 if (componentType != null) {
143 Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
144 .changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
145 if (actionResponse.isRight()) {
146 log.info("failed to change resource state");
147 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,
148 "failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId);
149 response = buildErrorResponse(actionResponse.right().value());
152 log.debug("change state successful !!!");
153 UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
156 value = RepresentationUtils.toRepresentation(componentMetatdata);
157 } catch (IOException e) {
158 log.debug("toRepresentation of componentMetatdata error :", e);
160 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
162 .log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, actionResponse.left().value().getComponentMetadataForSupportLog(),
163 StatusCode.COMPLETE, " change state to " + lifecycleTransition + " was successful by user" + userId);
166 log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"",
167 componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
168 ComponentTypeEnum.PRODUCT_PARAM_NAME);
169 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
170 return buildErrorResponse(error);
174 private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
175 LifeCycleTransitionEnum transitionEnum;
177 transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
178 } catch (IllegalArgumentException e) {
179 log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
180 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
181 return Either.right(buildErrorResponse(error));
183 return Either.left(transitionEnum);