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.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.exceptions.BusinessLogicException;
50 import org.openecomp.sdc.be.config.BeEcompErrorManager;
51 import org.openecomp.sdc.be.dao.api.ActionStatus;
52 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.datatypes.enums.NodeFilterConstraintType;
55 import org.openecomp.sdc.be.impl.ComponentsUtils;
56 import org.openecomp.sdc.be.impl.ServletUtils;
57 import org.openecomp.sdc.be.model.User;
58 import org.openecomp.sdc.be.model.dto.FilterConstraintDto;
59 import org.openecomp.sdc.be.tosca.utils.SubstitutionFilterConverter;
60 import org.openecomp.sdc.be.ui.mapper.FilterConstraintMapper;
61 import org.openecomp.sdc.be.ui.model.UIConstraint;
62 import org.openecomp.sdc.be.ui.model.UINodeFilter;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 @Path("/v1/catalog/{componentType}/{componentId}/substitutionFilter/{constraintType}")
68 @Tag(name = "SDCE-2 APIs")
69 @Consumes(MediaType.APPLICATION_JSON)
70 @Produces(MediaType.APPLICATION_JSON)
72 public class ComponentSubstitutionFilterServlet extends AbstractValidationsServlet {
74 private static final Logger LOGGER = LoggerFactory.getLogger(ComponentSubstitutionFilterServlet.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 private static final String FAILED_TO_PARSE_COMPONENT = "Failed to parse component";
78 private static final String INVALID_CONSTRAINTYPE_ENUM = "Invalid value for NodeFilterConstraintType enum %s";
79 private static final String FAILED_TO_ADD_SUBSTITUTION_FILTER = "Failed to add substitution filter";
80 private static final String ADD_SUBSTITUTION_FILTER = "Add Substitution Filter";
81 private static final String ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR = "An unexpected error has occurred while adding a substitution filter";
82 private static final String FAILED_TO_UPDATE_SUBSTITUTION_FILTER = "Failed to update substitution filter";
83 private static final String SUBSTITUTION_FILTER_UPDATE = "Substitution Filter Update";
84 private static final String UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Update substitution filter with an error {}";
85 private static final String FAILED_TO_DELETE_SUBSTITUTION_FILTER = "Failed to delete substitution filter";
86 private static final String SUBSTITUTION_FILTER_DELETE = "Substitution Filter Delete";
87 private static final String DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Delete substitution filter with an error";
88 private static final List<ComponentTypeEnum> EXPECTED_COMPONENT_TYPES = List.of(ComponentTypeEnum.SERVICE, ComponentTypeEnum.RESOURCE);
89 private static final String EXPECTED_COMPONENT_TYPES_AS_STRING = EXPECTED_COMPONENT_TYPES.stream()
90 .map(ComponentTypeEnum::findParamByType)
91 .collect(Collectors.joining(", "));
92 private final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic;
95 public ComponentSubstitutionFilterServlet(final ComponentInstanceBusinessLogic componentInstanceBL,
96 final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
97 final ResourceImportManager resourceImportManager,
98 final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic) {
99 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
100 this.componentSubstitutionFilterBusinessLogic = componentSubstitutionFilterBusinessLogic;
104 @Consumes(MediaType.APPLICATION_JSON)
105 @Produces(MediaType.APPLICATION_JSON)
106 @Operation(description = "Add Component Substitution Filter Constraint", method = "POST", summary = "Add Component Substitution Filter Constraint", responses = {
107 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
108 @ApiResponse(responseCode = "201", description = "Add Substitution Filter Constraint"),
109 @ApiResponse(responseCode = "403", description = "Restricted operation"),
110 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
111 public Response addSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData,
112 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
113 @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
114 ComponentTypeEnum.SERVICE_PARAM_NAME,
115 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
116 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
117 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
118 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
119 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
120 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
121 LOGGER.debug(MODIFIER_ID_IS, userId);
122 final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
123 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
125 final Optional<UIConstraint> convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum);
126 if (convertResponse.isEmpty()) {
127 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
128 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
130 final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(convertResponse.get());
131 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
132 if (nodeFilterConstraintType.isEmpty()) {
133 return buildErrorResponse(
134 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
136 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
137 .addSubstitutionFilter(componentId.toLowerCase(), filterConstraintDto, true, componentTypeEnum);
138 if (actionResponse.isEmpty()) {
139 LOGGER.error(FAILED_TO_ADD_SUBSTITUTION_FILTER);
140 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
142 final UINodeFilter uiFilter = new SubstitutionFilterConverter().convertToUi(actionResponse.get());
143 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiFilter);
144 } catch (final BusinessLogicException e) {
145 return buildErrorResponse(e.getResponseFormat());
146 } catch (final Exception e) {
147 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(ADD_SUBSTITUTION_FILTER);
148 LOGGER.error(ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
149 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
154 @Consumes(MediaType.APPLICATION_JSON)
155 @Produces(MediaType.APPLICATION_JSON)
156 @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
157 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
158 @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
159 @ApiResponse(responseCode = "403", description = "Restricted operation"),
160 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
161 public Response updateSubstitutionFilters(@Parameter(description = "UIConstraint data", required = true) String constraintData,
162 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
163 @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
164 ComponentTypeEnum.SERVICE_PARAM_NAME,
165 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
166 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
167 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
168 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
169 @Context final HttpServletRequest request,
170 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
171 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
172 LOGGER.debug(MODIFIER_ID_IS, userId);
173 final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
175 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
176 final List<UIConstraint> uiConstraints = componentsUtils.validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
177 if (CollectionUtils.isEmpty(uiConstraints)) {
178 LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, SUBSTITUTION_FILTER_UPDATE);
179 return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to parse constraint data"));
181 final List<FilterConstraintDto> filterConstraintList = uiConstraints.stream()
182 .map(uiConstraint -> new FilterConstraintMapper().mapFrom(uiConstraint))
183 .collect(Collectors.toList());
184 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
185 if (nodeFilterConstraintType.isEmpty()) {
186 return buildErrorResponse(
187 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
189 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
190 .updateSubstitutionFilter(componentId.toLowerCase(), filterConstraintList, true, componentTypeEnum);
191 if (actionResponse.isEmpty()) {
192 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
193 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
195 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
196 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
197 } catch (final BusinessLogicException e) {
198 return buildErrorResponse(e.getResponseFormat());
199 } catch (final Exception e) {
200 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
201 LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
202 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
207 @Consumes(MediaType.APPLICATION_JSON)
208 @Produces(MediaType.APPLICATION_JSON)
209 @Path("/{constraintIndex}")
210 @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
211 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
212 @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
213 @ApiResponse(responseCode = "403", description = "Restricted operation"),
214 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
215 public Response updateSubstitutionFilter(@Parameter(description = "Filter constraint information", required = true) UIConstraint uiConstraint,
216 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
217 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
218 @Parameter(description = "The component type", schema = @Schema(allowableValues = {
219 ComponentTypeEnum.SERVICE_PARAM_NAME,
220 ComponentTypeEnum.RESOURCE_PARAM_NAME})) @PathParam("componentType") final String componentType,
221 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
222 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
223 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
224 @Context final HttpServletRequest request,
225 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
226 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
227 LOGGER.debug(MODIFIER_ID_IS, userId);
228 componentSubstitutionFilterBusinessLogic.validateUser(userId);
230 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
231 if (componentTypeEnum == null || !EXPECTED_COMPONENT_TYPES.contains(componentTypeEnum)) {
232 return buildErrorResponse(
233 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_COMPONENT_TYPE, componentType, EXPECTED_COMPONENT_TYPES_AS_STRING));
235 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
236 if (nodeFilterConstraintType.isEmpty()) {
237 return buildErrorResponse(
238 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
240 final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
242 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
243 .updateSubstitutionFilter(componentId.toLowerCase(), filterConstraintDto, index, true);
244 if (actionResponse.isEmpty()) {
245 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
246 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
248 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
249 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
250 } catch (final BusinessLogicException e) {
251 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
252 LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
253 return buildErrorResponse(e.getResponseFormat());
254 } catch (final Exception e) {
255 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
256 LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
257 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
262 @Consumes(MediaType.APPLICATION_JSON)
263 @Produces(MediaType.APPLICATION_JSON)
264 @Path("/{constraintIndex}")
265 @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete", summary = "Delete Component Substitution Filter Constraint", responses = {
266 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
267 @ApiResponse(responseCode = "201", description = "Delete Substitution Filter Constraint"),
268 @ApiResponse(responseCode = "403", description = "Restricted operation"),
269 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
270 public Response deleteSubstitutionFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
271 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
272 @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
273 ComponentTypeEnum.SERVICE_PARAM_NAME,
274 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
275 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
276 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
277 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
278 @Context final HttpServletRequest request,
279 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
280 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
281 LOGGER.debug(MODIFIER_ID_IS, userId);
282 componentSubstitutionFilterBusinessLogic.validateUser(userId);
283 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
284 if (!nodeFilterConstraintType.isPresent()) {
285 return buildErrorResponse(
286 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
289 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
290 .deleteSubstitutionFilter(componentId.toLowerCase(), index, true, ComponentTypeEnum.findByParamName(componentType));
291 if (!actionResponse.isPresent()) {
292 LOGGER.debug(FAILED_TO_DELETE_SUBSTITUTION_FILTER);
293 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
295 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
296 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
297 } catch (final Exception e) {
298 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_DELETE);
299 LOGGER.debug(DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
300 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));