f15babd5b95d465c64dfe2d1b792eee3fd2a1f96
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / distribution / servlet / DistributionServlet.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.distribution.servlet;
22
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.annotations.*;
26 import org.openecomp.sdc.be.config.BeEcompErrorManager;
27 import org.openecomp.sdc.be.dao.api.ActionStatus;
28 import org.openecomp.sdc.be.distribution.AuditHandler;
29 import org.openecomp.sdc.be.distribution.DistributionBusinessLogic;
30 import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;
31 import org.openecomp.sdc.be.distribution.api.client.ServerListResponse;
32 import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse;
33 import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse;
34 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
35 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
36 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
37 import org.openecomp.sdc.be.servlets.BeGenericServlet;
38 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
39 import org.openecomp.sdc.common.api.Constants;
40 import org.openecomp.sdc.common.datastructure.Wrapper;
41 import org.openecomp.sdc.common.log.wrappers.Logger;
42 import org.openecomp.sdc.common.util.HttpUtil;
43 import org.openecomp.sdc.exception.ResponseFormat;
44 import org.springframework.web.context.WebApplicationContext;
45
46 import javax.annotation.Resource;
47 import javax.inject.Singleton;
48 import javax.servlet.ServletContext;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.ws.rs.*;
51 import javax.ws.rs.core.Context;
52 import javax.ws.rs.core.MediaType;
53 import javax.ws.rs.core.Response;
54
55 /**
56  * This Servlet serves external users for distribution purposes.
57  * 
58  * @author tgitelman
59  *
60  */
61
62 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
63 @Path("/v1")
64 @Api(value = "Distribution Servlet", description = "This Servlet serves external users for distribution purposes.")
65 @Singleton
66 public class DistributionServlet extends BeGenericServlet {
67
68     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
69         private static final Logger log = Logger.getLogger(DistributionServlet.class);
70     @Resource
71     private DistributionBusinessLogic distributionLogic;
72     @Context
73     private HttpServletRequest request;
74
75     /**
76      *
77      * @param requestId
78      * @param instanceId
79      * @param accept
80      * @param authorization
81      * @return
82      */
83     @GET
84     @Path("/distributionUebCluster")
85     @Consumes(MediaType.APPLICATION_JSON)
86     @Produces(MediaType.APPLICATION_JSON)
87     @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List",
88     //TODO Tal G fix response headers
89     responseHeaders = {
90             @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class),
91             @ResponseHeader(name = "Content-Length", description = "Length of  the response body", response = String.class)})
92     @ApiResponses(value = {
93             @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class),
94             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
95             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its credentials  for  Basic Authentication - POL5002"),
96             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
97             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
98             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
99     public Response getUebServerList(
100             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
101             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
102             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
103             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {
104
105         init(request);
106         String url = request.getMethod() + " " + request.getRequestURI();
107         log.debug(START_HANDLE_REQUEST_OF, url);
108         Response response = null;
109         ResponseFormat responseFormat = null;
110
111         if (instanceId == null) {
112             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
113             response = buildErrorResponse(responseFormat);
114             getComponentsUtils().auditGetUebCluster(null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
115             return response;
116         }
117
118         try {
119             Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();
120
121             if (actionResponse.isRight()) {
122                 responseFormat = actionResponse.right().value();
123                 response = buildErrorResponse(responseFormat);
124             } else {
125                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
126                 response = buildOkResponse(responseFormat, actionResponse.left().value());
127             }
128
129             getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
130             return response;
131
132         } catch (Exception e) {
133             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration");
134             log.debug("failed to get ueb serbver list from cofiguration", e);
135             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
136             getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
137             response = buildErrorResponse(responseFormat);
138             return response;
139         }
140
141     }
142
143     /**
144      *
145      * @param requestId
146      * @param instanceId
147      * @param accept
148      * @param contentType
149      * @param contenLength
150      * @param authorization
151      * @param requestJson
152      * @return
153      */
154     @POST
155     @Path("/registerForDistribution")
156     @Consumes(MediaType.APPLICATION_JSON)
157     @Produces(MediaType.APPLICATION_JSON)
158     @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications")
159     @ApiResponses(value = {
160             @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class),
161             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
162             @ApiResponse(code = 400, message = "Missing  Body - POL4500"),
163             @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
164             @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - POL4502"),
165             @ApiResponse(code = 400, message = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
166             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
167             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
168             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET  will be rejected) - POL4050"),
169             @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
170     @ApiImplicitParams({@ApiImplicitParam(name = "requestJson", required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})
171     public Response registerForDistribution(
172             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
173             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
174             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
175             @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
176             @ApiParam(value = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
177             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
178             @ApiParam( hidden = true) String requestJson) {
179         String url = request.getMethod() + " " + request.getRequestURI();
180         log.debug(START_HANDLE_REQUEST_OF, url);
181         init(request);
182
183         Wrapper<Response> responseWrapper = new Wrapper<>();
184         Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();
185
186         validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);
187
188         if (responseWrapper.isEmpty()) {
189             validateJson(responseWrapper, registrationRequestWrapper, requestJson);
190         }
191         if (responseWrapper.isEmpty()) {
192             validateEnv(responseWrapper);
193         }
194
195         if (responseWrapper.isEmpty()) {
196             distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
197         } else {
198             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
199         }
200
201         return responseWrapper.getInnerElement();
202     }
203
204     /**
205      * Returns list of valid artifact types for validation done in the distribution client.<br>
206      * The list is the representation of the values of the enum ArtifactTypeEnum.
207      *
208      * @param requestId
209      * @param instanceId
210      * @param authorization
211      * @param accept
212      * @return
213      */
214     @GET
215     @Path("/artifactTypes")
216     @Consumes(MediaType.APPLICATION_JSON)
217     @Produces(MediaType.APPLICATION_JSON)
218     @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list")
219     @ApiResponses(value = {
220             @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class),
221             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
222             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
223             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
224             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( POST,PUT,DELETE  will be rejected) - POL4050"),
225             @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
226     public Response getValidArtifactTypes(
227             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
228             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
229             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
230             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {
231         init(request);
232         String url = request.getMethod() + " " + request.getRequestURI();
233         log.debug(START_HANDLE_REQUEST_OF, url);
234         Response response = null;
235
236         Wrapper<Response> responseWrapper = new Wrapper<>();
237
238         //TODO check if in use
239         validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES);
240         if (responseWrapper.isEmpty()) {
241             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values());
242         } else {
243             response = responseWrapper.getInnerElement();
244         }
245         return response;
246     }
247
248     /**
249      * Removes from subscription for distribution notifications
250      *
251      * @param requestId
252      * @param instanceId
253      * @param accept
254      * @param contentType
255      * @param contenLength
256      * @param authorization
257      * @param requestJson
258      * @return
259      */
260     @POST
261     @Path("/unRegisterForDistribution")
262     @Consumes(MediaType.APPLICATION_JSON)
263     @Produces(MediaType.APPLICATION_JSON)
264     @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications")
265     //TODO Edit the responses
266     @ApiResponses(value = {
267             @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class),
268             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
269             @ApiResponse(code = 400, message = "Missing  Body - POL4500"),
270             @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
271             @ApiResponse(code = 400, message = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - SVC4506"),
272             @ApiResponse(code = 400, message = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
273             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
274             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
275             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
276             @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
277     @ApiImplicitParams({@ApiImplicitParam(name = "requestJson", required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})
278     public Response unRegisterForDistribution(
279             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
280             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
281             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
282             @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
283             @ApiParam(value = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
284             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
285             @ApiParam( hidden = true) String requestJson) {
286
287         String url = request.getMethod() + " " + request.getRequestURI();
288         log.debug(START_HANDLE_REQUEST_OF, url);
289         init(request);
290
291         Wrapper<Response> responseWrapper = new Wrapper<>();
292         Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();
293
294         validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);
295
296         if (responseWrapper.isEmpty()) {
297             validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);
298         }
299         if (responseWrapper.isEmpty()) {
300             validateEnv(responseWrapper);
301         }
302         if (responseWrapper.isEmpty()) {
303             distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
304         } else {
305             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
306         }
307
308         return responseWrapper.getInnerElement();
309     }
310
311     private void validateEnv(Wrapper<Response> responseWrapper) {
312
313         // DE194021
314         StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable();
315         if (environmentStatus != StorageOperationStatus.OK) {
316             if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) {
317                 Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));
318                 responseWrapper.setInnerElement(missingHeaderResponse);
319             } else {
320                 Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
321                 responseWrapper.setInnerElement(missingHeaderResponse);
322             }
323         }
324
325     }
326
327     private void init(HttpServletRequest request) {
328         if (distributionLogic == null) {
329             distributionLogic = getDistributionBL(request.getSession().getServletContext());
330         }
331     }
332
333     private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) {
334         if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) {
335             Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));
336             responseWrapper.setInnerElement(missingHeaderResponse);
337             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
338             getComponentsUtils().auditMissingInstanceIdAsDistributionEngineEvent(auditingAction, responseFormat.getStatus().toString());
339
340         }
341
342     }
343
344     private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) {
345         if (requestJson == null || requestJson.isEmpty()) {
346             Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
347             responseWrapper.setInnerElement(missingBodyResponse);
348         } else {
349             Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class);
350             if (eitherRegistration.isLeft()) {
351                 RegistrationRequest registrationRequest = eitherRegistration.left().value();
352                 if (registrationRequest.getApiPublicKey() == null) {
353                     Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));
354                     responseWrapper.setInnerElement(missingBodyResponse);
355
356                 } else if (registrationRequest.getDistrEnvName() == null) {
357                     Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
358                     responseWrapper.setInnerElement(missingBodyResponse);
359                 } else {
360                     registrationRequestWrapper.setInnerElement(registrationRequest);
361                 }
362             } else {
363                 Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
364                 responseWrapper.setInnerElement(missingBodyResponse);
365             }
366         }
367
368     }
369
370     private DistributionBusinessLogic getDistributionBL(ServletContext context) {
371         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
372         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
373         return webApplicationContext.getBean(DistributionBusinessLogic.class);
374     }
375
376     private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {
377         return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest);
378     }
379 }