55ff6f4a7ba87063e360f8effac1d7fb645b0af5
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ComponentSubstitutionFilterServlet.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.List;
29 import java.util.Optional;
30 import java.util.stream.Collectors;
31 import javax.inject.Inject;
32 import javax.inject.Singleton;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.ws.rs.Consumes;
35 import javax.ws.rs.DELETE;
36 import javax.ws.rs.HeaderParam;
37 import javax.ws.rs.POST;
38 import javax.ws.rs.PUT;
39 import javax.ws.rs.Path;
40 import javax.ws.rs.PathParam;
41 import javax.ws.rs.Produces;
42 import javax.ws.rs.core.Context;
43 import javax.ws.rs.core.MediaType;
44 import javax.ws.rs.core.Response;
45 import org.apache.commons.collections.CollectionUtils;
46 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.ComponentSubstitutionFilterBusinessLogic;
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.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition;
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.SubstitutionFilterConverter;
62 import org.openecomp.sdc.be.ui.mapper.FilterConstraintMapper;
63 import org.openecomp.sdc.be.ui.model.UIConstraint;
64 import org.openecomp.sdc.be.ui.model.UINodeFilter;
65 import org.openecomp.sdc.common.api.Constants;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 @Path("/v1/catalog/{componentType}/{componentId}/substitutionFilter/{constraintType}")
70 @Tag(name = "SDCE-2 APIs")
71 @Consumes(MediaType.APPLICATION_JSON)
72 @Produces(MediaType.APPLICATION_JSON)
73 @Singleton
74 public class ComponentSubstitutionFilterServlet extends AbstractValidationsServlet {
75
76     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentSubstitutionFilterServlet.class);
77     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
78     private static final String MODIFIER_ID_IS = "Modifier id is {}";
79     private static final String FAILED_TO_PARSE_COMPONENT = "Failed to parse component";
80     private static final String INVALID_CONSTRAINTYPE_ENUM = "Invalid value for NodeFilterConstraintType enum %s";
81     private static final String FAILED_TO_ADD_SUBSTITUTION_FILTER = "Failed to add substitution filter";
82     private static final String ADD_SUBSTITUTION_FILTER = "Add Substitution Filter";
83     private static final String ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR = "An unexpected error has occurred while adding a substitution filter";
84     private static final String FAILED_TO_UPDATE_SUBSTITUTION_FILTER = "Failed to update substitution filter";
85     private static final String SUBSTITUTION_FILTER_UPDATE = "Substitution Filter Update";
86     private static final String UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Update substitution filter with an error {}";
87     private static final String FAILED_TO_DELETE_SUBSTITUTION_FILTER = "Failed to delete substitution filter";
88     private static final String SUBSTITUTION_FILTER_DELETE = "Substitution Filter Delete";
89     private static final String DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Delete substitution filter with an error";
90     private static final List<ComponentTypeEnum> EXPECTED_COMPONENT_TYPES = List.of(ComponentTypeEnum.SERVICE, ComponentTypeEnum.RESOURCE);
91     private static final String EXPECTED_COMPONENT_TYPES_AS_STRING = EXPECTED_COMPONENT_TYPES.stream()
92         .map(ComponentTypeEnum::findParamByType)
93         .collect(Collectors.joining(", "));
94     private final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic;
95
96     @Inject
97     public ComponentSubstitutionFilterServlet(final ComponentInstanceBusinessLogic componentInstanceBL,
98                                               final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
99                                               final ResourceImportManager resourceImportManager,
100                                               final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic) {
101         super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
102         this.componentSubstitutionFilterBusinessLogic = componentSubstitutionFilterBusinessLogic;
103     }
104
105     @POST
106     @Consumes(MediaType.APPLICATION_JSON)
107     @Produces(MediaType.APPLICATION_JSON)
108     @Operation(description = "Add Component Substitution Filter Constraint", method = "POST", summary = "Add Component Substitution Filter Constraint", responses = {
109         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
110         @ApiResponse(responseCode = "201", description = "Add Substitution Filter Constraint"),
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 addSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData,
115                                           @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
116                                           @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
117                                               ComponentTypeEnum.SERVICE_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, @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 = componentSubstitutionFilterBusinessLogic.validateUser(userId);
126         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
127         try {
128             final Optional<UIConstraint> convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum);
129             if (convertResponse.isEmpty()) {
130                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
131                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
132             }
133             final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(convertResponse.get());
134             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
135             if (nodeFilterConstraintType.isEmpty()) {
136                 return buildErrorResponse(
137                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
138             }
139             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
140                 .addSubstitutionFilter(componentId.toLowerCase(), filterConstraintDto, true, componentTypeEnum);
141             if (actionResponse.isEmpty()) {
142                 LOGGER.error(FAILED_TO_ADD_SUBSTITUTION_FILTER);
143                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
144             }
145             final UINodeFilter uiFilter = new SubstitutionFilterConverter().convertToUi(actionResponse.get());
146             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiFilter);
147         } catch (final BusinessLogicException e) {
148             return buildErrorResponse(e.getResponseFormat());
149         } catch (final Exception e) {
150             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(ADD_SUBSTITUTION_FILTER);
151             LOGGER.error(ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
152             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
153         }
154     }
155
156     @PUT
157     @Consumes(MediaType.APPLICATION_JSON)
158     @Produces(MediaType.APPLICATION_JSON)
159     @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
160         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
161         @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
162         @ApiResponse(responseCode = "403", description = "Restricted operation"),
163         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
164     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
165     public Response updateSubstitutionFilters(@Parameter(description = "UIConstraint data", required = true) String constraintData,
166                                               @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
167                                               @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
168                                                   ComponentTypeEnum.SERVICE_PARAM_NAME,
169                                                   ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
170                                               @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
171                                                   NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
172                                                   NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
173                                               @Context final HttpServletRequest request,
174                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
175         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
176         LOGGER.debug(MODIFIER_ID_IS, userId);
177         final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
178         try {
179             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
180             final List<UIConstraint> uiConstraints = componentsUtils.validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
181             if (CollectionUtils.isEmpty(uiConstraints)) {
182                 LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, SUBSTITUTION_FILTER_UPDATE);
183                 return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to parse constraint data"));
184             }
185             final List<FilterConstraintDto> filterConstraintList = uiConstraints.stream()
186                 .map(uiConstraint -> new FilterConstraintMapper().mapFrom(uiConstraint))
187                 .collect(Collectors.toList());
188             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
189             if (nodeFilterConstraintType.isEmpty()) {
190                 return buildErrorResponse(
191                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
192             }
193             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
194                 .updateSubstitutionFilter(componentId.toLowerCase(), filterConstraintList, true, componentTypeEnum);
195             if (actionResponse.isEmpty()) {
196                 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
197                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
198             }
199             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
200                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
201         } catch (final BusinessLogicException e) {
202             return buildErrorResponse(e.getResponseFormat());
203         } catch (final Exception e) {
204             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
205             LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
206             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
207         }
208     }
209
210     @PUT
211     @Consumes(MediaType.APPLICATION_JSON)
212     @Produces(MediaType.APPLICATION_JSON)
213     @Path("/{constraintIndex}")
214     @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
215         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
216         @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
217         @ApiResponse(responseCode = "403", description = "Restricted operation"),
218         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
219     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
220     public Response updateSubstitutionFilter(@Parameter(description = "Filter constraint information", required = true) UIConstraint uiConstraint,
221                                              @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
222                                              @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
223                                              @Parameter(description = "The component type", schema = @Schema(allowableValues = {
224                                                  ComponentTypeEnum.SERVICE_PARAM_NAME,
225                                                  ComponentTypeEnum.RESOURCE_PARAM_NAME})) @PathParam("componentType") final String componentType,
226                                              @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
227                                                  NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
228                                                  NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
229                                              @Context final HttpServletRequest request,
230                                              @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
231         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
232         LOGGER.debug(MODIFIER_ID_IS, userId);
233         componentSubstitutionFilterBusinessLogic.validateUser(userId);
234         try {
235             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
236             if (componentTypeEnum == null || !EXPECTED_COMPONENT_TYPES.contains(componentTypeEnum)) {
237                 return buildErrorResponse(
238                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_COMPONENT_TYPE, componentType, EXPECTED_COMPONENT_TYPES_AS_STRING));
239             }
240             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
241             if (nodeFilterConstraintType.isEmpty()) {
242                 return buildErrorResponse(
243                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
244             }
245             final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
246
247             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
248                 .updateSubstitutionFilter(componentId.toLowerCase(), filterConstraintDto, index, true);
249             if (actionResponse.isEmpty()) {
250                 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
251                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
252             }
253             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
254                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
255         } catch (final BusinessLogicException e) {
256             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
257             LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
258             return buildErrorResponse(e.getResponseFormat());
259         } catch (final Exception e) {
260             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
261             LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
262             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
263         }
264     }
265
266     @DELETE
267     @Consumes(MediaType.APPLICATION_JSON)
268     @Produces(MediaType.APPLICATION_JSON)
269     @Path("/{constraintIndex}")
270     @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete", summary = "Delete Component Substitution Filter Constraint", responses = {
271         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
272         @ApiResponse(responseCode = "201", description = "Delete Substitution Filter Constraint"),
273         @ApiResponse(responseCode = "403", description = "Restricted operation"),
274         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
275     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
276     public Response deleteSubstitutionFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
277                                                        @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
278                                                        @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
279                                                            ComponentTypeEnum.SERVICE_PARAM_NAME,
280                                                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
281                                                        @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
282                                                            NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
283                                                            NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
284                                                        @Context final HttpServletRequest request,
285                                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
286         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
287         LOGGER.debug(MODIFIER_ID_IS, userId);
288         componentSubstitutionFilterBusinessLogic.validateUser(userId);
289         final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
290         if (!nodeFilterConstraintType.isPresent()) {
291             return buildErrorResponse(
292                 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
293         }
294         try {
295             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
296                 .deleteSubstitutionFilter(componentId.toLowerCase(), index, true, ComponentTypeEnum.findByParamName(componentType));
297             if (!actionResponse.isPresent()) {
298                 LOGGER.debug(FAILED_TO_DELETE_SUBSTITUTION_FILTER);
299                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
300             }
301             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
302                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
303         } catch (final Exception e) {
304             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_DELETE);
305             LOGGER.debug(DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
306             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
307         }
308     }
309 }