aa9b9310576cd6c5472751ea1bd8ccf9fffa55b7
[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
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.ComponentNodeFilterBusinessLogic;
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.components.impl.utils.NodeFilterConstraintAction;
51 import org.openecomp.sdc.be.config.BeEcompErrorManager;
52 import org.openecomp.sdc.be.dao.api.ActionStatus;
53 import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor;
54 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
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.NodeFilterConverter;
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}/resourceInstances/{componentInstanceId}/nodeFilter")
68 @Consumes(MediaType.APPLICATION_JSON)
69 @Produces(MediaType.APPLICATION_JSON)
70 @Singleton
71 public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
72
73     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.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
77     private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component";
78
79     private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter";
80     private static final String NODE_FILTER_CREATION = "Node Filter Creation";
81     private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error";
82
83     private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter";
84     private static final String NODE_FILTER_UPDATE = "Node Filter Update";
85     private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error";
86
87     private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter";
88     private static final String NODE_FILTER_DELETE = "Node Filter Delete";
89     private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error";
90
91     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
92
93     @Inject
94     public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic,
95                                       final ComponentInstanceBusinessLogic componentInstanceBL,
96                                       final ComponentsUtils componentsUtils,
97                                       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("/")
108     @Operation(description = "Add Component Filter Constraint", method = "POST",
109         summary = "Add Component Filter Constraint", responses = {
110         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
111         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
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 addComponentFilterConstraint(
116         @Parameter(description = "UIConstraint data", required = true) String constraintData,
117         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
118         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
119         @Parameter(description = "valid values: resources / services",
120             schema = @Schema(allowableValues = {
121                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
122                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
123         @Context final HttpServletRequest request,
124         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
125
126         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
127         LOGGER.debug(MODIFIER_ID_IS, userId);
128         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
129
130         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
131         try {
132             final Optional<UIConstraint> convertResponse = componentsUtils
133                 .parseToConstraint(constraintData, userModifier, componentTypeEnum);
134             if (!convertResponse.isPresent()) {
135                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
136                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
137             }
138             final UIConstraint uiConstraint = convertResponse.get();
139             final String constraint = new ConstraintConvertor().convert(uiConstraint);
140
141             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
142                 .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD,
143                     uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum);
144
145             if (!actionResponse.isPresent()) {
146                 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
147                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
148             }
149             final UINodeFilter nodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
150
151             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeFilter);
152
153         } catch (final Exception e) {
154             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
155             LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
156             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
157         }
158     }
159
160     @PUT
161     @Consumes(MediaType.APPLICATION_JSON)
162     @Produces(MediaType.APPLICATION_JSON)
163     @Path("/")
164     @Operation(description = "Update Component Filter Constraint", method = "PUT",
165         summary = "Update Component Filter Constraint", responses = {
166         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
167         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
168         @ApiResponse(responseCode = "403", description = "Restricted operation"),
169         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
170     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
171     public Response updateComponentFilterConstraint(
172         @Parameter(description = "UIConstraint data", required = true) String constraintData,
173         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
174         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
175         @Parameter(description = "valid values: resources / services",
176             schema = @Schema(allowableValues = {
177                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
178                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
179         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
180
181         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
182         LOGGER.debug(MODIFIER_ID_IS, userId);
183         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
184
185         try {
186             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
187             final List<UIConstraint>  uiConstraints = componentsUtils
188                 .validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
189             if (CollectionUtils.isEmpty(uiConstraints)) {
190                 LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, NODE_FILTER_UPDATE);
191                 return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
192                     "Failed to parse constraint data", constraintData));
193             }
194             final List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints);
195             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
196                 .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, constraints,
197                     true, componentTypeEnum);
198
199             if (!actionResponse.isPresent()) {
200                 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
201                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
202             }
203
204             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
205                 new NodeFilterConverter().convertToUi(actionResponse.get()));
206
207         } catch (final Exception e) {
208             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
209             LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
210             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
211         }
212     }
213
214     @DELETE
215     @Consumes(MediaType.APPLICATION_JSON)
216     @Produces(MediaType.APPLICATION_JSON)
217     @Path("/{constraintIndex}")
218     @Operation(description = "Delete Component Filter Constraint", method = "Delete",
219         summary = "Delete Component Filter Constraint", responses = {
220         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
221         @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"),
222         @ApiResponse(responseCode = "403", description = "Restricted operation"),
223         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
224     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
225     public Response deleteComponentFilterConstraint(
226         @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
227         @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
228         @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
229         @Parameter(description = "valid values: resources / services",
230             schema = @Schema(allowableValues = {
231                 ComponentTypeEnum.RESOURCE_PARAM_NAME,
232                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
233         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
234
235         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
236         LOGGER.debug(MODIFIER_ID_IS, userId);
237         componentNodeFilterBusinessLogic.validateUser(userId);
238
239         try {
240             final Optional<CINodeFilterDataDefinition>actionResponse = componentNodeFilterBusinessLogic
241                 .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE,
242                     null, index, true, ComponentTypeEnum.findByParamName(componentType));
243
244             if (!actionResponse.isPresent()) {
245                 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
246                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
247             }
248
249             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
250                 new NodeFilterConverter().convertToUi(actionResponse.get()));
251
252         } catch (final Exception e) {
253             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
254             LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
255             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
256
257         }
258     }
259
260 }