2 * ============LICENSE_START=======================================================
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
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.servlets;
23 import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
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.common.api.Constants;
66 import org.openecomp.sdc.common.datastructure.Wrapper;
67 import org.openecomp.sdc.common.util.ValidationUtils;
68 import org.openecomp.sdc.exception.ResponseFormat;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.stereotype.Controller;
75 @Tag(name = "SDCE-2 APIs")
76 @Consumes(MediaType.APPLICATION_JSON)
77 @Produces(MediaType.APPLICATION_JSON)
78 @Server(url = "/sdc2/rest")
80 public class ComponentInterfaceOperationServlet extends AbstractValidationsServlet {
82 private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class);
83 private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
84 private static final String MODIFIER_ID_IS = "modifier id is {}";
85 private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = "failed to update Interface Operation on component instance {}";
86 private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance";
87 private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = "Failed to update Interface Operation with an error";
88 private static final String INTERFACE_OPERATION_CONTENT_INVALID = "Interface Operation content is invalid - {}";
89 private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
90 private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = "Interface Operation successfully updated on component instance with id {}";
91 private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic;
94 public ComponentInterfaceOperationServlet(final ComponentInstanceBusinessLogic componentInstanceBL,
95 final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
96 final ResourceImportManager resourceImportManager,
97 final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic) {
98 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
99 this.componentInterfaceOperationBusinessLogic = componentInterfaceOperationBusinessLogic;
103 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/interfaceOperation")
104 @Consumes(MediaType.APPLICATION_JSON)
105 @Produces(MediaType.APPLICATION_JSON)
106 @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
107 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
108 @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
109 @ApiResponse(responseCode = "403", description = "Restricted operation"),
110 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
111 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
112 public Response updateComponentInstanceInterfaceOperation(
113 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
114 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") String componentType,
115 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
116 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
117 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
118 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
119 userId = ValidationUtils.sanitizeInputString(userId);
120 componentType = ValidationUtils.sanitizeInputString(componentType);
121 componentInstanceId = ValidationUtils.sanitizeInputString(componentInstanceId);
122 LOGGER.debug(MODIFIER_ID_IS, userId);
123 final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
124 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
125 if (componentTypeEnum == null) {
126 LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
127 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
129 final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
130 if (bytes == null || bytes.length == 0) {
131 LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, "content is empty");
132 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
134 final String data = new String(bytes);
135 final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
136 if (mappedInterfaceOperationData.isEmpty()) {
137 LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
138 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
140 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
142 final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic.updateComponentInstanceInterfaceOperation(
143 componentId, componentInstanceId, mappedInterfaceOperationData.get(), componentTypeEnum, errorWrapper, true);
144 if (actionResponse.isEmpty()) {
145 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId);
146 return buildErrorResponse(errorWrapper.getInnerElement());
148 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId);
149 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
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));
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 byte[] bytes = IOUtils.toByteArray(request.getInputStream());
175 if (bytes == null || bytes.length == 0) {
176 LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID);
177 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
179 final ComponentTypeEnum componentType = RESOURCE;
180 final String data = new String(bytes);
181 final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentType);
182 if (mappedInterfaceOperationData.isEmpty()) {
183 LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
184 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
186 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
188 final Optional<Component> actionResponse = componentInterfaceOperationBusinessLogic
189 .updateResourceInterfaceOperation(componentId, userId, mappedInterfaceOperationData.get(), componentType,
191 if (actionResponse.isEmpty()) {
192 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentId);
193 return buildErrorResponse(errorWrapper.getInnerElement());
195 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentId);
196 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
198 } catch (final ComponentException e) {
199 //let it be handled by org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper
201 } catch (final Exception e) {
202 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
203 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
204 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
209 @Path("/{componentType}/{componentId}/resource/interfaceOperation")
210 @Consumes(MediaType.APPLICATION_JSON)
211 @Produces(MediaType.APPLICATION_JSON)
212 @Operation(description = "Create Interface Operation", method = "POST", summary = "Create Interface Operation on ComponentInstance", responses = {
213 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
214 @ApiResponse(responseCode = "201", description = "Create Interface Operation"),
215 @ApiResponse(responseCode = "403", description = "Restricted operation"),
216 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
217 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
218 public Response createInterfaceOperationInResource(
219 @Parameter(description = "valid values: resources", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME}))
220 @PathParam("componentType") final String componentType,
221 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
222 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
223 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
224 LOGGER.debug(MODIFIER_ID_IS, userId);
225 final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
226 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
227 if (componentTypeEnum == null) {
228 LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
229 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
231 final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
232 if (bytes == null || bytes.length == 0) {
233 LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID);
234 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
236 final String data = new String(bytes);
237 final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
238 if (mappedInterfaceOperationData.isEmpty()) {
239 LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
240 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
242 final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
244 final Optional<Component> actionResponse = componentInterfaceOperationBusinessLogic.createInterfaceOperationInResource(
245 componentId, mappedInterfaceOperationData.get(), componentTypeEnum, errorWrapper, true);
246 if (actionResponse.isEmpty()) {
247 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentId);
248 return buildErrorResponse(errorWrapper.getInnerElement());
250 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentId);
251 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
253 } catch (final Exception e) {
254 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
255 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
256 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
260 private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson, final User user, final ComponentTypeEnum componentTypeEnum) {
261 final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils()
262 .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
264 return uiComponentEither.left().value().getInterfaces().values().stream().findFirst();