catalog-be servlets refactoring
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ProductServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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
21 package org.openecomp.sdc.be.servlets;
22
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.annotations.*;
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.ProductBusinessLogic;
30 import org.openecomp.sdc.be.config.BeEcompErrorManager;
31 import org.openecomp.sdc.be.dao.api.ActionStatus;
32 import org.openecomp.sdc.be.impl.ComponentsUtils;
33 import org.openecomp.sdc.be.model.Product;
34 import org.openecomp.sdc.be.model.User;
35 import org.openecomp.sdc.be.user.UserBusinessLogic;
36 import org.openecomp.sdc.common.api.Constants;
37 import org.openecomp.sdc.common.log.wrappers.Logger;
38 import org.openecomp.sdc.exception.ResponseFormat;
39
40 import javax.inject.Singleton;
41 import javax.servlet.ServletContext;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.ws.rs.*;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import java.util.Map;
48
49 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
50 @Path("/v1/catalog")
51 @Api(value = "Product Catalog", description = "Product Servlet")
52 @Singleton
53 public class ProductServlet extends BeGenericServlet {
54     private static final Logger log = Logger.getLogger(ProductServlet.class);
55     private final ProductBusinessLogic productBusinessLogic;
56
57     @Inject
58     public ProductServlet(UserBusinessLogic userBusinessLogic,
59         ProductBusinessLogic productBusinessLogic,
60         ComponentsUtils componentsUtils) {
61         super(userBusinessLogic, componentsUtils);
62         this.productBusinessLogic = productBusinessLogic;
63     }
64
65     @POST
66     @Path("/products")
67     @Consumes(MediaType.APPLICATION_JSON)
68     @Produces(MediaType.APPLICATION_JSON)
69     @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class)
70     @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"),
71     @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") })
72     public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request,
73             @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) {
74
75         String url = request.getMethod() + " " + request.getRequestURI();
76         log.debug("Start handle request of {}", url);
77
78         User modifier = new User();
79         modifier.setUserId(userId);
80         log.debug("modifier id is {}", userId);
81
82         Response response = null;
83         try {
84             Product product = RepresentationUtils.fromRepresentation(data, Product.class);
85             Either<Product, ResponseFormat> actionResponse = productBusinessLogic.createProduct(product, modifier);
86
87             if (actionResponse.isRight()) {
88                 log.debug("Failed to create product");
89                 response = buildErrorResponse(actionResponse.right().value());
90                 return response;
91             }
92
93             Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
94             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
95             return response;
96
97         } catch (Exception e) {
98             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product");
99             log.debug("create product failed with error ", e);
100             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
101             return response;
102         }
103     }
104
105     @GET
106     @Path("/products/{productId}")
107     @Consumes(MediaType.APPLICATION_JSON)
108     @Produces(MediaType.APPLICATION_JSON)
109     @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class)
110     @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"),
111             @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), })
112     public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
113
114         String url = request.getMethod() + " " + request.getRequestURI();
115         log.debug("Start handle request of {}", url);
116
117         User modifier = new User();
118         modifier.setUserId(userId);
119         log.debug("modifier id is {}", userId);
120
121         Response response = null;
122
123         try {
124             log.trace("get product with id {}", productId);
125             Either<Product, ResponseFormat> actionResponse = productBusinessLogic.getProduct(productId, modifier);
126
127             if (actionResponse.isRight()) {
128                 log.debug("Failed to get product");
129                 response = buildErrorResponse(actionResponse.right().value());
130                 return response;
131             }
132
133             Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
134             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
135
136         } catch (Exception e) {
137             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product");
138             log.debug("get product failed with error ", e);
139             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
140             return response;
141         }
142     }
143
144     @GET
145     @Path("/products/productName/{productName}/productVersion/{productVersion}")
146     @Consumes(MediaType.APPLICATION_JSON)
147     @Produces(MediaType.APPLICATION_JSON)
148     @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class)
149     @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") })
150     public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request,
151             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
152
153         // get modifier id
154         User modifier = new User();
155         modifier.setUserId(userId);
156         log.debug("modifier id is {}", userId);
157
158         Response response = null;
159         try {
160             Either<Product, ResponseFormat> actionResponse = productBusinessLogic.getProductByNameAndVersion(productName, productVersion, userId);
161
162             if (actionResponse.isRight()) {
163                 response = buildErrorResponse(actionResponse.right().value());
164                 return response;
165             }
166
167             Product product = actionResponse.left().value();
168             Object result = RepresentationUtils.toRepresentation(product);
169
170             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
171
172         } catch (Exception e) {
173             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version");
174             log.debug("get product failed with exception", e);
175             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
176
177         }
178     }
179
180     @DELETE
181     @Path("/products/{productId}")
182     public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) {
183
184         String url = request.getMethod() + " " + request.getRequestURI();
185         log.debug("Start handle request of {}", url);
186
187         // get modifier id
188         String userId = request.getHeader(Constants.USER_ID_HEADER);
189         User modifier = new User();
190         modifier.setUserId(userId);
191         log.debug("modifier id is {}", userId);
192
193         Response response = null;
194
195         try {
196             log.trace("delete product with id {}", productId);
197             Either<Product, ResponseFormat> actionResponse = productBusinessLogic.deleteProduct(productId, modifier);
198
199             if (actionResponse.isRight()) {
200                 log.debug("Failed to delete product");
201                 response = buildErrorResponse(actionResponse.right().value());
202                 return response;
203             }
204
205             Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
206             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
207             return response;
208
209         } catch (Exception e) {
210             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
211             log.debug("delete resource failed with error ", e);
212             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
213             return response;
214
215         }
216     }
217
218     @PUT
219     @Path("/products/{productId}/metadata")
220     @Consumes(MediaType.APPLICATION_JSON)
221     @Produces(MediaType.APPLICATION_JSON)
222     @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class)
223     @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
224     public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request,
225             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
226
227         String url = request.getMethod() + " " + request.getRequestURI();
228         log.debug("Start handle request of {}", url);
229
230         User modifier = new User();
231         modifier.setUserId(userId);
232         log.debug("modifier id is {}", userId);
233         Response response = null;
234
235         try {
236             String productIdLower = productId.toLowerCase();
237             Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class);
238             Either<Product, ResponseFormat> actionResponse = productBusinessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier);
239
240             if (actionResponse.isRight()) {
241                 log.debug("failed to update product");
242                 response = buildErrorResponse(actionResponse.right().value());
243                 return response;
244             }
245
246             Product product = actionResponse.left().value();
247             Object result = RepresentationUtils.toRepresentation(product);
248             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
249
250         } catch (Exception e) {
251             log.debug("update product metadata failed with exception", e);
252             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
253             return response;
254         }
255     }
256
257     @GET
258     @Path("/products/validate-name/{productName}")
259     @Consumes(MediaType.APPLICATION_JSON)
260     @Produces(MediaType.APPLICATION_JSON)
261     @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class)
262     @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
263     public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
264         String url = request.getMethod() + " " + request.getRequestURI();
265         log.debug("Start handle request of {}", url);
266
267         User modifier = new User();
268         modifier.setUserId(userId);
269         log.debug("modifier id is {}", userId);
270         Response response = null;
271         try {
272             Either<Map<String, Boolean>, ResponseFormat> actionResponse = productBusinessLogic.validateProductNameExists(productName, userId);
273
274             if (actionResponse.isRight()) {
275                 log.debug("failed to get validate service name");
276                 response = buildErrorResponse(actionResponse.right().value());
277                 return response;
278             }
279             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
280         } catch (Exception e) {
281             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name");
282             log.debug("validate product name failed with exception", e);
283             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
284         }
285     }
286
287 }