2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Nordix Foundation
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 * SPDX-License-Identifier: Apache-2.0
17 * ============LICENSE_END=========================================================
19 package org.openecomp.sdc.be.servlets;
21 import io.swagger.v3.oas.annotations.Operation;
22 import io.swagger.v3.oas.annotations.Parameter;
23 import io.swagger.v3.oas.annotations.media.ArraySchema;
24 import io.swagger.v3.oas.annotations.media.Content;
25 import io.swagger.v3.oas.annotations.media.Schema;
26 import io.swagger.v3.oas.annotations.responses.ApiResponse;
27 import io.swagger.v3.oas.annotations.tags.Tag;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30 import javax.inject.Inject;
31 import javax.inject.Singleton;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.ws.rs.Consumes;
34 import javax.ws.rs.DELETE;
35 import javax.ws.rs.HeaderParam;
36 import javax.ws.rs.POST;
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.collections4.CollectionUtils;
45 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
46 import org.openecomp.sdc.be.components.impl.ComponentNodeFilterBusinessLogic;
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.components.impl.exceptions.BusinessLogicException;
51 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
52 import org.openecomp.sdc.be.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.NodeFilterConstraintType;
57 import org.openecomp.sdc.be.impl.ComponentsUtils;
58 import org.openecomp.sdc.be.impl.ServletUtils;
59 import org.openecomp.sdc.be.model.User;
60 import org.openecomp.sdc.be.model.dto.FilterConstraintDto;
61 import org.openecomp.sdc.be.tosca.utils.NodeFilterConverter;
62 import org.openecomp.sdc.be.ui.mapper.FilterConstraintMapper;
63 import org.openecomp.sdc.be.ui.mapper.UIConstraintMapper;
64 import org.openecomp.sdc.be.ui.model.UIConstraint;
65 import org.openecomp.sdc.be.ui.model.UINodeFilter;
66 import org.openecomp.sdc.be.user.UserBusinessLogic;
67 import org.openecomp.sdc.common.api.Constants;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 @Tag(name = "SDCE-2 APIs")
73 @Consumes(MediaType.APPLICATION_JSON)
74 @Produces(MediaType.APPLICATION_JSON)
76 public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
78 private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.class);
79 private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
80 private static final String MODIFIER_ID_IS = "modifier id is {}";
81 private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component";
82 private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter";
83 private static final String NODE_FILTER_CREATION = "Node Filter Creation";
84 private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error";
85 private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter";
86 private static final String NODE_FILTER_UPDATE = "Node Filter Update";
87 private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error";
88 private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter";
89 private static final String NODE_FILTER_DELETE = "Node Filter Delete";
90 private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error";
91 private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}";
92 private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
95 public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
96 final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
97 final ResourceImportManager resourceImportManager,
98 final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) {
99 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
100 this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
104 @Consumes(MediaType.APPLICATION_JSON)
105 @Produces(MediaType.APPLICATION_JSON)
106 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/nodeFilter")
107 @Operation(description = "Add Component Filter Constraint", method = "POST", summary = "Add Component Filter Constraint", responses = {
108 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
109 @ApiResponse(responseCode = "201", description = "Create Component Filter"),
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 addComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
114 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
115 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
116 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
117 ComponentTypeEnum.RESOURCE_PARAM_NAME,
118 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
119 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
120 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
121 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
122 @Context final HttpServletRequest request,
123 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
124 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
125 LOGGER.debug(MODIFIER_ID_IS, userId);
126 final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
127 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
129 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
130 if (nodeFilterConstraintType.isEmpty()) {
131 return buildErrorResponse(
132 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
134 final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
135 if (uiConstraint == null) {
136 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
137 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
139 final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
140 final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
141 .addNodeFilter(componentId.toLowerCase(), componentInstanceId,
142 filterConstraintDto, true, componentTypeEnum, nodeFilterConstraintType.get());
143 if (actionResponse.isEmpty()) {
144 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
145 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
147 final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
148 if (uiConstraint.isLegacyGetFunction()) {
149 mapToLegacyResponse(uiNodeFilter);
151 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
152 } catch (final ComponentException e) {
154 } catch (final BusinessLogicException e) {
155 return buildErrorResponse(e.getResponseFormat());
156 } catch (final Exception e) {
157 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
158 LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
159 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
164 @Consumes(MediaType.APPLICATION_JSON)
165 @Produces(MediaType.APPLICATION_JSON)
166 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
167 @Operation(description = "Update Component Filter Constraint", method = "PUT", summary = "Update Component Filter Constraint", responses = {
168 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
169 @ApiResponse(responseCode = "201", description = "Create Component Filter"),
170 @ApiResponse(responseCode = "403", description = "Restricted operation"),
171 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
172 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
173 public Response updateComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
174 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
175 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
176 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
177 ComponentTypeEnum.RESOURCE_PARAM_NAME,
178 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
179 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
180 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
181 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
182 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
183 @Context final HttpServletRequest request,
184 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
185 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
186 LOGGER.debug(MODIFIER_ID_IS, userId);
187 final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
189 final Optional<NodeFilterConstraintType> nodeFilterConstraintTypeOptional = NodeFilterConstraintType.parse(constraintType);
190 if (nodeFilterConstraintTypeOptional.isEmpty()) {
191 return buildErrorResponse(
192 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
194 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
195 final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
196 if (uiConstraint == null) {
197 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
198 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
200 final NodeFilterConstraintType nodeFilterConstraintType = nodeFilterConstraintTypeOptional.get();
201 final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
202 .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, new FilterConstraintMapper().mapFrom(uiConstraint),
203 componentTypeEnum, nodeFilterConstraintType, index);
204 if (actionResponse.isEmpty()) {
205 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
206 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
208 final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
209 if (uiConstraint.isLegacyGetFunction()) {
210 mapToLegacyResponse(uiNodeFilter);
212 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
213 } catch (final Exception e) {
214 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
215 LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
216 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
221 @Consumes(MediaType.APPLICATION_JSON)
222 @Produces(MediaType.APPLICATION_JSON)
223 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
224 @Operation(description = "Delete Component Filter Constraint", method = "Delete", summary = "Delete Component Filter Constraint", responses = {
225 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
226 @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"),
227 @ApiResponse(responseCode = "403", description = "Restricted operation"),
228 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
229 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
230 public Response deleteComponentFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
231 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
232 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
233 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
234 ComponentTypeEnum.RESOURCE_PARAM_NAME,
235 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
236 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
237 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
238 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
239 @Context final HttpServletRequest request,
240 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
241 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
242 LOGGER.debug(MODIFIER_ID_IS, userId);
243 componentNodeFilterBusinessLogic.validateUser(userId);
245 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
246 if (nodeFilterConstraintType.isEmpty()) {
247 return buildErrorResponse(
248 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
250 final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
251 .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, index, true,
252 ComponentTypeEnum.findByParamName(componentType), nodeFilterConstraintType.get());
253 if (actionResponse.isEmpty()) {
254 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
255 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
257 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
258 new NodeFilterConverter().convertToUi(actionResponse.get()));
259 } catch (final Exception e) {
260 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
261 LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
262 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
266 private void mapToLegacyResponse(final UINodeFilter uiNodeFilter) {
267 if (CollectionUtils.isNotEmpty(uiNodeFilter.getProperties())) {
268 uiNodeFilter.setProperties(
269 uiNodeFilter.getProperties().stream()
270 .map(UIConstraintMapper::mapToLegacyConstraint)
271 .collect(Collectors.toList())
274 if (CollectionUtils.isNotEmpty(uiNodeFilter.getCapabilities())) {
275 uiNodeFilter.setCapabilities(
276 uiNodeFilter.getCapabilities().stream()
277 .map(UIConstraintMapper::mapToLegacyConstraint)
278 .collect(Collectors.toList())