Remove legacy certificate handling
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / LifecycleServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.openecomp.sdc.be.servlets;
21
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.lifecycle.LifecycleBusinessLogic;
48 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
49 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
50 import org.openecomp.sdc.be.config.BeEcompErrorManager;
51 import org.openecomp.sdc.be.dao.api.ActionStatus;
52 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.impl.ComponentsUtils;
55 import org.openecomp.sdc.be.model.Component;
56 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
57 import org.openecomp.sdc.be.model.User;
58 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
59 import org.openecomp.sdc.be.ui.model.UiComponentMetadata;
60 import org.openecomp.sdc.common.api.Constants;
61 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
62 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
63 import org.openecomp.sdc.common.log.enums.StatusCode;
64 import org.openecomp.sdc.common.log.wrappers.Logger;
65 import org.openecomp.sdc.common.util.ValidationUtils;
66 import org.openecomp.sdc.exception.ResponseFormat;
67 import org.springframework.stereotype.Controller;
68
69 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
70 @Path("/v1/catalog")
71 @Tags({@Tag(name = "SDCE-4 APIs")})
72 @Servers({@Server(url = "/sdc2/rest")})
73 @Controller
74 public class LifecycleServlet extends BeGenericServlet {
75
76     private static final Logger log = Logger.getLogger(LifecycleServlet.class);
77     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(LifecycleServlet.class.getName());
78     private LifecycleBusinessLogic lifecycleBusinessLogic;
79
80     @Inject
81     public LifecycleServlet(ComponentsUtils componentsUtils, LifecycleBusinessLogic lifecycleBusinessLogic) {
82         super(componentsUtils);
83         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
84     }
85
86     @POST
87     @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
88     @Consumes(MediaType.APPLICATION_JSON)
89     @Produces(MediaType.APPLICATION_JSON)
90     @Operation(description = "Change Resource lifecycle State", method = "POST", responses = {
91         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
92         @ApiResponse(responseCode = "200", description = "Resource state changed"),
93         @ApiResponse(responseCode = "403", description = "Restricted operation"),
94         @ApiResponse(responseCode = "409", description = "Resource already exist")})
95     public Response changeResourceState(
96         @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification") String jsonChangeInfo,
97         @Parameter(description = "validValues: resources / services / products", schema = @Schema(allowableValues = {
98             ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
99             ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(value = "componentCollection") final String componentCollection,
100         @Parameter(schema = @Schema(allowableValues = {
101             "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification,  cancelCertification, certify"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
102         @Parameter(description = "id of component to be changed") @PathParam(value = "componentId") final String componentId,
103         @Context final HttpServletRequest request,
104         @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
105         throws IOException {
106         String url = request.getMethod() + " " + request.getRequestURI();
107         log.debug("Start handle request of {}", url);
108         loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,
109             "Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId);
110         Response response = null;
111         // get modifier from graph
112         log.debug("get modifier properties");
113         Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
114         if (eitherGetUser.isRight()) {
115             return buildErrorResponse(eitherGetUser.right().value());
116         }
117         User user = eitherGetUser.left().value();
118         String resourceIdLower = componentId.toLowerCase();
119         log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
120         Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
121         if (validateEnum.isRight()) {
122             return validateEnum.right().value();
123         }
124         LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
125         try {
126             if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
127                 ObjectMapper mapper = new ObjectMapper();
128                 changeInfo = new LifecycleChangeInfoWithAction(
129                     mapper.readValue(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class).getUserRemarks());
130             }
131         } catch (Exception e) {
132             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
133             log.debug("failed to convert from json {}", jsonChangeInfo, e);
134             getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
135             throw e;
136         }
137         LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
138         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
139         if (componentType != null) {
140             Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
141                 .changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
142             if (actionResponse.isRight()) {
143                 log.info("failed to change resource state");
144                 loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,
145                     "failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId);
146                 response = buildErrorResponse(actionResponse.right().value());
147                 return response;
148             }
149             log.debug("change state successful !!!");
150             UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
151             Object value = null;
152             try {
153                 value = RepresentationUtils.toRepresentation(componentMetatdata);
154             } catch (IOException e) {
155                 log.debug("toRepresentation of componentMetatdata error :", e);
156             }
157             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
158             loggerSupportability
159                 .log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, actionResponse.left().value().getComponentMetadataForSupportLog(),
160                     StatusCode.COMPLETE, " change state to " + lifecycleTransition + " was successful by user" + userId);
161             return response;
162         } else {
163             log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"",
164                 componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
165                 ComponentTypeEnum.PRODUCT_PARAM_NAME);
166             ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
167             return buildErrorResponse(error);
168         }
169     }
170
171     private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
172         LifeCycleTransitionEnum transitionEnum;
173         try {
174             transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
175         } catch (IllegalArgumentException e) {
176             log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
177             ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
178             return Either.right(buildErrorResponse(error));
179         }
180         return Either.left(transitionEnum);
181     }
182 }