3470d9f92bdc59fd3d5ac9fe26c1f337a2649515
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / CapabilityServlet.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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 package org.openecomp.sdc.be.servlets;
17
18 import com.jcabi.aspects.Loggable;
19 import fj.data.Either;
20 import io.swagger.v3.oas.annotations.Operation;
21 import io.swagger.v3.oas.annotations.Parameter;
22 import io.swagger.v3.oas.annotations.media.ArraySchema;
23 import io.swagger.v3.oas.annotations.media.Content;
24 import io.swagger.v3.oas.annotations.media.Schema;
25 import io.swagger.v3.oas.annotations.responses.ApiResponse;
26 import io.swagger.v3.oas.annotations.servers.Server;
27 import io.swagger.v3.oas.annotations.servers.Servers;
28 import io.swagger.v3.oas.annotations.tags.Tag;
29 import io.swagger.v3.oas.annotations.tags.Tags;
30 import java.util.List;
31 import java.util.Optional;
32 import javax.inject.Inject;
33 import javax.servlet.ServletContext;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.ws.rs.Consumes;
36 import javax.ws.rs.DELETE;
37 import javax.ws.rs.GET;
38 import javax.ws.rs.HeaderParam;
39 import javax.ws.rs.POST;
40 import javax.ws.rs.PUT;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.PathParam;
43 import javax.ws.rs.Produces;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
48 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
50 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
51 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
52 import org.openecomp.sdc.be.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.impl.ComponentsUtils;
56 import org.openecomp.sdc.be.impl.ServletUtils;
57 import org.openecomp.sdc.be.model.CapabilityDefinition;
58 import org.openecomp.sdc.be.model.User;
59 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
60 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
61 import org.openecomp.sdc.be.user.UserBusinessLogic;
62 import org.openecomp.sdc.common.api.Constants;
63 import org.openecomp.sdc.common.log.wrappers.Logger;
64 import org.openecomp.sdc.exception.ResponseFormat;
65 import org.springframework.stereotype.Controller;
66
67 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
68 @Path("/v1/catalog")
69 @Consumes(MediaType.APPLICATION_JSON)
70 @Produces(MediaType.APPLICATION_JSON)
71 @Tags({@Tag(name = "SDC Internal APIs")})
72 @Servers({@Server(url = "/sdc2/rest")})
73 @Controller
74 public class CapabilityServlet extends AbstractValidationsServlet {
75
76     private static final Logger LOGGER = Logger.getLogger(CapabilityServlet.class);
77     private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;
78
79     @Inject
80     public CapabilityServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
81                              ServletUtils servletUtils, ResourceImportManager resourceImportManager,
82                              CapabilitiesBusinessLogic capabilitiesBusinessLogic) {
83         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
84         this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;
85     }
86
87     @POST
88     @Consumes(MediaType.APPLICATION_JSON)
89     @Produces(MediaType.APPLICATION_JSON)
90     @Path("/resources/{resourceId}/capabilities")
91     @Operation(description = "Create Capabilities on resource", method = "POST", summary = "Create Capabilities on resource", responses = {
92         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
93         @ApiResponse(responseCode = "201", description = "Create Capabilities"),
94         @ApiResponse(responseCode = "403", description = "Restricted operation"),
95         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
96         @ApiResponse(responseCode = "409", description = "Capability already exist")})
97     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
98     public Response createCapabilitiesOnResource(@Parameter(description = "Capability to create", required = true) String data,
99                                                  @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
100                                                  @Context final HttpServletRequest request,
101                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
102         return createOrUpdate(data, "resources", resourceId, request, userId, false, "createCapabilities");
103     }
104
105     @PUT
106     @Consumes(MediaType.APPLICATION_JSON)
107     @Produces(MediaType.APPLICATION_JSON)
108     @Path("/resources/{resourceId}/capabilities")
109     @Operation(description = "Update Capabilities on resource", method = "PUT", summary = "Update Capabilities on resource", responses = {
110         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
111         @ApiResponse(responseCode = "201", description = "Update Capabilities"),
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 updateCapabilitiesOnResource(@Parameter(description = "Capabilities to update", required = true) String data,
116                                                  @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,
117                                                  @Context final HttpServletRequest request,
118                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
119         return createOrUpdate(data, "resources", resourceId, request, userId, true, "updateCapabilities");
120     }
121
122     @GET
123     @Consumes(MediaType.APPLICATION_JSON)
124     @Produces(MediaType.APPLICATION_JSON)
125     @Path("/resources/{resourceId}/capabilities/{capabilityId}")
126     @Operation(description = "Get Capability from resource", method = "GET", summary = "GET Capability from resource", responses = {
127         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
128         @ApiResponse(responseCode = "201", description = "GET Capability"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
129         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
130     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
131     public Response getCapabilityOnResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
132                                             @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,
133                                             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
134         return get(capabilityId, resourceId, request, userId);
135     }
136
137     @DELETE
138     @Consumes(MediaType.APPLICATION_JSON)
139     @Produces(MediaType.APPLICATION_JSON)
140     @Path("/resources/{resourceId}/capabilities/{capabilityId}")
141     @Operation(description = "Delete capability from resource", method = "DELETE", summary = "Delete capability from resource", responses = {
142         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
143         @ApiResponse(responseCode = "201", description = "Delete capability"),
144         @ApiResponse(responseCode = "403", description = "Restricted operation"),
145         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
146     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
147     public Response deleteCapabilityOnResource(@Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,
148                                                @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
149                                                @Context final HttpServletRequest request,
150                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
151         return delete(capabilityId, resourceId, request, userId);
152     }
153
154     @POST
155     @Consumes(MediaType.APPLICATION_JSON)
156     @Produces(MediaType.APPLICATION_JSON)
157     @Path("/services/{serviceId}/capabilities")
158     @Operation(description = "Create Capabilities on service", method = "POST", summary = "Create Capabilities on service", responses = {
159         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
160         @ApiResponse(responseCode = "201", description = "Create Capabilities"),
161         @ApiResponse(responseCode = "403", description = "Restricted operation"),
162         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
163         @ApiResponse(responseCode = "409", description = "Capability already exist")})
164     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
165     public Response createCapabilitiesOnService(@Parameter(description = "Capability to create", required = true) String data,
166                                                 @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
167                                                 @Context final HttpServletRequest request,
168                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
169         return createOrUpdate(data, "services", serviceId, request, userId, false, "createCapabilities");
170     }
171
172     @PUT
173     @Consumes(MediaType.APPLICATION_JSON)
174     @Produces(MediaType.APPLICATION_JSON)
175     @Path("/services/{serviceId}/capabilities")
176     @Operation(description = "Update Capabilities on service", method = "PUT", summary = "Update Capabilities on service", responses = {
177         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
178         @ApiResponse(responseCode = "201", description = "Update Capabilities"),
179         @ApiResponse(responseCode = "403", description = "Restricted operation"),
180         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
181     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
182     public Response updateCapabilitiesOnService(@Parameter(description = "Capabilities to update", required = true) String data,
183                                                 @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,
184                                                 @Context final HttpServletRequest request,
185                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
186         return createOrUpdate(data, "services", serviceId, request, userId, true, "updateCapabilities");
187     }
188
189     @GET
190     @Consumes(MediaType.APPLICATION_JSON)
191     @Produces(MediaType.APPLICATION_JSON)
192     @Path("/services/{serviceId}/capabilities/{capabilityId}")
193     @Operation(description = "Get Capability from service", method = "GET", summary = "GET Capability from service", responses = {
194         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
195         @ApiResponse(responseCode = "201", description = "GET Capability"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
196         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
197     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
198     public Response getCapabilityOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
199                                            @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,
200                                            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
201         return get(capabilityId, serviceId, request, userId);
202     }
203
204     @DELETE
205     @Consumes(MediaType.APPLICATION_JSON)
206     @Produces(MediaType.APPLICATION_JSON)
207     @Path("/services/{serviceId}/capabilities/{capabilityId}")
208     @Operation(description = "Delete capability from service", method = "DELETE", summary = "Delete capability from service", responses = {
209         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
210         @ApiResponse(responseCode = "201", description = "Delete capability"),
211         @ApiResponse(responseCode = "403", description = "Restricted operation"),
212         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
213     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
214     public Response deleteCapabilityOnService(@Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,
215                                               @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
216                                               @Context final HttpServletRequest request,
217                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
218         return delete(capabilityId, serviceId, request, userId);
219     }
220
221     private Response createOrUpdate(String data, String componentType, String componentId, HttpServletRequest request, String userId,
222                                     boolean isUpdate, String errorContext) {
223         ServletContext context = request.getSession().getServletContext();
224         String url = request.getMethod() + " " + request.getRequestURI();
225         User modifier = new User();
226         modifier.setUserId(userId);
227         LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);
228         try {
229             String componentIdLower = componentId.toLowerCase();
230             Either<List<CapabilityDefinition>, ResponseFormat> mappedCapabilitiesDataEither = getMappedCapabilitiesData(data, modifier,
231                 ComponentTypeEnum.findByParamName(componentType));
232             if (mappedCapabilitiesDataEither.isRight()) {
233                 LOGGER.error("Failed to create or update capabilities");
234                 return buildErrorResponse(mappedCapabilitiesDataEither.right().value());
235             }
236             List<CapabilityDefinition> mappedCapabilitiesData = mappedCapabilitiesDataEither.left().value();
237             Either<List<CapabilityDefinition>, ResponseFormat> actionResponse;
238             if (isUpdate) {
239                 actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower, mappedCapabilitiesData, modifier, errorContext, true);
240             } else {
241                 actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower, mappedCapabilitiesData, modifier, errorContext, true);
242             }
243             if (actionResponse.isRight()) {
244                 LOGGER.error("Failed to create or update capabilities");
245                 return buildErrorResponse(actionResponse.right().value());
246             }
247             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
248         } catch (Exception e) {
249             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Capabilities create or update");
250             LOGGER.error("Failed to create or update capabilities with an error", e);
251             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
252         }
253     }
254
255     private Response get(String capabilityIdToGet, String componentId, HttpServletRequest request, String userId) {
256         ServletContext context = request.getSession().getServletContext();
257         String url = request.getMethod() + " " + request.getRequestURI();
258         User modifier = new User();
259         modifier.setUserId(userId);
260         LOGGER.debug("Start get request of {} with modifier id {}", url, userId);
261         try {
262             String componentIdLower = componentId.toLowerCase();
263             Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic
264                 .getCapability(componentIdLower, capabilityIdToGet, modifier, true);
265             if (actionResponse.isRight()) {
266                 LOGGER.error("failed to get capability");
267                 return buildErrorResponse(actionResponse.right().value());
268             }
269             Object result = RepresentationUtils.toFilteredRepresentation(actionResponse.left().value());
270             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
271         } catch (Exception e) {
272             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get capability");
273             LOGGER.error("get capabilities failed with exception", e);
274             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
275         }
276     }
277
278     private Response delete(String capabilityId, String componentId, HttpServletRequest request, String userId) {
279         ServletContext context = request.getSession().getServletContext();
280         String url = request.getMethod() + " " + request.getRequestURI();
281         User modifier = new User();
282         modifier.setUserId(userId);
283         LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);
284         try {
285             String componentIdLower = componentId.toLowerCase();
286             Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic
287                 .deleteCapability(componentIdLower, capabilityId, modifier, true);
288             if (actionResponse.isRight()) {
289                 LOGGER.error("failed to delete capability");
290                 return buildErrorResponse(actionResponse.right().value());
291             }
292             Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
293             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
294         } catch (Exception e) {
295             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete capability");
296             LOGGER.error("Delete capability failed with an error", e);
297             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
298         }
299     }
300
301     private Either<List<CapabilityDefinition>, ResponseFormat> getMappedCapabilitiesData(String inputJson, User user,
302                                                                                          ComponentTypeEnum componentTypeEnum) {
303         Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()
304             .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE,
305                 componentTypeEnum);
306         if (mappedData.isRight()) {
307             return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
308         }
309         Optional<List<CapabilityDefinition>> capabilityDefinitionList = mappedData.left().value().getCapabilities().values().stream().findFirst();
310         return capabilityDefinitionList.<Either<List<CapabilityDefinition>, ResponseFormat>>map(Either::left)
311             .orElseGet(() -> Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
312     }
313 }