catalog-be servlets refactoring
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / RequirementServlet.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
17 package org.openecomp.sdc.be.servlets;
18
19 import com.jcabi.aspects.Loggable;
20 import fj.data.Either;
21 import io.swagger.annotations.Api;
22 import io.swagger.annotations.ApiOperation;
23 import io.swagger.annotations.ApiParam;
24 import io.swagger.annotations.ApiResponse;
25 import io.swagger.annotations.ApiResponses;
26 import javax.inject.Inject;
27 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
28 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
29 import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic;
30 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.dao.api.ActionStatus;
33 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
34 import org.openecomp.sdc.be.impl.ComponentsUtils;
35 import org.openecomp.sdc.be.impl.ServletUtils;
36 import org.openecomp.sdc.be.model.RequirementDefinition;
37 import org.openecomp.sdc.be.model.User;
38 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
39 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
40 import org.openecomp.sdc.be.user.UserBusinessLogic;
41 import org.openecomp.sdc.common.api.Constants;
42 import org.openecomp.sdc.common.log.wrappers.Logger;
43 import org.openecomp.sdc.exception.ResponseFormat;
44
45 import javax.inject.Singleton;
46 import javax.servlet.ServletContext;
47 import javax.servlet.http.HttpServletRequest;
48 import javax.ws.rs.Consumes;
49 import javax.ws.rs.DELETE;
50 import javax.ws.rs.GET;
51 import javax.ws.rs.HeaderParam;
52 import javax.ws.rs.POST;
53 import javax.ws.rs.PUT;
54 import javax.ws.rs.Path;
55 import javax.ws.rs.PathParam;
56 import javax.ws.rs.Produces;
57 import javax.ws.rs.core.Context;
58 import javax.ws.rs.core.MediaType;
59 import javax.ws.rs.core.Response;
60 import java.util.List;
61 import java.util.Optional;
62
63 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
64 @Path("/v1/catalog")
65 @Consumes(MediaType.APPLICATION_JSON)
66 @Produces(MediaType.APPLICATION_JSON)
67 @Api(value = "Requirement Servlet", description = "Requirement Servlet")
68 @Singleton
69 public class RequirementServlet extends AbstractValidationsServlet {
70     private static final Logger LOGGER = Logger.getLogger(RequirementServlet.class);
71     private final RequirementBusinessLogic requirementBusinessLogic;
72
73     @Inject
74     public RequirementServlet(UserBusinessLogic userBusinessLogic,
75         ComponentInstanceBusinessLogic componentInstanceBL,
76         ComponentsUtils componentsUtils, ServletUtils servletUtils,
77         ResourceImportManager resourceImportManager,
78         RequirementBusinessLogic requirementBusinessLogic) {
79         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
80         this.requirementBusinessLogic = requirementBusinessLogic;
81     }
82
83     @POST
84     @Consumes(MediaType.APPLICATION_JSON)
85     @Produces(MediaType.APPLICATION_JSON)
86     @Path("/resources/{resourceId}/requirements")
87     @ApiOperation(value = "Create requirements on resource", httpMethod = "POST",
88             notes = "Create requirements on resource", response = Response.class)
89     @ApiResponses(value = {@ApiResponse(code = 201, message = "Create requirements"),
90             @ApiResponse(code = 403, message = "Restricted operation"),
91             @ApiResponse(code = 400, message = "Invalid content / Missing content"),
92             @ApiResponse(code = 409, message = "requirement already exist")})
93     public Response createRequirementsOnResource(
94             @ApiParam(value = "Requirement to create", required = true) String data,
95             @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
96             @Context final HttpServletRequest request,
97             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
98         return createOrUpdate(data, "resources" , resourceId, request,
99                 userId, false, "createRequirements");
100     }
101
102
103     @PUT
104     @Consumes(MediaType.APPLICATION_JSON)
105     @Produces(MediaType.APPLICATION_JSON)
106     @Path("/resources/{resourceId}/requirements")
107     @ApiOperation(value = "Update Requirements on resource", httpMethod = "PUT",
108             notes = "Update Requirements on resource", response = RequirementDefinition.class)
109     @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Requirements"),
110             @ApiResponse(code = 403, message = "Restricted operation"),
111             @ApiResponse(code = 400, message = "Invalid content / Missing content")})
112     public Response updateRequirementsOnResource(
113             @ApiParam(value = "Requirements to update", required = true) String data,
114             @ApiParam(value = "Component Id") @PathParam("resourceId") String resourceId,
115             @Context final HttpServletRequest request,
116             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
117         return createOrUpdate(data, "resources", resourceId, request,
118                 userId, true, "updateRequirements");
119     }
120
121     @GET
122     @Consumes(MediaType.APPLICATION_JSON)
123     @Produces(MediaType.APPLICATION_JSON)
124     @Path("/resources/{resourceId}/requirements/{requirementId}")
125     @ApiOperation(value = "Get Requirement from resource", httpMethod = "GET",
126             notes = "GET Requirement from resource", response = RequirementDefinition.class)
127     @ApiResponses(value = {@ApiResponse(code = 201, message = "GET requirement"),
128             @ApiResponse(code = 403, message = "Restricted operation"),
129             @ApiResponse(code = 400, message = "Invalid content / Missing content")})
130     public Response getRequirementsFromResource(
131             @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
132             @ApiParam(value = "Requirement Id") @PathParam("requirementId") String requirementId,
133             @Context final HttpServletRequest request,
134             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
135
136         return get(requirementId, resourceId, request, userId);
137     }
138
139     @DELETE
140     @Consumes(MediaType.APPLICATION_JSON)
141     @Produces(MediaType.APPLICATION_JSON)
142     @Path("/resources/{resourceId}/requirements/{requirementId}")
143     @ApiOperation(value = "Delete requirements from resource", httpMethod = "DELETE",
144             notes = "Delete requirements from resource", response = RequirementDefinition.class)
145     @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete requirement"),
146             @ApiResponse(code = 403, message = "Restricted operation"),
147             @ApiResponse(code = 400, message = "Invalid content / Missing content")})
148     public Response deleteRequirementsFromResource(
149             @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
150             @ApiParam(value = "requirement Id") @PathParam("requirementId") String requirementId,
151             @Context final HttpServletRequest request,
152             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
153         return delete(requirementId, resourceId, request, userId);
154     }
155
156     @POST
157     @Consumes(MediaType.APPLICATION_JSON)
158     @Produces(MediaType.APPLICATION_JSON)
159     @Path("/services/{serviceId}/requirements")
160     @ApiOperation(value = "Create requirements on service", httpMethod = "POST",
161             notes = "Create requirements on service", response = Response.class)
162     @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Requirements"),
163             @ApiResponse(code = 403, message = "Restricted operation"),
164             @ApiResponse(code = 400, message = "Invalid content / Missing content"),
165             @ApiResponse(code = 409, message = "Requirement already exist")})
166     public Response createRequirementsOnService(
167             @ApiParam(value = "Requirements to create", required = true) String data,
168             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
169             @Context final HttpServletRequest request,
170             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
171         return createOrUpdate(data, "services" , serviceId, request, userId,
172                 false , "createRequirements");
173     }
174
175
176     @PUT
177     @Consumes(MediaType.APPLICATION_JSON)
178     @Produces(MediaType.APPLICATION_JSON)
179     @Path("/services/{serviceId}/requirements")
180     @ApiOperation(value = "Update requirements on service", httpMethod = "PUT",
181             notes = "Update requirements on service", response = RequirementDefinition.class)
182     @ApiResponses(value = {@ApiResponse(code = 201, message = "Update requirements"),
183             @ApiResponse(code = 403, message = "Restricted operation"),
184             @ApiResponse(code = 400, message = "Invalid content / Missing content")})
185     public Response updateRequirementsOnService(
186             @ApiParam(value = "Requirements to update", required = true) String data,
187             @ApiParam(value = "Component Id") @PathParam("serviceId") String serviceId,
188             @Context final HttpServletRequest request,
189             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
190         return createOrUpdate(data, "services", serviceId, request, userId,
191                 true, "updateRequirements");
192     }
193
194     @GET
195     @Consumes(MediaType.APPLICATION_JSON)
196     @Produces(MediaType.APPLICATION_JSON)
197     @Path("/services/{serviceId}/requirements/{requirementId}")
198     @ApiOperation(value = "Get requirement from service", httpMethod = "GET",
199             notes = "GET requirement from service", response = RequirementDefinition.class)
200     @ApiResponses(value = {@ApiResponse(code = 201, message = "GET Requirements"),
201             @ApiResponse(code = 403, message = "Restricted operation"),
202             @ApiResponse(code = 400, message = "Invalid content / Missing content")})
203     public Response getRequirementsOnService(
204             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
205             @ApiParam(value = "Requirement Id") @PathParam("requirementId") String requirementId,
206             @Context final HttpServletRequest request,
207             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
208
209         return get(requirementId, serviceId, request, userId);
210     }
211
212
213     @DELETE
214     @Consumes(MediaType.APPLICATION_JSON)
215     @Produces(MediaType.APPLICATION_JSON)
216     @Path("/services/{serviceId}/requirements/{requirementId}")
217     @ApiOperation(value = "Delete requirement from service", httpMethod = "DELETE",
218             notes = "Delete requirement from service", response = RequirementDefinition.class)
219     @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Requirements"),
220             @ApiResponse(code = 403, message = "Restricted operation"),
221             @ApiResponse(code = 400, message = "Invalid content / Missing content")})
222     public Response deleteRequirementsOnService(
223             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
224             @ApiParam(value = "Requirement Id") @PathParam("requirementId") String requirementId,
225             @Context final HttpServletRequest request,
226             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
227         return delete(requirementId, serviceId, request, userId);
228     }
229
230
231     private Response createOrUpdate (String data, String componentType, String componentId,
232                                      HttpServletRequest request, String userId,
233                                      boolean isUpdate, String errorContext) {
234         String url = request.getMethod() + " " + request.getRequestURI();
235
236         User modifier = new User();
237         modifier.setUserId(userId);
238         LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);
239
240         try {
241             String componentIdLower = componentId.toLowerCase();
242
243             Either<List<RequirementDefinition>, ResponseFormat> mappedRequirementDataEither =
244                     getMappedRequirementData(data, modifier, ComponentTypeEnum.findByParamName(componentType));
245             if(mappedRequirementDataEither.isRight()) {
246                 LOGGER.error("Failed to create or update requirements");
247                 return buildErrorResponse(mappedRequirementDataEither.right().value());
248             }
249             List<RequirementDefinition> mappedRequirementData = mappedRequirementDataEither.left().value();
250             Either<List<RequirementDefinition>, ResponseFormat> actionResponse;
251             if(isUpdate) {
252                 actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier,
253                         errorContext, true);
254             } else {
255                 actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier,
256                         errorContext, true);
257             }
258
259             if (actionResponse.isRight()) {
260                 LOGGER.error("Failed to create or update requirements");
261                 return buildErrorResponse(actionResponse.right().value());
262             }
263
264             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
265                     actionResponse.left().value());
266         } catch (Exception e) {
267             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("requirements create or update");
268             LOGGER.error("Failed to create or update requirements with an error", e);
269             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
270         }
271     }
272
273     private Response get (String requirementIdToGet,  String componentId,
274                           HttpServletRequest request, String userId){
275         String url = request.getMethod() + " " + request.getRequestURI();
276
277         User modifier = new User();
278         modifier.setUserId(userId);
279         LOGGER.debug("Start get request of {} with modifier id {}", url, userId);
280
281         try {
282             String componentIdLower = componentId.toLowerCase();
283             Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic
284                     .getRequirement(componentIdLower, requirementIdToGet, modifier, true);
285             if (actionResponse.isRight()) {
286                 LOGGER.error("failed to get requirements");
287                 return buildErrorResponse(actionResponse.right().value());
288             }
289             Object result = RepresentationUtils.toFilteredRepresentation(actionResponse.left().value());
290             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
291         } catch (Exception e) {
292             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get requirements");
293             LOGGER.error("get requirements failed with exception", e);
294             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
295         }
296     }
297
298     private Response delete (String requirementId, String componentId, HttpServletRequest
299                                         request, String userId){
300         String url = request.getMethod() + " " + request.getRequestURI();
301
302         User modifier = new User();
303         modifier.setUserId(userId);
304         LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);
305
306         try {
307             String componentIdLower = componentId.toLowerCase();
308
309             Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic
310                     .deleteRequirement(componentIdLower, requirementId, modifier, true);
311             if (actionResponse.isRight()) {
312                 LOGGER.error("failed to delete requirements");
313                 return buildErrorResponse(actionResponse.right().value());
314             }
315             Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
316             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
317         } catch (Exception e) {
318             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete requirements");
319             LOGGER.error("Delete requirements failed with an error", e);
320             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
321         }
322     }
323
324     private Either<List<RequirementDefinition>, ResponseFormat> getMappedRequirementData(String inputJson, User user,
325                                                                  ComponentTypeEnum componentTypeEnum){
326         Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()
327                 .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,
328                         AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
329         Optional<List<RequirementDefinition>> requirementDefinitionList = mappedData.left().value()
330                 .getRequirements().values().stream().findFirst();
331         return requirementDefinitionList.<Either<List<RequirementDefinition>, ResponseFormat>>
332                 map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()
333                 .getResponseFormat(ActionStatus.GENERAL_ERROR)));
334     }
335 }