diff options
author | ys9693 <ys9693@att.com> | 2020-01-19 13:50:02 +0200 |
---|---|---|
committer | Ofir Sonsino <ofir.sonsino@intl.att.com> | 2020-01-22 12:33:31 +0000 |
commit | 16a9fce0e104a38371a9e5a567ec611ae3fc7f33 (patch) | |
tree | 03a2aff3060ddb5bc26a90115805a04becbaffc9 /common-app-api/src/main/java | |
parent | aa83a2da4f911c3ac89318b8e9e8403b072942e1 (diff) |
Catalog alignment
Issue-ID: SDC-2724
Signed-off-by: ys9693 <ys9693@att.com>
Change-Id: I52b4aacb58cbd432ca0e1ff7ff1f7dd52099c6fe
Diffstat (limited to 'common-app-api/src/main/java')
136 files changed, 7122 insertions, 8686 deletions
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java index 0a3d50f848..75da11155b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,417 +26,412 @@ import org.openecomp.sdc.common.config.IEcompConfigurationManager; public class BeEcompErrorManager extends AbsEcompErrorManager { - public enum ComponentName { - SERVICE, PRODUCT, VF - } - - public enum ErrorSeverity { - INFO, WARNING, ERROR, FATAL - } - - private static volatile BeEcompErrorManager instance; - private static ConfigurationManager configurationManager; - - private BeEcompErrorManager() { - } - - public static BeEcompErrorManager getInstance() { - if (instance == null) { - synchronized (BeEcompErrorManager.class) { - if (instance == null) { - instance = init(); - } - } - } - return instance; - } - - private static synchronized BeEcompErrorManager init() { - if (instance == null) { - instance = new BeEcompErrorManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } - - @Override - public IEcompConfigurationManager getConfigurationManager() { - return configurationManager; - } - - public void logBeUebAuthenticationError(String context, String reason) { - processEcompError(context, EcompErrorEnum.BeUebAuthenticationError, reason); - } - - public void logBeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckRecovery); - } - - public void logBeHealthCheckJanusGraphRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphRecovery); - } - - public void logBeHealthCheckElasticSearchRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckElasticSearchRecovery); - } - - public void logBeHealthCheckUebClusterRecovery(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterRecovery); - } - - public void logDmaapHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.DmaapHealthCheckError); - } - - public void logDmaapHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.DmaapHealthCheckRecovery); - } - - public void logFeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); - } - - public void logBeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckError); - } - - public void logBeHealthCheckJanusGraphError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphError); - } - - public void logBeHealthCheckElasticSearchError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckElasticSearchError); - } - - public void logBeHealthCheckUebClusterError(String context) { - processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterError); - } - - public void logFeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckError); - } - - /** - * @param context - * @param reason - */ - public void logBeUebConnectionError(String context, String reason) { - processEcompError(context, EcompErrorEnum.BeUebConnectionError, reason); - } - - public void logBeUebUnkownHostError(String context, String host) { - processEcompError(context, EcompErrorEnum.BeUebUnkownHostError, host); - } - - public void logBeComponentMissingError(String context, String componentType, String name) { - processEcompError(context, EcompErrorEnum.BeComponentMissingError, componentType, name); - } - - public void logBeIncorrectComponentError(String context, String componentType, String name) { - processEcompError(context, EcompErrorEnum.BeIncorrectComponentError, componentType, name); - } - - public void logBeInvalidConfigurationError(String context, String parameterName, String parameterValue) { - processEcompError(context, EcompErrorEnum.BeInvalidConfigurationError, parameterName, parameterValue); - } - - public void logBeUebObjectNotFoundError(String context, String notFoundObjectName) { - processEcompError(context, EcompErrorEnum.BeUebObjectNotFoundError, notFoundObjectName); - } - - public void logBeDistributionEngineInvalidArtifactType(String context, String artifactType, - String validArtifactTypes) { - processEcompError(context, EcompErrorEnum.BeDistributionEngineInvalidArtifactType, artifactType, - validArtifactTypes); - } - - public void logBeMissingConfigurationError(String context, String parameterName) { - processEcompError(context, EcompErrorEnum.BeMissingConfigurationError, parameterName); - } - - public void logBeConfigurationInvalidListSizeError(String context, String parameterName, int listMinimumSize) { - processEcompError(context, EcompErrorEnum.BeConfigurationInvalidListSizeError, parameterName, - String.valueOf(listMinimumSize)); - } - - public void logErrorConfigFileFormat(String context, String description) { - processEcompError(context, EcompErrorEnum.ErrorConfigFileFormat, description); - } - - public void logBeMissingArtifactInformationError(String context, String missingInfo) { - processEcompError(context, EcompErrorEnum.BeMissingArtifactInformationError, missingInfo); - } - - public void logBeArtifactMissingError(String context, String artifactName) { - processEcompError(context, EcompErrorEnum.BeArtifactMissingError, artifactName); - } - - public void logBeUserMissingError(String context, String userId) { - processEcompError(context, EcompErrorEnum.BeUserMissingError, userId); - } - - public void logBeInvalidTypeError(String context, String type, String name) { - processEcompError(context, EcompErrorEnum.BeInvalidTypeError, type, name); - } - - public void logBeInvalidValueError(String context, String value, String name, String type) { - processEcompError(context, EcompErrorEnum.BeInvalidValueError, value, name, type); - } - - public void logBeArtifactPayloadInvalid(String context) { - processEcompError(context, EcompErrorEnum.BeArtifactPayloadInvalid); - } - - public void logBeArtifactInformationInvalidError(String context) { - processEcompError(context, EcompErrorEnum.BeArtifactInformationInvalidError); - } - - public void logBeDistributionMissingError(String context, String distributionName) { - processEcompError(context, EcompErrorEnum.BeDistributionMissingError, "Distribution", distributionName); - } - - public void logBeGraphObjectMissingError(String context, String objectType, String objectName) { - processEcompError(context, EcompErrorEnum.BeGraphObjectMissingError, objectType, objectName); - } - - public void logBeInvalidJsonInput(String context) { - processEcompError(context, EcompErrorEnum.BeInvalidJsonInput); - } - - public void logBeInitializationError(String context) { - processEcompError(context, EcompErrorEnum.BeInitializationError); - } - - public void logBeFailedAddingResourceInstanceError(String context, String resourceName, String serviceId) { - processEcompError(context, EcompErrorEnum.BeFailedAddingResourceInstanceError, resourceName, serviceId); - } - - public void logBeUebSystemError(String context, String operation) { - processEcompError(context, EcompErrorEnum.BeUebSystemError, operation); - } - - public void logBeDistributionEngineSystemError(String context, String operation) { - processEcompError(context, EcompErrorEnum.BeDistributionEngineSystemError, operation); - } - - public void logBeFailedAddingNodeTypeError(String context, String nodeType) { - processEcompError(context, EcompErrorEnum.BeFailedAddingNodeTypeError, nodeType); - } - - public void logBeDaoSystemError(String context) { - processEcompError(context, EcompErrorEnum.BeDaoSystemError); - } - - public void logBeSystemError(String context) { - processEcompError(context, EcompErrorEnum.BeSystemError); - } - - public void logBeExecuteRollbackError(String context) { - processEcompError(context, EcompErrorEnum.BeExecuteRollbackError); - } - - public void logBeFailedLockObjectError(String context, String type, String id) { - processEcompError(context, EcompErrorEnum.BeFailedLockObjectError, type, id); - } - - public void logBeFailedCreateNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedCreateNodeError, nodeName, status); - } - - public void logBeFailedUpdateNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedUpdateNodeError, nodeName, status); - } - - public void logBeFailedDeleteNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedDeleteNodeError, nodeName, status); - } - - public void logBeFailedRetrieveNodeError(String context, String nodeName, String status) { - processEcompError(context, EcompErrorEnum.BeFailedRetrieveNodeError, nodeName, status); - } - - public void logBeFailedFindParentError(String context, String node, String status) { - processEcompError(context, EcompErrorEnum.BeFailedFindParentError, node, status); - } - - public void logBeFailedFindAllNodesError(String context, String nodeType, String parentNode, String status) { - processEcompError(context, EcompErrorEnum.BeFailedFindAllNodesError, nodeType, parentNode, status); - } - - public void logBeFailedFindAssociationError(String context, String nodeType, String fromNode, String status) { - processEcompError(context, EcompErrorEnum.BeFailedFindAssociationError, nodeType, fromNode, status); - } - - public void logBeComponentCleanerSystemError(String context, String operation) { - processEcompError(context, EcompErrorEnum.BeComponentCleanerSystemError, operation); - } - - public void logBeRestApiGeneralError(String context) { - processEcompError(context, EcompErrorEnum.BeRestApiGeneralError); - } - - public void logFqdnResolveError(String context, String description) { - processEcompError(context, EcompErrorEnum.FqdnResolveError, description); - } - - public void logSiteSwitchoverInfo(String context, String description) { - processEcompError(context, EcompErrorEnum.SiteSwitchoverInfo, description); - } - - public void logInternalAuthenticationError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalAuthenticationInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalAuthenticationWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalAuthenticationFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalConnectionError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalConnectionError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalConnectionInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalConnectionWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalConnectionError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalConnectionFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalDataError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalDataError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalDataInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalDataWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalDataError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalDataFatal, description); - break; - - default: - break; - } - } - - } - - public void logInvalidInputError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InvalidInputError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InvalidInputWarning, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InvalidInputInfo, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InvalidInputError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InvalidInputFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalFlowError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalFlowError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalFlowInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalFlowWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalFlowError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalFlowFatal, description); - break; - - default: - break; - } - } - - } - - public void logInternalUnexpectedError(String context, String description, ErrorSeverity severity) { - - if (severity == null) { - processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); - } else { - switch (severity) { - case INFO: - processEcompError(context, EcompErrorEnum.InternalUnexpectedInfo, description); - break; - case WARNING: - processEcompError(context, EcompErrorEnum.InternalUnexpectedWarning, description); - break; - case ERROR: - processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); - break; - case FATAL: - processEcompError(context, EcompErrorEnum.InternalUnexpectedFatal, description); - break; - - default: - break; - } - } - - } + public enum ComponentName { + SERVICE, PRODUCT, VF + } + + public enum ErrorSeverity { + INFO, WARNING, ERROR, FATAL + } + + private static volatile BeEcompErrorManager instance; + private static ConfigurationManager configurationManager; + + private BeEcompErrorManager() { + }; + + public static BeEcompErrorManager getInstance() { + if (instance == null) { + synchronized (BeEcompErrorManager.class){ + if (instance == null) + instance = init(); + } + } + return instance; + } + + private static synchronized BeEcompErrorManager init() { + if (instance == null) { + instance = new BeEcompErrorManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } + + @Override + public IEcompConfigurationManager getConfigurationManager() { + return configurationManager; + } + + public void logBeUebAuthenticationError(String context, String reason) { + processEcompError(context, EcompErrorEnum.BeUebAuthenticationError, reason); + } + + public void logBeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckRecovery); + } + + public void logBeHealthCheckJanusGraphRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphRecovery); + } + + public void logBeHealthCheckUebClusterRecovery(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterRecovery); + } + + public void logDmaapHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.DmaapHealthCheckError); + } + + public void logUserSessionExpiredError(String context) { + processEcompError(context, EcompErrorEnum.SessionExpiredAuthenticationError); + } + + public void logDmaapHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.DmaapHealthCheckRecovery); + } + + public void logFeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); + } + + public void logBeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckError); + } + + public void logBeHealthCheckJanusGraphError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckJanusGraphError); + } + + public void logBeHealthCheckUebClusterError(String context) { + processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterError); + } + + public void logFeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckError); + } + + /** + * @param context + * @param reason + */ + public void logBeUebConnectionError(String context, String reason) { + processEcompError(context, EcompErrorEnum.BeUebConnectionError, reason); + } + + public void logBeUebUnkownHostError(String context, String host) { + processEcompError(context, EcompErrorEnum.BeUebUnkownHostError, host); + } + + public void logBeComponentMissingError(String context, String componentType, String name) { + processEcompError(context, EcompErrorEnum.BeComponentMissingError, componentType, name); + } + + public void logBeIncorrectComponentError(String context, String componentType, String name) { + processEcompError(context, EcompErrorEnum.BeIncorrectComponentError, componentType, name); + } + + public void logBeInvalidConfigurationError(String context, String parameterName, String parameterValue) { + processEcompError(context, EcompErrorEnum.BeInvalidConfigurationError, parameterName, parameterValue); + } + + public void logBeUebObjectNotFoundError(String context, String notFoundObjectName) { + processEcompError(context, EcompErrorEnum.BeUebObjectNotFoundError, notFoundObjectName); + } + + public void logBeDistributionEngineInvalidArtifactType(String context, String artifactType, + String validArtifactTypes) { + processEcompError(context, EcompErrorEnum.BeDistributionEngineInvalidArtifactType, artifactType, + validArtifactTypes); + } + + public void logBeMissingConfigurationError(String context, String parameterName) { + processEcompError(context, EcompErrorEnum.BeMissingConfigurationError, parameterName); + } + + public void logBeConfigurationInvalidListSizeError(String context, String parameterName, int listMinimumSize) { + processEcompError(context, EcompErrorEnum.BeConfigurationInvalidListSizeError, parameterName, + String.valueOf(listMinimumSize)); + } + + public void logErrorConfigFileFormat(String context, String description) { + processEcompError(context, EcompErrorEnum.ErrorConfigFileFormat, description); + } + + public void logBeMissingArtifactInformationError(String context, String missingInfo) { + processEcompError(context, EcompErrorEnum.BeMissingArtifactInformationError, missingInfo); + } + + public void logBeArtifactMissingError(String context, String artifactName) { + processEcompError(context, EcompErrorEnum.BeArtifactMissingError, artifactName); + } + + public void logBeUserMissingError(String context, String userId) { + processEcompError(context, EcompErrorEnum.BeUserMissingError, userId); + } + + public void logBeInvalidTypeError(String context, String type, String name) { + processEcompError(context, EcompErrorEnum.BeInvalidTypeError, type, name); + } + + public void logBeInvalidValueError(String context, String value, String name, String type) { + processEcompError(context, EcompErrorEnum.BeInvalidValueError, value, name, type); + } + + public void logBeArtifactPayloadInvalid(String context) { + processEcompError(context, EcompErrorEnum.BeArtifactPayloadInvalid); + } + + public void logBeArtifactInformationInvalidError(String context) { + processEcompError(context, EcompErrorEnum.BeArtifactInformationInvalidError); + } + + public void logBeDistributionMissingError(String context, String distributionName) { + processEcompError(context, EcompErrorEnum.BeDistributionMissingError, "Distribution", distributionName); + } + + public void logBeGraphObjectMissingError(String context, String objectType, String objectName) { + processEcompError(context, EcompErrorEnum.BeGraphObjectMissingError, objectType, objectName); + } + + public void logBeInvalidJsonInput(String context) { + processEcompError(context, EcompErrorEnum.BeInvalidJsonInput); + } + + public void logBeInitializationError(String context) { + processEcompError(context, EcompErrorEnum.BeInitializationError); + } + + public void logBeFailedAddingResourceInstanceError(String context, String resourceName, String serviceId) { + processEcompError(context, EcompErrorEnum.BeFailedAddingResourceInstanceError, resourceName, serviceId); + } + + public void logBeUebSystemError(String context, String operation) { + processEcompError(context, EcompErrorEnum.BeUebSystemError, operation); + } + + public void logBeDistributionEngineSystemError(String context, String operation) { + processEcompError(context, EcompErrorEnum.BeDistributionEngineSystemError, operation); + } + + public void logBeFailedAddingNodeTypeError(String context, String nodeType) { + processEcompError(context, EcompErrorEnum.BeFailedAddingNodeTypeError, nodeType); + } + + public void logBeDaoSystemError(String context) { + processEcompError(context, EcompErrorEnum.BeDaoSystemError); + } + + public void logBeSystemError(String context) { + processEcompError(context, EcompErrorEnum.BeSystemError); + } + + public void logBeExecuteRollbackError(String context) { + processEcompError(context, EcompErrorEnum.BeExecuteRollbackError); + } + + public void logBeFailedLockObjectError(String context, String type, String id) { + processEcompError(context, EcompErrorEnum.BeFailedLockObjectError, type, id); + } + + public void logBeFailedCreateNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedCreateNodeError, nodeName, status); + } + + public void logBeFailedUpdateNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedUpdateNodeError, nodeName, status); + } + + public void logBeFailedDeleteNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedDeleteNodeError, nodeName, status); + } + + public void logBeFailedRetrieveNodeError(String context, String nodeName, String status) { + processEcompError(context, EcompErrorEnum.BeFailedRetrieveNodeError, nodeName, status); + } + + public void logBeFailedFindParentError(String context, String node, String status) { + processEcompError(context, EcompErrorEnum.BeFailedFindParentError, node, status); + } + + public void logBeFailedFindAllNodesError(String context, String nodeType, String parentNode, String status) { + processEcompError(context, EcompErrorEnum.BeFailedFindAllNodesError, nodeType, parentNode, status); + } + + public void logBeFailedFindAssociationError(String context, String nodeType, String fromNode, String status) { + processEcompError(context, EcompErrorEnum.BeFailedFindAssociationError, nodeType, fromNode, status); + } + + public void logBeComponentCleanerSystemError(String context, String operation) { + processEcompError(context, EcompErrorEnum.BeComponentCleanerSystemError, operation); + } + + public void logBeRestApiGeneralError(String context) { + processEcompError(context, EcompErrorEnum.BeRestApiGeneralError); + } + + public void logFqdnResolveError(String context, String description) { + processEcompError(context, EcompErrorEnum.FqdnResolveError, description); + } + + public void logSiteSwitchoverInfo(String context, String description) { + processEcompError(context, EcompErrorEnum.SiteSwitchoverInfo, description); + } + + public void logInternalAuthenticationError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalAuthenticationInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalAuthenticationWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalAuthenticationError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalAuthenticationFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalConnectionError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalConnectionError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalConnectionInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalConnectionWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalConnectionError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalConnectionFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalDataError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalDataError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalDataInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalDataWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalDataError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalDataFatal, description); + break; + + default: + break; + } + } + + } + + public void logInvalidInputError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InvalidInputError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InvalidInputWarning, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InvalidInputInfo, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InvalidInputError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InvalidInputFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalFlowError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalFlowError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalFlowInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalFlowWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalFlowError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalFlowFatal, description); + break; + + default: + break; + } + } + + } + + public void logInternalUnexpectedError(String context, String description, ErrorSeverity severity) { + + if (severity == null) { + processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); + } else { + switch (severity) { + case INFO: + processEcompError(context, EcompErrorEnum.InternalUnexpectedInfo, description); + break; + case WARNING: + processEcompError(context, EcompErrorEnum.InternalUnexpectedWarning, description); + break; + case ERROR: + processEcompError(context, EcompErrorEnum.InternalUnexpectedError, description); + break; + case FATAL: + processEcompError(context, EcompErrorEnum.InternalUnexpectedFatal, description); + break; + + default: + break; + } + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/CadiFilterParams.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CadiFilterParams.java new file mode 100644 index 0000000000..39793fb2cd --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CadiFilterParams.java @@ -0,0 +1,142 @@ +package org.openecomp.sdc.be.config; + +public class CadiFilterParams { + + private String hostname; + private String csp_domain; + private String cadi_keyfile; + private String cadi_loglevel; + private String cadi_truststore; + private String cadi_truststore_password; + + private String aaf_id; + private String aaf_password; + private String aaf_env; + private String aafLocateUrl; + private String aaf_url; + private String AFT_LATITUDE; + private String AFT_LONGITUDE; + private String AFT_ENVIRONMENT; + private String cadiX509Issuers; + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public String getCsp_domain() { + return csp_domain; + } + + public void setCsp_domain(String csp_domain) { + this.csp_domain = csp_domain; + } + + public String getCadi_keyfile() { + return cadi_keyfile; + } + + public void setCadi_keyfile(String cadi_keyfile) { + this.cadi_keyfile = cadi_keyfile; + } + + public String getCadi_loglevel() { + return cadi_loglevel; + } + + public void setCadi_loglevel(String cadi_loglevel) { + this.cadi_loglevel = cadi_loglevel; + } + + public String getCadi_truststore() { + return cadi_truststore; + } + + public void setCadi_truststore(String cadi_truststore) { + this.cadi_truststore = cadi_truststore; + } + + public String getCadi_truststore_password() { + return cadi_truststore_password; + } + + public void setCadi_truststore_password(String cadi_truststore_password) { + this.cadi_truststore_password = cadi_truststore_password; + } + + public String getAaf_id() { + return aaf_id; + } + + public void setAaf_id(String aaf_id) { + this.aaf_id = aaf_id; + } + + public String getAaf_password() { + return aaf_password; + } + + public void setAaf_password(String aaf_password) { + this.aaf_password = aaf_password; + } + + public String getAaf_env() { + return aaf_env; + } + + public void setAaf_env(String aaf_env) { + this.aaf_env = aaf_env; + } + + public String getAafLocateUrl() { + return aafLocateUrl; + } + + public void setAafLocateUrl(String aafLocateUrl) { + this.aafLocateUrl = aafLocateUrl; + } + + public String getAaf_url() { + return aaf_url; + } + + public void setAaf_url(String aaf_url) { + this.aaf_url = aaf_url; + } + + public String getAFT_LATITUDE() { + return AFT_LATITUDE; + } + + public void setAFT_LATITUDE(String aFT_LATITUDE) { + AFT_LATITUDE = aFT_LATITUDE; + } + + public String getAFT_LONGITUDE() { + return AFT_LONGITUDE; + } + + public void setAFT_LONGITUDE(String aFT_LONGITUDE) { + AFT_LONGITUDE = aFT_LONGITUDE; + } + + public String getAFT_ENVIRONMENT() { + return AFT_ENVIRONMENT; + } + + public void setAFT_ENVIRONMENT(String aFT_ENVIRONMENT) { + AFT_ENVIRONMENT = aFT_ENVIRONMENT; + } + + public String getCadiX509Issuers() { + return cadiX509Issuers; + } + + public void setCadiX509Issuers(String cadiX509Issuers) { + this.cadiX509Issuers = cadiX509Issuers; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java index dd0c6d0235..6411005449 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/CleanComponentsConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,23 +24,23 @@ import java.util.List; public class CleanComponentsConfiguration { - private long cleanIntervalInMinutes; - private List<String> componentsToClean; + private long cleanIntervalInMinutes; + private List<String> componentsToClean; - public long getCleanIntervalInMinutes() { - return cleanIntervalInMinutes; - } + public long getCleanIntervalInMinutes() { + return cleanIntervalInMinutes; + } - public void setCleanIntervalInMinutes(long cleanIntervalInMinutes) { - this.cleanIntervalInMinutes = cleanIntervalInMinutes; - } + public void setCleanIntervalInMinutes(long cleanIntervalInMinutes) { + this.cleanIntervalInMinutes = cleanIntervalInMinutes; + } - public List<String> getComponentsToClean() { - return componentsToClean; - } + public List<String> getComponentsToClean() { + return componentsToClean; + } - public void setComponentsToClean(List<String> componentsToClean) { - this.componentsToClean = componentsToClean; - } + public void setComponentsToClean(List<String> componentsToClean) { + this.componentsToClean = componentsToClean; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java index a51b42fb24..5d5afe0c98 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java @@ -68,7 +68,6 @@ public class Configuration extends BasicConfiguration { private List<String> protocols; private Map<String, String> users; private Map<String, Object> neo4j; - private ElasticSearchConfig elasticSearch; private String janusGraphCfgFile; private String janusGraphMigrationKeySpaceCfgFile; private Boolean janusGraphInMemoryGraph; @@ -77,7 +76,6 @@ public class Configuration extends BasicConfiguration { private Long janusGraphReconnectIntervalInSeconds; private List<String> healthStatusExclude; private Long janusGraphHealthCheckReadTimeout; - private Long esReconnectIntervalInSeconds; private Long uebHealthCheckReconnectIntervalInSeconds; private Long uebHealthCheckReadTimeout; private List<Map<String, Map<String, String>>> defaultImports; @@ -100,14 +98,12 @@ public class Configuration extends BasicConfiguration { private Map<String, ArtifactTypeConfig> resourceInformationalDeployedArtifacts; private Map<String, Object> serviceApiArtifacts; private List<String> excludeServiceCategory; - private Map<String, Set<String>> requirementsToFulfillBeforeCert; - private Map<String, Set<String>> capabilitiesToConsumeBeforeCert; private List<String> artifactTypes; private List<String> licenseTypes; private Integer additionalInformationMaxNumberOfKeys; - private Integer defaultHeatArtifactTimeoutMinutes; + private HeatDeploymentArtifactTimeout heatArtifactDeploymentTimeout; private BeMonitoringConfig systemMonitoring; private CleanComponentsConfiguration cleanComponentsConfiguration; @@ -136,25 +132,26 @@ public class Configuration extends BasicConfiguration { private boolean disableAudit; + private Boolean consumerBusinessLogic; + private Map<String, VfModuleProperty> vfModuleProperties; private Map<String, String> genericAssetNodeTypes; private String appVersion; + private String artifactGeneratorConfig; - public String getAutoHealingOwner() { - return autoHealingOwner; - } + private CadiFilterParams cadiFilterParams; - public void setAutoHealingOwner(String autoHealingOwner) { - this.autoHealingOwner = autoHealingOwner; - } + private Boolean aafAuthNeeded; private String autoHealingOwner; private boolean enableAutoHealing; private Map<String, List<String>> resourcesForUpgrade; private DmaapConsumerConfiguration dmaapConsumerConfiguration; + private DmaapProducerConfiguration dmaapProducerConfiguration; + private boolean skipUpgradeFailedVfs; private boolean skipUpgradeVSPs; private DmeConfiguration dmeConfiguration; @@ -162,6 +159,22 @@ public class Configuration extends BasicConfiguration { private boolean supportAllottedResourcesAndProxy; private Integer deleteLockTimeoutInSeconds; private Integer maxDeleteComponents; + private CookieConfig authCookie; + + + private String aafNamespace; + private String workloadContext; + + private EnvironmentContext environmentContext; + + + public String getAutoHealingOwner() { + return autoHealingOwner; + } + + public void setAutoHealingOwner(String autoHealingOwner) { + this.autoHealingOwner = autoHealingOwner; + } public Integer getMaxDeleteComponents() { return maxDeleteComponents; @@ -202,14 +215,9 @@ public class Configuration extends BasicConfiguration { public void setDmeConfiguration(DmeConfiguration dmeConfiguration) { this.dmeConfiguration = dmeConfiguration; } + public void setSkipUpgradeVSPs(boolean skipUpgradeVSPs) { this.skipUpgradeVSPs = skipUpgradeVSPs; } - public void setSkipUpgradeVSPs(boolean skipUpgradeVSPs) { - this.skipUpgradeVSPs = skipUpgradeVSPs; - } - - public boolean getSkipUpgradeVSPsFlag() { - return skipUpgradeVSPs; - } + public boolean getSkipUpgradeVSPsFlag() { return skipUpgradeVSPs; } public boolean getSkipUpgradeFailedVfs() { return skipUpgradeFailedVfs; @@ -235,9 +243,13 @@ public class Configuration extends BasicConfiguration { this.appVersion = appVersion; } - private String workloadContext; + public String getArtifactGeneratorConfig() { + return artifactGeneratorConfig; + } - private EnvironmentContext environmentContext; + public void setArtifactGeneratorConfig(String artifactGeneratorConfig) { + this.artifactGeneratorConfig = artifactGeneratorConfig; + } private List<GabConfig> gabConfig; @@ -371,14 +383,6 @@ public class Configuration extends BasicConfiguration { this.neo4j = neo4j; } - public ElasticSearchConfig getElasticSearch() { - return elasticSearch; - } - - public void setElasticSearch(ElasticSearchConfig elasticSearch) { - this.elasticSearch = elasticSearch; - } - public String getJanusGraphCfgFile() { return janusGraphCfgFile; } @@ -443,18 +447,6 @@ public class Configuration extends BasicConfiguration { this.janusGraphReconnectIntervalInSeconds = janusGraphReconnectIntervalInSeconds; } - public Long getEsReconnectIntervalInSeconds() { - return esReconnectIntervalInSeconds; - } - - public Long getEsReconnectIntervalInSeconds(long defaultVal) { - return esReconnectIntervalInSeconds == null ? defaultVal : esReconnectIntervalInSeconds; - } - - public void setEsReconnectIntervalInSeconds(Long esReconnectIntervalInSeconds) { - this.esReconnectIntervalInSeconds = esReconnectIntervalInSeconds; - } - public List<String> getArtifactTypes() { return artifactTypes; } @@ -576,20 +568,20 @@ public class Configuration extends BasicConfiguration { this.additionalInformationMaxNumberOfKeys = additionalInformationMaxNumberOfKeys; } - public BeMonitoringConfig getSystemMonitoring() { - return systemMonitoring; + public HeatDeploymentArtifactTimeout getHeatArtifactDeploymentTimeout() { + return heatArtifactDeploymentTimeout; } - public void setSystemMonitoring(BeMonitoringConfig systemMonitoring) { - this.systemMonitoring = systemMonitoring; + public void setHeatArtifactDeploymentTimeout(HeatDeploymentArtifactTimeout heatArtifactDeploymentTimeout) { + this.heatArtifactDeploymentTimeout = heatArtifactDeploymentTimeout; } - public Integer getDefaultHeatArtifactTimeoutMinutes() { - return defaultHeatArtifactTimeoutMinutes; + public BeMonitoringConfig getSystemMonitoring() { + return systemMonitoring; } - public void setDefaultHeatArtifactTimeoutMinutes(Integer defaultHeatArtifactTimeoutMinutes) { - this.defaultHeatArtifactTimeoutMinutes = defaultHeatArtifactTimeoutMinutes; + public void setSystemMonitoring(BeMonitoringConfig systemMonitoring) { + this.systemMonitoring = systemMonitoring; } public Long getUebHealthCheckReconnectIntervalInSeconds() { @@ -632,66 +624,128 @@ public class Configuration extends BasicConfiguration { this.gabConfig = gabConfig; } - public static class ElasticSearchConfig { - private List<IndicesTimeFrequencyEntry> indicesTimeFrequency; + public static class CookieConfig { + String securityKey = ""; + long maxSessionTimeOut = 600*1000; + long sessionIdleTimeOut = 30*1000; + String cookieName = "AuthenticationCookie"; + String redirectURL = "https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp"; + List<String> excludedUrls; + List<String> onboardingExcludedUrls; + String domain = ""; + String path = ""; + boolean isHttpOnly = true; + + public String getSecurityKey() { + return securityKey; + } + + public void setSecurityKey(String securityKey) { + this.securityKey = securityKey; + } - public List<IndicesTimeFrequencyEntry> getIndicesTimeFrequency() { - return indicesTimeFrequency; + public long getMaxSessionTimeOut() { + return maxSessionTimeOut; } - public void setIndicesTimeFrequency(List<IndicesTimeFrequencyEntry> indicesTimeFrequency) { - this.indicesTimeFrequency = indicesTimeFrequency; + public void setMaxSessionTimeOut(long maxSessionTimeOut) { + this.maxSessionTimeOut = maxSessionTimeOut; } - public static class IndicesTimeFrequencyEntry { + public long getSessionIdleTimeOut() { + return sessionIdleTimeOut; + } - private String indexPrefix; - private String creationPeriod; + public void setSessionIdleTimeOut(long sessionIdleTimeOut) { + this.sessionIdleTimeOut = sessionIdleTimeOut; + } - public String getIndexPrefix() { - return indexPrefix; - } + public String getCookieName() { + return cookieName; + } - public void setIndexPrefix(String indexPrefix) { - this.indexPrefix = indexPrefix; - } + public void setCookieName(String cookieName) { + this.cookieName = cookieName; + } - public String getCreationPeriod() { - return creationPeriod; - } + public String getRedirectURL() { + return redirectURL; + } - public void setCreationPeriod(String creationPeriod) { - this.creationPeriod = creationPeriod; - } + public void setRedirectURL(String redirectURL) { + this.redirectURL = redirectURL; } - } - public static class CassandrConfig { - private static final Integer CASSANDRA_DEFAULT_PORT = 9042; + public List<String> getExcludedUrls() { + return excludedUrls; + } + + public void setExcludedUrls(List<String> excludedUrls) { + this.excludedUrls = excludedUrls; + } + + public String getDomain() { + return domain; + } - private List<String> cassandraHosts; - private Integer cassandraPort; - private String localDataCenter; - private Long reconnectTimeout; - private Integer socketReadTimeout; - private Integer socketConnectTimeout; - private List<KeyspaceConfig> keySpaces; - private boolean authenticate; - private String username; - private String password; - private boolean ssl; - private String truststorePath; - private String truststorePassword; + public void setDomain(String domain) { + this.domain = domain; + } - public Integer getCassandraPort() { - return cassandraPort != null ? cassandraPort : Configuration.CassandrConfig.CASSANDRA_DEFAULT_PORT; + public String getPath() { + return path; } - public void setCassandraPort(Integer cassandraPort) { - this.cassandraPort = cassandraPort; + public void setPath(String path) { + this.path = path; } + public boolean isHttpOnly() { + return isHttpOnly; + } + + public void setIsHttpOnly(boolean isHttpOnly) { + this.isHttpOnly = isHttpOnly; + } + + public List<String> getOnboardingExcludedUrls() { + return onboardingExcludedUrls; + } + + public void setOnboardingExcludedUrls(List<String> onboardingExcludedUrls) { + this.onboardingExcludedUrls = onboardingExcludedUrls; + } + } + + public CookieConfig getAuthCookie() { + return authCookie; + } + + public void setAuthCookie(CookieConfig authCookie) { + this.authCookie = authCookie; + } + + public static class CassandrConfig { + private static final Integer CASSANDRA_DEFAULT_PORT = 9042; + List<String> cassandraHosts; + Integer cassandraPort; + String localDataCenter; + Long reconnectTimeout; + Integer socketReadTimeout; + Integer socketConnectTimeout; + List<KeyspaceConfig> keySpaces; + boolean authenticate; + String username; + String password; + boolean ssl; + String truststorePath; + String truststorePassword; + + public Integer getCassandraPort() { return cassandraPort != null ? cassandraPort : Configuration.CassandrConfig.CASSANDRA_DEFAULT_PORT; } + + public void setCassandraPort(Integer cassandraPort) { this.cassandraPort = cassandraPort; } + public String getLocalDataCenter() { return localDataCenter; } @@ -756,21 +810,13 @@ public class Configuration extends BasicConfiguration { this.reconnectTimeout = reconnectTimeout; } - public Integer getSocketReadTimeout() { - return socketReadTimeout; - } + public Integer getSocketReadTimeout() { return socketReadTimeout; } - public void setSocketReadTimeout(Integer socketReadTimeout) { - this.socketReadTimeout = socketReadTimeout; - } + public void setSocketReadTimeout(Integer socketReadTimeout) { this.socketReadTimeout = socketReadTimeout;} - public Integer getSocketConnectTimeout() { - return socketConnectTimeout; - } + public Integer getSocketConnectTimeout() { return socketConnectTimeout;} - public void setSocketConnectTimeout(Integer socketConnectTimeout) { - this.socketConnectTimeout = socketConnectTimeout; - } + public void setSocketConnectTimeout(Integer socketConnectTimeout) { this.socketConnectTimeout = socketConnectTimeout; } public List<String> getCassandraHosts() { return cassandraHosts; @@ -790,9 +836,9 @@ public class Configuration extends BasicConfiguration { public static class KeyspaceConfig { - private String name; - private String replicationStrategy; - private List<String> replicationInfo; + String name; + String replicationStrategy; + List<String> replicationInfo; public String getName() { return name; @@ -822,19 +868,19 @@ public class Configuration extends BasicConfiguration { public static class SwitchoverDetectorConfig { - private String gBeFqdn; - private String gFeFqdn; - private String beVip; - private String feVip; - private int beResolveAttempts; - private int feResolveAttempts; - private Boolean enabled; - private long interval; - private String changePriorityUser; - private String changePriorityPassword; - private String publishNetworkUrl; - private String publishNetworkBody; - private Map<String, GroupInfo> groups; + String gBeFqdn; + String gFeFqdn; + String beVip; + String feVip; + int beResolveAttempts; + int feResolveAttempts; + Boolean enabled; + long interval; + String changePriorityUser; + String changePriorityPassword; + String publishNetworkUrl; + String publishNetworkBody; + Map<String, GroupInfo> groups; public String getgBeFqdn() { return gBeFqdn; @@ -942,8 +988,8 @@ public class Configuration extends BasicConfiguration { public static class GroupInfo { - private String changePriorityUrl; - private String changePriorityBody; + String changePriorityUrl; + String changePriorityBody; public String getChangePriorityUrl() { return changePriorityUrl; @@ -964,11 +1010,46 @@ public class Configuration extends BasicConfiguration { } + public static class HeatDeploymentArtifactTimeout { + Integer defaultMinutes; + Integer minMinutes; + Integer maxMinutes; + + public Integer getDefaultMinutes() { + return defaultMinutes; + } + + public void setDefaultMinutes(Integer defaultMinutes) { + this.defaultMinutes = defaultMinutes; + } + + public Integer getMinMinutes() { + return minMinutes; + } + + public void setMinMinutes(Integer minMinutes) { + this.minMinutes = minMinutes; + } + + public Integer getMaxMinutes() { + return maxMinutes; + } + + public void setMaxMinutes(Integer maxMinutes) { + this.maxMinutes = maxMinutes; + } + + @Override + public String toString() { + return "HeatDeploymentArtifactTimeout config [default=" + defaultMinutes + ", min=" + minMinutes + ", max=" + maxMinutes + "]"; + } + } + public static class BeMonitoringConfig { - private Boolean enabled; - private Boolean isProxy; - private Integer probeIntervalInSeconds; + Boolean enabled; + Boolean isProxy; + Integer probeIntervalInSeconds; public Boolean getEnabled() { return enabled; @@ -1001,8 +1082,8 @@ public class Configuration extends BasicConfiguration { public static class ArtifactTypeConfig { - private List<String> acceptedTypes; - private List<String> validForResourceTypes; + List<String> acceptedTypes; + List<String> validForResourceTypes; public List<String> getValidForResourceTypes() { return validForResourceTypes; @@ -1023,11 +1104,11 @@ public class Configuration extends BasicConfiguration { public static class OnboardingConfig { - private String protocol = "http"; - private String host; - private Integer port; - private String downloadCsarUri; - private String healthCheckUri; + String protocol = "http"; + String host; + Integer port; + String downloadCsarUri; + String healthCheckUri; public String getProtocol() { return protocol; @@ -1087,10 +1168,10 @@ public class Configuration extends BasicConfiguration { public static class DcaeConfig { - private String protocol = "http"; - private String host; - private Integer port; - private String healthCheckUri; + String protocol = "http"; + String host; + Integer port; + String healthCheckUri; public String getProtocol() { return protocol; @@ -1126,9 +1207,55 @@ public class Configuration extends BasicConfiguration { } public static class EcompPortalConfig { - + private String protocol = "https"; + private String host; + private Integer port; + private String healthCheckUri; private String defaultFunctionalMenu; + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + private Integer pollingInterval; + private Integer timeoutMs; + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public String getHealthCheckUri() { + return healthCheckUri; + } + + public void setHealthCheckUri(String healthCheckUri) { + this.healthCheckUri = healthCheckUri; + } + public String getDefaultFunctionalMenu() { return defaultFunctionalMenu; } @@ -1137,6 +1264,14 @@ public class Configuration extends BasicConfiguration { this.defaultFunctionalMenu = defaultFunctionalMenu; } + public Integer getPollingInterval() { + return pollingInterval; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + @Override public String toString() { return "EcompPortalConfig [defaultFunctionalMenu=" + defaultFunctionalMenu + "]"; @@ -1146,7 +1281,7 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheConfig { - private ApplicationL1CacheInfo datatypes; + ApplicationL1CacheInfo datatypes; public ApplicationL1CacheInfo getDatatypes() { return datatypes; @@ -1165,10 +1300,10 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL2CacheConfig { - private boolean enabled; - private ApplicationL1CacheCatalogInfo catalogL1Cache; + boolean enabled; + ApplicationL1CacheCatalogInfo catalogL1Cache; - private QueueInfo queue; + QueueInfo queue; public boolean isEnabled() { return enabled; @@ -1222,9 +1357,9 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheInfo { - private Boolean enabled; - private Integer firstRunDelay; - private Integer pollIntervalInSec; + Boolean enabled; + Integer firstRunDelay; + Integer pollIntervalInSec; public Boolean getEnabled() { return enabled; @@ -1259,10 +1394,10 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheCatalogInfo { - private Boolean enabled; - private Integer resourcesSizeInCache; - private Integer servicesSizeInCache; - private Integer productsSizeInCache; + Boolean enabled; + Integer resourcesSizeInCache; + Integer servicesSizeInCache; + Integer productsSizeInCache; public Boolean getEnabled() { return enabled; @@ -1306,9 +1441,9 @@ public class Configuration extends BasicConfiguration { } public static class QueueInfo { - private Integer numberOfCacheWorkers; - private Integer waitOnShutDownInMinutes; - private Integer syncIntervalInSecondes; + Integer numberOfCacheWorkers; + Integer waitOnShutDownInMinutes; + Integer syncIntervalInSecondes; public Integer getWaitOnShutDownInMinutes() { return waitOnShutDownInMinutes; @@ -1343,8 +1478,8 @@ public class Configuration extends BasicConfiguration { public static class EnvironmentContext { - private String defaultValue; - private List<String> validValues; + String defaultValue; + List<String> validValues; public String getDefaultValue() { return defaultValue; @@ -1380,12 +1515,10 @@ public class Configuration extends BasicConfiguration { .append(format("backend protocol: %s%n", beProtocol)).append(format("Version: %s%n", version)) .append(format("Released: %s%n", released)).append(format("Supported protocols: %s%n", protocols)) .append(format("Users: %s%n", users)).append(format("Neo4j: %s%n", neo4j)) - .append(format("ElasticSearch: %s%n", elasticSearch)) .append(format("JanusGraph Cfg File: %s%n", janusGraphCfgFile)) .append(format("JanusGraph In memory: %s%n", janusGraphInMemoryGraph)) .append(format("JanusGraph lock timeout: %s%n", janusGraphLockTimeout)) - .append(format("JanusGraph reconnect interval seconds: %s%n", - janusGraphReconnectIntervalInSeconds)) + .append(format("JanusGraph reconnect interval seconds: %s%n", janusGraphReconnectIntervalInSeconds)) .append(format("excludeResourceCategory: %s%n", excludeResourceCategory)) .append(format("informationalResourceArtifacts: %s%n", informationalResourceArtifacts)) .append(format("deploymentResourceArtifacts: %s%n", deploymentResourceArtifacts)) @@ -1394,14 +1527,12 @@ public class Configuration extends BasicConfiguration { .append(format("Supported license types: %s%n", licenseTypes)) .append(format("Additional information Maximum number of preoperties: %s%n", additionalInformationMaxNumberOfKeys)) - .append(format("Default Heat Artifact Timeout in Minutes: %s%n", defaultHeatArtifactTimeoutMinutes)) + .append(format("Heat Artifact Timeout in Minutes: %s%n", heatArtifactDeploymentTimeout)) .append(format("URLs For HTTP Requests that will not be automatically logged : %s%n", unLoggedUrls)) .append(format("Service Api Artifacts: %s%n", serviceApiArtifacts)) .append(format("heat env artifact header: %s%n", heatEnvArtifactHeader)) .append(format("heat env artifact footer: %s%n", heatEnvArtifactFooter)) - .append(format("onboarding: %s%n", onboarding)) - .append(format("tosca conformance level: %s%n", toscaConformanceLevel)) - .toString(); + .append(format("onboarding: %s%n", onboarding)).toString(); } public List<String> getUnLoggedUrls() { @@ -1485,22 +1616,6 @@ public class Configuration extends BasicConfiguration { this.heatTranslatorPath = heatTranslatorPath; } - public Map<String, Set<String>> getRequirementsToFulfillBeforeCert() { - return requirementsToFulfillBeforeCert; - } - - public void setRequirementsToFulfillBeforeCert(Map<String, Set<String>> requirementsToFulfillBeforeCert) { - this.requirementsToFulfillBeforeCert = requirementsToFulfillBeforeCert; - } - - public Map<String, Set<String>> getCapabilitiesToConsumeBeforeCert() { - return capabilitiesToConsumeBeforeCert; - } - - public void setCapabilitiesToConsumeBeforeCert(Map<String, Set<String>> capabilitiesToConsumeBeforeCert) { - this.capabilitiesToConsumeBeforeCert = capabilitiesToConsumeBeforeCert; - } - public OnboardingConfig getOnboarding() { return onboarding; } @@ -1529,6 +1644,14 @@ public class Configuration extends BasicConfiguration { return disableAudit; } + public Boolean getConsumerBusinessLogic() { + return consumerBusinessLogic; + } + + public void setConsumerBusinessLogic(Boolean consumerBusinessLogic) { + this.consumerBusinessLogic = consumerBusinessLogic; + } + public void setDisableAudit(boolean enableAudit) { this.disableAudit = enableAudit; } @@ -1568,19 +1691,15 @@ public class Configuration extends BasicConfiguration { public static class VfModuleProperty { private String forBaseModule; private String forNonBaseModule; - public String getForBaseModule() { return forBaseModule; } - public void setForBaseModule(String forBaseModule) { this.forBaseModule = forBaseModule; } - public String getForNonBaseModule() { return forNonBaseModule; } - public void setForNonBaseModule(String forNonBaseModule) { this.forNonBaseModule = forNonBaseModule; } @@ -1603,7 +1722,7 @@ public class Configuration extends BasicConfiguration { } @SuppressWarnings("unchecked") - public static <K, V> Map<K, V> safeGetCapsInsensitiveMap(Map<K, V> map) { + public static <K,V> Map<K,V> safeGetCapsInsensitiveMap(Map<K,V> map) { return map == null ? emptyMap() : new CaseInsensitiveMap(map); } @@ -1616,6 +1735,38 @@ public class Configuration extends BasicConfiguration { this.healthStatusExclude = healthStatusExclude; } + public DmaapProducerConfiguration getDmaapProducerConfiguration() { + return dmaapProducerConfiguration; + } + + public void setDmaapProducerConfiguration(DmaapProducerConfiguration dmaapProducerConfiguration) { + this.dmaapProducerConfiguration = dmaapProducerConfiguration; + } + + public String getAafNamespace() { + return aafNamespace; + } + + public void setAafNamespace(String aafNamespace) { + this.aafNamespace = aafNamespace; + } + + public Boolean getAafAuthNeeded(){ + return aafAuthNeeded; + } + + public void setAafAuthNeeded(Boolean aafAuthNeeded){ + this.aafAuthNeeded = aafAuthNeeded; + } + + public CadiFilterParams getCadiFilterParams() { + return cadiFilterParams; + } + + public void setCadiFilterParams(CadiFilterParams cadiFilterParams) { + this.cadiFilterParams = cadiFilterParams; + } + public static class PathsAndNamesDefinition { private String friendlyName; @@ -1667,4 +1818,5 @@ public class Configuration extends BasicConfiguration { this.pathsAndNamesDefinitions = pathsAndNamesDefinitions; } } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java index 9920b597a1..0e9fd24111 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,121 +33,113 @@ import java.util.Map; public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { + + ConfigurationSource configurationSource = null; + private static ConfigurationManager instance; + @VisibleForTesting public ConfigurationManager() { super(); instance = this; } - private ConfigurationSource configurationSource = null; - private static ConfigurationManager instance; - - public Map<String, Object> getConfigurations() { - return configurations; - } - - public void setConfigurations(Map<String, Object> configurations) { - this.configurations = configurations; - } - - private Map<String, Object> configurations = new HashMap<>(); - - public ConfigurationManager(ConfigurationSource configurationSource) { - super(); - this.configurationSource = configurationSource; - loadConfigurationFiles(); - instance = this; - } + Map<String, Object> configurations = new HashMap<>(); + public ConfigurationManager(ConfigurationSource configurationSource) { + super(); + this.configurationSource = configurationSource; + loadConfigurationFiles(); + instance = this; + } - private void loadConfigurationFiles() { + private void loadConfigurationFiles() { - loadConfigurationClass(Configuration.class); - loadConfigurationClass(ErrorConfiguration.class); - loadConfigurationClass(Neo4jErrorsConfiguration.class); - loadConfigurationClass(EcompErrorConfiguration.class); - loadConfigurationClass(DistributionEngineConfiguration.class); - } + loadConfigurationClass(Configuration.class); + loadConfigurationClass(ErrorConfiguration.class); + loadConfigurationClass(Neo4jErrorsConfiguration.class); + loadConfigurationClass(EcompErrorConfiguration.class); + loadConfigurationClass(DistributionEngineConfiguration.class); + } - private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { - ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); + private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { + ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); - T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); + T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); - configurations.put(getKey(clazz), object); - } + configurations.put(getKey(clazz), object); + } - private <T> String getKey(Class<T> class1) { + private <T> String getKey(Class<T> class1) { - return class1.getSimpleName(); + return class1.getSimpleName(); - } + } - public Configuration getConfiguration() { + public Configuration getConfiguration() { - return (Configuration) configurations.get(getKey(Configuration.class)); + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public void setConfiguration(Configuration configuration) { + public void setConfiguration(Configuration configuration) { - configurations.put(getKey(Configuration.class), configuration); + configurations.put(getKey(Configuration.class), configuration); - } + } - public void setErrorConfiguration(ErrorConfiguration configuration) { + public void setErrorConfiguration(ErrorConfiguration configuration) { - configurations.put(getKey(ErrorConfiguration.class), configuration); + configurations.put(getKey(ErrorConfiguration.class), configuration); - } + } - public ErrorConfiguration getErrorConfiguration() { + public ErrorConfiguration getErrorConfiguration() { - return (ErrorConfiguration) configurations.get(getKey(ErrorConfiguration.class)); + return (ErrorConfiguration) configurations.get(getKey(ErrorConfiguration.class)); - } + } - public Neo4jErrorsConfiguration getNeo4jErrorsConfiguration() { - return (Neo4jErrorsConfiguration) configurations.get(getKey(Neo4jErrorsConfiguration.class)); - } + public Neo4jErrorsConfiguration getNeo4jErrorsConfiguration() { + return (Neo4jErrorsConfiguration) configurations.get(getKey(Neo4jErrorsConfiguration.class)); + } - @Override - public EcompErrorConfiguration getEcompErrorConfiguration() { + @Override + public EcompErrorConfiguration getEcompErrorConfiguration() { - return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); - } + } - public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { + public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { - if (configurationListener != null) { + if (configurationListener != null) { - configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + configurationSource.addWatchConfiguration(Configuration.class, configurationListener); - } - return (Configuration) configurations.get(getKey(Configuration.class)); + } + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public static ConfigurationManager getConfigurationManager() { - return instance; - } + public static ConfigurationManager getConfigurationManager() { + return instance; + } public void reconfigure(BasicConfiguration obj) { } - /** - * FOR TEST ONLY - * - * @param ecompErrorConfiguration - */ - public void setEcompErrorConfiguration(EcompErrorConfiguration ecompErrorConfiguration) { + /** + * FOR TEST ONLY + * + * @param ecompErrorConfiguration + */ + public void setEcompErrorConfiguration(EcompErrorConfiguration ecompErrorConfiguration) { - configurations.put(getKey(EcompErrorConfiguration.class), ecompErrorConfiguration); + configurations.put(getKey(EcompErrorConfiguration.class), ecompErrorConfiguration); - } + } - public DistributionEngineConfiguration getDistributionEngineConfiguration() { + public DistributionEngineConfiguration getDistributionEngineConfiguration() { - return (DistributionEngineConfiguration) configurations.get(getKey(DistributionEngineConfiguration.class)); + return (DistributionEngineConfiguration) configurations.get(getKey(DistributionEngineConfiguration.class)); - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java index b7b0e64189..b23e076334 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,461 +23,449 @@ package org.openecomp.sdc.be.config; import org.openecomp.sdc.common.api.BasicConfiguration; import org.openecomp.sdc.common.http.config.ExternalServiceConfig; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; public class DistributionEngineConfiguration extends BasicConfiguration { - private List<String> uebServers; + private List<String> uebServers; - private String distributionNotifTopicName; + private String distributionNotifTopicName; - private String distributionStatusTopicName; + private String distributionStatusTopicName; - private Integer initRetryIntervalSec; + private Integer initRetryIntervalSec; - private Integer initMaxIntervalSec; + private Integer initMaxIntervalSec; - private ComponentArtifactTypesConfig distribNotifServiceArtifactTypes; + private ComponentArtifactTypesConfig distribNotifServiceArtifactTypes; - private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; + private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; - private String uebPublicKey; + private String uebPublicKey; - private String uebSecretKey; + private String uebSecretKey; - private List<String> environments; + private List<String> environments; - private DistributionStatusTopicConfig distributionStatusTopic; + private DistributionStatusTopicConfig distributionStatusTopic; - private CreateTopicConfig createTopic; + private CreateTopicConfig createTopic; - private boolean startDistributionEngine; + private boolean startDistributionEngine; - private DistributionNotificationTopicConfig distributionNotificationTopic; + private DistributionNotificationTopicConfig distributionNotificationTopic; - private Integer defaultArtifactInstallationTimeout = 60; + private Integer defaultArtifactInstallationTimeout = 60; + + private Integer currentArtifactInstallationTimeout = 120; + private boolean useHttpsWithDmaap; - private Integer currentArtifactInstallationTimeout = 120; + private ExternalServiceConfig aaiConfig; - private boolean useHttpsWithDmaap; + private ExternalServiceConfig msoConfig; + + private Integer opEnvRecoveryIntervalSec; + + private Integer allowedTimeBeforeStaleSec; + + public static class DistribNotifServiceArtifacts { - private ExternalServiceConfig aaiConfig; + Map<String, Object> service; + Map<String, Object> resource; + + - private ExternalServiceConfig msoConfig; + public Map<String, Object> getService() { + return service; + } - private Integer opEnvRecoveryIntervalSec; + public void setService(Map<String, Object> service) { + this.service = service; + } - private Integer allowedTimeBeforeStaleSec; + public Map<String, Object> getResource() { + return resource; + } - public static class DistribNotifServiceArtifacts { + public void setResource(Map<String, Object> resource) { + this.resource = resource; + } - private Map<String, Object> service; - private Map<String, Object> resource; + } + public static class NotifArtifactTypes { - public Map<String, Object> getService() { - return service; - } + List<String> info; + List<String> lifecycle; - public void setService(Map<String, Object> service) { - this.service = service; - } + public List<String> getInfo() { + return info; + } - public Map<String, Object> getResource() { - return resource; - } + public void setInfo(List<String> info) { + this.info = info; + } - public void setResource(Map<String, Object> resource) { - this.resource = resource; - } + public List<String> getLifecycle() { + return lifecycle; + } - } - - public static class NotifArtifactTypes { - - private List<String> info; - private List<String> lifecycle; - - public List<String> getInfo() { - return info; - } - - public void setInfo(List<String> info) { - this.info = info; - } - - public List<String> getLifecycle() { - return lifecycle; - } - - public void setLifecycle(List<String> lifecycle) { - this.lifecycle = lifecycle; - } + public void setLifecycle(List<String> lifecycle) { + this.lifecycle = lifecycle; + } - } - - public static class NotifArtifactTypesResource { + } - private List<ArtifcatTypeEnum> lifecycle; + public static class NotifArtifactTypesResource { - public List<ArtifcatTypeEnum> getLifecycle() { - return lifecycle; - } - - public void setLifecycle(List<ArtifcatTypeEnum> lifecycle) { - this.lifecycle = lifecycle; - } - } + List<ArtifcatTypeEnum> lifecycle; - public enum ArtifcatTypeEnum { + } - MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); + public enum ArtifcatTypeEnum { - private String value; + MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); - ArtifcatTypeEnum(String value) { - this.value = value; - } + String value; - public String getValue() { + private ArtifcatTypeEnum(String value) { + this.value = value; + } - return value; - } - } - - public List<String> getUebServers() { - return uebServers; - } + public String getValue() { - public void setUebServers(List<String> uebServers) { - this.uebServers = uebServers; - } + return value; + } + } - public String getDistributionNotifTopicName() { - return distributionNotifTopicName; - } + public List<String> getUebServers() { + return uebServers; + } - public void setDistributionNotifTopicName(String distributionNotifTopicName) { - this.distributionNotifTopicName = distributionNotifTopicName; - } + public void setUebServers(List<String> uebServers) { + this.uebServers = uebServers; + } - public String getDistributionStatusTopicName() { - return distributionStatusTopicName; - } + public String getDistributionNotifTopicName() { + return distributionNotifTopicName; + } - public void setDistributionStatusTopicName(String distributionStatusTopicName) { - this.distributionStatusTopicName = distributionStatusTopicName; - } + public void setDistributionNotifTopicName(String distributionNotifTopicName) { + this.distributionNotifTopicName = distributionNotifTopicName; + } - public Integer getInitRetryIntervalSec() { - return initRetryIntervalSec; - } + public String getDistributionStatusTopicName() { + return distributionStatusTopicName; + } - public void setInitRetryIntervalSec(Integer initRetryIntervalSec) { - this.initRetryIntervalSec = initRetryIntervalSec; - } + public void setDistributionStatusTopicName(String distributionStatusTopicName) { + this.distributionStatusTopicName = distributionStatusTopicName; + } - public ComponentArtifactTypesConfig getDistribNotifServiceArtifactTypes() { - return distribNotifServiceArtifactTypes; - } + public Integer getInitRetryIntervalSec() { + return initRetryIntervalSec; + } - public void setDistribNotifServiceArtifactTypes(ComponentArtifactTypesConfig distribNotifServiceArtifactTypes) { - this.distribNotifServiceArtifactTypes = distribNotifServiceArtifactTypes; - } + public void setInitRetryIntervalSec(Integer initRetryIntervalSec) { + this.initRetryIntervalSec = initRetryIntervalSec; + } - public ComponentArtifactTypesConfig getDistribNotifResourceArtifactTypes() { - return distribNotifResourceArtifactTypes; - } + public ComponentArtifactTypesConfig getDistribNotifServiceArtifactTypes() { + return distribNotifServiceArtifactTypes; + } - public void setDistribNotifResourceArtifactTypes(ComponentArtifactTypesConfig distribNotifResourceArtifactTypes) { - this.distribNotifResourceArtifactTypes = distribNotifResourceArtifactTypes; - } + public void setDistribNotifServiceArtifactTypes(ComponentArtifactTypesConfig distribNotifServiceArtifactTypes) { + this.distribNotifServiceArtifactTypes = distribNotifServiceArtifactTypes; + } - public String getUebPublicKey() { - return uebPublicKey; - } + public ComponentArtifactTypesConfig getDistribNotifResourceArtifactTypes() { + return distribNotifResourceArtifactTypes; + } - public void setUebPublicKey(String uebPublicKey) { - this.uebPublicKey = uebPublicKey; - } + public void setDistribNotifResourceArtifactTypes(ComponentArtifactTypesConfig distribNotifResourceArtifactTypes) { + this.distribNotifResourceArtifactTypes = distribNotifResourceArtifactTypes; + } - public String getUebSecretKey() { - return uebSecretKey; - } + public String getUebPublicKey() { + return uebPublicKey; + } - public void setUebSecretKey(String uebSecretKey) { - this.uebSecretKey = uebSecretKey; - } + public void setUebPublicKey(String uebPublicKey) { + this.uebPublicKey = uebPublicKey; + } - public List<String> getEnvironments() { - return environments; - } + public String getUebSecretKey() { + return uebSecretKey; + } - public void setEnvironments(List<String> environments) { + public void setUebSecretKey(String uebSecretKey) { + this.uebSecretKey = uebSecretKey; + } - Set<String> set = new HashSet<>(); - if (environments != null) { - set.addAll(environments); - this.environments = new ArrayList<>(set); - } else { - this.environments = null; - } + public List<String> getEnvironments() { + return environments; + } - } + public void setEnvironments(List<String> environments) { - public DistributionStatusTopicConfig getDistributionStatusTopic() { - return distributionStatusTopic; - } + Set<String> set = new HashSet<>(); + if (environments != null) { + set.addAll(environments); + this.environments = new ArrayList<>(set); + } else { + this.environments = null; + } - public void setDistributionStatusTopic(DistributionStatusTopicConfig distributionStatusTopic) { - this.distributionStatusTopic = distributionStatusTopic; - } + } - public Integer getInitMaxIntervalSec() { - return initMaxIntervalSec; - } + public DistributionStatusTopicConfig getDistributionStatusTopic() { + return distributionStatusTopic; + } - public void setInitMaxIntervalSec(Integer initMaxIntervalSec) { - this.initMaxIntervalSec = initMaxIntervalSec; - } + public void setDistributionStatusTopic(DistributionStatusTopicConfig distributionStatusTopic) { + this.distributionStatusTopic = distributionStatusTopic; + } - public CreateTopicConfig getCreateTopic() { - return createTopic; - } + public Integer getInitMaxIntervalSec() { + return initMaxIntervalSec; + } - public void setCreateTopic(CreateTopicConfig createTopic) { - this.createTopic = createTopic; - } + public void setInitMaxIntervalSec(Integer initMaxIntervalSec) { + this.initMaxIntervalSec = initMaxIntervalSec; + } - public boolean isStartDistributionEngine() { - return startDistributionEngine; - } + public CreateTopicConfig getCreateTopic() { + return createTopic; + } - public void setStartDistributionEngine(boolean startDistributionEngine) { - this.startDistributionEngine = startDistributionEngine; - } + public void setCreateTopic(CreateTopicConfig createTopic) { + this.createTopic = createTopic; + } - public DistributionNotificationTopicConfig getDistributionNotificationTopic() { - return distributionNotificationTopic; - } + public boolean isStartDistributionEngine() { + return startDistributionEngine; + } - public void setDistributionNotificationTopic(DistributionNotificationTopicConfig distributionNotificationTopic) { - this.distributionNotificationTopic = distributionNotificationTopic; - } + public void setStartDistributionEngine(boolean startDistributionEngine) { + this.startDistributionEngine = startDistributionEngine; + } - public int getDefaultArtifactInstallationTimeout() { - return defaultArtifactInstallationTimeout; - } - public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) { - this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout; - } - public int getCurrentArtifactInstallationTimeout() { - return currentArtifactInstallationTimeout; - } + public DistributionNotificationTopicConfig getDistributionNotificationTopic() { + return distributionNotificationTopic; + } - public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) { - this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout; - } + public void setDistributionNotificationTopic(DistributionNotificationTopicConfig distributionNotificationTopic) { + this.distributionNotificationTopic = distributionNotificationTopic; + } - public boolean isUseHttpsWithDmaap() { - return useHttpsWithDmaap; - } + public int getDefaultArtifactInstallationTimeout() { + return defaultArtifactInstallationTimeout; + } + public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) { + this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout; + } + + public int getCurrentArtifactInstallationTimeout() { + return currentArtifactInstallationTimeout; + } + public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) { + this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout; + } + public boolean isUseHttpsWithDmaap() { + return useHttpsWithDmaap; + } - public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { - this.useHttpsWithDmaap = useHttpsWithDmaap; - } + public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { + this.useHttpsWithDmaap = useHttpsWithDmaap; + } - public static class CreateTopicConfig { + public static class CreateTopicConfig { - private Integer partitionCount; - private Integer replicationCount; + private Integer partitionCount; + private Integer replicationCount; - public Integer getPartitionCount() { - return partitionCount; - } + public Integer getPartitionCount() { + return partitionCount; + } - public void setPartitionCount(Integer partitionCount) { - this.partitionCount = partitionCount; - } + public void setPartitionCount(Integer partitionCount) { + this.partitionCount = partitionCount; + } - public Integer getReplicationCount() { - return replicationCount; - } + public Integer getReplicationCount() { + return replicationCount; + } - public void setReplicationCount(Integer replicationCount) { - this.replicationCount = replicationCount; - } + public void setReplicationCount(Integer replicationCount) { + this.replicationCount = replicationCount; + } - @Override - public String toString() { - return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount - + "]"; - } + @Override + public String toString() { + return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount + + "]"; + } - } + } - public static class EnvironmentConfig { + public static class EnvironmentConfig { - private String name; - private List<String> uebServers; + private String name; + private List<String> uebServers; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List<String> getUebServers() { - return uebServers; - } + public List<String> getUebServers() { + return uebServers; + } - public void setUebServers(List<String> uebServers) { - this.uebServers = uebServers; - } + public void setUebServers(List<String> uebServers) { + this.uebServers = uebServers; + } - @Override - public String toString() { - return "EnvironmentConfig [name=" + name + ", uebServers=" + uebServers + "]"; - } + @Override + public String toString() { + return "EnvironmentConfig [name=" + name + ", uebServers=" + uebServers + "]"; + } - } + } - public static class DistributionStatusTopicConfig { + public static class DistributionStatusTopicConfig { - private Integer pollingIntervalSec; - private Integer fetchTimeSec; - private String consumerGroup; - private String consumerId; + private Integer pollingIntervalSec; + private Integer fetchTimeSec; + private String consumerGroup; + private String consumerId; - public Integer getPollingIntervalSec() { - return pollingIntervalSec; - } + public Integer getPollingIntervalSec() { + return pollingIntervalSec; + } - public void setPollingIntervalSec(Integer pollingIntervalSec) { - this.pollingIntervalSec = pollingIntervalSec; - } + public void setPollingIntervalSec(Integer pollingIntervalSec) { + this.pollingIntervalSec = pollingIntervalSec; + } - public Integer getFetchTimeSec() { - return fetchTimeSec; - } + public Integer getFetchTimeSec() { + return fetchTimeSec; + } - public void setFetchTimeSec(Integer fetchTimeSec) { - this.fetchTimeSec = fetchTimeSec; - } + public void setFetchTimeSec(Integer fetchTimeSec) { + this.fetchTimeSec = fetchTimeSec; + } - public String getConsumerGroup() { - return consumerGroup; - } + public String getConsumerGroup() { + return consumerGroup; + } - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } - public String getConsumerId() { - return consumerId; - } + public String getConsumerId() { + return consumerId; + } - public void setConsumerId(String consumerId) { - this.consumerId = consumerId; - } + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } - @Override - public String toString() { - return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" - + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]"; - } + @Override + public String toString() { + return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" + + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]"; + } - } + } - public static class DistributionNotificationTopicConfig { + public static class DistributionNotificationTopicConfig { - private Integer maxWaitingAfterSendingSeconds; - private Integer maxThreadPoolSize; - private Integer minThreadPoolSize; + private Integer maxWaitingAfterSendingSeconds; + private Integer maxThreadPoolSize; + private Integer minThreadPoolSize; - public Integer getMaxWaitingAfterSendingSeconds() { - return maxWaitingAfterSendingSeconds; - } + public Integer getMaxWaitingAfterSendingSeconds() { + return maxWaitingAfterSendingSeconds; + } - public void setMaxWaitingAfterSendingSeconds(Integer maxWaitingAfterSendingSeconds) { - this.maxWaitingAfterSendingSeconds = maxWaitingAfterSendingSeconds; - } + public void setMaxWaitingAfterSendingSeconds(Integer maxWaitingAfterSendingSeconds) { + this.maxWaitingAfterSendingSeconds = maxWaitingAfterSendingSeconds; + } - public Integer getMaxThreadPoolSize() { - return maxThreadPoolSize; - } + public Integer getMaxThreadPoolSize() { + return maxThreadPoolSize; + } - public void setMaxThreadPoolSize(Integer maxThreadPoolSize) { - this.maxThreadPoolSize = maxThreadPoolSize; - } + public void setMaxThreadPoolSize(Integer maxThreadPoolSize) { + this.maxThreadPoolSize = maxThreadPoolSize; + } - public Integer getMinThreadPoolSize() { - return minThreadPoolSize; - } + public Integer getMinThreadPoolSize() { + return minThreadPoolSize; + } - public void setMinThreadPoolSize(Integer minThreadPoolSize) { - this.minThreadPoolSize = minThreadPoolSize; - } + public void setMinThreadPoolSize(Integer minThreadPoolSize) { + this.minThreadPoolSize = minThreadPoolSize; + } - @Override - public String toString() { - return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds - + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]"; - } + @Override + public String toString() { + return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds + + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]"; + } - } + } - public static class ComponentArtifactTypesConfig { + public static class ComponentArtifactTypesConfig { - private List<String> info; - private List<String> lifecycle; + private List<String> info; + private List<String> lifecycle; - public List<String> getInfo() { - return info; - } + public List<String> getInfo() { + return info; + } - public void setInfo(List<String> info) { - this.info = info; - } + public void setInfo(List<String> info) { + this.info = info; + } - public List<String> getLifecycle() { - return lifecycle; - } + public List<String> getLifecycle() { + return lifecycle; + } - public void setLifecycle(List<String> lifecycle) { - this.lifecycle = lifecycle; - } + public void setLifecycle(List<String> lifecycle) { + this.lifecycle = lifecycle; + } - @Override - public String toString() { - return "ArtifactTypesConfig [info=" + info + ", lifecycle=" + lifecycle + "]"; - } + @Override + public String toString() { + return "ArtifactTypesConfig [info=" + info + ", lifecycle=" + lifecycle + "]"; + } - } + } - public Integer getOpEnvRecoveryIntervalSec() { - return opEnvRecoveryIntervalSec; - } + public Integer getOpEnvRecoveryIntervalSec() { + return opEnvRecoveryIntervalSec; + } - public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { - this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; - } + public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { + this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; + } - public Integer getAllowedTimeBeforeStaleSec() { - return allowedTimeBeforeStaleSec; - } + public Integer getAllowedTimeBeforeStaleSec() { + return allowedTimeBeforeStaleSec; + } - public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { - this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; - } + public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { + this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; + } public ExternalServiceConfig getAaiConfig() { return aaiConfig; diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java index c99cbbaae3..926d21f395 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,284 +19,323 @@ */ package org.openecomp.sdc.be.config; - /** * Contains DMAAP Client configuration parameters */ public class DmaapConsumerConfiguration { - private boolean active; - private String hosts; - private String consumerGroup; - private String consumerId; - private Integer timeoutMs; - private Integer limit; - private Integer pollingInterval; - private String topic; - private Double latitude; - private Double longitude; - private String version; - private String serviceName; - private String environment; - private String partner; - private String routeOffer; - private String protocol; - private String contenttype; - private Boolean dme2TraceOn; - private String aftEnvironment; - private Integer aftDme2ConnectionTimeoutMs; - private Integer aftDme2RoundtripTimeoutMs; - private Integer aftDme2ReadTimeoutMs; - private String dme2preferredRouterFilePath; - private Credential credential; - private Integer timeLimitForNotificationHandleMs; - - public String getHosts() { - return hosts; - } - - public void setHosts(String hosts) { - this.hosts = hosts; - } - - public String getConsumerGroup() { - return consumerGroup; - } - - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } - - public String getConsumerId() { - return consumerId; - } - - public void setConsumerId(String consumerId) { - this.consumerId = consumerId; - } - - public Integer getTimeoutMs() { - return timeoutMs; - } - - public void setTimeoutMs(Integer timeoutMs) { - this.timeoutMs = timeoutMs; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - public Integer getPollingInterval() { - return pollingInterval; - } - - public void setPollingInterval(Integer pollingInterval) { - this.pollingInterval = pollingInterval; - } - - public String getTopic() { - return topic; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public Double getLatitude() { - return latitude; - } - - public void setLatitude(Double latitude) { - this.latitude = latitude; - } - - public Double getLongitude() { - return longitude; - } - - public void setLongitude(Double longitude) { - this.longitude = longitude; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } + private boolean active; + private String hosts; + private String consumerGroup; + private String consumerId; + private Integer timeoutMs; + private Integer limit; + private Integer pollingInterval; + private String topic; + private Double latitude; + private Double longitude; + private String version; + private String serviceName; + private String environment; + private String partner; + private String routeOffer; + private String protocol; + private String contenttype; + private Boolean dme2TraceOn; + private String aftEnvironment; + private Integer aftDme2ConnectionTimeoutMs; + private Integer aftDme2RoundtripTimeoutMs; + private Integer aftDme2ReadTimeoutMs; + private String dme2preferredRouterFilePath; + private Credential credential; + private Integer timeLimitForNotificationHandleMs; + private boolean aftDme2SslEnable; + private boolean aftDme2ClientIgnoreSslConfig; + private String aftDme2ClientKeystore; + private String aftDme2ClientKeystorePassword; + private String aftDme2ClientSslCertAlias; + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Integer getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getPartner() { + return partner; + } + + public void setPartner(String partner) { + this.partner = partner; + } + + public String getRouteOffer() { + return routeOffer; + } + + public void setRouteOffer(String routeOffer) { + this.routeOffer = routeOffer; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getContenttype() { + return contenttype; + } + + public void setContenttype(String contenttype) { + this.contenttype = contenttype; + } + + public Boolean isDme2TraceOn() { + return dme2TraceOn; + } + + public Boolean getDme2TraceOn() { + return dme2TraceOn; + } + + public void setDme2TraceOn(Boolean dme2TraceOn) { + this.dme2TraceOn = dme2TraceOn; + } + + public String getAftEnvironment() { + return aftEnvironment; + } + + public void setAftEnvironment(String aftEnvironment) { + this.aftEnvironment = aftEnvironment; + } - public String getEnvironment() { - return environment; - } + public Integer getAftDme2ConnectionTimeoutMs() { + return aftDme2ConnectionTimeoutMs; + } - public void setEnvironment(String environment) { - this.environment = environment; - } + public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { + this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + } - public String getPartner() { - return partner; - } + public Integer getAftDme2RoundtripTimeoutMs() { + return aftDme2RoundtripTimeoutMs; + } - public void setPartner(String partner) { - this.partner = partner; - } + public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { + this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + } - public String getRouteOffer() { - return routeOffer; - } + public Integer getAftDme2ReadTimeoutMs() { + return aftDme2ReadTimeoutMs; + } - public void setRouteOffer(String routeOffer) { - this.routeOffer = routeOffer; - } + public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { + this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + } - public String getProtocol() { - return protocol; - } + public String getDme2preferredRouterFilePath() { + return dme2preferredRouterFilePath; + } - public void setProtocol(String protocol) { - this.protocol = protocol; - } + public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { + this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; + } - public String getContenttype() { - return contenttype; - } + public Credential getCredential() { + return credential; + } - public void setContenttype(String contenttype) { - this.contenttype = contenttype; - } + public void setCredential(Credential credential) { + this.credential = credential; + } - public Boolean isDme2TraceOn() { - return dme2TraceOn; - } + public boolean isActive() { return active; } - public Boolean getDme2TraceOn() { - return dme2TraceOn; - } + public void setActive(boolean isActive) { this.active = isActive; } - public void setDme2TraceOn(Boolean dme2TraceOn) { - this.dme2TraceOn = dme2TraceOn; - } + /** + * Contains Dmaap Client credential parameters: username and password + */ + public static class Credential{ + + private String username; + private String password; + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + + } - public String getAftEnvironment() { - return aftEnvironment; - } + public Integer getTimeLimitForNotificationHandleMs() { + return timeLimitForNotificationHandleMs; + } - public void setAftEnvironment(String aftEnvironment) { - this.aftEnvironment = aftEnvironment; - } + public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { + this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + } - public Integer getAftDme2ConnectionTimeoutMs() { - return aftDme2ConnectionTimeoutMs; + public boolean isAftDme2SslEnable() { + return aftDme2SslEnable; } - public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { - this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + public void setAftDme2SslEnable(boolean aftDme2SslEnable) { + this.aftDme2SslEnable = aftDme2SslEnable; } - public Integer getAftDme2RoundtripTimeoutMs() { - return aftDme2RoundtripTimeoutMs; + public boolean isAftDme2ClientIgnoreSslConfig() { + return aftDme2ClientIgnoreSslConfig; } - public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { - this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + public void setAftDme2ClientIgnoreSslConfig(boolean aftDme2ClientIgnoreSslConfig) { + this.aftDme2ClientIgnoreSslConfig = aftDme2ClientIgnoreSslConfig; } - public Integer getAftDme2ReadTimeoutMs() { - return aftDme2ReadTimeoutMs; + public String getAftDme2ClientKeystore() { + return aftDme2ClientKeystore; } - public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { - this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + public void setAftDme2ClientKeystore(String aftDme2ClientKeystore) { + this.aftDme2ClientKeystore = aftDme2ClientKeystore; } - public String getDme2preferredRouterFilePath() { - return dme2preferredRouterFilePath; - } - - public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { - this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; - } - - public Credential getCredential() { - return credential; - } - - public void setCredential(Credential credential) { - this.credential = credential; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean isActive) { - this.active = isActive; - } - - /** - * Contains Dmaap Client credential parameters: username and password - */ - public static class Credential { - - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public String toString() { - return "Credential [username=" + username + ", password=" + password + "]"; - } - + public String getAftDme2ClientKeystorePassword() { + return aftDme2ClientKeystorePassword; } - @Override - public String toString() { - return "DmaapConsumerConfiguration [active=" + active + ", hosts=" + hosts + ", consumerGroup=" + consumerGroup + ", consumerId=" - + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + pollingInterval - + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + ", version=" + version - + ", serviceName=" + serviceName + ", environment=" + environment + ", partner=" + partner - + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + contenttype - + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment - + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" - + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs - + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath - + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs + ", credential=" + credential + "]"; + public void setAftDme2ClientKeystorePassword(String aftDme2ClientKeystorePassword) { + this.aftDme2ClientKeystorePassword = aftDme2ClientKeystorePassword; } - public Integer getTimeLimitForNotificationHandleMs() { - return timeLimitForNotificationHandleMs; + public String getAftDme2ClientSslCertAlias() { + return aftDme2ClientSslCertAlias; } - public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { - this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + public void setAftDme2ClientSslCertAlias(String aftDme2ClientSslCertAlias) { + this.aftDme2ClientSslCertAlias = aftDme2ClientSslCertAlias; } + @Override + public String toString() { + return "DmaapConsumerConfiguration [active=" + active + ", hosts=" + hosts + ", consumerGroup=" + consumerGroup + + ", consumerId=" + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + + pollingInterval + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + + ", version=" + version + ", serviceName=" + serviceName + ", environment=" + environment + + ", partner=" + partner + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + + contenttype + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment + + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" + + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs + + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath + ", credential=" + credential + + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs + ", aftDme2SslEnable=" + + aftDme2SslEnable + ", aftDme2ClientIgnoreSslConfig=" + aftDme2ClientIgnoreSslConfig + + ", aftDme2ClientKeystore=" + aftDme2ClientKeystore + ", aftDme2ClientKeystorePassword=" + + aftDme2ClientKeystorePassword + ", aftDme2ClientSslCertAlias=" + aftDme2ClientSslCertAlias + "]"; + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapProducerConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapProducerConfiguration.java new file mode 100644 index 0000000000..52d1def11f --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapProducerConfiguration.java @@ -0,0 +1,325 @@ +package org.openecomp.sdc.be.config; +/** + * Contains DMAAP Client configuration parameters + */ +public class DmaapProducerConfiguration { + + private Boolean active; + private String hosts; + private String consumerGroup; + private String consumerId; + private Integer timeoutMs; + private Integer limit; + private Integer pollingInterval; + private String topic; + private Double latitude; + private Double longitude; + private String version; + private String serviceName; + private String environment; + private String partner; + private String routeOffer; + private String protocol; + private String contenttype; + private Boolean dme2TraceOn; + private String aftEnvironment; + private Integer aftDme2ConnectionTimeoutMs; + private Integer aftDme2RoundtripTimeoutMs; + private Integer aftDme2ReadTimeoutMs; + private String dme2preferredRouterFilePath; + private Credential credential; + private Integer timeLimitForNotificationHandleMs; + private boolean aftDme2SslEnable; + private boolean aftDme2ClientIgnoreSslConfig; + private String aftDme2ClientKeystore; + private String aftDme2ClientKeystorePassword; + private String aftDme2ClientSslCertAlias; + + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public String getConsumerGroup() { + return consumerGroup; + } + + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public Integer getTimeoutMs() { + return timeoutMs; + } + + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Integer getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getEnvironment() { + return environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getPartner() { + return partner; + } + + public void setPartner(String partner) { + this.partner = partner; + } + + public String getRouteOffer() { + return routeOffer; + } + + public void setRouteOffer(String routeOffer) { + this.routeOffer = routeOffer; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getContenttype() { + return contenttype; + } + + public void setContenttype(String contenttype) { + this.contenttype = contenttype; + } + + public Boolean isDme2TraceOn() { + return dme2TraceOn; + } + + public Boolean getDme2TraceOn() { + return dme2TraceOn; + } + + public void setDme2TraceOn(Boolean dme2TraceOn) { + this.dme2TraceOn = dme2TraceOn; + } + + public String getAftEnvironment() { + return aftEnvironment; + } + + public void setAftEnvironment(String aftEnvironment) { + this.aftEnvironment = aftEnvironment; + } + + public Integer getAftDme2ConnectionTimeoutMs() { + return aftDme2ConnectionTimeoutMs; + } + + public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) { + this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs; + } + + public Integer getAftDme2RoundtripTimeoutMs() { + return aftDme2RoundtripTimeoutMs; + } + + public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) { + this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs; + } + + public Integer getAftDme2ReadTimeoutMs() { + return aftDme2ReadTimeoutMs; + } + + public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) { + this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs; + } + + public String getDme2preferredRouterFilePath() { + return dme2preferredRouterFilePath; + } + + public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) { + this.dme2preferredRouterFilePath = dme2preferredRouterFilePath; + } + + public Credential getCredential() { + return credential; + } + + public void setCredential(Credential credential) { + this.credential = credential; + } + + /** + * Contains Dmaap Client credential parameters: username and password + */ + public static class Credential{ + + private String username; + private String password; + + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + + } + public Integer getTimeLimitForNotificationHandleMs() { + return timeLimitForNotificationHandleMs; + } + + public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { + this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + } + + public boolean isAftDme2SslEnable() { + return aftDme2SslEnable; + } + + public void setAftDme2SslEnable(boolean aftDme2SslEnable) { + this.aftDme2SslEnable = aftDme2SslEnable; + } + + public boolean isAftDme2ClientIgnoreSslConfig() { + return aftDme2ClientIgnoreSslConfig; + } + + public void setAftDme2ClientIgnoreSslConfig(boolean aftDme2ClientIgnoreSslConfig) { + this.aftDme2ClientIgnoreSslConfig = aftDme2ClientIgnoreSslConfig; + } + + public String getAftDme2ClientKeystore() { + return aftDme2ClientKeystore; + } + + public void setAftDme2ClientKeystore(String aftDme2ClientKeystore) { + this.aftDme2ClientKeystore = aftDme2ClientKeystore; + } + + public String getAftDme2ClientKeystorePassword() { + return aftDme2ClientKeystorePassword; + } + + public void setAftDme2ClientKeystorePassword(String aftDme2ClientKeystorePassword) { + this.aftDme2ClientKeystorePassword = aftDme2ClientKeystorePassword; + } + + public String getAftDme2ClientSslCertAlias() { + return aftDme2ClientSslCertAlias; + } + + public void setAftDme2ClientSslCertAlias(String aftDme2ClientSslCertAlias) { + this.aftDme2ClientSslCertAlias = aftDme2ClientSslCertAlias; + } + + @Override + public String toString() { + return "DmaapProducerConfiguration [hosts=" + hosts + ", consumerGroup=" + consumerGroup + ", consumerId=" + + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + pollingInterval + + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + ", version=" + version + + ", serviceName=" + serviceName + ", environment=" + environment + ", partner=" + partner + + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + contenttype + + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment + + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs=" + + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs + + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath + + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs+ ", credential=" + credential + + ", aftDme2SslEnable=" + aftDme2SslEnable + ", aftDme2ClientIgnoreSslConfig=" + aftDme2ClientIgnoreSslConfig + + ", aftDme2ClientKeystore=" + aftDme2ClientKeystore + ", aftDme2ClientSslCertAlias=" + aftDme2ClientSslCertAlias + "]"; + } + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java index 4e553fdd8d..d876378421 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,27 +21,20 @@ package org.openecomp.sdc.be.config; public class DmeConfiguration { - private String dme2Search = "DME2SEARCH"; - private String dme2Resolve = "DME2RESOLVE"; + private String lookupUriFormat = "http://DME2RESOLVE/service=%s/version=1.0.0/envContext=%s/routeOffer=DEFAULT"; - public String getDme2Search() { - return dme2Search; + public String getLookupUriFormat() { + return lookupUriFormat; } - public void setDme2Search(String dme2Search) { - this.dme2Search = dme2Search; - } - - public String getDme2Resolve() { - return dme2Resolve; - } - - public void setDme2Resolve(String dme2Resolve) { - this.dme2Resolve = dme2Resolve; + public void setLookupUriFormat(String lookupUriFormat) { + this.lookupUriFormat = lookupUriFormat; } @Override public String toString() { - return "DmeConfiguration [dme2Search=" + dme2Search + ", dme2Resolve=" + dme2Resolve + "]"; + return "DmeConfiguration{" + + "lookupUriFormat='" + lookupUriFormat + '\'' + + '}'; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java index 3b7efbabf4..52ea02cfab 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,29 +26,29 @@ import java.util.Map; public class ErrorConfiguration extends BasicConfiguration { - private Map<String, ErrorInfo> errors; - - public Map<String, ErrorInfo> getErrors() { - return errors; - } - - public void setErrors(Map<String, ErrorInfo> errors) { - this.errors = errors; - } - - public ErrorInfo getErrorInfo(String key) { - ErrorInfo clone = null; - ErrorInfo other = errors.get(key); - if (other != null) { - clone = new ErrorInfo(); - clone.cloneData(other); - } - return clone; - } - - @Override - public String toString() { - return "ErrorConfiguration [errors=" + errors + "]"; - } + private Map<String, ErrorInfo> errors; + + public Map<String, ErrorInfo> getErrors() { + return errors; + } + + public void setErrors(Map<String, ErrorInfo> errors) { + this.errors = errors; + } + + public ErrorInfo getErrorInfo(String key) { + ErrorInfo clone = null; + ErrorInfo other = errors.get(key); + if (other != null) { + clone = new ErrorInfo(); + clone.cloneData(other); + } + return clone; + } + + @Override + public String toString() { + return "ErrorConfiguration [errors=" + errors + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java index 0846fc7083..ec9a61c81f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,76 +24,76 @@ import org.openecomp.sdc.common.log.wrappers.Logger; public class ErrorInfo { - private Integer code; - private String message; - private String messageId; - private ErrorInfoType errorInfoType; - - private static final String SVC_PREFIX = "SVC"; - private static final String POL_PREFIX = "POL"; - - private static Logger log = Logger.getLogger(ErrorInfo.class.getName()); - - public ErrorInfo() { - this.errorInfoType = ErrorInfoType.OK; - } - - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getMessageId() { - return messageId; - } - - public void setMessageId(String messageId) { - // Determining the type of error - if (messageId == null) { - this.errorInfoType = ErrorInfoType.OK; - } else if (messageId.startsWith(SVC_PREFIX)) { - this.errorInfoType = ErrorInfoType.SERVICE_EXCEPTION; - } else if (messageId.startsWith(POL_PREFIX)) { - this.errorInfoType = ErrorInfoType.POLICY_EXCEPTION; - } else { - // unexpected - should it fail the startup? - BeEcompErrorManager.getInstance().logErrorConfigFileFormat("Error Info", - "Could not set error info type for message id " + messageId); - log.debug("Error: unexpected error message ID {}, should start with {} or {}", messageId, SVC_PREFIX, - POL_PREFIX); - } - this.messageId = messageId; - } - - public ErrorInfoType getErrorInfoType() { - return this.errorInfoType; - } - - public void cloneData(ErrorInfo other) { - this.code = other.getCode(); - this.message = other.getMessage(); - this.messageId = other.getMessageId(); - this.errorInfoType = other.errorInfoType; - } - - @Override - public String toString() { - return "ErrorInfo [code=" + code + ", messageId=" + messageId + ", message=" + message + "]"; - } - - public enum ErrorInfoType { - OK, POLICY_EXCEPTION, SERVICE_EXCEPTION - } + private Integer code; + private String message; + private String messageId; + private ErrorInfoType errorInfoType; + + private static final String SVC_PREFIX = "SVC"; + private static final String POL_PREFIX = "POL"; + + private static Logger log = Logger.getLogger(ErrorInfo.class.getName()); + + public ErrorInfo() { + this.errorInfoType = ErrorInfoType.OK; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + // Determining the type of error + if (messageId == null) { + this.errorInfoType = ErrorInfoType.OK; + } else if (messageId.startsWith(SVC_PREFIX)) { + this.errorInfoType = ErrorInfoType.SERVICE_EXCEPTION; + } else if (messageId.startsWith(POL_PREFIX)) { + this.errorInfoType = ErrorInfoType.POLICY_EXCEPTION; + } else { + // unexpected - should it fail the startup? + BeEcompErrorManager.getInstance().logErrorConfigFileFormat("Error Info", + "Could not set error info type for message id " + messageId); + log.debug("Error: unexpected error message ID {}, should start with {} or {}", messageId, SVC_PREFIX, + POL_PREFIX); + } + this.messageId = messageId; + } + + public ErrorInfoType getErrorInfoType() { + return this.errorInfoType; + } + + public void cloneData(ErrorInfo other) { + this.code = other.getCode(); + this.message = other.getMessage(); + this.messageId = other.getMessageId(); + this.errorInfoType = other.errorInfoType; + } + + @Override + public String toString() { + return "ErrorInfo [code=" + code + ", messageId=" + messageId + ", message=" + message + "]"; + } + + public enum ErrorInfoType { + OK, POLICY_EXCEPTION, SERVICE_EXCEPTION + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java index 7dc8dc8f26..02965242cf 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Neo4jErrorsConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,23 +25,23 @@ import org.openecomp.sdc.common.api.BasicConfiguration; import java.util.Map; public class Neo4jErrorsConfiguration extends BasicConfiguration { - private Map<String, String> errors; + private Map<String, String> errors; - public Map<String, String> getErrors() { - return errors; - } + public Map<String, String> getErrors() { + return errors; + } - public void setErrors(Map<String, String> errors) { - this.errors = errors; - } + public void setErrors(Map<String, String> errors) { + this.errors = errors; + } - public String getErrorMessage(String key) { - return errors.get(key); - } + public String getErrorMessage(String key) { + return errors.get(key); + } - @Override - public String toString() { - return "Neo4jErrorsConfiguration [errors=" + errors + "]"; - } + @Override + public String toString() { + return "Neo4jErrorsConfiguration [errors=" + errors + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java index 88bab26d7c..72b53bac75 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/DeploymentArtifactHeatConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,33 +24,34 @@ import java.util.Map; /** * Currently for deployment artifacts HEAT validation only. - * + * * Other artifacts might require different fields validation Be sure to check it * before you re-use this class - * + * * @author paharoni + * */ public class DeploymentArtifactHeatConfiguration { - // All the rest of heat file is not needed for now... - private String heat_template_version; + // All the rest of heat file is not needed for now... + String heat_template_version; - private Map<String, Object> resources; + Map<String, Object> resources; - public String getHeat_template_version() { - return heat_template_version; - } + public String getHeat_template_version() { + return heat_template_version; + } - public void setHeat_template_version(String heat_template_version) { - this.heat_template_version = heat_template_version; - } + public void setHeat_template_version(String heat_template_version) { + this.heat_template_version = heat_template_version; + } - public Map<String, Object> getResources() { - return resources; - } + public Map<String, Object> getResources() { + return resources; + } - public void setResources(Map<String, Object> resources) { - this.resources = resources; - } + public void setResources(Map<String, Object> resources) { + this.resources = resources; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java index 0117b2be9e..c29574dd1b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -46,64 +46,64 @@ import java.util.concurrent.TimeUnit; public class BeMonitoringService { - private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; - private static Logger monitoringLogger = Logger.getLogger("asdc.be.monitoring.service"); - private static Logger log = Logger.getLogger(BeMonitoringService.class.getName()); - private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; + private static Logger monitoringLogger = Logger.getLogger("asdc.be.monitoring.service"); + private static Logger log = Logger.getLogger(BeMonitoringService.class.getName()); + private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private class MonitoringScheduledTask implements Runnable { - @Override - public void run() { - monitoringLogger.trace("Executing BE Monitoring Task - Start"); - MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); - processMonitoringEvent(monitoringMetrics); - monitoringLogger.trace("Executing BE Monitoring Task - Status = {}", monitoringMetrics.toString()); - } - } + private class MonitoringScheduledTask implements Runnable { + @Override + public void run() { + monitoringLogger.trace("Executing BE Monitoring Task - Start"); + MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); + processMonitoringEvent(monitoringMetrics); + monitoringLogger.trace("Executing BE Monitoring Task - Status = {}", monitoringMetrics.toString()); + } + } - /** - * This executor will execute the Monitoring task. - */ - private ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "BE-Monitoring-Thread"); - } - }); - private ServletContext context; + /** + * This executor will execute the Monitoring task. + */ + ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "BE-Monitoring-Thread"); + } + }); + private ServletContext context; - public BeMonitoringService(ServletContext context) { - this.context = context; - } + public BeMonitoringService(ServletContext context) { + this.context = context; + } - public void start(int interval) { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - if (config.getSystemMonitoring().getEnabled()) { - log.info("BE monitoring service is enabled, interval is {} seconds", interval); - this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); - } else { - log.info("BE monitoring service is disabled"); - } - } + public void start(int interval) { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + if (config.getSystemMonitoring().getEnabled()) { + log.info("BE monitoring service is enabled, interval is {} seconds", interval); + this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); + } else { + log.info("BE monitoring service is disabled"); + } + } - private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { - try { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeFqdn(), - config.getBeHttpPort()); + private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { + try { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeFqdn(), + config.getBeHttpPort()); - final int timeout = 3000; - String monitoringMetricsJson = gson.toJson(monitoringMetrics); - HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); - HttpResponse<String> httpResponse = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); + final int timeout = 3000; + String monitoringMetricsJson = gson.toJson(monitoringMetrics); + HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); + HttpResponse<String> httpResponse = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); int beResponseStatus = httpResponse.getStatusCode(); if (beResponseStatus != HttpStatus.SC_OK) { - monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Unexpected HTTP response from BE : {}", beResponseStatus); + monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Unexpected HTTP response from BE : {}", beResponseStatus); } - } catch (Exception e) { - monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Monitoring BE failed with exception ", e); - } - } + } catch (Exception e) { + monitoringLogger.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Monitoring BE failed with exception ", e); + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java index 2127441cb7..fa0f30842b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ApplicationErrorCodesEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,16 +22,16 @@ package org.openecomp.sdc.common.api; public enum ApplicationErrorCodesEnum { - POL5000, // INTERNAL_ERROR + POL5000, // INTERNAL_ERROR - SVC4000, // INVALID_INPUT + SVC4000, // INVALID_INPUT - SVC4002, // MISSING_INFORMATION - SVC4003, // RESOURCE_NAME_ALREADY_EXIST - SVC4004, // MISSING_CATEGORY - SVC4005, // MISSING_TAGS - SVC4006, // MISSING_DESCRIPTION - SVC4007, // BAD_CATEGORY + SVC4002, // MISSING_INFORMATION + SVC4003, // RESOURCE_NAME_ALREADY_EXIST + SVC4004, // MISSING_CATEGORY + SVC4005, // MISSING_TAGS + SVC4006, // MISSING_DESCRIPTION + SVC4007, // BAD_CATEGORY - SVC4030; // RESTRICTED_ACTION + SVC4030; // RESTRICTED_ACTION } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java index d3107e0117..c990d43f64 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactGroupTypeEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,37 +25,37 @@ import java.util.List; public enum ArtifactGroupTypeEnum { - INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER"); - - private String type; - - ArtifactGroupTypeEnum(String type) { - this.type = type; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public static ArtifactGroupTypeEnum findType(final String type) { - for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { - if (ate.getType().equals(type)) { - return ate; - } - } - return null; - } - - public static List<String> getAllTypes() { - List<String> types = new ArrayList<>(); - for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { - types.add(ate.getType()); - } - return types; - } + INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER"); + + private String type; + + ArtifactGroupTypeEnum(String type) { + this.type = type; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public static ArtifactGroupTypeEnum findType(final String type) { + for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { + if (ate.getType().equals(type)) { + return ate; + } + } + return null; + } + + public static List<String> getAllTypes() { + List<String> types = new ArrayList<>(); + for (ArtifactGroupTypeEnum ate : ArtifactGroupTypeEnum.values()) { + types.add(ate.getType()); + } + return types; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java index 722a3e74cc..9d0ff1c083 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ArtifactTypeEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,41 +27,43 @@ import lombok.Getter; /** * Enum That Represents possible Artifacts Types. + * */ @Getter @AllArgsConstructor public enum ArtifactTypeEnum { - CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), SHELL("SHELL"), ICON("ICON"), UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG("MURANO_PKG"), HEAT_ENV("HEAT_ENV"), YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), - HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"), NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"), VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"), BPEL("BPEL"), - VENDOR_LICENSE("VENDOR_LICENSE"), MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"), HEAT_ARTIFACT("HEAT_ARTIFACT"), CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT("CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT"), - VF_MODULES_METADATA("VF_MODULES_METADATA"), LIFECYCLE_OPERATIONS("LIFECYCLE_OPERATIONS"), VES_EVENTS("VES_EVENTS"), PERFORMANCE_COUNTER("PERFORMANCE_COUNTER"), UCPE_LAYER_2_CONFIGURATION("UCPE_LAYER_2_CONFIGURATION"), - CONTROLLER_BLUEPRINT_ARCHIVE("CONTROLLER_BLUEPRINT_ARCHIVE"), - // DCAE Artifacts - DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"), DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), - DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), - // AAI Artifacts - AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), - // MIB artifacts - SNMP_POLL("SNMP_POLL"), SNMP_TRAP("SNMP_TRAP"), GUIDE("GUIDE"), - PLAN("PLAN"), PM_DICTIONARY("PM_DICTIONARY"), YANG_MODULE("YANG_MODULE"), + CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), SHELL("SHELL"), ICON("ICON"), UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG("MURANO_PKG"), HEAT_ENV("HEAT_ENV"), YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), + HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"), NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"), TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"), VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"), BPEL("BPEL"), + VENDOR_LICENSE("VENDOR_LICENSE"), MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"), HEAT_ARTIFACT("HEAT_ARTIFACT"), CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT("CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT"), + VF_MODULES_METADATA("VF_MODULES_METADATA"), LIFECYCLE_OPERATIONS("LIFECYCLE_OPERATIONS"), VES_EVENTS("VES_EVENTS"), PERFORMANCE_COUNTER("PERFORMANCE_COUNTER"),UCPE_LAYER_2_CONFIGURATION("UCPE_LAYER_2_CONFIGURATION"), + CONTROLLER_BLUEPRINT_ARCHIVE("CONTROLLER_BLUEPRINT_ARCHIVE"), + // DCAE Artifacts + DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"), DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"), DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), + DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"), DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"), + // AAI Artifacts + AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), + // MIB artifacts + SNMP_POLL ("SNMP_POLL"), SNMP_TRAP("SNMP_TRAP"), GUIDE("GUIDE"), + PLAN("PLAN"), PM_DICTIONARY("PM_DICTIONARY"), YANG_MODULE("YANG_MODULE"), ANSIBLE_PLAYBOOK("ANSIBLE_PLAYBOOK"), ONBOARDED_PACKAGE("ONBOARDED_PACKAGE"), PNF_SW_INFORMATION("PNF_SW_INFORMATION"); private final String type; - public static ArtifactTypeEnum findType(final String type) { + + public static ArtifactTypeEnum findType(final String type) { for (final ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { - if (ate.getType().equalsIgnoreCase(type)) { - return ate; - } - } - return null; - } + if (ate.getType().equalsIgnoreCase(type)) { + return ate; + } + } + return null; + } - public static List<String> getAllTypes() { + public static List<String> getAllTypes() { final List<String> types = new ArrayList<>(); for (final ArtifactTypeEnum ate : ArtifactTypeEnum.values()) { - types.add(ate.getType()); - } - return types; - } + types.add(ate.getType()); + } + return types; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java index 271fbb7a96..5152b2af26 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/BasicConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java index 360562b91a..d60ed6dabc 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,29 +22,29 @@ package org.openecomp.sdc.common.api; public class ConfigurationListener { - private Class<? extends BasicConfiguration> type; - private FileChangeCallback callBack; + private Class<? extends BasicConfiguration> type; + private FileChangeCallback callBack; - public ConfigurationListener(Class<? extends BasicConfiguration> type, FileChangeCallback callBack) { - super(); - this.type = type; - this.callBack = callBack; - } + public ConfigurationListener(Class<? extends BasicConfiguration> type, FileChangeCallback callBack) { + super(); + this.type = type; + this.callBack = callBack; + } - public Class<? extends BasicConfiguration> getType() { - return type; - } + public Class<? extends BasicConfiguration> getType() { + return type; + } - public void setType(Class<? extends BasicConfiguration> type) { - this.type = type; - } + public void setType(Class<? extends BasicConfiguration> type) { + this.type = type; + } - public FileChangeCallback getCallBack() { - return callBack; - } + public FileChangeCallback getCallBack() { + return callBack; + } - public void setCallBack(FileChangeCallback callBack) { - this.callBack = callBack; - } + public void setCallBack(FileChangeCallback callBack) { + this.callBack = callBack; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java index a3d4179a41..5901d1e267 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ConfigurationSource.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.api; public interface ConfigurationSource { - <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); + public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); - <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); + public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java index 0ced7ec648..d11cc02d86 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,130 +22,138 @@ package org.openecomp.sdc.common.api; public final class Constants { - public static final String APPLICATION_NAME = "application-name"; - public static final String APPLICATION_VERSION = "application-version"; - public static final String CONFIG_HOME = "config.home"; - public static final String LOG_HOME = "log.home"; - public static final String YAML_SUFFIX = ".yaml"; - public static final String CONFIGURATION_SOURCE_ATTR = "configuration-source"; - public static final String MDC_APP_NAME = "APP_NAME"; - public static final String CONFIGURATION_MANAGER_ATTR = "configuration-manager"; - public static final String HEALTH_CHECK_SERVICE_ATTR = "healthCheckService"; - public static final String REST_CLIENT_ATTR = "rest-client"; - public static final String ARTIFACT_DAO_ATTR = "artifact-dao"; - public static final String UPLOAD_VALIDATORR_ATTR = "upload-validator"; - public static final String THREAD_EXECUTOR_ATTR = "thread-executor"; - public static final String ERROR_LOG_FORMAT = "EVENT = ARTIFACT_UPLOAD USER_ID=%s USER_NAME=%s ACCESS_IP=%s ACCESS_TYPE=%s RURL=%s SC=%d"; - public static final String FIRST_NAME_HEADER = "HTTP_CSP_FIRSTNAME"; - public static final String LAST_NAME_HEADER = "HTTP_CSP_LASTNAME"; - public static final String USER_ID_HEADER = "USER_ID"; - public static final String MD5_HEADER = "Content-MD5"; - public static final String CONTENT_LENGTH_HEADER = "Content-Length"; - public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition"; - public static final String CONTENT_TYPE_HEADER = "Content-Type"; - public static final String ORIGIN_HEADER = "HTTP_IV_REMOTE_ADDRESS"; - public static final String ACCESS_HEADER = "HTTP_CSP_WSTYPE"; - public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; - public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; - public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; - public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId"; - public static final String X_FROM_APP_ID = "X-FromAppId"; - public static final String HTTP = "http"; - public static final String HTTPS = "https"; - public static final String HTTP_IV_USER = "HTTP_IV_USER"; - public static final String A4C_CSAR_CONTEXT = "/rest/csars/"; - public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper"; - public static final String CATALOG_BE = "catalog-be"; - public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1"; - public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName - public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName - public static final String CONTENT_DISPOSITION = "content-disposition"; - public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic"; - public static final String ASDC_RELEASE_VERSION_ATTR = "SDC-Version"; - public static final String YEAR = "year"; - public static final String MONTH = "month"; - public static final String DAY = "day"; - public static final String HOUR = "hour"; - public static final String MINUTE = "minute"; - public static final String NONE = "none"; - public static final String RESOURCE_OPERATION_MANAGER = "resourceOperationManager"; - public static final String PROPERTY_OPERATION_MANAGER = "propertyOperationManager"; - public static final String SERVICE_OPERATION_MANAGER = "serviceOperationManager"; - public static final String EMPTY_STRING = ""; - public static final String NULL_STRING = "null"; - public static final String DOUBLE_NULL_STRING = "null null"; - public static final String ECOMP_ERROR_MNGR_ATTR = "ecompErrorMngrAttr"; - public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String ACCEPT_HEADER = "Accept"; - public static final String STANDARD_INTERFACE_TYPE = "standard"; - public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG"; + public static final String APPLICATION_NAME = "application-name"; + public static final String APPLICATION_VERSION = "application-version"; + public static final String CONFIG_HOME = "config.home"; + public static final String LOG_HOME = "log.home"; + public static final String YAML_SUFFIX = ".yaml"; + public static final String CONFIGURATION_SOURCE_ATTR = "configuration-source"; + public static final String MDC_APP_NAME = "APP_NAME"; + public static final String CONFIGURATION_MANAGER_ATTR = "configuration-manager"; + public static final String HEALTH_CHECK_SERVICE_ATTR = "healthCheckService"; + public static final String REST_CLIENT_ATTR = "rest-client"; + public static final String ARTIFACT_DAO_ATTR = "artifact-dao"; + public static final String UPLOAD_VALIDATORR_ATTR = "upload-validator"; + public static final String THREAD_EXECUTOR_ATTR = "thread-executor"; + public static final String ERROR_LOG_FORMAT = "EVENT = ARTIFACT_UPLOAD USER_ID=%s USER_NAME=%s ACCESS_IP=%s ACCESS_TYPE=%s RURL=%s SC=%d"; + public static final String FIRST_NAME_HEADER = "HTTP_CSP_FIRSTNAME"; + public static final String LAST_NAME_HEADER = "HTTP_CSP_LASTNAME"; + public static final String USER_ID_HEADER = "USER_ID"; + public static final String MD5_HEADER = "Content-MD5"; + public static final String USER_AGENT_HEADER = "User-Agent"; + public static final String CONTENT_LENGTH_HEADER = "Content-Length"; + public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition"; + public static final String CONTENT_TYPE_HEADER = "Content-Type"; + public static final String ORIGIN_HEADER = "HTTP_IV_REMOTE_ADDRESS"; + public static final String ACCESS_HEADER = "HTTP_CSP_WSTYPE"; + public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; + public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; + public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; + public static final String X_REQUEST_ID = "X-RequestID"; + public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId"; + public static final String X_FROM_APP_ID = "X-FromAppId"; + public static final String PartnerName_Unknown = "UNKNOWN"; + public static final String X_InvocationID = "X-InvocationID"; + public static final String HTTP = "http"; + public static final String HTTPS = "https"; + public static final String HTTP_IV_USER = "HTTP_IV_USER"; + public static final String A4C_CSAR_CONTEXT = "/rest/csars/"; + public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper"; + public static final String CATALOG_BE = "catalog-be"; + public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1"; + public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName + public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName + public static final String CONTENT_DISPOSITION = "content-disposition"; + public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic"; + public static final String ASDC_RELEASE_VERSION_ATTR = "SDC-Version"; + public static final String YEAR = "year"; + public static final String MONTH = "month"; + public static final String DAY = "day"; + public static final String HOUR = "hour"; + public static final String MINUTE = "minute"; + public static final String NONE = "none"; + public static final String RESOURCE_OPERATION_MANAGER = "resourceOperationManager"; + public static final String PROPERTY_OPERATION_MANAGER = "propertyOperationManager"; + public static final String SERVICE_OPERATION_MANAGER = "serviceOperationManager"; + public static final String EMPTY_STRING = ""; + public static final String NULL_STRING = "null"; + public static final String DOUBLE_NULL_STRING = "null null"; + public static final String ECOMP_ERROR_MNGR_ATTR = "ecompErrorMngrAttr"; + public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String ACCEPT_HEADER = "Accept"; + public static final String STANDARD_INTERFACE_TYPE = "standard"; + public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG"; - // TOSCA - public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; - public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; - public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; + // TOSCA + public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; + public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; + public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; - public static final String IS_BASE = "isBase"; - public static final String HEAT_FILE_PROPS = "heat_file"; - public static final String GROUP_POLICY_NAME_DELIMETER = ".."; - public static final String POLICY_UID_POSTFIX = ".policy"; - public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s"; - public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+"; - public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)"; - public static final String MODULE_NEW_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+\\.\\.)([\\_\\-\\.a-zA-Z0-9]+)(..module-)(\\d+)"; - public static final String MODULE_NAME_DELIMITER = "module-"; - public static final String IMPORT_STRUCTURE = "importStructure"; - public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule"; - public static final String GROUP_TOSCA_HEAT = "org.openecomp.groups.heat.HeatStack"; + public static final String IS_BASE = "isBase"; + public static final String HEAT_FILE_PROPS = "heat_file"; + public static final String GROUP_POLICY_NAME_DELIMETER = ".."; + public static final String POLICY_UID_POSTFIX = ".policy"; + public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s"; + public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+"; + public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)"; + public static final String MODULE_NEW_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+\\.\\.)([\\_\\-\\.a-zA-Z0-9]+)(..module-)(\\d+)"; + public static final String MODULE_NAME_DELIMITER = "module-"; + public static final String IMPORT_STRUCTURE = "importStructure"; + public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule"; + public static final String GROUP_TOSCA_HEAT = "org.openecomp.groups.heat.HeatStack"; - public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; - public static final String ARTIFACT_LABEL = "artifactLabel"; - public static final String ARTIFACT_PAYLOAD_DATA = "payloadData"; - public static final String ARTIFACT_DISPLAY_NAME = "artifactDisplayName"; - public static final String ARTIFACT_DESCRIPTION = "description"; - public static final String ARTIFACT_TYPE = "artifactType"; - public static final String ARTIFACT_NAME = "artifactName"; - public static final String IS_FROM_CSAR = "isFromCsar"; - public static final String ARTIFACT_ID = "uniqueId"; - public static final String REQUIRED_ARTIFACTS = "requiredArtifacts"; - public static final String ARTIFACT_HEAT_PARAMS = "heatParameters"; - public static final String ARTIFACT_ES_ID = "esId"; + public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; + public static final String ARTIFACT_LABEL = "artifactLabel"; + public static final String ARTIFACT_PAYLOAD_DATA = "payloadData"; + public static final String ARTIFACT_DISPLAY_NAME = "artifactDisplayName"; + public static final String ARTIFACT_DESCRIPTION = "description"; + public static final String ARTIFACT_TYPE = "artifactType"; + public static final String ARTIFACT_NAME = "artifactName"; + public static final String IS_FROM_CSAR = "isFromCsar"; + public static final String ARTIFACT_ID = "uniqueId"; + public static final String REQUIRED_ARTIFACTS = "requiredArtifacts"; + public static final String ARTIFACT_HEAT_PARAMS = "heatParameters"; + public static final String ARTIFACT_ES_ID = "esId"; + public static final String ARTIFACT_TIMEOUT = "timeout"; - public static final String ABSTRACT = "abstract"; - public static final String GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml"; - public static final String ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE = "Definitions/AbstractSubstituteGlobalTypesServiceTemplate.yaml"; + public static final String ABSTRACT = "abstract"; + public static final String GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml"; + public static final String ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE = "Definitions/AbstractSubstituteGlobalTypesServiceTemplate.yaml"; - public static final String VENDOR_LICENSE_MODEL = "vendor-license-model.xml"; - public static final String VENDOR_LICENSE_LABEL = "vendorlicense"; - public static final String VENDOR_LICENSE_DISPLAY_NAME = "Vendor License"; - public static final String VENDOR_LICENSE_DESCRIPTION = " Vendor license file"; + public static final String VENDOR_LICENSE_MODEL = "vendor-license-model.xml"; + public static final String VENDOR_LICENSE_LABEL = "vendorlicense"; + public static final String VENDOR_LICENSE_DISPLAY_NAME = "Vendor License"; + public static final String VENDOR_LICENSE_DESCRIPTION = " Vendor license file"; - public static final String VF_LICENSE_MODEL = "vf-license-model.xml"; - public static final String VF_LICENSE_LABEL = "vflicense"; - public static final String VF_LICENSE_DISPLAY_NAME = "VF License"; - public static final String VF_LICENSE_DESCRIPTION = "VF license file"; - public static final String GET_INPUT = "get_input"; - public static final String GET_POLICY = "get_policy"; - public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml"; - public static final String SERVICE_TEMPLATES_CONTAINING_FOLDER = "Definitions/"; - public static final String UNBOUNDED = "unbounded"; + public static final String VF_LICENSE_MODEL = "vf-license-model.xml"; + public static final String VF_LICENSE_LABEL = "vflicense"; + public static final String VF_LICENSE_DISPLAY_NAME = "VF License"; + public static final String VF_LICENSE_DESCRIPTION = "VF license file"; + public static final String GET_INPUT = "get_input"; + public static final String GET_POLICY = "get_policy"; + public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml"; + public static final String SERVICE_TEMPLATES_CONTAINING_FOLDER = "Definitions/"; + public static final String UNBOUNDED = "unbounded"; + + //SDC HealthCheck components + public static final String HC_COMPONENT_FE = "FE"; + public static final String HC_COMPONENT_BE = "BE"; + public static final String HC_COMPONENT_CADI = "External API"; + public static final String HC_COMPONENT_JANUSGRAPH = "JANUSGRAPH"; + public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA"; + public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE"; + public static final String HC_COMPONENT_DMAAP_ENGINE = "DMAAP"; + public static final String HC_COMPONENT_DMAAP_PRODUCER = "DMAAP_PRODUCER"; + public static final String HC_COMPONENT_CATALOG_FACADE_MS = "CATALOG_FACADE_MS"; - //SDC HealthCheck components - public static final String HC_COMPONENT_FE = "FE"; - public static final String HC_COMPONENT_BE = "BE"; - public static final String HC_COMPONENT_JANUSGRAPH = "JANUSGRAPH"; - public static final String HC_COMPONENT_ES = "ES"; - public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA"; - public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE"; - public static final String HC_COMPONENT_DMAAP_ENGINE = "DMAAP"; + //external HealthCheck components + public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; + public static final String HC_COMPONENT_DCAE = "DCAE"; + public static final String HC_COMPONENT_ECOMP_PORTAL = "PORTAL"; - //external HealthCheck components - public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; - public static final String HC_COMPONENT_DCAE = "DCAE"; - - //Plugin BL - public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; - - private Constants() { - } + + //Plugin BL + public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; + + private Constants(){} } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java index 730d7067c2..5c4d3d5926 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FileChangeCallback.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,6 @@ package org.openecomp.sdc.common.api; public interface FileChangeCallback { - void reconfigure(BasicConfiguration obj); + public void reconfigure(BasicConfiguration obj); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/FilterDecisionEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FilterDecisionEnum.java new file mode 100644 index 0000000000..2e0ce9481a --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/FilterDecisionEnum.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.common.api; + +public enum FilterDecisionEnum { + EXTERNAL,INTERNAL,NA; + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java index bfcba41faa..53cb6654ba 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,88 +27,96 @@ import java.lang.reflect.Type; import java.util.List; public class HealthCheckInfo { + + private String healthCheckComponent; + private HealthCheckStatus healthCheckStatus; + private String version; + private String description; + private List<HealthCheckInfo> componentsInfo; + + public void setHealthCheckComponent(String healthCheckComponent) { + this.healthCheckComponent = healthCheckComponent; + } + + public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, + String version, String description) { + super(); + this.healthCheckComponent = healthCheckComponent; + this.healthCheckStatus = healthCheckStatus; + this.version = version; + this.description = description; + } + + public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, + String version, String description, List<HealthCheckInfo> componentsInfo) { + super(); + this.healthCheckComponent = healthCheckComponent; + this.healthCheckStatus = healthCheckStatus; + this.version = version; + this.description = description; + this.componentsInfo = componentsInfo; +} - private String healthCheckComponent; - private HealthCheckStatus healthCheckStatus; - private String version; - private String description; - private List<HealthCheckInfo> componentsInfo; - - public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, - String version, String description) { - super(); - this.healthCheckComponent = healthCheckComponent; - this.healthCheckStatus = healthCheckStatus; - this.version = version; - this.description = description; - } - - public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, - String version, String description, List<HealthCheckInfo> componentsInfo) { - super(); - this.healthCheckComponent = healthCheckComponent; - this.healthCheckStatus = healthCheckStatus; - this.version = version; - this.description = description; - this.componentsInfo = componentsInfo; - } - - public HealthCheckInfo() { - super(); - } - - public String getHealthCheckComponent() { - return healthCheckComponent; - } - - public HealthCheckStatus getHealthCheckStatus() { - return healthCheckStatus; - } - - public void setHealthCheckStatus(HealthCheckStatus healthCheckStatus) { - this.healthCheckStatus = healthCheckStatus; - } - - public List<HealthCheckInfo> getComponentsInfo() { - return componentsInfo; - } - - public void setComponentsInfo(List<HealthCheckInfo> componentsInfo) { - this.componentsInfo = componentsInfo; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public enum HealthCheckStatus { - UP, DOWN, UNKNOWN; - } - - @Override - public String toString() { - return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus=" - + healthCheckStatus + ", version=" + version + ", description=" + description + ", componentsInfo=" - + componentsInfo + "]"; - } - - public static void main(String[] args) { - String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]"; - Type listType = new TypeToken<List<HealthCheckInfo>>() { - }.getType(); - List<HealthCheckInfo> componentsInfo = new Gson().fromJson(des.toString(), listType); - System.out.println(componentsInfo.toString()); - } + public HealthCheckInfo() { + super(); + } + + public String getHealthCheckComponent() { + return healthCheckComponent; + } + + public HealthCheckStatus getHealthCheckStatus() { + return healthCheckStatus; + } + + public void setHealthCheckStatus(HealthCheckStatus healthCheckStatus) { + this.healthCheckStatus = healthCheckStatus; + } + + public List<HealthCheckInfo> getComponentsInfo() { + return componentsInfo; + } + + public void setComponentsInfo(List<HealthCheckInfo> componentsInfo) { + this.componentsInfo = componentsInfo; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + /*public enum HealthCheckComponent { + FE, BE, JANUSGRAPH, DE, ON_BOARDING, CASSANDRA, DCAE, + CAS, ZU;//Amdocs components + }*/ + + public enum HealthCheckStatus { + UP, DOWN, UNKNOWN; + } + + @Override + public String toString() { + return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus=" + + healthCheckStatus + ", version=" + version + ", description=" + description + ", componentsInfo=" + + componentsInfo + "]"; + } + + public static void main(String[] args) { + String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]"; + Type listType = new TypeToken<List<HealthCheckInfo>>(){}.getType(); + List<HealthCheckInfo> componentsInfo = new Gson().fromJson(des.toString(), listType); + System.out.println(componentsInfo.toString()); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java index 184051600c..29c6350516 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckWrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,39 +24,39 @@ import java.util.List; public class HealthCheckWrapper { - private String sdcVersion; - private String siteMode; - private List<HealthCheckInfo> componentsInfo; + String sdcVersion; + String siteMode; + List<HealthCheckInfo> componentsInfo; - public HealthCheckWrapper(List<HealthCheckInfo> componentsInfo, String sdcVersion, String siteMode) { - super(); - this.componentsInfo = componentsInfo; - this.sdcVersion = sdcVersion; - this.siteMode = siteMode; - } + public HealthCheckWrapper(List<HealthCheckInfo> componentsInfo, String sdcVersion, String siteMode) { + super(); + this.componentsInfo = componentsInfo; + this.sdcVersion = sdcVersion; + this.siteMode = siteMode; + } - public List<HealthCheckInfo> getComponentsInfo() { - return componentsInfo; - } + public List<HealthCheckInfo> getComponentsInfo() { + return componentsInfo; + } - public void setComponentsInfo(List<HealthCheckInfo> componentsInfo) { - this.componentsInfo = componentsInfo; - } + public void setComponentsInfo(List<HealthCheckInfo> componentsInfo) { + this.componentsInfo = componentsInfo; + } - public String getSdcVersion() { - return sdcVersion; - } + public String getSdcVersion() { + return sdcVersion; + } - public void setSdcVersion(String sdcVersion) { - this.sdcVersion = sdcVersion; - } + public void setSdcVersion(String sdcVersion) { + this.sdcVersion = sdcVersion; + } - public String getSiteMode() { - return siteMode; - } + public String getSiteMode() { + return siteMode; + } - public void setSiteMode(String siteMode) { - this.siteMode = siteMode; - } + public void setSiteMode(String siteMode) { + this.siteMode = siteMode; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java index f757f32a40..b93fed2e0c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResourceType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.api; public enum ResourceType { - RESOURCE, SERVICE + RESOURCE, SERVICE } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java index 290a71fb3b..3e8968a481 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ResponseInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,59 +25,59 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class ResponseInfo { - public enum ResponseStatusEnum { - SUCCESS("success"), LOGIN_FAILED("loginFailed"), INTERNAL_ERROR("internalError"), MISSING_HEADERS("required headers are missing"), TIMEOUT("timeout"), PARSING_ERROR("parsingFailed"); - - private String statusDescription; - - ResponseStatusEnum(String status) { - this.statusDescription = status; - } - - public String getStatusDescription() { - return statusDescription; - } - } - - private ResponseStatusEnum applicativeStatus; - private String description; - - public ResponseInfo(ResponseStatusEnum applicativeStatus, String description) { - super(); - this.applicativeStatus = applicativeStatus; - this.description = description; - } - - public ResponseInfo(ResponseStatusEnum applicativeStatus) { - super(); - this.applicativeStatus = applicativeStatus; - } - - public ResponseStatusEnum getApplicativeStatus() { - return applicativeStatus; - } - - public void setApplicativeStatus(ResponseStatusEnum applicativeStatus) { - this.applicativeStatus = applicativeStatus; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - ObjectMapper mapper = new ObjectMapper(); - String tostring = super.toString(); - try { - tostring = mapper.writeValueAsString(this); - } catch (JsonProcessingException e) { - - } - return tostring; - } + public enum ResponseStatusEnum { + SUCCESS("success"), LOGIN_FAILED("loginFailed"), INTERNAL_ERROR("internalError"), MISSING_HEADERS("required headers are missing"), TIMEOUT("timeout"), PARSING_ERROR("parsingFailed"); + + private String statusDescription; + + ResponseStatusEnum(String status) { + this.statusDescription = status; + } + + public String getStatusDescription() { + return statusDescription; + } + } + + private ResponseStatusEnum applicativeStatus; + private String description; + + public ResponseInfo(ResponseStatusEnum applicativeStatus, String description) { + super(); + this.applicativeStatus = applicativeStatus; + this.description = description; + } + + public ResponseInfo(ResponseStatusEnum applicativeStatus) { + super(); + this.applicativeStatus = applicativeStatus; + } + + public ResponseStatusEnum getApplicativeStatus() { + return applicativeStatus; + } + + public void setApplicativeStatus(ResponseStatusEnum applicativeStatus) { + this.applicativeStatus = applicativeStatus; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + ObjectMapper mapper = new ObjectMapper(); + String tostring = super.toString(); + try { + tostring = mapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + + } + return tostring; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java index 8246716566..f6608952d0 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,56 +24,56 @@ import java.util.List; public class ToscaNodeTypeInfo { - private String nodeName; - private String templateVersion; - private List<ToscaNodeTypeInterface> interfaces; - private String iconPath; - private String templateName; - - public String getTemplateName() { - return templateName; - } - - public void setTemplateName(String templateName) { - this.templateName = templateName; - } - - public String getNodeName() { - return nodeName; - } - - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - - public List<ToscaNodeTypeInterface> getInterfaces() { - return interfaces; - } - - public void setInterfaces(List<ToscaNodeTypeInterface> interfaces) { - this.interfaces = interfaces; - } - - public String getIconPath() { - return iconPath; - } - - public void setIconPath(String iconPath) { - this.iconPath = iconPath; - } - - @Override - public String toString() { - return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", templateName=" - + templateName + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; - } + private String nodeName; + private String templateVersion; + private List<ToscaNodeTypeInterface> interfaces; + private String iconPath; + private String templateName; + + public String getTemplateName() { + return templateName; + } + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + public String getNodeName() { + return nodeName; + } + + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public List<ToscaNodeTypeInterface> getInterfaces() { + return interfaces; + } + + public void setInterfaces(List<ToscaNodeTypeInterface> interfaces) { + this.interfaces = interfaces; + } + + public String getIconPath() { + return iconPath; + } + + public void setIconPath(String iconPath) { + this.iconPath = iconPath; + } + + @Override + public String toString() { + return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", templateName=" + + templateName + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java index 517ba8cc86..4095714f4b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/ToscaNodeTypeInterface.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,14 +24,14 @@ import java.util.List; public class ToscaNodeTypeInterface { - private List<String> scripts; + List<String> scripts; - public List<String> getScripts() { - return scripts; - } + public List<String> getScripts() { + return scripts; + } - public void setScripts(List<String> scripts) { - this.scripts = scripts; - } + public void setScripts(List<String> scripts) { + this.scripts = scripts; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java index b168271257..110dbf34a2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UploadArtifactInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,134 +22,122 @@ package org.openecomp.sdc.common.api; public class UploadArtifactInfo { - public UploadArtifactInfo() { - - } - - public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription) { - super(); - this.artifactName = artifactName; - this.artifactPath = artifactPath; - this.artifactType = artifactType; - this.artifactDescription = artifactDescription; - } - - public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription, String artifactData) { - super(); - this.artifactName = artifactName; - this.artifactPath = artifactPath; - this.artifactType = artifactType; - this.artifactDescription = artifactDescription; - this.artifactData = artifactData; - } - - private String artifactName; - private String artifactPath; - private ArtifactTypeEnum artifactType; - private String artifactDescription; - private String artifactData; - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactPath() { - return artifactPath; - } - - public void setArtifactPath(String artifactPath) { - this.artifactPath = artifactPath; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public void setArtifactType(ArtifactTypeEnum artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public String getArtifactData() { - return artifactData; - } - - public void setArtifactData(String artifactData) { - this.artifactData = artifactData; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactData == null) ? 0 : artifactData.hashCode()); - result = prime * result + ((artifactDescription == null) ? 0 : artifactDescription.hashCode()); - result = prime * result + ((artifactName == null) ? 0 : artifactName.hashCode()); - result = prime * result + ((artifactPath == null) ? 0 : artifactPath.hashCode()); - result = prime * result + ((artifactType == null) ? 0 : artifactType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - UploadArtifactInfo other = (UploadArtifactInfo) obj; - if (artifactData == null) { - if (other.artifactData != null) { - return false; - } - } else if (!artifactData.equals(other.artifactData)) { - return false; - } - if (artifactDescription == null) { - if (other.artifactDescription != null) { - return false; - } - } else if (!artifactDescription.equals(other.artifactDescription)) { - return false; - } - if (artifactName == null) { - if (other.artifactName != null) { - return false; - } - } else if (!artifactName.equals(other.artifactName)) { - return false; - } - if (artifactPath == null) { - if (other.artifactPath != null) { - return false; - } - } else if (!artifactPath.equals(other.artifactPath)) { - return false; - } - if (artifactType != other.artifactType) { - return false; - } - return true; - } - - @Override - public String toString() { - return "UploadArtifactInfo [artifactName=" + artifactName + ", artifactPath=" + artifactPath + ", artifactType=" + artifactType + ", artifactDescription=" + artifactDescription + ", artifactData=" + artifactData + "]"; - } + public UploadArtifactInfo() { + + } + + public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription) { + super(); + this.artifactName = artifactName; + this.artifactPath = artifactPath; + this.artifactType = artifactType; + this.artifactDescription = artifactDescription; + } + + public UploadArtifactInfo(String artifactName, String artifactPath, ArtifactTypeEnum artifactType, String artifactDescription, String artifactData) { + super(); + this.artifactName = artifactName; + this.artifactPath = artifactPath; + this.artifactType = artifactType; + this.artifactDescription = artifactDescription; + this.artifactData = artifactData; + } + + private String artifactName; + private String artifactPath; + private ArtifactTypeEnum artifactType; + private String artifactDescription; + private String artifactData; + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactPath() { + return artifactPath; + } + + public void setArtifactPath(String artifactPath) { + this.artifactPath = artifactPath; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public void setArtifactType(ArtifactTypeEnum artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactData() { + return artifactData; + } + + public void setArtifactData(String artifactData) { + this.artifactData = artifactData; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((artifactData == null) ? 0 : artifactData.hashCode()); + result = prime * result + ((artifactDescription == null) ? 0 : artifactDescription.hashCode()); + result = prime * result + ((artifactName == null) ? 0 : artifactName.hashCode()); + result = prime * result + ((artifactPath == null) ? 0 : artifactPath.hashCode()); + result = prime * result + ((artifactType == null) ? 0 : artifactType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UploadArtifactInfo other = (UploadArtifactInfo) obj; + if (artifactData == null) { + if (other.artifactData != null) + return false; + } else if (!artifactData.equals(other.artifactData)) + return false; + if (artifactDescription == null) { + if (other.artifactDescription != null) + return false; + } else if (!artifactDescription.equals(other.artifactDescription)) + return false; + if (artifactName == null) { + if (other.artifactName != null) + return false; + } else if (!artifactName.equals(other.artifactName)) + return false; + if (artifactPath == null) { + if (other.artifactPath != null) + return false; + } else if (!artifactPath.equals(other.artifactPath)) + return false; + if (artifactType != other.artifactType) + return false; + return true; + } + + @Override + public String toString() { + return "UploadArtifactInfo [artifactName=" + artifactName + ", artifactPath=" + artifactPath + ", artifactType=" + artifactType + ", artifactDescription=" + artifactDescription + ", artifactData=" + artifactData + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java index 6e7b2403f3..a750fa454a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/UserRoleEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,15 +21,15 @@ package org.openecomp.sdc.common.api; public enum UserRoleEnum { - ADMIN("ADMIN"), DESIGNER("DESIGNER"), TESTER("TESTER"), GOVERNOR("GOVERNOR"), OPS("OPS"), PRODUCT_MANAGER("PRODUCT_MANAGER"), PRODUCT_STRATEGIST("PRODUCT_STRATEGIST"); + ADMIN("ADMIN"), DESIGNER("DESIGNER"), TESTER("TESTER"), GOVERNOR("GOVERNOR"), OPS("OPS"), PRODUCT_MANAGER("PRODUCT_MANAGER"), PRODUCT_STRATEGIST("PRODUCT_STRATEGIST"); - private String name; + private String name; - UserRoleEnum(String name) { - this.name = name; - } + UserRoleEnum(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java index fe5e5288b0..0dadef9292 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlConstants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,8 +22,8 @@ package org.openecomp.sdc.common.api; public interface YamlConstants { - String NODE_TYPES = "node_types"; - String INTERFACES = "interfaces"; - String TEMPLATE_VERSION = "template_version"; - String TEMPLATE_NAME = "template_name"; + public static final String NODE_TYPES = "node_types"; + public static final String INTERFACES = "interfaces"; + public static final String TEMPLATE_VERSION = "template_version"; + public static final String TEMPLATE_NAME = "template_name"; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java index 8daf335c25..1310ab170f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/YamlSuffixEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,36 +25,36 @@ import java.util.List; public enum YamlSuffixEnum { - YAML("YAML"), + YAML("YAML"), - yaml("yaml"), + yaml("yaml"), - YML("YML"), + YML("YML"), - yml("yml"); + yml("yml"); - YamlSuffixEnum(String suffix) { - this.suffix = suffix; - } + YamlSuffixEnum(String suffix) { + this.suffix = suffix; + } - private String suffix; + private String suffix; - public String getSuffix() { - return suffix; - } + public String getSuffix() { + return suffix; + } - public void setSuufix(String suffix) { - this.suffix = suffix; - } + public void setSuufix(String suffix) { + this.suffix = suffix; + } - public static List<String> getSuffixes() { + public static List<String> getSuffixes() { - List<String> arrayList = new ArrayList<>(); + List<String> arrayList = new ArrayList<>(); - for (YamlSuffixEnum yamlSuffixEnum : YamlSuffixEnum.values()) { - arrayList.add(yamlSuffixEnum.getSuffix()); - } + for (YamlSuffixEnum yamlSuffixEnum : YamlSuffixEnum.values()) { + arrayList.add(yamlSuffixEnum.getSuffix()); + } - return arrayList; - } + return arrayList; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java index 22df432afe..49f04d2ee1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,14 +25,14 @@ import com.jcabi.aspects.Loggable; @Loggable(prepend = true, value = Loggable.TRACE, trim = false) public abstract class AbsEcompErrorManager { - public static final String PARAM_STR = "%s"; + public static final String PARAM_STR = "%s"; - public abstract IEcompConfigurationManager getConfigurationManager(); + public abstract IEcompConfigurationManager getConfigurationManager(); - public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) { + public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) { - EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams); + EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams); - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java index fc5a2f0512..31499486de 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompClassification.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,20 +22,20 @@ package org.openecomp.sdc.common.config; public enum EcompClassification { - INFORMATION("I"), WARNING("W"), ERROR("E"), FATAL("F"); + INFORMATION("I"), WARNING("W"), ERROR("E"), FATAL("F"); - private String classification; + String classification; - EcompClassification(String classification) { - this.classification = classification; - } + EcompClassification(String classification) { + this.classification = classification; + } - public String getClassification() { - return classification; - } + public String getClassification() { + return classification; + } - public void setClassification(String classification) { - this.classification = classification; - } + public void setClassification(String classification) { + this.classification = classification; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java index 0763f9052e..e605366fcb 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java @@ -34,19 +34,19 @@ public enum EcompErrorCode { "Unable to connect to a valid ASDC Backend Server", "Please check connectivity from this FE instance towards BE or BE Load Balancer. Please check that parameters in FE configuration.yaml: beHost, beHttpPort and beSslPort point to a valid host and port values."), - E_205("ASDC Backend Recovery to either one of the following components: JanusGraph DB, Cassandra, Onboarding, UEB Cluster."), E_206( - "ASDC Backend connection recovery to JanusGraph DB."), E_207( - "ASDC Backend connection recovery to ElasticSearch."), E_208( - "ASDC Backend connection recovery to UEB Cluster."), E_209( - "Connectivity to ASDC BE Server is recovered."), E_210( - "Connection problem towards U-EB server. Reason: %s", - "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_211( - "Connection problem towards U-EB server. Cannot reach host %s", - "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_212( - "Couldn't resolve hostIP. Desciption: %s"), E_213( - "Site switch over was done. Site is now in %s mode"), E_214( - "Dmaap Connection problem."), E_299( - "Internal Connection problem. Description: %s"), + E_205("ASDC Backend Recovery to either one of the following components: JanusGraph DB, Cassandra, Onboarding, UEB Cluster."), E_206( + "ASDC Backend connection recovery to JanusGraph DB."), E_208( + "ASDC Backend connection recovery to UEB Cluster."), E_209( + "Connectivity to ASDC BE Server is recovered."), E_210( + "Connection problem towards U-EB server. Reason: %s", + "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_211( + "Connection problem towards U-EB server. Cannot reach host %s", + "Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_212( + "Couldn't resolve hostIP. Desciption: %s"), E_213( + "Site switch over was done. Site is now in %s mode"), E_214( + "Dmaap Connection problem."), E_220( + "User HTTP session is expired"), E_299( + "Internal Connection problem. Description: %s"), // [resource/service/product] E_300("Mandatory %s Component %s cannot be found in repository"), diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java index 89f4d17977..b44ceea678 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,7 @@ package org.openecomp.sdc.common.config; import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; import java.util.Arrays; import java.util.HashMap; @@ -29,135 +30,133 @@ import java.util.regex.Pattern; public class EcompErrorConfiguration extends BasicConfiguration { - private static final int LOWEST_ERROR_VALID_CODE = 3010; - private static final int HIGHEST_ERROR_VALID_CODE = 9999; - private Map<String, EcompErrorInfo> errors = new HashMap<>(); - static final String ECODE_PREFIX = "ASDC_"; - private static final Pattern ECODE_PATTERN = Pattern.compile("^" + ECODE_PREFIX + "\\d{4}$"); - - public Map<String, EcompErrorInfo> getErrors() { - return errors; - } - - public void setErrors(Map<String, EcompErrorInfo> errors) { - // Validating ecomp-error-configuration.yaml - for (Map.Entry<String, EcompErrorInfo> ecompErrorInfo : errors.entrySet()) { - String ecompErrorName = ecompErrorInfo.getKey(); - EcompErrorInfo res = validateEcompErrorInfo(ecompErrorName, ecompErrorInfo.getValue()); - if (res != null) { - // Validation failed! - EcompErrorLogUtil.logEcompError(EcompErrorName.EcompConfigFileFormat, res, this.getClass().getName()); - return; - } - } - // Validation passed - this.errors = errors; - } - - public EcompErrorInfo getEcompErrorInfo(String key) { - EcompErrorInfo clone = null; - EcompErrorInfo other = errors.get(key); - if (other != null) { - clone = new EcompErrorInfo(); - clone.cloneData(other); - } - return clone; - } - - protected EcompErrorInfo validateEcompErrorInfo(String ecompErrorName, EcompErrorInfo ecompErrorInfoToValidate) { - if (ecompErrorInfoToValidate == null) { - return getErrorInfoForConfigFile("error " + ecompErrorName + " not found "); - } - String type = ecompErrorInfoToValidate.getType(); - if (type == null) { - return getErrorInfoForConfigFile("empty error type for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); - } - try { - EcompErrorType.valueOf(type); - } catch (IllegalArgumentException e) { - return getErrorInfoForConfigFile("error type " + type + " is invalid for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); - } - - String severity = ecompErrorInfoToValidate.getSeverity(); - if (severity == null) { - return getErrorInfoForConfigFile("empty error severity for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); - } - try { - EcompErrorSeverity.valueOf(severity); - } catch (IllegalArgumentException e) { - return getErrorInfoForConfigFile("error severity " + severity + " is invalid for error " + ecompErrorName - + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); - } - String alarmSeverity = ecompErrorInfoToValidate.getAlarmSeverity(); - if (alarmSeverity == null) { - return getErrorInfoForConfigFile("empty error alarm for error " + ecompErrorName - + ", , value should be one of the following: " + Arrays.asList(EcompAlarmSeverity.values())); - } - try { - EcompAlarmSeverity.valueOf(alarmSeverity); - } catch (IllegalArgumentException e) { - return getErrorInfoForConfigFile("error alarm severity " + alarmSeverity + " is invalid for error " - + ecompErrorName + ", , value should be one of the following: " - + Arrays.asList(EcompAlarmSeverity.values())); - } - - String code = ecompErrorInfoToValidate.getCode(); - if (code != null && ECODE_PATTERN.matcher(code).matches()) { - String[] split = code.split("_"); - int parseInt = Integer.parseInt(split[1]); - if (parseInt < LOWEST_ERROR_VALID_CODE || parseInt > HIGHEST_ERROR_VALID_CODE) { - return getErrorInfoForInvalidCode(code, ecompErrorName); - } - } else { - return getErrorInfoForInvalidCode(code, ecompErrorName); - } - return null; - } - - private EcompErrorInfo getErrorInfoForInvalidCode(String code, String ecompErrorName) { - return getErrorInfoForConfigFile("error code " + code + " is invalid for error " + ecompErrorName - + ", should be in format ASDC_[3010-9999]"); - } - - private EcompErrorInfo getErrorInfoForConfigFile(String errorMessage) { - EcompErrorInfo ecompErrorInfo = new EcompErrorInfo(); - ecompErrorInfo.setCode(ECODE_PREFIX + "3000"); - ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name()); - ecompErrorInfo.setSeverity(EcompErrorSeverity.FATAL.name()); - ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.CRITICAL.name()); - ecompErrorInfo.setDescription(errorMessage); - return ecompErrorInfo; - } - - @Override - public String toString() { - return "EcompErrorConfiguration [errors=" + errors + "]"; - } - - /******************************* - * enums - */ - - public enum EcompErrorType { - RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM; - } - - public enum EcompAlarmSeverity { - CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE; - } - - public enum EcompErrorSeverity { - INFO, WARN, ERROR, FATAL; - } - - public enum EcompErrorSeverityPrefix { - I, W, E, F; - } - - public static void main(String[] args) { - System.out.println(Arrays.asList(EcompErrorType.values())); - } + private Map<String, EcompErrorInfo> errors = new HashMap<>(); + static final String ECODE_PREFIX = "ASDC_"; + private static final Pattern ECODE_PATTERN = Pattern.compile("^" + ECODE_PREFIX + "\\d{4}$"); + + public Map<String, EcompErrorInfo> getErrors() { + return errors; + } + + public void setErrors(Map<String, EcompErrorInfo> errors) { + // Validating ecomp-error-configuration.yaml + for (Map.Entry<String, EcompErrorInfo> ecompErrorInfo : errors.entrySet()) { + String ecompErrorName = ecompErrorInfo.getKey(); + EcompErrorInfo res = validateEcompErrorInfo(ecompErrorName, ecompErrorInfo.getValue()); + if (res != null) { + // Validation failed! + EcompErrorLogUtil.logEcompError(EcompErrorName.EcompConfigFileFormat, res, this.getClass().getName()); + return; + } + } + // Validation passed + this.errors = errors; + } + + public EcompErrorInfo getEcompErrorInfo(String key) { + EcompErrorInfo clone = null; + EcompErrorInfo other = errors.get(key); + if (other != null) { + clone = new EcompErrorInfo(); + clone.cloneData(other); + } + return clone; + } + + protected EcompErrorInfo validateEcompErrorInfo(String ecompErrorName, EcompErrorInfo ecompErrorInfoToValidate) { + if (ecompErrorInfoToValidate == null) { + return getErrorInfoForConfigFile("error " + ecompErrorName + " not found "); + } + String type = ecompErrorInfoToValidate.getType(); + if (type == null) { + return getErrorInfoForConfigFile("empty error type for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); + } + try { + EcompErrorType.valueOf(type); + } catch (IllegalArgumentException e) { + return getErrorInfoForConfigFile("error type " + type + " is invalid for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorType.values())); + } + + String severity = ecompErrorInfoToValidate.getSeverity(); + if (severity == null) { + return getErrorInfoForConfigFile("empty error severity for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); + } + try { + EcompErrorSeverity.valueOf(severity); + } catch (IllegalArgumentException e) { + return getErrorInfoForConfigFile("error severity " + severity + " is invalid for error " + ecompErrorName + + ", value should be one of the following: " + Arrays.asList(EcompErrorSeverity.values())); + } + String alarmSeverity = ecompErrorInfoToValidate.getAlarmSeverity(); + if (alarmSeverity == null) { + return getErrorInfoForConfigFile("empty error alarm for error " + ecompErrorName + + ", , value should be one of the following: " + Arrays.asList(EcompAlarmSeverity.values())); + } + try { + EcompAlarmSeverity.valueOf(alarmSeverity); + } catch (IllegalArgumentException e) { + return getErrorInfoForConfigFile("error alarm severity " + alarmSeverity + " is invalid for error " + + ecompErrorName + ", , value should be one of the following: " + + Arrays.asList(EcompAlarmSeverity.values())); + } + + String code = ecompErrorInfoToValidate.getCode(); + if (code != null && ECODE_PATTERN.matcher(code).matches()) { + String[] split = code.split("_"); + int parseInt = Integer.parseInt(split[1]); + if (parseInt < 3010 || parseInt > 9999) { + return getErrorInfoForInvalidCode(code, ecompErrorName); + } + } else { + return getErrorInfoForInvalidCode(code, ecompErrorName); + } + return null; + } + + private EcompErrorInfo getErrorInfoForInvalidCode(String code, String ecompErrorName) { + return getErrorInfoForConfigFile("error code " + code + " is invalid for error " + ecompErrorName + + ", should be in format ASDC_[3010-9999]"); + } + + private EcompErrorInfo getErrorInfoForConfigFile(String errorMessage) { + EcompErrorInfo ecompErrorInfo = new EcompErrorInfo(); + ecompErrorInfo.setCode(ECODE_PREFIX + "3000"); + ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name()); + ecompErrorInfo.setSeverity(EcompErrorSeverity.FATAL.name()); + ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.CRITICAL.name()); + ecompErrorInfo.setDescription(errorMessage); + return ecompErrorInfo; + } + + @Override + public String toString() { + return "EcompErrorConfiguration [errors=" + errors + "]"; + } + + /******************************* + * enums + */ + + public enum EcompErrorType { + RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM; + } + + public enum EcompAlarmSeverity { + CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE; + } + + public enum EcompErrorSeverity { + INFO, WARN, ERROR, FATAL; + } + + public enum EcompErrorSeverityPrefix { + I, W, E, F; + } + + public static void main(String[] args) { + System.out.println(Arrays.asList(EcompErrorType.values())); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java index 58e19a7347..bed7255057 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java @@ -30,6 +30,9 @@ public enum EcompErrorEnum { DmaapHealthCheckError(EcompErrorCode.E_214, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + SessionExpiredAuthenticationError(EcompErrorCode.E_220, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, + EcompClassification.ERROR), + InternalAuthenticationInfo(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), InternalAuthenticationWarning(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MINOR, @@ -42,8 +45,6 @@ public enum EcompErrorEnum { BeHealthCheckRecovery(EcompErrorCode.E_205, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), BeHealthCheckJanusGraphRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), BeHealthCheckElasticSearchRecovery(EcompErrorCode.E_207, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), BeHealthCheckUebClusterRecovery(EcompErrorCode.E_208, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), FeHealthCheckRecovery(EcompErrorCode.E_209, ErrorType.RECOVERY, @@ -55,9 +56,8 @@ public enum EcompErrorEnum { BeHealthCheckRecovery), BeHealthCheckJanusGraphError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR, BeHealthCheckJanusGraphRecovery), BeHealthCheckElasticSearchError( - EcompErrorCode.E_202, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, - BeHealthCheckElasticSearchRecovery), BeHealthCheckUebClusterError(EcompErrorCode.E_203, + EcompClassification.ERROR, BeHealthCheckJanusGraphRecovery), + BeHealthCheckUebClusterError(EcompErrorCode.E_203, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, BeHealthCheckUebClusterRecovery), FeHealthCheckError(EcompErrorCode.E_204, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, @@ -410,11 +410,13 @@ public enum EcompErrorEnum { * AlarmSeverity.CRITICAL, EcompClassification.FATAL), */; - private EcompErrorCode ecompErrorCode; - private ErrorType eType; - private AlarmSeverity alarmSeverity; - private EcompClassification classification; - private EcompErrorEnum clearCode; + ; + + EcompErrorCode ecompErrorCode; + ErrorType eType; + AlarmSeverity alarmSeverity; + EcompClassification classification; + EcompErrorEnum clearCode; EcompErrorEnum(EcompErrorCode ecompErrorCode, ErrorType eType, AlarmSeverity alarmSeverity, EcompClassification classification, EcompErrorEnum clearCode) { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java index 75ad74c56b..e1fd34b26d 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,57 +22,57 @@ package org.openecomp.sdc.common.config; public class EcompErrorInfo { - private String type; - private String code; - private String severity; - private String description; - private String alarmSeverity; + private String type; + private String code; + private String severity; + private String description; + private String alarmSeverity; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public String getSeverity() { - return severity; - } + public String getSeverity() { + return severity; + } - public void setSeverity(String severity) { - this.severity = severity; - } + public void setSeverity(String severity) { + this.severity = severity; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getAlarmSeverity() { - return alarmSeverity; - } + public String getAlarmSeverity() { + return alarmSeverity; + } - public void setAlarmSeverity(String alarmSeverity) { - this.alarmSeverity = alarmSeverity; - } + public void setAlarmSeverity(String alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } - public void cloneData(EcompErrorInfo other) { - this.type = other.getType(); - this.severity = other.getSeverity(); - this.description = other.getDescription(); - this.code = other.getCode(); - this.alarmSeverity = other.getAlarmSeverity(); - } + public void cloneData(EcompErrorInfo other) { + this.type = other.getType(); + this.severity = other.getSeverity(); + this.description = other.getDescription(); + this.code = other.getCode(); + this.alarmSeverity = other.getAlarmSeverity(); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java index 933b510e91..feb3ea6e68 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorLogUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.config; import fj.data.Either; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompErrorSeverity; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.slf4j.MDC; @@ -33,133 +33,133 @@ import java.util.Locale; public class EcompErrorLogUtil { - private static final String ECOMP_ERROR_TMPL = "ETYPE = \"%s\" ENAME = \"%s\" ECODE = \"%s\" ECONTEXT = \"%s\" EDESC = \"%s\""; - private static Logger log = Logger.getLogger(EcompErrorLogUtil.class.getName()); - private static final String FATAL_ERROR_PREFIX = "FATAL ERROR!! "; - - public static void logEcompError(EcompErrorName ecompErrorName, EcompErrorInfo ecompErrorInfo, - String ecompErrorContext, String... ecompDescriptionParams) { - if (ecompErrorInfo != null) { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - String description = ecompErrorInfo.getDescription(); - String severityStr = ecompErrorInfo.getSeverity(); - EcompErrorConfiguration.EcompErrorSeverity severity = EcompErrorSeverity.ERROR; - // Since there is no FATAL log level, this is how we distinguish - // the FATAL errors - if (severityStr.equals(EcompErrorConfiguration.EcompErrorSeverity.FATAL.name())) { - description = FATAL_ERROR_PREFIX + description; - severity = EcompErrorSeverity.FATAL; - } else if (severityStr.equals(EcompErrorConfiguration.EcompErrorSeverity.WARN.name())) { - severity = EcompErrorSeverity.WARN; - } else if (severityStr.equals(EcompErrorConfiguration.EcompErrorSeverity.INFO.name())) { - severity = EcompErrorSeverity.INFO; - } - - MDC.put("alarmSeverity", ecompErrorInfo.getAlarmSeverity()); - // else it stays ERROR - formatter.format(ECOMP_ERROR_TMPL, ecompErrorInfo.getType(), ecompErrorName.name(), - ecompErrorInfo.getCode(), ecompErrorContext, description); + private static String ECOMP_ERROR_TMPL = "ETYPE = \"%s\" ENAME = \"%s\" ECODE = \"%s\" ECONTEXT = \"%s\" EDESC = \"%s\""; + private static Logger log = Logger.getLogger(EcompErrorLogUtil.class.getName()); + private static final String FATAL_ERROR_PREFIX = "FATAL ERROR!! "; + + public static void logEcompError(EcompErrorName ecompErrorName, EcompErrorInfo ecompErrorInfo, + String ecompErrorContext, String... ecompDescriptionParams) { + if (ecompErrorInfo != null) { + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + String description = ecompErrorInfo.getDescription(); + String severityStr = ecompErrorInfo.getSeverity(); + EcompErrorSeverity severity = EcompErrorSeverity.ERROR; + // Since there is no FATAL log level, this is how we distinguish + // the FATAL errors + if (severityStr.equals(EcompErrorSeverity.FATAL.name())) { + description = FATAL_ERROR_PREFIX + description; + severity = EcompErrorSeverity.FATAL; + } else if (severityStr.equals(EcompErrorSeverity.WARN.name())) { + severity = EcompErrorSeverity.WARN; + } else if (severityStr.equals(EcompErrorSeverity.INFO.name())) { + severity = EcompErrorSeverity.INFO; + } + + MDC.put("alarmSeverity", ecompErrorInfo.getAlarmSeverity()); + // else it stays ERROR + formatter.format(ECOMP_ERROR_TMPL, ecompErrorInfo.getType(), ecompErrorName.name(), + ecompErrorInfo.getCode(), ecompErrorContext, description); log.error(severity, EcompLoggerErrorCode.getByValue(ecompErrorInfo.getCode()), ecompErrorContext, ecompErrorContext, description); } finally { - formatter.close(); - MDC.remove("alarmSeverity"); - } - } - } - - public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, - String... ecompDescriptionParams) { - logEcompError(ecompErrorContext, ecompErrorEnum, true, ecompDescriptionParams); - } - - public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, boolean logMissingParams, - String... ecompDescriptionParams) { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - String description; - - Either<String, Boolean> setDescriptionParamsResult = setDescriptionParams(ecompErrorEnum, - ecompDescriptionParams); - if (setDescriptionParamsResult.isLeft()) { - description = setDescriptionParamsResult.left().value(); - } else { - EcompErrorEnum mismatchErrorEnum = EcompErrorEnum.EcompMismatchParam; - if (logMissingParams) { - logEcompError("logEcompError", mismatchErrorEnum, false, ecompErrorEnum.name()); - } else { - log.info("Failed to log the error code {}", mismatchErrorEnum); - } - return; - } - EcompClassification classification = ecompErrorEnum.getClassification(); - - EcompErrorConfiguration.EcompErrorSeverity severity = EcompErrorSeverity.ERROR; - // Since there is no FATAL log level, this is how we distinguish the - // FATAL errors - if (classification == EcompClassification.FATAL) { - description = FATAL_ERROR_PREFIX + description; - severity = EcompErrorSeverity.FATAL; - } else if (classification == EcompClassification.WARNING) { - severity = EcompErrorSeverity.WARN; - } else if (classification == EcompClassification.INFORMATION) { - severity = EcompErrorSeverity.INFO; - } - - String eCode = createEcode(ecompErrorEnum); - - MDC.put("alarmSeverity", ecompErrorEnum.getAlarmSeverity().name()); - // else it stays ERROR - formatter.format(ECOMP_ERROR_TMPL, ecompErrorEnum.geteType(), ecompErrorEnum.name(), eCode, - ecompErrorContext, description); + formatter.close(); + MDC.remove("alarmSeverity"); + } + } + } + + public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, + String... ecompDescriptionParams) { + logEcompError(ecompErrorContext, ecompErrorEnum, true, ecompDescriptionParams); + } + + public static void logEcompError(String ecompErrorContext, EcompErrorEnum ecompErrorEnum, boolean logMissingParams, + String... ecompDescriptionParams) { + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + String description; + + Either<String, Boolean> setDescriptionParamsResult = setDescriptionParams(ecompErrorEnum, + ecompDescriptionParams); + if (setDescriptionParamsResult.isLeft()) { + description = setDescriptionParamsResult.left().value(); + } else { + EcompErrorEnum mismatchErrorEnum = EcompErrorEnum.EcompMismatchParam; + if (logMissingParams) { + logEcompError("logEcompError", mismatchErrorEnum, false, ecompErrorEnum.name()); + } else { + log.info("Failed to log the error code {}", mismatchErrorEnum); + } + return; + } + EcompClassification classification = ecompErrorEnum.getClassification(); + + EcompErrorSeverity severity = EcompErrorSeverity.ERROR; + // Since there is no FATAL log level, this is how we distinguish the + // FATAL errors + if (classification == EcompClassification.FATAL) { + description = FATAL_ERROR_PREFIX + description; + severity = EcompErrorSeverity.FATAL; + } else if (classification == EcompClassification.WARNING) { + severity = EcompErrorSeverity.WARN; + } else if (classification == EcompClassification.INFORMATION) { + severity = EcompErrorSeverity.INFO; + } + + String eCode = createEcode(ecompErrorEnum); + + MDC.put("alarmSeverity", ecompErrorEnum.alarmSeverity.name()); + // else it stays ERROR + formatter.format(ECOMP_ERROR_TMPL, ecompErrorEnum.geteType(), ecompErrorEnum.name(), eCode, + ecompErrorContext, description); log.error(severity, EcompLoggerErrorCode.getByValue(ecompErrorEnum.getEcompErrorCode().name()), ecompErrorContext, ecompErrorContext, description); - } finally { - formatter.close(); - MDC.remove("alarmSeverity"); - } - } + } finally { + formatter.close(); + MDC.remove("alarmSeverity"); + } + } - public static String createEcode(EcompErrorEnum ecompErrorEnum) { + public static String createEcode(EcompErrorEnum ecompErrorEnum) { - EcompClassification classification = ecompErrorEnum.getClassification(); - String ecompErrorCode = ecompErrorEnum.getEcompErrorCode().name(); + EcompClassification classification = ecompErrorEnum.getClassification(); + String ecompErrorCode = ecompErrorEnum.getEcompErrorCode().name(); - String ecodeNumber = ecompErrorCode.substring(ecompErrorCode.indexOf("_") + 1); + String ecodeNumber = ecompErrorCode.substring(ecompErrorCode.indexOf("_") + 1); return "ASDC" + ecodeNumber + classification.getClassification(); - } - - private static Either<String, Boolean> setDescriptionParams(EcompErrorEnum ecompErrorEnum, - String... descriptionParams) { - String description = ecompErrorEnum.getEcompErrorCode().getDescription(); - - // Counting number of params in description - int countMatches = StringUtils.countMatches(description, AbsEcompErrorManager.PARAM_STR); - // Catching cases when there are more params passed than there are in - // the description (formatter will ignore extra params and won't throw - // exception) - if (countMatches != descriptionParams.length) { - return Either.right(false); - } - // Setting params of the description if any - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - try { - formatter.format(description, (Object[]) descriptionParams).toString(); - return Either.left(formatter.toString()); - } catch (IllegalFormatException e) { - // Number of passed params doesn't match number of params in config - // file - return Either.right(false); - } finally { - formatter.close(); - } - - } + } + + private static Either<String, Boolean> setDescriptionParams(EcompErrorEnum ecompErrorEnum, + String... descriptionParams) { + String description = ecompErrorEnum.getEcompErrorCode().getDescription(); + + // Counting number of params in description + int countMatches = StringUtils.countMatches(description, AbsEcompErrorManager.PARAM_STR); + // Catching cases when there are more params passed than there are in + // the description (formatter will ignore extra params and won't throw + // exception) + if (countMatches != descriptionParams.length) { + return Either.right(false); + } + // Setting params of the description if any + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + formatter.format(description, (Object[]) descriptionParams).toString(); + return Either.left(formatter.toString()); + } catch (IllegalFormatException e) { + // Number of passed params doesn't match number of params in config + // file + return Either.right(false); + } finally { + formatter.close(); + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java index b33bc45520..5da7808376 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,23 +21,23 @@ package org.openecomp.sdc.common.config; public enum EcompErrorName { - // general - EcompConfigFileFormat, EcompErrorNotFound, EcompErrorDescParamsMismatch, + // general + EcompConfigFileFormat, EcompErrorNotFound, EcompErrorDescParamsMismatch, - // FE - FeHealthCheckConnectionError, FeHealthCheckRecovery /* Recovery */, FeHttpLoggingError, FePortalServletError, FeHealthCheckGeneralError, + // FE + FeHealthCheckConnectionError, FeHealthCheckRecovery /* Recovery */, FeHttpLoggingError, FePortalServletError, FeHealthCheckGeneralError, - // BE section here... - BeHealthCheckError, BeHealthCheckRecovery, /* Recovery */ - BeRestApiGeneralError, BeInitializationError, BeResourceMissingError, BeServiceMissingError, BeMissingArtifactInformationError, BeArtifactMissingError, BeArtifactPayloadInvalid, BeUserMissingError, BeArtifactInformationInvalidError, BeIncorrectServiceError, BeFailedAddingResourceInstanceError, - // BeFailedDeletingResourceInstanceError, - BeFailedAddingCapabilityTypeError, BeCapabilityTypeMissingError, BeInterfaceMissingError, - // BeRepositoryObjectNotFoundError, - // BeRepositoryDeleteError, - // BeRepositoryQueryError, - BeDaoSystemError, BeSystemError, BeInvalidConfigurationError, BeMissingConfigurationError, BeUebConnectionError, BeUebObjectNotFoundError, BeUebSystemError, BeDistributionEngineSystemError, BeDistributionEngineInvalidArtifactType, BeConfigurationInvalidListSizeError, BeUebAuthenticationError, BeUebUnkownHostError, BeInvalidTypeError, BeInvalidValueError, BeFailedLockObjectError, BeInvalidJsonInput, BeDistributionMissingError, ErrorConfigFileFormat, - // model - BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError, - //dmaap - DmaapHealthCheckRecovery, DmaapHealthCheckError; + // BE section here... + BeHealthCheckError, BeHealthCheckRecovery, /* Recovery */ + BeRestApiGeneralError, BeInitializationError, BeResourceMissingError, BeServiceMissingError, BeMissingArtifactInformationError, BeArtifactMissingError, BeArtifactPayloadInvalid, BeUserMissingError, BeArtifactInformationInvalidError, BeIncorrectServiceError, BeFailedAddingResourceInstanceError, + // BeFailedDeletingResourceInstanceError, + BeFailedAddingCapabilityTypeError, BeCapabilityTypeMissingError, BeInterfaceMissingError, + // BeRepositoryObjectNotFoundError, + // BeRepositoryDeleteError, + // BeRepositoryQueryError, + BeDaoSystemError, BeSystemError, BeInvalidConfigurationError, BeMissingConfigurationError, BeUebConnectionError, BeUebObjectNotFoundError, BeUebSystemError, BeDistributionEngineSystemError, BeDistributionEngineInvalidArtifactType, BeConfigurationInvalidListSizeError, BeUebAuthenticationError, BeUebUnkownHostError, BeInvalidTypeError, BeInvalidValueError, BeFailedLockObjectError, BeInvalidJsonInput, BeDistributionMissingError, ErrorConfigFileFormat, + // model + BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError, + //dmaap + DmaapHealthCheckRecovery , DmaapHealthCheckError; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java index 3ecfa7914a..c16d8d329b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompConfigurationManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.config; public interface IEcompConfigurationManager { - EcompErrorConfiguration getEcompErrorConfiguration(); + public EcompErrorConfiguration getEcompErrorConfiguration(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java index d46ead42a9..f59385e2f5 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/generation/GenerateEcompErrorsCsv.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,8 +24,6 @@ import org.openecomp.sdc.common.config.EcompErrorEnum; import org.openecomp.sdc.common.config.EcompErrorEnum.AlarmSeverity; import org.openecomp.sdc.common.config.EcompErrorEnum.ErrorType; import org.openecomp.sdc.common.config.EcompErrorLogUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; @@ -35,198 +33,199 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class GenerateEcompErrorsCsv { - private static final Logger LOGGER = LoggerFactory.getLogger(GenerateEcompErrorsCsv.class); - - private static final String DATE_FORMAT = "dd-M-yyyy-hh-mm-ss"; + private static Logger log = LoggerFactory.getLogger(GenerateEcompErrorsCsv.class); + private static String DATE_FORMAT = "dd-M-yyyy-hh-mm-ss"; - private static final String NEW_LINE = System.getProperty("line.separator"); + private static String NEW_LINE = System.getProperty("line.separator"); - private static void usage() { - System.out.println("java org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv <target folder>"); - System.exit(1); - } + private static void usage() { + System.out.println("java org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv <target folder>"); + System.exit(1); + } - public static void main(String[] args) { + public static void main(String[] args) { - String targetFolder = "target"; - if (args.length > 1) { - targetFolder = args[0]; - } + String targetFolder = "target"; + if (args.length > 1) { + targetFolder = args[0]; + } - GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); + GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); - ecompErrorsCsv.generateEcompErrorsCsvFile(targetFolder, true); - } + ecompErrorsCsv.generateEcompErrorsCsvFile(targetFolder, true); + } - public static class EcompErrorRow { + public static class EcompErrorRow { - private String errorName; - private String errorCode; - private String description; - private ErrorType errorType; - private AlarmSeverity alarmSeverity; - private String cleanErrorCode; - private String resolution; + String errorName; + String errorCode; + String description; + ErrorType errorType; + AlarmSeverity alarmSeverity; + String cleanErrorCode; + String resolution; - public String getErrorName() { - return errorName; - } + public String getErrorName() { + return errorName; + } - public void setErrorName(String errorName) { - this.errorName = errorName; - } + public void setErrorName(String errorName) { + this.errorName = errorName; + } - public String getErrorCode() { - return errorCode; - } + public String getErrorCode() { + return errorCode; + } - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public ErrorType getErrorType() { - return errorType; - } + public ErrorType getErrorType() { + return errorType; + } - public void setErrorType(ErrorType errorType) { - this.errorType = errorType; - } + public void setErrorType(ErrorType errorType) { + this.errorType = errorType; + } - public AlarmSeverity getAlarmSeverity() { - return alarmSeverity; - } + public AlarmSeverity getAlarmSeverity() { + return alarmSeverity; + } - public void setAlarmSeverity(AlarmSeverity alarmSeverity) { - this.alarmSeverity = alarmSeverity; - } + public void setAlarmSeverity(AlarmSeverity alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } - public String getCleanErrorCode() { - return cleanErrorCode; - } + public String getCleanErrorCode() { + return cleanErrorCode; + } - public void setCleanErrorCode(String cleanErrorCode) { - this.cleanErrorCode = cleanErrorCode; - } + public void setCleanErrorCode(String cleanErrorCode) { + this.cleanErrorCode = cleanErrorCode; + } - public String getResolution() { - return resolution; - } + public String getResolution() { + return resolution; + } - public void setResolution(String resolution) { - this.resolution = resolution; - } + public void setResolution(String resolution) { + this.resolution = resolution; + } - } + } - public boolean generateEcompErrorsCsvFile(String targetFolder, boolean addTimeToFileName) { + public boolean generateEcompErrorsCsvFile(String targetFolder, boolean addTimeToFileName) { - targetFolder += File.separator; + targetFolder += File.separator; - boolean result = false; - String dateFormatted = ""; + boolean result = false; + String dateFormatted = ""; - if (addTimeToFileName) { - DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); + if (addTimeToFileName) { + DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); - Date date = new Date(); + Date date = new Date(); - dateFormatted = "." + dateFormat.format(date); + dateFormatted = "." + dateFormat.format(date); - } + } - String outputFile = targetFolder + "ecompErrorCodes" + dateFormatted + ".csv"; + String outputFile = targetFolder + "ecompErrorCodes" + dateFormatted + ".csv"; - try (FileWriter writer = new FileWriter(outputFile)) { + try(FileWriter writer = new FileWriter(outputFile)) { - List<EcompErrorRow> errors = new ArrayList<>(); + List<EcompErrorRow> errors = new ArrayList<>(); - for (EcompErrorEnum ecompErrorEnum : EcompErrorEnum.values()) { + for (EcompErrorEnum ecompErrorEnum : EcompErrorEnum.values()) { - EcompErrorRow ecompErrorRow = new EcompErrorRow(); + EcompErrorRow ecompErrorRow = new EcompErrorRow(); - String errorCode = EcompErrorLogUtil.createEcode(ecompErrorEnum); + String errorCode = EcompErrorLogUtil.createEcode(ecompErrorEnum); - EcompErrorEnum clearCodeEnum = ecompErrorEnum.getClearCode(); - String cleanErrorCode = null; - if (clearCodeEnum != null) { - cleanErrorCode = EcompErrorLogUtil.createEcode(clearCodeEnum); - } + EcompErrorEnum clearCodeEnum = ecompErrorEnum.getClearCode(); + String cleanErrorCode = null; + if (clearCodeEnum != null) { + cleanErrorCode = EcompErrorLogUtil.createEcode(clearCodeEnum); + } - ecompErrorRow.setAlarmSeverity(ecompErrorEnum.getAlarmSeverity()); - ecompErrorRow.setCleanErrorCode(cleanErrorCode); - ecompErrorRow.setDescription(ecompErrorEnum.getEcompErrorCode().getDescription()); - ecompErrorRow.setErrorCode(errorCode); - ecompErrorRow.setErrorName(ecompErrorEnum.name().toString()); - ecompErrorRow.setErrorType(ecompErrorEnum.geteType()); - ecompErrorRow.setResolution(ecompErrorEnum.getEcompErrorCode().getResolution()); + ecompErrorRow.setAlarmSeverity(ecompErrorEnum.getAlarmSeverity()); + ecompErrorRow.setCleanErrorCode(cleanErrorCode); + ecompErrorRow.setDescription(ecompErrorEnum.getEcompErrorCode().getDescription()); + ecompErrorRow.setErrorCode(errorCode); + ecompErrorRow.setErrorName(ecompErrorEnum.name().toString()); + ecompErrorRow.setErrorType(ecompErrorEnum.geteType()); + ecompErrorRow.setResolution(ecompErrorEnum.getEcompErrorCode().getResolution()); - errors.add(ecompErrorRow); - } + errors.add(ecompErrorRow); + } - writeHeaders(writer); + writeHeaders(writer); - for (EcompErrorRow ecompErrorRow : errors) { - writer.append(addInvertedCommas(ecompErrorRow.getErrorCode())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getErrorType().toString())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getDescription())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getResolution())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getAlarmSeverity().toString())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getErrorName())); - writer.append(','); - writer.append(addInvertedCommas(ecompErrorRow.getCleanErrorCode())); - writer.append(NEW_LINE); - } + for (EcompErrorRow ecompErrorRow : errors) { + writer.append(addInvertedCommas(ecompErrorRow.getErrorCode())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getErrorType().toString())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getDescription())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getResolution())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getAlarmSeverity().toString())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getErrorName())); + writer.append(','); + writer.append(addInvertedCommas(ecompErrorRow.getCleanErrorCode())); + writer.append(NEW_LINE); + } - result = true; + result = true; - } catch (Exception e) { - LOGGER.info("generate Ecomp Errors Csv File failed - {}", e); - } + } catch (Exception e) { + log.info("generate Ecomp Errors Csv File failed - {}" , e); + } - return result; - } + return result; + } - private void writeHeaders(FileWriter writer) throws IOException { + private void writeHeaders(FileWriter writer) throws IOException { - writer.append("\"ERROR CODE\""); - writer.append(','); - writer.append("\"ERROR TYPE\""); - writer.append(','); - writer.append("\"DESCRIPTION\""); - writer.append(','); - writer.append("\"RESOLUTION\""); - writer.append(','); - writer.append("\"ALARM SEVERITY\""); - writer.append(','); - writer.append("\"ERROR NAME\""); - writer.append(','); - writer.append("\"CLEAN CODE\""); - writer.append(NEW_LINE); - } + writer.append("\"ERROR CODE\""); + writer.append(','); + writer.append("\"ERROR TYPE\""); + writer.append(','); + writer.append("\"DESCRIPTION\""); + writer.append(','); + writer.append("\"RESOLUTION\""); + writer.append(','); + writer.append("\"ALARM SEVERITY\""); + writer.append(','); + writer.append("\"ERROR NAME\""); + writer.append(','); + writer.append("\"CLEAN CODE\""); + writer.append(NEW_LINE); + } - private String addInvertedCommas(String str) { + private String addInvertedCommas(String str) { - if (str == null) { - return "\"\""; - } + if (str == null) { + return "\"\""; + } - return "\"" + str + "\""; - } + return "\"" + str + "\""; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java index 57752ae420..06b2452d82 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKey.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,92 +23,92 @@ package org.openecomp.sdc.common.datastructure; import java.util.Date; public enum AuditingFieldsKey { - // General - AUDIT_TIMESTAMP(Date.class, "TIMESTAMP"), - AUDIT_ACTION(String.class, "ACTION"), - AUDIT_MODIFIER_NAME(String.class, "MODIFIER_ID"), - AUDIT_MODIFIER_UID(String.class, "MODIFIER"), - AUDIT_STATUS(String.class, "STATUS"), - AUDIT_DESC(String.class, "DESC"), - AUDIT_SERVICE_INSTANCE_ID(String.class, "SERVICE_INSTANCE_ID"), - AUDIT_INVARIANT_UUID(String.class, "INVARIANT_UUID"), - AUDIT_REQUEST_ID(String.class, "REQUEST_ID"), + // General + AUDIT_TIMESTAMP(Date.class, "TIMESTAMP"), + AUDIT_ACTION(String.class, "ACTION"), + AUDIT_MODIFIER_NAME(String.class, "MODIFIER_ID"), + AUDIT_MODIFIER_UID(String.class, "MODIFIER"), + AUDIT_STATUS(String.class, "STATUS"), + AUDIT_DESC(String.class, "DESC"), + AUDIT_SERVICE_INSTANCE_ID(String.class, "SERVICE_INSTANCE_ID"), + AUDIT_INVARIANT_UUID(String.class, "INVARIANT_UUID"), + AUDIT_REQUEST_ID(String.class, "REQUEST_ID"), - // Users administration - AUDIT_USER_UID(String.class, "USER"), - AUDIT_USER_BEFORE(String.class, "USER_BEFORE"), - AUDIT_USER_AFTER(String.class, "USER_AFTER"), - AUDIT_USER_DETAILS(String.class, "DETAILS"), + // Users administration + AUDIT_USER_UID(String.class, "USER"), + AUDIT_USER_BEFORE(String.class, "USER_BEFORE"), + AUDIT_USER_AFTER(String.class, "USER_AFTER"), + AUDIT_USER_DETAILS(String.class, "DETAILS"), - // Resource administration - AUDIT_RESOURCE_NAME(String.class, "RESOURCE_NAME"), - AUDIT_RESOURCE_TYPE(String.class, "RESOURCE_TYPE"), - AUDIT_RESOURCE_CURR_VERSION(String.class, "CURR_VERSION"), - AUDIT_RESOURCE_PREV_VERSION(String.class, "PREV_VERSION"), - AUDIT_RESOURCE_CURR_STATE(String.class, "CURR_STATE"), - AUDIT_RESOURCE_PREV_STATE(String.class, "PREV_STATE"), - AUDIT_RESOURCE_COMMENT(String.class, "COMMENT"), - AUDIT_ARTIFACT_DATA(String.class, "ARTIFACT_DATA"), - AUDIT_PREV_ARTIFACT_UUID(String.class, "PREV_ARTIFACT_UUID"), - AUDIT_CURR_ARTIFACT_UUID(String.class, "CURR_ARTIFACT_UUID"), - AUDIT_RESOURCE_DPREV_STATUS(String.class, "DPREV_STATUS"), - AUDIT_RESOURCE_DCURR_STATUS(String.class, "DCURR_STATUS"), - AUDIT_RESOURCE_TOSCA_NODE_TYPE(String.class, "TOSCA_NODE_TYPE"), - AUDIT_RESOURCE_URL(String.class, "RESOURCE_URL"), + // Resource administration + AUDIT_RESOURCE_NAME(String.class, "RESOURCE_NAME"), + AUDIT_RESOURCE_TYPE(String.class, "RESOURCE_TYPE"), + AUDIT_RESOURCE_CURR_VERSION(String.class, "CURR_VERSION"), + AUDIT_RESOURCE_PREV_VERSION(String.class, "PREV_VERSION"), + AUDIT_RESOURCE_CURR_STATE(String.class, "CURR_STATE"), + AUDIT_RESOURCE_PREV_STATE(String.class, "PREV_STATE"), + AUDIT_RESOURCE_COMMENT(String.class, "COMMENT"), + AUDIT_ARTIFACT_DATA(String.class, "ARTIFACT_DATA"), + AUDIT_PREV_ARTIFACT_UUID(String.class, "PREV_ARTIFACT_UUID"), + AUDIT_CURR_ARTIFACT_UUID(String.class, "CURR_ARTIFACT_UUID"), + AUDIT_RESOURCE_DPREV_STATUS(String.class, "DPREV_STATUS"), + AUDIT_RESOURCE_DCURR_STATUS(String.class, "DCURR_STATUS"), + AUDIT_RESOURCE_TOSCA_NODE_TYPE(String.class, "TOSCA_NODE_TYPE"), + AUDIT_RESOURCE_URL(String.class, "RESOURCE_URL"), - // Distribution Engine - AUDIT_DISTRIBUTION_ENVRIONMENT_NAME(String.class, "D_ENV"), - AUDIT_DISTRIBUTION_TOPIC_NAME(String.class, "TOPIC_NAME"), - AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME(String.class, "DNOTIF_TOPIC"), + // Distribution Engine + AUDIT_DISTRIBUTION_ENVRIONMENT_NAME(String.class, "D_ENV"), + AUDIT_DISTRIBUTION_TOPIC_NAME(String.class, "TOPIC_NAME"), + AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME(String.class, "DNOTIF_TOPIC"), AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME(String.class, "DSTATUS_TOPIC"), - AUDIT_DISTRIBUTION_ROLE(String.class, "ROLE"), - AUDIT_DISTRIBUTION_ID(String.class, "DID"), - AUDIT_DISTRIBUTION_API_KEY(String.class, "API_KEY"), - AUDIT_DISTRIBUTION_CONSUMER_ID(String.class, "CONSUMER_ID"), - AUDIT_DISTRIBUTION_RESOURCE_URL(String.class, "RESOURCE_URL"), - AUDIT_DISTRIBUTION_STATUS_TIME(String.class, "STATUS_TIME"), + AUDIT_DISTRIBUTION_ROLE(String.class, "ROLE"), + AUDIT_DISTRIBUTION_ID(String.class, "DID"), + AUDIT_DISTRIBUTION_API_KEY(String.class, "API_KEY"), + AUDIT_DISTRIBUTION_CONSUMER_ID(String.class, "CONSUMER_ID"), + AUDIT_DISTRIBUTION_RESOURCE_URL(String.class, "RESOURCE_URL"), + AUDIT_DISTRIBUTION_STATUS_TIME(String.class, "STATUS_TIME"), AUDIT_DISTRIBUTION_STATUS_DESC(String.class, "STATUS_DESC"), - AUDIT_DISTRIBUTION_ENVIRONMENT_ID(String.class, "ENV_ID"), - AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT(String.class, "VNF_WORKLOAD_CONTEXT"), - AUDIT_DISTRIBUTION_TENANT(String.class, "TENANT"), + AUDIT_DISTRIBUTION_ENVIRONMENT_ID(String.class, "ENV_ID"), + AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT(String.class, "VNF_WORKLOAD_CONTEXT"), + AUDIT_DISTRIBUTION_TENANT(String.class, "TENANT"), - // category - AUDIT_CATEGORY_NAME(String.class, "CATEGORY_NAME"), - AUDIT_SUB_CATEGORY_NAME(String.class, "SUB_CATEGORY_NAME"), - AUDIT_GROUPING_NAME(String.class, "GROUPING_NAME"), - AUDIT_DETAILS(String.class, "DETAILS"), + // category + AUDIT_CATEGORY_NAME(String.class, "CATEGORY_NAME"), + AUDIT_SUB_CATEGORY_NAME(String.class, "SUB_CATEGORY_NAME"), + AUDIT_GROUPING_NAME(String.class, "GROUPING_NAME"), + AUDIT_DETAILS(String.class, "DETAILS"), - //operational environment - AUDIT_OPERATIONAL_ENVIRONMENT_ID(String.class, "OPERATIONAL_ENVIRONMENT_ID"), - AUDIT_OPERATIONAL_ENVIRONMENT_NAME(String.class, "OPERATIONAL_ENVIRONMENT_NAME"), - AUDIT_OPERATIONAL_ENVIRONMENT_TYPE(String.class, "OPERATIONAL_ENVIRONMENT_TYPE"), - AUDIT_OPERATIONAL_ENVIRONMENT_ACTION(String.class, "OPERATIONAL_ENVIRONMENT_ACTION"), - AUDIT_TENANT_CONTEXT(String.class, "TENANT_CONTEXT"), + //operational environment + AUDIT_OPERATIONAL_ENVIRONMENT_ID(String.class, "OPERATIONAL_ENVIRONMENT_ID"), + AUDIT_OPERATIONAL_ENVIRONMENT_NAME(String.class, "OPERATIONAL_ENVIRONMENT_NAME"), + AUDIT_OPERATIONAL_ENVIRONMENT_TYPE(String.class, "OPERATIONAL_ENVIRONMENT_TYPE"), + AUDIT_OPERATIONAL_ENVIRONMENT_ACTION(String.class, "OPERATIONAL_ENVIRONMENT_ACTION"), + AUDIT_TENANT_CONTEXT(String.class, "TENANT_CONTEXT"), - // authentication - AUDIT_AUTH_URL(String.class, "URL"), - AUDIT_AUTH_USER(String.class, "USER"), - AUDIT_AUTH_STATUS(String.class, "AUTH_STATUS"), - AUDIT_AUTH_REALM(String.class, "REALM"), - AUDIT_ECOMP_USER(String.class, "ECOMP_USER"); + // authentication + AUDIT_AUTH_URL(String.class, "URL"), + AUDIT_AUTH_USER(String.class, "USER"), + AUDIT_AUTH_STATUS(String.class, "AUTH_STATUS"), + AUDIT_AUTH_REALM(String.class, "REALM"), + AUDIT_ECOMP_USER(String.class, "ECOMP_USER"); - private Class<?> clazz; - private String displayName; + private Class<?> clazz; + private String displayName; - AuditingFieldsKey(Class<?> clazz, String displayName) { - this.clazz = clazz; - this.displayName = displayName; - } + AuditingFieldsKey(Class<?> clazz, String displayName) { + this.clazz = clazz; + this.displayName = displayName; + } - public Class<?> getValueClass() { - return this.clazz; - } + public Class<?> getValueClass() { + return this.clazz; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEvent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEvent.java deleted file mode 100644 index 9e991e8dcb..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/ESTimeBasedEvent.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.datastructure; - -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Formatter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -/** - * Extending this class enforces the objects of implementing classes to have a - * timestamp, so that like in logstash, we can derive the index name for those - * object from the timestamp. - * - * @author paharoni - */ -public class ESTimeBasedEvent { - - private static final int TIMESTAMP_YEAR_SUBSTRING = 4; - private static final int TIMESTAMP_MONTH_SUBSTRING = 7; - private static final int TIMESTAMP_DAY_SUBSTRING = 10; - private static final int TIMESTAMP_HOURS_START = 11; - private static final int TIMESTAMP_HOURS_END = 13; - private static final int TIMESTAMP_MINUTES_START = 14; - private static final int TIMESTAMP_MINUTES_END = 16; - - protected SimpleDateFormat simpleDateFormat; - protected static String dateFormatPattern = "yyyy-MM-dd HH:mm:ss.SSS z"; - protected String timestamp; - protected Map<String, Object> fields = new HashMap<>(); - - public ESTimeBasedEvent() { - simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.timestamp = simpleDateFormat.format(new Date()); - fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), this.timestamp); - - } - - public static ESTimeBasedEvent createEventFromJson(String jsonString) throws JSONException { - - ESTimeBasedEvent event = new ESTimeBasedEvent(); - JSONObject gsonObj; - gsonObj = new JSONObject(jsonString); - Iterator keys = gsonObj.keys(); - - while (keys.hasNext()) { - String key = (String) keys.next(); - event.fields.put(key, gsonObj.get(key)); - if (key.equals(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName())) { - event.timestamp = (String) gsonObj.get(key); - } - } - return event; - } - - public String calculateYearIndexSuffix() { - return timestamp.substring(0, TIMESTAMP_YEAR_SUBSTRING); - } - - public String calculateMonthIndexSuffix() { - return timestamp.substring(0, TIMESTAMP_MONTH_SUBSTRING); - } - - public String calculateDayIndexSuffix() { - return timestamp.substring(0, TIMESTAMP_DAY_SUBSTRING); - } - - public String calculateHourIndexSuffix() { - return calculateBaseIndexSuffix().toString(); - } - - public String calculateMinuteIndexSuffix() { - return calculateBaseIndexSuffix().append("-").append(timestamp, TIMESTAMP_MINUTES_START, TIMESTAMP_MINUTES_END).toString(); - } - - private StringBuilder calculateBaseIndexSuffix() { - return new StringBuilder().append(timestamp, 0, TIMESTAMP_DAY_SUBSTRING).append("-").append(timestamp, TIMESTAMP_HOURS_START, TIMESTAMP_HOURS_END); - } - - protected String getFormattedString(String template, Object... params) { - String res; - StringBuilder sb = new StringBuilder(); - try (Formatter formatter = new Formatter(sb, Locale.US)) { - formatter.format(template, params); - res = formatter.toString(); - } - return res; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public Map<String, Object> getFields() { - return fields; - } - - public void setFields(Map<String, Object> fields) { - this.fields = fields; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java index 5d268d2948..7cd099e07e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,97 +20,100 @@ package org.openecomp.sdc.common.datastructure; -import fj.F; -import fj.data.Either; -import org.apache.commons.lang3.math.NumberUtils; -import org.openecomp.sdc.common.log.wrappers.Logger; +import static org.apache.commons.lang3.StringUtils.EMPTY; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; +import java.util.concurrent.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.time.StopWatch; +import org.openecomp.sdc.common.log.enums.EcompErrorSeverity; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import fj.F; +import fj.data.Either; + /** * Class For Functional interfaces And Functional Methods - * + * * @author mshitrit + * */ public class FunctionalInterfaces { - private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50; - private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000; - private static final Logger LOGGER = Logger.getLogger(FunctionalInterfaces.class.getName()); - - /** - * This is an interface of a List that implements Serializable - * - * @param <T> - * @author mshitrit - */ - public interface SerializableList<T> extends List<T>, Serializable { - } - - /** - * @param <T1> - * @param <T2> - * @author mshitrit Consumer that takes two parameters - */ - public interface ConsumerTwoParam<T1, T2> { - /** - * Same Accept method, but takes two parameters - * - * @param t1 - * @param t2 - */ - void accept(T1 t1, T2 t2); - } - - /** - * @param <T1> - * @param <T2> - * @param <R> - * @author mshitrit Function that takes two parameters - */ - public interface FunctionTwoParam<T1, T2, R> { - /** - * Same apply method, but takes two parameters - * - * @param t1 - * @param t2 - * @return - */ - R apply(T1 t1, T2 t2); - } - - /** - * @param <T> - * @param <R> - * @param <E> - * @author mshitrit Function that throws an exception - */ - public interface FunctionThrows<T, R, E extends Exception> { - /** - * Same apply method, but throws an exception - * - * @param t - * @return - */ - R apply(T t) throws E; - } + private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50; + private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000; + private static final Logger LOGGER = Logger.getLogger(FunctionalInterfaces.class.getName()); + + /** + * This is an interface of a List that implements Serializable + * + * @author mshitrit + * + * @param <T> + */ + public interface SerializableList<T> extends List<T>, Serializable { + } + + /** + * @author mshitrit Consumer that takes two parameters + * @param <T1> + * @param <T2> + */ + public interface ConsumerTwoParam<T1, T2> { + /** + * Same Accept method, but takes two parameters + * + * @param t1 + * @param t2 + */ + void accept(T1 t1, T2 t2); + } + + /** + * @author mshitrit Function that takes two parameters + * @param <T1> + * @param <T2> + * @param <R> + */ + public interface FunctionTwoParam<T1, T2, R> { + /** + * Same apply method, but takes two parameters + * + * @param t1 + * @param t2 + * @return + */ + R apply(T1 t1, T2 t2); + } + + /** + * @author mshitrit Function that throws an exception + * @param <T> + * @param <R> + * @param <E> + */ + public interface FunctionThrows<T, R, E extends Exception> { + /** + * Same apply method, but throws an exception + * + * @param t + * @return + */ + R apply(T t) throws E; + } public interface FunctionTwoParamThrows<T1, T2, R, E extends Exception> { /** * Same apply method, but throws an exception - * + * * @param t1 * @param t2 * @return @@ -118,213 +121,219 @@ public class FunctionalInterfaces { R apply(T1 t1, T2 t2) throws E; } - /** - * @param <R> - * @param <E> - * @author mshitrit Supplier that throws an exception - */ - public interface SupplierThrows<R, E extends Exception> { - /** - * Same get method, but throws an exception - * - * @return - * @throws E - */ - R get() throws E; - } - - /** - * @param <T> - * @param <E> - * @author mshitrit Consumer that throws an exception - */ - public interface ConsumerThrows<T, E extends Exception> { - /** - * Same accept, but throws an exception - * - * @param t - * @throws E - */ - void accept(T t) throws E; - } - - /** - * @param <E> - * @author mshitrit Runnable that throws an exception - */ - public interface RunnableThrows<E extends Exception> { - /** - * Same run, but throws an exception - * - * @throws E - */ - void run() throws E; - } - - /** - * Runs a method that declares throwing an Exception and has a return value. - * <br> - * In case Exception Occurred replaces it with FunctionalAttException. <br> - * This is useful for two cases:<br> - * 1.using methods that throws exceptions in streams.<br> - * 2.replacing declared exception with undeclared exception (Runtime).<br> - * See below Use Case:<br> - * Instead of: intList.stream().map(e -> fooThrowsAndReturnsBoolean(e)); - - * does not compile !<br> - * Use This : intList.stream().map(e -> swallowException( () -> - * fooThrowsAndReturnsBoolean(e))); - compiles !<br> - * - * @param methodToRun - * @return - */ - public static <R, E extends Exception> R swallowException(SupplierThrows<R, E> methodToRun) { - try { + /** + * @author mshitrit Supplier that throws an exception + * @param <R> + * @param <E> + */ + public interface SupplierThrows<R, E extends Exception> { + /** + * Same get method, but throws an exception + * + * @return + * @throws E + */ + R get() throws E; + } + + /** + * @author mshitrit Consumer that throws an exception + * @param <T> + * @param <E> + */ + public interface ConsumerThrows<T, E extends Exception> { + /** + * Same accept, but throws an exception + * + * @param t + * @throws E + */ + void accept(T t) throws E; + } + + /** + * @author mshitrit Runnable that throws an exception + * @param <E> + */ + public interface RunnableThrows<E extends Exception> { + /** + * Same run, but throws an exception + * + * @throws E + */ + void run() throws E; + } + + /** + * Runs a method that declares throwing an Exception and has a return value. + * <br> + * In case Exception Occurred replaces it with FunctionalAttException. <br> + * This is useful for two cases:<br> + * 1.using methods that throws exceptions in streams.<br> + * 2.replacing declared exception with undeclared exception (Runtime).<br> + * See below Use Case:<br> + * Instead of: intList.stream().map(e -> fooThrowsAndReturnsBoolean(e)); - + * does not compile !<br> + * Use This : intList.stream().map(e -> swallowException( () -> + * fooThrowsAndReturnsBoolean(e))); - compiles !<br> + * + * @param methodToRun + * @return + */ + public static <R, E extends Exception> R swallowException(SupplierThrows<R, E> methodToRun) { + try { return methodToRun.get(); - } catch (Exception e) { - throw new FunctionalAttException(e); - } - } - - /** - * Runs a method that declares throwing an Exception without return value. - * <br> - * In case Exception Occurred replaces it with FunctionalAttException. <br> - * This is useful for two cases:<br> - * 1.using methods that throws exceptions in streams.<br> - * 2.replacing declared exception with undeclared exception (Runtime).<br> - * See below Use Case:<br> - * - * @param methodToRun - */ - public static <E extends Exception> void swallowException(RunnableThrows<E> methodToRun) { - - SupplierThrows<Boolean, E> runnableWrapper = () -> { - methodToRun.run(); - return true; - }; - swallowException(runnableWrapper); - } - - private static class FunctionalAttException extends RuntimeException { - private static final long serialVersionUID = 1L; - - private FunctionalAttException(Exception e) { - super(e); - } - } - - /** - * Runs the given method.<br> - * Verify the method result against the resultVerifier.<br> - * If verification passed returns the result.<br> - * If Verification failed keeps retrying until it passes or until 10 seconds - * pass.<br> - * If Exception Occurred keeps retrying until it passes or until 10 seconds - * pass,<br> - * If last retry result caused an exception - it is thrown. - * - * @param methodToRun given Method - * @param resultVerifier verifier for the method result - * @return - */ - public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier) { - return retryMethodOnResult(methodToRun, resultVerifier, DEFAULT_MAX_WAIT_TIME_MS, - DEFAULT_REDO_INTERVAL_TIME_MS); - } - - /** - * Runs the given method.<br> - * Verify the method result against the resultVerifier.<br> - * If verification passed returns the result.<br> - * If Verification failed keeps retrying until it passes or until maxWait - * pass.<br> - * If Exception Occurred keeps retrying until it passes or until maxWait - * pass,<br> - * If last retry result caused an exception - it is thrown. - * - * @param methodToRun given Method - * @param resultVerifier verifier for the method result - * @param maxWaitMS - * @param retryIntervalMS - * @return - */ - public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier, - long maxWaitMS, long retryIntervalMS) { - boolean stopSearch = false; - R ret = null; - int timeElapsed = 0; - FunctionalAttException functionalExceotion = null; - boolean isExceptionInLastTry = false; - while (!stopSearch) { - try { - ret = methodToRun.get(); - stopSearch = resultVerifier.apply(ret); - isExceptionInLastTry = false; - } catch (Exception e) { - functionalExceotion = new FunctionalAttException(e); - isExceptionInLastTry = true; - - } finally { - sleep(retryIntervalMS); - timeElapsed += retryIntervalMS; - if (timeElapsed > maxWaitMS) { - stopSearch = true; - } - } - - } - if (isExceptionInLastTry) { - throw functionalExceotion; - } else { - return ret; - } - - } - - /** - * Runs the given method.<br> - * Verify the method result against the resultVerifier.<br> - * If verification passed returns the result.<br> - * If Verification failed keeps retrying until maxRetries reached.<br> - * If Exception Occurred keeps retrying until it passes or until maxRetries - * reached,<br> - * If last retry result caused an exception - it is thrown. - * - * @param methodToRun given Method - * @param resultVerifier verifier for the method result - * @param maxRetries - * @return - */ - public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier, - long maxRetries) { - boolean stopSearch = false; - R ret = null; - int retriesCount = 0; - FunctionalAttException functionalExceotion = null; - boolean isExceptionInLastTry = false; - while (!stopSearch) { - try { - ret = methodToRun.get(); - stopSearch = resultVerifier.apply(ret); - isExceptionInLastTry = false; - } catch (Exception e) { - functionalExceotion = new FunctionalAttException(e); - isExceptionInLastTry = true; - } finally { - if (++retriesCount >= maxRetries) { - stopSearch = true; - } - } - } - if (isExceptionInLastTry) { - throw functionalExceotion; - } else { - return ret; - } - } - - public static <R> R retryMethodOnException(SupplierThrows<R, Exception> methodToRun, - Function<Exception, Boolean> exceptionVerifier, long maxRetries) throws Exception { + } catch (Exception e) { + throw new FunctionalAttException(e); + } + } + + /** + * Runs a method that declares throwing an Exception without return value. + * <br> + * In case Exception Occurred replaces it with FunctionalAttException. <br> + * This is useful for two cases:<br> + * 1.using methods that throws exceptions in streams.<br> + * 2.replacing declared exception with undeclared exception (Runtime).<br> + * See below Use Case:<br> + * + * @param methodToRun + */ + public static <E extends Exception> void swallowException(RunnableThrows<E> methodToRun) { + + SupplierThrows<Boolean, E> runnableWrapper = () -> { + methodToRun.run(); + return true; + }; + swallowException(runnableWrapper); + } + + private static class FunctionalAttException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private FunctionalAttException(Exception e) { + super(e); + } + } + + /** + * Runs the given method.<br> + * Verify the method result against the resultVerifier.<br> + * If verification passed returns the result.<br> + * If Verification failed keeps retrying until it passes or until 10 seconds + * pass.<br> + * If Exception Occurred keeps retrying until it passes or until 10 seconds + * pass,<br> + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @return + */ + public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier) { + return retryMethodOnResult(methodToRun, resultVerifier, DEFAULT_MAX_WAIT_TIME_MS, + DEFAULT_REDO_INTERVAL_TIME_MS); + } + + /** + * Runs the given method.<br> + * Verify the method result against the resultVerifier.<br> + * If verification passed returns the result.<br> + * If Verification failed keeps retrying until it passes or until maxWait + * pass.<br> + * If Exception Occurred keeps retrying until it passes or until maxWait + * pass,<br> + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @param maxWaitMS + * @param retryIntervalMS + * @return + */ + public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier, + long maxWaitMS, long retryIntervalMS) { + boolean stopSearch = false; + R ret = null; + int timeElapsed = 0; + FunctionalAttException functionalExceotion = null; + boolean isExceptionInLastTry = false; + while (!stopSearch) { + try { + ret = methodToRun.get(); + stopSearch = resultVerifier.apply(ret); + isExceptionInLastTry = false; + } catch (Exception e) { + functionalExceotion = new FunctionalAttException(e); + isExceptionInLastTry = true; + + } finally { + sleep(retryIntervalMS); + timeElapsed += retryIntervalMS; + if (timeElapsed > maxWaitMS) { + stopSearch = true; + } + } + + } + if (isExceptionInLastTry) { + throw functionalExceotion; + } else { + return ret; + } + + } + + /** + * Runs the given method.<br> + * Verify the method result against the resultVerifier.<br> + * If verification passed returns the result.<br> + * If Verification failed keeps retrying until maxRetries reached.<br> + * If Exception Occurred keeps retrying until it passes or until maxRetries + * reached,<br> + * If last retry result caused an exception - it is thrown. + * + * @param methodToRun + * given Method + * @param resultVerifier + * verifier for the method result + * @param maxRetries + * @return + */ + public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier, + long maxRetries) { + boolean stopSearch = false; + R ret = null; + int retriesCount = 0; + FunctionalAttException functionalExceotion = null; + boolean isExceptionInLastTry = false; + while (!stopSearch) { + try { + ret = methodToRun.get(); + stopSearch = resultVerifier.apply(ret); + isExceptionInLastTry = false; + } catch (Exception e) { + functionalExceotion = new FunctionalAttException(e); + isExceptionInLastTry = true; + } finally { + if (++retriesCount >= maxRetries) { + stopSearch = true; + } + } + } + if (isExceptionInLastTry) { + throw functionalExceotion; + } else { + return ret; + } + } + + public static <R> R retryMethodOnException(SupplierThrows<R, Exception> methodToRun, + Function<Exception, Boolean> exceptionVerifier, long maxRetries) throws Exception { boolean stopSearch = false; R ret = null; int retriesCount = 0; @@ -334,10 +343,12 @@ public class FunctionalInterfaces { exception = null; ret = methodToRun.get(); stopSearch = true; - } catch (Exception e) { + } + catch (Exception e) { exception = e; stopSearch = exceptionVerifier.apply(e); - } finally { + } + finally { if (++retriesCount >= maxRetries) { stopSearch = true; } @@ -345,157 +356,162 @@ public class FunctionalInterfaces { } if (exception != null) { throw exception; - } else { - return ret; } - } - - /** - * Runs the given method.<br> - * In case exception occurred runs the method again either until succeed or - * until 10 seconds pass. - * - * @param methodToRun given method - * @return - */ - - public static <R> R retryMethodOnException(Supplier<R> methodToRun) { - Function<R, Boolean> dummyVerifier = someResult -> true; - return retryMethodOnResult(methodToRun, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); - } - - /** - * Runs the given method.<br> - * In case exception occurred runs the method again either until succeed or - * until 10 seconds pass. - * - * @param methodToRun given method - */ - public static void retryMethodOnException(Runnable methodToRun) { - Function<Boolean, Boolean> dummyVerifier = someResult -> true; - Supplier<Boolean> dummySupplier = () -> { - methodToRun.run(); - return true; - }; - retryMethodOnResult(dummySupplier, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); - } - - /** - * Same as Thread.sleep but throws a FunctionalAttException - * (RuntimeException) instead of InterruptedException.<br> - * - * @param millis - */ - public static void sleep(long millis) { - swallowException(() -> Thread.sleep(millis)); - - } - - /** - * Converts Either containing right value to another either with different - * type of left value and the same type of right value. - * - * @param eitherToConvert - * @return - */ - public static <T1, T2, T3> Either<T1, T2> convertEitherRight(Either<T3, T2> eitherToConvert) { - if (eitherToConvert.isLeft()) { - throw new UnsupportedOperationException("Can not convert either right value because it has left value"); - } else { - return Either.right(eitherToConvert.right().value()); - } - - } - - /** - * Converts Either containing left value to another either with different - * type of right value and the same type of left value. - * - * @param eitherToConvert - * @return - */ - public static <T1, T2, T3> Either<T1, T2> convertEitherLeft(Either<T1, T3> eitherToConvert) { - if (eitherToConvert.isLeft()) { - throw new UnsupportedOperationException("Can not convert either left value because it has right value"); - } else { - return Either.left(eitherToConvert.left().value()); - } - - } - - /** - * Returns enum value for a field <br> - * - * @param fieldValue - * @param values - * @param enumValueGetter - * @return - */ - public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values, - Function<T, String> enumValueGetter, T defaultValue) { - return getEnumValueByFieldValue(fieldValue, values, enumValueGetter, defaultValue, true); - - } - - - public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values, - Function<T, String> enumValueGetter, T defaultValue, boolean isCaseSensetive) { - - final Predicate<? super T> predicate; - if (isCaseSensetive) { - predicate = e -> fieldValue.equals(enumValueGetter.apply(e)); - } else { - predicate = e -> fieldValue.equalsIgnoreCase(enumValueGetter.apply(e)); - } - Optional<T> optionalFound = - // Stream of values of enum - Arrays.asList(values).stream(). - // Filter in the one that match the field - filter(predicate). - // collect - findAny(); - T ret; - ret = optionalFound.isPresent() ? optionalFound.get() : defaultValue; - return ret; - - } - - /** - * This method runs the given method.<br> - * In case given method finished running within timeoutInMs limit it returns - * Either which left value is the result of the method that ran.<br> - * In case given method did not finish running within timeoutInMs limit it - * returns Either which right value is false. <br> - * - * @param supplier - * @param timeoutInMs - if 0 or lower no timeout is used - * @return - */ - public static <T> Either<T, Boolean> runMethodWithTimeOut(Supplier<T> supplier, long timeoutInMs) { - Either<T, Boolean> result; - if (timeoutInMs <= NumberUtils.LONG_ZERO) { - result = Either.left(supplier.get()); - } else { - ExecutorService pool = Executors.newSingleThreadExecutor(); - Future<T> future = pool.submit(supplier::get); - try { - T calcValue = future.get(timeoutInMs, TimeUnit.MILLISECONDS); - result = Either.left(calcValue); - } catch (InterruptedException e) { - LOGGER.debug("InterruptedException in runMethodWithTimeOut", e); - Thread.currentThread().interrupt(); - result = Either.right(false); - } catch (ExecutionException | TimeoutException e) { - LOGGER.debug("method run was canceled because it has passed its time limit of {} MS", timeoutInMs, e); - result = Either.right(false); - } finally { - pool.shutdownNow(); - } + else { + return ret; } - return result; } - public static <T> F<T, Boolean> convertToFunction(Consumer<T> consumer) { + /** + * Runs the given method.<br> + * In case exception occurred runs the method again either until succeed or + * until 10 seconds pass. + * + * @param methodToRun + * given method + * @return + */ + + public static <R> R retryMethodOnException(Supplier<R> methodToRun) { + Function<R, Boolean> dummyVerifier = someResult -> true; + return retryMethodOnResult(methodToRun, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); + } + + /** + * Runs the given method.<br> + * In case exception occurred runs the method again either until succeed or + * until 10 seconds pass. + * + * @param methodToRun + * given method + */ + public static void retryMethodOnException(Runnable methodToRun) { + Function<Boolean, Boolean> dummyVerifier = someResult -> true; + Supplier<Boolean> dummySupplier = () -> { + methodToRun.run(); + return true; + }; + retryMethodOnResult(dummySupplier, dummyVerifier, DEFAULT_MAX_WAIT_TIME_MS, DEFAULT_REDO_INTERVAL_TIME_MS); + } + + /** + * Same as Thread.sleep but throws a FunctionalAttException + * (RuntimeException) instead of InterruptedException.<br> + * + * @param millis + */ + public static void sleep(long millis) { + swallowException(() -> Thread.sleep(millis)); + + } + + /** + * Converts Either containing right value to another either with different + * type of left value and the same type of right value. + * + * @param eitherToConvert + * @return + */ + public static <T1, T2, T3> Either<T1, T2> convertEitherRight(Either<T3, T2> eitherToConvert) { + if (eitherToConvert.isLeft()) { + throw new UnsupportedOperationException("Can not convert either right value because it has left value"); + } else { + return Either.right(eitherToConvert.right().value()); + } + + } + + /** + * Converts Either containing left value to another either with different + * type of right value and the same type of left value. + * + * @param eitherToConvert + * @return + */ + public static <T1, T2, T3> Either<T1, T2> convertEitherLeft(Either<T1, T3> eitherToConvert) { + if (eitherToConvert.isLeft()) { + throw new UnsupportedOperationException("Can not convert either left value because it has right value"); + } else { + return Either.left(eitherToConvert.left().value()); + } + + } + + /** + * Returns enum value for a field <br> + * + * @param fieldValue + * @param values + * @param enumValueGetter + * @return + */ + public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values, + Function<T, String> enumValueGetter, T defaultValue) { + return getEnumValueByFieldValue(fieldValue, values, enumValueGetter, defaultValue, true); + + } + + + public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values, + Function<T, String> enumValueGetter, T defaultValue, boolean isCaseSensetive ){ + + final Predicate<? super T> predicate; + if( isCaseSensetive ){ + predicate = e -> fieldValue.equals(enumValueGetter.apply(e)); + } + else{ + predicate = e -> fieldValue.equalsIgnoreCase(enumValueGetter.apply(e)); + } + Optional<T> optionalFound = + // Stream of values of enum + Arrays.asList(values).stream(). + // Filter in the one that match the field + filter(predicate). + // collect + findAny(); + T ret; + ret = optionalFound.isPresent() ? optionalFound.get() : defaultValue; + return ret; + + } + + /** + * This method runs the given method.<br> + * In case given method finished running within timeoutInMs limit it returns + * Either which left value is the result of the method that ran.<br> + * In case given method did not finish running within timeoutInMs limit it + * returns Either which right value is false. <br> + * + * @param supplier + * @param timeoutInMs + * - if 0 or lower no timeout is used + * @return + */ + public static <T> Either<T, Boolean> runMethodWithTimeOut(Supplier<T> supplier, long timeoutInMs) { + Either<T, Boolean> result; + if (timeoutInMs <= NumberUtils.LONG_ZERO) { + result = Either.left(supplier.get()); + } else { + ExecutorService pool = Executors.newSingleThreadExecutor(); + Future<T> future = pool.submit(supplier::get); + try { + T calcValue = future.get(timeoutInMs, TimeUnit.MILLISECONDS); + result = Either.left(calcValue); + } catch (InterruptedException e) { + LOGGER.debug("InterruptedException in runMethodWithTimeOut", e); + Thread.currentThread().interrupt(); + result = Either.right(false); + } catch (ExecutionException | TimeoutException e) { + LOGGER.debug("method run was canceled because it has passed its time limit of {} MS", timeoutInMs, e); + result = Either.right(false); + } finally { + pool.shutdownNow(); + } + } + return result; + } + + public static <T> F<T, Boolean> convertToFunction(Consumer<T> consumer) { return t -> { try { consumer.accept(t); @@ -504,6 +520,83 @@ public class FunctionalInterfaces { return false; } }; - } + } + + /** + * Wraps the execution of the Runnable with try catch.<br> + * In case exception occurred returns Optional containing the + * resultOnException.<br> + * Otherwise returns an Empty optional. + * + * @param runnable + * @param resultOnException + * @return + */ + public static <T, E extends Exception> Optional<T> wrapWithTryCatch(RunnableThrows<E> runnable, + T resultOnException) { + Optional<T> optionalError; + try { + runnable.run(); + optionalError = Optional.empty(); + } catch (Exception e) { + logException(e); + optionalError = Optional.of(resultOnException); + } + return optionalError; + } + + /** + * Runs the given method.<br> + * In case the method passes without any Assertion Errors finishes.<br> + * In case there is an assertion error keeps running the method every retryIntervalMS.<br> until there is no Errors or maxWaitTimeMs has passed. <br> + * If there are still Assertion Errors in the last Run they are returned to the user.<br> + * + * @param methodToRun + * @param maxWaitTimeMs + * @param retryIntervalMS + */ + public static <T extends Throwable> void retryMethodOnException (Runnable methodToRun, long maxWaitTimeMs, long retryIntervalMS) { + if (maxWaitTimeMs <= 0) { + throw new UnsupportedOperationException("Number maxWaitTimeMs be greater than 0"); + } + StopWatch watch = new StopWatch(); + watch.start(); + + boolean isLastTry = false; + while (!isLastTry) { + isLastTry = watch.getTime() + retryIntervalMS > maxWaitTimeMs; + if (isLastTry) { + methodToRun.run(); + } + else { + try { + methodToRun.run(); + break; + } catch (Exception e) { + wrapWithTryCatch(() -> Thread.sleep(retryIntervalMS)); + } + } + } + + + } + + /** + * Wraps the execution of the Runnable with try catch.<br> + * In case exception occurred logs the Exception.<br> + * resultOnException.<br> + * Otherwise returns an Empty optional. + * + * @param runnable + * @return + */ + public static <E extends Exception> void wrapWithTryCatch(RunnableThrows<E> runnable) { + wrapWithTryCatch(runnable, null); + } + + private static void logException(Exception e) { + LOGGER.error(EcompErrorSeverity.ERROR, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, EMPTY, EMPTY, EMPTY, EMPTY); + LOGGER.debug("Error was caught ", e); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java index 4ac3e26f1e..f92b4ef687 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/MonitoringFieldsKeysEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,35 +23,35 @@ package org.openecomp.sdc.common.datastructure; import java.util.Date; public enum MonitoringFieldsKeysEnum { - MONITORING_TIMESTAMP(Date.class, "TIMESTAMP"), - MONITORING_HOST_IP(String.class, "HOST_IP"), - MONITORING_HOST_CPU(Long.class, "HOST_CPU"), - MONITORING_HOST_MEM(Long.class, "HOST_MEMORY"), - MONITORING_HOST_DISC(Long.class, "HOST_DISC"), - MONITORING_JVM_ID(String.class, "JVM_ID"), - MONITORING_JVM_CPU(Long.class, "JVM_CPU"), - MONITORING_JVM_MEM(Long.class, "JVM_MEMORY"), - MONITORING_JVM_TNUM(Long.class, "JVM_TNUM"), - MONITORING_APP_ID(String.class, "APP_ID"), - MONITORING_APP_STAT(String.class, "APP_STAT"); - - private Class<?> clazz; - private String displayName; - - MonitoringFieldsKeysEnum(Class<?> clazz, String displayName) { - this.clazz = clazz; - this.displayName = displayName; - } - - public Class<?> getValueClass() { - return this.clazz; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + MONITORING_TIMESTAMP(Date.class, "TIMESTAMP"), + MONITORING_HOST_IP(String.class, "HOST_IP"), + MONITORING_HOST_CPU(Long.class, "HOST_CPU"), + MONITORING_HOST_MEM(Long.class, "HOST_MEMORY"), + MONITORING_HOST_DISC(Long.class, "HOST_DISC"), + MONITORING_JVM_ID(String.class, "JVM_ID"), + MONITORING_JVM_CPU(Long.class, "JVM_CPU"), + MONITORING_JVM_MEM(Long.class, "JVM_MEMORY"), + MONITORING_JVM_TNUM(Long.class, "JVM_TNUM"), + MONITORING_APP_ID(String.class, "APP_ID"), + MONITORING_APP_STAT(String.class, "APP_STAT"); + + private Class<?> clazz; + private String displayName; + + MonitoringFieldsKeysEnum(Class<?> clazz, String displayName) { + this.clazz = clazz; + this.displayName = displayName; + } + + public Class<?> getValueClass() { + return this.clazz; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/UserContext.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/UserContext.java new file mode 100644 index 0000000000..8dcca6b6e1 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/UserContext.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.common.datastructure; + + +import java.util.Set; + +public class UserContext { + + + /** + * a pojo which holds the business logic layer to be aware of the user context as received in the authentication cookie + * Story https://jira.web.labs.att.com/browse/ASDC-232 + * Author: Idan Agam + */ + + + private String userId; + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + private Set<String> userRoles; + + + public UserContext(String userId, Set<String> userRoles, String firstName, String lastName) { + this.userId = userId; + this.userRoles = userRoles; + this.firstName = firstName; + this.lastName = lastName; + } + + public UserContext(String userId) { + this.userId = userId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Set<String> getUserRoles() { + return userRoles; + } + + public void setUserRoles(Set<String> userRoles) { + this.userRoles = userRoles; + } + + @Override + public String toString() { + return "UserContext{" + "userId='" + userId + '\'' + ", firstName='" + firstName + '\'' + ", lastname='" + lastName + '\'' + ", userRoles=" + userRoles + '}'; + } +} + + + + diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java index 96c38cc3cf..43fd5ca15f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/Wrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,30 +22,31 @@ package org.openecomp.sdc.common.datastructure; /** * Very Basic Wrapper class. - * - * @param <T> + * * @author mshitrit + * + * @param <T> */ public class Wrapper<T> { - private T innerElement; + private T innerElement; - public Wrapper(T innerElement) { - this.innerElement = innerElement; - } + public Wrapper(T innerElement) { + this.innerElement = innerElement; + } - public Wrapper() { - this.innerElement = null; - } + public Wrapper() { + this.innerElement = null; + } - public T getInnerElement() { - return innerElement; - } + public T getInnerElement() { + return innerElement; + } - public void setInnerElement(T innerElement) { - this.innerElement = innerElement; - } + public void setInnerElement(T innerElement) { + this.innerElement = innerElement; + } - public boolean isEmpty() { - return innerElement == null; - } + public boolean isEmpty() { + return innerElement == null; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java index 7273a04bd0..21c0f45e24 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,11 +19,10 @@ */ package org.openecomp.sdc.common.http.client.api; - import org.apache.http.client.HttpRequestRetryHandler; public interface ComparableHttpRequestRetryHandler extends HttpRequestRetryHandler { - default <T extends HttpRequestRetryHandler> boolean compare(T handler) { + public default <T extends HttpRequestRetryHandler> boolean compare(T handler) { return (handler != null && getClass() == handler.getClass()); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java index 9ed3efde11..66a7050821 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,13 +29,7 @@ import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.methods.*; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; @@ -52,19 +46,17 @@ import java.net.URI; import java.util.Properties; public class HttpClient { - private static final Logger LOGGER = Logger.getLogger(HttpClient.class.getName()); - public static final int HTTPS_PORT = 443; - public static final int HTTP_PORT = 80; - + private static final Logger logger = Logger.getLogger(HttpClient.class.getName()); + private final CloseableHttpClient client; private final HttpClientConfigImmutable configImmutable; - - HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { + + public HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { this.client = client; - this.configImmutable = configImmutable; + this.configImmutable = configImmutable; } - - <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + + public <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { HttpGet httpGet = new HttpGet(url); return execute(httpGet, headers, responseBuilder); } @@ -91,17 +83,18 @@ public class HttpClient { HttpDelete httpDelete = new HttpDelete(url); return execute(httpDelete, headers, responseBuilder); } - + void close() { try { client.close(); - } catch (IOException e) { - LOGGER.debug("Close http client failed with exception ", e); + } + catch (IOException e) { + logger.debug("Close http client failed with exception ", e); } } - + private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { - if (configImmutable.getHeaders() != null) { + if(configImmutable.getHeaders() != null) { configImmutable.getHeaders().forEach(request::addHeader); } @@ -110,52 +103,57 @@ public class HttpClient { } HttpClientContext httpClientContext = null; - if (request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { + if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) { httpClientContext = createHttpContext(request.getURI()); } - LOGGER.debug("Execute request {}", request.getRequestLine()); + logger.debug("Execute request {}", request.getRequestLine()); try (CloseableHttpResponse response = client.execute(request, httpClientContext)) { return responseBuilder.apply(response); - } catch (Exception e) { - String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); + } + catch (Exception e) { + String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR); - LOGGER.debug("{}: ", description, e); + logger.debug("{}: ",description, e); throw new HttpExecuteException(description, e); - } + } } private HttpClientContext createHttpContext(URI uri) { - if (StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { + if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) { return null; } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); int port = getPort(uri); - credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), + credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword())); HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(credentialsProvider); AuthCache authCache = new BasicAuthCache(); - authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme()); + HttpHost target = new HttpHost(uri.getHost(), port, "https"); + authCache.put(target, (AuthScheme) new BasicScheme()); localContext.setAuthCache(authCache); return localContext; } private int getPort(URI uri) { - int port = uri.getPort(); - if (port < 0) { - if (Constants.HTTPS.equals(uri.getScheme())) { - port = HTTPS_PORT; - } else if (Constants.HTTP.equals(uri.getScheme())) { - port = HTTP_PORT; - } else { + int port = uri.getPort(); + if(port < 0) { + if(Constants.HTTPS.equals(uri.getScheme())) { + port = 443; + } + else + if (Constants.HTTP.equals(uri.getScheme())) { + port = 80; + } + else { port = AuthScope.ANY_PORT; - LOGGER.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); + logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port); } } return port; diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java index f0fe09fe7c..9b21e1ac87 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,40 +29,46 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -final class HttpClientConfigImmutable { +public final class HttpClientConfigImmutable { private final Map<String, String> headers; private final BasicAuthorization basicAuthorization; private final ClientCertificate clientCertificate; private final Timeouts timeouts; + private boolean enableMetricLogging; /* - * use ComparableHttpRequestRetryHandler.compare instead of default generated equals + * use ComparableHttpRequestRetryHandler.compare instead of default generated equals */ private final ComparableHttpRequestRetryHandler retryHandler; private final int numOfRetries; - + static HttpClientConfigImmutable getOrCreate(HttpClientConfig httpClientConfig) { // TODO: retrieve from a pool if exist, otherwise create new - return new HttpClientConfigImmutable(httpClientConfig); + return new HttpClientConfigImmutable(httpClientConfig); } - HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { + public HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { timeouts = httpClientConfig.getTimeouts() != null ? new Timeouts(httpClientConfig.getTimeouts()) : null; basicAuthorization = httpClientConfig.getBasicAuthorization() != null ? new BasicAuthorization(httpClientConfig.getBasicAuthorization()) : null; clientCertificate = httpClientConfig.getClientCertificate() != null ? new ClientCertificate(httpClientConfig.getClientCertificate()) : null; headers = httpClientConfig.getHeaders() != null ? Collections.unmodifiableMap(new HashMap<>(httpClientConfig.getHeaders())) : null; retryHandler = httpClientConfig.getRetryHandler(); numOfRetries = httpClientConfig.getNumOfRetries(); + enableMetricLogging = httpClientConfig.isEnableMetricLogging(); + } + + public boolean isEnableMetricLogging() { + return enableMetricLogging; } Map<String, String> getHeaders() { return headers; } - int getNumOfRetries() { + public int getNumOfRetries() { return numOfRetries; } - + String getBasicAuthPassword() { return basicAuthorization != null ? basicAuthorization.getPassword() : null; } @@ -82,20 +88,20 @@ final class HttpClientConfigImmutable { ClientCertificate getClientCertificate() { return clientCertificate != null ? new ClientCertificate(clientCertificate) : null; } - - int getReadTimeoutMs() { + + public int getReadTimeoutMs() { return timeouts.getReadTimeoutMs(); } - int getConnectTimeoutMs() { + public int getConnectTimeoutMs() { return timeouts.getConnectTimeoutMs(); } - int getConnectPoolTimeoutMs() { + public int getConnectPoolTimeoutMs() { return timeouts.getConnectPoolTimeoutMs(); } - ComparableHttpRequestRetryHandler getRetryHandler() { + public ComparableHttpRequestRetryHandler getRetryHandler() { return retryHandler; } @@ -113,51 +119,43 @@ final class HttpClientConfigImmutable { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } HttpClientConfigImmutable other = (HttpClientConfigImmutable) obj; if (basicAuthorization == null) { - if (other.basicAuthorization != null) { + if (other.basicAuthorization != null) return false; - } - } else if (!basicAuthorization.equals(other.basicAuthorization)) { - return false; } + else if (!basicAuthorization.equals(other.basicAuthorization)) + return false; if (clientCertificate == null) { - if (other.clientCertificate != null) { + if (other.clientCertificate != null) return false; - } - } else if (!clientCertificate.equals(other.clientCertificate)) { - return false; } + else if (!clientCertificate.equals(other.clientCertificate)) + return false; if (headers == null) { - if (other.headers != null) { + if (other.headers != null) return false; - } - } else if (!headers.equals(other.headers)) { - return false; } + else if (!headers.equals(other.headers)) + return false; if (retryHandler == null) { - if (other.retryHandler != null) { + if (other.retryHandler != null) return false; - } - } else if (!retryHandler.compare(other.retryHandler)) { - return false; } + else if (!retryHandler.compare(other.retryHandler)) + return false; if (timeouts == null) { - if (other.timeouts != null) { + if (other.timeouts != null) return false; - } - } else if (!timeouts.equals(other.timeouts)) { - return false; } + else if (!timeouts.equals(other.timeouts)) + return false; return true; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java index 24e2f909bc..982453246f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,33 +25,36 @@ import org.apache.http.client.UserTokenHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.http.config.ClientCertificate; +import org.openecomp.sdc.common.log.interceptors.ApacheClientLogRequestInterceptor; +import org.openecomp.sdc.common.log.interceptors.ApacheClientLogResponseInterceptor; import org.openecomp.sdc.common.log.wrappers.Logger; public class HttpClientFactory { - private static final Logger LOGGER = Logger.getLogger(HttpClientFactory.class.getName()); - private static final UserTokenHandler USER_TOKEN_HANDLER = context -> null; + private static final Logger logger = Logger.getLogger(HttpClientFactory.class.getName()); + private static final UserTokenHandler userTokenHandler = context -> null; private final HttpConnectionMngFactory connectionMngFactory; - + HttpClientFactory(HttpConnectionMngFactory connectionMngFactory) { this.connectionMngFactory = connectionMngFactory; } HttpClient createClient(String protocol, HttpClientConfigImmutable config) { - LOGGER.debug("Create {} client based on {}", protocol, config); + logger.debug("Create {} client based on {}", protocol, config); - ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; + ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate); RequestConfig requestConfig = createClientTimeoutConfiguration(config); CloseableHttpClient client = HttpClients.custom() - .setDefaultRequestConfig(requestConfig) - .setConnectionManager(connectionManager) - .setUserTokenHandler(USER_TOKEN_HANDLER) - .setRetryHandler(resolveRetryHandler(config)) - .build(); + .setDefaultRequestConfig(requestConfig) + .setConnectionManager(connectionManager) + .setUserTokenHandler(userTokenHandler) + .setRetryHandler(resolveRetryHandler(config)) + .build(); return new HttpClient(client, config); } @@ -59,7 +62,7 @@ public class HttpClientFactory { private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null; } - + private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { return RequestConfig.custom() .setConnectTimeout(config.getConnectTimeoutMs()) diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java index d5d03329bb..c5634eaf8c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -48,42 +48,43 @@ public class HttpConnectionMngFactory { private static final String P12_KEYSTORE_EXTENTION = ".p12"; private static final String PFX_KEYSTORE_EXTENTION = ".pfx"; private static final String JKS_KEYSTORE_EXTENTION = ".jks"; - + private static final String P12_KEYSTORE_TYPE = "pkcs12"; private static final String JKS_KEYSTORE_TYPE = "jks"; - - private static final Logger LOGGER = Logger.getLogger(HttpConnectionMngFactory.class.getName()); + + private static final Logger logger = Logger.getLogger(HttpConnectionMngFactory.class.getName()); private static final int DEFAULT_CONNECTION_POOL_SIZE = 30; private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5; private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000; - + private Map<ClientCertificate, HttpClientConnectionManager> sslClientConnectionManagers = new ConcurrentHashMap<>(); private HttpClientConnectionManager plainClientConnectionManager; - + HttpConnectionMngFactory() { plainClientConnectionManager = createConnectionMng(null); } HttpClientConnectionManager getOrCreate(ClientCertificate clientCertificate) { - if (clientCertificate == null) { + if(clientCertificate == null) { return plainClientConnectionManager; } return sslClientConnectionManagers.computeIfAbsent(clientCertificate, k -> createConnectionMng(clientCertificate)); } - + private HttpClientConnectionManager createConnectionMng(ClientCertificate clientCertificate) { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); SSLConnectionSocketFactory sslsf = null; try { sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy()); - - if (clientCertificate != null) { + + if(clientCertificate != null) { setClientSsl(clientCertificate, sslContextBuilder); } sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE); - } catch (GeneralSecurityException e) { - LOGGER.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); + } + catch (GeneralSecurityException e) { + logger.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); sslsf = SSLConnectionSocketFactory.getSocketFactory(); } @@ -105,12 +106,13 @@ public class HttpConnectionMngFactory { char[] keyStorePassword = clientCertificate.getKeyStorePassword().toCharArray(); KeyStore clientKeyStore = createClientKeyStore(clientCertificate.getKeyStore(), keyStorePassword); sslContextBuilder.loadKeyMaterial(clientKeyStore, keyStorePassword); - LOGGER.debug("#setClientSsl - Set Client Certificate authentication"); - } catch (IOException | GeneralSecurityException e) { - LOGGER.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); + logger.debug("#setClientSsl - Set Client Certificate authentication"); + } + catch (IOException | GeneralSecurityException e) { + logger.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e); } } - + private KeyStore createClientKeyStore(String keyStorePath, char[] keyStorePassword) throws IOException, GeneralSecurityException { KeyStore keyStore = null; try (InputStream stream = new FileInputStream(keyStorePath)) { @@ -119,14 +121,15 @@ public class HttpConnectionMngFactory { } return keyStore; } - + private String getKeyStoreType(String keyStore) { - if (!StringUtils.isEmpty(keyStore)) { - if (keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { + if(!StringUtils.isEmpty(keyStore)) { + if(keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) { return P12_KEYSTORE_TYPE; - } else if (keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { - return JKS_KEYSTORE_TYPE; } + else if(keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) { + return JKS_KEYSTORE_TYPE; + } } return KeyStore.getDefaultType(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java index 2b2e7a4f12..8487e1ff72 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,17 +25,17 @@ public class HttpExecuteException extends Exception { private static final long serialVersionUID = 1L; public HttpExecuteException(String message) { - super(message); + super (message); } public HttpExecuteException(String message, Throwable cause) { - super(message, cause); + super (message, cause); } public HttpExecuteException(Throwable cause) { super(cause); } - + @Override public Throwable getCause() { Throwable cause = super.getCause(); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java index b418ce744e..57e5cb2bed 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,34 +28,27 @@ import java.util.Properties; //TODO- remove all static and use instance methods for better testing public abstract class HttpRequest { - private static final Properties DEFAULT_HEADERS = null; - private static final HttpClientConfig DEFAULT_CONFIG = new HttpClientConfig(); + static final Properties defaultHeaders = null; + static final HttpClientConfig defaultConfig = new HttpClientConfig(); - private HttpRequest() { - } - - public static Properties getDefaultHeaders() { - return DEFAULT_HEADERS; - } - public static HttpClientConfig getDefaultConfig() { - return DEFAULT_CONFIG; + private HttpRequest() { } /* * GET response as string */ public static HttpResponse<String> get(String url) throws HttpExecuteException { - return get(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return get(url, defaultHeaders, defaultConfig); } public static HttpResponse<String> get(String url, Properties headers) throws HttpExecuteException { - return get(url, headers, DEFAULT_CONFIG); + return get(url, headers, defaultConfig); } - + public static HttpResponse<String> get(String url, HttpClientConfig config) throws HttpExecuteException { - return get(url, DEFAULT_HEADERS, config); + return get(url, defaultHeaders, config); } public static HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { @@ -66,15 +59,15 @@ public abstract class HttpRequest { * GET response as byte array */ public static HttpResponse<byte[]> getAsByteArray(String url) throws HttpExecuteException { - return getAsByteArray(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return getAsByteArray(url, defaultHeaders, defaultConfig); } public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers) throws HttpExecuteException { - return getAsByteArray(url, headers, DEFAULT_CONFIG); + return getAsByteArray(url, headers, defaultConfig); } public static HttpResponse<byte[]> getAsByteArray(String url, HttpClientConfig config) throws HttpExecuteException { - return getAsByteArray(url, DEFAULT_HEADERS, config); + return getAsByteArray(url, defaultHeaders, config); } public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { @@ -85,15 +78,15 @@ public abstract class HttpRequest { * PUT */ public static HttpResponse<String> put(String url, HttpEntity entity) throws HttpExecuteException { - return put(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return put(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return put(url, headers, entity, DEFAULT_CONFIG); + return put(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> put(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return put(url, DEFAULT_HEADERS, entity, config); + return put(url, defaultHeaders, entity, config); } public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { @@ -104,59 +97,59 @@ public abstract class HttpRequest { * POST */ public static HttpResponse<String> post(String url, HttpEntity entity) throws HttpExecuteException { - return post(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return post(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return post(url, headers, entity, DEFAULT_CONFIG); + return post(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> post(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return post(url, DEFAULT_HEADERS, entity, config); + return post(url, defaultHeaders, entity, config); } public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().post(url, headers, entity, config); } - + /* * PATCH */ public static HttpResponse<String> patch(String url, HttpEntity entity) throws HttpExecuteException { - return patch(url, DEFAULT_HEADERS, entity, DEFAULT_CONFIG); + return patch(url, defaultHeaders, entity, defaultConfig); } public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { - return patch(url, headers, entity, DEFAULT_CONFIG); + return patch(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> patch(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { - return patch(url, DEFAULT_HEADERS, entity, config); + return patch(url, defaultHeaders, entity, config); } public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().patch(url, headers, entity, config); } - + /* * DELETE */ public static HttpResponse<String> delete(String url) throws HttpExecuteException { - return delete(url, DEFAULT_HEADERS, DEFAULT_CONFIG); + return delete(url, defaultHeaders, defaultConfig); } public static HttpResponse<String> delete(String url, Properties headers) throws HttpExecuteException { - return delete(url, headers, DEFAULT_CONFIG); + return delete(url, headers, defaultConfig); } - + public static HttpResponse<String> delete(String url, HttpClientConfig config) throws HttpExecuteException { - return delete(url, DEFAULT_HEADERS, config); + return delete(url, defaultHeaders, config); } public static HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().delete(url, headers, config); } - + public static void destroy() { HttpRequestHandler.get().destroy(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java index e4747f4308..73f0f15354 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,10 +38,10 @@ public class HttpRequestHandler { private static HttpRequestHandler handlerInstance = new HttpRequestHandler(); private static final String HTTPS_PREFIX = "https://"; private static final String HTTP_PREFIX = "http://"; - + private Map<HttpClientConfigImmutable, HttpClient> clients = new ConcurrentHashMap<>(); private HttpClientFactory clientFactory; - + private FunctionThrows<CloseableHttpResponse, HttpResponse<byte[]>, Exception> byteResponseBuilder = (CloseableHttpResponse httpResponse) -> { HttpEntity entity = httpResponse.getEntity(); byte[] response = null; @@ -51,8 +51,8 @@ public class HttpRequestHandler { response = IOUtils.toByteArray(content); } } - return new HttpResponse<>(response, - httpResponse.getStatusLine().getStatusCode(), + return new HttpResponse<>(response, + httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; @@ -62,7 +62,7 @@ public class HttpRequestHandler { if (entity != null) { response = EntityUtils.toString(entity); } - return new HttpResponse<>(response, + return new HttpResponse<>(response, httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; @@ -71,7 +71,7 @@ public class HttpRequestHandler { HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory(); clientFactory = new HttpClientFactory(connectionMngFactory); } - + public static HttpRequestHandler get() { return handlerInstance; } @@ -81,7 +81,7 @@ public class HttpRequestHandler { return client.<String>get(url, headers, stringResponseBuilder); } - public HttpResponse<byte[]> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { + public HttpResponse<byte []> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { HttpClient client = getOrCreateClient(url, config); return client.<byte[]>get(url, headers, byteResponseBuilder); } @@ -102,15 +102,15 @@ public class HttpRequestHandler { } public HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { - HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.getDefaultConfig()); + HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.defaultConfig); return client.<String>delete(url, headers, stringResponseBuilder); } - + public void destroy() { clients.forEach((k, v) -> v.close()); clients.clear(); } - + private HttpClient getOrCreateClient(String url, HttpClientConfig config) throws HttpExecuteException { String protocol = getProtocol(url); HttpClientConfigImmutable httpClientConfigImmutable = HttpClientConfigImmutable.getOrCreate(config); @@ -129,10 +129,12 @@ public class HttpRequestHandler { private String getProtocol(String url) throws HttpExecuteException { if (url.startsWith(HTTPS_PREFIX)) { return Constants.HTTPS; - } else if (url.startsWith(HTTP_PREFIX)) { + } + else if (url.startsWith(HTTP_PREFIX)) { return Constants.HTTP; - } else { - throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); } + else { + throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url)); + } } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java index b3a4a96b2f..c6061cf1c2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ public class HttpResponse<T> { this.statusCode = statusCode; this.description = StringUtils.EMPTY; } - + public HttpResponse(T response, int statusCode, String description) { this.response = response; this.statusCode = statusCode; @@ -63,6 +63,6 @@ public class HttpResponse<T> { builder.append("]"); return builder.toString(); } - - + + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java index 88c4a4fe87..71f9ac2629 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,7 +24,7 @@ import org.apache.http.HttpStatus; public final class Responses { public static final HttpResponse<String> INTERNAL_SERVER_ERROR = new HttpResponse<>("Internal server error", HttpStatus.SC_INTERNAL_SERVER_ERROR); - + private Responses() { } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java index efac5c18ef..7b39e3f8c9 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java index f611ad6eba..bbcd815e75 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,15 +27,14 @@ import java.io.IOException; public class RetryHandlers { - private static final Logger LOGGER = Logger.getLogger(RetryHandlers.class.getName()); + private static final Logger logger = Logger.getLogger(RetryHandlers.class.getName()); - private RetryHandlers() { - } + private RetryHandlers(){} public static ComparableHttpRequestRetryHandler getDefault(int numOfRetries) { return (IOException exception, int executionCount, HttpContext context) -> { - LOGGER.debug("failed sending request with exception", exception); - LOGGER.debug("try request number: {}", executionCount); + logger.debug("failed sending request with exception", exception); + logger.debug("try request number: {}", executionCount); return executionCount <= numOfRetries; }; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java index 47338b77e7..124c7ea0c8 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.http.config; import fj.data.Either; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.security.SecurityUtil; +import org.onap.sdc.security.SecurityUtil; public class BasicAuthorization { private String userName; @@ -53,17 +53,19 @@ public class BasicAuthorization { return password; } - + private void setPassword(String password, boolean isEncoded) { validate(password); - if (isEncoded) { + if(isEncoded) { Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(password); - if (passkey.isLeft()) { + if(passkey.isLeft()) { this.password = passkey.left().value(); - } else { + } + else { throw new IllegalArgumentException(passkey.right().value()); } - } else { + } + else { this.password = password; } } @@ -79,28 +81,26 @@ public class BasicAuthorization { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } BasicAuthorization other = (BasicAuthorization) obj; if (password == null) { - if (other.password != null) { + if (other.password != null) return false; - } - } else if (!password.equals(other.password)) { - return false; } + else if (!password.equals(other.password)) + return false; if (userName == null) { - return other.userName == null; - } else { - return userName.equals(other.userName); + if (other.userName != null) + return false; } + else if (!userName.equals(other.userName)) + return false; + return true; } @Override @@ -113,7 +113,7 @@ public class BasicAuthorization { } private void validate(String str) { - if (StringUtils.isEmpty(str)) { + if(StringUtils.isEmpty(str)) { throw new IllegalArgumentException("BasicAuthorization username and/or password cannot be empty"); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java index 259d965b0d..1f6c070094 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.common.http.config; import fj.data.Either; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.security.SecurityUtil; +import org.onap.sdc.security.SecurityUtil; public class ClientCertificate { private String keyStore; @@ -35,7 +35,7 @@ public class ClientCertificate { setKeyStore(clientCertificate.getKeyStore()); setKeyStorePassword(clientCertificate.getKeyStorePassword(), false); } - + public void setKeyStore(String keyStore) { validate(keyStore); this.keyStore = keyStore; @@ -47,14 +47,16 @@ public class ClientCertificate { private void setKeyStorePassword(String keyStorePassword, boolean isEncoded) { validate(keyStorePassword); - if (isEncoded) { + if(isEncoded) { Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(keyStorePassword); if (passkey.isLeft()) { this.keyStorePassword = passkey.left().value(); - } else { + } + else { throw new IllegalArgumentException(passkey.right().value()); } - } else { + } + else { this.keyStorePassword = keyStorePassword; } } @@ -66,7 +68,7 @@ public class ClientCertificate { public String getKeyStorePassword() { return keyStorePassword; } - + @Override public int hashCode() { final int prime = 31; @@ -78,37 +80,39 @@ public class ClientCertificate { @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } ClientCertificate other = (ClientCertificate) obj; if (keyStore == null) { - if (other.keyStore != null) { + if (other.keyStore != null) return false; - } - } else if (!keyStore.equals(other.keyStore)) { - return false; } + else if (!keyStore.equals(other.keyStore)) + return false; if (keyStorePassword == null) { - return other.keyStorePassword == null; - } else { - return keyStorePassword.equals(other.keyStorePassword); + if (other.keyStorePassword != null) + return false; } + else if (!keyStorePassword.equals(other.keyStorePassword)) + return false; + return true; } @Override public String toString() { - return "ClientCertificate [keyStore=" + keyStore + "]"; + StringBuilder builder = new StringBuilder(); + builder.append("ClientCertificate [keyStore="); + builder.append(keyStore); + builder.append("]"); + return builder.toString(); } - + private void validate(String str) { - if (StringUtils.isEmpty(str)) { + if(StringUtils.isEmpty(str)) { throw new IllegalArgumentException("ClientCertificate keystore and/or kestorePassword cannot be empty"); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java index 2af8e74447..dcc9b73bcd 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,14 +21,14 @@ package org.openecomp.sdc.common.http.config; public class ExternalServiceConfig { - + private HttpRequestConfig httpRequestConfig; private HttpClientConfig httpClientConfig; public HttpRequestConfig getHttpRequestConfig() { return httpRequestConfig; } - + public void setHttpRequestConfig(HttpRequestConfig httpRequestConfig) { this.httpRequestConfig = httpRequestConfig; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java index 3ed3b7c86c..a4f12e3eec 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.openecomp.sdc.common.http.config; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.nustaq.serialization.annotations.Serialize; import org.openecomp.sdc.common.http.client.api.ComparableHttpRequestRetryHandler; import java.util.Map; @@ -32,10 +34,12 @@ public class HttpClientConfig { private Timeouts timeouts = Timeouts.DEFAULT; private Map<String, String> headers; private int numOfRetries; + @JsonIgnore + private boolean enableMetricLogging = false; - public HttpClientConfig() { + public HttpClientConfig() { } - + public HttpClientConfig(Timeouts timeouts) { setTimeouts(timeouts); } @@ -81,11 +85,11 @@ public class HttpClientConfig { public void setClientCertificate(ClientCertificate clientCertificate) { this.clientCertificate = clientCertificate; } - + public Map<String, String> getHeaders() { return headers; } - + public void setHeaders(Map<String, String> headers) { this.headers = headers; } @@ -93,11 +97,19 @@ public class HttpClientConfig { public int getNumOfRetries() { return numOfRetries; } - + public void setNumOfRetries(int numOfRetries) { this.numOfRetries = numOfRetries; } + public boolean isEnableMetricLogging() { + return enableMetricLogging; + } + + public void setEnableMetricLogging(boolean enableMetricLogging) { + this.enableMetricLogging = enableMetricLogging; + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); @@ -113,6 +125,8 @@ public class HttpClientConfig { builder.append(headers); builder.append(", numOfRetries="); builder.append(numOfRetries); + builder.append(", enableMetricLogging="); + builder.append(enableMetricLogging); builder.append("]"); return builder.toString(); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java index 89e3532a10..040d068dfe 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,22 +27,22 @@ public class HttpRequestConfig { private String serverRootUrl; private Map<String, String> resourceNamespaces; - + public String getServerRootUrl() { return serverRootUrl; } - + public void setServerRootUrl(String serverRootUrl) { this.serverRootUrl = serverRootUrl; } - + public Map<String, String> getResourceNamespaces() { - if (resourceNamespaces == null) { + if(resourceNamespaces == null) { resourceNamespaces = new HashMap<>(); } return resourceNamespaces; } - + public void setResourceNamespaces(Map<String, String> resourceNamespaces) { this.resourceNamespaces = resourceNamespaces; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java index e8711f4d12..39ef8555ad 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,9 +28,8 @@ public class Timeouts { private int connectPoolTimeoutMs = DEFAULT_TIMEOUT_MS; public static final Timeouts DEFAULT; - static { - DEFAULT = new Timeouts(); + DEFAULT = new Timeouts(); } private Timeouts() { @@ -50,30 +49,30 @@ public class Timeouts { public int getConnectTimeoutMs() { return connectTimeoutMs; } - + public void setConnectTimeoutMs(int connectTimeoutMs) { validate(connectTimeoutMs); this.connectTimeoutMs = connectTimeoutMs; } - + public int getReadTimeoutMs() { return readTimeoutMs; } - + public void setReadTimeoutMs(int readTimeoutMs) { validate(readTimeoutMs); this.readTimeoutMs = readTimeoutMs; } - + public int getConnectPoolTimeoutMs() { return connectPoolTimeoutMs; } - + public void setConnectPoolTimeoutMs(int connectPoolTimeoutMs) { validate(connectPoolTimeoutMs); this.connectPoolTimeoutMs = connectPoolTimeoutMs; } - + @Override public int hashCode() { final int prime = 31; @@ -83,38 +82,40 @@ public class Timeouts { result = prime * result + readTimeoutMs; return result; } - + @Override public boolean equals(Object obj) { - if (this == obj) { + if (this == obj) return true; - } - if (obj == null) { + if (obj == null) return false; - } - if (getClass() != obj.getClass()) { + if (getClass() != obj.getClass()) return false; - } Timeouts other = (Timeouts) obj; - if (connectPoolTimeoutMs != other.connectPoolTimeoutMs) { + if (connectPoolTimeoutMs != other.connectPoolTimeoutMs) return false; - } - if (connectTimeoutMs != other.connectTimeoutMs) { + if (connectTimeoutMs != other.connectTimeoutMs) return false; - } - return readTimeoutMs == other.readTimeoutMs; + if (readTimeoutMs != other.readTimeoutMs) + return false; + return true; } - + @Override public String toString() { - return "Timeouts [connectTimeoutMs=" + connectTimeoutMs - + ", readTimeoutMs=" + readTimeoutMs - + ", connectPoolTimeoutMs=" + connectPoolTimeoutMs - + "]"; + StringBuilder builder = new StringBuilder(); + builder.append("Timeouts [connectTimeoutMs="); + builder.append(connectTimeoutMs); + builder.append(", readTimeoutMs="); + builder.append(readTimeoutMs); + builder.append(", connectPoolTimeoutMs="); + builder.append(connectPoolTimeoutMs); + builder.append("]"); + return builder.toString(); } - + private void validate(int timeout) { - if (timeout <= 0) { + if(timeout <= 0) { throw new IllegalArgumentException("Timeout values cannot be less than zero"); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java index f1f1305ee9..e243bac730 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ConfigFileChangeListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,111 +35,111 @@ import java.util.Map; public class ConfigFileChangeListener extends FileChangeListener { - private static Logger log = Logger.getLogger(ConfigFileChangeListener.class.getName()); + private static Logger log = Logger.getLogger(ConfigFileChangeListener.class.getName()); - private Map<String, List<ConfigurationListener>> fileChangeToCallBack = new HashMap<>(); + private Map<String, List<ConfigurationListener>> fileChangeToCallBack = new HashMap<>(); - private Object lock = new Object(); + private Object lock = new Object(); - private YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + private YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - @Override - public void onFileChange(File pFile) { + @Override + public void onFileChange(File pFile) { - super.onFileChange(pFile); + super.onFileChange(pFile); - if (pFile != null) { + if (pFile != null) { - if (fileChangeToCallBack != null) { + if (fileChangeToCallBack != null) { - String id = findIdFromFileName(pFile.getName()); + String id = findIdFromFileName(pFile.getName()); - if (id != null) { + if (id != null) { - List<ConfigurationListener> listeners = fileChangeToCallBack.get(id); - if (listeners != null) { - for (ConfigurationListener configurationListener : listeners) { + List<ConfigurationListener> listeners = fileChangeToCallBack.get(id); + if (listeners != null) { + for (ConfigurationListener configurationListener : listeners) { - Class<? extends BasicConfiguration> configClass = configurationListener.getType(); + Class<? extends BasicConfiguration> configClass = configurationListener.getType(); - BasicConfiguration basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass); + BasicConfiguration basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass); - if (basicConfiguration == null) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Cannot update the listeners for file Change since the file content is invalid"); - continue; - } - log.debug("Loaded configuration after converting is {}", basicConfiguration); + if (basicConfiguration == null) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Cannot update the listeners for file Change since the file content is invalid"); + continue; + } + log.debug("Loaded configuration after converting is {}", basicConfiguration); - configurationListener.getCallBack().reconfigure(basicConfiguration); + configurationListener.getCallBack().reconfigure(basicConfiguration); - } - } - } else { + } + } + } else { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Cannot calculate id from file {}", pFile.getName()); - } - } + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Cannot calculate id from file {}", pFile.getName()); + } + } - } + } - log.debug("File {} was changed.", pFile); - } + log.debug("File {} was changed.", pFile); + } - private String findIdFromFileName(String name) { + private String findIdFromFileName(String name) { - String result = null; - if (name != null) { - int startIndex = 0; - int endIndex = name.length(); - if (name.contains(File.separator)) { - startIndex = name.lastIndexOf(File.separator); - } - // String subNameString = name.substring(startIndex, endIndex); - // if (subNameString.contains(".")) { - // endIndex = subNameString.indexOf("."); - // } + String result = null; + if (name != null) { + int startIndex = 0; + int endIndex = name.length(); + if (name.contains(File.separator)) { + startIndex = name.lastIndexOf(File.separator); + } + // String subNameString = name.substring(startIndex, endIndex); + // if (subNameString.contains(".")) { + // endIndex = subNameString.indexOf("."); + // } - result = name.substring(startIndex, endIndex); + result = name.substring(startIndex, endIndex); - } + } - return result; - } + return result; + } - public void register(String id, ConfigurationListener configurationListener) { + public void register(String id, ConfigurationListener configurationListener) { - if (configurationListener != null) { + if (configurationListener != null) { - synchronized (lock) { + synchronized (lock) { - List<ConfigurationListener> callbacks = fileChangeToCallBack.get(id); - if (callbacks == null) { - callbacks = new ArrayList<>(); - fileChangeToCallBack.put(id, callbacks); - } - callbacks.add(configurationListener); + List<ConfigurationListener> callbacks = fileChangeToCallBack.get(id); + if (callbacks == null) { + callbacks = new ArrayList<>(); + fileChangeToCallBack.put(id, callbacks); + } + callbacks.add(configurationListener); - } + } - } + } - } + } - // public void notify(String id, BasicConfiguration object) { - // - // if (fileChangeToCallBack != null) { - // List<ConfigurationListener> listeners = fileChangeToCallBack - // .get(id); - // if (listeners != null) { - // for (ConfigurationListener configurationListener : listeners) { - // - // configurationListener.getCallBack().reconfigure(object); - // - // } - // } - // } - // - // } + // public void notify(String id, BasicConfiguration object) { + // + // if (fileChangeToCallBack != null) { + // List<ConfigurationListener> listeners = fileChangeToCallBack + // .get(id); + // if (listeners != null) { + // for (ConfigurationListener configurationListener : listeners) { + // + // configurationListener.getCallBack().reconfigure(object); + // + // } + // } + // } + // + // } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java index f1a1f490ca..79a78828e8 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/ExternalConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,80 +26,81 @@ import org.openecomp.sdc.common.api.ConfigurationSource; import java.io.File; /** + * * Save the - * + * * @author esofer + * */ public class ExternalConfiguration { - public static final int FILESYSTEM_MONITOR_INTERVAL = 1000; - private static String appName; - private static String appVersion; - private static String configDir; - private static ConfigurationSource configurationSource; - - private static FilesystemAlterationMonitor fam = null; - - private static ConfigFileChangeListener changeListener = new ConfigFileChangeListener(); - - private static boolean enableReconfigure = true; - - public static String getAppName() { - return appName; - } - - public static void setAppName(String appName) { - ExternalConfiguration.appName = appName; - } - - public static String getAppVersion() { - return appVersion; - } - - public static void setAppVersion(String appVersion) { - ExternalConfiguration.appVersion = appVersion; - } - - public static String getConfigDir() { - return configDir; - } - - public static void setConfigDir(String configDir) { - ExternalConfiguration.configDir = configDir; - } - - public static ConfigurationSource getConfigurationSource() { - return configurationSource; - } - - public static void setConfigurationSource(ConfigurationSource configurationSource) { - ExternalConfiguration.configurationSource = configurationSource; - } - - public static ConfigFileChangeListener getChangeListener() { - return changeListener; - } - - public static void listenForChanges() { - - String watchingDir = configDir + File.separator + appName; - if (enableReconfigure) { - if (fam == null) { - fam = new FilesystemAlterationMonitor(); - fam.setInterval(FILESYSTEM_MONITOR_INTERVAL); - fam.addListener(new File(watchingDir), changeListener); - fam.start(); - } - } - } - - public static void stopListenForFileChanges() { - if (enableReconfigure) { - if (fam != null) { - fam.stop(); - fam = null; - } - } - } + private static String appName; + private static String appVersion; + private static String configDir; + private static ConfigurationSource configurationSource; + + private static FilesystemAlterationMonitor fam = null; + + private static ConfigFileChangeListener changeListener = new ConfigFileChangeListener(); + + private static boolean enableReconfigure = true; + + public static String getAppName() { + return appName; + } + + public static void setAppName(String appName) { + ExternalConfiguration.appName = appName; + } + + public static String getAppVersion() { + return appVersion; + } + + public static void setAppVersion(String appVersion) { + ExternalConfiguration.appVersion = appVersion; + } + + public static String getConfigDir() { + return configDir; + } + + public static void setConfigDir(String configDir) { + ExternalConfiguration.configDir = configDir; + } + + public static ConfigurationSource getConfigurationSource() { + return configurationSource; + } + + public static void setConfigurationSource(ConfigurationSource configurationSource) { + ExternalConfiguration.configurationSource = configurationSource; + } + + public static ConfigFileChangeListener getChangeListener() { + return changeListener; + } + + public static void listenForChanges() { + + String watchingDir = configDir + File.separator + appName; + if (enableReconfigure) { + if (fam == null) { + fam = new FilesystemAlterationMonitor(); + fam.setInterval(1000); + fam.addListener(new File(watchingDir), changeListener); + fam.start(); + } + } + } + + public static void stopListenForFileChanges() { + if (enableReconfigure) { + if (fam != null) { + fam.stop(); + fam = null; + } + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java index 3aa220c5bc..8cab431594 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/FSConfigurationSource.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,8 +31,9 @@ import org.openecomp.sdc.common.util.YamlToObjectConverter; /** * Read configuration from file system - * + * * @author esofer + * */ public class FSConfigurationSource implements ConfigurationSource { @@ -41,50 +42,50 @@ public class FSConfigurationSource implements ConfigurationSource { private final ConfigFileChangeListener changeListener; private final String appConfigDir; - public FSConfigurationSource(ConfigFileChangeListener changeListener, String appConfigDir) { - super(); - this.changeListener = changeListener; - this.appConfigDir = appConfigDir; - } + public FSConfigurationSource(ConfigFileChangeListener changeListener, String appConfigDir) { + super(); + this.changeListener = changeListener; + this.appConfigDir = appConfigDir; + } - /* - * get and watch configuration changes. The file name we looking for is the lower case of the class name separated by "-". - * - * (non-Javadoc) - * - * @see org.openecomp.sdc.common.api.ConfigurationSource#getAndWatchConfiguration (java.lang.Class, org.openecomp.sdc.common.api.ConfigurationListener) - */ - public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + /* + * get and watch configuration changes. The file name we looking for is the lower case of the class name separated by "-". + * + * (non-Javadoc) + * + * @see org.openecomp.sdc.common.api.ConfigurationSource#getAndWatchConfiguration (java.lang.Class, org.openecomp.sdc.common.api.ConfigurationListener) + */ + public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { - String configFileName = calculateFileName(className); + String configFileName = calculateFileName(className); - T object = yamlToObjectConverter.convert(this.appConfigDir, className, configFileName); + T object = yamlToObjectConverter.convert(this.appConfigDir, className, configFileName); - if (configurationListener != null && changeListener != null) { - if (object != null) { - changeListener.register(configFileName, configurationListener); - } - } + if (configurationListener != null && changeListener != null) { + if (object != null) { + changeListener.register(configFileName, configurationListener); + } + } - return object; - } + return object; + } - public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { - String configFileName = calculateFileName(className); + String configFileName = calculateFileName(className); - if (configurationListener != null) { - changeListener.register(configFileName, configurationListener); - } + if (configurationListener != null) { + changeListener.register(configFileName, configurationListener); + } - } + } - /** - * convert camel case string to list of words separated by "-" where each word is in lower case format. For example, MyClass will be calculated to be my-class.yaml . - * - * @param className - * @return file name based on the class name - */ + /** + * convert camel case string to list of words separated by "-" where each word is in lower case format. For example, MyClass will be calculated to be my-class.yaml . + * + * @param className + * @return file name based on the class name + */ static <T> String calculateFileName(Class<T> className) { String[] words = className.getSimpleName().split("(?=\\p{Upper})"); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java index 90ab998557..3b88ff8978 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/impl/MutableHttpServletRequest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,51 +22,46 @@ package org.openecomp.sdc.common.impl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; public final class MutableHttpServletRequest extends HttpServletRequestWrapper { - // holds custom header and value mapping - private final Map<String, String> customHeaders; + // holds custom header and value mapping + private final Map<String, String> customHeaders; - public MutableHttpServletRequest(HttpServletRequest request) { - super(request); - this.customHeaders = new HashMap<>(); - } + public MutableHttpServletRequest(HttpServletRequest request) { + super(request); + this.customHeaders = new HashMap<>(); + } - public void putHeader(String name, String value) { - this.customHeaders.put(name, value); - } + public void putHeader(String name, String value) { + this.customHeaders.put(name, value); + } - public String getHeader(String name) { - // check the custom headers first - String headerValue = customHeaders.get(name); + public String getHeader(String name) { + // check the custom headers first + String headerValue = customHeaders.get(name); - if (headerValue != null) { - return headerValue; - } - // else return from into the original wrapped object - return ((HttpServletRequest) getRequest()).getHeader(name); - } + if (headerValue != null) { + return headerValue; + } + // else return from into the original wrapped object + return ((HttpServletRequest) getRequest()).getHeader(name); + } - public Enumeration<String> getHeaderNames() { - // create a set of the custom header names - Set<String> set = new HashSet<>(customHeaders.keySet()); + public Enumeration<String> getHeaderNames() { + // create a set of the custom header names + Set<String> set = new HashSet<>(customHeaders.keySet()); - // now add the headers from the wrapped request object - @SuppressWarnings("unchecked") - Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames(); - while (e.hasMoreElements()) { - // add the names of the request headers into the list - String n = e.nextElement(); - set.add(n); - } + // now add the headers from the wrapped request object + @SuppressWarnings("unchecked") + Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames(); + while (e.hasMoreElements()) { + // add the names of the request headers into the list + String n = e.nextElement(); + set.add(n); + } - // create an enumeration from the set and return - return Collections.enumeration(set); - } + // create an enumeration from the set and return + return Collections.enumeration(set); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java index cbc5f0d56f..a4fc1b520e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/jsongraph/util/CommonUtility.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,57 +24,57 @@ import org.openecomp.sdc.common.log.wrappers.Logger; /** * Provides common utility: functionality, common fields and enumerations + * */ public class CommonUtility { - /** - * Provides list of logging level names - */ - public enum LogLevelEnum { - ERROR, - WARNING, - INFO, - DEBUG, - TRACE, - } - - /** - * Adds received message to log according to level in case if specified level is enabled - * - * @param logger - * @param logLevel - * @param format - * @param arguments - */ - public static void addRecordToLog(Logger logger, LogLevelEnum logLevel, String format, Object... arguments) { - switch (logLevel) { - case ERROR: - if (logger.isErrorEnabled()) { - logger.error(format, arguments); - } - break; - case WARNING: - if (logger.isWarnEnabled()) { - logger.warn(format, arguments); - } - break; - case INFO: - if (logger.isInfoEnabled()) { - logger.info(format, arguments); - } - break; - case DEBUG: - if (logger.isDebugEnabled()) { - logger.debug(format, arguments); - } - break; - case TRACE: - if (logger.isTraceEnabled()) { - logger.trace(format, arguments); - } - break; - default: - break; - } - } - + /** + * Provides list of logging level names + * + */ + public enum LogLevelEnum { + ERROR, + WARNING, + INFO, + DEBUG, + TRACE, + } + /** + * Adds received message to log according to level in case if specified level is enabled + * @param logger + * @param logLevel + * @param format + * @param arguments + */ + public static void addRecordToLog(Logger logger, LogLevelEnum logLevel, String format, Object... arguments ){ + switch(logLevel){ + case ERROR: + if(logger.isErrorEnabled()){ + logger.error(format, arguments); + } + break; + case WARNING: + if(logger.isWarnEnabled()){ + logger.warn(format, arguments); + } + break; + case INFO: + if(logger.isInfoEnabled()){ + logger.info(format, arguments); + } + break; + case DEBUG: + if(logger.isDebugEnabled()){ + logger.debug(format, arguments); + } + break; + case TRACE: + if(logger.isTraceEnabled()){ + logger.trace(format, arguments); + } + break; + default: + break; + } + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java b/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java index b1bd99ef76..65cf7161d4 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/kpi/api/ASDCKpiApi.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,43 +24,43 @@ import org.openecomp.sdc.common.log.wrappers.Logger; public class ASDCKpiApi { - private static Logger log = Logger.getLogger(ASDCKpiApi.class.getName()); + private static Logger log = Logger.getLogger(ASDCKpiApi.class.getName()); - /* Number of activated resource imports. */ - public static void countImportResourcesKPI() { - // TODO Auto-generated method stub - log.trace("Number of activated resource imports."); + /* Number of activated resource imports. */ + public static void countImportResourcesKPI() { + // TODO Auto-generated method stub + log.trace("Number of activated resource imports."); - } + } - /* Number of created resources. */ - public static void countCreatedResourcesKPI() { - // TODO Auto-generated method stub - log.trace("Number of created resources."); + /* Number of created resources. */ + public static void countCreatedResourcesKPI() { + // TODO Auto-generated method stub + log.trace("Number of created resources."); - } + } - /* Number of created services */ - public static void countCreatedServicesKPI() { - // TODO Auto-generated method stub - log.trace("Number of created services."); + /* Number of created services */ + public static void countCreatedServicesKPI() { + // TODO Auto-generated method stub + log.trace("Number of created services."); - } + } - /* - * Number of ASDC portal accesses ( number of activated user authorizations) - */ - public static void countUsersAuthorizations() { - // TODO Auto-generated method stub - log.trace("Number of activated distribution"); + /* + * Number of ASDC portal accesses ( number of activated user authorizations) + */ + public static void countUsersAuthorizations() { + // TODO Auto-generated method stub + log.trace("Number of activated distribution"); - } + } - /* Number of activated distribution */ - public static void countActivatedDistribution() { - // TODO Auto-generated method stub - log.trace("Number of activated distribution"); + /* Number of activated distribution */ + public static void countActivatedDistribution() { + // TODO Auto-generated method stub + log.trace("Number of activated distribution"); - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java index dd05ee47ae..f5325a73e1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,89 +39,89 @@ import java.util.jar.Manifest; public class AppContextListener implements ServletContextListener { - private static Logger log = Logger.getLogger(AppContextListener.class.getName()); + private static Logger log = Logger.getLogger(AppContextListener.class.getName()); - public void contextInitialized(ServletContextEvent context) { + public void contextInitialized(ServletContextEvent context) { - log.debug("ServletContextListener initialized "); + log.debug("ServletContextListener initialized "); - log.debug("After read values from Manifest {}", getManifestInfo(context.getServletContext())); + log.debug("After read values from Manifest {}", getManifestInfo(context.getServletContext())); - Map<String, String> manifestAttr = getManifestInfo(context.getServletContext()); + Map<String, String> manifestAttr = getManifestInfo(context.getServletContext()); - String appName = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_NAME); - String appVersion = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_VERSION); + String appName = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_NAME); + String appVersion = setAndGetAttributeInContext(context, manifestAttr, Constants.APPLICATION_VERSION); - ExternalConfiguration.setAppName(appName); - ExternalConfiguration.setAppVersion(appVersion); - String configHome = System.getProperty(Constants.CONFIG_HOME); - ExternalConfiguration.setConfigDir(configHome); + ExternalConfiguration.setAppName(appName); + ExternalConfiguration.setAppVersion(appVersion); + String configHome = System.getProperty(Constants.CONFIG_HOME); + ExternalConfiguration.setConfigDir(configHome); - String appConfigDir = configHome + File.separator + appName; - // ChangeListener changeListener = new ChangeListener(); - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), - appConfigDir); + String appConfigDir = configHome + File.separator + appName; + // ChangeListener changeListener = new ChangeListener(); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), + appConfigDir); - context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource); + context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource); - ExternalConfiguration.setConfigurationSource(configurationSource); + ExternalConfiguration.setConfigurationSource(configurationSource); - ExternalConfiguration.listenForChanges(); + ExternalConfiguration.listenForChanges(); - } + } - public void contextDestroyed(ServletContextEvent context) { + public void contextDestroyed(ServletContextEvent context) { - log.debug("ServletContextListener destroyed"); - ExternalConfiguration.stopListenForFileChanges(); - } + log.debug("ServletContextListener destroyed"); + ExternalConfiguration.stopListenForFileChanges(); + } - private String setAndGetAttributeInContext(ServletContextEvent context, Map<String, String> manifestAttr, - String attr) { + private String setAndGetAttributeInContext(ServletContextEvent context, Map<String, String> manifestAttr, + String attr) { - String name = manifestAttr.get(attr); - if (name != null) { - context.getServletContext().setAttribute(attr, name); - } + String name = manifestAttr.get(attr); + if (name != null) { + context.getServletContext().setAttribute(attr, name); + } - return name; - } + return name; + } - public static Map<String, String> getManifestInfo(ServletContext application) { + public static Map<String, String> getManifestInfo(ServletContext application) { - Map<String, String> result = new HashMap<>(); - InputStream inputStream = null; - try { + Map<String, String> result = new HashMap<>(); + InputStream inputStream = null; + try { - inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF"); + inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF"); - Manifest manifest = new Manifest(inputStream); + Manifest manifest = new Manifest(inputStream); - Attributes attr = manifest.getMainAttributes(); - String name = attr.getValue("Implementation-Title"); - if (name != null) { - result.put(Constants.APPLICATION_NAME, name); - } + Attributes attr = manifest.getMainAttributes(); + String name = attr.getValue("Implementation-Title"); + if (name != null) { + result.put(Constants.APPLICATION_NAME, name); + } - String version = attr.getValue("Implementation-Version"); - if (version != null) { - result.put(Constants.APPLICATION_VERSION, version); - } + String version = attr.getValue("Implementation-Version"); + if (version != null) { + result.put(Constants.APPLICATION_VERSION, version); + } - } catch (IOException e) { + } catch (IOException e) { - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - log.info("close FileOutputStream failed - {}", e); - } - } - } + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + log.info("close FileOutputStream failed - {}" , e); + } + } + } - return result; + return result; - } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java deleted file mode 100644 index 56fd7ad3a1..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -public interface ILogConfiguration { - String MDC_KEY_REQUEST_ID = "RequestId"; - String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceId"; - String MDC_SERVICE_NAME = "ServiceName"; - String MDC_INSTANCE_UUID = "InstanceUUID"; - String MDC_SERVER_IP_ADDRESS = "ServerIPAddress"; - String MDC_SERVER_FQDN = "ServerFQDN"; - String MDC_REMOTE_HOST = "RemoteHost"; - String MDC_AUDIT_MESSAGE = "AuditMessage"; - String MDC_ALERT_SEVERITY = "AlertSeverity"; - String MDC_AUDIT_BEGIN_TIMESTAMP = "AuditBeginTimestamp"; - String MDC_METRIC_BEGIN_TIMESTAMP = "MetricBeginTimestamp"; - String MDC_END_TIMESTAMP = "EndTimestamp"; - String MDC_PARTNER_NAME = "PartnerName"; - String MDC_STATUS_CODE = "StatusCode"; - String MDC_RESPONSE_CODE = "ResponseCode"; - String MDC_RESPONSE_DESC = "ResponseDescription"; - String MDC_ELAPSED_TIME = "ElapsedTime"; - String MDC_PROCESS_KEY = "ProcessKey"; - String MDC_TARGET_ENTITY = "TargetEntity"; - String MDC_TARGET_SERVICE_NAME = "TargetServiceName"; - String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; - String MDC_ERROR_CATEGORY = "ErrorCategory"; - String MDC_ERROR_CODE = "ErrorCode"; - String MDC_ERROR_DESC = "ErrorDescription"; - String MDC_CLASS_NAME = "ClassName"; - String MDC_OPT_FIELD1 = "CustomField1"; - String MDC_OPT_FIELD2 = "CustomField2"; - String MDC_OPT_FIELD3 = "CustomField3"; - String MDC_OPT_FIELD4 = "CustomField4"; -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java deleted file mode 100644 index 5b9728a6da..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogFieldsHandler.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -import org.openecomp.sdc.common.log.enums.Severity; - -/** - * Created by dd4296 on 12/25/2017. - */ -public interface ILogFieldsHandler { - void startAuditTimer(); - - void startMetricTimer(); - - void stopAuditTimer(); - - void stopMetricTimer(); - - void setClassName(String className); - - void setServerFQDN(String serverFQDN); - - void setServerIPAddress(String serverIPAddress); - - // intended for setting this parameter in a given thread - void setServerFQDNInternally(); - - // intended for setting this parameter in a given thread - void setServerIPAddressInternally(); - - void setInstanceUUID(String instanceUUID); - - void setProcessKey(String processKey); - - void setAlertSeverity(Severity alertSeverity); - - void setOptCustomField1(String customField1); - - void setOptCustomField2(String customField2); - - void setOptCustomField3(String customField3); - - void setOptCustomField4(String customField4); - - void setKeyRequestId(String keyRequestId); - - void setRemoteHost(String remoteHost); - - void setServiceName(String serviceName); - - void setStatusCode(String statusCode); - - void setPartnerName(String partnerName); - - void setResponseCode(int responseCode); - - void setResponseDesc(String responseDesc); - - void setServiceInstanceId(String serviceInstanceId); - - void setTargetEntity(String targetEntity); - - void setTargetServiceName(String targetServiceName); - - void setTargetVirtualEntity(String targetVirtualEntity); - - void setErrorCode(int errorCode); - - void setErrorCategory(String errorCategory); - - String getErrorCode(); - - String getServiceName(); - - String getErrorCategory(); - - void clear(); - - boolean isMDCParamEmpty(String mdcKeyName); - - String getFqdn(); - - String getHostAddress(); - - String getKeyRequestId(); - - void removeStatusCode(); - - void removePartnerName(); - - void removeResponseCode(); - - void removeResponseDesc(); - - void removeServiceInstanceId(); - - void removeTargetEntity(); - - void removeTargetServiceName(); - - void removeTargetVirtualEntity(); - - void removeErrorCode(); - - void removeErrorCategory(); - - void removeErrorDescription(); - - void setAuditMessage(String message); - - String getAuditMessage(); - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java deleted file mode 100644 index 175e7ec016..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/api/ILogger.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.api; - -import org.openecomp.sdc.common.log.enums.LogLevel; - -import java.util.List; - -/** - * Created by dd4296 on 12/24/2017. - */ -public interface ILogger { - void log(LogLevel logLevel, String message); - - void log(LogLevel logLevel, String message, Object... params); - - void log(LogLevel logLevel, String message, Throwable throwable); - - List<String> getMandatoryFields(); - - ILogger clear(); - - ILogger startTimer(); - - ILogger setKeyRequestId(String keyRequestId); -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java deleted file mode 100644 index 9f7701bb49..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandler.java +++ /dev/null @@ -1,342 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.Severity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -import java.net.InetAddress; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; - -import static java.lang.Integer.valueOf; - -public class LogFieldsMdcHandler implements ILogFieldsHandler { - - private static LogFieldsMdcHandler instanceMdcWrapper = new LogFieldsMdcHandler(); - - public static LogFieldsMdcHandler getInstance() { - return instanceMdcWrapper; - } - - private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSSz"; - private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN); - protected static Logger log = LoggerFactory.getLogger(LogFieldsMdcHandler.class.getName()); - static String hostAddress; - protected static String fqdn; - - static { - try { - hostAddress = InetAddress.getLocalHost().getHostAddress(); - fqdn = InetAddress.getByName(hostAddress).getCanonicalHostName(); - } catch (Exception ex) { - log.error("failed to get machine parameters", ex); - } - } - - @Override - public void startAuditTimer() { - if (StringUtils.isEmpty(MDC.get(ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP))) { - MDC.put(ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP, generatedTimeNow()); - } - } - - @Override - public void startMetricTimer() { - if (StringUtils.isEmpty(MDC.get(ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP))) { - MDC.put(ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP, generatedTimeNow()); - } - } - - @Override - public void stopAuditTimer() { - //set start time if it is not set yet - startAuditTimer(); - MDC.put(ILogConfiguration.MDC_END_TIMESTAMP, generatedTimeNow()); - setElapsedTime(MDC.get(ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP)); - } - - @Override - public void stopMetricTimer() { - //set start time if it is not set yet - startMetricTimer(); - MDC.put(ILogConfiguration.MDC_END_TIMESTAMP, generatedTimeNow()); - setElapsedTime(MDC.get(ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP)); - } - - @Override - public void setClassName(String className) { - MDC.put(ILogConfiguration.MDC_CLASS_NAME, className); - } - - @Override - public void setServerFQDN(String serverFQDN) { - MDC.put(ILogConfiguration.MDC_SERVER_FQDN, serverFQDN); - } - - @Override - public void setServerIPAddress(String serverIPAddress) { - MDC.put(ILogConfiguration.MDC_SERVER_IP_ADDRESS, serverIPAddress); - } - - @Override - public void setServerFQDNInternally() { - setServerFQDN(fqdn); - } - - @Override - public void setServerIPAddressInternally() { - setServerIPAddress(hostAddress); - } - - @Override - public void setInstanceUUID(String instanceUUID) { - MDC.put(ILogConfiguration.MDC_INSTANCE_UUID, instanceUUID); - } - - @Override - public void setProcessKey(String processKey) { - MDC.put(ILogConfiguration.MDC_PROCESS_KEY, processKey); - } - - @Override - public void setAlertSeverity(Severity alertSeverity) { - MDC.put(ILogConfiguration.MDC_ALERT_SEVERITY, String.valueOf(alertSeverity.getSeverityType())); - } - - @Override - public void setOptCustomField1(String customField1) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD1, customField1); - } - - @Override - public void setOptCustomField2(String customField2) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD2, customField2); - } - - @Override - public void setOptCustomField3(String customField3) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD3, customField3); - } - - @Override - public void setOptCustomField4(String customField4) { - MDC.put(ILogConfiguration.MDC_OPT_FIELD4, customField4); - } - - @Override - public void setKeyRequestId(String keyRequestId) { - MDC.put(ILogConfiguration.MDC_KEY_REQUEST_ID, keyRequestId); // eg. servletRequest.getSession().getId() - } - - @Override - public void setRemoteHost(String remoteHost) { - MDC.put(ILogConfiguration.MDC_REMOTE_HOST, remoteHost); - } - - @Override - public void setServiceName(String serviceName) { - MDC.put(ILogConfiguration.MDC_SERVICE_NAME, serviceName); - } - - @Override - public void setStatusCode(String statusCode) { - MDC.put(ILogConfiguration.MDC_STATUS_CODE, statusCode); - } - - @Override - public void setPartnerName(String partnerName) { - MDC.put(ILogConfiguration.MDC_PARTNER_NAME, partnerName); - } - - @Override - public void setResponseCode(int responseCode) { - MDC.put(ILogConfiguration.MDC_RESPONSE_CODE, Integer.toString(responseCode)); - } - - @Override - public void setResponseDesc(String responseDesc) { - MDC.put(ILogConfiguration.MDC_RESPONSE_DESC, responseDesc); - } - - @Override - public void setServiceInstanceId(String serviceInstanceId) { - MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceId); - } - - @Override - public void setTargetEntity(String targetEntity) { - MDC.put(ILogConfiguration.MDC_TARGET_ENTITY, targetEntity); - } - - @Override - public void setTargetServiceName(String targetServiceName) { - MDC.put(ILogConfiguration.MDC_TARGET_SERVICE_NAME, targetServiceName); - } - - @Override - public void setTargetVirtualEntity(String targetVirtualEntity) { - MDC.put(ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity); - } - - @Override - public void setErrorCode(int errorCode) { - MDC.put(ILogConfiguration.MDC_ERROR_CODE, valueOf(errorCode).toString()); - } - - @Override - public void setErrorCategory(String errorCategory) { - MDC.put(ILogConfiguration.MDC_ERROR_CATEGORY, errorCategory); - } - - @Override - public String getErrorCode() { - return MDC.get(ILogConfiguration.MDC_ERROR_CODE); - } - - @Override - public String getServiceName() { - return MDC.get(ILogConfiguration.MDC_SERVICE_NAME); - } - - @Override - public String getErrorCategory() { - return MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY); - } - - @Override - public void clear() { - MDC.clear(); - } - - @Override - public boolean isMDCParamEmpty(String mdcKeyName) { - return StringUtils.isEmpty(MDC.get(mdcKeyName)); - } - - @Override - public String getFqdn() { - return fqdn; - } - - @Override - public String getHostAddress() { - return hostAddress; - } - - @Override - public String getKeyRequestId() { - return MDC.get(ILogConfiguration.MDC_KEY_REQUEST_ID); - } - - @Override - public void removeStatusCode() { - MDC.remove(ILogConfiguration.MDC_STATUS_CODE); - } - - @Override - public void removePartnerName() { - MDC.remove(ILogConfiguration.MDC_PARTNER_NAME); - } - - @Override - public void removeResponseCode() { - MDC.remove(ILogConfiguration.MDC_RESPONSE_CODE); - } - - @Override - public void removeResponseDesc() { - MDC.remove(ILogConfiguration.MDC_RESPONSE_DESC); - } - - @Override - public void removeServiceInstanceId() { - MDC.remove(ILogConfiguration.MDC_SERVICE_INSTANCE_ID); - } - - @Override - public void removeTargetEntity() { - MDC.remove(ILogConfiguration.MDC_TARGET_ENTITY); - } - - @Override - public void removeTargetServiceName() { - MDC.remove(ILogConfiguration.MDC_TARGET_SERVICE_NAME); - } - - @Override - public void removeTargetVirtualEntity() { - MDC.remove(ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY); - } - - @Override - public void removeErrorCode() { - MDC.remove(ILogConfiguration.MDC_ERROR_CODE); - } - - @Override - public void removeErrorCategory() { - MDC.remove(ILogConfiguration.MDC_ERROR_CATEGORY); - } - - @Override - public void removeErrorDescription() { - MDC.remove(ILogConfiguration.MDC_ERROR_DESC); - } - - @Override - public void setAuditMessage(String message) { - MDC.put(ILogConfiguration.MDC_AUDIT_MESSAGE, message); - } - - @Override - public String getAuditMessage() { - return MDC.get(ILogConfiguration.MDC_AUDIT_MESSAGE); - } - - private void setElapsedTime(String beginTimestamp) { - try { - final LocalDateTime startTime = LocalDateTime.parse(beginTimestamp, dateTimeFormatter); - final LocalDateTime endTime = LocalDateTime.parse(MDC.get(ILogConfiguration.MDC_END_TIMESTAMP), dateTimeFormatter); - final Duration timeDifference = Duration.between(startTime, endTime); - - MDC.put(ILogConfiguration.MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis())); - - } catch (Exception ex) { - log.error("failed to calculate elapsed time", ex); - } - } - - private String generatedTimeNow() { - return dateTimeFormatter - .withZone(ZoneOffset.UTC) - .format(Instant.now()); - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java deleted file mode 100644 index 247bed2773..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerAudit.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - - -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.log.enums.StatusCode; -import org.slf4j.Logger; -import org.slf4j.MDC; -import org.slf4j.MarkerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class LoggerAudit extends LoggerBase { - private static final int STATUS_MAJOR_PART_MASK = 100; - private static ArrayList<String> mandatoryFields = new ArrayList<>(Arrays.asList( - ILogConfiguration.MDC_AUDIT_BEGIN_TIMESTAMP, - ILogConfiguration.MDC_END_TIMESTAMP, - ILogConfiguration.MDC_KEY_REQUEST_ID, - ILogConfiguration.MDC_SERVICE_NAME, - ILogConfiguration.MDC_PARTNER_NAME, - ILogConfiguration.MDC_STATUS_CODE, - ILogConfiguration.MDC_RESPONSE_CODE, - ILogConfiguration.MDC_SERVICE_INSTANCE_ID, - ILogConfiguration.MDC_RESPONSE_DESC, - ILogConfiguration.MDC_ELAPSED_TIME, - ILogConfiguration.MDC_SERVER_IP_ADDRESS, - ILogConfiguration.MDC_SERVER_FQDN)); - - private static ArrayList<String> optionalFields = new ArrayList<>(Arrays.asList( - ILogConfiguration.MDC_INSTANCE_UUID, - ILogConfiguration.MDC_ALERT_SEVERITY, - ILogConfiguration.MDC_REMOTE_HOST, - ILogConfiguration.MDC_CLASS_NAME, - ILogConfiguration.MDC_PROCESS_KEY, - ILogConfiguration.MDC_OPT_FIELD1, - ILogConfiguration.MDC_OPT_FIELD2, - ILogConfiguration.MDC_OPT_FIELD3, - ILogConfiguration.MDC_OPT_FIELD4)); - - LoggerAudit(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.AUDIT_MARKER.text()), logger); - //put the remote host and FQDN values from another thread if they are set - ecompMdcWrapper.setServerIPAddressInternally(); - ecompMdcWrapper.setServerFQDNInternally(); - } - - @Override - public LoggerAudit startTimer() { - ecompLogFieldsHandler.startAuditTimer(); - return this; - } - - public LoggerAudit stopTimer() { - ecompLogFieldsHandler.stopAuditTimer(); - return this; - } - - public LoggerAudit setInstanceUUID(String instanceUUID) { - ecompLogFieldsHandler.setInstanceUUID(instanceUUID); - return this; - } - - public LoggerAudit setOptClassName(String className) { - MDC.put("ClassName", className); - return this; - } - - public LoggerAudit setOptProcessKey(String processKey) { - ecompLogFieldsHandler.setProcessKey(processKey); - return this; - } - - public LoggerAudit setOptAlertSeverity(Severity alertSeverity) { - ecompLogFieldsHandler.setAlertSeverity(alertSeverity); - return this; - } - - // log optional parameter - public LoggerAudit setOptCustomField1(String customField1) { - ecompLogFieldsHandler.setOptCustomField1(customField1); - return this; - } - - // log optional parameter - public LoggerAudit setOptCustomField2(String customField2) { - ecompLogFieldsHandler.setOptCustomField2(customField2); - return this; - } - - // log optional parameter - public LoggerAudit setOptCustomField3(String customField3) { - ecompLogFieldsHandler.setOptCustomField3(customField3); - return this; - } - - public LoggerAudit setOptCustomField4(String customField4) { - ecompLogFieldsHandler.setOptCustomField4(customField4); - return this; - } - - @Override - public LoggerAudit setKeyRequestId(String keyRequestId) { - return (LoggerAudit) super.setKeyRequestId(keyRequestId); - } - - public LoggerAudit setRemoteHost(String remoteHost) { - ecompLogFieldsHandler.setRemoteHost(remoteHost); - return this; - } - - public LoggerAudit setServiceName(String serviceName) { - ecompLogFieldsHandler.setServiceName(serviceName); - return this; - } - - public LoggerAudit setStatusCode(String statusCode) { - // status code is either success (COMPLETE) or failure (ERROR) of the request. - String respStatus = Integer.parseInt(statusCode) / STATUS_MAJOR_PART_MASK == 2 ? StatusCode.COMPLETE.getStatusCodeEnum() : StatusCode.ERROR.getStatusCodeEnum(); - ecompLogFieldsHandler.setStatusCode(respStatus); - return this; - } - - public LoggerAudit setPartnerName(String partnerName) { - ecompLogFieldsHandler.setPartnerName(partnerName); - return this; - } - - public LoggerAudit setResponseCode(EcompLoggerErrorCode responseCode) { - ecompLogFieldsHandler.setResponseCode(responseCode.getErrorCode()); - return this; - } - - public LoggerAudit setResponseDesc(String responseDesc) { - ecompLogFieldsHandler.setResponseDesc(responseDesc); - return this; - } - - public LoggerAudit setOptServiceInstanceId(String serviceInstanceId) { - ecompLogFieldsHandler.setServiceInstanceId(serviceInstanceId); - return this; - } - - public String getAuditMessage() { - return ecompLogFieldsHandler.getAuditMessage(); - } - - - @Override - public List<String> getMandatoryFields() { - return Collections.unmodifiableList(mandatoryFields); - } - - @Override - public LoggerAudit clear() { - super.clear(); - ecompLogFieldsHandler.setServerFQDNInternally(); - ecompLogFieldsHandler.setServerIPAddressInternally(); - return this; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java deleted file mode 100644 index 1c14d24da8..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerBase.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import com.google.common.annotations.VisibleForTesting; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.api.ILogger; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; - -import java.util.Arrays; -import java.util.List; - - -/** - * Created by mm288v on 12/27/2017. - * This class holds the common behavior of all Loger-Typed classes. - * The Concrete loggers shoudl derive from this one. - */ -public abstract class LoggerBase implements ILogger { - private final Logger myLogger; - private final Marker myMarker; - final ILogFieldsHandler ecompLogFieldsHandler; - private static final String MISSING_LOG_FIELDS_MESSAGE = "mandatory parameters for ECOMP logging, missing fields: %s, original message: %s"; - - LoggerBase(ILogFieldsHandler ecompLogFieldsHandler, Marker marker, Logger logger) { - this.ecompLogFieldsHandler = ecompLogFieldsHandler; - this.myMarker = marker; - this.myLogger = logger; - setKeyRequestIdIfNotSetYet(); - } - - void setKeyRequestIdIfNotSetYet() { - if (StringUtils.isEmpty(ecompLogFieldsHandler.getKeyRequestId())) { - setKeyRequestId(ThreadLocalsHolder.getUuid()); - } - } - - private void validateMandatoryFields(String originMsg) { - // this method only checks if the mandatory fields have been initialized - String filedNameThatHasNotBeenInitialized = checkMandatoryFieldsExistInMDC(); - - if (myLogger.isDebugEnabled() && !"".equalsIgnoreCase(filedNameThatHasNotBeenInitialized)) { - myLogger.debug(MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), - String.format(MISSING_LOG_FIELDS_MESSAGE, filedNameThatHasNotBeenInitialized, originMsg)); - } - } - - @VisibleForTesting - String checkMandatoryFieldsExistInMDC() { - // this method returns a String of uninitialised fields - StringBuilder missingFields = new StringBuilder(); - getMandatoryFields().forEach(field -> { - if (ecompLogFieldsHandler.isMDCParamEmpty(field)) { - missingFields.append(field).append(" "); - } - }); - return missingFields.toString(); - } - - public abstract List<String> getMandatoryFields(); - - protected String convertExceptionStackToString(Exception ex) { - StringBuilder stackTrack = new StringBuilder(); - Arrays.asList(ex.getStackTrace()).forEach(item -> stackTrack.append(item.toString()).append("\n")); - return stackTrack.toString(); - } - - @Override - public void log(LogLevel logLevel, String message) { - log(logLevel, message, (Object) null); - } - - @Override - public void log(LogLevel logLevel, String message, Object... params) { - validateMandatoryFields(message); - - switch (logLevel) { - case ERROR: - case FATAL: //TODO check how to log "FATAL" word - myLogger.error(myMarker, message, params); - break; - case WARN: - myLogger.warn(myMarker, message, params); - break; - case INFO: - myLogger.info(myMarker, message, params); - break; - case DEBUG: - myLogger.debug(myMarker, message, params); - break; - case TRACE: - myLogger.trace(myMarker, message, params); - break; - default: - break; - } - } - - @Override - public void log(LogLevel logLevel, String message, Throwable throwable) { - validateMandatoryFields(message); - - switch (logLevel) { - case ERROR: - case FATAL: //TODO check how to log "FATAL" word - myLogger.error(myMarker, createErrorMessage(message, throwable)); - break; - case WARN: - myLogger.warn(myMarker, createErrorMessage(message, throwable)); - break; - case INFO: - myLogger.info(myMarker, createErrorMessage(message, throwable)); - break; - case DEBUG: - myLogger.debug(myMarker, message, throwable); - break; - case TRACE: - myLogger.trace(myMarker, message, throwable); - break; - default: - break; - } - } - - String createErrorMessage(String message, Throwable throwable) { - return String.format("%s: %s", message, throwable.getLocalizedMessage()); - } - - - @Override - public ILogger clear() { - ecompLogFieldsHandler.clear(); - return this; - } - - @Override - public ILogger setKeyRequestId(String keyRequestId) { - ecompLogFieldsHandler.setKeyRequestId(keyRequestId); - return this; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java deleted file mode 100644 index d7d48274c8..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerDebug.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.slf4j.Logger; -import org.slf4j.MarkerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class LoggerDebug extends LoggerBase { - - private static ArrayList<String> mandatoryFields = new ArrayList<>(Arrays.asList(ILogConfiguration.MDC_KEY_REQUEST_ID)); - - LoggerDebug(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()), logger); - } - - @Override - public LoggerDebug clear() { - //nothing to clean up - return this; - } - - @Override - public void log(LogLevel logLevel, String message, Object... params) { - setKeyRequestIdIfNotSetYet(); - super.log(logLevel, message, params); - } - - @Override - public void log(LogLevel logLevel, String message, Throwable throwable) { - setKeyRequestIdIfNotSetYet(); - super.log(logLevel, message, throwable); - } - - @Override - public void log(LogLevel logLevel, String message) { - setKeyRequestIdIfNotSetYet(); - super.log(logLevel, message); - } - - @Override - public LoggerDebug startTimer() { - return this; - } - - @Override - public List<String> getMandatoryFields() { - return mandatoryFields; - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java deleted file mode 100644 index 835c5793ba..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerError.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.config.EcompErrorConfiguration; -import org.openecomp.sdc.common.log.api.ILogConfiguration; -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.slf4j.Logger; -import org.slf4j.MarkerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class LoggerError extends LoggerBase { - private static ArrayList<String> mandatoryFields = new ArrayList<>(Arrays.asList( - ILogConfiguration.MDC_KEY_REQUEST_ID, - ILogConfiguration.MDC_SERVICE_NAME, - ILogConfiguration.MDC_ERROR_CATEGORY, - ILogConfiguration.MDC_ERROR_CODE)); - - public static final String defaultServiceName = "SDC catalog"; - - LoggerError(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.ERROR_MARKER.text()), logger); - } - - @Override - public List<String> getMandatoryFields() { - return Collections.unmodifiableList(mandatoryFields); - } - - @Override - public LoggerError setKeyRequestId(String keyRequestId) { - return (LoggerError) super.setKeyRequestId(keyRequestId); - } - - @Override - public LoggerError startTimer() { - return this; - } - - @Override - public LoggerError clear() { - ecompLogFieldsHandler.removeErrorCategory(); - ecompLogFieldsHandler.removeErrorDescription(); - ecompLogFieldsHandler.removeErrorCode(); - return this; - } - - public void log(LogLevel logLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String message, Object... params) { - fillFieldsBeforeLogging(logLevel, errorCodeEnum, serviceName, targetEntity); - super.log(logLevel, message, params); - } - - private void fillFieldsBeforeLogging(LogLevel logLevel, EcompLoggerErrorCode errorCodeEnum, String serviceName, String targetEntity) { - clear(); - ecompLogFieldsHandler.setErrorCode(errorCodeEnum.getErrorCode()); - ecompLogFieldsHandler.setErrorCategory(logLevel.name()); - if (!StringUtils.isEmpty(targetEntity)) { - //avoid overriding this parameter in MDC - ecompLogFieldsHandler.setTargetEntity(targetEntity); - } - if (StringUtils.isEmpty(ecompLogFieldsHandler.getServiceName())) { - ecompLogFieldsHandler.setServiceName(serviceName); - } - setKeyRequestIdIfNotSetYet(); - } - - public void log(EcompErrorConfiguration.EcompErrorSeverity errorSeverity, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String message, Object... params) { - log(convertFromSeverityErrorLevel(errorSeverity), errorCodeEnum, serviceName, targetEntity, message, params); - } - - public void log(LogLevel logLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String message, Object... params) { - log(logLevel, errorCodeEnum, serviceName, null, message, params); - } - - public void log(LogLevel logLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String message) { - log(logLevel, errorCodeEnum, serviceName, message); - } - - @Override - public void log(LogLevel logLevel, String message, Object... params) { - log(logLevel, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, defaultServiceName, null, message, params); - } - - public void log(LogLevel logLevel, String message, Throwable throwable) { - log(logLevel, createErrorMessage(message, throwable)); - } - - public void log(LogLevel logLevel, String message) { - log(logLevel, EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, defaultServiceName, null, message); - } - - public void logInfo(LogLevel logLevel, String message, Object... params) { - log(logLevel, EcompLoggerErrorCode.SUCCESS, defaultServiceName, null, message, params); - } - - private LogLevel convertFromSeverityErrorLevel(EcompErrorConfiguration.EcompErrorSeverity severityLevel) { - switch (severityLevel) { - case INFO: - return LogLevel.INFO; - case FATAL: - return LogLevel.FATAL; - case ERROR: - return LogLevel.ERROR; - case WARN: - return LogLevel.WARN; - default: - return LogLevel.ERROR; - } - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java deleted file mode 100644 index 41c76a3ebe..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerFactory.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.slf4j.Logger; - -/** - * Created by dd4296 on 12/26/2017. - * this factory helps decouple the classes for Stopwatch and LogFieldsMdcHandler from - * the EcompLogger classes - */ -public class LoggerFactory { - - private LoggerFactory() { - } - - @SuppressWarnings("unchecked") - public static <T, V> V getLogger(Class<T> type, Logger logger) { - - if (type.isAssignableFrom(LoggerAudit.class)) { - return (V) new LoggerAudit(new LogFieldsMdcHandler(), logger); - } - - if (type.isAssignableFrom(LoggerDebug.class)) { - return (V) new LoggerDebug(new LogFieldsMdcHandler(), logger); - } - - if (type.isAssignableFrom(LoggerMetric.class)) { - return (V) new LoggerMetric(new LogFieldsMdcHandler(), logger); - } - - if (type.isAssignableFrom(LoggerError.class)) { - return (V) new LoggerError(new LogFieldsMdcHandler(), logger); - } - - return null; - } - - @SuppressWarnings("unchecked") - public static <T, V> V getMdcLogger(Class<T> type, Logger logger) { - - if (type.isAssignableFrom(LoggerAudit.class)) { - return (V) new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); - } - - if (type.isAssignableFrom(LoggerDebug.class)) { - return (V) new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); - } - - if (type.isAssignableFrom(LoggerMetric.class)) { - return (V) new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); - } - - if (type.isAssignableFrom(LoggerError.class)) { - return (V) new LoggerError(LogFieldsMdcHandler.getInstance(), logger); - } - - return null; - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java deleted file mode 100644 index f777244952..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/elements/LoggerMetric.java +++ /dev/null @@ -1,252 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.elements; - -import org.openecomp.sdc.common.log.api.ILogFieldsHandler; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.LogMarkers; -import org.openecomp.sdc.common.log.enums.Severity; -import org.slf4j.Logger; -import org.slf4j.MarkerFactory; - -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ALERT_SEVERITY; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_CLASS_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_ELAPSED_TIME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_END_TIMESTAMP; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_INSTANCE_UUID; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_KEY_REQUEST_ID; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_METRIC_BEGIN_TIMESTAMP; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD1; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD2; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD3; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_OPT_FIELD4; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_PARTNER_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_PROCESS_KEY; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_REMOTE_HOST; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_RESPONSE_CODE; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_RESPONSE_DESC; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVER_FQDN; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVER_IP_ADDRESS; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVICE_INSTANCE_ID; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_SERVICE_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_STATUS_CODE; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_ENTITY; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_SERVICE_NAME; -import static org.openecomp.sdc.common.log.api.ILogConfiguration.MDC_TARGET_VIRTUAL_ENTITY; - - -public class LoggerMetric extends LoggerBase { - private static ArrayList<String> mandatoryFields = new ArrayList<>(Arrays.asList( - MDC_METRIC_BEGIN_TIMESTAMP, - MDC_END_TIMESTAMP, - MDC_KEY_REQUEST_ID, - MDC_SERVICE_NAME, - MDC_PARTNER_NAME, - MDC_STATUS_CODE, - MDC_RESPONSE_CODE, - MDC_SERVICE_INSTANCE_ID, - MDC_RESPONSE_DESC, - MDC_ELAPSED_TIME, - MDC_TARGET_ENTITY, - MDC_TARGET_SERVICE_NAME, - MDC_TARGET_VIRTUAL_ENTITY, - MDC_SERVER_IP_ADDRESS, - MDC_SERVER_FQDN)); - - private static ArrayList<String> optionalFields = new ArrayList<>(Arrays.asList( - MDC_INSTANCE_UUID, - MDC_ALERT_SEVERITY, - MDC_REMOTE_HOST, - MDC_CLASS_NAME, - MDC_PROCESS_KEY, - MDC_OPT_FIELD1, - MDC_OPT_FIELD2, - MDC_OPT_FIELD3, - MDC_OPT_FIELD4)); - - LoggerMetric(ILogFieldsHandler ecompMdcWrapper, Logger logger) { - super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.METRIC_MARKER.text()), logger); - //put the remote host and FQDN values from another thread if they are set - ecompMdcWrapper.setServerIPAddressInternally(); - ecompMdcWrapper.setServerFQDNInternally(); - } - - public void log(Response.StatusType statusInfo, - String className, - LogLevel logLevel, - Severity securityLevel, - String message) { - log(statusInfo, className, logLevel, securityLevel, message); - } - - @Override - public void log(LogLevel logLevel, String message) { - setKeyRequestIdIfNotSetYet(); - log(logLevel, message, (Object) null); - } - - @Override - public LoggerMetric startTimer() { - clear(); - ecompLogFieldsHandler.startMetricTimer(); - return this; - } - - public LoggerMetric stopTimer() { - ecompLogFieldsHandler.stopMetricTimer(); - return this; - } - - @Override - public LoggerMetric setKeyRequestId(String keyRequestId) { - return (LoggerMetric) super.setKeyRequestId(keyRequestId); - } - - @Override - public List<String> getMandatoryFields() { - return mandatoryFields; - } - - @Override - public LoggerMetric clear() { - ecompLogFieldsHandler.removeTargetEntity(); - ecompLogFieldsHandler.removeTargetServiceName(); - ecompLogFieldsHandler.removeResponseCode(); - ecompLogFieldsHandler.removeResponseDesc(); - ecompLogFieldsHandler.removeStatusCode(); - return this; - } - - // automatic parameter this is optional - public LoggerMetric setAutoServerFQDN(String serverFQDN) { - ecompLogFieldsHandler.setServerFQDN(serverFQDN); - return this; - } - - // automatic parameter this is optional - public LoggerMetric setAutoServerIPAddress(String serverIPAddress) { - ecompLogFieldsHandler.setServerIPAddress(serverIPAddress); - return this; - } - - public LoggerMetric setInstanceUUID(String instanceUUID) { - ecompLogFieldsHandler.setInstanceUUID(instanceUUID); - return this; - } - - // log optional parameter - public LoggerMetric setOptProcessKey(String processKey) { - ecompLogFieldsHandler.setProcessKey(processKey); - return this; - } - - // log optional parameter - public LoggerMetric setOptAlertSeverity(Severity alertSeverity) { - ecompLogFieldsHandler.setAlertSeverity(alertSeverity); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField1(String customField1) { - ecompLogFieldsHandler.setOptCustomField1(customField1); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField2(String customField2) { - ecompLogFieldsHandler.setOptCustomField2(customField2); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField3(String customField3) { - ecompLogFieldsHandler.setOptCustomField3(customField3); - return this; - } - - // log optional parameter - public LoggerMetric setOptCustomField4(String customField4) { - ecompLogFieldsHandler.setOptCustomField4(customField4); - return this; - } - - public LoggerMetric setRemoteHost(String remoteHost) { - ecompLogFieldsHandler.setRemoteHost(remoteHost); - return this; - } - - public LoggerMetric setServiceName(String serviceName) { - ecompLogFieldsHandler.setServiceName(serviceName); - return this; - } - - public LoggerMetric setStatusCode(String statusCode) { - ecompLogFieldsHandler.setStatusCode(statusCode); - return this; - } - - public LoggerMetric setPartnerName(String partnerName) { - ecompLogFieldsHandler.setPartnerName(partnerName); - return this; - } - - public LoggerMetric setResponseCode(int responseCode) { - ecompLogFieldsHandler.setResponseCode(responseCode); - return this; - } - - public LoggerMetric setResponseDesc(String responseDesc) { - ecompLogFieldsHandler.setResponseDesc(responseDesc); - return this; - } - - public LoggerMetric setOptServiceInstanceId(String serviceInstanceId) { - ecompLogFieldsHandler.setServiceInstanceId(serviceInstanceId); - return this; - } - - public LoggerMetric setOptClassName(String className) { - ecompLogFieldsHandler.setClassName(className); - return this; - } - - public LoggerMetric setTargetEntity(String targetEntity) { - ecompLogFieldsHandler.setTargetEntity(targetEntity); - return this; - } - - public LoggerMetric setTargetServiceName(String targetServiceName) { - ecompLogFieldsHandler.setTargetServiceName(targetServiceName); - return this; - } - - public LoggerMetric setTargetVirtualEntity(String targetVirtualEntity) { - ecompLogFieldsHandler.setTargetVirtualEntity(targetVirtualEntity); - return this; - } - - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java deleted file mode 100644 index ce28ca0359..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/EcompLoggerErrorCode.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -import java.util.Arrays; -import java.util.Optional; - -/** - * Created by dd4296 on 12/26/2017. - */ -public enum EcompLoggerErrorCode { - SUCCESS(0), - PERMISSION_ERROR(100), - AVAILABILITY_TIMEOUTS_ERROR(200), - DATA_ERROR(300), - SCHEMA_ERROR(400), - BUSINESS_PROCESS_ERROR(500), - UNKNOWN_ERROR(900); - - private static final int ERROR_CODE_SUBSTRING = 3; - private int errorCode; - - EcompLoggerErrorCode(int errorCode) { - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - public static EcompLoggerErrorCode getByValue(String ecompErrorCode) { - String errorPrefix = parseCode(ecompErrorCode); - Optional<EcompLoggerErrorCode> optionalCode = Arrays.stream(values()).filter(v -> isCode(v, errorPrefix)).findFirst(); - return optionalCode.orElse(UNKNOWN_ERROR); - } - - private static boolean isCode(EcompLoggerErrorCode ecompLoggerErrorCode, String errorPrefix) { - return String.valueOf(ecompLoggerErrorCode.getErrorCode()).contains(errorPrefix); - } - - private static String parseCode(String errorCode) { - try { - return errorCode.substring("E_".length(), ERROR_CODE_SUBSTRING); - } catch (StringIndexOutOfBoundsException ex) { - return UNKNOWN_ERROR.name(); - } - } - - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java deleted file mode 100644 index b04477bc82..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogLevel.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -/** - * Created by dd4296 on 12/14/2017. - */ -public enum LogLevel { - INFO, - WARN, - DEBUG, - TRACE, - ERROR, - FATAL -} - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java deleted file mode 100644 index 3e99b729dd..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/LogMarkers.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -/** - * Created by mm288v on 12/27/2017. - * This enum reflects the Marker text in logback.xml file per each ecomp marker - */ -public enum LogMarkers { - DEBUG_MARKER("DEBUG_MARKER"), - ERROR_MARKER("ERROR_MARKER"), - AUDIT_MARKER("AUDIT_MARKER"), - METRIC_MARKER("METRICS"); - - private String text; - - LogMarkers(String text) { - this.text = text; - } - - public String text() { - return text; - } - -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java deleted file mode 100644 index 9a5e8d92ab..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/Severity.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -/** - * Created by dd4296 on 12/14/2017. - */ -public enum Severity { - OK(0), - WARNING(1), - CRITICAL(2), - DOWN(3), - UNREACHABLE(4); - - private int severityType; - - Severity(int serveryType) { - this.severityType = serveryType; - } - - public int getSeverityType() { - return severityType; - } -} - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java deleted file mode 100644 index 6489916a4c..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/enums/StatusCode.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.enums; - -public enum StatusCode { - ERROR("ERROR"), - COMPLETE("COMPLETE"); - - private String statusCode; - - StatusCode(String statusCode) { - this.statusCode = statusCode; - } - - public String getStatusCodeEnum() { - return statusCode; - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java new file mode 100644 index 0000000000..b51d7f1ba9 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.common.log.interceptors; + +import org.apache.http.*; +import org.apache.http.protocol.HttpContext; +import org.onap.logging.filter.base.AbstractMetricLogFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; + +import java.io.IOException; +import java.net.URI; + +public class ApacheClientLogRequestInterceptor extends AbstractMetricLogFilter<HttpRequest, HttpResponse, HttpMessage> implements HttpRequestInterceptor { + + private String previousInvocationId; + + @Override + protected void addHeader(HttpMessage httpMessage, String s, String s1) { + httpMessage.addHeader(s, s1); + } + + @Override + protected String getTargetServiceName(HttpRequest httpRequest) { + return httpRequest.getRequestLine().getUri(); + } + + @Override + protected String getServiceName(HttpRequest httpRequest) { + return URI.create(httpRequest.getRequestLine().getUri()).getPath(); + } + + @Override + protected int getHttpStatusCode(HttpResponse httpResponse) { + return httpResponse.getStatusLine().getStatusCode(); + } + + @Override + protected String getResponseCode(HttpResponse httpResponse) { + return String.valueOf(httpResponse.getStatusLine().getStatusCode()); + } + + @Override + protected String getTargetEntity(HttpRequest httpRequest) { + //fallback to default value that provided by AbstractMetricLogFilter + return null; + } + + @Override + protected void additionalPre(HttpRequest httpRequest, HttpMessage httpMessage) { + String outgoingInvocationId = httpMessage.getFirstHeader(ONAPLogConstants.Headers.INVOCATION_ID).getValue(); + LogFieldsMdcHandler.getInstance().setOutgoingInvocationId(outgoingInvocationId); + LogFieldsMdcHandler.getInstance().setKeyInvocationId(previousInvocationId); + } + + + @Override + public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { + previousInvocationId = LogFieldsMdcHandler.getInstance().getKeyInvocationId(); + super.pre(httpRequest, httpRequest); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java new file mode 100644 index 0000000000..d7f8b952f0 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java @@ -0,0 +1,49 @@ +package org.openecomp.sdc.common.log.interceptors; + +import org.apache.http.*; +import org.apache.http.protocol.HttpContext; +import org.onap.logging.filter.base.AbstractMetricLogFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; + +import java.io.IOException; +import java.net.URI; + +public class ApacheClientLogResponseInterceptor extends AbstractMetricLogFilter<HttpRequest, HttpResponse, HttpMessage> implements HttpResponseInterceptor { + + @Override + protected void addHeader(HttpMessage httpMessage, String s, String s1) { + httpMessage.addHeader(s, s1); + } + + @Override + protected String getTargetServiceName(HttpRequest httpRequest) { + return httpRequest.getRequestLine().getUri(); + } + + @Override + protected String getServiceName(HttpRequest httpRequest) { + return URI.create(httpRequest.getRequestLine().getUri()).getPath(); + } + + @Override + protected int getHttpStatusCode(HttpResponse httpResponse) { + return httpResponse.getStatusLine().getStatusCode(); + } + + @Override + protected String getResponseCode(HttpResponse httpResponse) { + return String.valueOf(httpResponse.getStatusLine().getStatusCode()); + } + + @Override + protected String getTargetEntity(HttpRequest httpRequest) { + //fallback to default value that provided by AbstractMetricLogFilter + return null; + } + + @Override + public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { + super.post(null, httpResponse); + } +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java deleted file mode 100644 index 8fbc44c46e..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/Logger.java +++ /dev/null @@ -1,571 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import com.google.common.annotations.VisibleForTesting; -import org.openecomp.sdc.common.config.EcompErrorConfiguration; -import org.openecomp.sdc.common.log.elements.LoggerDebug; -import org.openecomp.sdc.common.log.elements.LoggerError; -import org.openecomp.sdc.common.log.elements.LoggerFactory; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.slf4j.Marker; - - -/** - * This class wraps {@link org.slf4j.Logger} object and provides mandatory information required by Ecomp logging rules. - * Note: All deprecated methods are supported to be compatible to the legacy code - * and have not be used by the new code - */ -public class Logger implements org.slf4j.Logger { - private final LoggerDebug debug; - private final LoggerError error; - private final org.slf4j.Logger logger; - - @VisibleForTesting - private Logger(org.slf4j.Logger logger) { - this.logger = logger; - this.debug = LoggerFactory.getMdcLogger(LoggerDebug.class, logger); - this.error = LoggerFactory.getMdcLogger(LoggerError.class, logger); - } - - private Logger(String className) { - this(org.slf4j.LoggerFactory.getLogger(className)); - } - - public static Logger getLogger(String className) { - return new Logger(className); - } - - public static Logger getLogger(Class<?> clazz) { - return new Logger(clazz.getName()); - } - - - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public String getName() { - return logger.getName(); - } - - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Object o) { - - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o); - } - } - - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public void info(String msg) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg); - } - } - - @Override - public void info(String msg, Object o) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o); - } - } - - @Override - public void info(String msg, Object o, Object o1) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o, o1); - } - } - - public void debug(String msg, Object... params) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, params); - } - } - - @Override - public void debug(String msg, Throwable throwable) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, throwable); - } - } - - @Override - public boolean isDebugEnabled(Marker marker) { - return false; - } - - @Override - public void debug(Marker marker, String msg) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg); - } - } - - @Override - public void debug(Marker marker, String msg, Object o) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o); - } - } - - @Override - public void debug(Marker marker, String msg, Object o, Object o1) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o, o1); - } - } - - @Override - public void debug(Marker marker, String msg, Object... objects) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, objects); - } - } - - @Override - public void debug(Marker marker, String msg, Throwable throwable) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, throwable); - } - } - - public void debug(String message) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, message); - } - } - - @Override - public void debug(String msg, Object o) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o); - } - } - - @Override - public void debug(String msg, Object o, Object o1) { - if (isDebugEnabled()) { - debug.log(LogLevel.DEBUG, msg, o, o1); - } - } - - public void trace(String message, Object... params) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, message, params); - } - } - - @Override - public void trace(String msg, Throwable throwable) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, throwable); - } - } - - @Override - public boolean isTraceEnabled(Marker marker) { - return false; - } - - @Override - public void trace(Marker marker, String msg) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg); - } - } - - @Override - public void trace(Marker marker, String msg, Object o) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o); - } - } - - @Override - public void trace(Marker marker, String msg, Object o, Object o1) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o, o1); - } - } - - @Override - public void trace(Marker marker, String msg, Object... objects) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, objects); - } - } - - @Override - public void trace(Marker marker, String msg, Throwable throwable) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, throwable); - } - } - - public void trace(String msg) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg); - } - } - - @Override - public void trace(String msg, Object o) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o); - } - } - - @Override - public void trace(String msg, Object o, Object o1) { - if (isTraceEnabled()) { - debug.log(LogLevel.TRACE, msg, o, o1); - } - } - - public void info(String msg, Object... params) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, params); - } - } - - @Override - public void info(String msg, Throwable throwable) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, throwable); - } - } - - @Override - public boolean isInfoEnabled(Marker marker) { - return false; - } - - @Override - public void info(Marker marker, String msg) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg); - } - } - - @Override - public void info(Marker marker, String msg, Object o) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o); - } - } - - @Override - public void info(Marker marker, String msg, Object o, Object o1) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, o, o1); - } - } - - @Override - public void info(Marker marker, String msg, Object... objects) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, objects); - } - } - - @Override - public void info(Marker marker, String msg, Throwable throwable) { - if (isInfoEnabled()) { - error.logInfo(LogLevel.INFO, msg, throwable); - } - } - - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Object... params) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, params); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Object o, Object o1) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o, o1); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(String msg, Throwable throwable) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, throwable); - } - } - - @Override - public boolean isWarnEnabled(Marker marker) { - return false; - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Object o) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Object o, Object o1) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, o, o1); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Object... objects) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, objects); - } - } - - @Override - @Deprecated - /** Please use method {@link #warn(EcompLoggerErrorCode, String, String)} **/ - public void warn(Marker marker, String msg, Throwable throwable) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, msg, throwable); - } - } - - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, params); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Throwable throwable) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, throwable); - } - } - - @Override - public boolean isErrorEnabled(Marker marker) { - return false; - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Object o) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Object o, Object o1) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o, o1); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, params); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(Marker marker, String msg, Throwable throwable) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, throwable); - } - } - - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Object o) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o); - } - } - - @Override - @Deprecated - /** Please use method {@link #error(EcompLoggerErrorCode, String, String)} **/ - public void error(String msg, Object o, Object o1) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, msg, o, o1); - } - } - - /** - * Writes out ERROR logging level message to the application error log - * - * @param errorLevel code representing the error severity level - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void error(EcompErrorConfiguration.EcompErrorSeverity errorLevel, - EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isErrorEnabled()) { - error.log(errorLevel, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - /** - * Writes out ERROR logging level message to the application error log - * - * @param errorCodeEnum code representing the error condition - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void error(EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.ERROR, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - /** - * Writes out WARN logging level message to the application error log - * - * @param errorCodeEnum code representing the error condition - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void warn(EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isWarnEnabled()) { - error.log(LogLevel.WARN, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - /** - * Writes out FATAL logging level message to the application error log - * - * @param errorCodeEnum code representing the error condition - * @param serviceName name of the API invoked at the logging component - * @param targetEntity name of the ECOMP component or sub-component, or external entity at which the error occurred or null - * @param errorDescription a human readable description of the error condition - * @param params optional parameters of a given error description - */ - public void fatal(EcompLoggerErrorCode errorCodeEnum, - String serviceName, - String targetEntity, - String errorDescription, Object... params) { - if (isErrorEnabled()) { - error.log(LogLevel.FATAL, errorCodeEnum, serviceName, targetEntity, errorDescription, params); - } - } - - -} - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java deleted file mode 100644 index aac4e2b1c8..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcAudit.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.elements.LoggerAudit; -import org.openecomp.sdc.common.log.elements.LoggerFactory; -import org.openecomp.sdc.common.log.enums.LogLevel; -import org.openecomp.sdc.common.log.enums.Severity; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.MDC; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.Response; - - -/** - * Created by dd4296 on 12/19/2017. - * <p> - * audit log for asdc using the log library - * this is adapted for filter classes - */ -public class LoggerSdcAudit extends LoggerSdcUtilBase { - - private static final String AUDIT_ON = "auditOn"; - private String className; - private final LoggerAudit ecompLoggerAudit; - - public LoggerSdcAudit(Class<?> clazz) { - this.className = clazz.getName(); - ecompLoggerAudit = LoggerFactory.getMdcLogger(LoggerAudit.class, org.slf4j.LoggerFactory.getLogger(clazz)); - } - - public void startLog(ContainerRequestContext requestContext) { - ecompLoggerAudit.clear() - .startTimer() - .setPartnerName(getPartnerName( - requestContext.getHeaderString("user-agent"), - requestContext.getHeaderString("USER_ID"), - getUrl(requestContext))) - .setServiceName(getServiceName(requestContext)) - .setKeyRequestId(ThreadLocalsHolder.getUuid()); - MDC.put(AUDIT_ON, "true"); - } - - public static boolean isFlowBeingTakenCare() { - String auditOn = MDC.get(AUDIT_ON); - return !StringUtils.isEmpty(auditOn) && "true".equals(auditOn); - } - - //this function clears the MDC data that relevant for this class - public void clearMyData() { - ecompLoggerAudit.clear(); - } - - public void log(String remoteAddress, - ContainerRequestContext requestContext, - Response.StatusType statusInfo, - LogLevel logLevel, - Severity securityLevel, - String message) { - - try { - - String msg = ecompLoggerAudit.getAuditMessage() == null - ? message : ecompLoggerAudit.getAuditMessage(); - ecompLoggerAudit.stopTimer() - .setRemoteHost(remoteAddress) - .setResponseCode(convertHttpCodeToErrorCode(statusInfo.getStatusCode())) - .setStatusCode(Integer.toString(statusInfo.getStatusCode())) - .setResponseDesc(statusInfo.getReasonPhrase()) - .setInstanceUUID(requestContext.getHeaderString(Constants.X_ECOMP_INSTANCE_ID_HEADER)) - .setOptServiceInstanceId(requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER)) - .setOptClassName(className) - .setOptAlertSeverity(securityLevel) - .setOptCustomField1(requestContext.getMethod() + ": " + getUrl(requestContext)) - .setOptCustomField2(Integer.toString(statusInfo.getStatusCode())) - .log(logLevel, msg); - } catch (Exception e) { - log.warn("Failed to write to Audit Log. Original Message: {}", message, e); - } finally { - MDC.put(AUDIT_ON, "false"); - } - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java deleted file mode 100644 index 86d43235c0..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggerSdcUtilBase.java +++ /dev/null @@ -1,221 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.log.wrappers; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.container.ContainerRequestContext; -import java.util.List; -import java.util.StringTokenizer; - -import static java.net.HttpURLConnection.HTTP_BAD_METHOD; -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT; -import static java.net.HttpURLConnection.HTTP_CONFLICT; -import static java.net.HttpURLConnection.HTTP_ENTITY_TOO_LARGE; -import static java.net.HttpURLConnection.HTTP_FORBIDDEN; -import static java.net.HttpURLConnection.HTTP_GONE; -import static java.net.HttpURLConnection.HTTP_LENGTH_REQUIRED; -import static java.net.HttpURLConnection.HTTP_NOT_ACCEPTABLE; -import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static java.net.HttpURLConnection.HTTP_PAYMENT_REQUIRED; -import static java.net.HttpURLConnection.HTTP_PRECON_FAILED; -import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; -import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG; -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE; - -/** - * Created by dd4296 on 12/20/2017. - * <p> - * base class for metric and audit log logging - * holding the specific logic for data extraction - */ -public class LoggerSdcUtilBase { - - private static final int SUCCESS_ERROR_CODE_LIMIT = 399; - private static final int BUSINESS_PROCESS_ERROR_BOUNDRY = 499; - protected static Logger log = LoggerFactory.getLogger(LoggerSdcUtilBase.class.getName()); - - String getRequestIDfromHeaders(List<Object> requestHeader) { - // this method gets list of type object. - // toString method returns the RequestId with brackets. - String requestHeaderString = requestHeader.toString(); - return requestHeaderString.replace("[", "").replace("]", ""); - } - - - // this method translates http error code to ECOMP Logger Error code - // this is a naive translation and is not a result of any documented format ECOMP specification - protected EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { - if (isSuccessError(httpResponseCode)) { - return EcompLoggerErrorCode.SUCCESS; - } - - if (isSchemaError(httpResponseCode)) { - return EcompLoggerErrorCode.SCHEMA_ERROR; - } - if (isDataError(httpResponseCode)) { - return EcompLoggerErrorCode.DATA_ERROR; - } - if (isPermissionsError(httpResponseCode)) { - return EcompLoggerErrorCode.PERMISSION_ERROR; - } - if (isTimeoutOrAvailabilityError(httpResponseCode)) { - return EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR; - } - if (isBusinessProcessError(httpResponseCode)) { - return EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; - } - return EcompLoggerErrorCode.UNKNOWN_ERROR; - } - - private boolean isTimeoutOrAvailabilityError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_BAD_REQUEST: - case HTTP_UNAUTHORIZED: - case HTTP_NOT_FOUND: - case HTTP_CLIENT_TIMEOUT: - case HTTP_GONE: - return true; - default: - return false; - } - - } - - private boolean isPermissionsError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_PAYMENT_REQUIRED: - case HTTP_FORBIDDEN: - case HTTP_BAD_METHOD: - case HTTP_PROXY_AUTH: - return true; - - default: - return false; - } - } - - private boolean isDataError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_NOT_ACCEPTABLE: - case HTTP_LENGTH_REQUIRED: - case HTTP_PRECON_FAILED: - case HTTP_REQ_TOO_LONG: - case HTTP_ENTITY_TOO_LARGE: - case HTTP_UNSUPPORTED_TYPE: - return true; - - default: - return false; - } - } - - private boolean isSchemaError(int httpResponseCode) { - return HTTP_CONFLICT == httpResponseCode; - } - - private boolean isSuccessError(int httpResponseCode) { - return httpResponseCode < SUCCESS_ERROR_CODE_LIMIT; - } - - private boolean isBusinessProcessError(int httpResponseCode) { - return httpResponseCode > BUSINESS_PROCESS_ERROR_BOUNDRY; - } - - protected String getPartnerName(String userAgent, String userId, String url) { - - if (!StringUtils.isEmpty(userId)) { - return userId; - } - - String urlUser = getUserIdFromUrl(url); - - if (!StringUtils.isEmpty(urlUser)) { - return urlUser; - } - - String userAgentName = getUserIdFromUserAgent(userAgent); - - if (!StringUtils.isEmpty(userAgentName)) { - return userAgentName; - } - - return ""; - } - - private String getUserIdFromUserAgent(String userAgent) { - if (userAgent != null && userAgent.length() > 0) { - if (userAgent.toLowerCase().contains("firefox")) { - return "fireFox_FE"; - } - - if (userAgent.toLowerCase().contains("msie")) { - return "explorer_FE"; - } - - if (userAgent.toLowerCase().contains("chrome")) { - return "chrome_FE"; - } - - return userAgent; - } - return null; - } - - private String getUserIdFromUrl(String url) { - if (url != null && url.toLowerCase().contains("user")) { - StringTokenizer st = new StringTokenizer(url, "/"); - while (st.hasMoreElements()) { - if ("user".equalsIgnoreCase(st.nextToken())) { - return st.nextToken(); - } - } - } - return null; - } - - protected String getUrl(ContainerRequestContext requestContext) { - String url = ""; - - try { - if (requestContext.getUriInfo() != null && requestContext.getUriInfo().getRequestUri() != null) { - url = requestContext.getUriInfo().getRequestUri().toURL().toString(); - } - } catch (Exception ex) { - log.error("failed to get url from request context ", ex); - } - - return url; - } - - protected String getServiceName(ContainerRequestContext requestContext) { - return (requestContext.getUriInfo().getRequestUri().toString()) - .replace(requestContext.getUriInfo().getBaseUri().toString(), "/"); - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggingHelper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggingHelper.java new file mode 100644 index 0000000000..925701eab4 --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/log/wrappers/LoggingHelper.java @@ -0,0 +1,4 @@ +package org.openecomp.sdc.common.log.wrappers; + +public class LoggingHelper { +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java index 257d5a434b..c0cb7829cd 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringEvent.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,105 +20,120 @@ package org.openecomp.sdc.common.monitoring; -import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; -public class MonitoringEvent extends ESTimeBasedEvent { +import java.util.Formatter; +import java.util.Locale; - private static final String MONITORING_EVENT_TEMPLATE = "hostid=\"%s\" hostcpu=\"%s\" hostmem=\"%s\" hostdisk=\"%s\" " + "jvmid=\"%s\" jvmcpu=\"%s\" jvmmem=\"%s\" jvmtnum=\"%s\" " + "appid=\"%s\" appstat=\"%s\""; +public class MonitoringEvent { - private String hostid; - private Long hostcpu; - private Double hostmem; - private String hostdisk; - private String jvmid; - private Long jvmcpu; - private Long jvmmem; - private Integer jvmtnum; - private String appid; - private String appstat; - - public String getHostid() { - return hostid; - } - - public void setHostid(String hostid) { - this.hostid = hostid; - } - - public Long getHostcpu() { - return hostcpu; - } - - public void setHostcpu(Long hostcpu) { - this.hostcpu = hostcpu; - } - - public Double getHostmem() { - return hostmem; - } - - public void setHostmem(Double hostmem) { - this.hostmem = hostmem; - } - - public String getHostdisk() { - return hostdisk; - } - - public void setHostdisk(String hostdisk) { - this.hostdisk = hostdisk; - } - - public String getJvmid() { - return jvmid; - } - - public void setJvmid(String jvmid) { - this.jvmid = jvmid; - } - - public Long getJvmcpu() { - return jvmcpu; - } - - public void setJvmcpu(Long jvmcpu) { - this.jvmcpu = jvmcpu; - } - - public Long getJvmmem() { - return jvmmem; - } - - public void setJvmmem(Long jvmmem) { - this.jvmmem = jvmmem; - } - - public Integer getJvmtnum() { - return jvmtnum; - } - - public void setJvmtnum(Integer jvmtnum) { - this.jvmtnum = jvmtnum; - } - - public String getAppid() { - return appid; - } - - public void setAppid(String appid) { - this.appid = appid; - } - - public String getAppstat() { - return appstat; - } - - public void setAppstat(String appstat) { - this.appstat = appstat; - } - - @Override - public String toString() { - return getFormattedString(MONITORING_EVENT_TEMPLATE, hostid, hostcpu, hostmem, hostdisk, jvmid, jvmcpu, jvmmem, jvmtnum, appid, appstat); - } + private static String MONITORING_EVENT_TEMPLATE = "hostid=\"%s\" hostcpu=\"%s\" hostmem=\"%s\" hostdisk=\"%s\" " + "jvmid=\"%s\" jvmcpu=\"%s\" jvmmem=\"%s\" jvmtnum=\"%s\" " + "appid=\"%s\" appstat=\"%s\""; + + private String hostid; + private Long hostcpu; + private Double hostmem; + private String hostdisk; + private String jvmid; + private Long jvmcpu; + private Long jvmmem; + private Integer jvmtnum; + private String appid; + private String appstat; + + public String getHostid() { + return hostid; + } + + public void setHostid(String hostid) { + this.hostid = hostid; + } + + public Long getHostcpu() { + return hostcpu; + } + + public void setHostcpu(Long hostcpu) { + this.hostcpu = hostcpu; + } + + public Double getHostmem() { + return hostmem; + } + + public void setHostmem(Double hostmem) { + this.hostmem = hostmem; + } + + public String getHostdisk() { + return hostdisk; + } + + public void setHostdisk(String hostdisk) { + this.hostdisk = hostdisk; + } + + public String getJvmid() { + return jvmid; + } + + public void setJvmid(String jvmid) { + this.jvmid = jvmid; + } + + public Long getJvmcpu() { + return jvmcpu; + } + + public void setJvmcpu(Long jvmcpu) { + this.jvmcpu = jvmcpu; + } + + public Long getJvmmem() { + return jvmmem; + } + + public void setJvmmem(Long jvmmem) { + this.jvmmem = jvmmem; + } + + public Integer getJvmtnum() { + return jvmtnum; + } + + public void setJvmtnum(Integer jvmtnum) { + this.jvmtnum = jvmtnum; + } + + public String getAppid() { + return appid; + } + + public void setAppid(String appid) { + this.appid = appid; + } + + public String getAppstat() { + return appstat; + } + + public void setAppstat(String appstat) { + this.appstat = appstat; + } + + private String getFormattedString(String template, Object... params) { + String res = null; + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + try { + formatter.format(template, params); + res = formatter.toString(); + } finally { + formatter.close(); + } + return res; + } + + @Override + public String toString() { + return getFormattedString(MONITORING_EVENT_TEMPLATE, hostid, hostcpu, hostmem, hostdisk, jvmid, jvmcpu, jvmmem, jvmtnum, appid, appstat); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java index b5760bb521..ea92156ce1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/monitoring/MonitoringMetricsFetcher.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -37,175 +37,174 @@ import java.util.Map; public class MonitoringMetricsFetcher { - private static final int TO_PERCENT_MULTIPLIER = 100; - private static Logger monitoringLogger = LoggerFactory.getLogger("asdc.fe.monitoring.fetcher"); - - private static volatile MonitoringMetricsFetcher instance; - private static RuntimeMXBean runtimeMXBean; - private static ThreadMXBean threadMXBean; - private static MemoryMXBean memoryMXBean; - private static MBeanServer platformMBeanServer; - private static Sigar sigarSession; - - private static String appName; - private static String jvmName = "Unknown"; - private static final String PROCESS_CPU_TIME_ATTR = "ProcessCpuTime"; - - private static final String FE_JVM_NAME = "jetty-fe"; - private static final String BE_JVM_NAME = "jetty-be"; - - private MonitoringMetricsFetcher() { - } - - public static MonitoringMetricsFetcher getInstance() { - if (instance == null) { - instance = init(); - } - return instance; - } - - public MonitoringEvent getMonitoringMetrics() { - MonitoringEvent monitoringEvent = new MonitoringEvent(); - monitoringEvent.setHostid(getFQDN()); - monitoringEvent.setHostcpu(getHostCpuTime()); - monitoringEvent.setHostmem(getHostUsedMemory()); - monitoringEvent.setHostdisk(getHostUsedDisk().toString()); - - monitoringEvent.setJvmid(jvmName); - - monitoringEvent.setJvmcpu(getJvmCpuTime()); - monitoringEvent.setJvmmem(getJvmUsedHeapMemory()); - monitoringEvent.setJvmtnum(getJvmThreads()); - - monitoringEvent.setAppid(appName); - // this is probably from healthcheck - monitoringEvent.setAppstat("appStatus"); - return monitoringEvent; - } - - private static synchronized MonitoringMetricsFetcher init() { - if (instance == null) { - instance = new MonitoringMetricsFetcher(); - threadMXBean = ManagementFactory.getThreadMXBean(); - memoryMXBean = ManagementFactory.getMemoryMXBean(); - runtimeMXBean = ManagementFactory.getRuntimeMXBean(); - platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); - sigarSession = new Sigar(); - appName = ExternalConfiguration.getAppName(); - monitoringLogger.debug("appName is {}", appName); - // Accoridng to Yaki, there is no "calculated" jvmName like it was - // in TAS, - // just "jetty-be" or "jetty-fe" - if (appName.contains("fe")) { - jvmName = FE_JVM_NAME; - } else if (appName.contains("be")) { - jvmName = BE_JVM_NAME; - } else { - monitoringLogger - .warn("Couldn't determine jvmName, appName is expected to contain \"be\" or \"fe\" string"); - } - } - return instance; - } - - /** - * Returns the number of live threads for this JVM - * - * @return number of live threads - */ - private Integer getJvmThreads() { - return threadMXBean.getThreadCount(); - } - - /** - * Returns the number of used heap memory (bytes) - * - * @return the number of used heap memory (bytes) - */ - private long getJvmUsedHeapMemory() { - return memoryMXBean.getHeapMemoryUsage().getUsed(); - } - - /** - * Returns the jvm cpu time (msec) - * - * @return the jvm cpu time (msec) - */ - private long getJvmCpuTime() { - - long cpuTime = -1; - try { - cpuTime = (long) platformMBeanServer.getAttribute( - new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME), PROCESS_CPU_TIME_ATTR); - } catch (Exception e) { - monitoringLogger.error("Couldn't measure JVM CPU time, error: {}", e); - } - return cpuTime; - } - - /** - * Returns the host total cpu time (msec) - * - * @return the host total cpu time (msec) - */ - private long getHostCpuTime() { - long cpuTime = -1; - try { - cpuTime = sigarSession.getCpu().getTotal(); - } catch (Exception e) { - monitoringLogger.error("Couldn't measure host CPU time, error: {}", e); - } - return cpuTime; - } - - /** - * Returns the host used memory(msec) - * - * @return the host used memory(msec) - */ - private Double getHostUsedMemory() { - Double memory = -1.0; - try { - memory = sigarSession.getMem().getUsedPercent(); - } catch (Exception e) { - monitoringLogger.error("Couldn't measure host used memory, error: {}", e); - } - return memory; - } - - /** - * Returns the percentage of all available FS - * - * @return the host avail disk(bytes) - */ - private Map<String, Double> getHostUsedDisk() { - Map<String, Double> res = new HashMap<>(); - try { - FileSystem[] fileSystemList = sigarSession.getFileSystemList(); - for (FileSystem fileSystem : fileSystemList) { - - String dirName = fileSystem.getDirName(); - double usePercent = sigarSession.getFileSystemUsage(dirName).getUsePercent() * TO_PERCENT_MULTIPLIER; - res.put(dirName, usePercent); - } - } catch (Exception e) { - monitoringLogger.error("Couldn't measure host used disk, error: {}", e); - } - return res; - } - - /** - * Returns the FQDN - * - * @return the FQDN - */ - private String getFQDN() { - String fqdn = ""; - try { - fqdn = sigarSession.getFQDN(); - } catch (Exception e) { - monitoringLogger.error("Couldn't get FQDN, error: {}", e); - } - return fqdn; - } + private static Logger monitoringLogger = LoggerFactory.getLogger("asdc.fe.monitoring.fetcher"); + + private static volatile MonitoringMetricsFetcher instance; + private static RuntimeMXBean runtimeMXBean; + private static ThreadMXBean threadMXBean; + private static MemoryMXBean memoryMXBean; + private static MBeanServer platformMBeanServer; + private static Sigar sigarSession; + + private static String appName; + private static String jvmName = "Unknown"; + private final String PROCESS_CPU_TIME_ATTR = "ProcessCpuTime"; + + private static String FE_JVM_NAME = "jetty-fe"; + private static String BE_JVM_NAME = "jetty-be"; + + private MonitoringMetricsFetcher() { + }; + + public static MonitoringMetricsFetcher getInstance() { + if (instance == null) { + instance = init(); + } + return instance; + } + + public MonitoringEvent getMonitoringMetrics() { + MonitoringEvent monitoringEvent = new MonitoringEvent(); + monitoringEvent.setHostid(getFQDN()); + monitoringEvent.setHostcpu(getHostCpuTime()); + monitoringEvent.setHostmem(getHostUsedMemory()); + monitoringEvent.setHostdisk(getHostUsedDisk().toString()); + + monitoringEvent.setJvmid(jvmName); + + monitoringEvent.setJvmcpu(getJvmCpuTime()); + monitoringEvent.setJvmmem(getJvmUsedHeapMemory()); + monitoringEvent.setJvmtnum(getJvmThreads()); + + monitoringEvent.setAppid(appName); + // this is probably from healthcheck + monitoringEvent.setAppstat("appStatus"); + return monitoringEvent; + } + + private static synchronized MonitoringMetricsFetcher init() { + if (instance == null) { + instance = new MonitoringMetricsFetcher(); + threadMXBean = ManagementFactory.getThreadMXBean(); + memoryMXBean = ManagementFactory.getMemoryMXBean(); + runtimeMXBean = ManagementFactory.getRuntimeMXBean(); + platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); + sigarSession = new Sigar(); + appName = ExternalConfiguration.getAppName(); + monitoringLogger.debug("appName is {}", appName); + // Accoridng to Yaki, there is no "calculated" jvmName like it was + // in TAS, + // just "jetty-be" or "jetty-fe" + if (appName.contains("fe")) { + jvmName = FE_JVM_NAME; + } else if (appName.contains("be")) { + jvmName = BE_JVM_NAME; + } else { + monitoringLogger + .warn("Couldn't determine jvmName, appName is expected to contain \"be\" or \"fe\" string"); + } + } + return instance; + } + + /** + * Returns the number of live threads for this JVM + * + * @return number of live threads + */ + private Integer getJvmThreads() { + return threadMXBean.getThreadCount(); + } + + /** + * Returns the number of used heap memory (bytes) + * + * @return the number of used heap memory (bytes) + */ + private long getJvmUsedHeapMemory() { + return memoryMXBean.getHeapMemoryUsage().getUsed(); + } + + /** + * Returns the jvm cpu time (msec) + * + * @return the jvm cpu time (msec) + */ + private long getJvmCpuTime() { + + long cpuTime = -1; + try { + cpuTime = (long) platformMBeanServer.getAttribute( + new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME), PROCESS_CPU_TIME_ATTR); + } catch (Exception e) { + monitoringLogger.error("Couldn't measure JVM CPU time, error: {}", e); + } + return cpuTime; + } + + /** + * Returns the host total cpu time (msec) + * + * @return the host total cpu time (msec) + */ + private long getHostCpuTime() { + long cpuTime = -1; + try { + cpuTime = sigarSession.getCpu().getTotal(); + } catch (Exception e) { + monitoringLogger.error("Couldn't measure host CPU time, error: {}", e); + } + return cpuTime; + } + + /** + * Returns the host used memory(msec) + * + * @return the host used memory(msec) + */ + private Double getHostUsedMemory() { + Double memory = -1.0; + try { + memory = sigarSession.getMem().getUsedPercent(); + } catch (Exception e) { + monitoringLogger.error("Couldn't measure host used memory, error: {}", e); + } + return memory; + } + + /** + * Returns the percentage of all available FS + * + * @return the host avail disk(bytes) + */ + private Map<String, Double> getHostUsedDisk() { + Map<String, Double> res = new HashMap<>(); + try { + FileSystem[] fileSystemList = sigarSession.getFileSystemList(); + for (FileSystem fileSystem : fileSystemList) { + + String dirName = fileSystem.getDirName(); + double usePercent = sigarSession.getFileSystemUsage(dirName).getUsePercent() * 100; + res.put(dirName, usePercent); + } + } catch (Exception e) { + monitoringLogger.error("Couldn't measure host used disk, error: {}", e); + } + return res; + } + + /** + * Returns the FQDN + * + * @return the FQDN + */ + private String getFQDN() { + String fqdn = ""; + try { + fqdn = sigarSession.getFQDN(); + } catch (Exception e) { + monitoringLogger.error("Couldn't get FQDN, error: {}", e); + } + return fqdn; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java index 0e660400d3..89a9e24dff 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestConfigurationInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,80 +24,84 @@ import org.openecomp.sdc.common.api.BasicConfiguration; public class RestConfigurationInfo extends BasicConfiguration { - private Integer readTimeoutInSec = null; - - private Boolean ignoreCertificate = null; - - private Integer connectionPoolSize = null; - - private Integer connectTimeoutInSec = null; - - /** - * @return the readTimeoutInSec - */ - public Integer getReadTimeoutInSec() { - return readTimeoutInSec; - } - - /** - * @param readTimeoutInSec the readTimeoutInSec to set - */ - public void setReadTimeoutInSec(Integer readTimeoutInSec) { - this.readTimeoutInSec = readTimeoutInSec; - } - - /** - * @return the ignoreCertificate - */ - public Boolean getIgnoreCertificate() { - return ignoreCertificate; - } - - /** - * @param ignoreCertificate the ignoreCertificate to set - */ - public void setIgnoreCertificate(Boolean ignoreCertificate) { - this.ignoreCertificate = ignoreCertificate; - } - - /** - * @return the connectionPoolSize - */ - public Integer getConnectionPoolSize() { - return connectionPoolSize; - } - - /** - * @param connectionPoolSize the connectionPoolSize to set - */ - public void setConnectionPoolSize(Integer connectionPoolSize) { - this.connectionPoolSize = connectionPoolSize; - } - - /** - * @return the connectTimeoutInSec - */ - public Integer getConnectTimeoutInSec() { - return connectTimeoutInSec; - } - - /** - * @param connectTimeoutInSec the connectTimeoutInSec to set - */ - public void setConnectTimeoutInSec(Integer connectTimeoutInSec) { - this.connectTimeoutInSec = connectTimeoutInSec; - } - - public String toString() { - - StringBuilder builder = new StringBuilder(); - - builder.append("[ timeoutInSec=" + readTimeoutInSec + ","); - builder.append("connectTimeoutInSec=" + connectTimeoutInSec + ","); - builder.append("ignoreCertificate=" + ignoreCertificate + ","); - builder.append("connectionPoolSize=" + connectionPoolSize + "]"); - - return builder.toString(); - - } + private Integer readTimeoutInSec = null; + + private Boolean ignoreCertificate = null; + + private Integer connectionPoolSize = null; + + private Integer connectTimeoutInSec = null; + + /** + * @return the readTimeoutInSec + */ + public Integer getReadTimeoutInSec() { + return readTimeoutInSec; + } + + /** + * @param readTimeoutInSec + * the readTimeoutInSec to set + */ + public void setReadTimeoutInSec(Integer readTimeoutInSec) { + this.readTimeoutInSec = readTimeoutInSec; + } + + /** + * @return the ignoreCertificate + */ + public Boolean getIgnoreCertificate() { + return ignoreCertificate; + } + + /** + * @param ignoreCertificate + * the ignoreCertificate to set + */ + public void setIgnoreCertificate(Boolean ignoreCertificate) { + this.ignoreCertificate = ignoreCertificate; + } + + /** + * @return the connectionPoolSize + */ + public Integer getConnectionPoolSize() { + return connectionPoolSize; + } + + /** + * @param connectionPoolSize + * the connectionPoolSize to set + */ + public void setConnectionPoolSize(Integer connectionPoolSize) { + this.connectionPoolSize = connectionPoolSize; + } + + /** + * @return the connectTimeoutInSec + */ + public Integer getConnectTimeoutInSec() { + return connectTimeoutInSec; + } + + /** + * @param connectTimeoutInSec + * the connectTimeoutInSec to set + */ + public void setConnectTimeoutInSec(Integer connectTimeoutInSec) { + this.connectTimeoutInSec = connectTimeoutInSec; + } + + public String toString() { + + StringBuilder builder = new StringBuilder(); + + builder.append("[ timeoutInSec=" + readTimeoutInSec + ","); + builder.append("connectTimeoutInSec=" + connectTimeoutInSec + ","); + builder.append("ignoreCertificate=" + ignoreCertificate + ","); + builder.append("connectionPoolSize=" + connectionPoolSize + "]"); + + return builder.toString(); + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java index 5c389fcd3f..6703b91a60 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RequestHeadersValidator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,64 +31,64 @@ import java.util.List; import java.util.Map; public class RequestHeadersValidator { - private static Logger log = Logger.getLogger(RequestHeadersValidator.class.getName()); + private static Logger log = Logger.getLogger(RequestHeadersValidator.class.getName()); - public static void validateContentType(HttpServletRequest request, MediaType expectedContentType, - Map<String, String> headersMap) throws RestRequestValidationException { + public static void validateContentType(HttpServletRequest request, MediaType expectedContentType, + Map<String, String> headersMap) throws RestRequestValidationException { - log.debug("validateContentType - expected: {}", expectedContentType); - if (request == null || expectedContentType == null) { - throw new RestRequestValidationException("request or media-type are null"); - } - String contentType = request.getHeader(Constants.CONTENT_TYPE_HEADER); - if (contentType == null || !contentType.contains(MediaType.APPLICATION_JSON)) { - throw new RestRequestValidationException( - "Content-Type of requset is different then " + expectedContentType); - } else { - headersMap.put(Constants.CONTENT_TYPE_HEADER, contentType); - } - } + log.debug("validateContentType - expected: {}", expectedContentType); + if (request == null || expectedContentType == null) { + throw new RestRequestValidationException("request or media-type are null"); + } + String contentType = request.getHeader(Constants.CONTENT_TYPE_HEADER); + if (contentType == null || !contentType.contains(MediaType.APPLICATION_JSON)) { + throw new RestRequestValidationException( + "Content-Type of requset is different then " + expectedContentType); + } else { + headersMap.put(Constants.CONTENT_TYPE_HEADER, contentType); + } + } - public static void validateIdentificationHeaders(HttpServletRequest request, List<String> identificationList, - Map<String, String> headersMap) throws RestRequestValidationException { + public static void validateIdentificationHeaders(HttpServletRequest request, List<String> identificationList, + Map<String, String> headersMap) throws RestRequestValidationException { - log.debug("validateIdentificationHeaders"); - for (String requiredHeader : identificationList) { - String headerVal = request.getHeader(requiredHeader); - if (headerVal != null && !headerVal.isEmpty()) { - headersMap.put(requiredHeader, headerVal); - log.debug("found header - {} : {}", requiredHeader, headerVal); - } else { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "missing identification header: {}", requiredHeader); - throw new RestRequestValidationException("missing identification header: " + requiredHeader); - } - } + log.debug("validateIdentificationHeaders"); + for (String requiredHeader : identificationList) { + String headerVal = request.getHeader(requiredHeader); + if (headerVal != null && !headerVal.isEmpty()) { + headersMap.put(requiredHeader, headerVal); + log.debug("found header - {} : {}", requiredHeader, headerVal); + } else { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","missing identification header: {}", requiredHeader); + throw new RestRequestValidationException("missing identification header: " + requiredHeader); + } + } - } + } - public static void validateMd5(byte[] encodedData, HttpServletRequest request, Map<String, String> headersMap) - throws RestRequestValidationException { + public static void validateMd5(byte[] encodedData, HttpServletRequest request, Map<String, String> headersMap) + throws RestRequestValidationException { - // validate parameters - if (encodedData == null || request == null) { - throw new RestRequestValidationException("encoded data or request are not valid"); - } + // validate parameters + if (encodedData == null || request == null) { + throw new RestRequestValidationException("encoded data or request are not valid"); + } - // calculate MD5 on the data - String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(encodedData); - byte[] encodedMd5 = Base64.encodeBase64(md5.getBytes()); + // calculate MD5 on the data + String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(encodedData); + byte[] encodedMd5 = Base64.encodeBase64(md5.getBytes()); - // read the Content-MD5 header - String origMd5 = request.getHeader(Constants.MD5_HEADER); - if ((origMd5 == null) || origMd5.isEmpty()) { - throw new RestRequestValidationException("missing Content-MD5 header "); - } + // read the Content-MD5 header + String origMd5 = request.getHeader(Constants.MD5_HEADER); + if ((origMd5 == null) || origMd5.isEmpty()) { + throw new RestRequestValidationException("missing Content-MD5 header "); + } - // verify MD5 value - if (!origMd5.equals(new String(encodedMd5))) { - throw new RestRequestValidationException("uploaded file failed MD5 validation"); - } - headersMap.put(Constants.MD5_HEADER, origMd5); - } + // verify MD5 value + if (!origMd5.equals(new String(encodedMd5))) { + throw new RestRequestValidationException("uploaded file failed MD5 validation"); + } + headersMap.put(Constants.MD5_HEADER, origMd5); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java index 0dd186a155..90ed39e1c2 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/validator/RestRequestValidationException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,13 +22,13 @@ package org.openecomp.sdc.common.rest.impl.validator; public class RestRequestValidationException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1962654783383591672L; + /** + * + */ + private static final long serialVersionUID = 1962654783383591672L; - public RestRequestValidationException(String message) { - super(message); - } + public RestRequestValidationException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java b/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java index 7f428f253b..9fbf4ca416 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/servlets/BasicServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java index 8e50c97623..9faaaf9931 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,24 +28,23 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource; import java.io.File; public class BaseConfDependent { - - protected static ConfigurationManager configurationManager; - protected static String componentName; - protected static String confPath; - - - protected static void setUp() { - ExternalConfiguration.setAppName(componentName); - ExternalConfiguration.setConfigDir(confPath); - ExternalConfiguration.listenForChanges(); - ExternalConfiguration.setAppVersion("1806.666"); - - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - - configurationManager = new ConfigurationManager(configurationSource); - - configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); - - } - + protected static ConfigurationManager configurationManager; + protected static String componentName; + protected static String confPath; + + + protected static void setUp(){ + ExternalConfiguration.setAppName(componentName); + ExternalConfiguration.setConfigDir(confPath); + ExternalConfiguration.listenForChanges(); + ExternalConfiguration.setAppVersion("1806.666"); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + configurationManager = new ConfigurationManager(configurationSource); + + configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); + + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java index a79e1ee22b..cb78b8ed9b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,26 +21,26 @@ package org.openecomp.sdc.common.util; public enum CapabilityTypeNameEnum { - ROOT("tosca.capabilities.Root"), - NODE("tosca.capabilities.Node"), - CONTAINER("tosca.capabilities.Container"), - ENDPOINT("tosca.capabilities.Endpoint"), - ENDPOINT_PUBLIC("tosca.capabilities.Endpoint.Public"), - ENDPOINT_ADMIN("tosca.capabilities.Endpoint.Admin"), - ENDPOINT_DATABASE("tosca.capabilities.Endpoint.Database"), - OPERATING_SYSTEM("tosca.capabilities.OperatingSystem"), - SCALABLE("tosca.capabilities.Scalable"), - BINDABLE("tosca.capabilities.network.Bindable"), - DOCKER("tosca.capabilities.Container.Docker"), - ATTACHMENT("tosca.capabilities.Attachment"); + ROOT("tosca.capabilities.Root"), + NODE("tosca.capabilities.Node"), + CONTAINER("tosca.capabilities.Container"), + ENDPOINT("tosca.capabilities.Endpoint"), + ENDPOINT_PUBLIC("tosca.capabilities.Endpoint.Public"), + ENDPOINT_ADMIN("tosca.capabilities.Endpoint.Admin"), + ENDPOINT_DATABASE("tosca.capabilities.Endpoint.Database"), + OPERATING_SYSTEM("tosca.capabilities.OperatingSystem"), + SCALABLE("tosca.capabilities.Scalable"), + BINDABLE("tosca.capabilities.network.Bindable"), + DOCKER("tosca.capabilities.Container.Docker"), + ATTACHMENT("tosca.capabilities.Attachment"); - private String capabilityName; + private String capabilityName; - CapabilityTypeNameEnum(String capName) { - this.capabilityName = capName; - } + private CapabilityTypeNameEnum(String capName) { + this.capabilityName = capName; + } - public String getCapabilityName() { - return capabilityName; - } + public String getCapabilityName() { + return capabilityName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java index 7ff19ace72..d82538a355 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,145 +22,194 @@ package org.openecomp.sdc.common.util; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; +import org.slf4j.MDC; import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Pattern; public class GeneralUtility { - private static final int STRING_LENGTH_MULTIPLIER = 4; - - public static boolean generateTextFile(String fileName, String fileData) { - boolean isSuccessfull = true; - try { - FileUtils.writeStringToFile(new File(fileName), fileData); - } catch (IOException e) { - isSuccessfull = false; - } - return isSuccessfull; + public static boolean generateTextFile(String fileName, String fileData) { + boolean isSuccessfull = true; + try { + FileUtils.writeStringToFile(new File(fileName), fileData); + } catch (IOException e) { + isSuccessfull = false; + } + return isSuccessfull; + } + + /** + * Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(byte[] data) { + return Base64.isBase64(data); + } + + /** + *Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(String str) { + boolean isEncoded = false; + try { + // checks if the string was properly padded to the + isEncoded = ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); + if (isEncoded) { + // If no exception is caught, then it is possibly a base64 + // encoded string + byte[] data = Base64.decodeBase64(str); + } + + } catch (Exception e) { + // If exception is caught, then it is not a base64 encoded string + isEncoded = false; + } + return isEncoded; + } + + /** + * Checks whether the passed string exceeds a limit of number of characters. + * + * @param str + * @param limit + * @return the result of comparison, or false if str is null. + */ + public static boolean isExceedingLimit(String str, int limit) { + if (str == null) { + return false; + } + return str.length() > limit; + } + + /** + * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated + * 3+1+3+1+5=13 + * + * @param strList + * @param limit + * @param delimiterLength + * - 0 if there is no delimeter. + * @return the result of comparison, or false if strList is null. + */ + public static boolean isExceedingLimit(List<String> strList, int limit, int delimiterLength) { + if (strList == null || strList.isEmpty()) { + return false; + } + int sum = 0; + int size = strList.size(); + for (int i = 0; i < size - 1; i++) { + String str = strList.get(i); + if (str != null) { + sum += str.length(); + } + sum += delimiterLength; + } + String str = strList.get(size - 1); + if (str != null) { + sum += str.length(); + } + return sum > limit; + } + + /** + * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. + * + * @param fileName + * @return extension + */ + public static String getFilenameExtension(String fileName) { + String res = Constants.EMPTY_STRING; + if (fileName != null) { + int indexOf = fileName.lastIndexOf('.'); + if (indexOf != -1 && indexOf < (fileName.length() - 1)) { + res = fileName.substring(indexOf + 1); + } + } + return res; + } + + public static String calculateMD5Base64EncodedByByteArray(byte[] payload) { + String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); + byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); + return new String(encodeMd5); + + } + + /** + * + * @param data + * @return + */ + public static String calculateMD5Base64EncodedByString(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + return new String(encodeBase64); + } + + + /** + * + * @param String + * @return String is null or Empty + */ + public static boolean isEmptyString(String str) { + return str == null || str.trim().isEmpty(); } - /** - * Use with care, usage is not advised!!! - * The method only checks if String does not contain special characters + length divided by 4 with no remainder. - * The methods contained in other common libraries do the same. - */ - public static boolean isBase64Encoded(byte[] data) { - return Base64.isBase64(data); - } + public static String getEcompRequestId() { + return MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + } - /** - * Use with care, usage is not advised!!! - * The method only checks if String does not contain special characters + length divided by 4 with no remainder. - * The methods contained in other common libraries do the same. - */ - public static boolean isBase64Encoded(String str) { - boolean isEncoded = false; - try { - // checks if the string was properly padded to the - isEncoded = ((str.length() % STRING_LENGTH_MULTIPLIER == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); - if (isEncoded) { - // If no exception is caught, then it is possibly a base64 - // encoded string - byte[] data = Base64.decodeBase64(str); - } - - } catch (Exception e) { - // If exception is caught, then it is not a base64 encoded string - isEncoded = false; - } - return isEncoded; - } - /** - * Checks whether the passed string exceeds a limit of number of characters. - * - * @param str - * @param limit - * @return the result of comparison, or false if str is null. - */ - public static boolean isExceedingLimit(String str, int limit) { - if (str == null) { - return false; - } - return str.length() > limit; - } - /** - * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated - * 3+1+3+1+5=13 - * - * @param strList - * @param limit - * @param delimiterLength - 0 if there is no delimeter. - * @return the result of comparison, or false if strList is null. - */ - public static boolean isExceedingLimit(List<String> strList, int limit, int delimiterLength) { - if (strList == null || strList.isEmpty()) { - return false; - } - int sum = 0; - int size = strList.size(); - for (int i = 0; i < size - 1; i++) { - String str = strList.get(i); - if (str != null) { - sum += str.length(); - } - sum += delimiterLength; - } - String str = strList.get(size - 1); - if (str != null) { - sum += str.length(); - } - return sum > limit; - } - /** - * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. - * - * @param fileName - * @return extension - */ - public static String getFilenameExtension(String fileName) { - String res = Constants.EMPTY_STRING; - if (fileName != null) { - int indexOf = fileName.lastIndexOf('.'); - if (indexOf != -1 && indexOf < (fileName.length() - 1)) { - res = fileName.substring(indexOf + 1); - } - } - return res; - } + public static <T extends ICategorizedElement> Map<String,Map<String,List<T>>> getCategorizedComponents(List<T> components) { - public static String calculateMD5Base64EncodedByByteArray(byte[] payload) { - String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); - byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); - return new String(encodeMd5); + Map<String, Map<String, List<T>>> categorizedMap = new HashMap<>(); + components.forEach(component -> categorizeComponent(component, categorizedMap)); + return categorizedMap; + } - } + private static <T extends ICategorizedElement> void categorizeComponent(T component, Map<String, Map<String, List<T>>> categorizedMap) { + if(component.getComponentTypeAsString().equals("SERVICE")){ + categorizeService(component, categorizedMap); + }else if(component.getComponentTypeAsString().equals("RESOURCE")){ + categorizeResource(component, categorizedMap); + } + } - /** - * @param data - * @return - */ - public static String calculateMD5Base64EncodedByString(String data) { - String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + private static <T extends ICategorizedElement> void categorizeResource(T component, Map<String, Map<String, List<T>>> categorizedMap) { + String category = component.getCategoryName(); + String subCategory = component.getSubcategoryName(); + putComponentToMap(component, categorizedMap, category, subCategory); + } - // encode base-64 result - byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); - return new String(encodeBase64); - } + private static <T extends ICategorizedElement> void categorizeService(T component, Map<String, Map<String, List<T>>> categorizedMap) { + String category = "Generic"; + String subCategory = "Generic"; + putComponentToMap(component, categorizedMap, category, subCategory); + } + private static <T extends ICategorizedElement> void putComponentToMap(T component, Map<String, Map<String, List<T>>> categorizedMap, + String category, String subCategory) { - /** - * @param String - * @return String is null or Empty - */ - public static boolean isEmptyString(String str) { - return str == null || str.trim().isEmpty(); - } + Map<String, List<T>> categoryMap = categorizedMap.computeIfAbsent(category, k -> new HashMap<>()); + List<T> subCategoryList = categoryMap.computeIfAbsent(subCategory, k -> new ArrayList<>()); + subCategoryList.add(component); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java index e7877e4fad..7c3bcb6cad 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,17 +24,17 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonFactory { - private static Gson gson = null; + private static Gson gson = null; - public static Gson getGson() { - if (gson == null) { - synchronized (GsonFactory.class) { - if (gson == null) { - gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); - } - } - } + public static Gson getGson() { + if (gson == null) { + synchronized (GsonFactory.class) { + if (gson == null) { + gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); + } + } + } - return gson; - } + return gson; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java index 7474d38372..00a03de7cf 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,6 @@ import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOW public class HealthCheckUtil { private static Logger log = Logger.getLogger(HealthCheckUtil.class.getName()); - public boolean getAggregateStatus(List<HealthCheckInfo> healthCheckInfos, Collection<String> excludes) { boolean status = true; excludes = CollectionUtils.isEmpty(excludes) ? new ArrayList<>() : excludes; @@ -48,7 +47,7 @@ public class HealthCheckUtil { return status; } - public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos, String parentDescription) { + public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos) { StringBuilder sb = new StringBuilder(); healthCheckInfos.forEach(x -> { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java index 5a7c426949..c9086fc272 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,81 +31,81 @@ import java.util.regex.Pattern; public class HtmlCleaner { - private static Set<String> htmlTags = new HashSet<>(); + private static Set<String> htmlTags = new HashSet<>(); - private static String patternHtmlFullTagStr = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[\\^'\">\\s]+))?)+\\s*|\\s*)/?>"; + private static String patternHtmlFullTagStr = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[\\^'\">\\s]+))?)+\\s*|\\s*)/?>"; - private static String patternHtmlTagOnlyStr = "</?(\\w+)[^>]*/?>"; + private static String patternHtmlTagOnlyStr = "</?(\\w+)[^>]*/?>"; - private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); + private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); - private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); + private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); - static { - Tag[] allTags = HTML.getAllTags(); - for (Tag tag : allTags) { - htmlTags.add(tag.toString().toLowerCase()); - } - } + static { + Tag[] allTags = HTML.getAllTags(); + for (Tag tag : allTags) { + htmlTags.add(tag.toString().toLowerCase()); + } + } - public static String stripHtml(String input) { + public static String stripHtml(String input) { - return stripHtml(input, false); + return stripHtml(input, false); - } + } - public static String stripHtml(String input, boolean toEscape) { + public static String stripHtml(String input, boolean toEscape) { - if (input == null || input.isEmpty()) { - return input; - } + if (input == null || input.isEmpty()) { + return input; + } - Matcher matcher = onlyTagPattern.matcher(input); + Matcher matcher = onlyTagPattern.matcher(input); - Set<String> tagsToRemove = new HashSet<>(); + Set<String> tagsToRemove = new HashSet<>(); - while (matcher.find()) { + while (matcher.find()) { - int start = matcher.start(); - int end = matcher.end(); + int start = matcher.start(); + int end = matcher.end(); - String matchTag = input.substring(start, end); + String matchTag = input.substring(start, end); - int groupCount = matcher.groupCount(); + int groupCount = matcher.groupCount(); - if (groupCount > 0) { - String tag = matcher.group(1); - if (tag != null && htmlTags.contains(tag.toLowerCase())) { - if (!tagsToRemove.contains(matchTag)) { - tagsToRemove.add(matchTag); - } - } - } - } + if (groupCount > 0) { + String tag = matcher.group(1); + if (tag != null && htmlTags.contains(tag.toLowerCase())) { + if (!tagsToRemove.contains(matchTag)) { + tagsToRemove.add(matchTag); + } + } + } + } - String stripHtmlStr = removeTagsFromString(tagsToRemove, input); + String stripHtmlStr = removeTagsFromString(tagsToRemove, input); - if (stripHtmlStr != null) { - if (toEscape) { - stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); - } - } + if (stripHtmlStr != null) { + if (toEscape) { + stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); + } + } - return stripHtmlStr; + return stripHtmlStr; - } + } - private static String removeTagsFromString(Set<String> tagsToRemove, String input) { + private static String removeTagsFromString(Set<String> tagsToRemove, String input) { - String stripStr = input; - if (input == null || tagsToRemove.isEmpty()) { - return input; - } + String stripStr = input; + if (input == null || tagsToRemove.isEmpty()) { + return input; + } - for (String tag : tagsToRemove) { - stripStr = stripStr.replaceAll(tag, ""); - } - return stripStr; - } + for (String tag : tagsToRemove) { + stripStr = stripStr.replaceAll(tag, ""); + } + return stripStr; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java index 5bd3b87fc4..d9f099876a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,50 +30,50 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; public class HttpUtil { - public static Either<String, IOException> readJsonStringFromRequest(HttpServletRequest request) { - Either<String, IOException> eitherResult; - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - ServletInputStream reader = request.getInputStream(); - int value; - while ((value = reader.read()) != -1) { - stream.write(value); - } - eitherResult = Either.left(new String(stream.toByteArray())); - } catch (IOException e) { - eitherResult = Either.right(e); - } - return eitherResult; + public static Either<String, IOException> readJsonStringFromRequest(HttpServletRequest request) { + Either<String, IOException> eitherResult; + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { + ServletInputStream reader = request.getInputStream(); + int value; + while ((value = reader.read()) != -1) { + stream.write(value); + } + eitherResult = Either.left(new String(stream.toByteArray())); + } catch (IOException e) { + eitherResult = Either.right(e); + } + return eitherResult; - } + } - /** - * Builds an object from a JSON in the POST Body of the request. - */ - public static <T> Either<T, Exception> getObjectFromJson(HttpServletRequest request, Class<T> classOfT) { - Either<T, Exception> eitherResult; - try { - Either<String, IOException> eitherReadJson = readJsonStringFromRequest(request); - if (eitherReadJson.isLeft()) { - eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT); - } else { - eitherResult = Either.right((Exception) eitherReadJson.right().value()); - } - } catch (Exception e) { - eitherResult = Either.right(e); - } + /** + * Builds an object from a JSON in the POST Body of the request. + */ + public static <T> Either<T, Exception> getObjectFromJson(HttpServletRequest request, Class<T> classOfT) { + Either<T, Exception> eitherResult; + try { + Either<String, IOException> eitherReadJson = readJsonStringFromRequest(request); + if (eitherReadJson.isLeft()) { + eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT); + } else { + eitherResult = Either.right((Exception) eitherReadJson.right().value()); + } + } catch (Exception e) { + eitherResult = Either.right(e); + } - return eitherResult; - } + return eitherResult; + } - public static <T> Either<T, Exception> convertJsonStringToObject(String sentJson, Class<T> classOfT) { - Either<T, Exception> eitherResult; - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - T object = gson.fromJson(sentJson, classOfT); - eitherResult = Either.left(object); - } catch (Exception e) { - eitherResult = Either.right(e); - } - return eitherResult; - } + public static <T> Either<T, Exception> convertJsonStringToObject(String sentJson, Class<T> classOfT) { + Either<T, Exception> eitherResult; + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + T object = gson.fromJson(sentJson, classOfT); + eitherResult = Either.left(object); + } catch (Exception e) { + eitherResult = Either.right(e); + } + return eitherResult; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java new file mode 100644 index 0000000000..0121af702a --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.common.util; + +import java.util.List; + +public interface ICategorizedElement { + + String getComponentTypeAsString(); + + String getCategoryName(); + + String getSubcategoryName(); + + + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java index b992f7dc7c..fbf94eaaed 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,38 +25,38 @@ import com.google.gson.JsonObject; public class JsonUtils { - public static String toString(JsonElement jsonElement) { + public static String toString(JsonElement jsonElement) { - if (jsonElement == null) { - return null; - } + if (jsonElement == null) { + return null; + } - if (!jsonElement.isJsonNull()) { - if (!jsonElement.isJsonObject()) { - return jsonElement.getAsString(); - } else { - return jsonElement.toString(); - } - } else { - return null; - } + if (!jsonElement.isJsonNull()) { + if (!jsonElement.isJsonObject()) { + return jsonElement.getAsString(); + } else { + return jsonElement.toString(); + } + } else { + return null; + } - } + } - public static boolean containsEntry(JsonObject json, String key) { - return json.get(key) != null; - } + public static boolean containsEntry(JsonObject json, String key) { + return json.get(key) != null; + } - public static boolean isEmptyJson(JsonObject json) { - return json.entrySet().isEmpty(); - } + public static boolean isEmptyJson(JsonObject json) { + return json.entrySet().isEmpty(); + } - public static boolean isEmptyJson(JsonElement json) { - return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); - } + public static boolean isEmptyJson(JsonElement json) { + return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); + } - public static boolean isJsonNullOrEmpty(JsonObject json) { - return json.isJsonNull() || isEmptyJson(json); - } + public static boolean isJsonNullOrEmpty(JsonObject json) { + return json.isJsonNull() || isEmptyJson(json); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java index 758b33bbd3..bba04fa359 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.util; public enum MethodActivationStatusEnum { - SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; + SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java index 7fee13fc0d..eb6c29ce4a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java index 42eb6086fa..cf49718600 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,59 +26,54 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInput; -import java.io.ObjectInputStream; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; +import java.io.*; public class SerializationUtils { - private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); + private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); - private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); + private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); - public static Either<byte[], Boolean> serialize(Object object) { + public static Either<byte[], Boolean> serialize(Object object) { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { - out.writeObject(object); - return Either.left(bos.toByteArray()); - } catch (Exception e) { - log.debug("Failed to serialize object", e); - return Either.right(false); - } - } + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { + out.writeObject(object); + return Either.left(bos.toByteArray()); + } catch (Exception e) { + log.debug("Failed to serialize object", e); + return Either.right(false); + } + } - public static Either<Object, Boolean> deserialize(byte[] bytes) { + public static Either<Object, Boolean> deserialize(byte[] bytes) { - try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { - return Either.left(in.readObject()); - } catch (Exception e) { - log.debug("Failed to deserialize object", e); - return Either.right(false); - } - } + try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { + return Either.left(in.readObject()); + } catch (Exception e) { + log.debug("Failed to deserialize object", e); + return Either.right(false); + } + } - public static Either<byte[], Boolean> serializeExt(Object object) { - try { - byte[] value = conf.asByteArray(object); - return Either.left(value); - } catch (Exception e) { - return Either.right(false); - } - } + public static Either<byte[], Boolean> serializeExt(Object object) { + try { + byte[] value = conf.asByteArray(object); + return Either.left(value); + } catch (Exception e) { + return Either.right(false); + } + } - public static <T> Either<T, Boolean> deserializeExt(byte[] bytes, Class<T> clazz, String componentName) { - try { - Object object = conf.asObject(bytes); - T castObject = clazz.cast(object); - return Either.left(castObject); - } catch (Exception e) { - log.debug("Failed to deserialize object of type {} and uid {}", clazz, componentName, e); - BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING); - return Either.right(false); - } - } + public static <T> Either<T, Boolean> deserializeExt(byte[] bytes, Class<T> clazz, String componentName) { + try { + Object object = conf.asObject(bytes); + T castObject = clazz.cast(object); + return Either.left(castObject); + } catch (Exception e) { + log.debug("Failed to deserialize object of type {} and uid {}",clazz,componentName, e); + BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING); + return Either.right(false); + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java index 88f00f5ee4..2d07069388 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,68 +31,69 @@ import java.util.stream.StreamSupport; /** * Utility Class For Actions On Streams - * + * * @author mshitrit + * */ public final class StreamUtils { - private StreamUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Breaks the stream when the predicate is not met.<br> - * Does not evaluate elements after the stream breaks.<br> - * This method evaluates the stream.<br> - * - * @param stream - * @param predicate - * @return - */ - public static <T> Stream<T> takeWhilePlusOneNoEval(Stream<T> stream, Predicate<T> predicate) { - List<T> results = new ArrayList<>(); - Consumer<T> listAdder = results::add; - stream.map(e -> { - listAdder.accept(e); - return e; - }).filter(e -> !predicate.test(e)).findFirst(); - return results.stream(); - } - - public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); - } - - public static <T> Stream<T> takeWhilePlusOne(Stream<T> stream, Predicate<T> predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); - } - - private static <T> Spliterator<T> takeWhile(Spliterator<T> splitr, Predicate<T> predicate) { - return new MySplitIterator<>(splitr, predicate); - } - - public static class MySplitIterator<T> extends AbstractSpliterator<T> implements Spliterator<T> { - private boolean stillGoing = true; - private Spliterator<T> innerItr; - private Predicate<T> innerPred; - - private MySplitIterator(Spliterator<T> splitItr, Predicate<T> pred) { - super(splitItr.estimateSize(), 0); - innerItr = splitItr; - innerPred = pred; - } - - @Override - public boolean tryAdvance(Consumer<? super T> action) { - boolean canAdvance = true; - if (stillGoing) { - stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); - } else { - canAdvance = false; - } - return canAdvance; - } - - private Consumer<? super T> createConsumerWrapper(Consumer<? super T> action) { + private StreamUtils() { + throw new UnsupportedOperationException(); + } + + /** + * Breaks the stream when the predicate is not met.<br> + * Does not evaluate elements after the stream breaks.<br> + * This method evaluates the stream.<br> + * + * @param stream + * @param predicate + * @return + */ + public static <T> Stream<T> takeWhilePlusOneNoEval(Stream<T> stream, Predicate<T> predicate) { + List<T> results = new ArrayList<>(); + Consumer<T> listAdder = results::add; + stream.map(e -> { + listAdder.accept(e); + return e; + }).filter(e -> !predicate.test(e)).findFirst(); + return results.stream(); + } + + public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) { + return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); + } + + public static <T> Stream<T> takeWhilePlusOne(Stream<T> stream, Predicate<T> predicate) { + return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); + } + + private static <T> Spliterator<T> takeWhile(Spliterator<T> splitr, Predicate<T> predicate) { + return new MySplitIterator<>(splitr, predicate); + } + + public static class MySplitIterator<T> extends AbstractSpliterator<T> implements Spliterator<T> { + boolean stillGoing = true; + private Spliterator<T> innerItr; + private Predicate<T> innerPred; + + private MySplitIterator(Spliterator<T> splitItr, Predicate<T> pred) { + super(splitItr.estimateSize(), 0); + innerItr = splitItr; + innerPred = pred; + } + + @Override + public boolean tryAdvance(Consumer<? super T> action) { + boolean canAdvance = true; + if (stillGoing) { + stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); + } else { + canAdvance = false; + } + return canAdvance; + } + + private Consumer<? super T> createConsumerWrapper(Consumer<? super T> action) { return new Consumer<T>() { @Override @@ -104,31 +105,31 @@ public final class StreamUtils { } }; - } - - } - - public static class StopAfterFailPredicate<T> implements Predicate<T> { - private boolean hasNotFailed; - private Predicate<T> innerPredicate; - - private StopAfterFailPredicate(Predicate<T> pred) { - hasNotFailed = true; - innerPredicate = pred; - } - - @Override - public boolean test(T t) { - boolean isPassed; - if (hasNotFailed) { - isPassed = true; - hasNotFailed = innerPredicate.test(t); - } else { - isPassed = false; - } - return isPassed; - } - - } + } + + } + + public static class StopAfterFailPredicate<T> implements Predicate<T> { + boolean hasNotFailed; + Predicate<T> innerPredicate; + + private StopAfterFailPredicate(Predicate<T> pred) { + hasNotFailed = true; + innerPredicate = pred; + }; + + @Override + public boolean test(T t) { + boolean isPassed; + if (hasNotFailed) { + isPassed = true; + hasNotFailed = innerPredicate.test(t); + } else { + isPassed = false; + } + return isPassed; + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java index dcba5711d1..e14c98ee8f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +20,77 @@ package org.openecomp.sdc.common.util; +import org.openecomp.sdc.common.api.FilterDecisionEnum; +import org.openecomp.sdc.common.datastructure.UserContext; + public class ThreadLocalsHolder { - private static final ThreadLocal<String> UUID_THREAD_LOCAL = new ThreadLocal<>(); - private static final ThreadLocal<Long> REQUEST_START_TIME_THREAD_LOCAL = new ThreadLocal<>(); - private static final ThreadLocal<Boolean> IS_MDC_PROCESSED_THREAD_LOCAL = ThreadLocal.withInitial(() -> false); + private static final ThreadLocal<String> uuidThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal<Long> requestStartTimeThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal<FilterDecisionEnum> apiType = new ThreadLocal<>(); + private static final ThreadLocal<Boolean> isMdcProcessedThreadLocal = new ThreadLocal<Boolean>() { + @Override + protected Boolean initialValue() { + return false; + } + }; - public static void setMdcProcessed(Boolean isMdcProcessed) { - IS_MDC_PROCESSED_THREAD_LOCAL.set(isMdcProcessed); - } - public static void setUuid(String uuid) { - UUID_THREAD_LOCAL.set(uuid); - } + private static final ThreadLocal<UserContext> userContextThreadLocal = new ThreadLocal<>(); - public static void setRequestStartTime(Long requestStartTime) { - REQUEST_START_TIME_THREAD_LOCAL.set(requestStartTime); - } + public static final UserContext getUserContext() {return userContextThreadLocal.get(); } - public static String getUuid() { - return UUID_THREAD_LOCAL.get(); - } + public static void setUserContext(UserContext userContext) {userContextThreadLocal.set(userContext); } - public static Long getRequestStartTime() { - return REQUEST_START_TIME_THREAD_LOCAL.get(); - } + public static void setMdcProcessed(Boolean isMdcProcessed) { + isMdcProcessedThreadLocal.set(isMdcProcessed); + } - public static Boolean isMdcProcessed() { - return IS_MDC_PROCESSED_THREAD_LOCAL.get(); - } + public static void setUuid(String uuid) { + uuidThreadLocal.set(uuid); + } + + public static void setRequestStartTime(Long requestStartTime) { + requestStartTimeThreadLocal.set(requestStartTime); + } - public static void cleanup() { - UUID_THREAD_LOCAL.remove(); - REQUEST_START_TIME_THREAD_LOCAL.remove(); - IS_MDC_PROCESSED_THREAD_LOCAL.remove(); + public static String getUuid() { + return uuidThreadLocal.get(); + } + + public static Long getRequestStartTime() { + return requestStartTimeThreadLocal.get(); + } + + public static Boolean isMdcProcessed() { + return isMdcProcessedThreadLocal.get(); + } + + public static void cleanup() { + uuidThreadLocal.remove(); + requestStartTimeThreadLocal.remove(); + isMdcProcessedThreadLocal.remove(); + userContextThreadLocal.remove(); + apiType.remove(); + } + + public static FilterDecisionEnum getApiType() { + return apiType.get(); + } + public static void setApiType(FilterDecisionEnum filterDecisionEnum) { + apiType.set(filterDecisionEnum); + } + + + public static boolean isInternalRequest() { + if (getApiType().equals(FilterDecisionEnum.INTERNAL)){ + return true; + } else return false; } + + public static boolean isExternalRequest() { + if (getApiType().equals(FilterDecisionEnum.EXTERNAL)){ + return true; + } else return false; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java index 988f215a72..6183d42417 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java @@ -21,365 +21,397 @@ package org.openecomp.sdc.common.util; import com.google.common.base.CharMatcher; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.validator.routines.UrlValidator; import org.jsoup.Jsoup; +import org.jsoup.helper.StringUtil; import org.jsoup.safety.Whitelist; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Pattern; public class ValidationUtils { - public static final Integer COMPONENT_NAME_MAX_LENGTH = 1024; - public static final Pattern COMPONENT_NAME_PATTERN = Pattern - .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH - 1) + "}$"); - public static final Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50; - public static final Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern - .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$"); - public static final Integer RSI_NAME_MAX_LENGTH = 1024; - public static final Pattern RSI_NAME_PATTERN = Pattern - .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$"); - public static final Integer COMMENT_MAX_LENGTH = 256; - - public static final Integer ICON_MAX_LENGTH = 25; - public static final Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$"); - public static final Integer PROJECT_CODE_MAX_LEGTH = 50; - public static final Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$"); - - public static final Integer CONNTACT_ID_MAX_LENGTH = 50; - public static final Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$"); - public static final Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}"); - public static final Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+"); - public static final Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+"); // ,#?&@$<>~^`\\[]{}|")(*! - - public static final Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$"); - public static final Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; - public static final Integer SERVICE_TYPE_MAX_LENGTH = 400; - public static final Integer SERVICE_ROLE_MAX_LENGTH = 400; - - public static final Integer TAG_MAX_LENGTH = 1024; - public static final Integer TAG_LIST_MAX_LENGTH = 1024; - public static final Integer VENDOR_NAME_MAX_LENGTH = 60; - public static final Pattern VENDOR_NAME_PATTERN = Pattern - .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); - public static final Integer VENDOR_RELEASE_MAX_LENGTH = 25; - public static final Pattern VENDOR_RELEASE_PATTERN = Pattern - .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); - public static final Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65; - - public static final Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+"); - - public static final Pattern DASH_PATTERN = Pattern.compile("[-]+"); - public static final Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+"); - public static final Pattern PLUS_PATTERN = Pattern.compile("[+]+"); - public static final Pattern SPACE_PATTERN = Pattern.compile("[ ]+"); - public static final Pattern AMP_PATTERN = Pattern.compile("[&]+"); - public static final Pattern DOT_PATTERN = Pattern.compile("[\\.]+"); - public static final Pattern APOST_PATTERN = Pattern.compile("[']+"); - public static final Pattern HASHTAG_PATTERN = Pattern.compile("[#]+"); - public static final Pattern EQUAL_PATTERN = Pattern.compile("[=]+"); - public static final Pattern COLON_PATTERN = Pattern.compile("[:]+"); - public static final Pattern AT_PATTERN = Pattern.compile("[@]+"); - public static final Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] "); - public static final Set<String> CATEGORY_CONJUNCTIONS = new HashSet<>( - Arrays.asList("of", "to", "for", "as", "a", "an", "the")); - - public static final Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$"); - public static final Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$"); - public static final Integer ARTIFACT_LABEL_LENGTH = 255; - public static final Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); - public static final Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); - public static final Integer CATEGORY_LABEL_MIN_LENGTH = 3; - public static final Integer CATEGORY_LABEL_MAX_LENGTH = 25; - - public static final Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); - public static final Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); - public static final Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+"); - public static final Integer CONSUMER_NAME_MAX_LENGTH = 255; - // public static final Pattern CONSUMER_NAME_PATTERN = - // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH + - // "}?$"); - public static final Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$"); - public static final Integer CONSUMER_SALT_LENGTH = 32; - public static final Integer CONSUMER_PASSWORD_LENGTH = 64; - public static final Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$"); - public static final Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$"); - public static final Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$"); - public static final Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$"); - public static final Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>"); - - public static final Integer ARTIFACT_NAME_LENGTH = 255; - public static final Integer API_URL_LENGTH = 100; - public static final Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256; - - public static final Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; - public static final Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; - public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; - public static final Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH - 1) + "}$"); - - public static final Integer POLICY_MAX_LENGTH = 1024; - public static final Pattern POLICY_NAME_PATTERN = Pattern - .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH - 1) + "}$"); - - public static boolean validateArtifactLabel(String label) { - return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); - } - - public static boolean validateArtifactDisplayName(String displayName) { - return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches(); - } - - public static boolean validateCategoryDisplayNameFormat(String label) { - boolean res = true; - if (label != null) { - label = label.trim(); - res = CATEGORY_LABEL_PATTERN.matcher(label).matches(); - } - return res; - } - - public static String normalizeCategoryName4Display(String str) { - if (str != null) { - str = str.trim(); - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = AMP_PATTERN.matcher(str).replaceAll("&"); - str = PLUS_PATTERN.matcher(str).replaceAll("+"); - str = DOT_PATTERN.matcher(str).replaceAll("."); - str = APOST_PATTERN.matcher(str).replaceAll("'"); - str = HASHTAG_PATTERN.matcher(str).replaceAll("#"); - str = EQUAL_PATTERN.matcher(str).replaceAll("="); - str = COLON_PATTERN.matcher(str).replaceAll(":"); - str = AT_PATTERN.matcher(str).replaceAll("@"); - str = normaliseWhitespace(str); - str = AND_PATTERN.matcher(str).replaceAll(" & "); - - // Case normalizing - StringBuilder sb = new StringBuilder(); - String[] split = str.split(" "); - for (int i = 0; i < split.length; i++) { - String splitted = split[i]; - String lowerCase = splitted.toLowerCase(); - // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but - // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not - // lowercased because it's first word) - // Agreed with Ella, 26/11/15 - if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) { - sb.append(lowerCase); - } else { - sb.append(WordUtils.capitalize(splitted)); - } - sb.append(" "); - } - str = sb.toString().trim(); - } - return str; - } - - public static String normalizeCategoryName4Uniqueness(String str) { - return str.toLowerCase(); - } - - public static boolean validateCategoryDisplayNameLength(String label) { - return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH - && label.length() <= CATEGORY_LABEL_MAX_LENGTH); - } - - public static boolean validateProductFullNameLength(String fullName) { - return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH - && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH); - } - - public static boolean validateArtifactLabelLength(String label) { - return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH; - } - - public static boolean validateResourceInstanceNameLength(String resourceInstanceName) { - return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH; - } - - public static boolean validateResourceInstanceName(String resourceInstanceName) { - return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches(); - } - - public static boolean validateUrlLength(String url) { - return url.length() <= API_URL_LENGTH; - } - - public static boolean validateArtifactNameLength(String artifactName) { - return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0); - } - - public static boolean validateComponentNamePattern(String componentName) { - return COMPONENT_NAME_PATTERN.matcher(componentName).matches(); - } - - public static boolean validateComponentNameLength(String componentName) { - return componentName.length() <= COMPONENT_NAME_MAX_LENGTH; - } - - public static boolean validateIcon(String icon) { - return ICON_PATTERN.matcher(icon).matches(); - } - - public static boolean validateIconLength(String icon) { - return icon.length() <= ICON_MAX_LENGTH; - } - - public static boolean validateProjectCode(String projectCode) { - return PROJECT_CODE_PATTERN.matcher(projectCode).matches(); - } - - public static boolean validateProjectCodeLegth(String projectCode) { - return projectCode.length() <= PROJECT_CODE_MAX_LEGTH; - } - - public static boolean validateContactId(String contactId) { - return CONTACT_ID_PATTERN.matcher(contactId).matches(); - } - - public static boolean validateCost(String cost) { - return COST_PATTERN.matcher(cost).matches(); - } - - public static String removeHtmlTags(String str) { - return Jsoup.clean(str, Whitelist.none()); - } - - public static String removeAllTags(String htmlText) { - - return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim(); - } - - public static String normaliseWhitespace(String str) { - StringBuilder sb = new StringBuilder(str.length()); - appendNormalisedWhitespace(sb, str, false); - return sb.toString(); - } - - private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { - boolean lastWasWhite = false; - boolean reachedNonWhite = false; - - int len = string.length(); - int c; - for (int i = 0; i < len; i += Character.charCount(c)) { - c = string.codePointAt(i); - if (isWhitespace(c)) { - if ((stripLeading && !reachedNonWhite) || lastWasWhite) { - continue; - } - accum.append(' '); - lastWasWhite = true; - } else { - accum.appendCodePoint(c); - lastWasWhite = false; - reachedNonWhite = true; - } - } - } - - private static boolean isWhitespace(int c) { - return c == ' '; - } - - public static String stripOctets(String str) { - return OCTET_PATTERN.matcher(str).replaceAll(""); - } - - public static String removeNoneUtf8Chars(String input) { - return NONE_UTF8_PATTERN.matcher(input).replaceAll(""); - } - - public static boolean validateIsEnglish(String input) { - return ENGLISH_PATTERN.matcher(input).matches(); - } - - public static boolean validateIsAscii(String input) { - - return CharMatcher.ASCII.matchesAllOf(input); - } - - public static String convertHtmlTagsToEntities(String input) { - return StringEscapeUtils.escapeHtml4(input); - } - - public static List<String> removeDuplicateFromList(List<String> list) { - Set<String> hs = new LinkedHashSet<>(list); - list.clear(); - list.addAll(hs); - return list; - - } - - public static boolean validateTagLength(String tag) { - if (tag != null) { - return tag.length() <= TAG_MAX_LENGTH; - } - return false; - } - - public static boolean validateTagListLength(int tagListLength) { - return tagListLength <= TAG_LIST_MAX_LENGTH; - } - - public static boolean validateDescriptionLength(String description) { - return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH; - } - - public static boolean validateStringNotEmpty(String value) { - if ((value == null) || (value.isEmpty())) { - return false; - } - return true; - } - - public static boolean validateListNotEmpty(List<?> list) { - if ((list == null) || (list.isEmpty())) { - return false; - } - return true; - } - - public static boolean validateVendorName(String vendorName) { - return VENDOR_NAME_PATTERN.matcher(vendorName).matches(); - } - - public static boolean validateVendorNameLength(String vendorName) { - return vendorName.length() <= VENDOR_NAME_MAX_LENGTH; - } - - public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) { - return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH; - } - - public static boolean validateVendorRelease(String vendorRelease) { - return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches(); - } - - public static boolean validateVendorReleaseLength(String vendorRelease) { - return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH; - } - - public static boolean validateServiceTypeLength(String serviceType) { - return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH; - } - - public static boolean validateServiceRoleLength(String serviceRole) { - return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH; - } - - - public static boolean hasBeenCertified(String version) { - return NumberUtils.toDouble(version) >= 1; - } + public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024; + public final static Pattern COMPONENT_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH-1) + "}$"); + public final static Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50; + public final static Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern + .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$"); + public final static Integer RSI_NAME_MAX_LENGTH = 1024; + public final static Pattern RSI_NAME_PATTERN = Pattern + .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$"); + public final static Integer COMMENT_MAX_LENGTH = 256; + + public final static Integer ICON_MAX_LENGTH = 25; + public final static Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$"); + public final static Integer PROJECT_CODE_MAX_LEGTH = 50; + public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$"); + + // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9) + public final static Integer CONNTACT_ID_MAX_LENGTH = 50; + // public final static Pattern CONTACT_ID_PATTERN = Pattern +// .compile("[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}"); + public final static Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$"); + public final static Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}"); + public final static Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+"); + public final static Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");// ,#?&@$<>~^`\\[]{}|")(*! + + public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$"); + public final static Pattern COMMENT_PATTERN = Pattern.compile("^[\\u0000-\\u00BF]{1,1024}$"); + public final static Pattern SERVICE_METADATA_PATTERN = Pattern.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]{1,256}"); + public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; + public final static Integer SERVICE_TYPE_MAX_LENGTH = 256; + public final static Integer SERVICE_ROLE_MAX_LENGTH = 256; + public final static Integer SERVICE_FUNCTION_MAX_LENGTH = 256; + public final static Integer SERVICE_NAMING_POLICY_MAX_SIZE = 100; + + public final static Integer TAG_MAX_LENGTH = 1024; + public final static Integer TAG_LIST_MAX_LENGTH = 1024; + public final static Integer VENDOR_NAME_MAX_LENGTH = 60; + public final static Pattern VENDOR_NAME_PATTERN = Pattern + .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); + public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25; + public final static Pattern VENDOR_RELEASE_PATTERN = Pattern + .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); + public final static Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65; + + public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+"); + + public final static Pattern DASH_PATTERN = Pattern.compile("[-]+"); + public final static Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+"); + public final static Pattern PLUS_PATTERN = Pattern.compile("[+]+"); + public final static Pattern SPACE_PATTERN = Pattern.compile("[ ]+"); + public final static Pattern AMP_PATTERN = Pattern.compile("[&]+"); + public final static Pattern DOT_PATTERN = Pattern.compile("[\\.]+"); + public final static Pattern APOST_PATTERN = Pattern.compile("[']+"); + public final static Pattern HASHTAG_PATTERN = Pattern.compile("[#]+"); + public final static Pattern EQUAL_PATTERN = Pattern.compile("[=]+"); + public final static Pattern COLON_PATTERN = Pattern.compile("[:]+"); + public final static Pattern AT_PATTERN = Pattern.compile("[@]+"); + public final static Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] "); + public final static Set<String> CATEGORY_CONJUNCTIONS = new HashSet<>( + Arrays.asList("of", "to", "for", "as", "a", "an", "the")); + + public final static Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$"); + public final static Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$"); + public final static Integer ARTIFACT_LABEL_LENGTH = 255; + public final static Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); + public final static Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); + public final static Integer CATEGORY_LABEL_MIN_LENGTH = 3; + public final static Integer CATEGORY_LABEL_MAX_LENGTH = 25; + + public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); + public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); + public final static Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+"); + public final static Integer CONSUMER_NAME_MAX_LENGTH = 255; + // public final static Pattern CONSUMER_NAME_PATTERN = + // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH + + // "}?$"); + public final static Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$"); + public final static Integer CONSUMER_SALT_LENGTH = 32; + public final static Integer CONSUMER_PASSWORD_LENGTH = 64; + public final static Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$"); + public final static Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$"); + public final static Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$"); + public final static Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$"); + public final static Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>"); + public final static Pattern TAG_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,1024}$"); + + public final static Integer ARTIFACT_NAME_LENGTH = 255; + public final static Integer API_URL_LENGTH = 100; + public final static Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256; + + public final static Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; + public final static Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; + public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; + public final static Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH-1) + "}$"); + + public final static Integer POLICY_MAX_LENGTH = 1024; + public final static Pattern POLICY_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH-1) + "}$"); + + public static boolean validateArtifactLabel(String label) { + return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); + } + + public static boolean validateArtifactDisplayName(String displayName) { + return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches(); + } + + public static String cleanUpText(String text){ + text = removeNoneUtf8Chars(text); + text = normaliseWhitespace(text); + text = stripOctets(text); + text = removeHtmlTagsOnly(text); + return text; + } + + public static boolean validateTagPattern(String tag) { + return TAG_PATTERN.matcher(tag).matches(); + } + + public static boolean validateServiceMetadata(String metadataField) { + return SERVICE_METADATA_PATTERN.matcher(metadataField).matches(); + } + + public static boolean validateCommentPattern(String comment) { + return COMMENT_PATTERN.matcher(comment).matches(); + } + + public static boolean validateCategoryDisplayNameFormat(String label) { + boolean res = true; + if (label != null) { + label = label.trim(); + res = CATEGORY_LABEL_PATTERN.matcher(label).matches(); + } + return res; + } + + public static String normalizeCategoryName4Display(String str) { + if (str != null) { + str = str.trim(); + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = AMP_PATTERN.matcher(str).replaceAll("&"); + str = PLUS_PATTERN.matcher(str).replaceAll("+"); + str = DOT_PATTERN.matcher(str).replaceAll("."); + str = APOST_PATTERN.matcher(str).replaceAll("'"); + str = HASHTAG_PATTERN.matcher(str).replaceAll("#"); + str = EQUAL_PATTERN.matcher(str).replaceAll("="); + str = COLON_PATTERN.matcher(str).replaceAll(":"); + str = AT_PATTERN.matcher(str).replaceAll("@"); + str = normaliseWhitespace(str); + str = AND_PATTERN.matcher(str).replaceAll(" & "); + + // Case normalizing + StringBuilder sb = new StringBuilder(); + String[] split = str.split(" "); + for (int i = 0; i < split.length; i++) { + String splitted = split[i]; + String lowerCase = splitted.toLowerCase(); + // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but + // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not + // lowercased because it's first word) + // Agreed with Ella, 26/11/15 + if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) { + sb.append(lowerCase); + } else { + sb.append(WordUtils.capitalize(splitted)); + } + sb.append(" "); + } + str = sb.toString().trim(); + } + return str; + } + + public static String normalizeCategoryName4Uniqueness(String str) { + return str.toLowerCase(); + } + + public static boolean validateCategoryDisplayNameLength(String label) { + return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH + && label.length() <= CATEGORY_LABEL_MAX_LENGTH); + } + + public static boolean validateProductFullNameLength(String fullName) { + return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH + && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH); + } + + public static boolean validateArtifactLabelLength(String label) { + return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH; + } + + public static boolean validateResourceInstanceNameLength(String resourceInstanceName) { + return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH; + } + + public static boolean validateResourceInstanceName(String resourceInstanceName) { + return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches(); + } + + public static boolean validateUrlLength(String url) { + return url.length() <= API_URL_LENGTH; + } + + public static boolean validateArtifactNameLength(String artifactName) { + return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0); + } + + public static boolean validateComponentNamePattern(String componentName) { + return COMPONENT_NAME_PATTERN.matcher(componentName).matches(); + } + + public static boolean validateComponentNameLength(String componentName) { + return componentName.length() <= COMPONENT_NAME_MAX_LENGTH; + } + + public static boolean validateIcon(String icon) { + return ICON_PATTERN.matcher(icon).matches(); + } + + public static boolean validateIconLength(String icon) { + return icon.length() <= ICON_MAX_LENGTH; + } + + public static boolean validateProjectCode(String projectCode) { + return PROJECT_CODE_PATTERN.matcher(projectCode).matches(); + } + + public static boolean validateProjectCodeLegth(String projectCode) { + return projectCode.length() <= PROJECT_CODE_MAX_LEGTH; + } + + public static boolean validateContactId(String contactId) { + return CONTACT_ID_PATTERN.matcher(contactId).matches(); + } + + public static boolean validateCost(String cost) { + return COST_PATTERN.matcher(cost).matches(); + } + + public static String removeHtmlTags(String str) { + return Jsoup.clean(str, Whitelist.none()); + } + + public static String removeAllTags(String htmlText) { + + return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim(); + } + + public static String normaliseWhitespace(String str) { + StringBuilder sb = new StringBuilder(str.length()); + appendNormalisedWhitespace(sb, str, false); + return sb.toString(); + } + + private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { + boolean lastWasWhite = false; + boolean reachedNonWhite = false; + + int len = string.length(); + int c; + for (int i = 0; i < len; i+= Character.charCount(c)) { + c = string.codePointAt(i); + if (isWhitespace(c)) { + if ((stripLeading && !reachedNonWhite) || lastWasWhite) + continue; + accum.append(' '); + lastWasWhite = true; + } + else { + accum.appendCodePoint(c); + lastWasWhite = false; + reachedNonWhite = true; + } + } + } + + private static boolean isWhitespace(int c){ + return c == ' '; + } + + public static String stripOctets(String str) { + return OCTET_PATTERN.matcher(str).replaceAll(""); + } + + public static String removeNoneUtf8Chars(String input) { + return NONE_UTF8_PATTERN.matcher(input).replaceAll(""); + } + + public static boolean validateIsEnglish(String input) { + return ENGLISH_PATTERN.matcher(input).matches(); + } + + public static boolean validateIsAscii(String input) { + + return CharMatcher.ASCII.matchesAllOf(input); + } + + public static String convertHtmlTagsToEntities(String input) { + return StringEscapeUtils.escapeHtml4(input); + } + + public static List<String> removeDuplicateFromList(List<String> list) { + Set<String> hs = new LinkedHashSet<>(list); + list.clear(); + list.addAll(hs); + return list; + + } + + public static boolean validateTagLength(String tag) { + if (tag != null) { + return tag.length() <= TAG_MAX_LENGTH; + } + return false; + } + + public static boolean validateTagListLength(int tagListLength) { + return tagListLength <= TAG_LIST_MAX_LENGTH; + } + + public static boolean validateDescriptionLength(String description) { + return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH; + } + + public static boolean validateStringNotEmpty(String value) { + if ((value == null) || (value.isEmpty())) { + return false; + } + return true; + } + + public static boolean validateListNotEmpty(List<?> list) { + if ((list == null) || (list.isEmpty())) { + return false; + } + return true; + } + + public static boolean validateVendorName(String vendorName) { + return VENDOR_NAME_PATTERN.matcher(vendorName).matches(); + } + + public static boolean validateVendorNameLength(String vendorName) { + return vendorName.length() <= VENDOR_NAME_MAX_LENGTH; + } + + public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) { + return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH; + } + + public static boolean validateVendorRelease(String vendorRelease) { + return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches(); + } + + public static boolean validateVendorReleaseLength(String vendorRelease) { + return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH; + } + + public static boolean validateServiceTypeLength(String serviceType) { + return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH; + } + + public static boolean validateServiceRoleLength(String serviceRole) { + return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH; + } + + public static boolean validateServiceFunctionLength(String serviceFunction) { + return serviceFunction.length() <= SERVICE_FUNCTION_MAX_LENGTH; + } + + public static boolean validateServiceNamingPolicyLength(String namingPolicy) { + return namingPolicy.length() <= SERVICE_NAMING_POLICY_MAX_SIZE; + } + public static boolean hasBeenCertified(String version) { + return NumberUtils.toDouble(version) >= 1; + } public static String normaliseComponentName(String name) { String[] split = splitComponentName(name); @@ -389,7 +421,7 @@ public class ValidationUtils { } return sb.toString(); - } + } public static String normalizeComponentInstanceName(String name) { String[] split = splitComponentInstanceName(name); @@ -399,19 +431,19 @@ public class ValidationUtils { } return sb.toString(); - } + } - private static String[] splitComponentName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } + private static String[] splitComponentName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } - private static String[] splitComponentInstanceName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } + private static String[] splitComponentInstanceName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } public static String convertToSystemName(String name) { String[] split = splitComponentName(name); @@ -423,133 +455,137 @@ public class ValidationUtils { return sb.toString(); } - public static String normalizeFileName(String filename) { - // String[] split = filename.split(Pattern.quote(File.separator)); - // String name = ""; - // - // name = split[split.length - 1]; - return cleanFileName(filename); - - } - - private static String cleanFileName(String str) { - str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll(""); - str = normaliseWhitespace(str); - str = SPACE_PATTERN.matcher(str).replaceAll("-"); - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = StringUtils.strip(str, "-_ ."); - - return str; - } - - public static boolean validateUrl(String url) { - - UrlValidator urlValidator = new UrlValidator(); - if (!urlValidator.isValid(url)) { - return false; - } - if (NONE_UTF8_PATTERN.matcher(url).find()) { - return false; - } - - if (URL_INVALIDE_PATTERN.matcher(url).find()) { - return false; - } - return true; - - } - - public static String cleanArtifactDisplayName(String strIn) { - String str = DASH_PATTERN.matcher(strIn).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = PLUS_PATTERN.matcher(str).replaceAll("+"); - str = normaliseWhitespace(str); - str = str.trim(); - // str = str.replaceAll(" ", ""); - - return str; - } - - public static String normalizeArtifactLabel(String strIn) { - - String str = DASH_PATTERN.matcher(strIn).replaceAll(""); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll(""); - str = PLUS_PATTERN.matcher(str).replaceAll(""); - str = SPACE_PATTERN.matcher(str).replaceAll(""); - str = DOT_PATTERN.matcher(str).replaceAll(""); - str = str.toLowerCase(); - - return str; - } - - public static boolean validateAdditionalInformationKeyName(String str) { - return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches(); - } - - public static String normalizeAdditionalInformation(String str) { - if (str != null) { - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = normaliseWhitespace(str); - } - return str; - } - - public static boolean validateLength(String str, int length) { - if (str == null) { - return true; - } - return str.length() <= length; - } - - public static boolean validateConsumerName(String consumerName) { - return CONSUMER_NAME_PATTERN.matcher(consumerName).matches(); - } - - public static boolean isUTF8Str(String str) { - if (NONE_UTF8_PATTERN.matcher(str).find()) { - return false; - } - return true; - } - - public static boolean validateConsumerPassSalt(String consumerSalt) { - return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches(); - } - - public static boolean isFloatNumber(String number) { - return FLOAT_PATTERN.matcher(number).matches(); - } - - public static boolean validateCertifiedVersion(String version) { - return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches()); - } - - public static boolean validateMinorVersion(String version) { - return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches()); - } - - public static String normaliseProductName(String name) { - String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name); - StringBuilder sb = new StringBuilder(); - for (String splitElement : split) { - sb.append(splitElement); - } - return sb.toString(); - - } - - private static String[] splitComponentName(Pattern pattern, String name) { - String normalizedName = name.toLowerCase(); - normalizedName = pattern.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } - - public static String removeHtmlTagsOnly(String htmlText) { - return HtmlCleaner.stripHtml(htmlText, false); - } - - public static boolean validateForwardingPathNamePattern(String forwardingPathName) { - return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); - } + public static String normalizeFileName(String filename) { + // String[] split = filename.split(Pattern.quote(File.separator)); + // String name = ""; + // + // name = split[split.length - 1]; + return cleanFileName(filename); + + } + + private static String cleanFileName(String str) { + str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll(""); + str = normaliseWhitespace(str); + str = SPACE_PATTERN.matcher(str).replaceAll("-"); + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = StringUtils.strip(str, "-_ ."); + + return str; + } + + public static boolean validateUrl(String url) { + + UrlValidator urlValidator = new UrlValidator(); + if (!urlValidator.isValid(url)) { + return false; + } + if (NONE_UTF8_PATTERN.matcher(url).find()) { + return false; + } + + if (URL_INVALIDE_PATTERN.matcher(url).find()) { + return false; + } + return true; + + } + + public static String cleanArtifactDisplayName(String strIn) { + String str = DASH_PATTERN.matcher(strIn).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = PLUS_PATTERN.matcher(str).replaceAll("+"); + str = normaliseWhitespace(str); + str = str.trim(); + // str = str.replaceAll(" ", ""); + + return str; + } + + public static String normalizeArtifactLabel(String strIn) { + + String str = DASH_PATTERN.matcher(strIn).replaceAll(""); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll(""); + str = PLUS_PATTERN.matcher(str).replaceAll(""); + str = SPACE_PATTERN.matcher(str).replaceAll(""); + str = DOT_PATTERN.matcher(str).replaceAll(""); + str = str.toLowerCase(); + + return str; + } + + public static boolean validateAdditionalInformationKeyName(String str) { + return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches(); + } + + public static String normalizeAdditionalInformation(String str) { + if (str != null) { + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = normaliseWhitespace(str); + } + return str; + } + + public static boolean validateLength(String str, int length) { + if (str == null) { + return true; + } + return str.length() <= length; + } + + public static boolean validateConsumerName(String consumerName) { + return CONSUMER_NAME_PATTERN.matcher(consumerName).matches(); + } + + public static boolean isUTF8Str(String str) { + if (NONE_UTF8_PATTERN.matcher(str).find()) { + return false; + } + return true; + } + + public static boolean validateConsumerPassSalt(String consumerSalt) { + return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches(); + } + + public static boolean isFloatNumber(String number) { + return FLOAT_PATTERN.matcher(number).matches(); + } + + public static boolean validateCertifiedVersion(String version) { + return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches()); + } + + public static boolean validateMinorVersion(String version) { + return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches()); + } + + public static boolean validateCategoryIconNotEmpty(List<String> categoryIcons) { + return CollectionUtils.isEmpty(categoryIcons); + } + + public static String normaliseProductName(String name) { + String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name); + StringBuilder sb = new StringBuilder(); + for (String splitElement : split) { + sb.append(splitElement); + } + return sb.toString(); + + } + + private static String[] splitComponentName(Pattern pattern, String name) { + String normalizedName = name.toLowerCase(); + normalizedName = pattern.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } + + public static String removeHtmlTagsOnly(String htmlText) { + return HtmlCleaner.stripHtml(htmlText, false); + } + + public static boolean validateForwardingPathNamePattern(String forwardingPathName) { + return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java index 801b6c1aaa..b2435de12c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,16 +21,7 @@ package org.openecomp.sdc.common.util; import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig; -import org.openecomp.sdc.be.config.Configuration.ApplicationL2CacheConfig; -import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; -import org.openecomp.sdc.be.config.Configuration.BeMonitoringConfig; -import org.openecomp.sdc.be.config.Configuration.EcompPortalConfig; -import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig; -import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry; -import org.openecomp.sdc.be.config.Configuration.OnboardingConfig; -import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; -import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig; +import org.openecomp.sdc.be.config.Configuration.*; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.ComponentArtifactTypesConfig; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; @@ -57,228 +48,222 @@ import java.util.Map; public class YamlToObjectConverter { - private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); + private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); - private static HashMap<String, Yaml> yamls = new HashMap<>(); + private static HashMap<String, Yaml> yamls = new HashMap<>(); - private static Yaml defaultYaml = new Yaml(); + private static Yaml defaultYaml = new Yaml(); - static { + static { - org.yaml.snakeyaml.constructor.Constructor deConstructor = new org.yaml.snakeyaml.constructor.Constructor( - DistributionEngineConfiguration.class); - TypeDescription deDescription = new TypeDescription(DistributionEngineConfiguration.class); - deDescription.putListPropertyType("distributionStatusTopic", DistributionStatusTopicConfig.class); - deDescription.putListPropertyType("distribNotifServiceArtifactTypes", ComponentArtifactTypesConfig.class); - deDescription.putListPropertyType("distribNotifResourceArtifactTypes", ComponentArtifactTypesConfig.class); - deDescription.putListPropertyType("createTopic", CreateTopicConfig.class); - deDescription.putListPropertyType("distributionNotificationTopic", DistributionNotificationTopicConfig.class); - deConstructor.addTypeDescription(deDescription); - Yaml yaml = new Yaml(deConstructor); - yamls.put(DistributionEngineConfiguration.class.getName(), yaml); + org.yaml.snakeyaml.constructor.Constructor deConstructor = new org.yaml.snakeyaml.constructor.Constructor( + DistributionEngineConfiguration.class); + TypeDescription deDescription = new TypeDescription(DistributionEngineConfiguration.class); + deDescription.putListPropertyType("distributionStatusTopic", DistributionStatusTopicConfig.class); + deDescription.putListPropertyType("distribNotifServiceArtifactTypes", ComponentArtifactTypesConfig.class); + deDescription.putListPropertyType("distribNotifResourceArtifactTypes", ComponentArtifactTypesConfig.class); + deDescription.putListPropertyType("createTopic", CreateTopicConfig.class); + deDescription.putListPropertyType("distributionNotificationTopic", DistributionNotificationTopicConfig.class); + deConstructor.addTypeDescription(deDescription); + Yaml yaml = new Yaml(deConstructor); + yamls.put(DistributionEngineConfiguration.class.getName(), yaml); - // FE conf - org.yaml.snakeyaml.constructor.Constructor feConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( - org.openecomp.sdc.fe.config.Configuration.class); - TypeDescription feConfDescription = new TypeDescription(org.openecomp.sdc.fe.config.Configuration.class); - feConfDescription.putListPropertyType("systemMonitoring", FeMonitoringConfig.class); - feConfConstructor.addTypeDescription(feConfDescription); - yamls.put(org.openecomp.sdc.fe.config.Configuration.class.getName(), new Yaml(feConfConstructor)); - - // BE conf - org.yaml.snakeyaml.constructor.Constructor beConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( - org.openecomp.sdc.be.config.Configuration.class); - TypeDescription beConfDescription = new TypeDescription(org.openecomp.sdc.be.config.Configuration.class); - beConfConstructor.addTypeDescription(beConfDescription); - - // systemMonitoring - beConfDescription.putListPropertyType("systemMonitoring", BeMonitoringConfig.class); - - // elasticSearch - beConfDescription.putListPropertyType("elasticSearch", ElasticSearchConfig.class); - TypeDescription esDescription = new TypeDescription(ElasticSearchConfig.class); - esDescription.putListPropertyType("indicesTimeFrequency", IndicesTimeFrequencyEntry.class); - beConfConstructor.addTypeDescription(esDescription); - - // resourceDeploymentArtifacts and serviceDeploymentArtifacts - beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class, - ArtifactTypeConfig.class); - beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class, - ArtifactTypeConfig.class); - - // onboarding - beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class); - - // ecompPortal - beConfDescription.putListPropertyType("ecompPortal", EcompPortalConfig.class); - // switchoverDetector - beConfDescription.putListPropertyType("switchoverDetector", SwitchoverDetectorConfig.class); - - // ApplicationL1Cache - beConfDescription.putListPropertyType("applicationL1Cache", ApplicationL1CacheConfig.class); - - // ApplicationL2Cache - beConfDescription.putListPropertyType("applicationL2Cache", ApplicationL2CacheConfig.class); - - // tosca validators config - beConfDescription.putListPropertyType("toscaValidators", ToscaValidatorsConfig.class); - - yamls.put(org.openecomp.sdc.be.config.Configuration.class.getName(), new Yaml(beConfConstructor)); - - // HEAT deployment artifact - org.yaml.snakeyaml.constructor.Constructor depArtHeatConstructor = new org.yaml.snakeyaml.constructor.Constructor( - DeploymentArtifactHeatConfiguration.class); - PropertyUtils propertyUtils = new PropertyUtils(); - // Skip properties which are found in YAML but not found in POJO - propertyUtils.setSkipMissingProperties(true); - depArtHeatConstructor.setPropertyUtils(propertyUtils); - yamls.put(org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration.class.getName(), - new Yaml(depArtHeatConstructor)); - - } - - private static <T> Yaml getYamlByClassName(Class<T> className) { - - Yaml yaml = yamls.get(className.getName()); - if (yaml == null) { - yaml = defaultYaml; - } - - return yaml; - } - - public <T> T convert(String dirPath, Class<T> className, String configFileName) { - - T config = null; - - try { - - String fullFileName = dirPath + File.separator + configFileName; - - config = convert(fullFileName, className); - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", configFileName, e); - } - - return config; - } - - public class MyYamlConstructor extends org.yaml.snakeyaml.constructor.Constructor { - private HashMap<String, Class<?>> classMap = new HashMap<>(); - - public MyYamlConstructor(Class<? extends Object> theRoot) { - super(theRoot); - classMap.put(DistributionEngineConfiguration.class.getName(), DistributionEngineConfiguration.class); - classMap.put(DistributionStatusTopicConfig.class.getName(), DistributionStatusTopicConfig.class); - } - - /* - * This is a modified version of the Constructor. Rather than using a - * class loader to get external classes, they are already predefined - * above. This approach works similar to the typeTags structure in the - * original constructor, except that class information is pre-populated - * during initialization rather than runtime. - * - * @see - * org.yaml.snakeyaml.constructor.Constructor#getClassForNode(org.yaml. - * snakeyaml.nodes.Node) - */ - protected Class<?> getClassForNode(Node node) { - String name = node.getTag().getClassName(); - Class<?> cl = classMap.get(name); - if (cl == null) { - throw new YAMLException("Class not found: " + name); - } else { - return cl; - } - } - } - - public <T> T convert(String fullFileName, Class<T> className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); - - InputStream in = null; - try { - - File f = new File(fullFileName); - if (!f.exists()) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "The file {} cannot be found. Ignore reading configuration.", fullFileName); - return null; - } - in = Files.newInputStream(Paths.get(fullFileName)); - - config = yaml.loadAs(in, className); - - // System.out.println(config.toString()); - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", fullFileName, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - log.debug("Failed to close input stream", e); - } - } - } - - return config; - } - - public <T> T convert(byte[] fileContents, Class<T> className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); + // FE conf + org.yaml.snakeyaml.constructor.Constructor feConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( + org.openecomp.sdc.fe.config.Configuration.class); + TypeDescription feConfDescription = new TypeDescription(org.openecomp.sdc.fe.config.Configuration.class); + feConfDescription.putListPropertyType("systemMonitoring", FeMonitoringConfig.class); + feConfConstructor.addTypeDescription(feConfDescription); + yamls.put(org.openecomp.sdc.fe.config.Configuration.class.getName(), new Yaml(feConfConstructor)); + + // BE conf + org.yaml.snakeyaml.constructor.Constructor beConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( + org.openecomp.sdc.be.config.Configuration.class); + TypeDescription beConfDescription = new TypeDescription(org.openecomp.sdc.be.config.Configuration.class); + beConfConstructor.addTypeDescription(beConfDescription); + + // systemMonitoring + beConfDescription.putListPropertyType("systemMonitoring", BeMonitoringConfig.class); - InputStream in = null; - try { - - in = new ByteArrayInputStream(fileContents); - - config = yaml.loadAs(in, className); - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - log.debug("Failed to close input stream", e); - } - } - } - - return config; - } - - public boolean isValidYamlEncoded64(byte[] fileContents) { - log.trace("Received Base64 data - decoding before validating..."); - byte[] decodedFileContents = Base64.decodeBase64(fileContents); - - return isValidYaml(decodedFileContents); - } - - @SuppressWarnings("unchecked") - public boolean isValidYaml(byte[] fileContents) { - try { - - Iterable<Object> mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); - - for (Object o : mappedToscaTemplateIt) { - System.out.println("Loaded object type:" + o.getClass()); - Map<String, Object> map = (Map<String, Object>) o; - } - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object - yaml is invalid", e); - return false; - } - return true; - } + // resourceDeploymentArtifacts and serviceDeploymentArtifacts + beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class, + ArtifactTypeConfig.class); + beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class, + ArtifactTypeConfig.class); + + // onboarding + beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class); + + // ecompPortal + beConfDescription.putListPropertyType("ecompPortal", EcompPortalConfig.class); + // switchoverDetector + beConfDescription.putListPropertyType("switchoverDetector", SwitchoverDetectorConfig.class); + + // ApplicationL1Cache + beConfDescription.putListPropertyType("applicationL1Cache", ApplicationL1CacheConfig.class); + + // ApplicationL2Cache + beConfDescription.putListPropertyType("applicationL2Cache", ApplicationL2CacheConfig.class); + + // tosca validators config + beConfDescription.putListPropertyType("toscaValidators", ToscaValidatorsConfig.class); + + yamls.put(org.openecomp.sdc.be.config.Configuration.class.getName(), new Yaml(beConfConstructor)); + + // HEAT deployment artifact + org.yaml.snakeyaml.constructor.Constructor depArtHeatConstructor = new org.yaml.snakeyaml.constructor.Constructor( + DeploymentArtifactHeatConfiguration.class); + PropertyUtils propertyUtils = new PropertyUtils(); + // Skip properties which are found in YAML but not found in POJO + propertyUtils.setSkipMissingProperties(true); + depArtHeatConstructor.setPropertyUtils(propertyUtils); + yamls.put(org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration.class.getName(), + new Yaml(depArtHeatConstructor)); + + } + + private static <T> Yaml getYamlByClassName(Class<T> className) { + + Yaml yaml = yamls.get(className.getName()); + if (yaml == null) { + yaml = defaultYaml; + } + + return yaml; + } + + public <T> T convert(String dirPath, Class<T> className, String configFileName) { + + T config = null; + + try { + + String fullFileName = dirPath + File.separator + configFileName; + + config = convert(fullFileName, className); + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file {} to object.", configFileName,e); + } + + return config; + } + + public class MyYamlConstructor extends org.yaml.snakeyaml.constructor.Constructor { + private HashMap<String, Class<?>> classMap = new HashMap<>(); + + public MyYamlConstructor(Class<? extends Object> theRoot) { + super(theRoot); + classMap.put(DistributionEngineConfiguration.class.getName(), DistributionEngineConfiguration.class); + classMap.put(DistributionStatusTopicConfig.class.getName(), DistributionStatusTopicConfig.class); + } + + /* + * This is a modified version of the Constructor. Rather than using a + * class loader to get external classes, they are already predefined + * above. This approach works similar to the typeTags structure in the + * original constructor, except that class information is pre-populated + * during initialization rather than runtime. + * + * @see + * org.yaml.snakeyaml.constructor.Constructor#getClassForNode(org.yaml. + * snakeyaml.nodes.Node) + */ + protected Class<?> getClassForNode(Node node) { + String name = node.getTag().getClassName(); + Class<?> cl = classMap.get(name); + if (cl == null) + throw new YAMLException("Class not found: " + name); + else + return cl; + } + } + + public <T> T convert(String fullFileName, Class<T> className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + File f = new File(fullFileName); + if (!f.exists()) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","The file {} cannot be found. Ignore reading configuration.",fullFileName); + return null; + } + in = Files.newInputStream(Paths.get(fullFileName)); + + config = yaml.loadAs(in, className); + + // System.out.println(config.toString()); + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file {} to object.", fullFileName, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + log.debug("Failed to close input stream", e); + e.printStackTrace(); + } + } + } + + return config; + } + + public <T> T convert(byte[] fileContents, Class<T> className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + in = new ByteArrayInputStream(fileContents); + + config = yaml.loadAs(in, className); + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file to object", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + log.debug("Failed to close input stream", e); + e.printStackTrace(); + } + } + } + + return config; + } + + public boolean isValidYamlEncoded64(byte[] fileContents) { + log.trace("Received Base64 data - decoding before validating..."); + byte[] decodedFileContents = Base64.decodeBase64(fileContents); + + return isValidYaml(decodedFileContents); + } + @SuppressWarnings("unchecked") + public boolean isValidYaml(byte[] fileContents) { + try { + + Iterable<Object> mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); + + for (Object o : mappedToscaTemplateIt) { + System.out.println("Loaded object type:" + o.getClass()); + Map<String, Object> map = (Map<String, Object>) o; + } + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file to object - yaml is invalid", e); + return false; + } + return true; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java index 7fac9f33fa..75315a06cc 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/AbstractSdncException.java @@ -22,6 +22,7 @@ package org.openecomp.sdc.exception; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.GeneralUtility; import java.util.Arrays; import java.util.Formatter; @@ -30,87 +31,94 @@ import java.util.regex.Pattern; public abstract class AbstractSdncException { - private String messageId; - - private String text; - - private String[] variables; - - private static Logger log = Logger.getLogger(AbstractSdncException.class.getName()); - - private static final Pattern ERROR_PARAM_PATTERN = Pattern.compile("%\\d"); - - public AbstractSdncException() { - } - - public AbstractSdncException(String messageId, String text, String[] variables) { - super(); - this.messageId = messageId; - this.text = text; - this.variables = validateParameters(messageId, text, variables); - } - - private String[] validateParameters(String messageId, String text, String[] variables) { - String[] res = null; - Matcher m = ERROR_PARAM_PATTERN.matcher(text); - int expectedParamsNum = 0; - while (m.find()) { - expectedParamsNum += 1; - } - int actualParamsNum = (variables != null) ? variables.length : 0; - if (actualParamsNum < expectedParamsNum) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", - "Received less parameters than expected for error with messageId {}, expected: {}, actual: {}. Missing parameters are padded with null values.", - messageId, expectedParamsNum, actualParamsNum); - } else if (actualParamsNum > expectedParamsNum) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "", - "Received more parameters than expected for error with messageId {}, expected: {}, actual: {}. Extra parameters are ignored.", - messageId, expectedParamsNum, actualParamsNum); - } - if (variables != null) { - res = Arrays.copyOf(variables, expectedParamsNum); - } - - return res; - } - - public String getMessageId() { - return this.messageId; - } - - public String getText() { - return text; - } - - public String[] getVariables() { - return variables; - } - - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - public void setText(String text) { - this.text = text; - } - - public void setVariables(String[] variables) { - this.variables = variables; - } - - public String getFormattedErrorMessage() { - String res; - if (variables != null && variables.length > 0) { - Formatter formatter = new Formatter(); - try { - res = formatter.format(this.text.replaceAll("%\\d", "%s"), (Object[]) this.variables).toString(); - } finally { - formatter.close(); - } - } else { - res = this.text; - } - return res; - } + private String messageId; + + private String text; + + private final String ecompRequestId; + + private String[] variables; + + private static Logger log = Logger.getLogger(AbstractSdncException.class.getName()); + + private final static Pattern ERROR_PARAM_PATTERN = Pattern.compile("%\\d"); + + public AbstractSdncException() { + this.ecompRequestId = GeneralUtility.getEcompRequestId(); + } + + public AbstractSdncException(String messageId, String text, String[] variables) { + this(); + this.messageId = messageId; + this.text = text; + this.variables = validateParameters(messageId, text, variables); + } + + private String[] validateParameters(String messageId, String text, String[] variables) { + String[] res = null; + Matcher m = ERROR_PARAM_PATTERN.matcher(text); + int expectedParamsNum = 0; + while (m.find()) { + expectedParamsNum += 1; + } + int actualParamsNum = (variables != null) ? variables.length : 0; + if (actualParamsNum < expectedParamsNum) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","", + "Received less parameters than expected for error with messageId {}, expected: {}, actual: {}. Missing parameters are padded with null values.", + messageId, expectedParamsNum, actualParamsNum); + } else if (actualParamsNum > expectedParamsNum) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","", + "Received more parameters than expected for error with messageId {}, expected: {}, actual: {}. Extra parameters are ignored.", + messageId, expectedParamsNum, actualParamsNum); + } + if (variables != null) { + res = Arrays.copyOf(variables, expectedParamsNum); + } + + return res; + } + + public String getMessageId() { + return messageId; + } + + public String getText() { + return text; + } + + public String getEcompRequestId() { + return ecompRequestId; + } + + public String[] getVariables() { + return variables; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public void setText(String text) { + this.text = text; + } + + public void setVariables(String[] variables) { + this.variables = variables; + } + + public String getFormattedErrorMessage() { + String res; + if (variables != null && variables.length > 0) { + Formatter formatter = new Formatter(); + try { + res = formatter.format(this.text.replaceAll("%\\d", "%s"), (Object[]) this.variables).toString(); + } finally { + formatter.close(); + } + } else { + res = this.text; + } + return res; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java index b9de46640a..ec33b69d82 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteLastApplicationEnvironmentException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,13 +22,13 @@ package org.openecomp.sdc.exception; public class DeleteLastApplicationEnvironmentException extends TechnicalException { - private static final long serialVersionUID = -5192834855057177252L; + private static final long serialVersionUID = -5192834855057177252L; - public DeleteLastApplicationEnvironmentException(String message, Throwable cause) { - super(message, cause); - } + public DeleteLastApplicationEnvironmentException(String message, Throwable cause) { + super(message, cause); + } - public DeleteLastApplicationEnvironmentException(String message) { - super(message); - } + public DeleteLastApplicationEnvironmentException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java index 28c0d99538..6957e960c3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/DeleteReferencedObjectException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,9 +27,9 @@ package org.openecomp.sdc.exception; * @author Minh Khang VU */ public class DeleteReferencedObjectException extends TechnicalException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public DeleteReferencedObjectException(String message) { - super(message); - } + public DeleteReferencedObjectException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java index 8989feb2ef..5bf67484d5 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/FunctionalException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,18 +23,19 @@ package org.openecomp.sdc.exception; /** * All functional exception which is related to user input must go here. It's a * checked exception to force error handling and checking. - * + * * @author mkv + * */ public class FunctionalException extends Exception { - private static final long serialVersionUID = 6712845685798792493L; + private static final long serialVersionUID = 6712845685798792493L; - public FunctionalException(String message, Throwable cause) { - super(message, cause); - } + public FunctionalException(String message, Throwable cause) { + super(message, cause); + } - public FunctionalException(String message) { - super(message); - } + public FunctionalException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java index 0e505ff7ff..d8b8518919 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/IndexingServiceException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,18 +22,18 @@ package org.openecomp.sdc.exception; /** * All errors happened while trying to access to index service - * + * * @author mkv */ public class IndexingServiceException extends TechnicalException { - private static final long serialVersionUID = 8644422735660389058L; + private static final long serialVersionUID = 8644422735660389058L; - public IndexingServiceException(String message, Throwable cause) { - super(message, cause); - } + public IndexingServiceException(String message, Throwable cause) { + super(message, cause); + } - public IndexingServiceException(String message) { - super(message); - } + public IndexingServiceException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java index 6de09fd594..ef6cd659e4 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/InvalidArgumentException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,13 +21,13 @@ package org.openecomp.sdc.exception; public class InvalidArgumentException extends TechnicalException { - private static final long serialVersionUID = 931646037604062840L; + private static final long serialVersionUID = 931646037604062840L; - public InvalidArgumentException(String message, Throwable cause) { - super(message, cause); - } + public InvalidArgumentException(String message, Throwable cause) { + super(message, cause); + } - public InvalidArgumentException(String message) { - super(message); - } + public InvalidArgumentException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java index 6f4d41c582..988325ff3e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/NotFoundException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,14 +22,14 @@ package org.openecomp.sdc.exception; public class NotFoundException extends TechnicalException { - private static final long serialVersionUID = -5838741067731786413L; + private static final long serialVersionUID = -5838741067731786413L; - public NotFoundException(String message, Throwable cause) { - super(message, cause); - } + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } - public NotFoundException(String message) { - super(message); - } + public NotFoundException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java index 2c5da89eef..78405e0eb1 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/OkResponseInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,7 +22,7 @@ package org.openecomp.sdc.exception; public class OkResponseInfo extends AbstractSdncException { - public OkResponseInfo(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } + public OkResponseInfo(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java index c557bccad3..8c5c8609b6 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/PolicyException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,10 +22,10 @@ package org.openecomp.sdc.exception; public class PolicyException extends AbstractSdncException { - public PolicyException(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } + public PolicyException(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } - public PolicyException() { - } + public PolicyException() { + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java index 59d30d5180..109164d07d 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/ResponseFormat.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,169 +22,171 @@ package org.openecomp.sdc.exception; /** * Nested POJOs to express required JSON format of the error - * + * * { "requestError": { "serviceException": { "messageId": "", "text": "", * "variables": [] } } } - * + * + * * @author paharoni + * */ public class ResponseFormat { - private int status; - private RequestErrorWrapper requestErrorWrapper; - - public ResponseFormat() { - super(); - } - - public ResponseFormat(int status) { - super(); - this.status = status; - } - - public void setStatus(int status) { - this.status = status; - } - - public Integer getStatus() { - return status; - } - - public RequestErrorWrapper getRequestError() { - return requestErrorWrapper; - } - - public void setRequestError(RequestErrorWrapper requestErrorWrapper) { - this.requestErrorWrapper = requestErrorWrapper; - } - - public void setPolicyException(PolicyException policyException) { - this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); - requestErrorWrapper.setPolicyException(policyException); - } - - public void setServiceException(ServiceException serviceException) { - this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); - requestErrorWrapper.setServiceException(serviceException); - } - - public void setOkResponseInfo(OkResponseInfo okResponseInfo) { - this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); - requestErrorWrapper.setOkResponseInfo(okResponseInfo); - } - - public String getFormattedMessage() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getFormattedErrorMessage(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getFormattedErrorMessage(); - } - return this.requestErrorWrapper.requestError.policyException.getFormattedErrorMessage(); - } - - public String getText() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getText(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getText(); - } - return this.requestErrorWrapper.requestError.policyException.getText(); - } - - public String[] getVariables() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getVariables(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getVariables(); - } - return this.requestErrorWrapper.requestError.policyException.getVariables(); - } - - public String getMessageId() { - if (this.requestErrorWrapper.requestError.okResponseInfo != null) { - return this.requestErrorWrapper.requestError.okResponseInfo.getMessageId(); - } - if (this.requestErrorWrapper.requestError.serviceException != null) { - return this.requestErrorWrapper.requestError.serviceException.getMessageId(); - } - return this.requestErrorWrapper.requestError.policyException.getMessageId(); - } - - public class RequestErrorWrapper { - private RequestError requestError; - - public RequestErrorWrapper() { - this.requestError = new RequestError(); - } - - public RequestErrorWrapper(RequestError requestError) { - this.requestError = requestError; - } - - public RequestError getRequestError() { - return requestError; - } - - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - public void setPolicyException(PolicyException policyException) { - requestError.setPolicyException(policyException); - } - - public void setServiceException(ServiceException serviceException) { - requestError.setServiceException(serviceException); - } - - public void setOkResponseInfo(OkResponseInfo okResponseInfo) { - requestError.setOkResponseInfo(okResponseInfo); - } - } - - public class RequestError { - @SuppressWarnings("unused") - private PolicyException policyException; - @SuppressWarnings("unused") - private ServiceException serviceException; - @SuppressWarnings("unused") - private OkResponseInfo okResponseInfo; - - public RequestError() { - } - - public PolicyException getPolicyException() { - return policyException; - } - - public ServiceException getServiceException() { - return serviceException; - } - - public OkResponseInfo getOkResponseInfo() { - return okResponseInfo; - } - - public void setPolicyException(PolicyException policyException) { - this.policyException = policyException; - } - - public void setServiceException(ServiceException serviceException) { - this.serviceException = serviceException; - } - - public void setOkResponseInfo(OkResponseInfo okResponseInfo) { - this.okResponseInfo = okResponseInfo; - } - } - - @Override - public String toString() { - return "ResponseFormat[" + "status=" + status + ", requestErrorWrapper=" + requestErrorWrapper + ']'; - } - + private int status; + private RequestErrorWrapper requestErrorWrapper; + + public ResponseFormat() { + super(); + } + + public ResponseFormat(int status) { + super(); + this.status = status; + } + + public void setStatus(int status) { + this.status = status; + } + + public Integer getStatus() { + return status; + } + + public RequestErrorWrapper getRequestError() { + return requestErrorWrapper; + } + + public void setRequestError(RequestErrorWrapper requestErrorWrapper) { + this.requestErrorWrapper = requestErrorWrapper; + } + + public void setPolicyException(PolicyException policyException) { + this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); + requestErrorWrapper.setPolicyException(policyException); + } + + public void setServiceException(ServiceException serviceException) { + this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); + requestErrorWrapper.setServiceException(serviceException); + } + + public void setOkResponseInfo(OkResponseInfo okResponseInfo) { + this.requestErrorWrapper = new RequestErrorWrapper(new RequestError()); + requestErrorWrapper.setOkResponseInfo(okResponseInfo); + } + + public String getFormattedMessage() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getFormattedErrorMessage(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getFormattedErrorMessage(); + } + return this.requestErrorWrapper.requestError.policyException.getFormattedErrorMessage(); + } + + public String getText() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getText(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getText(); + } + return this.requestErrorWrapper.requestError.policyException.getText(); + } + + public String[] getVariables() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getVariables(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getVariables(); + } + return this.requestErrorWrapper.requestError.policyException.getVariables(); + } + + public String getMessageId() { + if (this.requestErrorWrapper.requestError.okResponseInfo != null) { + return this.requestErrorWrapper.requestError.okResponseInfo.getMessageId(); + } + if (this.requestErrorWrapper.requestError.serviceException != null) { + return this.requestErrorWrapper.requestError.serviceException.getMessageId(); + } + return this.requestErrorWrapper.requestError.policyException.getMessageId(); + } + + public class RequestErrorWrapper { + private RequestError requestError; + + public RequestErrorWrapper() { + this.requestError = new RequestError(); + } + + public RequestErrorWrapper(RequestError requestError) { + this.requestError = requestError; + } + + public RequestError getRequestError() { + return requestError; + } + + public void setRequestError(RequestError requestError) { + this.requestError = requestError; + } + + public void setPolicyException(PolicyException policyException) { + requestError.setPolicyException(policyException); + } + + public void setServiceException(ServiceException serviceException) { + requestError.setServiceException(serviceException); + } + + public void setOkResponseInfo(OkResponseInfo okResponseInfo) { + requestError.setOkResponseInfo(okResponseInfo); + } + } + + public class RequestError { + @SuppressWarnings("unused") + private PolicyException policyException; + @SuppressWarnings("unused") + private ServiceException serviceException; + @SuppressWarnings("unused") + private OkResponseInfo okResponseInfo; + + public RequestError() { + } + + public PolicyException getPolicyException() { + return policyException; + } + + public ServiceException getServiceException() { + return serviceException; + } + + public OkResponseInfo getOkResponseInfo() { + return okResponseInfo; + } + + public void setPolicyException(PolicyException policyException) { + this.policyException = policyException; + } + + public void setServiceException(ServiceException serviceException) { + this.serviceException = serviceException; + } + + public void setOkResponseInfo(OkResponseInfo okResponseInfo) { + this.okResponseInfo = okResponseInfo; + } + } + + @Override + public String toString() { + return "ResponseFormat[" + "status=" + status + ", requestErrorWrapper=" + requestErrorWrapper + ']'; + } + } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java index 4bf3b2ba44..3aae180517 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/ServiceException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,11 +22,11 @@ package org.openecomp.sdc.exception; public class ServiceException extends AbstractSdncException { - public ServiceException(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } + public ServiceException(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } - public ServiceException() { - } + public ServiceException() { + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java index 3262a685fa..96ef2f3159 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/TechnicalException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,16 +24,17 @@ package org.openecomp.sdc.exception; * Base class for all Alien technical exception * * @author mkv + * */ public abstract class TechnicalException extends RuntimeException { - private static final long serialVersionUID = -9152473183025390161L; + private static final long serialVersionUID = -9152473183025390161L; - public TechnicalException(String message, Throwable cause) { - super(message, cause); - } + public TechnicalException(String message, Throwable cause) { + super(message, cause); + } - public TechnicalException(String message) { - super(message); - } + public TechnicalException(String message) { + super(message); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java index ba0457a16c..a998d6393e 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/VersionConflictException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,9 +25,9 @@ package org.openecomp.sdc.exception; * manner for users */ public class VersionConflictException extends TechnicalException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public VersionConflictException(String message, Throwable cause) { - super(message, cause); - } + public VersionConflictException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java index 85417fb611..b2e58f5766 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java @@ -53,17 +53,15 @@ public class Configuration extends BasicConfiguration { private FeMonitoringConfig systemMonitoring; - private String kibanaHost; - - private Integer kibanaPort; - - private String kibanaProtocol; - private String onboardingForwardContext; private OnboardingConfig onboarding; private DcaeConfig dcae; + + private CookieConfig authCookie; + + private CatalogFacadeMsConfig catalogFacadeMs; /** * be http context */ @@ -80,30 +78,15 @@ public class Configuration extends BasicConfiguration { private int requestTimeout; private List<List<String>> identificationHeaderFields; private List<List<String>> optionalHeaderFields; - private List<String> forwardHeaderFields; - - public String getKibanaProtocol() { - return kibanaProtocol; - } - - public void setKibanaProtocol(String kibanaProtocol) { - this.kibanaProtocol = kibanaProtocol; - } - public String getKibanaHost() { - return kibanaHost; - } - - public void setKibanaHost(String kibanaHost) { - this.kibanaHost = kibanaHost; - } + private List<String> forwardHeaderFields; - public Integer getKibanaPort() { - return kibanaPort; + public CatalogFacadeMsConfig getCatalogFacadeMs() { + return catalogFacadeMs; } - public void setKibanaPort(Integer kibanaPort) { - this.kibanaPort = kibanaPort; + public void setCatalogFacadeMs(CatalogFacadeMsConfig catalogFacadeMs) { + this.catalogFacadeMs = catalogFacadeMs; } public FeMonitoringConfig getSystemMonitoring() { @@ -274,6 +257,14 @@ public class Configuration extends BasicConfiguration { this.dcae = dcae; } + public CookieConfig getAuthCookie() { + return authCookie; + } + + public void setAuthCookie(CookieConfig authCookie) { + this.authCookie = authCookie; + } + @Override public String toString() { return new StringBuilder().append(format("backend host: %s%n", beHost)) @@ -288,9 +279,9 @@ public class Configuration extends BasicConfiguration { public static class FeMonitoringConfig { - private Boolean enabled; - private Boolean isProxy; - private Integer probeIntervalInSeconds; + Boolean enabled; + Boolean isProxy; + Integer probeIntervalInSeconds; public Boolean getEnabled() { return enabled; @@ -322,13 +313,13 @@ public class Configuration extends BasicConfiguration { } public static class OnboardingConfig { - private String protocolFe = "http"; - private String hostFe; - private Integer portFe; - private String protocolBe = "http"; - private String hostBe; - private Integer portBe; - private String healthCheckUriFe; + String protocolFe = "http"; + String hostFe; + Integer portFe; + String protocolBe = "http"; + String hostBe; + Integer portBe; + String healthCheckUriFe; public String getProtocolFe() { return protocolFe; @@ -389,10 +380,10 @@ public class Configuration extends BasicConfiguration { public static class DcaeConfig { - private String protocol = "http"; - private String host; - private Integer port; - private String healthCheckUri; + String protocol = "http"; + String host; + Integer port; + String healthCheckUri; public String getProtocol() { return protocol; @@ -427,6 +418,94 @@ public class Configuration extends BasicConfiguration { } } + public static class CookieConfig { + String cookieName = "AuthenticationCookie"; + String path = ""; + String domain = ""; + String securityKey = ""; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getSecurityKey() {return securityKey; + } + + public void setSecurityKey(String securityKey) { + this.securityKey = securityKey; + } + + public String getCookieName() { + return cookieName; + } + + public void setCookieName(String cookieName) { + this.cookieName = cookieName; + } + } + + public static class CatalogFacadeMsConfig { + String protocol; + String host; + Integer port; + String healthCheckUri; + String path; + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public void setHost(String host) { + this.host = host; + } + + public void setPort(Integer port) { + this.port = port; + } + + public void setHealthCheckUri(String healthCheckUri) { + this.healthCheckUri = healthCheckUri; + } + + public void setPath(String path) { + this.path = path; + } + + public String getProtocol() { + return protocol; + } + + public String getHost() { + return host; + } + + public Integer getPort() { + return port; + } + + public String getHealthCheckUri() { + return healthCheckUri; + } + + public String getPath() { + return path; + } + + + } + public List<String> getHealthStatusExclude() { return healthStatusExclude; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java index 5aa2d1f79d..ed7a2e9817 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java @@ -27,28 +27,28 @@ import org.openecomp.sdc.common.api.FileChangeCallback; import org.openecomp.sdc.common.config.EcompErrorConfiguration; import org.openecomp.sdc.common.config.IEcompConfigurationManager; import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import java.util.HashMap; import java.util.Map; public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { - private ConfigurationSource configurationSource = null; - private static ConfigurationManager instance; - private static Logger logger = LoggerFactory.getLogger(ConfigurationManager.class.getName()); + ConfigurationSource configurationSource = null; + private static ConfigurationManager instance; - public ConfigurationManager(ConfigurationSource configurationSource) { - super(); - this.configurationSource = configurationSource; - loadConfigurationFiles(); - instance = this; - } + private static final Logger log = Logger.getLogger(ConfigurationManager.class.getName()); + + public ConfigurationManager(ConfigurationSource configurationSource) { + super(); + this.configurationSource = configurationSource; + loadConfigurationFiles(); + instance = this; + } - private Map<String, Object> configurations = new HashMap<>(); + Map<String, Object> configurations = new HashMap<>(); - private void loadConfigurationFiles() { + private void loadConfigurationFiles() { loadConfigurationClass(Configuration.class); loadConfigurationClass(RestConfigurationInfo.class); @@ -56,54 +56,54 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura loadConfigurationClass(PluginsConfiguration.class); loadConfigurationClass(WorkspaceConfiguration.class); - } + } - private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { - ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); + private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { + ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); - logger.info("created listener for class {}: {}", clazz.getName(), configurationListener); + log.info("created listener for class {}: {}", clazz.getName(), configurationListener); - T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); + T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); - configurations.put(getKey(clazz), object); - } + configurations.put(getKey(clazz), object); + } - private <T> String getKey(Class<T> class1) { + private <T> String getKey(Class<T> class1) { - return class1.getSimpleName(); + return class1.getSimpleName(); - } + } - public Configuration getConfiguration() { + public Configuration getConfiguration() { - return (Configuration) configurations.get(getKey(Configuration.class)); + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public RestConfigurationInfo getRestClientConfiguration() { + public RestConfigurationInfo getRestClientConfiguration() { - return (RestConfigurationInfo) configurations.get(getKey(RestConfigurationInfo.class)); + return (RestConfigurationInfo) configurations.get(getKey(RestConfigurationInfo.class)); - } + } - @Override - public EcompErrorConfiguration getEcompErrorConfiguration() { + @Override + public EcompErrorConfiguration getEcompErrorConfiguration() { - return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); - } + } - public PluginsConfiguration getPluginsConfiguration() { + public PluginsConfiguration getPluginsConfiguration() { - logger.info("requested plugins configuration and got this:{}", configurations.get(getKey(PluginsConfiguration.class))); + log.info("requested plugins configuration and got this:{}", configurations.get(getKey(PluginsConfiguration.class))); - return (PluginsConfiguration) configurations.get(getKey(PluginsConfiguration.class)); - } + return (PluginsConfiguration) configurations.get(getKey(PluginsConfiguration.class)); + } public WorkspaceConfiguration getWorkspaceConfiguration() { - logger.info("requested plugins configuration and got this:{}", configurations.get(getKey(WorkspaceConfiguration.class))); + log.info("requested plugins configuration and got this:{}", configurations.get(getKey(WorkspaceConfiguration.class))); return (WorkspaceConfiguration) configurations.get(getKey(WorkspaceConfiguration.class)); } @@ -111,22 +111,34 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { - if (configurationListener != null) { + if (configurationListener != null) { - configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + configurationSource.addWatchConfiguration(Configuration.class, configurationListener); - } - return (Configuration) configurations.get(getKey(Configuration.class)); + } + return (Configuration) configurations.get(getKey(Configuration.class)); - } + } - public void reconfigure(BasicConfiguration obj) { } + public void reconfigure(BasicConfiguration obj) { + // + // if (obj != null) { + // + // if (obj instanceof Configuration) { + // configurations.put(getKey(Configuration.class), obj); + // } + // + // if (obj instanceof EcompErrorConfiguration) { + // configurations.put(getKey(EcompErrorConfiguration.class), obj); + // } + // } + } - public static ConfigurationManager getConfigurationManager() { - return instance; - } + public static ConfigurationManager getConfigurationManager() { + return instance; + } - public static void setTestInstance(ConfigurationManager configurationManagerInstance) { - instance = configurationManagerInstance; - } + public static void setTestInstance(ConfigurationManager configurationManagerInstance) { + instance = configurationManagerInstance; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java index 7d681bdba6..7208398525 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Connection.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,27 +22,27 @@ package org.openecomp.sdc.fe.config; public class Connection { - private String url; - private int poolSize; + private String url; + private int poolSize; - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public void setUrl(String url) { - this.url = url; - } + public void setUrl(String url) { + this.url = url; + } - public int getPoolSize() { - return poolSize; - } + public int getPoolSize() { + return poolSize; + } - public void setPoolSize(int poolSize) { - this.poolSize = poolSize; - } + public void setPoolSize(int poolSize) { + this.poolSize = poolSize; + } - @Override - public String toString() { - return String.format("'%s' with pool of %d", getUrl(), getPoolSize()); - } + @Override + public String toString() { + return String.format("'%s' with pool of %d", getUrl(), getPoolSize()); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java index 13459713ff..a36293b829 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/FeEcompErrorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,51 +26,51 @@ import org.openecomp.sdc.common.config.IEcompConfigurationManager; public class FeEcompErrorManager extends AbsEcompErrorManager { - private static volatile FeEcompErrorManager instance; - private static ConfigurationManager configurationManager; + private static volatile FeEcompErrorManager instance; + private static ConfigurationManager configurationManager; - private FeEcompErrorManager() { - } + private FeEcompErrorManager() { + }; - public static FeEcompErrorManager getInstance() { - if (instance == null) { + public static FeEcompErrorManager getInstance() { + if (instance == null) { - instance = init(); - } - return instance; - } + instance = init(); + } + return instance; + } - private static synchronized FeEcompErrorManager init() { - if (instance == null) { - instance = new FeEcompErrorManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } + private static synchronized FeEcompErrorManager init() { + if (instance == null) { + instance = new FeEcompErrorManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } - @Override - public IEcompConfigurationManager getConfigurationManager() { - return configurationManager; - } + @Override + public IEcompConfigurationManager getConfigurationManager() { + return configurationManager; + } - public void logFeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); - } + public void logFeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); + } - public void logFeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckError); - } + public void logFeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckError); + } - public void logFeHttpLoggingError(String context) { - processEcompError(context, EcompErrorEnum.FeHttpLoggingError); - } + public void logFeHttpLoggingError(String context) { + processEcompError(context, EcompErrorEnum.FeHttpLoggingError); + } - public void logFePortalServletError(String context) { - processEcompError(context, EcompErrorEnum.FePortalServletError); - } + public void logFePortalServletError(String context) { + processEcompError(context, EcompErrorEnum.FePortalServletError); + } - public void logFeHealthCheckGeneralError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckGeneralError); - } + public void logFeHealthCheckGeneralError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckGeneralError); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java index 449c9eaccc..b891c7f85c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/PluginsConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -134,17 +134,17 @@ public class PluginsConfiguration extends BasicConfiguration { @Override public String toString() { - return "PluginDisplayOptions[" - + "displayName='" + displayName - + ", displayContext=" + displayContext - + ", displayRoles=" + displayRoles - + ']'; + return "PluginDisplayOptions[" + + "displayName='" + displayName + + ", displayContext=" + displayContext + + ", displayRoles=" + displayRoles + + ']'; } } @Override public String toString() { - return "PluginsConfiguration[" + "pluginsList=" + pluginsList + ", connectionTimeout=" + connectionTimeout + ']'; + return "PluginsConfiguration[" + "pluginsList=" + pluginsList + ", connectionTimeout=" + connectionTimeout +']'; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java index 1ac10a2611..78e565e6c3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,8 +35,7 @@ import org.openecomp.sdc.common.monitoring.MonitoringEvent; import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher; import org.openecomp.sdc.fe.config.Configuration; import org.openecomp.sdc.fe.config.ConfigurationManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import javax.servlet.ServletContext; import java.util.concurrent.Executors; @@ -46,65 +45,64 @@ import java.util.concurrent.TimeUnit; public class FeMonitoringService { - private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; - private static final int DEFAULT_TIMEOUT = 3000; - private static Logger monitoringLogger = LoggerFactory.getLogger("asdc.fe.monitoring.service"); - private static Logger log = LoggerFactory.getLogger(FeMonitoringService.class.getName()); - private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; + private static Logger monitoringLogger = Logger.getLogger("asdc.fe.monitoring.service"); + private static Logger log = Logger.getLogger(FeMonitoringService.class.getName()); + private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private class MonitoringScheduledTask implements Runnable { - @Override - public void run() { - monitoringLogger.trace("Executing FE Monitoring Task - Start"); - MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); - processMonitoringEvent(monitoringMetrics); - monitoringLogger.trace("Executing FE Monitoring Task - Status = {}", monitoringMetrics.toString()); - } - } + private class MonitoringScheduledTask implements Runnable { + @Override + public void run() { + monitoringLogger.trace("Executing FE Monitoring Task - Start"); + MonitoringEvent monitoringMetrics = MonitoringMetricsFetcher.getInstance().getMonitoringMetrics(); + processMonitoringEvent(monitoringMetrics); + monitoringLogger.trace("Executing FE Monitoring Task - Status = {}", monitoringMetrics.toString()); + } + } - /** - * This executor will execute the Monitoring task. - */ - private ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "FE-Monitoring-Thread"); - } - }); - private ServletContext context; + /** + * This executor will execute the Monitoring task. + */ + ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "FE-Monitoring-Thread"); + } + }); + private ServletContext context; - public FeMonitoringService(ServletContext context) { - this.context = context; - } + public FeMonitoringService(ServletContext context) { + this.context = context; + } - public void start(int interval) { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - if (config.getSystemMonitoring().getEnabled()) { - log.info("FE monitoring service enabled, interval is {} seconds", interval); - this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); - } else { - log.info("FE monitoring service is disabled"); - } - } + public void start(int interval) { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + if (config.getSystemMonitoring().getEnabled()) { + log.info("FE monitoring service enabled, interval is {} seconds", interval); + this.monitoringExecutor.scheduleAtFixedRate(new MonitoringScheduledTask(), 0, interval, TimeUnit.SECONDS); + } else { + log.info("FE monitoring service is disabled"); + } + } - private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { - try { - Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); - String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), - Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); + private void processMonitoringEvent(MonitoringEvent monitoringMetrics) { + try { + Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) + .getConfiguration(); + String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(), + Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort()); - int timeout = DEFAULT_TIMEOUT; - String monitoringMetricsJson = gson.toJson(monitoringMetrics); - HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); - HttpResponse<String> resposne = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); + int timeout = 3000; + String monitoringMetricsJson = gson.toJson(monitoringMetrics); + HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON); + HttpResponse<String> resposne = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout))); int beResponseStatus = resposne.getStatusCode(); if (beResponseStatus != HttpStatus.SC_OK) { monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus); } - } catch (Exception e) { - monitoringLogger.error("Monitoring BE failed with exception ", e); - } - } + } catch (Exception e) { + monitoringLogger.error("Monitoring BE failed with exception ", e); + } + } } |