Fix node filter capability issue
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / OutputsServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2021, Nordix Foundation. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.servlets;
21
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.tags.Tag;
32 import io.swagger.v3.oas.annotations.tags.Tags;
33 import java.util.List;
34 import javax.inject.Inject;
35 import javax.servlet.ServletContext;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.Consumes;
38 import javax.ws.rs.DELETE;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.HeaderParam;
41 import javax.ws.rs.POST;
42 import javax.ws.rs.Path;
43 import javax.ws.rs.PathParam;
44 import javax.ws.rs.Produces;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.MediaType;
47 import javax.ws.rs.core.Response;
48 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.OutputsBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
52 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.dao.api.ActionStatus;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
57 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
58 import org.openecomp.sdc.be.impl.ComponentsUtils;
59 import org.openecomp.sdc.be.impl.ServletUtils;
60 import org.openecomp.sdc.be.model.ComponentInstOutputsMap;
61 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
62 import org.openecomp.sdc.be.model.OutputDefinition;
63 import org.openecomp.sdc.be.model.Resource;
64 import org.openecomp.sdc.be.model.User;
65 import org.openecomp.sdc.be.user.UserBusinessLogic;
66 import org.openecomp.sdc.common.api.Constants;
67 import org.openecomp.sdc.common.log.wrappers.Logger;
68 import org.openecomp.sdc.exception.ResponseFormat;
69 import org.springframework.stereotype.Controller;
70
71 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
72 @Tags({@Tag(name = "SDCE-2 APIs")})
73 @Server(url = "/sdc2/rest")
74 @Path("/v1/catalog")
75 @Controller
76 @Consumes(MediaType.APPLICATION_JSON)
77 @Produces(MediaType.APPLICATION_JSON)
78 public class OutputsServlet extends AbstractValidationsServlet {
79
80     private static final Logger log = Logger.getLogger(OutputsServlet.class);
81     private static final String START_HANDLE_REQUEST_OF = "(get) Start handle request of {}";
82     private final OutputsBusinessLogic outputsBusinessLogic;
83
84     @Inject
85     public OutputsServlet(final UserBusinessLogic userBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic,
86                           final ComponentInstanceBusinessLogic componentInstanceBL, final ComponentsUtils componentsUtils,
87                           final ServletUtils servletUtils, final ResourceImportManager resourceImportManager) {
88         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
89         this.outputsBusinessLogic = outputsBusinessLogic;
90     }
91
92     @GET
93     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/outputs")
94     @Operation(description = "Get Outputs only", method = "GET", summary = "Returns Outputs list", responses = {
95         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
96         @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
97         @ApiResponse(responseCode = "404", description = "Component not found")})
98     public Response getComponentInstanceOutputs(@PathParam("componentType") final String componentType,
99                                                 @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
100                                                 @PathParam("originComponentUid") final String originComponentUid,
101                                                 @Context final HttpServletRequest request,
102                                                 @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
103         final String url = request.getMethod() + " " + request.getRequestURI();
104         log.debug(START_HANDLE_REQUEST_OF, url);
105         try {
106             final Either<List<ComponentInstanceOutput>, ResponseFormat> outputsResponse = outputsBusinessLogic
107                 .getComponentInstanceOutputs(userId, componentId, instanceId);
108             if (outputsResponse.isRight()) {
109                 log.debug("failed to get component instance outputs {}", componentType);
110                 return buildErrorResponse(outputsResponse.right().value());
111             }
112             final Object outputs = RepresentationUtils.toRepresentation(outputsResponse.left().value());
113             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), outputs);
114         } catch (final Exception e) {
115             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Outputs " + componentType);
116             log.debug("getOutputs failed with exception", e);
117             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
118         }
119     }
120
121     @POST
122     @Path("/{componentType}/{componentId}/create/outputs")
123     @Operation(description = "Create outputs on service", method = "POST", summary = "Return outputs list", responses = {
124         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
125         @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
126         @ApiResponse(responseCode = "404", description = "Component not found")})
127     public Response createMultipleOutputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
128                                           @Context final HttpServletRequest request,
129                                           @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
130                                           @Parameter(description = "ComponentIns Outputs Object to be created", required = true) final String componentInstOutputsMapObj) {
131         final String url = request.getMethod() + " " + request.getRequestURI();
132         log.debug(START_HANDLE_REQUEST_OF, url);
133         try {
134             return declareAttributes(userId, componentId, componentType, componentInstOutputsMapObj, DeclarationTypeEnum.OUTPUT, request);
135         } catch (final Exception e) {
136             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create outputs for service with id: " + componentId);
137             log.debug("Attributes declaration failed with exception", e);
138             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
139         }
140     }
141
142     private Response declareAttributes(final String userId, final String componentId, final String componentType,
143                                        final String componentInstOutputsMapObj, final DeclarationTypeEnum typeEnum,
144                                        final HttpServletRequest request) {
145         final ServletContext context = request.getSession().getServletContext();
146         final String url = request.getMethod() + " " + request.getRequestURI();
147         log.debug(START_HANDLE_REQUEST_OF, url);
148         try {
149             final BaseBusinessLogic businessLogic = getBlForDeclaration(typeEnum, context);
150             // get modifier id
151             final User modifier = new User(userId);
152             log.debug("modifier id is {}", userId);
153             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
154             final Either<ComponentInstOutputsMap, ResponseFormat> componentInstOutputsMapRes = parseToComponentInstanceMap(componentInstOutputsMapObj,
155                 modifier, componentTypeEnum, ComponentInstOutputsMap.class);
156             if (componentInstOutputsMapRes.isRight()) {
157                 log.debug("failed to parse componentInstOutMap");
158                 return buildErrorResponse(componentInstOutputsMapRes.right().value());
159             }
160             final Either<List<ToscaDataDefinition>, ResponseFormat> attributesAfterDeclaration = businessLogic
161                 .declareAttributes(userId, componentId, componentTypeEnum, componentInstOutputsMapRes.left().value());
162             if (attributesAfterDeclaration.isRight()) {
163                 log.debug("failed to create outputs  for service: {}", componentId);
164                 return buildErrorResponse(attributesAfterDeclaration.right().value());
165             }
166             final Object attributes = RepresentationUtils.toRepresentation(attributesAfterDeclaration.left().value());
167             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), attributes);
168         } catch (final Exception e) {
169             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create outputs for service with id: " + componentId);
170             log.debug("Attributes declaration failed with exception", e);
171             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
172         }
173     }
174
175     @DELETE
176     @Path("/{componentType}/{componentId}/delete/{outputId}/output")
177     @Operation(description = "Delete output from service", method = "DELETE", summary = "Delete service output", responses = {
178         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
179         @ApiResponse(responseCode = "200", description = "Output deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
180         @ApiResponse(responseCode = "404", description = "Output not found")})
181     public Response deleteOutput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
182                                  @PathParam("outputId") final String outputId, @Context final HttpServletRequest request,
183                                  @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
184                                  @Parameter(description = "Service Output to be deleted", required = true) final String componentInstOutputsMapObj) {
185         String url = request.getMethod() + " " + request.getRequestURI();
186         log.debug(START_HANDLE_REQUEST_OF, url);
187         try {
188             final OutputDefinition deleteOutput = outputsBusinessLogic.deleteOutput(componentId, userId, outputId);
189             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteOutput);
190         } catch (final ComponentException e) {
191             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete output for service + " + componentId + " + with id: " + outputId);
192             log.debug("Delete output failed with exception", e);
193             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
194         }
195     }
196 }