2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.distribution.servlet;
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;
46 import javax.annotation.Resource;
47 import javax.inject.Singleton;
48 import javax.servlet.ServletContext;
49 import javax.servlet.http.HttpServletRequest;
51 import javax.ws.rs.core.Context;
52 import javax.ws.rs.core.MediaType;
53 import javax.ws.rs.core.Response;
56 * This Servlet serves external users for distribution purposes.
62 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
64 @Api(value = "Distribution Servlet", description = "This Servlet serves external users for distribution purposes.")
66 public class DistributionServlet extends BeGenericServlet {
68 private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
69 private static final Logger log = Logger.getLogger(DistributionServlet.class);
71 private DistributionBusinessLogic distributionLogic;
73 private HttpServletRequest request;
80 * @param authorization
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
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) {
106 String url = request.getMethod() + " " + request.getRequestURI();
107 log.debug(START_HANDLE_REQUEST_OF, url);
108 Response response = null;
109 ResponseFormat responseFormat = null;
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());
119 Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();
121 if (actionResponse.isRight()) {
122 responseFormat = actionResponse.right().value();
123 response = buildErrorResponse(responseFormat);
125 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
126 response = buildOkResponse(responseFormat, actionResponse.left().value());
129 getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
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);
149 * @param contenLength
150 * @param authorization
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);
183 Wrapper<Response> responseWrapper = new Wrapper<>();
184 Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();
186 validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);
188 if (responseWrapper.isEmpty()) {
189 validateJson(responseWrapper, registrationRequestWrapper, requestJson);
191 if (responseWrapper.isEmpty()) {
192 validateEnv(responseWrapper);
195 if (responseWrapper.isEmpty()) {
196 distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
198 BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
201 return responseWrapper.getInnerElement();
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.
210 * @param authorization
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) {
232 String url = request.getMethod() + " " + request.getRequestURI();
233 log.debug(START_HANDLE_REQUEST_OF, url);
234 Response response = null;
236 Wrapper<Response> responseWrapper = new Wrapper<>();
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());
243 response = responseWrapper.getInnerElement();
249 * Removes from subscription for distribution notifications
255 * @param contenLength
256 * @param authorization
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) {
287 String url = request.getMethod() + " " + request.getRequestURI();
288 log.debug(START_HANDLE_REQUEST_OF, url);
291 Wrapper<Response> responseWrapper = new Wrapper<>();
292 Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();
294 validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);
296 if (responseWrapper.isEmpty()) {
297 validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);
299 if (responseWrapper.isEmpty()) {
300 validateEnv(responseWrapper);
302 if (responseWrapper.isEmpty()) {
303 distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
305 BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
308 return responseWrapper.getInnerElement();
311 private void validateEnv(Wrapper<Response> responseWrapper) {
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);
320 Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
321 responseWrapper.setInnerElement(missingHeaderResponse);
327 private void init(HttpServletRequest request) {
328 if (distributionLogic == null) {
329 distributionLogic = getDistributionBL(request.getSession().getServletContext());
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());
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);
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);
356 } else if (registrationRequest.getDistrEnvName() == null) {
357 Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
358 responseWrapper.setInnerElement(missingBodyResponse);
360 registrationRequestWrapper.setInnerElement(registrationRequest);
363 Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
364 responseWrapper.setInnerElement(missingBodyResponse);
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);
376 private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {
377 return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest);