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.be.user.UserBusinessLogic;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
65 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
66 import org.openecomp.sdc.common.log.enums.StatusCode;
67 import org.openecomp.sdc.common.log.wrappers.Logger;
68 import org.openecomp.sdc.common.util.ValidationUtils;
69 import org.openecomp.sdc.exception.ResponseFormat;
70 import org.springframework.stereotype.Controller;
72 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
74 @Tags({@Tag(name = "SDCE-4 APIs")})
75 @Servers({@Server(url = "/sdc2/rest")})
77 public class LifecycleServlet extends BeGenericServlet {
79 private static final Logger log = Logger.getLogger(LifecycleServlet.class);
80 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(LifecycleServlet.class.getName());
81 private LifecycleBusinessLogic lifecycleBusinessLogic;
84 public LifecycleServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, LifecycleBusinessLogic lifecycleBusinessLogic) {
85 super(userBusinessLogic, componentsUtils);
86 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
90 @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
91 @Consumes(MediaType.APPLICATION_JSON)
92 @Produces(MediaType.APPLICATION_JSON)
93 @Operation(description = "Change Resource lifecycle State", method = "POST", responses = {
94 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
95 @ApiResponse(responseCode = "200", description = "Resource state changed"),
96 @ApiResponse(responseCode = "403", description = "Restricted operation"),
97 @ApiResponse(responseCode = "409", description = "Resource already exist")})
98 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
99 public Response changeResourceState(
100 @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification") String jsonChangeInfo,
101 @Parameter(description = "validValues: resources / services / products", schema = @Schema(allowableValues = {
102 ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
103 ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(value = "componentCollection") final String componentCollection,
104 @Parameter(schema = @Schema(allowableValues = {
105 "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
106 @Parameter(description = "id of component to be changed") @PathParam(value = "componentId") final String componentId,
107 @Context final HttpServletRequest request,
108 @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
110 String url = request.getMethod() + " " + request.getRequestURI();
111 log.debug("Start handle request of {}", url);
112 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,
113 "Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId);
114 Response response = null;
115 // get modifier from graph
116 log.debug("get modifier properties");
117 Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
118 if (eitherGetUser.isRight()) {
119 return buildErrorResponse(eitherGetUser.right().value());
121 User user = eitherGetUser.left().value();
122 String resourceIdLower = componentId.toLowerCase();
123 log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
124 Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
125 if (validateEnum.isRight()) {
126 return validateEnum.right().value();
128 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
130 if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
131 ObjectMapper mapper = new ObjectMapper();
132 changeInfo = new LifecycleChangeInfoWithAction(
133 mapper.readValue(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class).getUserRemarks());
135 } catch (Exception e) {
136 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
137 log.debug("failed to convert from json {}", jsonChangeInfo, e);
138 getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
141 LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
142 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
143 if (componentType != null) {
144 Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
145 .changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
146 if (actionResponse.isRight()) {
147 log.info("failed to change resource state");
148 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,
149 "failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId);
150 response = buildErrorResponse(actionResponse.right().value());
153 log.debug("change state successful !!!");
154 UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
157 value = RepresentationUtils.toRepresentation(componentMetatdata);
158 } catch (IOException e) {
159 log.debug("toRepresentation of componentMetatdata error :", e);
161 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
163 .log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, actionResponse.left().value().getComponentMetadataForSupportLog(),
164 StatusCode.COMPLETE, " change state to " + lifecycleTransition + " was successful by user" + userId);
167 log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"",
168 componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
169 ComponentTypeEnum.PRODUCT_PARAM_NAME);
170 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
171 return buildErrorResponse(error);
175 private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
176 LifeCycleTransitionEnum transitionEnum;
178 transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
179 } catch (IllegalArgumentException e) {
180 log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
181 ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
182 return Either.right(buildErrorResponse(error));
184 return Either.left(transitionEnum);