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.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.be.user.UserBusinessLogic;
66 import org.openecomp.sdc.common.api.Constants;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 @Path("/v1/catalog/{componentType}/{componentId}/substitutionFilter/{constraintType}")
71 @Tag(name = "SDCE-2 APIs")
72 @Consumes(MediaType.APPLICATION_JSON)
73 @Produces(MediaType.APPLICATION_JSON)
75 public class ComponentSubstitutionFilterServlet extends AbstractValidationsServlet {
77 private static final Logger LOGGER = LoggerFactory.getLogger(ComponentSubstitutionFilterServlet.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 INVALID_CONSTRAINTYPE_ENUM = "Invalid value for NodeFilterConstraintType enum %s";
82 private static final String FAILED_TO_ADD_SUBSTITUTION_FILTER = "Failed to add substitution filter";
83 private static final String ADD_SUBSTITUTION_FILTER = "Add Substitution Filter";
84 private static final String ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR = "An unexpected error has occurred while adding a substitution filter";
85 private static final String FAILED_TO_UPDATE_SUBSTITUTION_FILTER = "Failed to update substitution filter";
86 private static final String SUBSTITUTION_FILTER_UPDATE = "Substitution Filter Update";
87 private static final String UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Update substitution filter with an error {}";
88 private static final String FAILED_TO_DELETE_SUBSTITUTION_FILTER = "Failed to delete substitution filter";
89 private static final String SUBSTITUTION_FILTER_DELETE = "Substitution Filter Delete";
90 private static final String DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Delete substitution filter with an error";
91 private static final List<ComponentTypeEnum> EXPECTED_COMPONENT_TYPES = List.of(ComponentTypeEnum.SERVICE, ComponentTypeEnum.RESOURCE);
92 private static final String EXPECTED_COMPONENT_TYPES_AS_STRING = EXPECTED_COMPONENT_TYPES.stream()
93 .map(ComponentTypeEnum::findParamByType)
94 .collect(Collectors.joining(", "));
95 private final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic;
98 public ComponentSubstitutionFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
99 final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
100 final ResourceImportManager resourceImportManager,
101 final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic) {
102 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
103 this.componentSubstitutionFilterBusinessLogic = componentSubstitutionFilterBusinessLogic;
107 @Consumes(MediaType.APPLICATION_JSON)
108 @Produces(MediaType.APPLICATION_JSON)
109 @Operation(description = "Add Component Substitution Filter Constraint", method = "POST", summary = "Add Component Substitution Filter Constraint", responses = {
110 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
111 @ApiResponse(responseCode = "201", description = "Add Substitution Filter Constraint"),
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 addSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData,
116 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
117 @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
118 ComponentTypeEnum.SERVICE_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, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
124 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
125 LOGGER.debug(MODIFIER_ID_IS, userId);
126 final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
127 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
129 final Optional<UIConstraint> convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum);
130 if (convertResponse.isEmpty()) {
131 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
132 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
134 final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(convertResponse.get());
135 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
136 if (nodeFilterConstraintType.isEmpty()) {
137 return buildErrorResponse(
138 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
140 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
141 .addSubstitutionFilter(componentId.toLowerCase(), filterConstraintDto, true, componentTypeEnum);
142 if (actionResponse.isEmpty()) {
143 LOGGER.error(FAILED_TO_ADD_SUBSTITUTION_FILTER);
144 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
146 final UINodeFilter uiFilter = new SubstitutionFilterConverter().convertToUi(actionResponse.get());
147 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiFilter);
148 } catch (final BusinessLogicException e) {
149 return buildErrorResponse(e.getResponseFormat());
150 } catch (final Exception e) {
151 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(ADD_SUBSTITUTION_FILTER);
152 LOGGER.error(ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
153 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
158 @Consumes(MediaType.APPLICATION_JSON)
159 @Produces(MediaType.APPLICATION_JSON)
160 @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
161 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
162 @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
163 @ApiResponse(responseCode = "403", description = "Restricted operation"),
164 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
165 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
166 public Response updateSubstitutionFilters(@Parameter(description = "UIConstraint data", required = true) String constraintData,
167 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
168 @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
169 ComponentTypeEnum.SERVICE_PARAM_NAME,
170 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
171 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
172 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
173 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
174 @Context final HttpServletRequest request,
175 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
176 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
177 LOGGER.debug(MODIFIER_ID_IS, userId);
178 final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
180 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
181 final List<UIConstraint> uiConstraints = componentsUtils.validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
182 if (CollectionUtils.isEmpty(uiConstraints)) {
183 LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, SUBSTITUTION_FILTER_UPDATE);
184 return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to parse constraint data"));
186 final List<FilterConstraintDto> filterConstraintList = uiConstraints.stream()
187 .map(uiConstraint -> new FilterConstraintMapper().mapFrom(uiConstraint))
188 .collect(Collectors.toList());
189 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
190 if (nodeFilterConstraintType.isEmpty()) {
191 return buildErrorResponse(
192 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
194 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
195 .updateSubstitutionFilter(componentId.toLowerCase(), filterConstraintList, true, componentTypeEnum);
196 if (actionResponse.isEmpty()) {
197 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
198 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
200 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
201 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
202 } catch (final BusinessLogicException e) {
203 return buildErrorResponse(e.getResponseFormat());
204 } catch (final Exception e) {
205 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
206 LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
207 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
212 @Consumes(MediaType.APPLICATION_JSON)
213 @Produces(MediaType.APPLICATION_JSON)
214 @Path("/{constraintIndex}")
215 @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
216 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
217 @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
218 @ApiResponse(responseCode = "403", description = "Restricted operation"),
219 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
220 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
221 public Response updateSubstitutionFilter(@Parameter(description = "Filter constraint information", required = true) UIConstraint uiConstraint,
222 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
223 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
224 @Parameter(description = "The component type", schema = @Schema(allowableValues = {
225 ComponentTypeEnum.SERVICE_PARAM_NAME,
226 ComponentTypeEnum.RESOURCE_PARAM_NAME})) @PathParam("componentType") final String componentType,
227 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
228 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
229 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
230 @Context final HttpServletRequest request,
231 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
232 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
233 LOGGER.debug(MODIFIER_ID_IS, userId);
234 componentSubstitutionFilterBusinessLogic.validateUser(userId);
236 final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
237 if (componentTypeEnum == null || !EXPECTED_COMPONENT_TYPES.contains(componentTypeEnum)) {
238 return buildErrorResponse(
239 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_COMPONENT_TYPE, componentType, EXPECTED_COMPONENT_TYPES_AS_STRING));
241 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
242 if (nodeFilterConstraintType.isEmpty()) {
243 return buildErrorResponse(
244 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
246 final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
248 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
249 .updateSubstitutionFilter(componentId.toLowerCase(), filterConstraintDto, index , true);
250 if (actionResponse.isEmpty()) {
251 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
252 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
254 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
255 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
256 } catch (final BusinessLogicException e) {
257 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
258 LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
259 return buildErrorResponse(e.getResponseFormat());
260 } catch (final Exception e) {
261 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
262 LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
263 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
268 @Consumes(MediaType.APPLICATION_JSON)
269 @Produces(MediaType.APPLICATION_JSON)
270 @Path("/{constraintIndex}")
271 @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete", summary = "Delete Component Substitution Filter Constraint", responses = {
272 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
273 @ApiResponse(responseCode = "201", description = "Delete Substitution Filter Constraint"),
274 @ApiResponse(responseCode = "403", description = "Restricted operation"),
275 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
276 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
277 public Response deleteSubstitutionFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
278 @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
279 @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
280 ComponentTypeEnum.SERVICE_PARAM_NAME,
281 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
282 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
283 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
284 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
285 @Context final HttpServletRequest request,
286 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
287 LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
288 LOGGER.debug(MODIFIER_ID_IS, userId);
289 componentSubstitutionFilterBusinessLogic.validateUser(userId);
290 final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
291 if (!nodeFilterConstraintType.isPresent()) {
292 return buildErrorResponse(
293 getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
296 final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
297 .deleteSubstitutionFilter(componentId.toLowerCase(), index, true, ComponentTypeEnum.findByParamName(componentType));
298 if (!actionResponse.isPresent()) {
299 LOGGER.debug(FAILED_TO_DELETE_SUBSTITUTION_FILTER);
300 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
302 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
303 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
304 } catch (final Exception e) {
305 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_DELETE);
306 LOGGER.debug(DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
307 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));