Support complex types in interface operation inputs
[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 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.tags.Tag;
31 import io.swagger.v3.oas.annotations.tags.Tags;
32 import java.io.IOException;
33 import java.util.Optional;
34 import javax.servlet.http.HttpServletRequest;
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.apache.commons.io.IOUtils;
45 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
46 import org.openecomp.sdc.be.components.impl.ComponentInterfaceOperationBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
48 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
49 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
50 import org.openecomp.sdc.be.config.BeEcompErrorManager;
51 import org.openecomp.sdc.be.dao.api.ActionStatus;
52 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
53 import org.openecomp.sdc.be.impl.ComponentsUtils;
54 import org.openecomp.sdc.be.impl.ServletUtils;
55 import org.openecomp.sdc.be.model.ComponentInstance;
56 import org.openecomp.sdc.be.model.InterfaceDefinition;
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.UiComponentDataTransfer;
60 import org.openecomp.sdc.be.user.UserBusinessLogic;
61 import org.openecomp.sdc.common.api.Constants;
62 import org.openecomp.sdc.common.datastructure.Wrapper;
63 import org.openecomp.sdc.common.util.ValidationUtils;
64 import org.openecomp.sdc.exception.ResponseFormat;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.stereotype.Controller;
69
70 @Path("/v1/catalog/{componentType}/{componentId}/componentInstance/{componentInstanceId}/interfaceOperation")
71 @Tag(name = "SDCE-2 APIs")
72 @Consumes(MediaType.APPLICATION_JSON)
73 @Produces(MediaType.APPLICATION_JSON)
74 @Controller
75 public class ComponentInterfaceOperationServlet extends AbstractValidationsServlet {
76
77     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class);
78     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
79     private static final String MODIFIER_ID_IS = "modifier id is {}";
80     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = "failed to update Interface Operation on component instance {}";
81     private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance";
82     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = "Failed to update Interface Operation with an error";
83     private static final String INTERFACE_OPERATION_CONTENT_INVALID = "Interface Operation content is invalid - {}";
84     private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
85     private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = "Interface Operation successfully updated on component instance with id {}";
86     private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic;
87
88     @Autowired
89     public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
90                                               final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
91                                               final ResourceImportManager resourceImportManager,
92                                               final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic) {
93         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
94         this.componentInterfaceOperationBusinessLogic = componentInterfaceOperationBusinessLogic;
95     }
96
97     @PUT
98     @Consumes(MediaType.APPLICATION_JSON)
99     @Produces(MediaType.APPLICATION_JSON)
100     @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
101         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
102         @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
103         @ApiResponse(responseCode = "403", description = "Restricted operation"),
104         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
105     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
106     public Response updateComponentInstanceInterfaceOperation(
107         @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
108             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") String componentType,
109         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
110         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
111         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
112         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
113         userId = ValidationUtils.sanitizeInputString(userId);
114         componentType = ValidationUtils.sanitizeInputString(componentType);
115         componentInstanceId = ValidationUtils.sanitizeInputString(componentInstanceId);
116         LOGGER.debug(MODIFIER_ID_IS, userId);
117         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
118         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
119         if (componentTypeEnum == null) {
120             LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
121             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
122         }
123         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
124         if (bytes == null || bytes.length == 0) {
125             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, "content is empty");
126             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
127         }
128         final String data = new String(bytes);
129         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
130         if (mappedInterfaceOperationData.isEmpty()) {
131             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
132             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
133         }
134         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
135         try {
136             final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic
137                 .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(), componentTypeEnum,
138                     errorWrapper, true);
139             final Response response;
140             if (actionResponse.isEmpty()) {
141                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId);
142                 response = buildErrorResponse(errorWrapper.getInnerElement());
143             } else {
144                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId);
145                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
146             }
147             return response;
148         } catch (final Exception e) {
149             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
150             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
151             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
152         }
153     }
154
155     private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson, final User user, final ComponentTypeEnum componentTypeEnum) {
156         final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils()
157             .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
158                 componentTypeEnum);
159         return uiComponentEither.left().value().getInterfaces().values().stream().findFirst();
160     }
161 }