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