bbc09bf435bddb47815dbed7a0a7e2a246842e20
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ConsumerServlet.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.google.gson.Gson;
24 import com.jcabi.aspects.Loggable;
25 import fj.data.Either;
26 import io.swagger.annotations.*;
27 import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
28 import org.openecomp.sdc.be.config.BeEcompErrorManager;
29 import org.openecomp.sdc.be.dao.api.ActionStatus;
30 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
31 import org.openecomp.sdc.be.model.ConsumerDefinition;
32 import org.openecomp.sdc.be.model.User;
33 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
34 import org.openecomp.sdc.common.api.Constants;
35 import org.openecomp.sdc.common.log.wrappers.Logger;
36 import org.openecomp.sdc.exception.ResponseFormat;
37 import org.springframework.web.context.WebApplicationContext;
38
39 import javax.inject.Singleton;
40 import javax.servlet.ServletContext;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.ws.rs.*;
43 import javax.ws.rs.core.Context;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
46
47 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
48 @Path("/v1/consumers")
49 @Api(value = "Consumer Servlet", description = "Consumer Servlet")
50 @Singleton
51 public class ConsumerServlet extends BeGenericServlet {
52
53     private static final String MODIFIER_ID_IS = "modifier id is {}";
54         private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
55         private static final Logger log = Logger.getLogger(ConsumerServlet.class);
56
57     @POST
58     @Consumes(MediaType.APPLICATION_JSON)
59     @Produces(MediaType.APPLICATION_JSON)
60     @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ECOMP consumer credentials", response = Response.class)
61     @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
62     public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
63
64         ServletContext context = request.getSession().getServletContext();
65
66         String url = request.getMethod() + " " + request.getRequestURI();
67         log.debug(START_HANDLE_REQUEST_OF, url);
68
69         User modifier = new User();
70         modifier.setUserId(userId);
71         log.debug(MODIFIER_ID_IS, userId);
72
73         try {
74             ConsumerBusinessLogic businessLogic = getConsumerBL(context);
75
76             Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
77
78             if (convertionResponse.isRight()) {
79                 log.debug("failed to create Consumer");
80                 return buildErrorResponse(convertionResponse.right().value());
81             }
82
83             ConsumerDefinition consumer = convertionResponse.left().value();
84
85             Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);
86
87             if (actionResult.isRight()) {
88                 log.debug("failed to create Consumer");
89                 return buildErrorResponse(actionResult.right().value());
90             }
91
92             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());
93
94         } catch (Exception e) {
95             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");
96             log.debug("create consumer failed with exception", e);
97             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
98             return buildErrorResponse(responseFormat);
99
100         }
101     }
102
103     @GET
104     @Path("/{consumerId}")
105     @Consumes(MediaType.APPLICATION_JSON)
106     @Produces(MediaType.APPLICATION_JSON)
107     @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class)
108     @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
109     public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
110
111         ServletContext context = request.getSession().getServletContext();
112
113         String url = request.getMethod() + " " + request.getRequestURI();
114         log.debug(START_HANDLE_REQUEST_OF, url);
115
116         User modifier = new User();
117         modifier.setUserId(userId);
118         log.debug(MODIFIER_ID_IS, userId);
119
120         Response response = null;
121         try {
122             ConsumerBusinessLogic businessLogic = getConsumerBL(context);
123
124             Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);
125
126             if (actionResponse.isRight()) {
127                 log.debug("failed to get consumer");
128                 response = buildErrorResponse(actionResponse.right().value());
129                 return response;
130             }
131             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
132
133         } catch (Exception e) {
134             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
135             log.debug("get consumer failed with exception", e);
136             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
137
138         }
139     }
140
141     @DELETE
142     @Path("/{consumerId}")
143     @Consumes(MediaType.APPLICATION_JSON)
144     @Produces(MediaType.APPLICATION_JSON)
145     @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class)
146     @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
147     public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
148
149         ServletContext context = request.getSession().getServletContext();
150
151         String url = request.getMethod() + " " + request.getRequestURI();
152         log.debug(START_HANDLE_REQUEST_OF, url);
153
154         User modifier = new User();
155         modifier.setUserId(userId);
156         log.debug(MODIFIER_ID_IS, userId);
157
158         Response response = null;
159         try {
160             ConsumerBusinessLogic businessLogic = getConsumerBL(context);
161
162             Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);
163
164             if (actionResponse.isRight()) {
165                 log.debug("failed to delete consumer");
166                 response = buildErrorResponse(actionResponse.right().value());
167                 return response;
168             }
169             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
170
171         } catch (Exception e) {
172             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
173             log.debug("delete consumer failed with exception", e);
174             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
175
176         }
177     }
178
179     private ConsumerBusinessLogic getConsumerBL(ServletContext context) {
180         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
181         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
182         return webApplicationContext.getBean(ConsumerBusinessLogic.class);
183     }
184
185     public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) {
186         ConsumerDefinition consumer;
187         Gson gson = new Gson();
188         try {
189             log.trace("convert json to object. json=\n {}", data);
190             consumer = gson.fromJson(data, ConsumerDefinition.class);
191             if (consumer == null) {
192                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
193                 log.debug("object is null after converting from json");
194                 ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);
195                 return Either.right(responseFormat);
196             }
197         } catch (Exception e) {
198             // INVALID JSON
199             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
200             log.debug("failed to convert from json {}", data, e);
201             ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);
202             return Either.right(responseFormat);
203         }
204         return Either.left(consumer);
205     }
206
207 }