83ee15240f06397427feab5aa52f8987b481a66b
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ComponentInterfaceOperationServlet.java
1 /*
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  *  Copyright (C) 2021 Nordix Foundation. 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  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21 package org.openecomp.sdc.be.servlets;
22
23 import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
24
25 import fj.data.Either;
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.ArraySchema;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.servers.Server;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34 import java.io.IOException;
35 import java.util.Optional;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.HeaderParam;
39 import javax.ws.rs.PUT;
40 import javax.ws.rs.Path;
41 import javax.ws.rs.PathParam;
42 import javax.ws.rs.Produces;
43 import javax.ws.rs.core.Context;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
46 import org.apache.commons.io.IOUtils;
47 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
48 import org.openecomp.sdc.be.components.impl.ComponentInterfaceOperationBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
50 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
51 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
52 import org.openecomp.sdc.be.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.impl.ComponentsUtils;
56 import org.openecomp.sdc.be.impl.ServletUtils;
57 import org.openecomp.sdc.be.model.Component;
58 import org.openecomp.sdc.be.model.ComponentInstance;
59 import org.openecomp.sdc.be.model.InterfaceDefinition;
60 import org.openecomp.sdc.be.model.User;
61 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
62 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
63 import org.openecomp.sdc.be.user.UserBusinessLogic;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.openecomp.sdc.common.datastructure.Wrapper;
66 import org.openecomp.sdc.common.util.ValidationUtils;
67 import org.openecomp.sdc.exception.ResponseFormat;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.stereotype.Controller;
72
73 @Path("/v1/catalog")
74 @Tag(name = "SDCE-2 APIs")
75 @Consumes(MediaType.APPLICATION_JSON)
76 @Produces(MediaType.APPLICATION_JSON)
77 @Server(url = "/sdc2/rest")
78 @Controller
79 public class ComponentInterfaceOperationServlet extends AbstractValidationsServlet {
80
81     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class);
82     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
83     private static final String MODIFIER_ID_IS = "modifier id is {}";
84     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = "failed to update Interface Operation on component instance {}";
85     private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance";
86     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = "Failed to update Interface Operation with an error";
87     private static final String INTERFACE_OPERATION_CONTENT_INVALID = "Interface Operation content is invalid - {}";
88     private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
89     private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = "Interface Operation successfully updated on component instance with id {}";
90     private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic;
91
92     @Autowired
93     public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
94                                               final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
95                                               final ResourceImportManager resourceImportManager,
96                                               final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic) {
97         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
98         this.componentInterfaceOperationBusinessLogic = componentInterfaceOperationBusinessLogic;
99     }
100
101     @PUT
102     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/interfaceOperation")
103     @Consumes(MediaType.APPLICATION_JSON)
104     @Produces(MediaType.APPLICATION_JSON)
105     @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
106         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
107         @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
108         @ApiResponse(responseCode = "403", description = "Restricted operation"),
109         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
110     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
111     public Response updateComponentInstanceInterfaceOperation(
112         @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
113             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") String componentType,
114         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
115         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
116         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
117         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
118         userId = ValidationUtils.sanitizeInputString(userId);
119         componentType = ValidationUtils.sanitizeInputString(componentType);
120         componentInstanceId = ValidationUtils.sanitizeInputString(componentInstanceId);
121         LOGGER.debug(MODIFIER_ID_IS, userId);
122         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
123         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
124         if (componentTypeEnum == null) {
125             LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
126             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
127         }
128         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
129         if (bytes == null || bytes.length == 0) {
130             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, "content is empty");
131             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
132         }
133         final String data = new String(bytes);
134         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
135         if (mappedInterfaceOperationData.isEmpty()) {
136             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
137             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
138         }
139         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
140         try {
141             final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic
142                 .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(), componentTypeEnum,
143                     errorWrapper, true);
144             if (actionResponse.isEmpty()) {
145                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId);
146                 return buildErrorResponse(errorWrapper.getInnerElement());
147             } else {
148                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId);
149                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
150             }
151         } catch (final Exception e) {
152             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
153             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
154             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
155         }
156     }
157
158     @PUT
159     @Path("/resources/{componentId}/interfaceOperation")
160     @Consumes(MediaType.APPLICATION_JSON)
161     @Produces(MediaType.APPLICATION_JSON)
162     @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
163         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
164         @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
165         @ApiResponse(responseCode = "403", description = "Restricted operation"),
166         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
167     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
168     public Response updateResourceInterfaceOperation(
169         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
170         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
171         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
172         LOGGER.debug(MODIFIER_ID_IS, userId);
173         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
174         final ComponentTypeEnum componentTypeEnum = RESOURCE;
175         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
176         if (bytes == null || bytes.length == 0) {
177             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID);
178             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
179         }
180         final String data = new String(bytes);
181         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
182         if (mappedInterfaceOperationData.isEmpty()) {
183             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
184             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
185         }
186         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
187         try {
188             final Optional<Component> actionResponse = componentInterfaceOperationBusinessLogic
189                 .updateResourceInterfaceOperation(componentId, mappedInterfaceOperationData.get(), componentTypeEnum, errorWrapper, true);
190             if (actionResponse.isEmpty()) {
191                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentId);
192                 return buildErrorResponse(errorWrapper.getInnerElement());
193             } else {
194                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentId);
195                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
196             }
197         } catch (final Exception e) {
198             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
199             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
200             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
201         }
202     }
203
204     private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson, final User user, final ComponentTypeEnum componentTypeEnum) {
205         final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils()
206             .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
207                 componentTypeEnum);
208         return uiComponentEither.left().value().getInterfaces().values().stream().findFirst();
209     }
210 }