diff options
author | vasraz <vasyl.razinkov@est.tech> | 2021-03-27 16:17:27 +0000 |
---|---|---|
committer | Christophe Closset <christophe.closset@intl.att.com> | 2021-03-29 07:13:03 +0000 |
commit | 3ee61018a1140ace7f9cda5839949f9a31182fa6 (patch) | |
tree | 72aa9f37c6922589c001e08c56079d44c9262e07 /common-app-api/src/main/java/org | |
parent | 59f4edc21e410e158a79e1bff842f9623126a453 (diff) |
Reformat common-app-api
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Issue-ID: SDC-3449
Change-Id: Id381fd296f1a06cb9d23175c80bdf322637b14e1
Diffstat (limited to 'common-app-api/src/main/java/org')
128 files changed, 5845 insertions, 6992 deletions
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfigManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfigManager.java index e3327cc696..21638e7ae0 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfigManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfigManager.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import java.util.List; @@ -32,7 +31,6 @@ public class ArtifactConfigManager { public static final ArtifactConfigManager INSTANCE = new ArtifactConfigManager(); private ArtifactConfigManager() { - } public static ArtifactConfigManager getInstance() { @@ -47,26 +45,22 @@ public class ArtifactConfigManager { */ public Optional<ArtifactConfiguration> find(final String type) { final List<ArtifactConfiguration> artifactConfigurationList = getConfiguration(); - return artifactConfigurationList.stream() - .filter(artifactConfiguration -> artifactConfiguration.getType().equals(type)) - .findFirst(); + return artifactConfigurationList.stream().filter(artifactConfiguration -> artifactConfiguration.getType().equals(type)).findFirst(); } /** * Find an artifact configuration by artifact type, that supports the artifact category/group and component type. * - * @param type the artifact type + * @param type the artifact type * @param artifactGroup the artifact category/group * @param componentType the component type * @return the artifact configuration if it matches the provided filter */ - public Optional<ArtifactConfiguration> find(final String type, final ArtifactGroupTypeEnum artifactGroup, - final ComponentType componentType) { + public Optional<ArtifactConfiguration> find(final String type, final ArtifactGroupTypeEnum artifactGroup, final ComponentType componentType) { final ArtifactConfiguration artifactConfiguration = find(type).orElse(null); if (artifactConfiguration == null) { return Optional.empty(); } - final boolean hasCategory = artifactConfiguration.hasSupport(artifactGroup); if (!hasCategory) { return Optional.empty(); @@ -75,7 +69,6 @@ public class ArtifactConfigManager { if (!hasComponentType) { return Optional.empty(); } - return Optional.of(artifactConfiguration); } @@ -86,14 +79,11 @@ public class ArtifactConfigManager { * @param componentType the component type * @return the artifact configurations that matches the filter */ - public List<ArtifactConfiguration> findAll(final ArtifactGroupTypeEnum artifactGroup, - final ComponentType componentType) { - final List<ArtifactConfiguration> artifactConfigurationList = - ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts(); - + public List<ArtifactConfiguration> findAll(final ArtifactGroupTypeEnum artifactGroup, final ComponentType componentType) { + final List<ArtifactConfiguration> artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration() + .getArtifacts(); return artifactConfigurationList.stream() - .filter(artifactConfiguration1 -> - artifactConfiguration1.hasSupport(artifactGroup) && artifactConfiguration1.hasSupport(componentType)) + .filter(artifactConfiguration1 -> artifactConfiguration1.hasSupport(artifactGroup) && artifactConfiguration1.hasSupport(componentType)) .collect(Collectors.toList()); } @@ -104,11 +94,9 @@ public class ArtifactConfigManager { * @return the artifact configurations that matches the filter */ public List<ArtifactConfiguration> findAll(final ArtifactGroupTypeEnum artifactGroup) { - final List<ArtifactConfiguration> artifactConfigurationList = - ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts(); - - return artifactConfigurationList.stream() - .filter(artifactConfiguration1 -> artifactConfiguration1.hasSupport(artifactGroup)) + final List<ArtifactConfiguration> artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration() + .getArtifacts(); + return artifactConfigurationList.stream().filter(artifactConfiguration1 -> artifactConfiguration1.hasSupport(artifactGroup)) .collect(Collectors.toList()); } @@ -119,11 +107,9 @@ public class ArtifactConfigManager { * @return the artifact configurations that matches the filter */ public List<ArtifactConfiguration> findAll(final ComponentType componentType) { - final List<ArtifactConfiguration> artifactConfigurationList = - ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts(); - - return artifactConfigurationList.stream() - .filter(artifactConfiguration1 -> artifactConfiguration1.hasSupport(componentType)) + final List<ArtifactConfiguration> artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration() + .getArtifacts(); + return artifactConfigurationList.stream().filter(artifactConfiguration1 -> artifactConfiguration1.hasSupport(componentType)) .collect(Collectors.toList()); } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfiguration.java index 1656b4abb1..f5f3673a5b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ArtifactConfiguration.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import java.util.List; 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 75da11155b..8883745416 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import org.openecomp.sdc.common.config.AbsEcompErrorManager; @@ -26,412 +25,387 @@ 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 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; - } - } - - } + 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; + } + } + } + + public enum ComponentName {SERVICE, PRODUCT, VF} + + public enum ErrorSeverity {INFO, WARNING, ERROR, FATAL} } 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 index b82983e0bc..63d1c81cb7 100644 --- 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 @@ -13,7 +13,6 @@ public class CadiFilterParams { 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; 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 6411005449..2dfbcc4106 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. @@ -17,30 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import java.util.List; public class CleanComponentsConfiguration { - private long cleanIntervalInMinutes; - private List<String> componentsToClean; - - public long getCleanIntervalInMinutes() { - return cleanIntervalInMinutes; - } + private long cleanIntervalInMinutes; + private List<String> componentsToClean; - public void setCleanIntervalInMinutes(long cleanIntervalInMinutes) { - this.cleanIntervalInMinutes = cleanIntervalInMinutes; - } + public long getCleanIntervalInMinutes() { + return cleanIntervalInMinutes; + } - public List<String> getComponentsToClean() { - return componentsToClean; - } + public void setCleanIntervalInMinutes(long cleanIntervalInMinutes) { + this.cleanIntervalInMinutes = cleanIntervalInMinutes; + } - public void setComponentsToClean(List<String> componentsToClean) { - this.componentsToClean = componentsToClean; - } + public List<String> getComponentsToClean() { + return componentsToClean; + } + public void setComponentsToClean(List<String> componentsToClean) { + this.componentsToClean = componentsToClean; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ComponentType.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ComponentType.java index 2f28687620..b3572d20ef 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ComponentType.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ComponentType.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import lombok.AllArgsConstructor; @@ -25,12 +24,6 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum ComponentType { - - RESOURCE("Resource"), - SERVICE("Service"), - RESOURCE_INSTANCE("Resource Instance"), - SERVICE_INSTANCE("Service Instance"); - + RESOURCE("Resource"), SERVICE("Service"), RESOURCE_INSTANCE("Resource Instance"), SERVICE_INSTANCE("Service Instance"); private final String value; - } 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 b670bbd959..e30f5f32fc 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import static java.lang.String.format; @@ -46,7 +45,6 @@ public class Configuration extends BasicConfiguration { * Requests from these Urls will not be logged by org.openecomp.sdc.be.filters.BeServletFilter.<br> **/ private List<String> unLoggedUrls; - /** * backend host */ @@ -67,7 +65,6 @@ public class Configuration extends BasicConfiguration { * backend protocol. http | https */ private String beProtocol = "http"; - private Date released; private String version = "1111"; private String toscaConformanceLevel = "3.0"; @@ -86,13 +83,11 @@ public class Configuration extends BasicConfiguration { private Long uebHealthCheckReconnectIntervalInSeconds; private Long uebHealthCheckReadTimeout; private List<Map<String, Map<String, String>>> defaultImports; - private List<String> globalCsarImports; private List<String> resourceTypes; private List<String> excludeResourceCategory; private List<String> excludeResourceType; private Map<String, Set<String>> excludedPolicyTypesMapping; - private Map<String, Set<String>> excludedGroupTypesMapping; private Map<String, Object> deploymentResourceArtifacts; private Map<String, Object> deploymentResourceInstanceArtifacts; @@ -101,54 +96,34 @@ public class Configuration extends BasicConfiguration { private Map<String, Object> informationalServiceArtifacts; private Map<String, Object> serviceApiArtifacts; private List<String> excludeServiceCategory; - private List<String> licenseTypes; private List<String> definedResourceNamespace; private List<String> directives; - private Integer additionalInformationMaxNumberOfKeys; private HeatDeploymentArtifactTimeout heatArtifactDeploymentTimeout; - private BeMonitoringConfig systemMonitoring; private CleanComponentsConfiguration cleanComponentsConfiguration; - private String artifactsIndex; - private String heatEnvArtifactHeader; private String heatEnvArtifactFooter; - private String toscaFilesDir; private String heatTranslatorPath; - private OnboardingConfig onboarding; - private BasicAuthConfig basicAuth; - private CassandrConfig cassandraConfig; - private SwitchoverDetectorConfig switchoverDetector; - private ApplicationL1CacheConfig applicationL1Cache; - private ApplicationL2CacheConfig applicationL2Cache; - private ToscaValidatorsConfig toscaValidators; - private boolean disableAudit; - private Boolean consumerBusinessLogic; - private Map<String, VfModuleProperty> vfModuleProperties; - private Map<String, String> genericAssetNodeTypes; private Map<String, String> serviceNodeTypes; private Map<String, Map<String, String>> resourceNodeTypes; - private String appVersion; private String artifactGeneratorConfig; - private CadiFilterParams cadiFilterParams; - private Boolean aafAuthNeeded = false; private String autoHealingOwner; private boolean enableAutoHealing; @@ -193,29 +168,24 @@ public class Configuration extends BasicConfiguration { @Override public String toString() { - return new StringBuilder().append(format("backend host: %s%n", beFqdn)) - .append(format("backend http port: %s%n", beHttpPort)) + return new StringBuilder().append(format("backend host: %s%n", beFqdn)).append(format("backend http port: %s%n", beHttpPort)) .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext)) - .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("JanusGraph Cfg File: %s%n", janusGraphCfgFile)) - .append(format("JanusGraph In memory: %s%n", janusGraphInMemoryGraph)) + .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("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("excludeResourceCategory: %s%n", excludeResourceCategory)) .append(format("informationalResourceArtifacts: %s%n", informationalResourceArtifacts)) .append(format("deploymentResourceArtifacts: %s%n", deploymentResourceArtifacts)) .append(format("informationalServiceArtifacts: %s%n", informationalServiceArtifacts)) - .append(format("Supported artifacts types: %s%n", artifacts)) - .append(format("Supported license types: %s%n", licenseTypes)) + .append(format("Supported artifacts types: %s%n", artifacts)).append(format("Supported license types: %s%n", licenseTypes)) .append(format("Additional information Maximum number of preoperties: %s%n", additionalInformationMaxNumberOfKeys)) .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)).toString(); + .append(format("heat env artifact footer: %s%n", heatEnvArtifactFooter)).append(format("onboarding: %s%n", onboarding)).toString(); } public List<String> getGlobalCsarImports() { @@ -248,7 +218,6 @@ public class Configuration extends BasicConfiguration { public void setIsHttpOnly(final boolean isHttpOnly) { this.isHttpOnly = isHttpOnly; } - } @Getter @@ -284,7 +253,6 @@ public class Configuration extends BasicConfiguration { private String name; private String replicationStrategy; private List<String> replicationInfo; - } } @@ -330,7 +298,6 @@ public class Configuration extends BasicConfiguration { String changePriorityUrl; String changePriorityBody; - } } @@ -343,7 +310,6 @@ public class Configuration extends BasicConfiguration { private Integer defaultMinutes; private Integer minMinutes; private Integer maxMinutes; - } @Getter @@ -358,7 +324,6 @@ public class Configuration extends BasicConfiguration { public Integer getProbeIntervalInSeconds(int defaultVal) { return probeIntervalInSeconds == null ? defaultVal : probeIntervalInSeconds; } - } @Getter @@ -368,7 +333,6 @@ public class Configuration extends BasicConfiguration { private List<String> acceptedTypes; private List<String> validForResourceTypes; - } @Getter @@ -383,7 +347,6 @@ public class Configuration extends BasicConfiguration { private String downloadCsarUri; @ToString.Exclude private String healthCheckUri; - } @Getter @@ -395,7 +358,6 @@ public class Configuration extends BasicConfiguration { private String userName; private String userPass; private String excludedUrls; - } @Getter @@ -412,7 +374,6 @@ public class Configuration extends BasicConfiguration { private String defaultFunctionalMenu; private Integer pollingInterval; private Integer timeoutMs; - } @Getter @@ -422,7 +383,6 @@ public class Configuration extends BasicConfiguration { public static class ApplicationL1CacheConfig { private ApplicationL1CacheInfo datatypes; - } @Getter @@ -435,7 +395,6 @@ public class Configuration extends BasicConfiguration { private ApplicationL1CacheCatalogInfo catalogL1Cache; @ToString.Exclude private QueueInfo queue; - } @Getter @@ -445,7 +404,6 @@ public class Configuration extends BasicConfiguration { public static class ToscaValidatorsConfig { private Integer stringMaxLength; - } @Getter @@ -457,7 +415,6 @@ public class Configuration extends BasicConfiguration { private Boolean enabled; private Integer firstRunDelay; private Integer pollIntervalInSec; - } @Getter @@ -470,7 +427,6 @@ public class Configuration extends BasicConfiguration { private Integer resourcesSizeInCache; private Integer servicesSizeInCache; private Integer productsSizeInCache; - } @Getter @@ -482,7 +438,6 @@ public class Configuration extends BasicConfiguration { private Integer waitOnShutDownInMinutes; private Integer syncIntervalInSecondes; private Integer numberOfCacheWorkers; - } @Getter @@ -492,7 +447,6 @@ public class Configuration extends BasicConfiguration { private String defaultValue; private List<String> validValues; - } @Getter @@ -502,7 +456,6 @@ public class Configuration extends BasicConfiguration { private String forBaseModule; private String forNonBaseModule; - } @Getter @@ -513,7 +466,6 @@ public class Configuration extends BasicConfiguration { private String friendlyName; private String path; private Boolean searchable; - } @Getter @@ -523,7 +475,5 @@ public class Configuration extends BasicConfiguration { private String artifactType; private List<PathsAndNamesDefinition> 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 66494ed668..7241decd62 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. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; import com.google.common.annotations.VisibleForTesting; +import java.util.HashMap; +import java.util.Map; import org.openecomp.sdc.be.config.validation.ArtifactConfigValidator; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.BasicConfiguration; @@ -30,15 +31,11 @@ import org.openecomp.sdc.common.api.FileChangeCallback; import org.openecomp.sdc.common.config.EcompErrorConfiguration; import org.openecomp.sdc.common.config.IEcompConfigurationManager; -import java.util.HashMap; -import java.util.Map; - public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { - - ConfigurationSource configurationSource = null; - private static ConfigurationManager instance; - final Map<String, Object> configurations = new HashMap<>(); + private static ConfigurationManager instance; + final Map<String, Object> configurations = new HashMap<>(); + ConfigurationSource configurationSource = null; @VisibleForTesting public ConfigurationManager() { @@ -46,115 +43,93 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura instance = this; } - public ConfigurationManager(ConfigurationSource configurationSource) { - super(); - this.configurationSource = configurationSource; - loadConfigurationFiles(); - validateConfiguration(); - instance = this; - } - - private void loadConfigurationFiles() { - loadConfigurationClass(Configuration.class); - loadConfigurationClass(ErrorConfiguration.class); - loadConfigurationClass(Neo4jErrorsConfiguration.class); - loadConfigurationClass(EcompErrorConfiguration.class); - loadConfigurationClass(DistributionEngineConfiguration.class); - } - - private void validateConfiguration() { - final Object configurationObj = configurations.get(getKey(Configuration.class)); - if (configurationObj instanceof Configuration) { - final ArtifactConfigValidator artifactConfigValidator = - new ArtifactConfigValidator((Configuration) configurationObj, ArtifactTypeEnum.getBaseArtifacts()); - artifactConfigValidator.validate(); - } - } - - private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { - ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); - - T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); - - configurations.put(getKey(clazz), object); - } - - private <T> String getKey(Class<T> class1) { - - return class1.getSimpleName(); - - } - - public Configuration getConfiguration() { - - return (Configuration) configurations.get(getKey(Configuration.class)); - - } - - public void setConfiguration(Configuration configuration) { - - configurations.put(getKey(Configuration.class), configuration); - - } - - public void setErrorConfiguration(ErrorConfiguration configuration) { - - configurations.put(getKey(ErrorConfiguration.class), configuration); - - } + public ConfigurationManager(ConfigurationSource configurationSource) { + super(); + this.configurationSource = configurationSource; + loadConfigurationFiles(); + validateConfiguration(); + instance = this; + } - public ErrorConfiguration getErrorConfiguration() { + public static ConfigurationManager getConfigurationManager() { + return instance; + } - return (ErrorConfiguration) configurations.get(getKey(ErrorConfiguration.class)); + private void loadConfigurationFiles() { + loadConfigurationClass(Configuration.class); + loadConfigurationClass(ErrorConfiguration.class); + loadConfigurationClass(Neo4jErrorsConfiguration.class); + loadConfigurationClass(EcompErrorConfiguration.class); + loadConfigurationClass(DistributionEngineConfiguration.class); + } - } + private void validateConfiguration() { + final Object configurationObj = configurations.get(getKey(Configuration.class)); + if (configurationObj instanceof Configuration) { + final ArtifactConfigValidator artifactConfigValidator = new ArtifactConfigValidator((Configuration) configurationObj, + ArtifactTypeEnum.getBaseArtifacts()); + artifactConfigValidator.validate(); + } + } - public Neo4jErrorsConfiguration getNeo4jErrorsConfiguration() { - return (Neo4jErrorsConfiguration) configurations.get(getKey(Neo4jErrorsConfiguration.class)); - } + private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { + ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); + T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); + configurations.put(getKey(clazz), object); + } - @Override - public EcompErrorConfiguration getEcompErrorConfiguration() { + private <T> String getKey(Class<T> class1) { + return class1.getSimpleName(); + } - return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + public Configuration getConfiguration() { + return (Configuration) configurations.get(getKey(Configuration.class)); + } - } + public void setConfiguration(Configuration configuration) { + configurations.put(getKey(Configuration.class), configuration); + } - public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { + public ErrorConfiguration getErrorConfiguration() { + return (ErrorConfiguration) configurations.get(getKey(ErrorConfiguration.class)); + } - if (configurationListener != null) { + public void setErrorConfiguration(ErrorConfiguration configuration) { + configurations.put(getKey(ErrorConfiguration.class), configuration); + } - configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + public Neo4jErrorsConfiguration getNeo4jErrorsConfiguration() { + return (Neo4jErrorsConfiguration) configurations.get(getKey(Neo4jErrorsConfiguration.class)); + } - } - return (Configuration) configurations.get(getKey(Configuration.class)); + @Override + public EcompErrorConfiguration getEcompErrorConfiguration() { + return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + } - } + /** + * FOR TEST ONLY + * + * @param ecompErrorConfiguration + */ + public void setEcompErrorConfiguration(EcompErrorConfiguration ecompErrorConfiguration) { + configurations.put(getKey(EcompErrorConfiguration.class), ecompErrorConfiguration); + } - public static ConfigurationManager getConfigurationManager() { - return instance; - } + public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { + if (configurationListener != null) { + configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + } + return (Configuration) configurations.get(getKey(Configuration.class)); + } public void reconfigure(final BasicConfiguration basicConfiguration) { - if (basicConfiguration instanceof Configuration) { - configurations.put(getKey(Configuration.class), basicConfiguration); - } - } - - /** - * FOR TEST ONLY - * - * @param ecompErrorConfiguration - */ - public void setEcompErrorConfiguration(EcompErrorConfiguration ecompErrorConfiguration) { - - configurations.put(getKey(EcompErrorConfiguration.class), ecompErrorConfiguration); - - } - - public DistributionEngineConfiguration getDistributionEngineConfiguration() { - - return (DistributionEngineConfiguration) configurations.get(getKey(DistributionEngineConfiguration.class)); + if (basicConfiguration instanceof Configuration) { + configurations.put(getKey(Configuration.class), basicConfiguration); + } + } - } + public DistributionEngineConfiguration getDistributionEngineConfiguration() { + 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 b23e076334..834d7cb579 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. @@ -17,469 +17,437 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.openecomp.sdc.common.api.BasicConfiguration; import org.openecomp.sdc.common.http.config.ExternalServiceConfig; -import java.util.*; - public class DistributionEngineConfiguration extends BasicConfiguration { - private List<String> uebServers; - - private String distributionNotifTopicName; - - private String distributionStatusTopicName; - - private Integer initRetryIntervalSec; - - private Integer initMaxIntervalSec; - - private ComponentArtifactTypesConfig distribNotifServiceArtifactTypes; - - private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; - - private String uebPublicKey; - - private String uebSecretKey; - - private List<String> environments; - - private DistributionStatusTopicConfig distributionStatusTopic; - - private CreateTopicConfig createTopic; - - private boolean startDistributionEngine; - - private DistributionNotificationTopicConfig distributionNotificationTopic; - - private Integer defaultArtifactInstallationTimeout = 60; - - private Integer currentArtifactInstallationTimeout = 120; - private boolean useHttpsWithDmaap; - - private ExternalServiceConfig aaiConfig; - - private ExternalServiceConfig msoConfig; - - private Integer opEnvRecoveryIntervalSec; - - private Integer allowedTimeBeforeStaleSec; - - public static class DistribNotifServiceArtifacts { - - Map<String, Object> service; - Map<String, Object> resource; - - - - public Map<String, Object> getService() { - return service; - } - - public void setService(Map<String, Object> service) { - this.service = service; - } - - public Map<String, Object> getResource() { - return resource; - } - - public void setResource(Map<String, Object> resource) { - this.resource = resource; - } - - } - - public static class NotifArtifactTypes { - - List<String> info; - List<String> lifecycle; - - public List<String> getInfo() { - return info; - } - - public void setInfo(List<String> info) { - this.info = info; - } - - public List<String> getLifecycle() { - return lifecycle; - } + private List<String> uebServers; + private String distributionNotifTopicName; + private String distributionStatusTopicName; + private Integer initRetryIntervalSec; + private Integer initMaxIntervalSec; + private ComponentArtifactTypesConfig distribNotifServiceArtifactTypes; + private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes; + private String uebPublicKey; + private String uebSecretKey; + private List<String> environments; + private DistributionStatusTopicConfig distributionStatusTopic; + private CreateTopicConfig createTopic; + private boolean startDistributionEngine; + private DistributionNotificationTopicConfig distributionNotificationTopic; + private Integer defaultArtifactInstallationTimeout = 60; + private Integer currentArtifactInstallationTimeout = 120; + private boolean useHttpsWithDmaap; + private ExternalServiceConfig aaiConfig; + private ExternalServiceConfig msoConfig; + private Integer opEnvRecoveryIntervalSec; + private Integer allowedTimeBeforeStaleSec; + + public List<String> getUebServers() { + return uebServers; + } - public void setLifecycle(List<String> lifecycle) { - this.lifecycle = lifecycle; - } + public void setUebServers(List<String> uebServers) { + this.uebServers = uebServers; + } - } + public String getDistributionNotifTopicName() { + return distributionNotifTopicName; + } - public static class NotifArtifactTypesResource { + public void setDistributionNotifTopicName(String distributionNotifTopicName) { + this.distributionNotifTopicName = distributionNotifTopicName; + } - List<ArtifcatTypeEnum> lifecycle; + public String getDistributionStatusTopicName() { + return distributionStatusTopicName; + } - } + public void setDistributionStatusTopicName(String distributionStatusTopicName) { + this.distributionStatusTopicName = distributionStatusTopicName; + } - public enum ArtifcatTypeEnum { + public Integer getInitRetryIntervalSec() { + return initRetryIntervalSec; + } - MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); + public void setInitRetryIntervalSec(Integer initRetryIntervalSec) { + this.initRetryIntervalSec = initRetryIntervalSec; + } - String value; + public ComponentArtifactTypesConfig getDistribNotifServiceArtifactTypes() { + return distribNotifServiceArtifactTypes; + } - private ArtifcatTypeEnum(String value) { - this.value = value; - } + public void setDistribNotifServiceArtifactTypes(ComponentArtifactTypesConfig distribNotifServiceArtifactTypes) { + this.distribNotifServiceArtifactTypes = distribNotifServiceArtifactTypes; + } - public String getValue() { + public ComponentArtifactTypesConfig getDistribNotifResourceArtifactTypes() { + return distribNotifResourceArtifactTypes; + } - return value; - } - } + public void setDistribNotifResourceArtifactTypes(ComponentArtifactTypesConfig distribNotifResourceArtifactTypes) { + this.distribNotifResourceArtifactTypes = distribNotifResourceArtifactTypes; + } - public List<String> getUebServers() { - return uebServers; - } + public String getUebPublicKey() { + return uebPublicKey; + } - public void setUebServers(List<String> uebServers) { - this.uebServers = uebServers; - } + public void setUebPublicKey(String uebPublicKey) { + this.uebPublicKey = uebPublicKey; + } - public String getDistributionNotifTopicName() { - return distributionNotifTopicName; - } + public String getUebSecretKey() { + return uebSecretKey; + } - public void setDistributionNotifTopicName(String distributionNotifTopicName) { - this.distributionNotifTopicName = distributionNotifTopicName; - } + public void setUebSecretKey(String uebSecretKey) { + this.uebSecretKey = uebSecretKey; + } - public String getDistributionStatusTopicName() { - return distributionStatusTopicName; - } + public List<String> getEnvironments() { + return environments; + } - public void setDistributionStatusTopicName(String distributionStatusTopicName) { - this.distributionStatusTopicName = distributionStatusTopicName; - } + public void setEnvironments(List<String> environments) { + Set<String> set = new HashSet<>(); + if (environments != null) { + set.addAll(environments); + this.environments = new ArrayList<>(set); + } else { + this.environments = null; + } + } - public Integer getInitRetryIntervalSec() { - return initRetryIntervalSec; - } + public DistributionStatusTopicConfig getDistributionStatusTopic() { + return distributionStatusTopic; + } - public void setInitRetryIntervalSec(Integer initRetryIntervalSec) { - this.initRetryIntervalSec = initRetryIntervalSec; - } + public void setDistributionStatusTopic(DistributionStatusTopicConfig distributionStatusTopic) { + this.distributionStatusTopic = distributionStatusTopic; + } - public ComponentArtifactTypesConfig getDistribNotifServiceArtifactTypes() { - return distribNotifServiceArtifactTypes; - } + public Integer getInitMaxIntervalSec() { + return initMaxIntervalSec; + } - public void setDistribNotifServiceArtifactTypes(ComponentArtifactTypesConfig distribNotifServiceArtifactTypes) { - this.distribNotifServiceArtifactTypes = distribNotifServiceArtifactTypes; - } + public void setInitMaxIntervalSec(Integer initMaxIntervalSec) { + this.initMaxIntervalSec = initMaxIntervalSec; + } - public ComponentArtifactTypesConfig getDistribNotifResourceArtifactTypes() { - return distribNotifResourceArtifactTypes; - } + public CreateTopicConfig getCreateTopic() { + return createTopic; + } - public void setDistribNotifResourceArtifactTypes(ComponentArtifactTypesConfig distribNotifResourceArtifactTypes) { - this.distribNotifResourceArtifactTypes = distribNotifResourceArtifactTypes; - } + public void setCreateTopic(CreateTopicConfig createTopic) { + this.createTopic = createTopic; + } - public String getUebPublicKey() { - return uebPublicKey; - } + public boolean isStartDistributionEngine() { + return startDistributionEngine; + } - public void setUebPublicKey(String uebPublicKey) { - this.uebPublicKey = uebPublicKey; - } + public void setStartDistributionEngine(boolean startDistributionEngine) { + this.startDistributionEngine = startDistributionEngine; + } - public String getUebSecretKey() { - return uebSecretKey; - } + public DistributionNotificationTopicConfig getDistributionNotificationTopic() { + return distributionNotificationTopic; + } - public void setUebSecretKey(String uebSecretKey) { - this.uebSecretKey = uebSecretKey; - } + public void setDistributionNotificationTopic(DistributionNotificationTopicConfig distributionNotificationTopic) { + this.distributionNotificationTopic = distributionNotificationTopic; + } - public List<String> getEnvironments() { - return environments; - } + public int getDefaultArtifactInstallationTimeout() { + return defaultArtifactInstallationTimeout; + } - public void setEnvironments(List<String> environments) { + public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) { + this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout; + } - Set<String> set = new HashSet<>(); - if (environments != null) { - set.addAll(environments); - this.environments = new ArrayList<>(set); - } else { - this.environments = null; - } + public int getCurrentArtifactInstallationTimeout() { + return currentArtifactInstallationTimeout; + } - } + public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) { + this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout; + } - public DistributionStatusTopicConfig getDistributionStatusTopic() { - return distributionStatusTopic; - } + public boolean isUseHttpsWithDmaap() { + return useHttpsWithDmaap; + } - public void setDistributionStatusTopic(DistributionStatusTopicConfig distributionStatusTopic) { - this.distributionStatusTopic = distributionStatusTopic; - } + public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { + this.useHttpsWithDmaap = useHttpsWithDmaap; + } - public Integer getInitMaxIntervalSec() { - return initMaxIntervalSec; - } + public Integer getOpEnvRecoveryIntervalSec() { + return opEnvRecoveryIntervalSec; + } - public void setInitMaxIntervalSec(Integer initMaxIntervalSec) { - this.initMaxIntervalSec = initMaxIntervalSec; - } + public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { + this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; + } - public CreateTopicConfig getCreateTopic() { - return createTopic; - } + public Integer getAllowedTimeBeforeStaleSec() { + return allowedTimeBeforeStaleSec; + } - public void setCreateTopic(CreateTopicConfig createTopic) { - this.createTopic = createTopic; - } + public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { + this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; + } - public boolean isStartDistributionEngine() { - return startDistributionEngine; - } + public ExternalServiceConfig getAaiConfig() { + return aaiConfig; + } - public void setStartDistributionEngine(boolean startDistributionEngine) { - this.startDistributionEngine = startDistributionEngine; - } + public void setAaiConfig(ExternalServiceConfig aaiConfig) { + this.aaiConfig = aaiConfig; + } + public ExternalServiceConfig getMsoConfig() { + return msoConfig; + } + public void setMsoConfig(ExternalServiceConfig msoConfig) { + this.msoConfig = msoConfig; + } - public DistributionNotificationTopicConfig getDistributionNotificationTopic() { - return distributionNotificationTopic; - } + public enum ArtifcatTypeEnum { + MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML"); + String value; - public void setDistributionNotificationTopic(DistributionNotificationTopicConfig distributionNotificationTopic) { - this.distributionNotificationTopic = distributionNotificationTopic; - } + private ArtifcatTypeEnum(String value) { + this.value = value; + } - 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 String getValue() { + return value; + } + } - public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) { - this.useHttpsWithDmaap = useHttpsWithDmaap; - } + public static class DistribNotifServiceArtifacts { - public static class CreateTopicConfig { + Map<String, Object> service; + Map<String, Object> resource; - private Integer partitionCount; - private Integer replicationCount; + public Map<String, Object> getService() { + return service; + } - public Integer getPartitionCount() { - return partitionCount; - } + public void setService(Map<String, Object> service) { + this.service = service; + } - public void setPartitionCount(Integer partitionCount) { - this.partitionCount = partitionCount; - } + public Map<String, Object> getResource() { + return resource; + } - public Integer getReplicationCount() { - return replicationCount; - } + public void setResource(Map<String, Object> resource) { + this.resource = resource; + } + } - public void setReplicationCount(Integer replicationCount) { - this.replicationCount = replicationCount; - } + public static class NotifArtifactTypes { - @Override - public String toString() { - return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount - + "]"; - } + List<String> info; + List<String> lifecycle; - } + public List<String> getInfo() { + return info; + } - public static class EnvironmentConfig { + public void setInfo(List<String> info) { + this.info = info; + } - private String name; - private List<String> uebServers; + public List<String> getLifecycle() { + return lifecycle; + } - public String getName() { - return name; - } + public void setLifecycle(List<String> lifecycle) { + this.lifecycle = lifecycle; + } + } - public void setName(String name) { - this.name = name; - } + public static class NotifArtifactTypesResource { - public List<String> getUebServers() { - return uebServers; - } + List<ArtifcatTypeEnum> lifecycle; + } - public void setUebServers(List<String> uebServers) { - this.uebServers = uebServers; - } + public static class CreateTopicConfig { - @Override - public String toString() { - return "EnvironmentConfig [name=" + name + ", uebServers=" + uebServers + "]"; - } + private Integer partitionCount; + private Integer replicationCount; - } + public Integer getPartitionCount() { + return partitionCount; + } - public static class DistributionStatusTopicConfig { + public void setPartitionCount(Integer partitionCount) { + this.partitionCount = partitionCount; + } - private Integer pollingIntervalSec; - private Integer fetchTimeSec; - private String consumerGroup; - private String consumerId; + public Integer getReplicationCount() { + return replicationCount; + } - public Integer getPollingIntervalSec() { - return pollingIntervalSec; - } + public void setReplicationCount(Integer replicationCount) { + this.replicationCount = replicationCount; + } - public void setPollingIntervalSec(Integer pollingIntervalSec) { - this.pollingIntervalSec = pollingIntervalSec; - } + @Override + public String toString() { + return "CreateTopicConfig [partitionCount=" + partitionCount + ", replicationCount=" + replicationCount + "]"; + } + } - public Integer getFetchTimeSec() { - return fetchTimeSec; - } + public static class EnvironmentConfig { - public void setFetchTimeSec(Integer fetchTimeSec) { - this.fetchTimeSec = fetchTimeSec; - } + private String name; + private List<String> uebServers; - public String getConsumerGroup() { - return consumerGroup; - } + public String getName() { + return name; + } - public void setConsumerGroup(String consumerGroup) { - this.consumerGroup = consumerGroup; - } + public void setName(String name) { + this.name = name; + } - public String getConsumerId() { - return consumerId; - } + public List<String> getUebServers() { + return uebServers; + } - public void setConsumerId(String consumerId) { - this.consumerId = consumerId; - } + public void setUebServers(List<String> uebServers) { + this.uebServers = uebServers; + } - @Override - public String toString() { - return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" - + fetchTimeSec + ", consumerGroup=" + consumerGroup + ", consumerId=" + consumerId + "]"; - } + @Override + public String toString() { + return "EnvironmentConfig [name=" + name + ", uebServers=" + uebServers + "]"; + } + } - } + public static class DistributionStatusTopicConfig { - public static class DistributionNotificationTopicConfig { + private Integer pollingIntervalSec; + private Integer fetchTimeSec; + private String consumerGroup; + private String consumerId; - private Integer maxWaitingAfterSendingSeconds; - private Integer maxThreadPoolSize; - private Integer minThreadPoolSize; + public Integer getPollingIntervalSec() { + return pollingIntervalSec; + } - public Integer getMaxWaitingAfterSendingSeconds() { - return maxWaitingAfterSendingSeconds; - } + public void setPollingIntervalSec(Integer pollingIntervalSec) { + this.pollingIntervalSec = pollingIntervalSec; + } - public void setMaxWaitingAfterSendingSeconds(Integer maxWaitingAfterSendingSeconds) { - this.maxWaitingAfterSendingSeconds = maxWaitingAfterSendingSeconds; - } + public Integer getFetchTimeSec() { + return fetchTimeSec; + } - public Integer getMaxThreadPoolSize() { - return maxThreadPoolSize; - } + public void setFetchTimeSec(Integer fetchTimeSec) { + this.fetchTimeSec = fetchTimeSec; + } - public void setMaxThreadPoolSize(Integer maxThreadPoolSize) { - this.maxThreadPoolSize = maxThreadPoolSize; - } + public String getConsumerGroup() { + return consumerGroup; + } - public Integer getMinThreadPoolSize() { - return minThreadPoolSize; - } + public void setConsumerGroup(String consumerGroup) { + this.consumerGroup = consumerGroup; + } - public void setMinThreadPoolSize(Integer minThreadPoolSize) { - this.minThreadPoolSize = minThreadPoolSize; - } + public String getConsumerId() { + return consumerId; + } - @Override - public String toString() { - return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds - + ", maxThreadPoolSize=" + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]"; - } + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } - } + @Override + public String toString() { + return "DistributionStatusTopicConfig [pollingIntervalSec=" + pollingIntervalSec + ", fetchTimeSec=" + fetchTimeSec + ", consumerGroup=" + + consumerGroup + ", consumerId=" + consumerId + "]"; + } + } - public static class ComponentArtifactTypesConfig { + public static class DistributionNotificationTopicConfig { - private List<String> info; - private List<String> lifecycle; + private Integer maxWaitingAfterSendingSeconds; + private Integer maxThreadPoolSize; + private Integer minThreadPoolSize; - public List<String> getInfo() { - return info; - } + public Integer getMaxWaitingAfterSendingSeconds() { + return maxWaitingAfterSendingSeconds; + } - public void setInfo(List<String> info) { - this.info = info; - } + public void setMaxWaitingAfterSendingSeconds(Integer maxWaitingAfterSendingSeconds) { + this.maxWaitingAfterSendingSeconds = maxWaitingAfterSendingSeconds; + } - public List<String> getLifecycle() { - return lifecycle; - } + public Integer getMaxThreadPoolSize() { + return maxThreadPoolSize; + } - public void setLifecycle(List<String> lifecycle) { - this.lifecycle = lifecycle; - } + public void setMaxThreadPoolSize(Integer maxThreadPoolSize) { + this.maxThreadPoolSize = maxThreadPoolSize; + } - @Override - public String toString() { - return "ArtifactTypesConfig [info=" + info + ", lifecycle=" + lifecycle + "]"; - } + public Integer getMinThreadPoolSize() { + return minThreadPoolSize; + } - } + public void setMinThreadPoolSize(Integer minThreadPoolSize) { + this.minThreadPoolSize = minThreadPoolSize; + } - public Integer getOpEnvRecoveryIntervalSec() { - return opEnvRecoveryIntervalSec; - } + @Override + public String toString() { + return "DistributionNotificationTopicConfig [maxWaitingAfterSendingSeconds=" + maxWaitingAfterSendingSeconds + ", maxThreadPoolSize=" + + maxThreadPoolSize + ", minThreadPoolSize=" + minThreadPoolSize + "]"; + } + } - public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) { - this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec; - } + public static class ComponentArtifactTypesConfig { - public Integer getAllowedTimeBeforeStaleSec() { - return allowedTimeBeforeStaleSec; - } + private List<String> info; + private List<String> lifecycle; - public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) { - this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec; - } + public List<String> getInfo() { + return info; + } - public ExternalServiceConfig getAaiConfig() { - return aaiConfig; - } + public void setInfo(List<String> info) { + this.info = info; + } - public void setAaiConfig(ExternalServiceConfig aaiConfig) { - this.aaiConfig = aaiConfig; - } + public List<String> getLifecycle() { + return lifecycle; + } - public ExternalServiceConfig getMsoConfig() { - return msoConfig; - } + public void setLifecycle(List<String> lifecycle) { + this.lifecycle = lifecycle; + } - public void setMsoConfig(ExternalServiceConfig msoConfig) { - this.msoConfig = msoConfig; + @Override + public String toString() { + return "ArtifactTypesConfig [info=" + info + ", lifecycle=" + lifecycle + "]"; + } } } 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 926d21f395..742cd1815e 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. @@ -17,269 +17,247 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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; + + 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 String getHosts() { + return hosts; + } - public void setHosts(String hosts) { - this.hosts = hosts; - } + public void setHosts(String hosts) { + this.hosts = hosts; + } - 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; + } - public Integer getTimeoutMs() { - return timeoutMs; - } + public Integer getTimeoutMs() { + return timeoutMs; + } - public void setTimeoutMs(Integer timeoutMs) { - this.timeoutMs = timeoutMs; - } + public void setTimeoutMs(Integer timeoutMs) { + this.timeoutMs = timeoutMs; + } - public Integer getLimit() { - return limit; - } + public Integer getLimit() { + return limit; + } - public void setLimit(Integer limit) { - this.limit = limit; - } + public void setLimit(Integer limit) { + this.limit = limit; + } - public Integer getPollingInterval() { - return pollingInterval; - } + public Integer getPollingInterval() { + return pollingInterval; + } - public void setPollingInterval(Integer pollingInterval) { - this.pollingInterval = pollingInterval; - } + public void setPollingInterval(Integer pollingInterval) { + this.pollingInterval = pollingInterval; + } - public String getTopic() { - return topic; - } + public String getTopic() { + return topic; + } - public void setTopic(String topic) { - this.topic = topic; - } + public void setTopic(String topic) { + this.topic = topic; + } - public Double getLatitude() { - return latitude; - } + public Double getLatitude() { + return latitude; + } - public void setLatitude(Double latitude) { - this.latitude = latitude; - } + public void setLatitude(Double latitude) { + this.latitude = latitude; + } - public Double getLongitude() { - return longitude; - } + public Double getLongitude() { + return longitude; + } - public void setLongitude(Double longitude) { - this.longitude = longitude; - } + public void setLongitude(Double longitude) { + this.longitude = longitude; + } - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } - public void setVersion(String version) { - this.version = version; - } + public void setVersion(String version) { + this.version = version; + } - public String getServiceName() { - return serviceName; - } + 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 void setServiceName(String serviceName) { - this.serviceName = serviceName; - } + public String getRouteOffer() { + return routeOffer; + } + + public void setRouteOffer(String routeOffer) { + this.routeOffer = routeOffer; + } - public String getEnvironment() { - return environment; - } + public String getProtocol() { + return protocol; + } - public void setEnvironment(String environment) { - this.environment = environment; - } + public void setProtocol(String protocol) { + this.protocol = protocol; + } - 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; - } - - 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 Integer getTimeLimitForNotificationHandleMs() { - return timeLimitForNotificationHandleMs; - } - - public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { - this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; - } + 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; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean isActive) { + this.active = isActive; + } + + public Integer getTimeLimitForNotificationHandleMs() { + return timeLimitForNotificationHandleMs; + } + + public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) { + this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs; + } public boolean isAftDme2SslEnable() { return aftDme2SslEnable; @@ -321,21 +299,47 @@ public class DmaapConsumerConfiguration { 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 + "]"; - } - + @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 + "]"; + } + + /** + * 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 + "]"; + } + } } 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 index dce327c150..287c26c00f 100644 --- 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 @@ -12,56 +12,54 @@ import lombok.ToString; @ToString 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; + 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 isDme2TraceOn() { - return dme2TraceOn; - } + public Boolean isDme2TraceOn() { + return dme2TraceOn; + } - /** - * Contains Dmaap Client credential parameters: username and password - */ - @Getter - @Setter - public static class Credential{ + /** + * Contains Dmaap Client credential parameters: username and password + */ + @Getter + @Setter + public static class Credential { - private String username; - private String password; - - @Override - public String toString() { - return "Credential [username=" + username + ", password=" + password + "]"; - } - - } + private String username; + private String password; + @Override + public String toString() { + return "Credential [username=" + username + ", password=" + password + "]"; + } + } } 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 d876378421..3a4914d578 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. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; public class DmeConfiguration { + private String lookupUriFormat = "http://DME2RESOLVE/service=%s/version=1.0.0/envContext=%s/routeOffer=DEFAULT"; public String getLookupUriFormat() { @@ -33,8 +33,6 @@ public class DmeConfiguration { @Override public String toString() { - return "DmeConfiguration{" + - "lookupUriFormat='" + lookupUriFormat + '\'' + - '}'; + 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 52ea02cfab..39207c6023 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. @@ -17,38 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; -import org.openecomp.sdc.common.api.BasicConfiguration; - import java.util.Map; +import org.openecomp.sdc.common.api.BasicConfiguration; 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 ec9a61c81f..a14d6fdff7 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. @@ -17,83 +17,75 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; 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 static final String SVC_PREFIX = "SVC"; + private static final String POL_PREFIX = "POL"; + private static Logger log = Logger.getLogger(ErrorInfo.class.getName()); + private Integer code; + private String message; + private String messageId; + private ErrorInfoType errorInfoType; + + 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 02965242cf..835621fcf2 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. @@ -17,31 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config; -import org.openecomp.sdc.common.api.BasicConfiguration; - import java.util.Map; +import org.openecomp.sdc.common.api.BasicConfiguration; public class Neo4jErrorsConfiguration extends BasicConfiguration { - private Map<String, String> errors; - public Map<String, String> getErrors() { - return errors; - } + private Map<String, String> errors; - public void setErrors(Map<String, String> errors) { - this.errors = errors; - } + public Map<String, String> getErrors() { + return errors; + } - public String getErrorMessage(String key) { - return errors.get(key); - } + public void setErrors(Map<String, String> errors) { + this.errors = errors; + } - @Override - public String toString() { - return "Neo4jErrorsConfiguration [errors=" + errors + "]"; - } + public String getErrorMessage(String key) { + return errors.get(key); + } + @Override + public String toString() { + return "Neo4jErrorsConfiguration [errors=" + errors + "]"; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/exception/MissingBaseArtifactConfigException.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/exception/MissingBaseArtifactConfigException.java index 87bf2cc5a8..d6787f1dac 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/exception/MissingBaseArtifactConfigException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/exception/MissingBaseArtifactConfigException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config.exception; public class MissingBaseArtifactConfigException extends RuntimeException { @@ -24,5 +23,4 @@ public class MissingBaseArtifactConfigException extends RuntimeException { public MissingBaseArtifactConfigException(final String msg) { super(msg); } - } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/ArtifactConfigValidator.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/ArtifactConfigValidator.java index 66152d6a20..21ca5bd815 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/ArtifactConfigValidator.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/validation/ArtifactConfigValidator.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config.validation; import java.util.List; @@ -36,12 +35,10 @@ import org.slf4j.LoggerFactory; public class ArtifactConfigValidator { private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactConfigValidator.class); - private final Configuration configuration; private final Set<ArtifactTypeEnum> baseArtifactSet; - public ArtifactConfigValidator(final Configuration configuration, - final Set<ArtifactTypeEnum> baseArtifactSet) { + public ArtifactConfigValidator(final Configuration configuration, final Set<ArtifactTypeEnum> baseArtifactSet) { this.configuration = configuration; this.baseArtifactSet = baseArtifactSet; } @@ -53,19 +50,13 @@ public class ArtifactConfigValidator { if (CollectionUtils.isEmpty(baseArtifactSet)) { return; } - final List<ArtifactConfiguration> artifacts = configuration.getArtifacts(); if (CollectionUtils.isEmpty(artifacts)) { LOGGER.warn("No configuration artifacts entry found. Ignoring artifacts validation."); return; } - - final Set<ArtifactTypeEnum> notConfiguredArtifactTypeSet = baseArtifactSet.stream() - .filter(artifactTypeEnum -> - artifacts.stream() - .noneMatch(artifactConfiguration -> - artifactTypeEnum.getType().equals(artifactConfiguration.getType()))) - .collect(Collectors.toSet()); + final Set<ArtifactTypeEnum> notConfiguredArtifactTypeSet = baseArtifactSet.stream().filter(artifactTypeEnum -> artifacts.stream() + .noneMatch(artifactConfiguration -> artifactTypeEnum.getType().equals(artifactConfiguration.getType()))).collect(Collectors.toSet()); if (!notConfiguredArtifactTypeSet.isEmpty()) { final String msg = buildErrorMessage(notConfiguredArtifactTypeSet); throw new MissingBaseArtifactConfigException(msg); @@ -73,10 +64,7 @@ public class ArtifactConfigValidator { } private String buildErrorMessage(final Set<ArtifactTypeEnum> missingConfigArtifactTypeSet) { - final String artifactTypeAsString = missingConfigArtifactTypeSet.stream() - .map(ArtifactTypeEnum::getType) - .collect(Collectors.joining(", ")); + final String artifactTypeAsString = missingConfigArtifactTypeSet.stream().map(ArtifactTypeEnum::getType).collect(Collectors.joining(", ")); return String.format("Missing configuration for Artifact Type(s): %s", artifactTypeAsString); } - } 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 72b53bac75..1567355937 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. @@ -17,41 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.config.validation; 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 + * <p> + * 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... - String heat_template_version; - - Map<String, Object> resources; - - public String getHeat_template_version() { - return heat_template_version; - } + // All the rest of heat file is not needed for now... + String heat_template_version; + Map<String, Object> resources; - public void setHeat_template_version(String heat_template_version) { - this.heat_template_version = heat_template_version; - } + public String getHeat_template_version() { + return heat_template_version; + } - public Map<String, Object> getResources() { - return resources; - } + public void setHeat_template_version(String heat_template_version) { + this.heat_template_version = heat_template_version; + } - public void setResources(Map<String, Object> resources) { - this.resources = resources; - } + public Map<String, Object> getResources() { + return 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 c29574dd1b..1247cd2319 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. @@ -17,11 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.monitoring; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import javax.servlet.ServletContext; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; @@ -38,72 +42,61 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.monitoring.MonitoringEvent; import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher; -import javax.servlet.ServletContext; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -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 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. - */ - ScheduledExecutorService monitoringExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "BE-Monitoring-Thread"); - } - }); - private ServletContext context; + 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(); + /** + * 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()); - - 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))); + 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))); 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); + } + } + + 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()); + } + } } 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 fa0f30842b..eb3ca0b396 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. @@ -17,21 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; public enum ApplicationErrorCodesEnum { - - POL5000, // INTERNAL_ERROR - - SVC4000, // INVALID_INPUT - - SVC4002, // MISSING_INFORMATION - SVC4003, // RESOURCE_NAME_ALREADY_EXIST - SVC4004, // MISSING_CATEGORY - SVC4005, // MISSING_TAGS - SVC4006, // MISSING_DESCRIPTION - SVC4007, // BAD_CATEGORY - - SVC4030; // RESTRICTED_ACTION -} + POL5000, // INTERNAL_ERROR + SVC4000, // INVALID_INPUT + SVC4002, // MISSING_INFORMATION + SVC4003, // RESOURCE_NAME_ALREADY_EXIST + SVC4004, // MISSING_CATEGORY + SVC4005, // MISSING_TAGS + SVC4006, // MISSING_DESCRIPTION + SVC4007, // BAD_CATEGORY + 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 b9b440dc49..e951dc07f6 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; import java.util.ArrayList; @@ -27,27 +26,24 @@ import lombok.Getter; @AllArgsConstructor public enum ArtifactGroupTypeEnum { - - INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER"); - - @Getter - private final String type; - - public static ArtifactGroupTypeEnum findType(final String type) { - for (ArtifactGroupTypeEnum ate : values()) { - if (ate.getType().equals(type)) { - return ate; - } - } - return null; - } - - public static List<String> getAllTypes() { - List<String> types = new ArrayList<>(); - for (ArtifactGroupTypeEnum ate : values()) { - types.add(ate.getType()); - } - return types; - } - + INFORMATIONAL("INFORMATIONAL"), DEPLOYMENT("DEPLOYMENT"), LIFE_CYCLE("LIFE_CYCLE"), SERVICE_API("SERVICE_API"), TOSCA("TOSCA"), OTHER("OTHER"); + @Getter + private final String type; + + public static ArtifactGroupTypeEnum findType(final String type) { + for (ArtifactGroupTypeEnum ate : values()) { + if (ate.getType().equals(type)) { + return ate; + } + } + return null; + } + + public static List<String> getAllTypes() { + List<String> types = new ArrayList<>(); + for (ArtifactGroupTypeEnum ate : 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 766825cdbe..6be6c7f048 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; import java.util.ArrayList; @@ -29,12 +28,13 @@ import lombok.AllArgsConstructor; import lombok.Getter; /** - * Represents an artifact type that is used for hard-coded type representation. + * Represents an artifact type that is used for hard-coded type representation. * All artifacts must be configured in the SDC configuration file. */ @Getter @AllArgsConstructor public enum ArtifactTypeEnum { + // @formatter:off AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), @@ -95,6 +95,7 @@ public enum ArtifactTypeEnum { YANG_MODULE("YANG_MODULE"), YANG_XML("YANG_XML"), YANG("YANG"); + // @formatter:on private final String type; @@ -119,67 +120,15 @@ public enum ArtifactTypeEnum { * @return A set of base artifact types */ public static Set<ArtifactTypeEnum> getBaseArtifacts() { - final List<ArtifactTypeEnum> artifactTypeEnums = Arrays.asList( - AAI_SERVICE_MODEL, - AAI_VF_INSTANCE_MODEL, - AAI_VF_MODEL, - AAI_VF_MODULE_MODEL, - ANSIBLE_PLAYBOOK, - APPC_CONFIG, - BPEL, - CHEF, - CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, - CONTROLLER_BLUEPRINT_ARCHIVE, - DCAE_DOC, - DCAE_EVENT, - DCAE_INVENTORY_BLUEPRINT, - DCAE_INVENTORY_DOC, - DCAE_INVENTORY_EVENT, - DCAE_INVENTORY_JSON, - DCAE_INVENTORY_POLICY, - DCAE_INVENTORY_TOSCA, - DCAE_JSON, - DCAE_POLICY, - DCAE_TOSCA, - DG_XML, - ETSI_PACKAGE, - GUIDE, - HEAT, - HEAT_ARTIFACT, - HEAT_ENV, - HEAT_NESTED, - HEAT_NET, - HEAT_VOL, - ICON, - LIFECYCLE_OPERATIONS, - MODEL_INVENTORY_PROFILE, - MODEL_QUERY_SPEC, - MURANO_PKG, - NETWORK_CALL_FLOW, - ONBOARDED_PACKAGE, - OTHER, - PERFORMANCE_COUNTER, - PLAN, - PM_DICTIONARY, - PNF_SW_INFORMATION, - PUPPET, - SHELL, - SHELL_SCRIPT, - SNMP_POLL, - SNMP_TRAP, - TOSCA_CSAR, - TOSCA_TEMPLATE, - UCPE_LAYER_2_CONFIGURATION, - VENDOR_LICENSE, - VES_EVENTS, - VF_LICENSE, - VF_MODULES_METADATA, - VNF_CATALOG, - WORKFLOW, - YANG, - YANG_MODULE, - YANG_XML - ); + final List<ArtifactTypeEnum> artifactTypeEnums = Arrays + .asList(AAI_SERVICE_MODEL, AAI_VF_INSTANCE_MODEL, AAI_VF_MODEL, AAI_VF_MODULE_MODEL, ANSIBLE_PLAYBOOK, APPC_CONFIG, BPEL, CHEF, + CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, CONTROLLER_BLUEPRINT_ARCHIVE, DCAE_DOC, DCAE_EVENT, DCAE_INVENTORY_BLUEPRINT, DCAE_INVENTORY_DOC, + DCAE_INVENTORY_EVENT, DCAE_INVENTORY_JSON, DCAE_INVENTORY_POLICY, DCAE_INVENTORY_TOSCA, DCAE_JSON, DCAE_POLICY, DCAE_TOSCA, DG_XML, + ETSI_PACKAGE, GUIDE, HEAT, HEAT_ARTIFACT, HEAT_ENV, HEAT_NESTED, HEAT_NET, HEAT_VOL, ICON, LIFECYCLE_OPERATIONS, + MODEL_INVENTORY_PROFILE, MODEL_QUERY_SPEC, MURANO_PKG, NETWORK_CALL_FLOW, ONBOARDED_PACKAGE, OTHER, PERFORMANCE_COUNTER, PLAN, + PM_DICTIONARY, PNF_SW_INFORMATION, PUPPET, SHELL, SHELL_SCRIPT, SNMP_POLL, SNMP_TRAP, TOSCA_CSAR, TOSCA_TEMPLATE, + UCPE_LAYER_2_CONFIGURATION, VENDOR_LICENSE, VES_EVENTS, VF_LICENSE, VF_MODULES_METADATA, VNF_CATALOG, WORKFLOW, YANG, YANG_MODULE, + YANG_XML); return new HashSet<>(artifactTypeEnums); } 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 5152b2af26..ce4e484a27 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; public class BasicConfiguration { 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 d60ed6dabc..b6b6e52b20 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. @@ -17,34 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; public class ConfigurationListener { - private Class<? extends BasicConfiguration> type; - private FileChangeCallback callBack; - - public ConfigurationListener(Class<? extends BasicConfiguration> type, FileChangeCallback callBack) { - super(); - this.type = type; - this.callBack = callBack; - } + private Class<? extends BasicConfiguration> type; + private FileChangeCallback callBack; - public Class<? extends BasicConfiguration> getType() { - return type; - } + public ConfigurationListener(Class<? extends BasicConfiguration> type, FileChangeCallback callBack) { + super(); + this.type = type; + this.callBack = callBack; + } - public void setType(Class<? extends BasicConfiguration> type) { - this.type = type; - } + public Class<? extends BasicConfiguration> getType() { + return type; + } - public FileChangeCallback getCallBack() { - return callBack; - } + public void setType(Class<? extends BasicConfiguration> type) { + this.type = type; + } - public void setCallBack(FileChangeCallback callBack) { - this.callBack = callBack; - } + public FileChangeCallback getCallBack() { + return 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 12982caec0..cfdac07a0f 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. @@ -17,12 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; public interface ConfigurationSource { - <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); + <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); - <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener); + <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 b06d55aa67..d44aa3018e 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. @@ -17,144 +17,135 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 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."; - public static final String USER_DEFINED_SERVICE_NAMESPACE_PREFIX = "org.openecomp.service."; - - 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_TIMEOUT = "timeout"; + 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 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 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_ATTRIBUTE = "get_attribute"; - 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 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."; + public static final String USER_DEFINED_SERVICE_NAMESPACE_PREFIX = "org.openecomp.service."; + 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_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 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_ATTRIBUTE = "get_attribute"; + 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"; - - //external HealthCheck components - public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; - public static final String HC_COMPONENT_ECOMP_PORTAL = "PORTAL"; + 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"; + //external HealthCheck components + public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING"; + public static final String HC_COMPONENT_ECOMP_PORTAL = "PORTAL"; + //Plugin BL + public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; - - //Plugin BL - public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL"; - - private Constants(){} + 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 9684c98bd3..0d6b577995 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. @@ -17,12 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; @FunctionalInterface public interface FileChangeCallback { - void reconfigure(BasicConfiguration obj); - + 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 index 2e0ce9481a..83f6dae28a 100644 --- 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 @@ -1,6 +1,3 @@ package org.openecomp.sdc.common.api; -public enum FilterDecisionEnum { - EXTERNAL,INTERNAL,NA; - -} +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 fb1938fb9a..361701a9d7 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. @@ -17,91 +17,85 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; 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; -} - 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 + "]"; - } - + 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 void setHealthCheckComponent(String healthCheckComponent) { + this.healthCheckComponent = 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; + } + + @Override + public String toString() { + return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus=" + healthCheckStatus + ", version=" + version + + ", description=" + description + ", componentsInfo=" + componentsInfo + "]"; + } + + public enum HealthCheckStatus {UP, DOWN, UNKNOWN;} } 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 80dac70f2a..aeef6a0002 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 @@ -17,21 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -import java.util.List; - @Getter @Setter @AllArgsConstructor public class HealthCheckWrapper { - private List<HealthCheckInfo> componentsInfo; - private String sdcVersion; - private String siteMode; + private List<HealthCheckInfo> componentsInfo; + private String sdcVersion; + private String 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 b93fed2e0c..61275f7c5b 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. @@ -17,9 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; -public enum ResourceType { - RESOURCE, SERVICE -} +public enum ResourceType {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 3e8968a481..84715a25b4 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; import com.fasterxml.jackson.core.JsonProcessingException; @@ -25,59 +24,57 @@ 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; - } + 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; + } + } } 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 f6608952d0..18bc4cd308 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. @@ -17,63 +17,61 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; 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 4095714f4b..3d0a8f9a3c 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. @@ -17,21 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; import java.util.List; public class ToscaNodeTypeInterface { - List<String> scripts; - - public List<String> getScripts() { - return scripts; - } + List<String> scripts; - public void setScripts(List<String> scripts) { - this.scripts = scripts; - } + public List<String> getScripts() { + return 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 110dbf34a2..e98cc7a45b 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. @@ -17,127 +17,135 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 + "]"; - } - + private String artifactName; + private String artifactPath; + private ArtifactTypeEnum artifactType; + private String artifactDescription; + private String 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; + } + + 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 a750fa454a..8aa8a4b070 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. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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"); - 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 0dadef9292..863d78c97f 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. @@ -17,13 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; public interface YamlConstants { - 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"; + 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 ae25ebe177..45bc72ca6e 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api; import java.util.ArrayList; @@ -27,23 +26,15 @@ import lombok.Getter; @AllArgsConstructor public enum YamlSuffixEnum { - - YAML("YAML"), - yaml("yaml"), - YML("YML"), - yml("yml"); - - @Getter - private final String suffix; - - public static List<String> getSuffixes() { - - List<String> arrayList = new ArrayList<>(); - - for (YamlSuffixEnum yamlSuffixEnum : YamlSuffixEnum.values()) { - arrayList.add(yamlSuffixEnum.getSuffix()); - } - - return arrayList; - } + YAML("YAML"), yaml("yaml"), YML("YML"), yml("yml"); + @Getter + private final String suffix; + + public static List<String> getSuffixes() { + List<String> arrayList = new ArrayList<>(); + for (YamlSuffixEnum yamlSuffixEnum : YamlSuffixEnum.values()) { + arrayList.add(yamlSuffixEnum.getSuffix()); + } + return arrayList; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/exception/LoadConfigurationException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/exception/LoadConfigurationException.java index dff83c6d6f..2338ec84b5 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/exception/LoadConfigurationException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/exception/LoadConfigurationException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.api.exception; public class LoadConfigurationException extends RuntimeException { 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 49f04d2ee1..a8ee0e85c0 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; import com.jcabi.aspects.Loggable; @@ -25,14 +24,11 @@ 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 abstract IEcompConfigurationManager getConfigurationManager(); - - public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) { - - EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams); + public static final String PARAM_STR = "%s"; - } + public abstract IEcompConfigurationManager getConfigurationManager(); + public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... 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 5ea06cb3f7..f27ed035bb 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; import lombok.AllArgsConstructor; @@ -25,10 +24,7 @@ import lombok.Getter; @AllArgsConstructor public enum EcompClassification { - - INFORMATION("I"), WARNING("W"), ERROR("E"), FATAL("F"); - - @Getter - private final String classification; - + INFORMATION("I"), WARNING("W"), ERROR("E"), FATAL("F"); + @Getter + private final String 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 845288a5db..445ee63701 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; import lombok.Getter; @@ -25,6 +24,7 @@ import lombok.Getter; @Getter public enum EcompErrorCode { + // @formatter:off E_100("Authentication problem towards U-EB server. Reason: %s", "An Authentication failure occured during access to UEB server. Please check that UEB keys are configured correctly in ASDC BE distribution configuration."), E_199("Internal authentication problem. Description: %s"), @@ -108,6 +108,7 @@ public enum EcompErrorCode { E_900("Unexpected error during BE REST API execution"), E_901("General error during FE Health Check"), E_999("Unexpected error. Description: %s"); + // @formatter:on /* * 100-199 Security/Permission Related - Authentication problems (from 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 b9bdd88e7d..3fcd32e060 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. @@ -17,143 +17,129 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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; import java.util.Map; import java.util.regex.Pattern; +import org.openecomp.sdc.common.api.BasicConfiguration; public class EcompErrorConfiguration extends BasicConfiguration { - 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; - } - + 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;} } 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 61e992bbd7..8330a79fdd 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 @@ -17,411 +17,104 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; import lombok.Getter; @Getter public enum EcompErrorEnum { - - - BeUebAuthenticationError(EcompErrorCode.E_100, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, - EcompClassification.ERROR), - - - 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, - EcompClassification.WARNING), InternalAuthenticationError(EcompErrorCode.E_199, - ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, - EcompClassification.ERROR), InternalAuthenticationFatal(EcompErrorCode.E_199, - ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.CRITICAL, - EcompClassification.FATAL), - - BeHealthCheckRecovery(EcompErrorCode.E_205, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION, null), BeHealthCheckJanusGraphRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), BeHealthCheckUebClusterRecovery(EcompErrorCode.E_208, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), FeHealthCheckRecovery(EcompErrorCode.E_209, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), DmaapHealthCheckRecovery(EcompErrorCode.E_210, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, - null), BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR, - AlarmSeverity.CRITICAL, EcompClassification.ERROR, - BeHealthCheckRecovery), - - BeHealthCheckJanusGraphError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - 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, - FeHealthCheckRecovery), BeUebConnectionError(EcompErrorCode.E_210, - ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeUebUnkownHostError(EcompErrorCode.E_211, - ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - EcompClassification.ERROR), - - FqdnResolveError(EcompErrorCode.E_212, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - EcompClassification.ERROR), SiteSwitchoverInfo(EcompErrorCode.E_213, ErrorType.RECOVERY, - AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), - - InternalConnectionInfo(EcompErrorCode.E_299, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION), InternalConnectionWarning(EcompErrorCode.E_299, - ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MINOR, - EcompClassification.WARNING), InternalConnectionError(EcompErrorCode.E_299, - ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - EcompClassification.ERROR), InternalConnectionFatal(EcompErrorCode.E_299, - ErrorType.CONNECTION_PROBLEM, AlarmSeverity.CRITICAL, EcompClassification.FATAL), - - BeComponentMissingError(EcompErrorCode.E_300, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeIncorrectComponentError(EcompErrorCode.E_301, ErrorType.SYSTEM_ERROR, - AlarmSeverity.MAJOR, EcompClassification.ERROR), BeInvalidConfigurationError(EcompErrorCode.E_302, - ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, - EcompClassification.FATAL), BeUebObjectNotFoundError(EcompErrorCode.E_303, - ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeDistributionEngineInvalidArtifactType( - EcompErrorCode.E_304, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, - EcompClassification.WARNING), BeMissingConfigurationError( - EcompErrorCode.E_305, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, - EcompClassification.FATAL), BeConfigurationInvalidListSizeError( - EcompErrorCode.E_306, ErrorType.CONFIG_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.FATAL), ErrorConfigFileFormat( - EcompErrorCode.E_307, ErrorType.CONFIG_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeMissingArtifactInformationError( - EcompErrorCode.E_308, ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeArtifactMissingError( - EcompErrorCode.E_309, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeUserMissingError( - EcompErrorCode.E_310, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), EcompMismatchParam( - EcompErrorCode.E_311, - ErrorType.CONFIG_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), EcompMissingError( - EcompErrorCode.E_312, - ErrorType.CONFIG_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), - - InternalDataInfo(EcompErrorCode.E_399, ErrorType.DATA_ERROR, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION), InternalDataWarning(EcompErrorCode.E_399, ErrorType.DATA_ERROR, - AlarmSeverity.MINOR, EcompClassification.WARNING), InternalDataError(EcompErrorCode.E_399, - ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), InternalDataFatal(EcompErrorCode.E_399, ErrorType.DATA_ERROR, - AlarmSeverity.CRITICAL, EcompClassification.FATAL), - - BeInvalidTypeError(EcompErrorCode.E_400, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, - EcompClassification.WARNING), BeInvalidValueError(EcompErrorCode.E_401, ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, EcompClassification.WARNING), BeArtifactPayloadInvalid(EcompErrorCode.E_402, - ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeArtifactInformationInvalidError(EcompErrorCode.E_403, - ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeGraphObjectMissingError(EcompErrorCode.E_404, - ErrorType.DATA_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR), BeInvalidJsonInput(EcompErrorCode.E_405, - ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeDistributionMissingError( - EcompErrorCode.E_406, ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, EcompClassification.ERROR), - - InvalidInputInfo(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION), InvalidInputWarning(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, - AlarmSeverity.MINOR, EcompClassification.WARNING), InvalidInputError(EcompErrorCode.E_499, - ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), InvalidInputFatal(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, - AlarmSeverity.CRITICAL, EcompClassification.FATAL), - - BeInitializationError(EcompErrorCode.E_500, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR), BeFailedAddingResourceInstanceError(EcompErrorCode.E_501, - ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), BeUebSystemError( - EcompErrorCode.E_502, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeDistributionEngineSystemError(EcompErrorCode.E_503, - ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedAddingNodeTypeError(EcompErrorCode.E_504, - ErrorType.DATA_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR), BeDaoSystemError(EcompErrorCode.E_505, - ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR), BeSystemError(EcompErrorCode.E_506, - ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR), BeExecuteRollbackError( - EcompErrorCode.E_507, ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedLockObjectError( - EcompErrorCode.E_508, - ErrorType.SYSTEM_ERROR, - AlarmSeverity.CRITICAL, - EcompClassification.WARNING), BeFailedCreateNodeError( - EcompErrorCode.E_509, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedUpdateNodeError( - EcompErrorCode.E_510, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedDeleteNodeError( - EcompErrorCode.E_511, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedRetrieveNodeError( - EcompErrorCode.E_512, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedFindParentError( - EcompErrorCode.E_513, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedFindAllNodesError( - EcompErrorCode.E_514, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeFailedFindAssociationError( - EcompErrorCode.E_515, - ErrorType.DATA_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), BeComponentCleanerSystemError( - EcompErrorCode.E_516, - ErrorType.SYSTEM_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), FeHttpLoggingError( - EcompErrorCode.E_517, - ErrorType.SYSTEM_ERROR, - AlarmSeverity.MINOR, - EcompClassification.ERROR), FePortalServletError( - EcompErrorCode.E_518, - ErrorType.SYSTEM_ERROR, - AlarmSeverity.MAJOR, - EcompClassification.ERROR), - - InternalFlowInfo(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION), InternalFlowWarning(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, - AlarmSeverity.MINOR, EcompClassification.WARNING), InternalFlowError(EcompErrorCode.E_599, - ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), InternalFlowFatal(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, - AlarmSeverity.CRITICAL, EcompClassification.FATAL), - - BeRestApiGeneralError(EcompErrorCode.E_900, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - EcompClassification.ERROR, null), FeHealthCheckGeneralError(EcompErrorCode.E_901, ErrorType.SYSTEM_ERROR, - AlarmSeverity.CRITICAL, EcompClassification.ERROR, null), - - InternalUnexpectedInfo(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, AlarmSeverity.INFORMATIONAL, - EcompClassification.INFORMATION), InternalUnexpectedWarning(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, - AlarmSeverity.MINOR, EcompClassification.WARNING), InternalUnexpectedError(EcompErrorCode.E_999, - ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, - EcompClassification.ERROR), InternalUnexpectedFatal(EcompErrorCode.E_999, - ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.FATAL), - - /* - * BeUebAuthenticationError(EcompErrorCode.E_100, - * 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, - * EcompClassification.WARNING), - * InternalAuthenticationError(EcompErrorCode.E_199, - * ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, - * EcompClassification.ERROR), - * InternalAuthenticationFatal(EcompErrorCode.E_199, - * ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.CRITICAL, - * EcompClassification.FATAL), - * //BeFailedDeletingResourceInstanceError(EcompErrorCode.E_200, - * ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, Classification.ERROR), - * - * 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, - * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), - * BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR, - * 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, - * ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, - * EcompClassification.ERROR, BeHealthCheckUebClusterRecovery), - * FeHealthCheckError(EcompErrorCode.E_204, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR, - * FeHealthCheckRecovery), BeUebConnectionError(EcompErrorCode.E_210, - * ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - * EcompClassification.ERROR), BeUebUnkownHostError(EcompErrorCode.E_211, - * ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - * EcompClassification.ERROR), - * - * InternalConnectionInfo(EcompErrorCode.E_299, - * ErrorType.CONNECTION_PROBLEM, AlarmSeverity.INFORMATIONAL, - * EcompClassification.INFORMATION), - * InternalConnectionWarning(EcompErrorCode.E_299, - * ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MINOR, - * EcompClassification.WARNING), - * InternalConnectionError(EcompErrorCode.E_299, - * ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, - * EcompClassification.ERROR), InternalConnectionFatal(EcompErrorCode.E_299, - * ErrorType.CONNECTION_PROBLEM, AlarmSeverity.CRITICAL, - * EcompClassification.FATAL), - * - * BeComponentMissingError(EcompErrorCode.E_300, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeIncorrectComponentError(EcompErrorCode.E_301, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeInvalidConfigurationError(EcompErrorCode.E_302, ErrorType.CONFIG_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.FATAL), - * BeUebObjectNotFoundError(EcompErrorCode.E_303, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeDistributionEngineInvalidArtifactType(EcompErrorCode.E_304, - * ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.WARNING), - * BeMissingConfigurationError(EcompErrorCode.E_305, ErrorType.CONFIG_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.FATAL), - * BeConfigurationInvalidListSizeError(EcompErrorCode.E_306, - * ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.FATAL), - * ErrorConfigFileFormat(EcompErrorCode.E_307, ErrorType.CONFIG_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeMissingArtifactInformationError(EcompErrorCode.E_308, - * ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeArtifactMissingError(EcompErrorCode.E_309, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeUserMissingError(EcompErrorCode.E_310, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * EcompMismatchParam(EcompErrorCode.E_311, ErrorType.CONFIG_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * EcompMissingError(EcompErrorCode.E_312, ErrorType.CONFIG_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * - * InternalDataInfo(EcompErrorCode.E_399, ErrorType.DATA_ERROR, - * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), - * InternalDataWarning(EcompErrorCode.E_399, ErrorType.DATA_ERROR, - * AlarmSeverity.MINOR, EcompClassification.WARNING), - * InternalDataError(EcompErrorCode.E_399, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * InternalDataFatal(EcompErrorCode.E_399, ErrorType.DATA_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.FATAL), - * - * BeInvalidTypeError(EcompErrorCode.E_400, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.WARNING), - * BeInvalidValueError(EcompErrorCode.E_401, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.WARNING), - * BeArtifactPayloadInvalid(EcompErrorCode.E_402, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeArtifactInformationInvalidError(EcompErrorCode.E_403, - * ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeDistributionMissingError(EcompErrorCode.E_404, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeGraphObjectMissingError(EcompErrorCode.E_404, ErrorType.DATA_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR), - * BeInvalidJsonInput(EcompErrorCode.E_405, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * - * InvalidInputInfo(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), - * InvalidInputWarning(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MINOR, EcompClassification.WARNING), - * InvalidInputError(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * InvalidInputFatal(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.FATAL), - * - * BeInitializationError(EcompErrorCode.E_500, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR), - * BeFailedAddingResourceInstanceError(EcompErrorCode.E_501, - * ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeUebSystemError(EcompErrorCode.E_502, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeDistributionEngineSystemError(EcompErrorCode.E_503, - * ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedAddingNodeTypeError(EcompErrorCode.E_504, ErrorType.DATA_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR), - * BeDaoSystemError(EcompErrorCode.E_505, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR), - * BeSystemError(EcompErrorCode.E_506, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR), - * BeExecuteRollbackError(EcompErrorCode.E_507, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedLockObjectError(EcompErrorCode.E_508, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.WARNING), - * BeFailedCreateNodeError(EcompErrorCode.E_509, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedUpdateNodeError(EcompErrorCode.E_510, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedDeleteNodeError(EcompErrorCode.E_511, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedRetrieveNodeError(EcompErrorCode.E_512, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedFindParentError(EcompErrorCode.E_513, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedFindAllNodesError(EcompErrorCode.E_514, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeFailedFindAssociationError(EcompErrorCode.E_515, ErrorType.DATA_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * BeComponentCleanerSystemError(EcompErrorCode.E_516, - * ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), - * FeHttpLoggingError(EcompErrorCode.E_517, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MINOR, EcompClassification.ERROR), - * FePortalServletError(EcompErrorCode.E_518, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * - * InternalFlowInfo(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), - * InternalFlowWarning(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MINOR, EcompClassification.WARNING), - * InternalFlowError(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * InternalFlowFatal(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.FATAL), - * - * BeRestApiGeneralError(EcompErrorCode.E_900, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR, null), - * FeHealthCheckGeneralError(EcompErrorCode.E_901, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.ERROR, null), - * - * InternalUnexpectedInfo(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), - * InternalUnexpectedWarning(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MINOR, EcompClassification.WARNING), - * InternalUnexpectedError(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.MAJOR, EcompClassification.ERROR), - * InternalUnexpectedFatal(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, - * AlarmSeverity.CRITICAL, EcompClassification.FATAL), - */; - - private final EcompErrorCode ecompErrorCode; + // @formatter:off + BeUebAuthenticationError(EcompErrorCode.E_100, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + 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, EcompClassification.WARNING), + InternalAuthenticationError(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalAuthenticationFatal(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.CRITICAL, EcompClassification.FATAL), + BeHealthCheckRecovery(EcompErrorCode.E_205, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), + BeHealthCheckJanusGraphRecovery(EcompErrorCode.E_206, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), + BeHealthCheckUebClusterRecovery(EcompErrorCode.E_208, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), + FeHealthCheckRecovery(EcompErrorCode.E_209, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), + DmaapHealthCheckRecovery(EcompErrorCode.E_210, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION, null), + BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, BeHealthCheckRecovery), + BeHealthCheckJanusGraphError(EcompErrorCode.E_201, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, 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, FeHealthCheckRecovery), + BeUebConnectionError(EcompErrorCode.E_210, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeUebUnkownHostError(EcompErrorCode.E_211, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + FqdnResolveError(EcompErrorCode.E_212, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + SiteSwitchoverInfo(EcompErrorCode.E_213, ErrorType.RECOVERY, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), + InternalConnectionInfo(EcompErrorCode.E_299, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), + InternalConnectionWarning(EcompErrorCode.E_299, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MINOR, EcompClassification.WARNING), + InternalConnectionError(EcompErrorCode.E_299, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalConnectionFatal(EcompErrorCode.E_299, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.CRITICAL, EcompClassification.FATAL), + BeComponentMissingError(EcompErrorCode.E_300, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeIncorrectComponentError(EcompErrorCode.E_301, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeInvalidConfigurationError(EcompErrorCode.E_302, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.FATAL), + BeUebObjectNotFoundError(EcompErrorCode.E_303, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeDistributionEngineInvalidArtifactType(EcompErrorCode.E_304, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.WARNING), + BeMissingConfigurationError(EcompErrorCode.E_305, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.FATAL), + BeConfigurationInvalidListSizeError(EcompErrorCode.E_306, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.FATAL), + ErrorConfigFileFormat(EcompErrorCode.E_307, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeMissingArtifactInformationError(EcompErrorCode.E_308, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeArtifactMissingError(EcompErrorCode.E_309, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeUserMissingError(EcompErrorCode.E_310, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + EcompMismatchParam(EcompErrorCode.E_311, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + EcompMissingError(EcompErrorCode.E_312, ErrorType.CONFIG_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalDataInfo(EcompErrorCode.E_399, ErrorType.DATA_ERROR, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), + InternalDataWarning(EcompErrorCode.E_399, ErrorType.DATA_ERROR, AlarmSeverity.MINOR, EcompClassification.WARNING), + InternalDataError(EcompErrorCode.E_399, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalDataFatal(EcompErrorCode.E_399, ErrorType.DATA_ERROR, AlarmSeverity.CRITICAL, EcompClassification.FATAL), + BeInvalidTypeError(EcompErrorCode.E_400, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.WARNING), + BeInvalidValueError(EcompErrorCode.E_401, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.WARNING), + BeArtifactPayloadInvalid(EcompErrorCode.E_402, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeArtifactInformationInvalidError(EcompErrorCode.E_403, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeGraphObjectMissingError(EcompErrorCode.E_404, ErrorType.DATA_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR), + BeInvalidJsonInput(EcompErrorCode.E_405, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeDistributionMissingError(EcompErrorCode.E_406, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InvalidInputInfo(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), + InvalidInputWarning(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, AlarmSeverity.MINOR, EcompClassification.WARNING), + InvalidInputError(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InvalidInputFatal(EcompErrorCode.E_499, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.FATAL), + BeInitializationError(EcompErrorCode.E_500, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR), + BeFailedAddingResourceInstanceError(EcompErrorCode.E_501, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeUebSystemError(EcompErrorCode.E_502, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeDistributionEngineSystemError(EcompErrorCode.E_503, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedAddingNodeTypeError(EcompErrorCode.E_504, ErrorType.DATA_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR), + BeDaoSystemError(EcompErrorCode.E_505, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR), + BeSystemError(EcompErrorCode.E_506, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR), + BeExecuteRollbackError(EcompErrorCode.E_507, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedLockObjectError(EcompErrorCode.E_508, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.WARNING), + BeFailedCreateNodeError(EcompErrorCode.E_509, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedUpdateNodeError(EcompErrorCode.E_510, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedDeleteNodeError(EcompErrorCode.E_511, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedRetrieveNodeError(EcompErrorCode.E_512, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedFindParentError(EcompErrorCode.E_513, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedFindAllNodesError(EcompErrorCode.E_514, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeFailedFindAssociationError(EcompErrorCode.E_515, ErrorType.DATA_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + BeComponentCleanerSystemError(EcompErrorCode.E_516, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + FeHttpLoggingError(EcompErrorCode.E_517, ErrorType.SYSTEM_ERROR, AlarmSeverity.MINOR, EcompClassification.ERROR), + FePortalServletError(EcompErrorCode.E_518, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalFlowInfo(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), + InternalFlowWarning(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, AlarmSeverity.MINOR, EcompClassification.WARNING), + InternalFlowError(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalFlowFatal(EcompErrorCode.E_599, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.FATAL), + BeRestApiGeneralError(EcompErrorCode.E_900, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, null), + FeHealthCheckGeneralError(EcompErrorCode.E_901, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.ERROR, null), + InternalUnexpectedInfo(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION), + InternalUnexpectedWarning(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, AlarmSeverity.MINOR, EcompClassification.WARNING), + InternalUnexpectedError(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, AlarmSeverity.MAJOR, EcompClassification.ERROR), + InternalUnexpectedFatal(EcompErrorCode.E_999, ErrorType.SYSTEM_ERROR, AlarmSeverity.CRITICAL, EcompClassification.FATAL); + // @formatter:on + + private final EcompErrorCode ecompErrorCode; private final ErrorType eType; private final AlarmSeverity alarmSeverity; private final EcompClassification classification; private final EcompErrorEnum clearCode; - EcompErrorEnum(EcompErrorCode ecompErrorCode, ErrorType eType, AlarmSeverity alarmSeverity, - EcompClassification classification, EcompErrorEnum clearCode) { - + EcompErrorEnum(EcompErrorCode ecompErrorCode, ErrorType eType, AlarmSeverity alarmSeverity, EcompClassification classification, + EcompErrorEnum clearCode) { this.ecompErrorCode = ecompErrorCode; this.eType = eType; this.alarmSeverity = alarmSeverity; @@ -429,9 +122,7 @@ public enum EcompErrorEnum { this.clearCode = clearCode; } - EcompErrorEnum(EcompErrorCode ecompErrorCode, ErrorType eType, AlarmSeverity alarmSeverity, - EcompClassification classification) { - + EcompErrorEnum(EcompErrorCode ecompErrorCode, ErrorType eType, AlarmSeverity alarmSeverity, EcompClassification classification) { this.ecompErrorCode = ecompErrorCode; this.eType = eType; this.alarmSeverity = alarmSeverity; @@ -439,12 +130,7 @@ public enum EcompErrorEnum { this.clearCode = null; } - public enum ErrorType { - RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM - } - - public enum AlarmSeverity { - CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE - } + public enum ErrorType {RECOVERY, CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM} + public enum AlarmSeverity {CRITICAL, MAJOR, MINOR, INFORMATIONAL, NONE} } 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 e1fd34b26d..5a07040c16 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. @@ -17,62 +17,61 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 7145a11005..aaa83a3044 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. @@ -17,149 +17,135 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; import fj.data.Either; +import java.util.Formatter; +import java.util.IllegalFormatException; +import java.util.Locale; import org.apache.commons.lang3.StringUtils; 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; -import java.util.Formatter; -import java.util.IllegalFormatException; -import java.util.Locale; - public class EcompErrorLogUtil { - 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); + private static final String FATAL_ERROR_PREFIX = "FATAL ERROR!! "; + 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()); + + 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(); - - 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); - - log.error(severity, EcompLoggerErrorCode.getByValue(ecompErrorEnum.getEcompErrorCode().name()), - ecompErrorContext, ecompErrorContext, description); - } finally { - formatter.close(); - MDC.remove("alarmSeverity"); - } - } - - public static String createEcode(EcompErrorEnum ecompErrorEnum) { - - EcompClassification classification = ecompErrorEnum.getClassification(); - String ecompErrorCode = ecompErrorEnum.getEcompErrorCode().name(); - - String ecodeNumber = ecompErrorCode.substring(ecompErrorCode.indexOf("_") + 1); - + 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.getAlarmSeverity().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"); + } + } + + public static String createEcode(EcompErrorEnum ecompErrorEnum) { + EcompClassification classification = ecompErrorEnum.getClassification(); + String ecompErrorCode = ecompErrorEnum.getEcompErrorCode().name(); + 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 5da7808376..e8786c40fe 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. @@ -17,27 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; public enum EcompErrorName { - // general - EcompConfigFileFormat, EcompErrorNotFound, EcompErrorDescParamsMismatch, - - // 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; + // general + EcompConfigFileFormat, EcompErrorNotFound, EcompErrorDescParamsMismatch, + // 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; } 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 c16d8d329b..a36c6a8942 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. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config; public interface IEcompConfigurationManager { - public 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 5470fb9d9d..b934ab6679 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 @@ -17,14 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.config.generation; -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 java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -33,182 +27,160 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; +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; public class GenerateEcompErrorsCsv { - private static Logger log = LoggerFactory.getLogger(GenerateEcompErrorsCsv.class); - private static String DATE_FORMAT = "dd-M-yyyy-hh-mm-ss"; - - private static String NEW_LINE = System.getProperty("line.separator"); - - public static class EcompErrorRow { - - String errorName; - String errorCode; - String description; - ErrorType errorType; - AlarmSeverity alarmSeverity; - String cleanErrorCode; - String resolution; - - public String getErrorName() { - return errorName; - } - - public void setErrorName(String errorName) { - this.errorName = errorName; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public ErrorType getErrorType() { - return errorType; - } - - public void setErrorType(ErrorType errorType) { - this.errorType = errorType; - } - - public AlarmSeverity getAlarmSeverity() { - return alarmSeverity; - } - - public void setAlarmSeverity(AlarmSeverity alarmSeverity) { - this.alarmSeverity = alarmSeverity; - } - - public String getCleanErrorCode() { - return cleanErrorCode; - } - - public void setCleanErrorCode(String cleanErrorCode) { - this.cleanErrorCode = cleanErrorCode; - } - - public String getResolution() { - return resolution; - } - - public void setResolution(String resolution) { - this.resolution = resolution; - } - - } - - public boolean generateEcompErrorsCsvFile(String targetFolder, boolean addTimeToFileName) { - - targetFolder += File.separator; - - boolean result = false; - String dateFormatted = ""; - - if (addTimeToFileName) { - DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); - - Date date = new Date(); - - dateFormatted = "." + dateFormat.format(date); - - } - - String outputFile = targetFolder + "ecompErrorCodes" + dateFormatted + ".csv"; - - try(FileWriter writer = new FileWriter(outputFile)) { - - List<EcompErrorRow> errors = new ArrayList<>(); - - for (EcompErrorEnum ecompErrorEnum : EcompErrorEnum.values()) { - - EcompErrorRow ecompErrorRow = new EcompErrorRow(); - - String errorCode = EcompErrorLogUtil.createEcode(ecompErrorEnum); - - 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()); - ecompErrorRow.setErrorType(ecompErrorEnum.getEType()); - ecompErrorRow.setResolution(ecompErrorEnum.getEcompErrorCode().getResolution()); - - errors.add(ecompErrorRow); - } - - 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); - } - - result = true; - - } catch (Exception e) { - log.info("generate Ecomp Errors Csv File failed" , e); - } - - return result; - } - - 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); - } - - private String addInvertedCommas(String str) { - - if (str == null) { - return "\"\""; - } - - return "\"" + str + "\""; - } - + private static Logger log = LoggerFactory.getLogger(GenerateEcompErrorsCsv.class); + private static String DATE_FORMAT = "dd-M-yyyy-hh-mm-ss"; + private static String NEW_LINE = System.getProperty("line.separator"); + + public boolean generateEcompErrorsCsvFile(String targetFolder, boolean addTimeToFileName) { + targetFolder += File.separator; + boolean result = false; + String dateFormatted = ""; + if (addTimeToFileName) { + DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); + Date date = new Date(); + dateFormatted = "." + dateFormat.format(date); + } + String outputFile = targetFolder + "ecompErrorCodes" + dateFormatted + ".csv"; + try (FileWriter writer = new FileWriter(outputFile)) { + List<EcompErrorRow> errors = new ArrayList<>(); + for (EcompErrorEnum ecompErrorEnum : EcompErrorEnum.values()) { + EcompErrorRow ecompErrorRow = new EcompErrorRow(); + String errorCode = EcompErrorLogUtil.createEcode(ecompErrorEnum); + 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()); + ecompErrorRow.setErrorType(ecompErrorEnum.getEType()); + ecompErrorRow.setResolution(ecompErrorEnum.getEcompErrorCode().getResolution()); + errors.add(ecompErrorRow); + } + 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); + } + result = true; + } catch (Exception e) { + log.info("generate Ecomp Errors Csv File failed", e); + } + return result; + } + + 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); + } + + private String addInvertedCommas(String str) { + if (str == null) { + return "\"\""; + } + return "\"" + str + "\""; + } + + public static class EcompErrorRow { + + String errorName; + String errorCode; + String description; + ErrorType errorType; + AlarmSeverity alarmSeverity; + String cleanErrorCode; + String resolution; + + public String getErrorName() { + return errorName; + } + + public void setErrorName(String errorName) { + this.errorName = errorName; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public ErrorType getErrorType() { + return errorType; + } + + public void setErrorType(ErrorType errorType) { + this.errorType = errorType; + } + + public AlarmSeverity getAlarmSeverity() { + return alarmSeverity; + } + + public void setAlarmSeverity(AlarmSeverity alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } + + public String getCleanErrorCode() { + return cleanErrorCode; + } + + public void setCleanErrorCode(String cleanErrorCode) { + this.cleanErrorCode = cleanErrorCode; + } + + public String getResolution() { + return resolution; + } + + public void setResolution(String resolution) { + this.resolution = resolution; + } + } } 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 060e3ea79a..6bffd6b240 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.datastructure; import java.util.Date; @@ -27,76 +26,78 @@ import lombok.Getter; @AllArgsConstructor @Getter 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"), + // @formatter:off + // 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"); + // @formatter:on - private final Class<?> clazz; - private final String displayName; + private final Class<?> clazz; + private final String displayName; } 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 7cd099e07e..1cd030629e 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. @@ -17,103 +17,109 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.datastructure; import static org.apache.commons.lang3.StringUtils.EMPTY; +import fj.F; +import fj.data.Either; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.util.concurrent.*; +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.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 * + * @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 - * - * @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; - } + + 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; + } public interface FunctionTwoParamThrows<T1, T2, R, E extends Exception> { + /** * Same apply method, but throws an exception - * + * * @param t1 * @param t2 * @return @@ -121,219 +127,188 @@ public class FunctionalInterfaces { R apply(T1 t1, T2 t2) throws E; } - /** - * @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 { + /** + * @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 { 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; @@ -343,12 +318,10 @@ 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; } @@ -356,162 +329,139 @@ public class FunctionalInterfaces { } if (exception != null) { throw exception; - } - else { + } 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(); - } - } - 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); @@ -520,83 +470,72 @@ 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); - } + } + /** + * 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 d44470758a..7c4af67eab 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.datastructure; import java.util.Date; @@ -27,19 +26,20 @@ import lombok.Getter; @AllArgsConstructor @Getter 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 final Class<?> clazz; - private final String displayName; + // @formatter:off + 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"); + // @formatter:on + private final Class<?> clazz; + private final String 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 index 8dcca6b6e1..ea44d674fa 100644 --- 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 @@ -1,18 +1,13 @@ 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 + * 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; @@ -35,7 +30,6 @@ public class UserContext { private Set<String> userRoles; - public UserContext(String userId, Set<String> userRoles, String firstName, String lastName) { this.userId = userId; this.userRoles = userRoles; @@ -65,10 +59,7 @@ public class UserContext { @Override public String toString() { - return "UserContext{" + "userId='" + userId + '\'' + ", firstName='" + firstName + '\'' + ", lastname='" + lastName + '\'' + ", userRoles=" + userRoles + '}'; + 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 43fd5ca15f..8cc54694c6 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. @@ -17,36 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.datastructure; /** * Very Basic Wrapper class. - * - * @author mshitrit - * + * * @param <T> + * @author mshitrit */ public class Wrapper<T> { - private T innerElement; - public Wrapper(T innerElement) { - this.innerElement = innerElement; - } + private T 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 21c0f45e24..31363e50c1 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. @@ -17,11 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; + import org.apache.http.client.HttpRequestRetryHandler; public interface ComparableHttpRequestRetryHandler extends HttpRequestRetryHandler { + 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 66a7050821..a7ae6e6671 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. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; +import java.io.IOException; +import java.net.URI; +import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; @@ -29,7 +31,13 @@ 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.*; +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.protocol.HttpClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; @@ -41,117 +49,107 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.IOException; -import java.net.URI; -import java.util.Properties; - public class HttpClient { + private static final Logger logger = Logger.getLogger(HttpClient.class.getName()); - private final CloseableHttpClient client; private final HttpClientConfigImmutable configImmutable; - + public HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) { this.client = client; - this.configImmutable = configImmutable; + this.configImmutable = configImmutable; } - - public <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); } - <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, + FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { HttpPut httpPut = new HttpPut(url); httpPut.setEntity(entity); return execute(httpPut, headers, responseBuilder); } - <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, + FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); return execute(httpPost, headers, responseBuilder); } - <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, + FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { HttpPatch httpPatch = new HttpPatch(url); httpPatch.setEntity(entity); return execute(httpPatch, headers, responseBuilder); } - <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException { + <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) + throws HttpExecuteException { HttpDelete httpDelete = new HttpDelete(url); return execute(httpDelete, headers, responseBuilder); } - + void close() { try { client.close(); - } - catch (IOException 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) { + + private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, + FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) + throws HttpExecuteException { + if (configImmutable.getHeaders() != null) { configImmutable.getHeaders().forEach(request::addHeader); } - if (headers != null) { headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString())); } - 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()); 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), - new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword())); - + credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), + new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword())); HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(credentialsProvider); - AuthCache authCache = new BasicAuthCache(); 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())) { + int port = uri.getPort(); + if (port < 0) { + if (Constants.HTTPS.equals(uri.getScheme())) { port = 443; - } - else - if (Constants.HTTP.equals(uri.getScheme())) { + } else if (Constants.HTTP.equals(uri.getScheme())) { port = 80; - } - else { + } else { port = AuthScope.ANY_PORT; logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), 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 9b21e1ac87..7498315041 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. @@ -17,39 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import org.openecomp.sdc.common.http.config.BasicAuthorization; import org.openecomp.sdc.common.http.config.ClientCertificate; import org.openecomp.sdc.common.http.config.HttpClientConfig; import org.openecomp.sdc.common.http.config.Timeouts; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - 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); - } + private boolean enableMetricLogging; public HttpClientConfigImmutable(HttpClientConfig httpClientConfig) { timeouts = httpClientConfig.getTimeouts() != null ? new Timeouts(httpClientConfig.getTimeouts()) : null; - basicAuthorization = httpClientConfig.getBasicAuthorization() != null ? new BasicAuthorization(httpClientConfig.getBasicAuthorization()) : 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(); @@ -57,6 +51,11 @@ public final class HttpClientConfigImmutable { enableMetricLogging = httpClientConfig.isEnableMetricLogging(); } + static HttpClientConfigImmutable getOrCreate(HttpClientConfig httpClientConfig) { + // TODO: retrieve from a pool if exist, otherwise create new + return new HttpClientConfigImmutable(httpClientConfig); + } + public boolean isEnableMetricLogging() { return enableMetricLogging; } @@ -68,7 +67,7 @@ public final class HttpClientConfigImmutable { public int getNumOfRetries() { return numOfRetries; } - + String getBasicAuthPassword() { return basicAuthorization != null ? basicAuthorization.getPassword() : null; } @@ -88,7 +87,7 @@ public final class HttpClientConfigImmutable { ClientCertificate getClientCertificate() { return clientCertificate != null ? new ClientCertificate(clientCertificate) : null; } - + public int getReadTimeoutMs() { return timeouts.getReadTimeoutMs(); } @@ -119,43 +118,51 @@ public 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)) + } + } 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)) + } + } 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)) + } + } 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)) + } + } 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)) + } + } 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 982453246f..d45deb328b 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; import org.apache.http.client.HttpRequestRetryHandler; @@ -25,12 +24,9 @@ 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 { @@ -38,36 +34,27 @@ public class HttpClientFactory { 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); - - 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(userTokenHandler) - .setRetryHandler(resolveRetryHandler(config)) - .build(); - + CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager) + .setUserTokenHandler(userTokenHandler).setRetryHandler(resolveRetryHandler(config)).build(); return new HttpClient(client, config); } private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null; } - + private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) { - return RequestConfig.custom() - .setConnectTimeout(config.getConnectTimeoutMs()) - .setSocketTimeout(config.getReadTimeoutMs()) - .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs()) - .build(); + return RequestConfig.custom().setConnectTimeout(config.getConnectTimeoutMs()).setSocketTimeout(config.getReadTimeoutMs()) + .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs()).build(); } } 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 c5634eaf8c..966bf857c8 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. @@ -17,9 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; @@ -35,69 +41,50 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.http.config.ClientCertificate; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - 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 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) { + 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) { + } catch (GeneralSecurityException e) { logger.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e); sslsf = SSLConnectionSocketFactory.getSocketFactory(); } - Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() - .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory()) - .register(Constants.HTTPS, sslsf).build(); - + .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(Constants.HTTPS, sslsf).build(); PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry); - manager.setMaxTotal(DEFAULT_CONNECTION_POOL_SIZE); manager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION_PER_ROUTE); manager.setValidateAfterInactivity(VALIDATE_CONNECTION_AFTER_INACTIVITY_MS); - return manager; } @@ -107,12 +94,11 @@ public class HttpConnectionMngFactory { KeyStore clientKeyStore = createClientKeyStore(clientCertificate.getKeyStore(), keyStorePassword); sslContextBuilder.loadKeyMaterial(clientKeyStore, keyStorePassword); logger.debug("#setClientSsl - Set Client Certificate authentication"); - } - catch (IOException | GeneralSecurityException e) { + } 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)) { @@ -121,15 +107,14 @@ 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)) { + } 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 8487e1ff72..9c1435a211 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; public class HttpExecuteException extends Exception { @@ -25,17 +24,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 57e5cb2bed..7deac29d67 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. @@ -17,22 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; +import java.util.Properties; import org.apache.http.HttpEntity; import org.openecomp.sdc.common.http.config.HttpClientConfig; -import java.util.Properties; - //TODO- remove all static and use instance methods for better testing public abstract class HttpRequest { - static final Properties defaultHeaders = null; + static final Properties defaultHeaders = null; static final HttpClientConfig defaultConfig = new HttpClientConfig(); - - private HttpRequest() { } @@ -46,7 +42,7 @@ public abstract class HttpRequest { public static HttpResponse<String> get(String url, Properties headers) throws HttpExecuteException { return get(url, headers, defaultConfig); } - + public static HttpResponse<String> get(String url, HttpClientConfig config) throws HttpExecuteException { return get(url, defaultHeaders, config); } @@ -84,7 +80,7 @@ public abstract class HttpRequest { public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { return put(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> put(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return put(url, defaultHeaders, entity, config); } @@ -103,7 +99,7 @@ public abstract class HttpRequest { public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { return post(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> post(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return post(url, defaultHeaders, entity, config); } @@ -111,7 +107,7 @@ public abstract class HttpRequest { public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().post(url, headers, entity, config); } - + /* * PATCH */ @@ -122,7 +118,7 @@ public abstract class HttpRequest { public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity) throws HttpExecuteException { return patch(url, headers, entity, defaultConfig); } - + public static HttpResponse<String> patch(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return patch(url, defaultHeaders, entity, config); } @@ -130,7 +126,7 @@ public abstract class HttpRequest { public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException { return HttpRequestHandler.get().patch(url, headers, entity, config); } - + /* * DELETE */ @@ -141,7 +137,7 @@ public abstract class HttpRequest { public static HttpResponse<String> delete(String url, Properties headers) throws HttpExecuteException { return delete(url, headers, defaultConfig); } - + public static HttpResponse<String> delete(String url, HttpClientConfig config) throws HttpExecuteException { return delete(url, defaultHeaders, config); } @@ -149,7 +145,7 @@ public abstract class HttpRequest { 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 73f0f15354..c52933b401 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. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; import com.google.common.annotations.VisibleForTesting; +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; @@ -29,19 +32,13 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows; import org.openecomp.sdc.common.http.config.HttpClientConfig; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - public class HttpRequestHandler { - private static HttpRequestHandler handlerInstance = new HttpRequestHandler(); + private static final String HTTPS_PREFIX = "https://"; private static final String HTTP_PREFIX = "http://"; - + private static HttpRequestHandler handlerInstance = new HttpRequestHandler(); 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,37 +48,37 @@ public class HttpRequestHandler { response = IOUtils.toByteArray(content); } } - return new HttpResponse<>(response, - httpResponse.getStatusLine().getStatusCode(), - httpResponse.getStatusLine().getReasonPhrase()); + return new HttpResponse<>(response, httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; - private FunctionThrows<CloseableHttpResponse, HttpResponse<String>, Exception> stringResponseBuilder = (CloseableHttpResponse httpResponse) -> { HttpEntity entity = httpResponse.getEntity(); String response = null; if (entity != null) { response = EntityUtils.toString(entity); } - return new HttpResponse<>(response, - httpResponse.getStatusLine().getStatusCode(), - httpResponse.getStatusLine().getReasonPhrase()); + return new HttpResponse<>(response, httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); }; private HttpRequestHandler() { HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory(); clientFactory = new HttpClientFactory(connectionMngFactory); } - + public static HttpRequestHandler get() { return handlerInstance; } + @VisibleForTesting + public static void setTestInstance(HttpRequestHandler handlerInstance) { + HttpRequestHandler.handlerInstance = handlerInstance; + } + public HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException { HttpClient client = getOrCreateClient(url, config); 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); } @@ -105,12 +102,12 @@ public class HttpRequestHandler { 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); @@ -121,20 +118,13 @@ public class HttpRequestHandler { return clientFactory.createClient(protocol, config); } - @VisibleForTesting - public static void setTestInstance(HttpRequestHandler handlerInstance) { - HttpRequestHandler.handlerInstance = handlerInstance; - } - 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 { + } 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 c6061cf1c2..573c97f130 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. @@ -17,12 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; import org.apache.commons.lang3.StringUtils; public class HttpResponse<T> { + private final T response; private final int statusCode; private final String description; @@ -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,4 @@ 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 71f9ac2629..529502d7c9 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. @@ -17,14 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; 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 7b39e3f8c9..47fc1a8422 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. @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; -import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpHeaders; - import java.nio.charset.StandardCharsets; import java.util.Properties; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; public class RestUtils { @@ -32,5 +30,4 @@ public class RestUtils { byte[] credentials = Base64.encodeBase64((username + ":" + password).getBytes(StandardCharsets.UTF_8)); headers.setProperty(HttpHeaders.AUTHORIZATION, "Basic " + new String(credentials, StandardCharsets.UTF_8)); } - } 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 bbcd815e75..1c4a5a47a7 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. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.client.api; +import java.io.IOException; import org.apache.http.protocol.HttpContext; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.IOException; - public class RetryHandlers { 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) -> { @@ -38,6 +37,4 @@ public class RetryHandlers { 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 124c7ea0c8..c9147719a4 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.config; import fj.data.Either; @@ -25,6 +24,7 @@ import org.apache.commons.lang3.StringUtils; import org.onap.sdc.security.SecurityUtil; public class BasicAuthorization { + private String userName; private String password; @@ -36,36 +36,33 @@ public class BasicAuthorization { setPassword(basicAuthorization.password, false); } + public String getUserName() { + return userName; + } + public void setUserName(String userName) { validate(userName); this.userName = userName; } - public void setPassword(String password) { - setPassword(password, true); - } - - public String getUserName() { - return userName; - } - public String getPassword() { return password; } - + public void setPassword(String password) { + setPassword(password, true); + } + 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; } } @@ -81,25 +78,30 @@ 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)) + } + } else if (!password.equals(other.password)) { return false; + } if (userName == null) { - if (other.userName != null) + if (other.userName != null) { return false; - } - else if (!userName.equals(other.userName)) + } + } else if (!userName.equals(other.userName)) { return false; + } return true; } @@ -113,7 +115,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 c318a3b514..510c0a277c 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.config; import fj.data.Either; @@ -27,6 +26,7 @@ import org.onap.sdc.security.SecurityUtil; @EqualsAndHashCode public class ClientCertificate { + private String keyStore; private String keyStorePassword; @@ -37,28 +37,17 @@ public class ClientCertificate { setKeyStore(clientCertificate.getKeyStore()); setKeyStorePassword(clientCertificate.getKeyStorePassword(), false); } - - public void setKeyStore(String keyStore) { - validate(keyStore); - this.keyStore = keyStore; - } - - public void setKeyStorePassword(String keyStorePassword) { - setKeyStorePassword(keyStorePassword, true); - } 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; } } @@ -67,10 +56,19 @@ public class ClientCertificate { return keyStore; } + public void setKeyStore(String keyStore) { + validate(keyStore); + this.keyStore = keyStore; + } + public String getKeyStorePassword() { return keyStorePassword; } + public void setKeyStorePassword(String keyStorePassword) { + setKeyStorePassword(keyStorePassword, true); + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); @@ -79,9 +77,9 @@ public class ClientCertificate { 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 dcc9b73bcd..268dfce045 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. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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; } @@ -51,5 +50,4 @@ public class ExternalServiceConfig { builder.append("]"); return builder.toString(); } - } 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 a4f12e3eec..cfff386a2b 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. @@ -17,14 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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; +import org.openecomp.sdc.common.http.client.api.ComparableHttpRequestRetryHandler; public class HttpClientConfig { @@ -37,9 +34,9 @@ public class HttpClientConfig { @JsonIgnore private boolean enableMetricLogging = false; - public HttpClientConfig() { + public HttpClientConfig() { } - + public HttpClientConfig(Timeouts timeouts) { setTimeouts(timeouts); } @@ -85,11 +82,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; } @@ -97,7 +94,7 @@ public class HttpClientConfig { public int getNumOfRetries() { return numOfRetries; } - + public void setNumOfRetries(int numOfRetries) { this.numOfRetries = numOfRetries; } 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 040d068dfe..3b2cea87bb 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.config; import java.util.HashMap; @@ -27,22 +26,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 39ef8555ad..1fa5f9864a 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. @@ -17,21 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.http.config; public class Timeouts { + public static final Timeouts DEFAULT; private static final int DEFAULT_TIMEOUT_MS = 15000; - private int connectTimeoutMs = DEFAULT_TIMEOUT_MS; - private int readTimeoutMs = DEFAULT_TIMEOUT_MS; - private int connectPoolTimeoutMs = DEFAULT_TIMEOUT_MS; - public static final Timeouts DEFAULT; static { - DEFAULT = new Timeouts(); + DEFAULT = new Timeouts(); } + private int connectTimeoutMs = DEFAULT_TIMEOUT_MS; + private int readTimeoutMs = DEFAULT_TIMEOUT_MS; + private int connectPoolTimeoutMs = DEFAULT_TIMEOUT_MS; + private Timeouts() { } @@ -49,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; @@ -82,25 +82,31 @@ 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; - if (readTimeoutMs != other.readTimeoutMs) + } + if (readTimeoutMs != other.readTimeoutMs) { return false; + } return true; } - + @Override public String toString() { StringBuilder builder = new StringBuilder(); @@ -113,9 +119,9 @@ public class Timeouts { 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 c94db9a3c9..4efc43d675 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.impl; import java.io.File; @@ -36,92 +35,71 @@ import org.openecomp.sdc.exception.YamlConversionException; public class ConfigFileChangeListener extends FileChangeListener { - private static final Logger LOGGER = Logger.getLogger(ConfigFileChangeListener.class.getName()); - - private Map<String, List<ConfigurationListener>> fileChangeToCallBack = new HashMap<>(); - - private Object lock = new Object(); - - private YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - - @Override - public void onFileChange(File pFile) { - super.onFileChange(pFile); - - if (pFile == null) { - LOGGER.debug("Invalid file '{}'.", pFile); - return; - } - - if (fileChangeToCallBack == null) { - LOGGER.debug("File '{}' callback is null.", pFile); - return; - } - - final String id = findIdFromFileName(pFile.getName()); - if (id == null) { - LOGGER.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","", - "Cannot calculate id from file {}", pFile.getName()); - return; - } - - final List<ConfigurationListener> listeners = fileChangeToCallBack.get(id); - if (CollectionUtils.isEmpty(listeners)) { - LOGGER.debug("No file listeners for file '{}', id '{}'.", pFile, id); - return; - } - for (final ConfigurationListener configurationListener : listeners) { - final Class<? extends BasicConfiguration> configClass = configurationListener.getType(); - final BasicConfiguration basicConfiguration; - try { - basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass); - } catch (final YamlConversionException e) { - LOGGER.warn(EcompLoggerErrorCode.SCHEMA_ERROR, - "Configuration", "Configuration", - "Cannot update the listeners for file Change since the file content is invalid: {}", - e.getLocalizedMessage()); - continue; - } - LOGGER.debug("Loaded configuration after converting is {}", basicConfiguration); - configurationListener.getCallBack().reconfigure(basicConfiguration); - } - LOGGER.debug("File {} was changed.", pFile); - } - - 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); - } - - result = name.substring(startIndex, endIndex); - - } - - return result; - } - - public void register(String id, ConfigurationListener configurationListener) { - - if (configurationListener != null) { - - synchronized (lock) { - - List<ConfigurationListener> callbacks = fileChangeToCallBack.get(id); - if (callbacks == null) { - callbacks = new ArrayList<>(); - fileChangeToCallBack.put(id, callbacks); - } - callbacks.add(configurationListener); - - } - - } - - } - + private static final Logger LOGGER = Logger.getLogger(ConfigFileChangeListener.class.getName()); + private Map<String, List<ConfigurationListener>> fileChangeToCallBack = new HashMap<>(); + private Object lock = new Object(); + private YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + + @Override + public void onFileChange(File pFile) { + super.onFileChange(pFile); + if (pFile == null) { + LOGGER.debug("Invalid file '{}'.", pFile); + return; + } + if (fileChangeToCallBack == null) { + LOGGER.debug("File '{}' callback is null.", pFile); + return; + } + final String id = findIdFromFileName(pFile.getName()); + if (id == null) { + LOGGER.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Cannot calculate id from file {}", pFile.getName()); + return; + } + final List<ConfigurationListener> listeners = fileChangeToCallBack.get(id); + if (CollectionUtils.isEmpty(listeners)) { + LOGGER.debug("No file listeners for file '{}', id '{}'.", pFile, id); + return; + } + for (final ConfigurationListener configurationListener : listeners) { + final Class<? extends BasicConfiguration> configClass = configurationListener.getType(); + final BasicConfiguration basicConfiguration; + try { + basicConfiguration = yamlToObjectConverter.convert(pFile.getAbsolutePath(), configClass); + } catch (final YamlConversionException e) { + LOGGER.warn(EcompLoggerErrorCode.SCHEMA_ERROR, "Configuration", "Configuration", + "Cannot update the listeners for file Change since the file content is invalid: {}", e.getLocalizedMessage()); + continue; + } + LOGGER.debug("Loaded configuration after converting is {}", basicConfiguration); + configurationListener.getCallBack().reconfigure(basicConfiguration); + } + LOGGER.debug("File {} was changed.", pFile); + } + + 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); + } + result = name.substring(startIndex, endIndex); + } + return result; + } + + public void register(String id, ConfigurationListener configurationListener) { + if (configurationListener != null) { + synchronized (lock) { + List<ConfigurationListener> callbacks = fileChangeToCallBack.get(id); + if (callbacks == null) { + callbacks = new ArrayList<>(); + fileChangeToCallBack.put(id, callbacks); + } + callbacks.add(configurationListener); + } + } + } } 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 79a78828e8..7c665c61cd 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. @@ -17,90 +17,81 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.impl; +import java.io.File; import org.apache.commons.jci.monitor.FilesystemAlterationMonitor; import org.openecomp.sdc.common.api.ConfigurationSource; -import java.io.File; - /** - * * Save the - * - * @author esofer * + * @author esofer */ public class ExternalConfiguration { - 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; - } - } - } - + 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 3820f2c26c..cbb2de7dbc 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. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.common.impl; import java.util.Arrays; @@ -33,75 +32,60 @@ import org.openecomp.sdc.exception.YamlConversionException; /** * Read configuration from file system - * - * @author esofer * + * @author esofer */ public class FSConfigurationSource implements ConfigurationSource { private final YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - private final ConfigFileChangeListener changeListener; private final String 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(final Class<T> className, final ConfigurationListener configurationListener) { - - final String configFileName = calculateFileName(className); - - T object; - try { - object = yamlToObjectConverter.convert(this.appConfigDir, className, configFileName); - } catch (final YamlConversionException e) { - final String errorMsg = - String.format("Could not load '%s' in '%s' for class '%s'", configFileName, appConfigDir, className); - throw new LoadConfigurationException(errorMsg, e); - } - - if (configurationListener != null && changeListener != null) { - changeListener.register(configFileName, configurationListener); - } - - return object; - } - - public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { - - String configFileName = calculateFileName(className); - - if (configurationListener != null) { - changeListener.register(configFileName, configurationListener); - } - - } + public FSConfigurationSource(ConfigFileChangeListener changeListener, String appConfigDir) { + super(); + this.changeListener = changeListener; + this.appConfigDir = appConfigDir; + } - /** - * 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})"); + return Arrays.stream(words).map(String::toLowerCase) + .collect(Collectors.collectingAndThen(Collectors.joining("-"), str -> str + Constants.YAML_SUFFIX)); + } - return Arrays.stream(words) - .map(String::toLowerCase) - .collect(Collectors.collectingAndThen( - Collectors.joining("-"), - str -> str + Constants.YAML_SUFFIX) - ); + /* + * 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(final Class<T> className, final ConfigurationListener configurationListener) { + final String configFileName = calculateFileName(className); + T object; + try { + object = yamlToObjectConverter.convert(this.appConfigDir, className, configFileName); + } catch (final YamlConversionException e) { + final String errorMsg = String.format("Could not load '%s' in '%s' for class '%s'", configFileName, appConfigDir, className); + throw new LoadConfigurationException(errorMsg, e); + } + if (configurationListener != null && changeListener != null) { + changeListener.register(configFileName, configurationListener); + } + return object; } + public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) { + String configFileName = calculateFileName(className); + if (configurationListener != null) { + changeListener.register(configFileName, configurationListener); + } + } } 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 3b88ff8978..36a16e3f0d 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. @@ -17,51 +17,52 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.impl; +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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; -import java.util.*; public final class MutableHttpServletRequest extends HttpServletRequestWrapper { - // holds custom header and value mapping - private final Map<String, String> customHeaders; - - public MutableHttpServletRequest(HttpServletRequest request) { - super(request); - this.customHeaders = new HashMap<>(); - } - - 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); + // holds custom header and value mapping + private final Map<String, String> customHeaders; - if (headerValue != null) { - return headerValue; - } - // else return from into the original wrapped object - return ((HttpServletRequest) getRequest()).getHeader(name); - } + public MutableHttpServletRequest(HttpServletRequest request) { + super(request); + this.customHeaders = new HashMap<>(); + } - public Enumeration<String> getHeaderNames() { - // create a set of the custom header names - Set<String> set = new HashSet<>(customHeaders.keySet()); + public void putHeader(String name, String value) { + this.customHeaders.put(name, value); + } - // 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); - } + 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); + } - // create an enumeration from the set and return - return Collections.enumeration(set); - } + 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); + } + // 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 a4fc1b520e..1b0757fd39 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. @@ -17,64 +17,57 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.jsongraph.util; 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 65cf7161d4..29a0e2a053 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. @@ -17,50 +17,48 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.kpi.api; import org.openecomp.sdc.common.log.wrappers.Logger; public class ASDCKpiApi { - 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."); + 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 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 f5325a73e1..70a94fd460 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. @@ -17,18 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.listener; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; -import org.openecomp.sdc.common.log.wrappers.Logger; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -36,92 +26,75 @@ import java.util.HashMap; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.Manifest; +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.log.wrappers.Logger; public class AppContextListener implements ServletContextListener { - private static Logger log = Logger.getLogger(AppContextListener.class.getName()); - - public void contextInitialized(ServletContextEvent context) { - - log.debug("ServletContextListener initialized "); - - log.debug("After read values from Manifest {}", 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); - - 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); - - context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource); - - ExternalConfiguration.setConfigurationSource(configurationSource); - - ExternalConfiguration.listenForChanges(); - - } - - public void contextDestroyed(ServletContextEvent context) { - - log.debug("ServletContextListener destroyed"); - ExternalConfiguration.stopListenForFileChanges(); - } - - private String setAndGetAttributeInContext(ServletContextEvent context, Map<String, String> manifestAttr, - String attr) { - - String name = manifestAttr.get(attr); - if (name != null) { - context.getServletContext().setAttribute(attr, name); - } - - return name; - } - - public static Map<String, String> getManifestInfo(ServletContext application) { - - Map<String, String> result = new HashMap<>(); - InputStream inputStream = null; - try { - - inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF"); - - Manifest manifest = new Manifest(inputStream); - - 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); - } - - } catch (IOException e) { - - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (IOException e) { - log.info("close FileOutputStream failed - {}" , e); - } - } - } - - return result; - - } - + private static Logger log = Logger.getLogger(AppContextListener.class.getName()); + + public void contextInitialized(ServletContextEvent context) { + log.debug("ServletContextListener initialized "); + log.debug("After read values from Manifest {}", 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); + 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); + context.getServletContext().setAttribute(Constants.CONFIGURATION_SOURCE_ATTR, configurationSource); + ExternalConfiguration.setConfigurationSource(configurationSource); + ExternalConfiguration.listenForChanges(); + } + + public void contextDestroyed(ServletContextEvent context) { + log.debug("ServletContextListener destroyed"); + ExternalConfiguration.stopListenForFileChanges(); + } + + private String setAndGetAttributeInContext(ServletContextEvent context, Map<String, String> manifestAttr, String attr) { + String name = manifestAttr.get(attr); + if (name != null) { + context.getServletContext().setAttribute(attr, name); + } + return name; + } + + public static Map<String, String> getManifestInfo(ServletContext application) { + Map<String, String> result = new HashMap<>(); + InputStream inputStream = null; + try { + inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF"); + Manifest manifest = new Manifest(inputStream); + 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); + } + } catch (IOException e) { + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + log.info("close FileOutputStream failed - {}", e); + } + } + } + return result; + } } 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 index b51d7f1ba9..82bf295762 100644 --- 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 @@ -1,15 +1,19 @@ package org.openecomp.sdc.common.log.interceptors; -import org.apache.http.*; +import java.io.IOException; +import java.net.URI; +import org.apache.http.HttpException; +import org.apache.http.HttpMessage; +import org.apache.http.HttpRequest; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.HttpResponse; 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 { +public class ApacheClientLogRequestInterceptor extends AbstractMetricLogFilter<HttpRequest, HttpResponse, HttpMessage> implements + HttpRequestInterceptor { private String previousInvocationId; @@ -51,7 +55,6 @@ public class ApacheClientLogRequestInterceptor extends AbstractMetricLogFilter<H LogFieldsMdcHandler.getInstance().setKeyInvocationId(previousInvocationId); } - @Override public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { previousInvocationId = LogFieldsMdcHandler.getInstance().getKeyInvocationId(); 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 index d7f8b952f0..26c7c2540b 100644 --- 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 @@ -1,15 +1,17 @@ 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; +import org.apache.http.HttpException; +import org.apache.http.HttpMessage; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.HttpResponseInterceptor; +import org.apache.http.protocol.HttpContext; +import org.onap.logging.filter.base.AbstractMetricLogFilter; -public class ApacheClientLogResponseInterceptor extends AbstractMetricLogFilter<HttpRequest, HttpResponse, HttpMessage> implements HttpResponseInterceptor { +public class ApacheClientLogResponseInterceptor extends AbstractMetricLogFilter<HttpRequest, HttpResponse, HttpMessage> implements + HttpResponseInterceptor { @Override protected void addHeader(HttpMessage httpMessage, String s, String s1) { 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 index 925701eab4..5468e63a78 100644 --- 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 @@ -1,4 +1,5 @@ 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 c0cb7829cd..670ce991e5 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. @@ -17,123 +17,122 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.monitoring; - import java.util.Formatter; import java.util.Locale; public class MonitoringEvent { - 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); - } + 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 a7230c51e8..ad94664486 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. @@ -17,194 +17,184 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.monitoring; -import org.hyperic.sigar.FileSystem; -import org.hyperic.sigar.Sigar; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.management.MBeanServer; -import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadMXBean; import java.util.HashMap; import java.util.Map; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import org.hyperic.sigar.FileSystem; +import org.hyperic.sigar.Sigar; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MonitoringMetricsFetcher { - 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", 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", 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", 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", 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", 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", 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", 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", 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", 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", 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 89a9e24dff..951d923916 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. @@ -17,91 +17,79 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.rest.api; 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 6703b91a60..a872f867c7 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. @@ -17,78 +17,68 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.rest.impl.validator; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.MediaType; -import java.util.List; -import java.util.Map; - public class RequestHeadersValidator { - private static Logger log = Logger.getLogger(RequestHeadersValidator.class.getName()); - - 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); - } - } - - 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); - } - } - - } - - 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"); - } - // calculate MD5 on the data - String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(encodedData); - byte[] encodedMd5 = Base64.encodeBase64(md5.getBytes()); + private static Logger log = Logger.getLogger(RequestHeadersValidator.class.getName()); - // read the Content-MD5 header - String origMd5 = request.getHeader(Constants.MD5_HEADER); - if ((origMd5 == null) || origMd5.isEmpty()) { - throw new RestRequestValidationException("missing Content-MD5 header "); - } + 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); + } + } - // verify MD5 value - if (!origMd5.equals(new String(encodedMd5))) { - throw new RestRequestValidationException("uploaded file failed MD5 validation"); - } - headersMap.put(Constants.MD5_HEADER, origMd5); - } + 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); + } + } + } + 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"); + } + // 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 "); + } + // 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 90ed39e1c2..e1f245058d 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. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.rest.impl.validator; public class RestRequestValidationException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1962654783383591672L; - - public RestRequestValidationException(String message) { - super(message); - } + /** + * + */ + private static final long serialVersionUID = 1962654783383591672L; + 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 9fbf4ca416..658f0955b2 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.servlets; import com.google.gson.Gson; @@ -26,5 +25,4 @@ import com.google.gson.GsonBuilder; public abstract class BasicServlet { protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - } 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 9faaaf9931..e8774923a9 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. @@ -17,34 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.test; +import java.io.File; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; 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); + protected static ConfigurationManager configurationManager; + protected static String componentName; + protected static String confPath; - configurationManager.getConfiguration().setJanusGraphInMemoryGraph(true); - - } - + 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 cb78b8ed9b..6ca11810e4 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. @@ -17,30 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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"); + // @formatter:off + 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"); + // @formatter:on - private String capabilityName; + private String capabilityName; - private 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 d82538a355..e75c9bf3dd 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. @@ -17,16 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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; @@ -34,182 +26,174 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +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.slf4j.MDC; public class GeneralUtility { - 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(); + 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); } - 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() % 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 <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; - } + /** + * @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); + } - 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 String + * @return String is null or Empty + */ + public static boolean isEmptyString(String str) { + return str == null || str.trim().isEmpty(); + } - 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); - } + public static String getEcompRequestId() { + return MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + } - 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); - } + public static <T extends ICategorizedElement> Map<String, Map<String, List<T>>> getCategorizedComponents(List<T> components) { + Map<String, Map<String, List<T>>> categorizedMap = new HashMap<>(); + components.forEach(component -> categorizeComponent(component, categorizedMap)); + return categorizedMap; + } - private static <T extends ICategorizedElement> void putComponentToMap(T component, Map<String, Map<String, List<T>>> categorizedMap, - String category, String subCategory) { + 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); + } + } - Map<String, List<T>> categoryMap = categorizedMap.computeIfAbsent(category, k -> new HashMap<>()); - List<T> subCategoryList = categoryMap.computeIfAbsent(subCategory, k -> new ArrayList<>()); - subCategoryList.add(component); - } + 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); + } + 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) { + 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 882422ba4a..19ce1e9c2b 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. @@ -17,20 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonFactory { - private static Gson gson = null; - public static synchronized Gson getGson() { - if (gson == null) { - gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); - } + private static Gson gson = null; - return gson; - } + public static synchronized Gson getGson() { + if (gson == null) { + gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); + } + 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 00a03de7cf..f530fd399d 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. @@ -17,22 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; -import org.apache.commons.collections.CollectionUtils; -import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.log.wrappers.Logger; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; import java.util.ArrayList; import java.util.Collection; import java.util.List; - -import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.log.wrappers.Logger; 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; @@ -43,20 +42,16 @@ public class HealthCheckUtil { break; } } - return status; } public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos) { - StringBuilder sb = new StringBuilder(); healthCheckInfos.forEach(x -> { if (x.getHealthCheckStatus() == DOWN) { sb.append("Component ").append(x.getHealthCheckComponent()).append(" is Down, "); } }); - return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : ""; } - } 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 c9086fc272..e7fc0b970f 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. @@ -17,95 +17,72 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; -import org.apache.commons.lang3.StringEscapeUtils; - -import javax.swing.text.html.HTML; -import javax.swing.text.html.HTML.Tag; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTML.Tag; +import org.apache.commons.lang3.StringEscapeUtils; public class HtmlCleaner { - private static Set<String> htmlTags = new HashSet<>(); - - private static String patternHtmlFullTagStr = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[\\^'\">\\s]+))?)+\\s*|\\s*)/?>"; - - private static String patternHtmlTagOnlyStr = "</?(\\w+)[^>]*/?>"; - - private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); - - private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); - - static { - Tag[] allTags = HTML.getAllTags(); - for (Tag tag : allTags) { - htmlTags.add(tag.toString().toLowerCase()); - } - } - - public static String stripHtml(String input) { - - return stripHtml(input, false); - - } - - public static String stripHtml(String input, boolean toEscape) { - - if (input == null || input.isEmpty()) { - return input; - } - - Matcher matcher = onlyTagPattern.matcher(input); - - Set<String> tagsToRemove = new HashSet<>(); - - while (matcher.find()) { - - int start = matcher.start(); - int end = matcher.end(); - - String matchTag = input.substring(start, end); - - 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); - } - } - } - } - - String stripHtmlStr = removeTagsFromString(tagsToRemove, input); - - if (stripHtmlStr != null) { - if (toEscape) { - stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); - } - } - - return stripHtmlStr; - - } - - private static String removeTagsFromString(Set<String> tagsToRemove, String input) { - - String stripStr = input; - if (input == null || tagsToRemove.isEmpty()) { - return input; - } - - for (String tag : tagsToRemove) { - stripStr = stripStr.replaceAll(tag, ""); - } - return stripStr; - } - + private static Set<String> htmlTags = new HashSet<>(); + private static String patternHtmlFullTagStr = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[\\^'\">\\s]+))?)+\\s*|\\s*)/?>"; + private static String patternHtmlTagOnlyStr = "</?(\\w+)[^>]*/?>"; + private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); + private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); + + static { + Tag[] allTags = HTML.getAllTags(); + for (Tag tag : allTags) { + htmlTags.add(tag.toString().toLowerCase()); + } + } + + public static String stripHtml(String input) { + return stripHtml(input, false); + } + + public static String stripHtml(String input, boolean toEscape) { + if (input == null || input.isEmpty()) { + return input; + } + Matcher matcher = onlyTagPattern.matcher(input); + Set<String> tagsToRemove = new HashSet<>(); + while (matcher.find()) { + int start = matcher.start(); + int end = matcher.end(); + String matchTag = input.substring(start, end); + 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); + } + } + } + } + String stripHtmlStr = removeTagsFromString(tagsToRemove, input); + if (stripHtmlStr != null) { + if (toEscape) { + stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); + } + } + return stripHtmlStr; + } + + private static String removeTagsFromString(Set<String> tagsToRemove, String input) { + String stripStr = input; + if (input == null || tagsToRemove.isEmpty()) { + return input; + } + 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 d9f099876a..f23a1e7e61 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. @@ -17,63 +17,60 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; - -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; 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; - - } - /** - * 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); - } + 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; + } - 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); + } + 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 index 0121af702a..822bb3dbc1 100644 --- 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 @@ -1,7 +1,5 @@ package org.openecomp.sdc.common.util; -import java.util.List; - public interface ICategorizedElement { String getComponentTypeAsString(); @@ -9,7 +7,4 @@ public interface ICategorizedElement { 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 fbf94eaaed..6ee4984b9f 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import com.google.gson.JsonElement; @@ -25,38 +24,34 @@ import com.google.gson.JsonObject; public class JsonUtils { - public static String toString(JsonElement jsonElement) { - - if (jsonElement == null) { - 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 isEmptyJson(JsonObject json) { - return json.entrySet().isEmpty(); - } - - 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 String toString(JsonElement jsonElement) { + if (jsonElement == null) { + 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 isEmptyJson(JsonObject json) { + return json.entrySet().isEmpty(); + } + + 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); + } } 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 bba04fa359..7d9d3ec660 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. @@ -17,9 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; -public enum MethodActivationStatusEnum { - SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; -} +public enum MethodActivationStatusEnum {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 eb6c29ce4a..a7c469f774 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. @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - import java.util.List; import java.util.stream.Collectors; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; public class PairUtils { @@ -35,5 +33,4 @@ public class PairUtils { public static <L, R> List<R> rightSequence(List<Pair<L, R>> pairs) { return pairs.stream().map(Pair::getRight).collect(Collectors.toList()); } - } 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 cf49718600..1db1c86bff 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. @@ -17,63 +17,63 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import fj.data.Either; +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 org.nustaq.serialization.FSTConfiguration; 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.*; - public class SerializationUtils { - private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); - - private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); - - 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); - } - } - - public static Either<Object, Boolean> deserialize(byte[] bytes) { + private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); + private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); - 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> 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); + } + } - 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<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); + } + } - 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 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); + } + } } 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 2d07069388..37769fbaef 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import java.util.ArrayList; @@ -31,70 +30,69 @@ import java.util.stream.StreamSupport; /** * Utility Class For Actions On Streams - * - * @author mshitrit * + * @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> { - 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 public void accept(T t) { @@ -102,34 +100,33 @@ public final class StreamUtils { if (stillGoing) { action.accept(t); } - } }; - } - - } - - 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; - } - - } - + } + } + + 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 e14c98ee8f..1aa6bc07b8 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import org.openecomp.sdc.common.api.FilterDecisionEnum; @@ -25,72 +24,78 @@ import org.openecomp.sdc.common.datastructure.UserContext; public class ThreadLocalsHolder { - 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; - } - }; - - - private static final ThreadLocal<UserContext> userContextThreadLocal = new ThreadLocal<>(); - - public static final UserContext getUserContext() {return userContextThreadLocal.get(); } + 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; + } + }; + private static final ThreadLocal<UserContext> userContextThreadLocal = new ThreadLocal<>(); + + public static final UserContext getUserContext() { + return userContextThreadLocal.get(); + } - public static void setUserContext(UserContext userContext) {userContextThreadLocal.set(userContext); } + public static void setUserContext(UserContext userContext) { + userContextThreadLocal.set(userContext); + } - public static void setMdcProcessed(Boolean isMdcProcessed) { - isMdcProcessedThreadLocal.set(isMdcProcessed); - } + public static void setMdcProcessed(Boolean isMdcProcessed) { + isMdcProcessedThreadLocal.set(isMdcProcessed); + } - public static void setUuid(String uuid) { - uuidThreadLocal.set(uuid); - } + public static String getUuid() { + return uuidThreadLocal.get(); + } - public static void setRequestStartTime(Long requestStartTime) { - requestStartTimeThreadLocal.set(requestStartTime); - } + public static void setUuid(String uuid) { + uuidThreadLocal.set(uuid); + } - public static String getUuid() { - return uuidThreadLocal.get(); - } + public static Long getRequestStartTime() { + return requestStartTimeThreadLocal.get(); + } - public static Long getRequestStartTime() { - return requestStartTimeThreadLocal.get(); - } + public static void setRequestStartTime(Long requestStartTime) { + requestStartTimeThreadLocal.set(requestStartTime); + } - public static Boolean isMdcProcessed() { - return isMdcProcessedThreadLocal.get(); - } + public static Boolean isMdcProcessed() { + return isMdcProcessedThreadLocal.get(); + } - public static void cleanup() { - uuidThreadLocal.remove(); - requestStartTimeThreadLocal.remove(); - isMdcProcessedThreadLocal.remove(); - userContextThreadLocal.remove(); - apiType.remove(); - } + 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 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; + if (getApiType().equals(FilterDecisionEnum.INTERNAL)) { + return true; + } else { + return false; + } } - public static boolean isExternalRequest() { - if (getApiType().equals(FilterDecisionEnum.EXTERNAL)){ - 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 1a9cb26a0f..82e1b924b6 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 @@ -17,402 +17,384 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import com.google.common.base.CharMatcher; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.text.WordUtils; import org.apache.commons.validator.routines.UrlValidator; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; -import java.util.*; -import java.util.regex.Pattern; - public class ValidationUtils { - private 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}$"); - - // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9) - 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 Pattern COMMENT_PATTERN = Pattern.compile("^[\\u0000-\\u00BF]{1,1024}$"); - public static final 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 static final Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; - public static final Integer SERVICE_TYPE_MAX_LENGTH = 256; - public static final Integer SERVICE_ROLE_MAX_LENGTH = 256; - public static final Integer SERVICE_FUNCTION_MAX_LENGTH = 256; - public static final Integer SERVICE_NAMING_POLICY_MAX_SIZE = 100; - - 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 YANG_MODULE_3GPP_PATTERN = Pattern.compile("^(_3gpp).*$"); - 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] "); - private 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]+[\\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 Pattern TAG_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,1024}$"); - - 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 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 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}$"); + // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9) + 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 Pattern COMMENT_PATTERN = Pattern.compile("^[\\u0000-\\u00BF]{1,1024}$"); + public static final 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 static final Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; + public static final Integer SERVICE_TYPE_MAX_LENGTH = 256; + public static final Integer SERVICE_ROLE_MAX_LENGTH = 256; + public static final Integer SERVICE_FUNCTION_MAX_LENGTH = 256; + public static final Integer SERVICE_NAMING_POLICY_MAX_SIZE = 100; + 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 YANG_MODULE_3GPP_PATTERN = Pattern.compile("^(_3gpp).*$"); + 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 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]+[\\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 Pattern TAG_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,1024}$"); + 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) + "}$"); + private static final Set<String> CATEGORY_CONJUNCTIONS = new HashSet<>(Arrays.asList("of", "to", "for", "as", "a", "an", "the")); + private ValidationUtils() { + } + + 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); @@ -421,8 +403,7 @@ public class ValidationUtils { sb.append(splitElement); } return sb.toString(); - - } + } public static String normalizeComponentInstanceName(String name) { String[] split = splitComponentInstanceName(name); @@ -431,20 +412,19 @@ public class ValidationUtils { sb.append(splitElement); } 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); @@ -456,144 +436,135 @@ public class ValidationUtils { return sb.toString(); } - public static String normalizeFileName(String filename) { - 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("-"); - if (!YANG_MODULE_3GPP_PATTERN.matcher(str).matches()) - 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(); - - 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(); - } - - public static String sanitizeInputString(String input) { - if (StringUtils.isNotEmpty(input)) { - input = ValidationUtils.removeNoneUtf8Chars(input); - input = ValidationUtils.removeHtmlTags(input); - input = ValidationUtils.normaliseWhitespace(input); - input = ValidationUtils.stripOctets(input); - } - return input; - } + public static String normalizeFileName(String filename) { + 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("-"); + if (!YANG_MODULE_3GPP_PATTERN.matcher(str).matches()) { + 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(); + 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(); + } + + public static String sanitizeInputString(String input) { + if (StringUtils.isNotEmpty(input)) { + input = ValidationUtils.removeNoneUtf8Chars(input); + input = ValidationUtils.removeHtmlTags(input); + input = ValidationUtils.normaliseWhitespace(input); + input = ValidationUtils.stripOctets(input); + } + return input; + } } 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 92f633dcd1..2475b77705 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.util; import java.io.ByteArrayInputStream; @@ -53,160 +52,127 @@ import org.yaml.snakeyaml.introspector.PropertyUtils; public class YamlToObjectConverter { - private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); - - private static HashMap<String, Yaml> yamls = new HashMap<>(); - - private static Yaml defaultYaml = new Yaml(); - - 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); - - // 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); - - // 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(final String dirPath, final Class<T> className, - final String configFileName) throws YamlConversionException { - if (className == null) { - throw new IllegalArgumentException("className cannot be null"); - } - final String fullFileName = dirPath + File.separator + configFileName; - return convert(fullFileName, className); - } - - public <T> T convert(String fullFileName, Class<T> className) throws YamlConversionException { - final File file = new File(fullFileName); - if (!file.exists() || file.isDirectory()) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","", - "The file {} cannot be found. Ignore reading configuration.", fullFileName); - return null; - } - - final Yaml yaml = getYamlByClassName(className); - - try (final InputStream in = Files.newInputStream(Paths.get(fullFileName))) { - return yaml.loadAs(in, className); - } catch (final IOException e) { - log.debug("Failed to open/close input stream", e); - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","", - "Failed to convert yaml file {} to object.", fullFileName, e); - final String errorMsg = String.format("Could not parse '%s' to class '%s'", fullFileName, className); - throw new YamlConversionException(errorMsg, e); - } - - return null; - } - - public <T> T convert(byte[] fileContents, Class<T> className) { - final Yaml yaml = getYamlByClassName(className); - - try (final InputStream in = new ByteArrayInputStream(fileContents)){ - return yaml.loadAs(in, className); - } catch (final IOException e) { - log.debug("Failed to open or close input stream", e); - } catch (final Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, - "","","Failed to convert yaml file to object", e); - } - - return null; - } - - 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; - } + private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); + private static HashMap<String, Yaml> yamls = new HashMap<>(); + private static Yaml defaultYaml = new Yaml(); + + 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); + // 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); + // 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(final String dirPath, final Class<T> className, final String configFileName) throws YamlConversionException { + if (className == null) { + throw new IllegalArgumentException("className cannot be null"); + } + final String fullFileName = dirPath + File.separator + configFileName; + return convert(fullFileName, className); + } + + public <T> T convert(String fullFileName, Class<T> className) throws YamlConversionException { + final File file = new File(fullFileName); + if (!file.exists() || file.isDirectory()) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "The file {} cannot be found. Ignore reading configuration.", fullFileName); + return null; + } + final Yaml yaml = getYamlByClassName(className); + try (final InputStream in = Files.newInputStream(Paths.get(fullFileName))) { + return yaml.loadAs(in, className); + } catch (final IOException e) { + log.debug("Failed to open/close input stream", e); + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", fullFileName, e); + final String errorMsg = String.format("Could not parse '%s' to class '%s'", fullFileName, className); + throw new YamlConversionException(errorMsg, e); + } + return null; + } + + public <T> T convert(byte[] fileContents, Class<T> className) { + final Yaml yaml = getYamlByClassName(className); + try (final InputStream in = new ByteArrayInputStream(fileContents)) { + return yaml.loadAs(in, className); + } catch (final IOException e) { + log.debug("Failed to open or close input stream", e); + } catch (final Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object", e); + } + return null; + } + + 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/common/zip/ZipUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/zip/ZipUtils.java index 25f85badef..4cf731cdbe 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/zip/ZipUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/zip/ZipUtils.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.zip; import java.io.BufferedOutputStream; @@ -55,6 +54,7 @@ public class ZipUtils { /** * Checks if the path is a zip slip attempt calling the {@link #checkForZipSlipInRead(Path)} method. + * * @param zipEntry the zip entry * @throws ZipSlipException when a zip slip attempt is detected */ @@ -64,8 +64,7 @@ public class ZipUtils { } /** - * Checks if the path is a zip slip attempt when you don't have a destination folder eg in memory reading or zip - * creation. + * Checks if the path is a zip slip attempt when you don't have a destination folder eg in memory reading or zip creation. * * @param filePath the file path * @throws ZipSlipException when a zip slip attempt is detected @@ -81,7 +80,6 @@ public class ZipUtils { if (canonicalPath != null && !canonicalPath.equals(file.getAbsolutePath())) { throw new ZipSlipException(filePath.toString()); } - if (filePath.toString().contains("../") || filePath.toString().contains("..\\")) { throw new ZipSlipException(filePath.toString()); } @@ -90,30 +88,26 @@ public class ZipUtils { /** * Checks if the zip entry is a zip slip attempt based on the destination directory. * - * @param zipEntry the zip entry + * @param zipEntry the zip entry * @param targetDirectoryPath the target extraction folder - * @throws ZipException when the zip slip was detected as a {@link ZipSlipException}. Also when there was a problem - * getting the canonical paths from the zip entry or target directory. + * @throws ZipException when the zip slip was detected as a {@link ZipSlipException}. Also when there was a problem getting the canonical paths + * from the zip entry or target directory. */ - public static void checkForZipSlipInExtraction(final ZipEntry zipEntry, - final Path targetDirectoryPath) throws ZipException { + public static void checkForZipSlipInExtraction(final ZipEntry zipEntry, final Path targetDirectoryPath) throws ZipException { final File targetDirectoryAsFile = targetDirectoryPath.toFile(); final File targetFile = new File(targetDirectoryAsFile, zipEntry.getName()); final String targetDirectoryCanonicalPath; try { targetDirectoryCanonicalPath = targetDirectoryAsFile.getCanonicalPath(); } catch (final IOException e) { - throw new ZipException( - String.format("Could not obtain canonical path of: '%s'", targetDirectoryAsFile.getAbsolutePath()), e); + throw new ZipException(String.format("Could not obtain canonical path of: '%s'", targetDirectoryAsFile.getAbsolutePath()), e); } final String targetFileCanonicalPath; try { targetFileCanonicalPath = targetFile.getCanonicalPath(); } catch (final IOException e) { - throw new ZipException( - String.format("Could not obtain canonical path of: '%s'", targetFile.getAbsolutePath()), e); + throw new ZipException(String.format("Could not obtain canonical path of: '%s'", targetFile.getAbsolutePath()), e); } - if (!targetFileCanonicalPath.startsWith(targetDirectoryCanonicalPath + File.separator)) { throw new ZipSlipException(zipEntry.getName()); } @@ -132,13 +126,12 @@ public class ZipUtils { /** * Reads a zip file into memory. Parses the zipFile in byte array and calls {@link #readZip(byte[], boolean)}. * - * @param zipFile the zip file to read + * @param zipFile the zip file to read * @param hasToIncludeDirectories includes or not the directories found during the zip reading * @return a Map representing a pair of file path and file byte array * @throws ZipException when there was a problem during the reading process */ - public static Map<String, byte[]> readZip(final File zipFile, - final boolean hasToIncludeDirectories) throws ZipException { + public static Map<String, byte[]> readZip(final File zipFile, final boolean hasToIncludeDirectories) throws ZipException { try { return readZip(Files.readAllBytes(zipFile.toPath()), hasToIncludeDirectories); } catch (final IOException e) { @@ -147,9 +140,9 @@ public class ZipUtils { } /** - * Reads a zip file to a in memory structure formed by the file path and its bytes. The structure can contains only - * files or files and directories. If configured to include directories, only empty directories and directories that - * contains files will be included. The full directory tree will not be generated, eg: + * Reads a zip file to a in memory structure formed by the file path and its bytes. The structure can contains only files or files and + * directories. If configured to include directories, only empty directories and directories that contains files will be included. The full + * directory tree will not be generated, eg: * <pre> * \ * \..\Directory @@ -157,33 +150,27 @@ public class ZipUtils { * \..\..\..\aFile.txt * \..\..\EmptyChildDirectory * </pre> - * The return will include "Directory\ChildDirectory\aFile.txt" and "Directory\EmptyChildDirectory" but not - * "Directory" or the root. + * The return will include "Directory\ChildDirectory\aFile.txt" and "Directory\EmptyChildDirectory" but not "Directory" or the root. * - * @param zipFileBytes the zip file byte array to read + * @param zipFileBytes the zip file byte array to read * @param hasToIncludeDirectories includes or not the directories found during the zip reading. * @return a Map representing a pair of file path and file byte array * @throws ZipException when there was a problem during the reading process */ - public static Map<String, byte[]> readZip(final byte[] zipFileBytes, - final boolean hasToIncludeDirectories) throws ZipException { + public static Map<String, byte[]> readZip(final byte[] zipFileBytes, final boolean hasToIncludeDirectories) throws ZipException { final Map<String, byte[]> filePathAndByteMap = new HashMap<>(); - try (final ZipInputStream inputZipStream = ZipUtils.getInputStreamFromBytes(zipFileBytes)) { ZipEntry zipEntry; while ((zipEntry = inputZipStream.getNextEntry()) != null) { - filePathAndByteMap - .putAll(processZipEntryInRead(zipEntry, getBytes(inputZipStream), hasToIncludeDirectories)); + filePathAndByteMap.putAll(processZipEntryInRead(zipEntry, getBytes(inputZipStream), hasToIncludeDirectories)); } } catch (final IOException e) { LOGGER.warn("Could not close the zip input stream", e); } - return filePathAndByteMap; } - private static Map<String, byte[]> processZipEntryInRead(final ZipEntry zipEntry, - final byte[] inputStreamBytes, + private static Map<String, byte[]> processZipEntryInRead(final ZipEntry zipEntry, final byte[] inputStreamBytes, final boolean hasToIncludeDirectories) throws ZipException { final Map<String, byte[]> filePathAndByteMap = new HashMap<>(); checkForZipSlipInRead(zipEntry); @@ -193,7 +180,6 @@ public class ZipUtils { } return filePathAndByteMap; } - if (hasToIncludeDirectories) { final Path parentFolderPath = Paths.get(zipEntry.getName()).getParent(); if (parentFolderPath != null) { @@ -201,7 +187,6 @@ public class ZipUtils { } } filePathAndByteMap.put(zipEntry.getName(), inputStreamBytes); - return filePathAndByteMap; } @@ -213,7 +198,7 @@ public class ZipUtils { */ private static String normalizeFolder(final String folderPath) { final StringBuilder normalizedFolderBuilder = new StringBuilder(folderPath); - if(!folderPath.endsWith(File.separator)) { + if (!folderPath.endsWith(File.separator)) { normalizedFolderBuilder.append(File.separator); } return normalizedFolderBuilder.toString(); @@ -239,7 +224,7 @@ public class ZipUtils { /** * Unzips a zip file into an output folder. * - * @param zipFilePath the zip file path + * @param zipFilePath the zip file path * @param outputFolder the output folder path * @throws ZipException when there was a problem during the unzip process */ @@ -248,11 +233,9 @@ public class ZipUtils { return; } createDirectoryIfNotExists(outputFolder); - final File zipFile = zipFilePath.toFile(); - try (final FileInputStream fileInputStream = new FileInputStream(zipFile); - final ZipInputStream stream = new ZipInputStream(fileInputStream)) { - + try (final FileInputStream fileInputStream = new FileInputStream(zipFile); final ZipInputStream stream = new ZipInputStream( + fileInputStream)) { ZipEntry zipEntry; while ((zipEntry = stream.getNextEntry()) != null) { checkForZipSlipInExtraction(zipEntry, outputFolder); @@ -267,14 +250,14 @@ public class ZipUtils { } catch (final FileNotFoundException e) { throw new ZipException(String.format("Could not find file: '%s'", zipFile.getAbsolutePath()), e); } catch (final IOException e) { - throw new ZipException( - String.format("An unexpected error occurred trying to unzip '%s'", zipFile.getAbsolutePath()), e); + throw new ZipException(String.format("An unexpected error occurred trying to unzip '%s'", zipFile.getAbsolutePath()), e); } } /** * Writes a file from a zipInputStream to a path. Creates the file parent directories if they don't exist. - * @param zipInputStream the zip input stream + * + * @param zipInputStream the zip input stream * @param fileToWritePath the file path to write * @throws ZipException when there was a problem during the file creation */ @@ -284,8 +267,7 @@ public class ZipUtils { try { Files.createDirectories(parentFolderPath); } catch (final IOException e) { - throw new ZipException( - String.format("Could not create parent directories of '%s'", fileToWritePath.toString()), e); + throw new ZipException(String.format("Could not create parent directories of '%s'", fileToWritePath.toString()), e); } } try (final FileOutputStream outputStream = new FileOutputStream(fileToWritePath.toFile())) { @@ -293,9 +275,7 @@ public class ZipUtils { } catch (final FileNotFoundException e) { throw new ZipException(String.format("Could not find file '%s'", fileToWritePath.toString()), e); } catch (final IOException e) { - throw new ZipException( - String.format("An unexpected error has occurred while writing file '%s'", fileToWritePath.toString()) - , e); + throw new ZipException(String.format("An unexpected error has occurred while writing file '%s'", fileToWritePath.toString()), e); } } @@ -306,7 +286,7 @@ public class ZipUtils { * @throws ZipException when there was a problem to create the directories */ private static void createDirectoryIfNotExists(final Path path) throws ZipException { - if(path.toFile().exists()) { + if (path.toFile().exists()) { return; } try { @@ -319,7 +299,7 @@ public class ZipUtils { /** * Zips a directory and its children content. * - * @param fromPath the directory path to zip + * @param fromPath the directory path to zip * @param toZipFilePath the path to the zip file that will be created * @throws ZipException when there was a problem during the zip process */ @@ -330,11 +310,9 @@ public class ZipUtils { } catch (final IOException e) { throw new ZipException(String.format("Could not create file '%s'", toZipFilePath.toString()), e); } - - try(final FileOutputStream fileOutputStream = new FileOutputStream(createdZipFilePath.toFile()); - final BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream); - final ZipOutputStream zipOut = new ZipOutputStream(bos); - final Stream<Path> walkStream = Files.walk(fromPath)) { + try (final FileOutputStream fileOutputStream = new FileOutputStream( + createdZipFilePath.toFile()); final BufferedOutputStream bos = new BufferedOutputStream( + fileOutputStream); final ZipOutputStream zipOut = new ZipOutputStream(bos); final Stream<Path> walkStream = Files.walk(fromPath)) { final Set<Path> allFilesSet = walkStream.collect(Collectors.toSet()); for (final Path path : allFilesSet) { checkForZipSlipInRead(path); @@ -357,5 +335,4 @@ public class ZipUtils { throw new ZipException("An error has occurred while creating the zip package", e); } } - } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipException.java index 414b4823ad..393617ef2a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.zip.exception; public class ZipException extends Exception { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipSlipException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipSlipException.java index 203e357f8f..7fb75210d8 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipSlipException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/zip/exception/ZipSlipException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.zip.exception; public class ZipSlipException extends ZipException { 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 75315a06cc..12412a56a0 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 @@ -17,108 +17,99 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.GeneralUtility; public abstract class AbstractSdncException { - 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; - } - + 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 ec33b69d82..061681c2fd 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. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 6957e960c3..a22e43ff41 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. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; /** - * This exception should be thrown when attempting to delete an object in Alien - * which is still referenced (used) by other object + * This exception should be thrown when attempting to delete an object in Alien which is still referenced (used) by other object * * @author Minh Khang VU */ public class DeleteReferencedObjectException extends TechnicalException { - private static final long serialVersionUID = 1L; - public DeleteReferencedObjectException(String message) { - super(message); - } + private static final long serialVersionUID = 1L; + + 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 5bf67484d5..15b9005c68 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. @@ -17,25 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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. - * + * 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 d8b8518919..4f20051df9 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. @@ -17,23 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 ef6cd659e4..9f4058e505 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. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; public class InvalidArgumentException extends TechnicalException { - private static final long serialVersionUID = 931646037604062840L; - public InvalidArgumentException(String message, Throwable cause) { - super(message, cause); - } + private static final long serialVersionUID = 931646037604062840L; + + 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 988325ff3e..48c49bf546 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. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; public class NotFoundException extends TechnicalException { - private static final long serialVersionUID = -5838741067731786413L; - - public NotFoundException(String message, Throwable cause) { - super(message, cause); - } + private static final long serialVersionUID = -5838741067731786413L; - public NotFoundException(String message) { - super(message); - } + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } + 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 78405e0eb1..9a329823ef 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. @@ -17,12 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 8c5c8609b6..6b6e8c18e1 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. @@ -17,15 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 109164d07d..b0467425ec 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. @@ -17,176 +17,172 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; /** * Nested POJOs to express required JSON format of the error - * - * { "requestError": { "serviceException": { "messageId": "", "text": "", - * "variables": [] } } } - * - * - * @author paharoni + * <p> + * { "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 3aae180517..aeb8951831 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. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; public class ServiceException extends AbstractSdncException { - public ServiceException(String messageId, String text, String[] variables) { - super(messageId, text, variables); - } - - public ServiceException() { - } + public ServiceException(String messageId, String text, String[] variables) { + super(messageId, text, variables); + } + 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 96ef2f3159..7072ce4a86 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. @@ -17,24 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 a998d6393e..0de2ee1d76 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. @@ -17,17 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; /** - * Exception happens when a4c cannot resolve version conflicts in a transparent - * manner for users + * Exception happens when a4c cannot resolve version conflicts in a transparent manner for users */ public class VersionConflictException extends TechnicalException { - private static final long serialVersionUID = 1L; - public VersionConflictException(String message, Throwable cause) { - super(message, cause); - } + private static final long serialVersionUID = 1L; + + public VersionConflictException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/exception/YamlConversionException.java b/common-app-api/src/main/java/org/openecomp/sdc/exception/YamlConversionException.java index 4d8791f15d..0856eccb63 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/exception/YamlConversionException.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/exception/YamlConversionException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.exception; public class YamlConversionException extends Exception { 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 ca38a46efd..322c57ccd6 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.config; import static java.lang.String.format; @@ -50,23 +49,14 @@ public class Configuration extends BasicConfiguration { * backend http secured port */ private Integer beSslPort; - private Integer healthCheckSocketTimeoutInMs; - private Integer healthCheckIntervalInSeconds; - private List<String> healthStatusExclude; - private FeMonitoringConfig systemMonitoring; - private String onboardingForwardContext; - private OnboardingConfig onboarding; - private CookieConfig authCookie; - private BasicAuthConfig basicAuth; - private CatalogFacadeMsConfig catalogFacadeMs; /** * be http context @@ -84,7 +74,6 @@ public class Configuration extends BasicConfiguration { private int requestTimeout; private List<List<String>> identificationHeaderFields; private List<List<String>> optionalHeaderFields; - private List<String> forwardHeaderFields; public Integer getHealthCheckSocketTimeoutInMs(int defaultVal) { @@ -97,14 +86,11 @@ public class Configuration extends BasicConfiguration { @Override public String toString() { - return new StringBuilder().append(format("backend host: %s%n", beHost)) - .append(format("backend http port: %s%n", beHttpPort)) + return new StringBuilder().append(format("backend host: %s%n", beHost)).append(format("backend http port: %s%n", beHttpPort)) .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext)) - .append(format("backend protocol: %s%n", beProtocol)) - .append(format("onboarding forward context: %s%n", onboardingForwardContext)) + .append(format("backend protocol: %s%n", beProtocol)).append(format("onboarding forward context: %s%n", onboardingForwardContext)) .append(format("Version: %s%n", version)).append(format("Released: %s%n", released)) - .append(format("Connecting to database: %s%n", connection)) - .append(format("Supported protocols: %s%n", protocols)).toString(); + .append(format("Connecting to database: %s%n", connection)).append(format("Supported protocols: %s%n", protocols)).toString(); } @Getter @@ -133,7 +119,6 @@ public class Configuration extends BasicConfiguration { private String hostBe; private Integer portBe; private String healthCheckUriFe; - } @Getter @@ -145,7 +130,6 @@ public class Configuration extends BasicConfiguration { private String path = ""; private String domain = ""; private String securityKey = ""; - } @Getter @@ -156,8 +140,6 @@ public class Configuration extends BasicConfiguration { private boolean enabled = false; private String userName = ""; private String userPass = ""; - - } @Getter @@ -170,7 +152,5 @@ public class Configuration extends BasicConfiguration { private Integer port; private String healthCheckUri; private String path; - } - } 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 ed7a2e9817..0d5cf62cb1 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 @@ -17,128 +17,111 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.config; +import java.util.HashMap; +import java.util.Map; import org.openecomp.sdc.common.api.BasicConfiguration; import org.openecomp.sdc.common.api.ConfigurationListener; import org.openecomp.sdc.common.api.ConfigurationSource; 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.openecomp.sdc.common.log.wrappers.Logger; - -import java.util.HashMap; -import java.util.Map; +import org.openecomp.sdc.common.rest.api.RestConfigurationInfo; public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { - ConfigurationSource configurationSource = null; - private static ConfigurationManager instance; - - private static final Logger log = Logger.getLogger(ConfigurationManager.class.getName()); + private static final Logger log = Logger.getLogger(ConfigurationManager.class.getName()); + private static ConfigurationManager instance; + ConfigurationSource configurationSource = null; + Map<String, Object> configurations = new HashMap<>(); - public ConfigurationManager(ConfigurationSource configurationSource) { - super(); - this.configurationSource = configurationSource; - loadConfigurationFiles(); - instance = this; - } + public ConfigurationManager(ConfigurationSource configurationSource) { + super(); + this.configurationSource = configurationSource; + loadConfigurationFiles(); + instance = this; + } - Map<String, Object> configurations = new HashMap<>(); + public static ConfigurationManager getConfigurationManager() { + return instance; + } - private void loadConfigurationFiles() { + public static void setTestInstance(ConfigurationManager configurationManagerInstance) { + instance = configurationManagerInstance; + } + private void loadConfigurationFiles() { loadConfigurationClass(Configuration.class); loadConfigurationClass(RestConfigurationInfo.class); loadConfigurationClass(EcompErrorConfiguration.class); loadConfigurationClass(PluginsConfiguration.class); loadConfigurationClass(WorkspaceConfiguration.class); + } - } - - private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { - ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); - - log.info("created listener for class {}: {}", clazz.getName(), configurationListener); - - T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); - - configurations.put(getKey(clazz), object); - } - - private <T> String getKey(Class<T> class1) { - - return class1.getSimpleName(); - - } - - public Configuration getConfiguration() { - - return (Configuration) configurations.get(getKey(Configuration.class)); - - } - - public RestConfigurationInfo getRestClientConfiguration() { - - return (RestConfigurationInfo) configurations.get(getKey(RestConfigurationInfo.class)); - - } - - @Override - public EcompErrorConfiguration getEcompErrorConfiguration() { - - return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + private <T extends BasicConfiguration> void loadConfigurationClass(Class<T> clazz) { + ConfigurationListener configurationListener = new ConfigurationListener(clazz, this); + log.info("created listener for class {}: {}", clazz.getName(), configurationListener); + T object = configurationSource.getAndWatchConfiguration(clazz, configurationListener); + configurations.put(getKey(clazz), object); + } - } + private <T> String getKey(Class<T> class1) { + return class1.getSimpleName(); + } - public PluginsConfiguration getPluginsConfiguration() { + public Configuration getConfiguration() { + return (Configuration) configurations.get(getKey(Configuration.class)); + } - log.info("requested plugins configuration and got this:{}", configurations.get(getKey(PluginsConfiguration.class))); + public RestConfigurationInfo getRestClientConfiguration() { + return (RestConfigurationInfo) configurations.get(getKey(RestConfigurationInfo.class)); + } - return (PluginsConfiguration) configurations.get(getKey(PluginsConfiguration.class)); - } + @Override + public EcompErrorConfiguration getEcompErrorConfiguration() { + return (EcompErrorConfiguration) configurations.get(getKey(EcompErrorConfiguration.class)); + } + public PluginsConfiguration getPluginsConfiguration() { + log.info("requested plugins configuration and got this:{}", configurations.get(getKey(PluginsConfiguration.class))); + return (PluginsConfiguration) configurations.get(getKey(PluginsConfiguration.class)); + } public WorkspaceConfiguration getWorkspaceConfiguration() { - log.info("requested plugins configuration and got this:{}", configurations.get(getKey(WorkspaceConfiguration.class))); - return (WorkspaceConfiguration) configurations.get(getKey(WorkspaceConfiguration.class)); } - public Configuration getConfigurationAndWatch(ConfigurationListener configurationListener) { + if (configurationListener != null) { + configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + } + return (Configuration) configurations.get(getKey(Configuration.class)); + } - if (configurationListener != null) { + public void reconfigure(BasicConfiguration obj) { + // - configurationSource.addWatchConfiguration(Configuration.class, configurationListener); + // if (obj != null) { - } - return (Configuration) configurations.get(getKey(Configuration.class)); + // - } + // if (obj instanceof Configuration) { - 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); - // } - // } - } + // configurations.put(getKey(Configuration.class), obj); - public static ConfigurationManager getConfigurationManager() { - return instance; - } + // } - public static void setTestInstance(ConfigurationManager configurationManagerInstance) { - instance = configurationManagerInstance; - } + // + + // if (obj instanceof EcompErrorConfiguration) { + + // configurations.put(getKey(EcompErrorConfiguration.class), obj); + + // } + + // } + } } 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 7208398525..f9399f6132 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. @@ -17,32 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 a36293b829..2fe089c383 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. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.config; import org.openecomp.sdc.common.config.AbsEcompErrorManager; @@ -26,51 +25,49 @@ import org.openecomp.sdc.common.config.IEcompConfigurationManager; public class FeEcompErrorManager extends AbsEcompErrorManager { - private static volatile FeEcompErrorManager instance; - private static ConfigurationManager configurationManager; - - private FeEcompErrorManager() { - }; - - public static FeEcompErrorManager getInstance() { - if (instance == null) { + private static volatile FeEcompErrorManager instance; + private static ConfigurationManager configurationManager; - instance = init(); - } - return instance; - } + private FeEcompErrorManager() { + } - private static synchronized FeEcompErrorManager init() { - if (instance == null) { - instance = new FeEcompErrorManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } + public static FeEcompErrorManager getInstance() { + if (instance == null) { + instance = init(); + } + return instance; + } - @Override - public IEcompConfigurationManager getConfigurationManager() { - return configurationManager; - } + private static synchronized FeEcompErrorManager init() { + if (instance == null) { + instance = new FeEcompErrorManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } - public void logFeHealthCheckRecovery(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); - } + @Override + public IEcompConfigurationManager getConfigurationManager() { + return configurationManager; + } - public void logFeHealthCheckError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckError); - } + public void logFeHealthCheckRecovery(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery); + } - public void logFeHttpLoggingError(String context) { - processEcompError(context, EcompErrorEnum.FeHttpLoggingError); - } + public void logFeHealthCheckError(String context) { + processEcompError(context, EcompErrorEnum.FeHealthCheckError); + } - public void logFePortalServletError(String context) { - processEcompError(context, EcompErrorEnum.FePortalServletError); - } + public void logFeHttpLoggingError(String context) { + processEcompError(context, EcompErrorEnum.FeHttpLoggingError); + } - public void logFeHealthCheckGeneralError(String context) { - processEcompError(context, EcompErrorEnum.FeHealthCheckGeneralError); - } + public void logFePortalServletError(String context) { + processEcompError(context, EcompErrorEnum.FePortalServletError); + } + 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 b891c7f85c..136174af92 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. @@ -17,20 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.config; -import org.openecomp.sdc.common.api.BasicConfiguration; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.openecomp.sdc.common.api.BasicConfiguration; public class PluginsConfiguration extends BasicConfiguration { private List<Plugin> pluginsList; private Integer connectionTimeout; + public PluginsConfiguration() { + this.pluginsList = new ArrayList<>(); + } + public List<Plugin> getPluginsList() { return pluginsList; } @@ -47,8 +49,9 @@ public class PluginsConfiguration extends BasicConfiguration { this.connectionTimeout = connectionTimeout; } - public PluginsConfiguration() { - this.pluginsList = new ArrayList<>(); + @Override + public String toString() { + return "PluginsConfiguration[" + "pluginsList=" + pluginsList + ", connectionTimeout=" + connectionTimeout + ']'; } public static class Plugin { @@ -99,7 +102,6 @@ public class PluginsConfiguration extends BasicConfiguration { public void setPluginDisplayOptions(Map<String, PluginDisplayOptions> pluginDisplayOptions) { this.pluginDisplayOptions = pluginDisplayOptions; } - } public static class PluginDisplayOptions { @@ -134,18 +136,8 @@ 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 +']'; - } } - - diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/WorkspaceConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/WorkspaceConfiguration.java index caaaf5ad6d..50fce16a15 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/WorkspaceConfiguration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/WorkspaceConfiguration.java @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.config; -import org.openecomp.sdc.common.api.BasicConfiguration; - import java.util.List; import java.util.Map; - import lombok.Getter; import lombok.Setter; +import org.openecomp.sdc.common.api.BasicConfiguration; @Getter @Setter @@ -37,6 +34,7 @@ public class WorkspaceConfiguration extends BasicConfiguration { @Getter @Setter private static class MenuConfiguration { + private String text; private String action; private String state; 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 78e565e6c3..1c46ca2784 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. @@ -17,11 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.fe.monitoring; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import javax.servlet.ServletContext; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; @@ -31,78 +35,68 @@ import org.openecomp.sdc.common.http.client.api.HttpRequest; import org.openecomp.sdc.common.http.client.api.HttpResponse; import org.openecomp.sdc.common.http.config.HttpClientConfig; import org.openecomp.sdc.common.http.config.Timeouts; +import org.openecomp.sdc.common.log.wrappers.Logger; 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.openecomp.sdc.common.log.wrappers.Logger; - -import javax.servlet.ServletContext; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; public class FeMonitoringService { - private static final String URL = "%s://%s:%s/sdc2/rest/monitoring"; + 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 static Gson gson = new GsonBuilder().setPrettyPrinting().create(); + /** + * 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; + } - /** - * 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 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 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"); - } - } - - 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 = 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))); + 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 = 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); + } + } + + 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()); + } + } } |