Delete node_filter capabilities
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ComponentNodeFilterServlet.java
1 /*
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
8  *
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.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.sdc.be.servlets;
21
22 import io.swagger.v3.oas.annotations.Operation;
23 import io.swagger.v3.oas.annotations.Parameter;
24 import io.swagger.v3.oas.annotations.media.ArraySchema;
25 import io.swagger.v3.oas.annotations.media.Content;
26 import io.swagger.v3.oas.annotations.media.Schema;
27 import io.swagger.v3.oas.annotations.responses.ApiResponse;
28 import java.util.List;
29 import java.util.Optional;
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.collections.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.utils.NodeFilterConstraintAction;
51 import org.openecomp.sdc.be.config.BeEcompErrorManager;
52 import org.openecomp.sdc.be.dao.api.ActionStatus;
53 import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor;
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.tosca.utils.NodeFilterConverter;
61 import org.openecomp.sdc.be.ui.model.UIConstraint;
62 import org.openecomp.sdc.be.ui.model.UINodeFilter;
63 import org.openecomp.sdc.be.user.UserBusinessLogic;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 @Path("/v1/catalog/{componentType}/{componentId}/resourceInstances/{componentInstanceId}/nodeFilter/{constraintType}")
69 @Consumes(MediaType.APPLICATION_JSON)
70 @Produces(MediaType.APPLICATION_JSON)
71 @Singleton
72 public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.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_PARSE_COMPONENT = "failed to parse component";
79
80     private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter";
81     private static final String NODE_FILTER_CREATION = "Node Filter Creation";
82     private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error";
83
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
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
92     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
93
94     @Inject
95     public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic,
96                                       final ComponentInstanceBusinessLogic componentInstanceBL,
97                                       final ComponentsUtils componentsUtils,
98                                       final ServletUtils servletUtils,
99                                       final ResourceImportManager resourceImportManager,
100                                       final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) {
101         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
102         this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
103     }
104
105     @POST
106     @Consumes(MediaType.APPLICATION_JSON)
107     @Produces(MediaType.APPLICATION_JSON)
108     @Operation(description = "Add Component Filter Constraint", method = "POST",
109         summary = "Add Component Filter Constraint", responses = {
110         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
111         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
112         @ApiResponse(responseCode = "403", description = "Restricted operation"),
113         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
114     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
115     public Response addComponentFilterConstraint(
116         @Parameter(description = "UIConstraint data", required = true) String constraintData,
117         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
118         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
119         @Parameter(description = "valid values: resources / services",
120             schema = @Schema(allowableValues = {
121                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
122                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
123         @Parameter(description = "Constraint type. Valid values: properties / capabilities",
124             schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
125                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
126         @PathParam("constraintType") final String constraintType,
127         @Context final HttpServletRequest request,
128         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
129
130         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
131         LOGGER.debug(MODIFIER_ID_IS, userId);
132         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
133
134         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
135         try {
136             final Optional<UIConstraint> convertResponse = componentsUtils
137                 .parseToConstraint(constraintData, userModifier, componentTypeEnum);
138             if (!convertResponse.isPresent()) {
139                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
140                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
141             }
142             final UIConstraint uiConstraint = convertResponse.get();
143             final String constraint = new ConstraintConvertor().convert(uiConstraint);
144
145             final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
146                 NodeFilterConstraintType.parse(constraintType);
147             if (!nodeFilterConstraintType.isPresent()) {
148                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
149                     "Invalid value for NodeFilterConstraintType enum %s", constraintType));
150             }
151
152             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
153                 .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD,
154                     uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum,
155                     nodeFilterConstraintType.get());
156
157             if (!actionResponse.isPresent()) {
158                 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
159                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
160             }
161             final UINodeFilter nodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
162
163             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeFilter);
164
165         } catch (final Exception e) {
166             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
167             LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
168             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
169         }
170     }
171
172     @PUT
173     @Consumes(MediaType.APPLICATION_JSON)
174     @Produces(MediaType.APPLICATION_JSON)
175     @Operation(description = "Update Component Filter Constraint", method = "PUT",
176         summary = "Update Component Filter Constraint", responses = {
177         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
178         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
179         @ApiResponse(responseCode = "403", description = "Restricted operation"),
180         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
181     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
182     public Response updateComponentFilterConstraint(
183         @Parameter(description = "UIConstraint data", required = true) String constraintData,
184         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
185         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
186         @Parameter(description = "valid values: resources / services",
187             schema = @Schema(allowableValues = {
188                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
189                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
190         @Parameter(description = "Constraint type. Valid values: properties / capabilities",
191             schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
192                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
193         @PathParam("constraintType") final String constraintType,
194         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
195
196         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
197         LOGGER.debug(MODIFIER_ID_IS, userId);
198         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
199
200         try {
201             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
202             final List<UIConstraint>  uiConstraints = componentsUtils
203                 .validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
204             if (CollectionUtils.isEmpty(uiConstraints)) {
205                 LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, NODE_FILTER_UPDATE);
206                 return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
207                     "Failed to parse constraint data", constraintData));
208             }
209             final List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints);
210             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
211                 .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, constraints,
212                     true, componentTypeEnum);
213
214             if (!actionResponse.isPresent()) {
215                 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
216                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
217             }
218
219             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
220                 new NodeFilterConverter().convertToUi(actionResponse.get()));
221
222         } catch (final Exception e) {
223             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
224             LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
225             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
226         }
227     }
228
229     @DELETE
230     @Consumes(MediaType.APPLICATION_JSON)
231     @Produces(MediaType.APPLICATION_JSON)
232     @Path("/{constraintIndex}")
233     @Operation(description = "Delete Component Filter Constraint", method = "Delete",
234         summary = "Delete Component Filter Constraint", responses = {
235         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
236         @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"),
237         @ApiResponse(responseCode = "403", description = "Restricted operation"),
238         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
239     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
240     public Response deleteComponentFilterConstraint(
241         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
242         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
243         @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
244         @Parameter(description = "valid values: resources / services",
245             schema = @Schema(allowableValues = {
246                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
247                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
248         @Parameter(description = "Constraint type. Valid values: properties / capabilities",
249             schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
250                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
251         @PathParam("constraintType") final String constraintType,
252         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
253
254         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
255         LOGGER.debug(MODIFIER_ID_IS, userId);
256         componentNodeFilterBusinessLogic.validateUser(userId);
257
258         try {
259             final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
260                 NodeFilterConstraintType.parse(constraintType);
261             if (!nodeFilterConstraintType.isPresent()) {
262                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
263                     "Invalid value for NodeFilterConstraintType enum %s", constraintType));
264             }
265             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
266                 .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE,
267                     null, index, true, ComponentTypeEnum.findByParamName(componentType),
268                     nodeFilterConstraintType.get());
269
270             if (!actionResponse.isPresent()) {
271                 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
272                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
273             }
274
275             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
276                 new NodeFilterConverter().convertToUi(actionResponse.get()));
277
278         } catch (final Exception e) {
279             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
280             LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
281             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
282
283         }
284     }
285
286 }