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