f83f83df2bb1c93eb4bd3c76764ff6c921fb3547
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ComponentInstanceCapabilityServlet.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.sdc.be.servlets;
21
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.tags.Tag;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.validation.Valid;
34 import javax.validation.constraints.NotNull;
35 import javax.ws.rs.Consumes;
36 import javax.ws.rs.HeaderParam;
37 import javax.ws.rs.PUT;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.PathParam;
40 import javax.ws.rs.Produces;
41 import javax.ws.rs.core.Context;
42 import javax.ws.rs.core.MediaType;
43 import javax.ws.rs.core.Response;
44 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
45 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
46 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
47 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
51 import org.openecomp.sdc.be.exception.BusinessException;
52 import org.openecomp.sdc.be.model.CapabilityDefinition;
53 import org.openecomp.sdc.be.servlets.builder.ServletResponseBuilder;
54 import org.openecomp.sdc.be.ui.mapper.CapabilityMapper;
55 import org.openecomp.sdc.be.ui.model.ComponentInstanceCapabilityUpdateModel;
56 import org.openecomp.sdc.common.api.Constants;
57 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
58 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
59 import org.openecomp.sdc.common.log.enums.StatusCode;
60 import org.openecomp.sdc.common.log.wrappers.Logger;
61 import org.openecomp.sdc.exception.ResponseFormat;
62 import org.springframework.stereotype.Controller;
63 import org.springframework.web.bind.annotation.RequestBody;
64
65 /**
66  * Handles component instance capabilities operations
67  */
68 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
69 @Path("/v1/catalog")
70 @Tag(name = "SDCE-2 APIs")
71 @Server(url = "/sdc2/rest")
72 @Controller
73 public class ComponentInstanceCapabilityServlet {
74
75     private static final Logger LOGGER = Logger.getLogger(ComponentInstanceCapabilityServlet.class);
76     private static final LoggerSupportability LOGGER_SUPPORTABILITY = LoggerSupportability.getLogger(ComponentInstanceCapabilityServlet.class);
77
78     private final ResponseFormatManager responseFormatManager;
79     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
80     private final CapabilityMapper capabilityMapper;
81     private final ServletResponseBuilder servletResponseBuilder;
82
83     public ComponentInstanceCapabilityServlet(final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
84                                               final CapabilityMapper capabilityMapper, final ServletResponseBuilder servletResponseBuilder) {
85         this.capabilityMapper = capabilityMapper;
86         this.servletResponseBuilder = servletResponseBuilder;
87         this.responseFormatManager = ResponseFormatManager.getInstance();
88         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
89     }
90
91     @PUT
92     @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/")
93     @Consumes(MediaType.APPLICATION_JSON)
94     @Produces(MediaType.APPLICATION_JSON)
95     @Operation(description = "Update Component Instance Capability", method = "PUT", summary = "Returns updated Component Instance Capability",
96         responses = {
97             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
98             @ApiResponse(responseCode = "200", description = "Resource instance capability successfully updated"),
99             @ApiResponse(responseCode = "403", description = "Restricted operation"),
100             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
101             @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability not found")})
102     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
103     public Response updateInstanceRequirement(@PathParam("containerComponentType") final String containerComponentType,
104                                               @PathParam("containerComponentId") final String containerComponentId,
105                                               @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
106                                               @Parameter(description = "Component instance capability to update", required = true)
107                                               @Valid @RequestBody @NotNull final ComponentInstanceCapabilityUpdateModel capabilityUpdateModel,
108                                               @Context final HttpServletRequest request,
109                                               @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
110         if (LOGGER.isDebugEnabled()) {
111             final var url = request.getMethod() + " " + request.getRequestURI();
112             LOGGER.debug("Start handle request of {}", url);
113         }
114         try {
115             var componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
116             if (componentTypeEnum == null) {
117                 LOGGER.debug("Unsupported component type {}", containerComponentType);
118                 return servletResponseBuilder
119                     .buildErrorResponse(responseFormatManager.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
120             }
121             final var capabilityDefinition = capabilityMapper.mapToCapabilityDefinition(capabilityUpdateModel);
122             LOGGER_SUPPORTABILITY.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY, StatusCode.STARTED,
123                 "Starting to update capability '{}' in component instance '{}' by '{}'",
124                 capabilityDefinition.getName(), componentInstanceUniqueId, userId);
125             final Either<CapabilityDefinition, ResponseFormat> response = componentInstanceBusinessLogic
126                 .updateInstanceCapability(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityDefinition, userId);
127             if (response.isRight()) {
128                 return servletResponseBuilder.buildErrorResponse(response.right().value());
129             }
130             return servletResponseBuilder.buildOkResponse(responseFormatManager.getResponseFormat(ActionStatus.OK), response.left().value());
131         } catch (final BusinessException e) {
132             //leave to the handlers deal with it
133             throw e;
134         } catch (final Exception e) {
135             var errorMsg = String
136                 .format("Unexpected error while updating component '%s' of type '%s' instance '%s'. Payload '%s'",
137                     containerComponentId, containerComponentType, componentInstanceUniqueId, capabilityUpdateModel);
138             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
139             LOGGER.debug(errorMsg, e);
140             return servletResponseBuilder.buildErrorResponse(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR));
141         }
142     }
143
144 }