Fix node filter API payload retro-compatibility
[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 package org.openecomp.sdc.be.servlets;
20
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.apache.commons.lang3.StringUtils;
46 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.ComponentNodeFilterBusinessLogic;
48 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
49 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
50 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
51 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
52 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.dao.api.ActionStatus;
55 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.NodeFilterConstraintType;
58 import org.openecomp.sdc.be.impl.ComponentsUtils;
59 import org.openecomp.sdc.be.impl.ServletUtils;
60 import org.openecomp.sdc.be.model.User;
61 import org.openecomp.sdc.be.model.dto.FilterConstraintDto;
62 import org.openecomp.sdc.be.tosca.utils.NodeFilterConverter;
63 import org.openecomp.sdc.be.ui.mapper.FilterConstraintMapper;
64 import org.openecomp.sdc.be.ui.mapper.UIConstraintMapper;
65 import org.openecomp.sdc.be.ui.model.UIConstraint;
66 import org.openecomp.sdc.be.ui.model.UINodeFilter;
67 import org.openecomp.sdc.be.user.UserBusinessLogic;
68 import org.openecomp.sdc.common.api.Constants;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 @Path("/v1/catalog")
73 @Tag(name = "SDCE-2 APIs")
74 @Consumes(MediaType.APPLICATION_JSON)
75 @Produces(MediaType.APPLICATION_JSON)
76 @Singleton
77 public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
78
79     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.class);
80     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
81     private static final String MODIFIER_ID_IS = "modifier id is {}";
82     private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component";
83     private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter";
84     private static final String NODE_FILTER_CREATION = "Node Filter Creation";
85     private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error";
86     private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter";
87     private static final String NODE_FILTER_UPDATE = "Node Filter Update";
88     private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error";
89     private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter";
90     private static final String NODE_FILTER_DELETE = "Node Filter Delete";
91     private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error";
92     private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}";
93     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
94
95     @Inject
96     public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
97                                       final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
98                                       final ResourceImportManager resourceImportManager,
99                                       final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) {
100         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
101         this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
102     }
103
104     @POST
105     @Consumes(MediaType.APPLICATION_JSON)
106     @Produces(MediaType.APPLICATION_JSON)
107     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/nodeFilter")
108     @Operation(description = "Add Component Filter Constraint", method = "POST", summary = "Add Component Filter Constraint", responses = {
109         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
110         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
111         @ApiResponse(responseCode = "403", description = "Restricted operation"),
112         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
113     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
114     public Response addComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
115                                                  @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
116                                                  @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
117                                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
118                                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
119                                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
120                                                  @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
121                                                      NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
122                                                      NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
123                                                  @Context final HttpServletRequest request,
124                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
125         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
126         LOGGER.debug(MODIFIER_ID_IS, userId);
127         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
128         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
129         try {
130             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
131             if (nodeFilterConstraintType.isEmpty()) {
132                 return buildErrorResponse(
133                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
134             }
135             final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
136             if (uiConstraint == null) {
137                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
138                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
139             }
140             final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
141             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
142                 .addNodeFilter(componentId.toLowerCase(), componentInstanceId,
143                     filterConstraintDto, true, componentTypeEnum, nodeFilterConstraintType.get(),
144                     StringUtils.isEmpty(uiConstraint.getCapabilityName()) ? "" : uiConstraint.getCapabilityName());
145             if (actionResponse.isEmpty()) {
146                 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
147                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
148             }
149             final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
150             if (uiConstraint.isLegacyGetFunction()) {
151                 mapToLegacyResponse(uiNodeFilter);
152             }
153             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
154         } catch (final ComponentException e) {
155             throw e;
156         } catch (final BusinessLogicException e) {
157             return buildErrorResponse(e.getResponseFormat());
158         } catch (final Exception e) {
159             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
160             LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
161             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
162         }
163     }
164
165     @PUT
166     @Consumes(MediaType.APPLICATION_JSON)
167     @Produces(MediaType.APPLICATION_JSON)
168     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
169     @Operation(description = "Update Component Filter Constraint", method = "PUT", summary = "Update Component Filter Constraint", responses = {
170         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
171         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
172         @ApiResponse(responseCode = "403", description = "Restricted operation"),
173         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
174     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
175     public Response updateComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
176                                                     @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
177                                                     @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
178                                                     @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
179                                                         ComponentTypeEnum.RESOURCE_PARAM_NAME,
180                                                         ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
181                                                     @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
182                                                         NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
183                                                         NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
184                                                     @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
185                                                     @Context final HttpServletRequest request,
186                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
187         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
188         LOGGER.debug(MODIFIER_ID_IS, userId);
189         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
190         try {
191             final Optional<NodeFilterConstraintType> nodeFilterConstraintTypeOptional = NodeFilterConstraintType.parse(constraintType);
192             if (nodeFilterConstraintTypeOptional.isEmpty()) {
193                 return buildErrorResponse(
194                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
195             }
196             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
197             final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
198             if (uiConstraint == null) {
199                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
200                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
201             }
202             final NodeFilterConstraintType nodeFilterConstraintType = nodeFilterConstraintTypeOptional.get();
203             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
204                 .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, uiConstraint, componentTypeEnum, nodeFilterConstraintType,
205                     index);
206             if (actionResponse.isEmpty()) {
207                 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
208                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
209             }
210             final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
211             if (uiConstraint.isLegacyGetFunction()) {
212                 mapToLegacyResponse(uiNodeFilter);
213             }
214             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
215         } catch (final Exception e) {
216             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
217             LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
218             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
219         }
220     }
221
222     @DELETE
223     @Consumes(MediaType.APPLICATION_JSON)
224     @Produces(MediaType.APPLICATION_JSON)
225     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
226     @Operation(description = "Delete Component Filter Constraint", method = "Delete", summary = "Delete Component Filter Constraint", responses = {
227         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
228         @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"),
229         @ApiResponse(responseCode = "403", description = "Restricted operation"),
230         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
231     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
232     public Response deleteComponentFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
233                                                     @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
234                                                     @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
235                                                     @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
236                                                         ComponentTypeEnum.RESOURCE_PARAM_NAME,
237                                                         ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
238                                                     @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
239                                                         NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
240                                                         NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
241                                                     @Context final HttpServletRequest request,
242                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
243         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
244         LOGGER.debug(MODIFIER_ID_IS, userId);
245         componentNodeFilterBusinessLogic.validateUser(userId);
246         try {
247             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
248             if (nodeFilterConstraintType.isEmpty()) {
249                 return buildErrorResponse(
250                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
251             }
252             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
253                 .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, index, true,
254                     ComponentTypeEnum.findByParamName(componentType), nodeFilterConstraintType.get());
255             if (actionResponse.isEmpty()) {
256                 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
257                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
258             }
259             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
260                 new NodeFilterConverter().convertToUi(actionResponse.get()));
261         } catch (final Exception e) {
262             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
263             LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
264             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
265         }
266     }
267
268     private void mapToLegacyResponse(final UINodeFilter uiNodeFilter) {
269         if (CollectionUtils.isNotEmpty(uiNodeFilter.getProperties())) {
270             uiNodeFilter.setProperties(
271                 uiNodeFilter.getProperties().stream()
272                     .map(UIConstraintMapper::mapToLegacyConstraint)
273                     .collect(Collectors.toList())
274             );
275         }
276         if (CollectionUtils.isNotEmpty(uiNodeFilter.getCapabilities())) {
277             uiNodeFilter.setCapabilities(
278                 uiNodeFilter.getCapabilities().stream()
279                     .map(UIConstraintMapper::mapToLegacyConstraint)
280                     .collect(Collectors.toList())
281             );
282         }
283     }
284
285 }