Add support for updating interface operations
[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
22 package org.openecomp.sdc.be.servlets;
23
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 java.io.IOException;
32 import java.util.Optional;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.ws.rs.Consumes;
35 import javax.ws.rs.HeaderParam;
36 import javax.ws.rs.PUT;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.PathParam;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import org.apache.commons.io.IOUtils;
44 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
45 import org.openecomp.sdc.be.components.impl.ComponentInterfaceOperationBusinessLogic;
46 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
47 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
48 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
49 import org.openecomp.sdc.be.config.BeEcompErrorManager;
50 import org.openecomp.sdc.be.dao.api.ActionStatus;
51 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
52 import org.openecomp.sdc.be.impl.ComponentsUtils;
53 import org.openecomp.sdc.be.impl.ServletUtils;
54 import org.openecomp.sdc.be.model.ComponentInstance;
55 import org.openecomp.sdc.be.model.InterfaceDefinition;
56 import org.openecomp.sdc.be.model.User;
57 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
58 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
59 import org.openecomp.sdc.be.user.UserBusinessLogic;
60 import org.openecomp.sdc.common.api.Constants;
61 import org.openecomp.sdc.common.datastructure.Wrapper;
62 import org.openecomp.sdc.exception.ResponseFormat;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.springframework.beans.factory.annotation.Autowired;
66 import org.springframework.stereotype.Controller;
67
68 @Path("/v1/catalog/{componentType}/{componentId}/componentInstance/{componentInstanceId}/interfaceOperation")
69 @Consumes(MediaType.APPLICATION_JSON)
70 @Produces(MediaType.APPLICATION_JSON)
71 @Controller
72 public class ComponentInterfaceOperationServlet extends AbstractValidationsServlet {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class);
75     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
76     private static final String MODIFIER_ID_IS = "modifier id is {}";
77
78     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION =
79         "failed to update Interface Operation on component instance {}";
80     private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance";
81     private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR =
82         "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 =
86         "Interface Operation successfully updated on component instance with id {}";
87
88     private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic;
89
90     @Autowired
91     public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic,
92                                               final ComponentInstanceBusinessLogic componentInstanceBL,
93                                               final ComponentsUtils componentsUtils,
94                                               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     @Consumes(MediaType.APPLICATION_JSON)
103     @Produces(MediaType.APPLICATION_JSON)
104     @Operation(description = "Update Interface Operation", method = "PUT",
105         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",
113             schema = @Schema(allowableValues = {
114                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
115                 ComponentTypeEnum.SERVICE_PARAM_NAME}))
116         @PathParam("componentType") final String componentType,
117         @Parameter(description = "Component Id")
118         @PathParam("componentId") String componentId,
119         @Parameter(description = "Component Instance Id")
120         @PathParam("componentInstanceId") String componentInstanceId,
121         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
122         throws IOException {
123
124         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
125         LOGGER.debug(MODIFIER_ID_IS, userId);
126
127         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
128         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
129         if (componentTypeEnum == null) {
130             LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
131             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
132         }
133
134         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
135         if (bytes == null || bytes.length == 0) {
136             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID);
137             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
138         }
139         final String data = new String(bytes);
140
141         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
142         if (mappedInterfaceOperationData.isEmpty()) {
143             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
144             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
145         }
146         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
147         try {
148              final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic
149                 .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(),
150                     componentTypeEnum, errorWrapper, true);
151
152             final Response response;
153             if (actionResponse.isEmpty()) {
154                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId);
155                 response = buildErrorResponse(errorWrapper.getInnerElement());
156             } else {
157                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId);
158                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
159             }
160
161             return response;
162
163         } catch (final Exception e) {
164             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
165             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
166             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
167         }
168     }
169
170     private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson,
171                                                                  final User user,
172                                                                  final ComponentTypeEnum componentTypeEnum) {
173         final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither =
174             getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user,
175                 UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, componentTypeEnum);
176         return uiComponentEither.left().value().getInterfaces().values().stream().findFirst();
177     }
178
179 }