64b85009792bab8c6907963be236fbc260f1c529
[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.POST;
40 import javax.ws.rs.PUT;
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.apache.commons.io.IOUtils;
48 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.ComponentInterfaceOperationBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
51 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
52 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
53 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
54 import org.openecomp.sdc.be.config.BeEcompErrorManager;
55 import org.openecomp.sdc.be.dao.api.ActionStatus;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.impl.ComponentsUtils;
58 import org.openecomp.sdc.be.impl.ServletUtils;
59 import org.openecomp.sdc.be.model.Component;
60 import org.openecomp.sdc.be.model.ComponentInstance;
61 import org.openecomp.sdc.be.model.InterfaceDefinition;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
64 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
65 import org.openecomp.sdc.be.user.UserBusinessLogic;
66 import org.openecomp.sdc.common.api.Constants;
67 import org.openecomp.sdc.common.datastructure.Wrapper;
68 import org.openecomp.sdc.common.util.ValidationUtils;
69 import org.openecomp.sdc.exception.ResponseFormat;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.stereotype.Controller;
74
75 @Path("/v1/catalog")
76 @Tag(name = "SDCE-2 APIs")
77 @Consumes(MediaType.APPLICATION_JSON)
78 @Produces(MediaType.APPLICATION_JSON)
79 @Server(url = "/sdc2/rest")
80 @Controller
81 public class ComponentInterfaceOperationServlet extends AbstractValidationsServlet {
82
83     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class);
84     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
85     private static final String MODIFIER_ID_IS = "modifier id is {}";
86     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = "failed to update Interface Operation on component instance {}";
87     private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance";
88     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = "Failed to update Interface Operation with an error";
89     private static final String INTERFACE_OPERATION_CONTENT_INVALID = "Interface Operation content is invalid - {}";
90     private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
91     private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = "Interface Operation successfully updated on component instance with id {}";
92     private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic;
93
94     @Autowired
95     public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
96                                               final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
97                                               final ResourceImportManager resourceImportManager,
98                                               final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic) {
99         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
100         this.componentInterfaceOperationBusinessLogic = componentInterfaceOperationBusinessLogic;
101     }
102
103     @PUT
104     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/interfaceOperation")
105     @Consumes(MediaType.APPLICATION_JSON)
106     @Produces(MediaType.APPLICATION_JSON)
107     @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
108         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
109         @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
110         @ApiResponse(responseCode = "403", description = "Restricted operation"),
111         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
112     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
113     public Response updateComponentInstanceInterfaceOperation(
114         @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
115             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") String componentType,
116         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
117         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
118         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
119         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
120         userId = ValidationUtils.sanitizeInputString(userId);
121         componentType = ValidationUtils.sanitizeInputString(componentType);
122         componentInstanceId = ValidationUtils.sanitizeInputString(componentInstanceId);
123         LOGGER.debug(MODIFIER_ID_IS, userId);
124         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
125         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
126         if (componentTypeEnum == null) {
127             LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
128             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
129         }
130         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
131         if (bytes == null || bytes.length == 0) {
132             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, "content is empty");
133             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
134         }
135         final String data = new String(bytes);
136         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
137         if (mappedInterfaceOperationData.isEmpty()) {
138             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
139             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
140         }
141         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
142         try {
143             final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic.updateComponentInstanceInterfaceOperation(
144                 componentId, componentInstanceId, mappedInterfaceOperationData.get(), componentTypeEnum, errorWrapper, true);
145             if (actionResponse.isEmpty()) {
146                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId);
147                 return buildErrorResponse(errorWrapper.getInnerElement());
148             } else {
149                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId);
150                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
151             }
152         } catch (final Exception e) {
153             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
154             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
155             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
156         }
157     }
158
159     @PUT
160     @Path("/resources/{componentId}/interfaceOperation")
161     @Consumes(MediaType.APPLICATION_JSON)
162     @Produces(MediaType.APPLICATION_JSON)
163     @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
164         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
165         @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
166         @ApiResponse(responseCode = "403", description = "Restricted operation"),
167         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
168     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
169     public Response updateResourceInterfaceOperation(
170         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
171         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
172         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
173         LOGGER.debug(MODIFIER_ID_IS, userId);
174         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
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 ComponentTypeEnum componentType = RESOURCE;
181         final String data = new String(bytes);
182         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentType);
183         if (mappedInterfaceOperationData.isEmpty()) {
184             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
185             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
186         }
187         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
188         try {
189             final Optional<Component> actionResponse = componentInterfaceOperationBusinessLogic
190                 .updateResourceInterfaceOperation(componentId, userId, mappedInterfaceOperationData.get(), componentType,
191                     errorWrapper, true);
192             if (actionResponse.isEmpty()) {
193                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentId);
194                 return buildErrorResponse(errorWrapper.getInnerElement());
195             } else {
196                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentId);
197                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
198             }
199         } catch (final ComponentException e) {
200             //let it be handled by org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper
201             throw e;
202         } catch (final Exception e) {
203             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
204             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
205             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
206         }
207     }
208
209     @POST
210     @Path("/{componentType}/{componentId}/resource/interfaceOperation")
211     @Consumes(MediaType.APPLICATION_JSON)
212     @Produces(MediaType.APPLICATION_JSON)
213     @Operation(description = "Create Interface Operation", method = "POST", summary = "Create Interface Operation on ComponentInstance", responses = {
214         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
215         @ApiResponse(responseCode = "201", description = "Create Interface Operation"),
216         @ApiResponse(responseCode = "403", description = "Restricted operation"),
217         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
218     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
219     public Response createInterfaceOperationInResource(
220         @Parameter(description = "valid values: resources", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME}))
221         @PathParam("componentType") final String componentType,
222         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
223         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
224         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
225         LOGGER.debug(MODIFIER_ID_IS, userId);
226         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
227         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
228         if (componentTypeEnum == null) {
229             LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
230             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
231         }
232         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
233         if (bytes == null || bytes.length == 0) {
234             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID);
235             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
236         }
237         final String data = new String(bytes);
238         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
239         if (mappedInterfaceOperationData.isEmpty()) {
240             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
241             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
242         }
243         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
244         try {
245             final Optional<Component> actionResponse = componentInterfaceOperationBusinessLogic.createInterfaceOperationInResource(
246                 componentId, mappedInterfaceOperationData.get(), componentTypeEnum, errorWrapper, true);
247             if (actionResponse.isEmpty()) {
248                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentId);
249                 return buildErrorResponse(errorWrapper.getInnerElement());
250             } else {
251                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentId);
252                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
253             }
254         } catch (final Exception e) {
255             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
256             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
257             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
258         }
259     }
260
261     private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson, final User user, final ComponentTypeEnum componentTypeEnum) {
262         final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils()
263             .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
264                 componentTypeEnum);
265         return uiComponentEither.left().value().getInterfaces().values().stream().findFirst();
266     }
267 }