diff options
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/distribution')
9 files changed, 912 insertions, 892 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java index 0cc415c80d..0aa8d5afa6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java @@ -27,39 +27,34 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; public class AuditHandler { - ComponentsUtils componentsUtils; - String instanceID; - private RegistrationRequest registrationRequest; + ComponentsUtils componentsUtils; + String instanceID; + private RegistrationRequest registrationRequest; - public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) { - super(); - this.componentsUtils = componentsUtils; - this.instanceID = instanceID; - this.registrationRequest = registrationRequest; - } + public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) { + super(); + this.componentsUtils = componentsUtils; + this.instanceID = instanceID; + this.registrationRequest = registrationRequest; + } - public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) { - String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()) - : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()); - componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); - } + public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , String topicName) { + componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + } - public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) { - String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()) - : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()); - componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, String topicName) { + componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + } - } + public void auditRegisterRequest(CambriaErrorResponse registerResponse) { + componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), + registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); - public void auditRegisterRequest(CambriaErrorResponse registerResponse) { - componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), - registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); + } - } - - public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) { - componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), - registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); - } + public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) { + componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), + registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java index ae1de21ea8..2c2adaa970 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java @@ -20,224 +20,275 @@ package org.openecomp.sdc.be.distribution; -import java.util.List; - -import javax.annotation.Resource; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.http.HttpStatus; -import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; -import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; -import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.components.distribution.engine.*; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; -import org.openecomp.sdc.be.distribution.api.client.ServerListResponse; -import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; -import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.be.distribution.api.client.*; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Resource; +import javax.ws.rs.core.Response; +import java.util.List; -import fj.data.Either; +import static org.apache.commons.lang.BooleanUtils.isTrue; +import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName; +import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager; @Component("distributionBusinessLogic") public class DistributionBusinessLogic { - public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine"; - public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine"; - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static Logger log = LoggerFactory.getLogger(DistributionBusinessLogic.class.getName()); - @Resource - private DistributionEngine distributionEngine; - - private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); - private CambriaHandler cambriaHandler; - - public Either<ServerListResponse, ResponseFormat> getUebServerList() { - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - List<String> serverList = distributionEngineConfiguration.getUebServers(); - - if (serverList != null && !serverList.isEmpty()) { - - ServerListResponse serverListResponse = new ServerListResponse(); - - serverListResponse.setUebServerList(serverList); - - return Either.left(serverListResponse); - } else { - ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(errorResponseWrapper); - } - - } - - public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, AuditHandler auditHandler) { - CambriaErrorResponse registerResponse = null; - try { - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER); - - if (responseWrapper.isEmpty()) { - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER); - // Second Register failed - unregister the first - if (!responseWrapper.isEmpty()) { - CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER); - } - } - - if (responseWrapper.isEmpty()) { - TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic"); - Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - } finally { - auditHandler.auditRegisterRequest(registerResponse); - } - } - - public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest, AuditHandler auditHandler) { - Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>(); - try { - CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER); - updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); - - CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.CONSUMER); - auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER); - updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); - - // Success unregister both topics - TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), getStatusTopicName(unRegistrationRequest.getDistrEnvName()), - unregisterClientConsumerTopicResponse.getOperationStatus(), unregisterClientProducerTopicResponse.getOperationStatus()); - - if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) { - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build()); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed"); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration of subscriber to topic"); - Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - - } finally { - auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); - } - } - - private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper, CambriaErrorResponse currentResponse) { - if (cambriaResponseWrapper.isEmpty()) { - cambriaResponseWrapper.setInnerElement(currentResponse); - } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) { - cambriaResponseWrapper.setInnerElement(currentResponse); - - } - - } - - public static String getNotificationTopicName(String envName) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName); - - } - - public static String getStatusTopicName(String envName) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName); - - } - - protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, SubscriberTypeEnum subscriberType) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String topicName; - if (subscriberType == SubscriberTypeEnum.PRODUCER) { - topicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); - } else { - topicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); - - } - log.debug("unregistering client as {} , from topic: {}", subscriberType.name(), topicName); - return getCambriaHandler().unRegisterFromTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType); - } - - private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - - TopicRegistrationResponse topicResponse = new TopicRegistrationResponse(); - topicResponse.setDistrNotificationTopicName(notificationTopicName); - topicResponse.setDistrStatusTopicName(statusTopicName); - return topicResponse; - } - - protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String topicName, errorMsg; - - // Register for notifications as consumer - if (subscriberType == SubscriberTypeEnum.CONSUMER) { - topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; - } - // Register for status as producer - else { - topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; - } - log.debug("registering client as {} , from topic: {}", subscriberType.name(), topicName); - CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), subscriberType); - - if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) { - Response failedRegistrationResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg); - responseWrapper.setInnerElement(failedRegistrationResponse); - } - return registerToTopic; - } - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { - Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - return response; - } - - public ResponseFormatManager getResponseFormatManager() { - return responseFormatManager; - } - - public DistributionEngine getDistributionEngine() { - return distributionEngine; - } - - public CambriaHandler getCambriaHandler() { - if (cambriaHandler == null) { - cambriaHandler = new CambriaHandler(); - } - return cambriaHandler; - } + public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine"; + public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine"; + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final Logger LOGGER = LoggerFactory.getLogger(DistributionBusinessLogic.class); + @Resource + private IDistributionEngine distributionEngine; + + private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); + private CambriaHandler cambriaHandler; + + private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) { + if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){ + registrationRequest.setDistEnvEndPoints(config.getUebServers()); + } + } + public Either<ServerListResponse, ResponseFormat> getUebServerList() { + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + + List<String> serverList = distributionEngineConfiguration.getUebServers(); + + if (serverList != null && !serverList.isEmpty()) { + + ServerListResponse serverListResponse = new ServerListResponse(); + + serverListResponse.setUebServerList(serverList); + + return Either.left(serverListResponse); + } else { + ResponseFormat errorResponseWrapper = getResponseFormatManager() + .getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(errorResponseWrapper); + } + + } + + public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, + AuditHandler auditHandler) { + CambriaErrorResponse registerResponse = null; + try { + DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration(); + String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); + + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER, statusTopicName); + boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty(); + + // Story [347698] Distribution Client Get Indication from + // component whether to register as consumer and producer on + // status topic + boolean registeredAsConsumerOnStatus = false; + if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) { + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.CONSUMER, statusTopicName); + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, statusTopicName); + registeredAsConsumerOnStatus = responseWrapper.isEmpty(); + + } + + if (responseWrapper.isEmpty()) { + String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.CONSUMER, notificationTopicName); + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, notificationTopicName); + } + // Unregister Rollback + if (!responseWrapper.isEmpty()) { + if (isRegisteredAsProducerOnStatusSuccess) { + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); + auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER, statusTopicName); + } + if (registeredAsConsumerOnStatus) { + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, + SubscriberTypeEnum.CONSUMER, statusTopicName); + auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER, statusTopicName); + } + } + + if (responseWrapper.isEmpty()) { + TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + } + + } catch (Exception e) { + LOGGER.error("registration to topic failed", e); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, + "registration of subscriber to topic"); + Response errorResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + } finally { + auditHandler.auditRegisterRequest(registerResponse); + } + } + + public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest, + AuditHandler auditHandler) { + Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>(); + try { + String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); + CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic( + unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName); + auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER, + statusTopicName); + updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); + + String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); + CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic( + unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName); + auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER, + notificationTopicName); + updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); + + // Success unregister both topics + TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse( + getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), + getStatusTopicName(unRegistrationRequest.getDistrEnvName()), + unregisterClientConsumerTopicResponse.getOperationStatus(), + unregisterClientProducerTopicResponse.getOperationStatus()); + + if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) { + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build()); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, + "unregistration failed"); + responseWrapper.setInnerElement( + Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build()); + } + } catch (Exception e) { + LOGGER.error("unregistered to topic failed", e); + Response errorResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + + } finally { + auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); + } + } + + private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper, + CambriaErrorResponse currentResponse) { + if (cambriaResponseWrapper.isEmpty()) { + cambriaResponseWrapper.setInnerElement(currentResponse); + } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) { + cambriaResponseWrapper.setInnerElement(currentResponse); + + } + + } + + public static String getNotificationTopicName(String envName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName); + + } + + public static String getStatusTopicName(String envName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName); + + } + + protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, + SubscriberTypeEnum subscriberType, String topicName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + initRequestEnvEndPoints(unRegistrationRequest, config); + + LOGGER.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints()); + return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(), + config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName); + } + + private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + + TopicRegistrationResponse topicResponse = new TopicRegistrationResponse(); + topicResponse.setDistrNotificationTopicName(notificationTopicName); + topicResponse.setDistrStatusTopicName(statusTopicName); + return topicResponse; + } + + protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper, + RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + initRequestEnvEndPoints(registrationRequest, config); + String errorMsg; + + // Register for notifications as consumer + if (subscriberType == SubscriberTypeEnum.CONSUMER) { + errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; + } + // Register for status as producer + else { + errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; + } + LOGGER.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints()); + CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + subscriberType, topicName); + + if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) { + Response failedRegistrationResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, + errorMsg); + responseWrapper.setInnerElement(failedRegistrationResponse); + } + return registerToTopic; + } + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { + return Response.status(requestErrorWrapper.getStatus()) + .entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + } + + public ResponseFormatManager getResponseFormatManager() { + return responseFormatManager; + } + + public IDistributionEngine getDistributionEngine() { + return distributionEngine; + } + + public CambriaHandler getCambriaHandler() { + if (cambriaHandler == null) { + cambriaHandler = new CambriaHandler(); + } + return cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java index a6a6602cb0..3edb3d8f69 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java @@ -21,5 +21,5 @@ package org.openecomp.sdc.be.distribution.api.client; public enum CambriaOperationStatus { - OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR, + OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR, } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java index ef14efe4f8..1dfbdb538d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java @@ -20,21 +20,43 @@ package org.openecomp.sdc.be.distribution.api.client; +import java.util.List; + public class RegistrationRequest { - String apiPublicKey; - String distrEnvName; + String apiPublicKey; + String distrEnvName; + Boolean isConsumerToSdcDistrStatusTopic; + List<String> distEnvEndPoints; + + public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic) { + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + } + public RegistrationRequest(String apiPublicKey, String distrEnvName, List<String> distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic){ + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.distEnvEndPoints = distEnvEndPoints; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + } + + public String getApiPublicKey() { + return apiPublicKey; + } - public RegistrationRequest(String apiPublicKey, String distrEnvName) { - this.apiPublicKey = apiPublicKey; - this.distrEnvName = distrEnvName; - } + public String getDistrEnvName() { + return distrEnvName; + } - public String getApiPublicKey() { - return apiPublicKey; - } + public Boolean getIsConsumerToSdcDistrStatusTopic() { + return isConsumerToSdcDistrStatusTopic; + } + public List<String> getDistEnvEndPoints() { + return distEnvEndPoints; + } - public String getDistrEnvName() { - return distrEnvName; - } + public void setDistEnvEndPoints(List<String> distEnvEndPoints) { + this.distEnvEndPoints = distEnvEndPoints; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java index 267a691e29..2eebedfd7c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java @@ -24,13 +24,13 @@ import java.util.List; public class ServerListResponse { - private List<String> uebServerList; + private List<String> uebServerList; - public List<String> getUebServerList() { - return uebServerList; - } + public List<String> getUebServerList() { + return uebServerList; + } - public void setUebServerList(List<String> uebServerList) { - this.uebServerList = uebServerList; - } + public void setUebServerList(List<String> uebServerList) { + this.uebServerList = uebServerList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java index e2a34a19d5..5d1b0657c6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java @@ -21,22 +21,22 @@ package org.openecomp.sdc.be.distribution.api.client; public class TopicRegistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; + String distrNotificationTopicName; + String distrStatusTopicName; - public void setDistrNotificationTopicName(String distrNotificationTopicName) { - this.distrNotificationTopicName = distrNotificationTopicName; - } + public void setDistrNotificationTopicName(String distrNotificationTopicName) { + this.distrNotificationTopicName = distrNotificationTopicName; + } - public void setDistrStatusTopicName(String distrStatusTopicName) { - this.distrStatusTopicName = distrStatusTopicName; - } + public void setDistrStatusTopicName(String distrStatusTopicName) { + this.distrStatusTopicName = distrStatusTopicName; + } - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java index ffb9f9352f..621cd37a54 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java @@ -21,32 +21,32 @@ package org.openecomp.sdc.be.distribution.api.client; public class TopicUnregistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; - CambriaOperationStatus notificationUnregisterResult; - CambriaOperationStatus statusUnregisterResult; + String distrNotificationTopicName; + String distrStatusTopicName; + CambriaOperationStatus notificationUnregisterResult; + CambriaOperationStatus statusUnregisterResult; - public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) { - super(); - this.distrNotificationTopicName = distrNotificationTopicName; - this.distrStatusTopicName = distrStatusTopicName; - this.notificationUnregisterResult = notificationUnregisterResult; - this.statusUnregisterResult = statusUnregisterResult; - } + public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) { + super(); + this.distrNotificationTopicName = distrNotificationTopicName; + this.distrStatusTopicName = distrStatusTopicName; + this.notificationUnregisterResult = notificationUnregisterResult; + this.statusUnregisterResult = statusUnregisterResult; + } - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } - public CambriaOperationStatus getNotificationUnregisterResult() { - return notificationUnregisterResult; - } + public CambriaOperationStatus getNotificationUnregisterResult() { + return notificationUnregisterResult; + } - public CambriaOperationStatus getStatusUnregisterResult() { - return statusUnregisterResult; - } + public CambriaOperationStatus getStatusUnregisterResult() { + return statusUnregisterResult; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java index 125c1012b2..984a831c8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java @@ -20,45 +20,33 @@ package org.openecomp.sdc.be.distribution.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; import org.openecomp.sdc.be.servlets.BeGenericServlet; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; /** * This Servlet serves external users to download artifacts. @@ -73,249 +61,233 @@ import io.swagger.annotations.ApiResponses; @Singleton public class DistributionCatalogServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - @Context - private HttpServletRequest request; + private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class); + @Context + private HttpServletRequest request; + + // ******************************************************* + // Download (GET) artifacts + // **********************************************************/ + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @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")}) + public Response downloadServiceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("artifactName") final String artifactName) { + + Response response = null; + String requestURI = request.getRequestURI(); + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); - // ******************************************************* - // Download (GET) artifacts - // **********************************************************/ - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @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")}) - public Response downloadServiceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param resourceName + * @param resourceVersion + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @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")}) + public Response downloadResourceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("resourceName") final String resourceName, + @PathParam("resourceVersion") final String resourceVersion, + @PathParam("artifactName") final String artifactName) { - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + Response response = null; + String requestURI = request.getRequestURI(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download Murano package artifact for service - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param resourceName - * @param resourceVersion - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @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")}) - public Response downloadResourceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("resourceName") final String resourceName, - @PathParam("resourceVersion") final String resourceVersion, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + // Returning 64-encoded as it was received during upload + InputStream is = new ByteArrayInputStream(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - // Returning 64-encoded as it was received during upload - InputStream is = new ByteArrayInputStream(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param resourceInstanceName + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @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")}) + public Response downloadResourceInstanceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("resourceInstanceName") final String resourceInstanceName, + @PathParam("artifactName") final String artifactName) { - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param resourceInstanceName - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(nickname = "downloadResourceInstanceArtifactByName",value = "Download resource instance artifact by artifact name", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @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")}) - public Response downloadResourceInstanceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("resourceInstanceName") final String resourceInstanceName, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + Response response = null; + String requestURI = request.getRequestURI(); - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - // Returning 64-encoded as it was received during upload - InputStream is = new ByteArrayInputStream(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + // Returning 64-encoded as it was received during upload + InputStream is = new ByteArrayInputStream(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java index 6add877fe0..b5c322f90b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java @@ -20,20 +20,9 @@ package org.openecomp.sdc.be.distribution.servlet; -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.distribution.AuditHandler; @@ -56,17 +45,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.ResponseHeader; +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * This Servlet serves external users for distribution purposes. @@ -81,321 +67,315 @@ import io.swagger.annotations.ResponseHeader; @Singleton public class DistributionServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionServlet.class.getName()); - @Resource - private DistributionBusinessLogic distributionLogic; - @Context - private HttpServletRequest request; - - /** - * - * @param requestId - * @param instanceId - * @param accept - * @param authorization - * @return - */ - @GET - @Path("/distributionUebCluster") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List", - //TODO Tal G fix response headers - responseHeaders = { - @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class), - @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)}) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @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")}) - public Response getUebServerList( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - if (instanceId == null) { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - response = buildErrorResponse(responseFormat); - getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - return response; - } - - try { - Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList(); - - if (actionResponse.isRight()) { - responseFormat = actionResponse.right().value(); - response = buildErrorResponse(responseFormat); - } else { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - } - - getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "failed to get ueb serbver list from cofiguration"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration"); - log.debug("failed to get ueb serbver list from cofiguration", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - response = buildErrorResponse(responseFormat); - return response; - } - - } - - /** - * - * @param requestId - * @param instanceId - * @param accept - * @param contenType - * @param contenLength - * @param authorization - * @param requestJson - * @return - */ - @POST - @Path("/registerForDistribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 400, message = "Missing Body - POL4500"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), - @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @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")}) - //TODO Tal G fix response headers and to check missing header validations with Michael L - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact") - public Response registerForDistribution( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - String requestJson) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - init(request); - - Wrapper<Response> responseWrapper = new Wrapper<>(); - Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL); - - if (responseWrapper.isEmpty()) { - validateJson(responseWrapper, registrationRequestWrapper, requestJson); - } - if (responseWrapper.isEmpty()) { - validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName()); - } - - if (responseWrapper.isEmpty()) { - distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); - } - - return responseWrapper.getInnerElement(); - } - - /** - * Returns list of valid artifact types for validation done in the distribution client.<br> - * The list is the representation of the values of the enum ArtifactTypeEnum. - * - * @param requestId - * @param instanceId - * @param authorization - * @param accept - * @return - */ - @GET - @Path("/artifactTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), - @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")}) - public Response getValidArtifactTypes( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - - Wrapper<Response> responseWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); - if (responseWrapper.isEmpty()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values()); - } else { - response = responseWrapper.getInnerElement(); - } - return response; - } - - /** - * Removes from subscription for distribution notifications - * - * @param requestId - * @param instanceId - * @param accept - * @param contenType - * @param contenLength - * @param authorization - * @param requestJson - * @return - */ - @POST - @Path("/unRegisterForDistribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications") - //TODO Edit the responses - @ApiResponses(value = { - @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 400, message = "Missing Body - POL4500"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), - @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @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")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact") - public Response unRegisterForDistribution( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - String requestJson) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - init(request); - - Wrapper<Response> responseWrapper = new Wrapper<>(); - Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); - - if (responseWrapper.isEmpty()) { - validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); - } - if (responseWrapper.isEmpty()) { - validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName()); - } - if (responseWrapper.isEmpty()) { - distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); - } - - return responseWrapper.getInnerElement(); - } - - private void validateEnv(Wrapper<Response> responseWrapper, String distrEnvName) { - - // DE194021 - StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable(); - // DE194021 - // StorageOperationStatus environmentStatus = - // distributionLogic.getDistributionEngine().isEnvironmentAvailable(distrEnvName); - if (environmentStatus != StorageOperationStatus.OK) { - if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST)); - responseWrapper.setInnerElement(missingHeaderResponse); - } else { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(missingHeaderResponse); - } - } - - } - - private void init(HttpServletRequest request) { - if (distributionLogic == null) { - distributionLogic = getDistributionBL(request.getSession().getServletContext()); - } - } - - private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) { - if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); - responseWrapper.setInnerElement(missingHeaderResponse); - // Audit - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - - } - - } - - private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) { - if (requestJson == null || requestJson.isEmpty()) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); - responseWrapper.setInnerElement(missingBodyResponse); - } else { - Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class); - if (eitherRegistration.isLeft()) { - RegistrationRequest registrationRequest = eitherRegistration.left().value(); - if (registrationRequest.getApiPublicKey() == null) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY)); - responseWrapper.setInnerElement(missingBodyResponse); - - } else if (registrationRequest.getDistrEnvName() == null) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME)); - responseWrapper.setInnerElement(missingBodyResponse); - } else { - registrationRequestWrapper.setInnerElement(registrationRequest); - } - } else { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); - responseWrapper.setInnerElement(missingBodyResponse); - } - } - - } - - private DistributionBusinessLogic getDistributionBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(DistributionBusinessLogic.class); - } - - private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) { - return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest); - } + private static final Logger log = LoggerFactory.getLogger(DistributionServlet.class); + @Resource + private DistributionBusinessLogic distributionLogic; + @Context + private HttpServletRequest request; + + /** + * + * @param requestId + * @param instanceId + * @param accept + * @param authorization + * @return + */ + @GET + @Path("/distributionUebCluster") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List", + //TODO Tal G fix response headers + responseHeaders = { + @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class), + @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @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")}) + public Response getUebServerList( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + if (instanceId == null) { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + response = buildErrorResponse(responseFormat); + getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + return response; + } + + try { + Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList(); + + if (actionResponse.isRight()) { + responseFormat = actionResponse.right().value(); + response = buildErrorResponse(responseFormat); + } else { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + } + + getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration"); + log.debug("failed to get ueb serbver list from cofiguration", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + response = buildErrorResponse(responseFormat); + return response; + } + + } + + /** + * + * @param requestId + * @param instanceId + * @param accept + * @param contenType + * @param contenLength + * @param authorization + * @param requestJson + * @return + */ + @POST + @Path("/registerForDistribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 400, message = "Missing Body - POL4500"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), + @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @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")}) + //TODO Tal G fix response headers and to check missing header validations with Michael L + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")}) + public Response registerForDistribution( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + String requestJson) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + init(request); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL); + + if (responseWrapper.isEmpty()) { + validateJson(responseWrapper, registrationRequestWrapper, requestJson); + } + if (responseWrapper.isEmpty()) { + validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName()); + } + + if (responseWrapper.isEmpty()) { + distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); + } + + return responseWrapper.getInnerElement(); + } + + /** + * Returns list of valid artifact types for validation done in the distribution client.<br> + * The list is the representation of the values of the enum ArtifactTypeEnum. + * + * @param requestId + * @param instanceId + * @param authorization + * @param accept + * @return + */ + @GET + @Path("/artifactTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), + @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")}) + public Response getValidArtifactTypes( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + + Wrapper<Response> responseWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); + if (responseWrapper.isEmpty()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values()); + } else { + response = responseWrapper.getInnerElement(); + } + return response; + } + + /** + * Removes from subscription for distribution notifications + * + * @param requestId + * @param instanceId + * @param accept + * @param contenType + * @param contenLength + * @param authorization + * @param requestJson + * @return + */ + @POST + @Path("/unRegisterForDistribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications") + //TODO Edit the responses + @ApiResponses(value = { + @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 400, message = "Missing Body - POL4500"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), + @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @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")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")}) + public Response unRegisterForDistribution( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + String requestJson) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + init(request); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); + + if (responseWrapper.isEmpty()) { + validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); + } + if (responseWrapper.isEmpty()) { + validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName()); + } + if (responseWrapper.isEmpty()) { + distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); + } + + return responseWrapper.getInnerElement(); + } + + private void validateEnv(Wrapper<Response> responseWrapper, String distrEnvName) { + + // DE194021 + StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable(); + if (environmentStatus != StorageOperationStatus.OK) { + if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST)); + responseWrapper.setInnerElement(missingHeaderResponse); + } else { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(missingHeaderResponse); + } + } + + } + + private void init(HttpServletRequest request) { + if (distributionLogic == null) { + distributionLogic = getDistributionBL(request.getSession().getServletContext()); + } + } + + private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) { + if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); + responseWrapper.setInnerElement(missingHeaderResponse); + // Audit + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + + } + + } + + private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) { + if (requestJson == null || requestJson.isEmpty()) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + responseWrapper.setInnerElement(missingBodyResponse); + } else { + Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class); + if (eitherRegistration.isLeft()) { + RegistrationRequest registrationRequest = eitherRegistration.left().value(); + if (registrationRequest.getApiPublicKey() == null) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY)); + responseWrapper.setInnerElement(missingBodyResponse); + + } else if (registrationRequest.getDistrEnvName() == null) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME)); + responseWrapper.setInnerElement(missingBodyResponse); + } else { + registrationRequestWrapper.setInnerElement(registrationRequest); + } + } else { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + responseWrapper.setInnerElement(missingBodyResponse); + } + } + + } + + private DistributionBusinessLogic getDistributionBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(DistributionBusinessLogic.class); + } + + private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) { + return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest); + } } |