4a44c202f351cf1452010242e3113c5fda4a98e6
[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
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.ComponentSubstitutionFilterBusinessLogic;
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.config.BeEcompErrorManager;
51 import org.openecomp.sdc.be.dao.api.ActionStatus;
52 import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor;
53 import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.NodeFilterConstraintType;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.impl.ServletUtils;
58 import org.openecomp.sdc.be.model.User;
59 import org.openecomp.sdc.be.tosca.utils.SubstitutionFilterConverter;
60 import org.openecomp.sdc.be.ui.model.UIConstraint;
61 import org.openecomp.sdc.be.ui.model.UINodeFilter;
62 import org.openecomp.sdc.be.user.UserBusinessLogic;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 @Path("/v1/catalog/{componentType}/{componentId}/substitutionFilter/{constraintType}")
68 @Consumes(MediaType.APPLICATION_JSON)
69 @Produces(MediaType.APPLICATION_JSON)
70 @Singleton
71 public class ComponentSubstitutionFilterServlet extends AbstractValidationsServlet {
72
73     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentSubstitutionFilterServlet.class);
74     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
75     private static final String MODIFIER_ID_IS = "Modifier id is {}";
76     private static final String FAILED_TO_PARSE_COMPONENT = "Failed to parse component";
77     private static final String INVALID_CONSTRAINTYPE_ENUM = "Invalid value for NodeFilterConstraintType enum %s";
78
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 = "Add substitution filter with an error";
82
83     private static final String FAILED_TO_UPDATE_SUBSTITUTION_FILTER = "Failed to update substitution filter";
84     private static final String SUBSTITUTION_FILTER_UPDATE = "Substitution Filter Update";
85     private static final String UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Update substitution filter with an error {}";
86
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
91     private final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic;
92
93     @Inject
94     public ComponentSubstitutionFilterServlet(final UserBusinessLogic userBusinessLogic,
95                                               final ComponentInstanceBusinessLogic componentInstanceBL,
96                                               final ComponentsUtils componentsUtils,
97                                               final ServletUtils servletUtils,
98                                               final ResourceImportManager resourceImportManager,
99                                               final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic) {
100         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
101         this.componentSubstitutionFilterBusinessLogic = componentSubstitutionFilterBusinessLogic;
102     }
103
104     @POST
105     @Consumes(MediaType.APPLICATION_JSON)
106     @Produces(MediaType.APPLICATION_JSON)
107     @Operation(description = "Add Component Substitution Filter Constraint", method = "POST",
108         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(
115         @Parameter(description = "UIConstraint data", required = true) String constraintData,
116         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
117         @Parameter(description = "valid value: resources / services",
118             schema = @Schema(allowableValues = {
119                 ComponentTypeEnum.SERVICE_PARAM_NAME,
120                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
121         @Parameter(description = "Constraint type. Valid values: properties / capabilities",
122             schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
123                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
124         @PathParam("constraintType") final String constraintType,
125         @Context final HttpServletRequest request,
126         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
127
128         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
129         LOGGER.debug(MODIFIER_ID_IS, userId);
130         final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
131
132         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
133         try {
134             final Optional<UIConstraint> convertResponse = componentsUtils
135                 .parseToConstraint(constraintData, userModifier, componentTypeEnum);
136             if (convertResponse.isEmpty()) {
137                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
138                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
139             }
140
141             final UIConstraint uiConstraint = convertResponse.get();
142             final String constraint = new ConstraintConvertor().convert(uiConstraint);
143
144             final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
145                 NodeFilterConstraintType.parse(constraintType);
146             if (nodeFilterConstraintType.isEmpty()) {
147                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
148                         INVALID_CONSTRAINTYPE_ENUM, constraintType));
149             }
150
151             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
152                 .addSubstitutionFilter(componentId.toLowerCase(),
153                     uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum);
154
155             if (actionResponse.isEmpty()) {
156                 LOGGER.error(FAILED_TO_ADD_SUBSTITUTION_FILTER);
157                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
158             }
159             final UINodeFilter uiFilter = new SubstitutionFilterConverter().convertToUi(actionResponse.get());
160
161             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiFilter);
162
163         } catch (final Exception e) {
164             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(ADD_SUBSTITUTION_FILTER);
165             LOGGER.error(ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
166             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
167         }
168     }
169
170     @PUT
171     @Consumes(MediaType.APPLICATION_JSON)
172     @Produces(MediaType.APPLICATION_JSON)
173     @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT",
174         summary = "Update Component Substitution Filter Constraint", responses = {
175         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
176         @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
177         @ApiResponse(responseCode = "403", description = "Restricted operation"),
178         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
179     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
180     public Response updateSubstitutionFilter(
181         @Parameter(description = "UIConstraint data", required = true) String constraintData,
182         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
183         @Parameter(description = "valid value: resources / services",
184             schema = @Schema(allowableValues = {
185                 ComponentTypeEnum.SERVICE_PARAM_NAME,
186                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
187         @Parameter(description = "Constraint type. Valid values: properties / capabilities",
188             schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
189                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
190         @PathParam("constraintType") final String constraintType,
191         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
192
193         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
194         LOGGER.debug(MODIFIER_ID_IS, userId);
195         final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
196
197         try {
198             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
199             final List<UIConstraint>  uiConstraints = componentsUtils
200                 .validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
201             if (CollectionUtils.isEmpty(uiConstraints)) {
202                 LOGGER.error("Failed to Parse Constraint data {} when executing {} ",
203                     constraintData, SUBSTITUTION_FILTER_UPDATE);
204                 return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
205                     "Failed to parse constraint data"));
206             }
207
208             final List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints);
209             final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
210                 NodeFilterConstraintType.parse(constraintType);
211             if (!nodeFilterConstraintType.isPresent()) {
212                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
213                         INVALID_CONSTRAINTYPE_ENUM, constraintType));
214             }
215             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
216                 .updateSubstitutionFilter(componentId.toLowerCase(), constraints,
217                     true, componentTypeEnum);
218
219             if (!actionResponse.isPresent()) {
220                 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
221                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
222             }
223
224             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
225                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
226
227         } catch (final Exception e) {
228             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
229             LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
230             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
231         }
232     }
233
234     @DELETE
235     @Consumes(MediaType.APPLICATION_JSON)
236     @Produces(MediaType.APPLICATION_JSON)
237     @Path("/{constraintIndex}")
238     @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete",
239         summary = "Delete Component Substitution Filter Constraint", responses = {
240         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
241         @ApiResponse(responseCode = "201", description = "Delete Substitution Filter Constraint"),
242         @ApiResponse(responseCode = "403", description = "Restricted operation"),
243         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
244     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
245     public Response deleteSubstitutionFilterConstraint(
246         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
247         @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
248         @Parameter(description = "valid value: resources / services",
249             schema = @Schema(allowableValues = {
250                 ComponentTypeEnum.SERVICE_PARAM_NAME,
251                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
252         @Parameter(description = "Constraint type. Valid values: properties / capabilities",
253             schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
254                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
255         @PathParam("constraintType") final String constraintType,
256         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
257
258         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
259         LOGGER.debug(MODIFIER_ID_IS, userId);
260         componentSubstitutionFilterBusinessLogic.validateUser(userId);
261
262             final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
263                 NodeFilterConstraintType.parse(constraintType);
264             if (!nodeFilterConstraintType.isPresent()) {
265                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
266                         INVALID_CONSTRAINTYPE_ENUM, constraintType));
267             }
268
269         try {
270             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
271                 .deleteSubstitutionFilter(componentId.toLowerCase(), index, true, ComponentTypeEnum.findByParamName(componentType));
272
273             if (!actionResponse.isPresent()) {
274                 LOGGER.debug(FAILED_TO_DELETE_SUBSTITUTION_FILTER);
275                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
276             }
277
278             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
279                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
280
281         } catch (final Exception e) {
282             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_DELETE);
283             LOGGER.debug(DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
284             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
285
286         }
287     }
288
289 }