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.common.api.Constants;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 @Tag(name = "SDCE-2 APIs")
72 @Consumes(MediaType.APPLICATION_JSON)
73 @Produces(MediaType.APPLICATION_JSON)
75 public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
77 private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.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_PARSE_COMPONENT = "failed to parse component";
81 private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter";
82 private static final String NODE_FILTER_CREATION = "Node Filter Creation";
83 private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error";
84 private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter";
85 private static final String NODE_FILTER_UPDATE = "Node Filter Update";
86 private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error";
87 private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter";
88 private static final String NODE_FILTER_DELETE = "Node Filter Delete";
89 private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error";
90 private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}";
91 private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
94 public ComponentNodeFilterServlet(final ComponentInstanceBusinessLogic componentInstanceBL,
95 final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
96 final ResourceImportManager resourceImportManager,
97 final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) {
98 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
99 this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
103 @Consumes(MediaType.APPLICATION_JSON)
104 @Produces(MediaType.APPLICATION_JSON)
105 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/nodeFilter")
106 @Operation(description = "Add Component Filter Constraint", method = "POST", summary = "Add Component Filter Constraint", responses = {
107 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
108 @ApiResponse(responseCode = "201", description = "Create Component Filter"),
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 addComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
113 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
114 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
115 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
116 ComponentTypeEnum.RESOURCE_PARAM_NAME,
117 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
118 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
119 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
120 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
121 @Context final HttpServletRequest request,
122 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
123 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
124 LOGGER.debug(MODIFIER_ID_IS, userId);
125 final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
126 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
128 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
129 if (nodeFilterConstraintType.isEmpty()) {
130 return buildErrorResponse(
131 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
133 final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
134 if (uiConstraint == null) {
135 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
136 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
138 final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
139 final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
140 .addNodeFilter(componentId.toLowerCase(), componentInstanceId,
141 filterConstraintDto, true, componentTypeEnum, nodeFilterConstraintType.get());
142 if (actionResponse.isEmpty()) {
143 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
144 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
146 final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
147 if (uiConstraint.isLegacyGetFunction()) {
148 mapToLegacyResponse(uiNodeFilter);
150 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
151 } catch (final ComponentException e) {
153 } catch (final BusinessLogicException e) {
154 return buildErrorResponse(e.getResponseFormat());
155 } catch (final Exception e) {
156 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
157 LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
158 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
163 @Consumes(MediaType.APPLICATION_JSON)
164 @Produces(MediaType.APPLICATION_JSON)
165 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
166 @Operation(description = "Update Component Filter Constraint", method = "PUT", summary = "Update Component Filter Constraint", responses = {
167 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
168 @ApiResponse(responseCode = "201", description = "Create Component Filter"),
169 @ApiResponse(responseCode = "403", description = "Restricted operation"),
170 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
171 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
172 public Response updateComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
173 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
174 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
175 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
176 ComponentTypeEnum.RESOURCE_PARAM_NAME,
177 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
178 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
179 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
180 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
181 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
182 @Context final HttpServletRequest request,
183 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
184 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
185 LOGGER.debug(MODIFIER_ID_IS, userId);
186 final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
188 final Optional<NodeFilterConstraintType> nodeFilterConstraintTypeOptional = NodeFilterConstraintType.parse(constraintType);
189 if (nodeFilterConstraintTypeOptional.isEmpty()) {
190 return buildErrorResponse(
191 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
193 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
194 final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
195 if (uiConstraint == null) {
196 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
197 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
199 final NodeFilterConstraintType nodeFilterConstraintType = nodeFilterConstraintTypeOptional.get();
200 final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
201 .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, new FilterConstraintMapper().mapFrom(uiConstraint),
202 componentTypeEnum, nodeFilterConstraintType, index);
203 if (actionResponse.isEmpty()) {
204 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
205 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
207 final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
208 if (uiConstraint.isLegacyGetFunction()) {
209 mapToLegacyResponse(uiNodeFilter);
211 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
212 } catch (final Exception e) {
213 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
214 LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
215 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
220 @Consumes(MediaType.APPLICATION_JSON)
221 @Produces(MediaType.APPLICATION_JSON)
222 @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
223 @Operation(description = "Delete Component Filter Constraint", method = "Delete", summary = "Delete Component Filter Constraint", responses = {
224 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
225 @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"),
226 @ApiResponse(responseCode = "403", description = "Restricted operation"),
227 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
228 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
229 public Response deleteComponentFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
230 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
231 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
232 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
233 ComponentTypeEnum.RESOURCE_PARAM_NAME,
234 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
235 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
236 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
237 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
238 @Context final HttpServletRequest request,
239 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
240 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
241 LOGGER.debug(MODIFIER_ID_IS, userId);
242 componentNodeFilterBusinessLogic.validateUser(userId);
244 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
245 if (nodeFilterConstraintType.isEmpty()) {
246 return buildErrorResponse(
247 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
249 final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
250 .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, index, true,
251 ComponentTypeEnum.findByParamName(componentType), nodeFilterConstraintType.get());
252 if (actionResponse.isEmpty()) {
253 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
254 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
256 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
257 new NodeFilterConverter().convertToUi(actionResponse.get()));
258 } catch (final Exception e) {
259 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
260 LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
261 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
265 private void mapToLegacyResponse(final UINodeFilter uiNodeFilter) {
266 if (CollectionUtils.isNotEmpty(uiNodeFilter.getProperties())) {
267 uiNodeFilter.setProperties(
268 uiNodeFilter.getProperties().stream()
269 .map(UIConstraintMapper::mapToLegacyConstraint)
270 .collect(Collectors.toList())
273 if (CollectionUtils.isNotEmpty(uiNodeFilter.getCapabilities())) {
274 uiNodeFilter.setCapabilities(
275 uiNodeFilter.getCapabilities().stream()
276 .map(UIConstraintMapper::mapToLegacyConstraint)
277 .collect(Collectors.toList())