f3d18602bd3c2ed3028b06c46c704d4426b2f6f5
[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.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.ArraySchema;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.servers.Server;
33 import io.swagger.v3.oas.annotations.servers.Servers;
34 import io.swagger.v3.oas.annotations.tags.Tag;
35 import io.swagger.v3.oas.annotations.tags.Tags;
36 import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
37 import org.openecomp.sdc.be.config.BeEcompErrorManager;
38 import org.openecomp.sdc.be.dao.api.ActionStatus;
39 import org.openecomp.sdc.be.impl.ComponentsUtils;
40 import org.openecomp.sdc.be.model.ConsumerDefinition;
41 import org.openecomp.sdc.be.model.User;
42 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
43 import org.openecomp.sdc.be.user.UserBusinessLogic;
44 import org.openecomp.sdc.common.api.Constants;
45 import org.openecomp.sdc.common.log.wrappers.Logger;
46 import org.openecomp.sdc.exception.ResponseFormat;
47
48 import javax.inject.Inject;
49 import javax.inject.Singleton;
50 import javax.servlet.ServletContext;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.ws.rs.Consumes;
53 import javax.ws.rs.DELETE;
54 import javax.ws.rs.GET;
55 import javax.ws.rs.HeaderParam;
56 import javax.ws.rs.POST;
57 import javax.ws.rs.Path;
58 import javax.ws.rs.PathParam;
59 import javax.ws.rs.Produces;
60 import javax.ws.rs.core.Context;
61 import javax.ws.rs.core.MediaType;
62 import javax.ws.rs.core.Response;
63
64 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
65 @Path("/v1/consumers")
66 @Tags({@Tag(name = "SDC Internal APIs")})
67 @Servers({@Server(url = "/sdc2/rest")})
68 @Singleton
69 public class ConsumerServlet extends BeGenericServlet {
70
71     private static final String MODIFIER_ID_IS = "modifier id is {}";
72         private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
73         private static final Logger log = Logger.getLogger(ConsumerServlet.class);
74     private final ConsumerBusinessLogic businessLogic;
75
76           @Inject
77     public ConsumerServlet(UserBusinessLogic userBusinessLogic,
78         ComponentsUtils componentsUtils,
79         ConsumerBusinessLogic businessLogic) {
80         super(userBusinessLogic, componentsUtils);
81         this.businessLogic = businessLogic;
82     }
83
84     @POST
85     @Consumes(MediaType.APPLICATION_JSON)
86     @Produces(MediaType.APPLICATION_JSON)
87     @Operation(description = "Consumer credentials", method = "POST",
88             summary = "Returns created ECOMP consumer credentials", responses = {
89             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
90             @ApiResponse(responseCode = "201", description = "Consumer credentials created"),
91             @ApiResponse(responseCode = "403", description = "Restricted operation"),
92             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
93     public Response createConsumer(@Parameter(description = "Consumer Object to be created", required = true) String data,
94             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
95
96         ServletContext context = request.getSession().getServletContext();
97
98         String url = request.getMethod() + " " + request.getRequestURI();
99         log.debug(START_HANDLE_REQUEST_OF, url);
100
101         User modifier = new User();
102         modifier.setUserId(userId);
103         log.debug(MODIFIER_ID_IS, userId);
104
105         try {
106             Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
107
108             if (convertionResponse.isRight()) {
109                 log.debug("failed to create Consumer");
110                 return buildErrorResponse(convertionResponse.right().value());
111             }
112
113             ConsumerDefinition consumer = convertionResponse.left().value();
114
115             Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);
116
117             if (actionResult.isRight()) {
118                 log.debug("failed to create Consumer");
119                 return buildErrorResponse(actionResult.right().value());
120             }
121
122             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());
123
124         } catch (Exception e) {
125             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");
126             log.debug("create consumer failed with exception", e);
127             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
128             return buildErrorResponse(responseFormat);
129
130         }
131     }
132
133     @GET
134     @Path("/{consumerId}")
135     @Consumes(MediaType.APPLICATION_JSON)
136     @Produces(MediaType.APPLICATION_JSON)
137     @Operation(description = "Retrieve Consumer", method = "GET", summary = "Returns consumer according to ConsumerID",
138             responses = {@ApiResponse(content = @Content(
139                     array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))),
140                     @ApiResponse(responseCode = "200", description = "Consumer found"),
141                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
142                     @ApiResponse(responseCode = "404", description = "Consumer not found")})
143     public Response getConsumer(@PathParam("consumerId") final String consumerId,
144             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
145
146         ServletContext context = request.getSession().getServletContext();
147
148         String url = request.getMethod() + " " + request.getRequestURI();
149         log.debug(START_HANDLE_REQUEST_OF, url);
150
151         User modifier = new User();
152         modifier.setUserId(userId);
153         log.debug(MODIFIER_ID_IS, userId);
154
155         try {
156             Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);
157
158             if (actionResponse.isRight()) {
159                 log.debug("failed to get consumer");
160                 return buildErrorResponse(actionResponse.right().value());
161             }
162             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
163
164         } catch (Exception e) {
165             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
166             log.debug("get consumer failed with exception", e);
167             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
168         }
169     }
170
171     @DELETE
172     @Path("/{consumerId}")
173     @Consumes(MediaType.APPLICATION_JSON)
174     @Produces(MediaType.APPLICATION_JSON)
175     @Operation(description = "Deletes Consumer", method = "DELETE",
176             summary = "Returns deleted consumer according to ConsumerID", responses = {@ApiResponse(
177             content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))),
178             @ApiResponse(responseCode = "204", description = "Consumer deleted"),
179             @ApiResponse(responseCode = "403", description = "Restricted operation"),
180             @ApiResponse(responseCode = "404", description = "Consumer not found")})
181     public Response deleteConsumer(@PathParam("consumerId") final String consumerId,
182             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
183
184         String url = request.getMethod() + " " + request.getRequestURI();
185         log.debug(START_HANDLE_REQUEST_OF, url);
186
187         User modifier = new User();
188         modifier.setUserId(userId);
189         log.debug(MODIFIER_ID_IS, userId);
190
191         try {
192             Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);
193
194             if (actionResponse.isRight()) {
195                 log.debug("failed to delete consumer");
196                 return buildErrorResponse(actionResponse.right().value());
197             }
198             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
199
200         } catch (Exception e) {
201             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
202             log.debug("delete consumer failed with exception", e);
203             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
204         }
205     }
206
207     public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) {
208         ConsumerDefinition consumer;
209         Gson gson = new Gson();
210         try {
211             log.trace("convert json to object. json=\n {}", data);
212             consumer = gson.fromJson(data, ConsumerDefinition.class);
213             if (consumer == null) {
214                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
215                 log.debug("object is null after converting from json");
216                 ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);
217                 return Either.right(responseFormat);
218             }
219         } catch (Exception e) {
220             // INVALID JSON
221             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
222             log.debug("failed to convert from json {}", data, e);
223             ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorForConsumerAndAudit(user, null, actionEnum);
224             return Either.right(responseFormat);
225         }
226         return Either.left(consumer);
227     }
228
229 }