Remove legacy certificate handling
[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 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.Optional;
29 import java.util.stream.Collectors;
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.collections4.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.exceptions.BusinessLogicException;
49 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
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.CINodeFilterDataDefinition;
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.NodeFilterConverter;
60 import org.openecomp.sdc.be.ui.mapper.FilterConstraintMapper;
61 import org.openecomp.sdc.be.ui.mapper.UIConstraintMapper;
62 import org.openecomp.sdc.be.ui.model.UIConstraint;
63 import org.openecomp.sdc.be.ui.model.UINodeFilter;
64 import org.openecomp.sdc.common.api.Constants;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 @Path("/v1/catalog")
69 @Tag(name = "SDCE-2 APIs")
70 @Consumes(MediaType.APPLICATION_JSON)
71 @Produces(MediaType.APPLICATION_JSON)
72 @Singleton
73 public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
74
75     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.class);
76     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
77     private static final String MODIFIER_ID_IS = "modifier id is {}";
78     private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component";
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     private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter";
83     private static final String NODE_FILTER_UPDATE = "Node Filter Update";
84     private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error";
85     private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter";
86     private static final String NODE_FILTER_DELETE = "Node Filter Delete";
87     private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error";
88     private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}";
89     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
90
91     @Inject
92     public ComponentNodeFilterServlet(final ComponentInstanceBusinessLogic componentInstanceBL,
93                                       final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
94                                       final ResourceImportManager resourceImportManager,
95                                       final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) {
96         super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
97         this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
98     }
99
100     @POST
101     @Consumes(MediaType.APPLICATION_JSON)
102     @Produces(MediaType.APPLICATION_JSON)
103     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/nodeFilter")
104     @Operation(description = "Add Component Filter Constraint", method = "POST", summary = "Add Component Filter Constraint", responses = {
105         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
106         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
107         @ApiResponse(responseCode = "403", description = "Restricted operation"),
108         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
109     public Response addComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
110                                                  @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
111                                                  @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
112                                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
113                                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
114                                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
115                                                  @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
116                                                      NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
117                                                      NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
118                                                  @Context final HttpServletRequest request,
119                                                  @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 = componentNodeFilterBusinessLogic.validateUser(userId);
123         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
124         try {
125             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
126             if (nodeFilterConstraintType.isEmpty()) {
127                 return buildErrorResponse(
128                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
129             }
130             final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
131             if (uiConstraint == null) {
132                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
133                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
134             }
135             final FilterConstraintDto filterConstraintDto = new FilterConstraintMapper().mapFrom(uiConstraint);
136             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
137                 .addNodeFilter(componentId.toLowerCase(), componentInstanceId,
138                     filterConstraintDto, true, componentTypeEnum, nodeFilterConstraintType.get());
139             if (actionResponse.isEmpty()) {
140                 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
141                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
142             }
143             final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
144             if (uiConstraint.isLegacyGetFunction()) {
145                 mapToLegacyResponse(uiNodeFilter);
146             }
147             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
148         } catch (final ComponentException e) {
149             throw e;
150         } catch (final BusinessLogicException e) {
151             return buildErrorResponse(e.getResponseFormat());
152         } catch (final Exception e) {
153             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
154             LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
155             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
156         }
157     }
158
159     @PUT
160     @Consumes(MediaType.APPLICATION_JSON)
161     @Produces(MediaType.APPLICATION_JSON)
162     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
163     @Operation(description = "Update Component Filter Constraint", method = "PUT", summary = "Update Component Filter Constraint", responses = {
164         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
165         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
166         @ApiResponse(responseCode = "403", description = "Restricted operation"),
167         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
168     public Response updateComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
169                                                     @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
170                                                     @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
171                                                     @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
172                                                         ComponentTypeEnum.RESOURCE_PARAM_NAME,
173                                                         ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
174                                                     @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
175                                                         NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
176                                                         NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
177                                                     @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
178                                                     @Context final HttpServletRequest request,
179                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
180         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
181         LOGGER.debug(MODIFIER_ID_IS, userId);
182         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
183         try {
184             final Optional<NodeFilterConstraintType> nodeFilterConstraintTypeOptional = NodeFilterConstraintType.parse(constraintType);
185             if (nodeFilterConstraintTypeOptional.isEmpty()) {
186                 return buildErrorResponse(
187                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
188             }
189             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
190             final UIConstraint uiConstraint = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum).orElse(null);
191             if (uiConstraint == null) {
192                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
193                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
194             }
195             final NodeFilterConstraintType nodeFilterConstraintType = nodeFilterConstraintTypeOptional.get();
196             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
197                 .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, new FilterConstraintMapper().mapFrom(uiConstraint),
198                     componentTypeEnum, nodeFilterConstraintType, index);
199             if (actionResponse.isEmpty()) {
200                 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
201                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
202             }
203             final UINodeFilter uiNodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get());
204             if (uiConstraint.isLegacyGetFunction()) {
205                 mapToLegacyResponse(uiNodeFilter);
206             }
207             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiNodeFilter);
208         } catch (final Exception e) {
209             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
210             LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
211             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
212         }
213     }
214
215     @DELETE
216     @Consumes(MediaType.APPLICATION_JSON)
217     @Produces(MediaType.APPLICATION_JSON)
218     @Path("/{componentType}/{componentId}/componentInstance/{componentInstanceId}/{constraintType}/{constraintIndex}/nodeFilter")
219     @Operation(description = "Delete Component Filter Constraint", method = "Delete", 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     public Response deleteComponentFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
225                                                     @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
226                                                     @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
227                                                     @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
228                                                         ComponentTypeEnum.RESOURCE_PARAM_NAME,
229                                                         ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
230                                                     @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
231                                                         NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
232                                                         NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
233                                                     @Context final HttpServletRequest request,
234                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
235         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
236         LOGGER.debug(MODIFIER_ID_IS, userId);
237         componentNodeFilterBusinessLogic.validateUser(userId);
238         try {
239             final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
240             if (nodeFilterConstraintType.isEmpty()) {
241                 return buildErrorResponse(
242                     getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
243             }
244             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
245                 .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, index, true,
246                     ComponentTypeEnum.findByParamName(componentType), nodeFilterConstraintType.get());
247             if (actionResponse.isEmpty()) {
248                 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
249                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
250             }
251             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
252                 new NodeFilterConverter().convertToUi(actionResponse.get()));
253         } catch (final Exception e) {
254             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
255             LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
256             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
257         }
258     }
259
260     private void mapToLegacyResponse(final UINodeFilter uiNodeFilter) {
261         if (CollectionUtils.isNotEmpty(uiNodeFilter.getProperties())) {
262             uiNodeFilter.setProperties(
263                 uiNodeFilter.getProperties().stream()
264                     .map(UIConstraintMapper::mapToLegacyConstraint)
265                     .collect(Collectors.toList())
266             );
267         }
268         if (CollectionUtils.isNotEmpty(uiNodeFilter.getCapabilities())) {
269             uiNodeFilter.setCapabilities(
270                 uiNodeFilter.getCapabilities().stream()
271                     .map(UIConstraintMapper::mapToLegacyConstraint)
272                     .collect(Collectors.toList())
273             );
274         }
275     }
276
277 }