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