From 5b593496b8f1b8e8be8d7d2dbcc223332e65a49b Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 29 Jul 2018 16:13:45 +0300 Subject: re base code Change-Id: I12a5ca14a6d8a87e9316b9ff362eb131105f98a5 Issue-ID: SDC-1566 Signed-off-by: Michael Lando --- .../org/openecomp/sdc/be/dao/api/ActionStatus.java | 19 +- .../org/openecomp/sdc/be/dao/api/BasicDao.java | 176 ++ .../openecomp/sdc/be/dao/api/ESGenericIdDAO.java | 23 +- .../sdc/be/dao/api/ESGenericSearchDAO.java | 13 +- .../org/openecomp/sdc/be/dao/api/IBasicDAO.java | 64 + .../org/openecomp/sdc/be/dao/api/ICatalogDAO.java | 5 +- .../org/openecomp/sdc/be/dao/api/IElementDAO.java | 5 +- .../org/openecomp/sdc/be/dao/api/IPropertyDAO.java | 28 + .../org/openecomp/sdc/be/dao/api/IResourceDAO.java | 56 + .../org/openecomp/sdc/be/dao/api/IUsersDAO.java | 3 +- .../sdc/be/dao/cassandra/ArtifactCassandraDao.java | 17 +- .../sdc/be/dao/cassandra/AuditAccessor.java | 15 +- .../sdc/be/dao/cassandra/AuditCassandraDao.java | 91 +- .../sdc/be/dao/cassandra/CassandraClient.java | 35 +- .../sdc/be/dao/cassandra/CassandraDao.java | 9 +- .../be/dao/cassandra/ComponentCacheAccessor.java | 7 +- .../be/dao/cassandra/ComponentCassandraDao.java | 44 +- .../dao/cassandra/OperationalEnvironmentDao.java | 29 +- .../cassandra/OperationalEnvironmentsAccessor.java | 3 +- .../be/dao/cassandra/SdcSchemaFilesAccessor.java | 3 +- .../dao/cassandra/SdcSchemaFilesCassandraDao.java | 20 +- .../be/dao/cassandra/schema/ITableDescription.java | 7 +- .../be/dao/cassandra/schema/SdcSchemaBuilder.java | 47 +- .../be/dao/cassandra/schema/SdcSchemaUtils.java | 14 +- .../sdc/be/dao/cassandra/schema/Table.java | 22 +- .../schema/tables/ArtifactTableDescription.java | 15 +- .../schema/tables/AuthEventTableDescription.java | 17 +- .../tables/CategoryEventTableDescription.java | 17 +- .../tables/ComponentCacheTableDescription.java | 15 +- .../tables/ConsumerEventTableDefinition.java | 17 +- .../schema/tables/DistribBaseEventTableDesc.java | 17 +- .../schema/tables/DistribDeployEventTableDesc.java | 11 +- .../tables/DistribDownloadEventTableDesc.java | 7 +- .../schema/tables/DistribEngineEventTableDesc.java | 9 +- .../schema/tables/DistribNotifEventTableDesc.java | 9 +- .../schema/tables/DistribStatusEventTableDesc.java | 7 +- .../EcompOperationalEnvironmentEventTableDesc.java | 13 +- .../schema/tables/ExternalApiEventTableDesc.java | 17 +- .../schema/tables/GetCatHierEventTableDesc.java | 17 +- .../schema/tables/GetUebClusterEventTableDesc.java | 17 +- .../schema/tables/GetUsersListEventTableDesc.java | 17 +- .../tables/MigrationTasksTableDescription.java | 15 +- .../tables/OldExternalApiEventTableDesc.java | 17 +- .../OperationalEnvironmentsTableDescription.java | 12 +- .../tables/ResAdminEventTableDescription.java | 17 +- .../tables/SdcSchemaFilesTableDescription.java | 19 +- .../tables/UserAccessEventTableDescription.java | 19 +- .../tables/UserAdminEventTableDescription.java | 17 +- .../sdc/be/dao/config/TitanSpringConfig.java | 9 + .../sdc/be/dao/es/ElasticSearchClient.java | 32 +- .../sdc/be/dao/graph/GraphElementFactory.java | 41 +- .../sdc/be/dao/graph/datatype/GraphEdge.java | 4 +- .../sdc/be/dao/graph/datatype/GraphNode.java | 10 +- .../sdc/be/dao/graph/datatype/GraphRelation.java | 4 +- .../org/openecomp/sdc/be/dao/impl/AuditingDao.java | 61 +- .../openecomp/sdc/be/dao/impl/ESCatalogDAO.java | 32 +- .../openecomp/sdc/be/dao/impl/ESTimeBasedDao.java | 33 +- .../sdc/be/dao/impl/EsHealthCheckDao.java | 9 +- .../openecomp/sdc/be/dao/impl/Neo4jElementDAO.java | 107 + .../sdc/be/dao/impl/Neo4jPropertyDAO.java | 49 + .../sdc/be/dao/impl/Neo4jResourceDAO.java | 217 ++ .../openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java | 163 ++ .../sdc/be/dao/jsongraph/GraphVertex.java | 22 +- .../openecomp/sdc/be/dao/jsongraph/TitanDao.java | 2108 ++++++++++---------- .../sdc/be/dao/jsongraph/types/EdgeLabelEnum.java | 10 +- .../be/dao/jsongraph/types/EdgePropertyEnum.java | 3 +- .../sdc/be/dao/jsongraph/types/VertexTypeEnum.java | 27 +- .../sdc/be/dao/jsongraph/utils/IdBuilderUtils.java | 4 +- .../be/dao/jsongraph/utils/JsonParserUtils.java | 34 +- .../sdc/be/dao/model/FacetedSearchFacet.java | 58 - .../sdc/be/dao/model/FacetedSearchResult.java | 72 - .../sdc/be/dao/model/GetMultipleDataResult.java | 113 -- .../openecomp/sdc/be/dao/neo4j/BatchBuilder.java | 79 + .../sdc/be/dao/neo4j/CypherTemplates.java | 52 + .../sdc/be/dao/neo4j/CypherTranslator.java | 251 +++ .../sdc/be/dao/neo4j/GraphEdgeLabels.java | 8 +- .../dao/neo4j/GraphEdgePropertiesDictionary.java | 2 +- .../sdc/be/dao/neo4j/GraphNeighbourTable.java | 64 + .../be/dao/neo4j/GraphPropertiesDictionary.java | 12 +- .../openecomp/sdc/be/dao/neo4j/Neo4jClient.java | 983 +++++++++ .../org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java | 69 + .../sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java | 179 ++ .../sdc/be/dao/neo4j/Neo4jOperationStatus.java | 77 + .../openecomp/sdc/be/dao/neo4j/NodeRelation.java | 65 + .../sdc/be/dao/neo4j/filters/MatchFilter.java | 51 + .../neo4j/filters/RecursiveByRelationFilter.java | 81 + .../sdc/be/dao/neo4j/filters/RecursiveFilter.java | 68 + .../sdc/be/dao/neo4j/filters/UpdateFilter.java | 56 + .../sdc/be/dao/titan/TitanGenericDao.java | 377 ++-- .../sdc/be/dao/titan/TitanGraphClient.java | 56 +- .../org/openecomp/sdc/be/dao/titan/TitanUtils.java | 8 +- .../SimpleTitanTransactionManager.java | 70 + .../sdc/be/dao/utils/CollectionUtils.java | 192 +- .../openecomp/sdc/be/dao/utils/ImageQuality.java | 40 - .../sdc/be/dao/utils/ImageResizeUtil.java | 142 -- .../org/openecomp/sdc/be/dao/utils/JsonUtil.java | 68 +- .../org/openecomp/sdc/be/dao/utils/MapEntry.java | 55 - .../org/openecomp/sdc/be/dao/utils/MapUtil.java | 230 ++- .../org/openecomp/sdc/be/dao/utils/TypeMap.java | 4 +- .../openecomp/sdc/be/dao/utils/UserStatusEnum.java | 3 +- .../sdc/be/resources/api/IResourceUploader.java | 3 +- .../data/AdditionalInfoParameterData.java | 11 +- .../sdc/be/resources/data/AnnotationTypeData.java | 84 + .../sdc/be/resources/data/ArtifactData.java | 13 +- .../sdc/be/resources/data/AttributeData.java | 11 +- .../sdc/be/resources/data/AttributeValueData.java | 10 +- .../sdc/be/resources/data/CapabilityData.java | 106 +- .../sdc/be/resources/data/CapabilityInstData.java | 13 +- .../sdc/be/resources/data/CapabilityTypeData.java | 18 +- .../sdc/be/resources/data/CategoryData.java | 8 +- .../sdc/be/resources/data/ComponentCacheData.java | 6 +- .../be/resources/data/ComponentInstanceData.java | 8 +- .../be/resources/data/ComponentMetadataData.java | 21 +- .../sdc/be/resources/data/ConsumerData.java | 8 +- .../sdc/be/resources/data/DataTypeData.java | 8 +- .../sdc/be/resources/data/ESArtifactData.java | 4 +- .../sdc/be/resources/data/GraphNodeLock.java | 8 +- .../openecomp/sdc/be/resources/data/GroupData.java | 8 +- .../sdc/be/resources/data/GroupInstanceData.java | 8 +- .../sdc/be/resources/data/GroupTypeData.java | 24 +- .../sdc/be/resources/data/HeatParameterData.java | 10 +- .../be/resources/data/HeatParameterValueData.java | 8 +- .../sdc/be/resources/data/InputValueData.java | 10 +- .../sdc/be/resources/data/InputsData.java | 13 +- .../sdc/be/resources/data/InterfaceData.java | 8 +- .../sdc/be/resources/data/MigrationTaskEntry.java | 4 +- .../sdc/be/resources/data/OperationData.java | 8 +- .../data/OperationalEnvironmentEntry.java | 11 +- .../sdc/be/resources/data/PolicyTypeData.java | 20 +- .../sdc/be/resources/data/ProductMetadataData.java | 9 +- .../sdc/be/resources/data/PropertyData.java | 13 +- .../sdc/be/resources/data/PropertyValueData.java | 13 +- .../be/resources/data/RelationshipInstData.java | 8 +- .../be/resources/data/RelationshipTypeData.java | 13 +- .../sdc/be/resources/data/RequirementData.java | 8 +- .../sdc/be/resources/data/RequirementImplData.java | 8 +- .../be/resources/data/ResourceCategoryData.java | 4 +- .../be/resources/data/ResourceMetadataData.java | 4 +- .../sdc/be/resources/data/SdcSchemaFilesData.java | 6 +- .../sdc/be/resources/data/ServiceCategoryData.java | 4 +- .../sdc/be/resources/data/ServiceMetadataData.java | 4 +- .../openecomp/sdc/be/resources/data/TagData.java | 8 +- .../sdc/be/resources/data/UniqueIdData.java | 4 +- .../openecomp/sdc/be/resources/data/UserData.java | 10 +- .../be/resources/data/UserFunctionalMenuData.java | 8 +- .../data/auditing/AuditRecordFactory.java | 93 - .../data/auditing/AuditingActionEnum.java | 213 +- .../data/auditing/AuditingGenericEvent.java | 91 +- .../data/auditing/AuditingGetUebClusterEvent.java | 74 +- .../data/auditing/AuditingTypesConstants.java | 47 +- .../sdc/be/resources/data/auditing/AuthEvent.java | 327 ++- .../be/resources/data/auditing/CategoryEvent.java | 403 ++-- .../be/resources/data/auditing/ConsumerEvent.java | 77 +- .../data/auditing/DistributionDeployEvent.java | 130 +- .../data/auditing/DistributionDownloadEvent.java | 98 +- .../data/auditing/DistributionEngineEvent.java | 124 +- .../auditing/DistributionNotificationEvent.java | 580 +++--- .../data/auditing/DistributionStatusEvent.java | 429 ++-- .../auditing/EcompOperationalEnvironmentEvent.java | 60 +- .../resources/data/auditing/ExternalApiEvent.java | 153 +- .../data/auditing/GetCategoryHierarchyEvent.java | 67 +- .../resources/data/auditing/GetUsersListEvent.java | 69 +- .../data/auditing/ResourceAdminEvent.java | 766 ++++--- .../resources/data/auditing/UserAccessEvent.java | 303 ++- .../be/resources/data/auditing/UserAdminEvent.java | 364 ++-- .../data/auditing/model/CommonAuditData.java | 4 + .../data/auditing/model/DistributionTopicData.java | 45 + .../data/auditing/model/ResourceAuditData.java | 60 - .../data/auditing/model/ResourceCommonInfo.java | 31 + .../data/auditing/model/ResourceVersionInfo.java | 60 + .../be/resources/data/category/CategoryData.java | 13 +- .../be/resources/data/category/GroupingData.java | 8 +- .../resources/data/category/SubCategoryData.java | 13 +- .../sdc/be/resources/impl/ResourceUploader.java | 12 +- 174 files changed, 7352 insertions(+), 5615 deletions(-) create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AnnotationTypeData.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionTopicData.java delete mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceCommonInfo.java create mode 100644 catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceVersionInfo.java (limited to 'catalog-dao/src/main') diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java index e90621515d..50dbf570f4 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java @@ -25,12 +25,12 @@ public enum ActionStatus { // User related USER_ALREADY_EXIST, USER_INACTIVE, USER_NOT_FOUND, USER_HAS_ACTIVE_ELEMENTS, INVALID_EMAIL_ADDRESS, INVALID_ROLE, DELETE_USER_ADMIN_CONFLICT, UPDATE_USER_ADMIN_CONFLICT, CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, INVALID_USER_ID, // CapabilityType related - CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, + CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, MISSING_CAPABILITIES, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, RELATION_NOT_FOUND, // Resource related RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND, INVALID_RESOURCE_TYPE, TOSCA_PARSE_ERROR, // Service related - SERVICE_TYPE_EXCEEDS_LIMIT, INVALID_SERVICE_TYPE, SERVICE_ROLE_EXCEEDS_LIMIT, INVALID_SERVICE_ROLE, + SERVICE_TYPE_EXCEEDS_LIMIT, INVALID_SERVICE_TYPE, SERVICE_ROLE_EXCEEDS_LIMIT, INVALID_SERVICE_ROLE, INVALID_INSTANTIATION_TYPE, // Component name related COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME, // Component description related @@ -54,7 +54,7 @@ public enum ActionStatus { // State related INVALID_SERVICE_STATE, COMPONENT_IN_CHECKOUT_STATE, ILLEGAL_COMPONENT_STATE, COMPONENT_IN_CERT_IN_PROGRESS_STATE, COMPONENT_SENT_FOR_CERTIFICATION, COMPONENT_VERSION_ALREADY_EXIST, COMPONENT_ALREADY_CHECKED_IN, COMPONENT_CHECKOUT_BY_ANOTHER_USER, COMPONENT_IN_USE, COMPONENT_HAS_NEWER_VERSION, COMPONENT_ALREADY_CERTIFIED, COMPONENT_NOT_READY_FOR_CERTIFICATION, COMPONENT_ARTIFACT_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, SERVICE_NOT_FOUND, SERVICE_CATEGORY_CANNOT_BE_CHANGED, SERVICE_NAME_CANNOT_BE_CHANGED, SERVICE_ICON_CANNOT_BE_CHANGED, COMPONENT_TOO_MUCH_CATEGORIES, SERVICE_CANNOT_CONTAIN_SUBCATEGORY, RESOURCE_CATEGORY_CANNOT_BE_CHANGED, RESOURCE_NAME_CANNOT_BE_CHANGED, RESOURCE_ICON_CANNOT_BE_CHANGED, RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED, RESOURCE_TOO_MUCH_SUBCATEGORIES, SERVICE_ICON_EXCEEDS_LIMIT, RESOURCE_INSTANCE_NOT_FOUND, RESOURCE_INSTANCE_BAD_REQUEST, RESOURCE_INSTANCE_MATCH_NOT_FOUND, RESOURCE_INSTANCE_ALREADY_EXIST, RESOURCE_INSTANCE_RELATION_NOT_FOUND, COMPONENT_MISSING_SUBCATEGORY, COMPONENT_INVALID_SUBCATEGORY, ARTIFACT_TYPE_NOT_SUPPORTED, MISSING_ARTIFACT_TYPE, ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED, ARTIFACT_EXIST, ARTIFACT_NOT_FOUND, ARTIFACT_INVALID_MD5, MISSING_ARTIFACT_NAME, MISSING_PROJECT_CODE, INVALID_PROJECT_CODE, COMPONENT_MISSING_MANDATORY_ARTIFACTS, LIFECYCLE_TYPE_ALREADY_EXIST, SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, MISSING_LIFECYCLE_TYPE, RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, // Distribution - BAD_REQUEST_MISSING_RESOURCE, MISSING_USER_ID, MISSING_X_ECOMP_INSTANCE_ID, MISSING_PUBLIC_KEY, MISSING_ENV_NAME, DISTRIBUTION_ENV_DOES_NOT_EXIST, MISSING_BODY, ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS, ECOMP_COMPONENT_NOT_AUTHORIZED, METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT, REGISTRATION_FAILED, DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, DISTRIBUTION_ENVIRONMENT_NOT_FOUND, DISTRIBUTION_ENVIRONMENT_INVALID, DISTRIBUTION_ARTIFACT_NOT_FOUND, DISTRIBUTION_REQUESTED_NOT_FOUND, DISTRIBUTION_REQUESTED_FAILED, DISTRIBUTION_NOT_FOUND, ADDITIONAL_INFORMATION_ALREADY_EXISTS, COMPONENT_VERSION_NOT_FOUND, ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_NOT_FOUND, ASDC_VERSION_NOT_FOUND, MISSING_DATA, EXCEEDS_LIMIT, UNSUPPORTED_ERROR, ARTIFACT_INVALID_TIMEOUT, SERVICE_IS_VNF_CANNOT_BE_CHANGED, RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, WRONG_ARTIFACT_FILE_EXTENSION, INVALID_YAML, INVALID_XML, INVALID_JSON, INVALID_DEPLOYMENT_ARTIFACT_HEAT, INVALID_HEAT_PARAMETER_TYPE, INVALID_HEAT_PARAMETER_VALUE, DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, MISSING_HEAT, MISMATCH_HEAT_VS_HEAT_ENV, CORRUPTED_FORMAT, MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, INVALID_PARAMS_IN_HEAT_ENV_FILE, API_RESOURCE_NOT_FOUND, + BAD_REQUEST_MISSING_RESOURCE, MISSING_USER_ID, MISSING_X_ECOMP_INSTANCE_ID, MISSING_PUBLIC_KEY, MISSING_ENV_NAME, DISTRIBUTION_ENV_DOES_NOT_EXIST, MISSING_BODY, ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS, ECOMP_COMPONENT_NOT_AUTHORIZED, METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT, REGISTRATION_FAILED, DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, DISTRIBUTION_ENVIRONMENT_NOT_FOUND, DISTRIBUTION_ENVIRONMENT_INVALID, DISTRIBUTION_REQUESTED_NOT_FOUND, DISTRIBUTION_REQUESTED_FAILED, DISTRIBUTION_NOT_FOUND, ADDITIONAL_INFORMATION_ALREADY_EXISTS, COMPONENT_VERSION_NOT_FOUND, ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_NOT_FOUND, ASDC_VERSION_NOT_FOUND, MISSING_DATA, EXCEEDS_LIMIT, UNSUPPORTED_ERROR, ARTIFACT_INVALID_TIMEOUT, SERVICE_IS_VNF_CANNOT_BE_CHANGED, RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, WRONG_ARTIFACT_FILE_EXTENSION, INVALID_YAML, INVALID_XML, INVALID_JSON, INVALID_DEPLOYMENT_ARTIFACT_HEAT, INVALID_HEAT_PARAMETER_TYPE, INVALID_HEAT_PARAMETER_VALUE, DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, MISSING_HEAT, MISMATCH_HEAT_VS_HEAT_ENV, CORRUPTED_FORMAT, MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, INVALID_PARAMS_IN_HEAT_ENV_FILE, API_RESOURCE_NOT_FOUND, //UEB UNKNOWN_HOST, AUTHENTICATION_ERROR, CONNNECTION_ERROR, OBJECT_NOT_FOUND, INVALID_RESPONSE_FROM_PROXY, // auth @@ -75,8 +75,11 @@ public enum ActionStatus { // Group Type related GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST, GROUP_TYPE_ILLEGAL_PER_COMPONENT, + // Annotation Type related + ANNOTATION_TYPE_ALREADY_EXIST, + // CSAR - MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID,ERROR_DURING_CSAR_CREATION, + MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID, ARTIFACT_PAYLOAD_EMPTY,ERROR_DURING_CSAR_CREATION, // Group GROUP_HAS_CYCLIC_DEPENDENCY, GROUP_ALREADY_EXIST, GROUP_TYPE_IS_INVALID, GROUP_MISSING_GROUP_TYPE, GROUP_INVALID_COMPONENT_INSTANCE, GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, GROUP_IS_MISSING, GROUP_ARTIFACT_ALREADY_ASSOCIATED, GROUP_ARTIFACT_ALREADY_DISSOCIATED, GROUP_PROPERTY_NOT_FOUND, INVALID_VF_MODULE_NAME, INVALID_VF_MODULE_NAME_MODIFICATION, INVALID_VF_MODULE_TYPE, @@ -106,7 +109,13 @@ public enum ActionStatus { EXT_REF_ALREADY_EXIST, EXT_REF_NOT_FOUND, - POLICY_TARGET_DOES_NOT_EXIST, POLICY_TARGET_TYPE_DOES_NOT_EXIST, + POLICY_TARGET_DOES_NOT_EXIST, POLICY_TARGET_TYPE_DOES_NOT_EXIST, INPUTS_NOT_FOUND, + RESOURCE_LIFECYCLE_STATE_NOT_VALID, + COMPONENT_IS_ARCHIVED, + //Automated upgrade + COMPONENT_IS_NOT_HIHGEST_CERTIFIED, + NO_INSTANCES_TO_UPGRADE, + ARCHIVED_ORIGINS_FOUND, //InterfaceOperation INTERFACE_OPERATION_NOT_FOUND, INTERFACE_OPERATION_TYPE_ALREADY_IN_USE, INTERFACE_OPERATION_TYPE_MANDATORY, INTERFACE_OPERATION_TYPE_INVALID, diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java new file mode 100644 index 0000000000..cccb7d0b4b --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/BasicDao.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.api; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.impl.Neo4jResourceDAO; +import org.openecomp.sdc.be.dao.neo4j.*; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public abstract class BasicDao implements IBasicDAO { + + Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder(); + + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jResourceDAO.class.getName()); + + public Either create(GraphNeighbourTable graphNeighbourTable, + Class clazz, NodeTypeEnum nodeType) { + + if (graphNeighbourTable != null) { + + Either bbResult = graphBatchBuilder + .buildBatchBuilderFromTable(graphNeighbourTable); + + if (bbResult.isLeft()) { + + BatchBuilder batchBuilder = bbResult.left().value(); + // Neo4jOperationStatus neo4jOperationStatus = + // neo4jClient.execute(batchBuilder); + Either>, Neo4jOperationStatus> executeResult = neo4jClient + .execute(batchBuilder); + + if (executeResult.isRight()) { + return Either.right(executeResult.right().value()); + } + + T result = null; + List> listOfResults = executeResult.left().value(); + if (listOfResults != null) { + for (List listOfElements : listOfResults) { + if (listOfElements != null && !listOfElements.isEmpty()) { + for (GraphElement element : listOfElements) { + logger.debug("element {} was returned after running batch operation {}", + element, batchBuilder); + if (element instanceof GraphNode) { + GraphNode neo4jNode = (GraphNode) element; + if (NodeTypeEnum.getByName(neo4jNode.getLabel()) == nodeType) { + result = clazz.cast(neo4jNode); + } + } + } + } + } + } + + return Either.left(result); + + } else { + return Either.right(bbResult.right().value()); + } + + } else { + logger.error("The table sent in order to create resource is empty."); + return Either.right(Neo4jOperationStatus.BAD_REQUEST); + } + + } + + @Override + public Either getNodeData(String uniqueid, Class clazz, + NodeTypeEnum nodeTypeEnum) { + + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueid); + + return getNodeData(filter, clazz, nodeTypeEnum); + + } + + @Override + public Either getNodeData(String keyName, String uniqueid, + Class clazz, NodeTypeEnum nodeTypeEnum) { + + MatchFilter filter = new MatchFilter(); + filter.addToMatch(keyName, uniqueid); + + return getNodeData(filter, clazz, nodeTypeEnum); + + } + + private Either getNodeData(MatchFilter filter, Class clazz, + NodeTypeEnum nodeTypeEnum) { + + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + nodeTypeEnum.getName(), filter); + + if (status.isRight()) { + return Either.right(status.right().value()); + } else { + List value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(Neo4jOperationStatus.NOT_FOUND); + } else { + return Either.left(clazz.cast(value.get(0))); + } + } + } + + @Override + public Either, Neo4jOperationStatus> getNodesData( + Map propertiesToMatch, Class clazz, NodeTypeEnum nodeTypeEnum) { + + MatchFilter filter = new MatchFilter(); + if (propertiesToMatch != null) { + for (Entry property : propertiesToMatch.entrySet()) { + filter.addToMatch(property.getKey(), property.getValue()); + } + } + + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + nodeTypeEnum.getName(), filter); + + if (status.isRight()) { + return Either.right(status.right().value()); + } else { + List value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(Neo4jOperationStatus.NOT_FOUND); + } else { + List list = new ArrayList<>(); + for (GraphElement element : value) { + list.add(clazz.cast(element)); + } + return Either.left(list); + } + } + } + + public Neo4jClient getNeo4jClient() { + return neo4jClient; + } + + public void setNeo4jClient(Neo4jClient neo4jClient) { + this.neo4jClient = neo4jClient; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java index 1ab27fc930..e10930db08 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericIdDAO.java @@ -20,15 +20,8 @@ package org.openecomp.sdc.be.dao.api; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.get.GetResponse; @@ -36,22 +29,22 @@ import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.client.Client; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.IndexingServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.annotation.Resource; +import java.io.IOException; +import java.util.*; public abstract class ESGenericIdDAO implements IGenericIdDAO { - private static Logger log = LoggerFactory.getLogger(ESGenericIdDAO.class.getName()); + private static Logger log = Logger.getLogger(ESGenericIdDAO.class.getName()); @Resource(name = "elasticsearch-client") private ElasticSearchClient esClient; private ObjectMapper jsonMapper = new ObjectMapper(); - private final Map typesToIndices = new HashMap(); + private final Map typesToIndices = new HashMap<>(); public Client getClient() { return this.esClient.getClient(); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java index 77aac87427..4dc57201fb 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ESGenericSearchDAO.java @@ -20,18 +20,17 @@ package org.openecomp.sdc.be.dao.api; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Resource; - import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.SortBuilder; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; +import javax.annotation.Resource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + /** * Elastic search dao that manages search operations. * @@ -92,7 +91,7 @@ public class ESGenericSearchDAO extends ESGenericIdDAO implements IGenericSearch public List doCustomFind(Class clazz, String indexName, String typeName, QueryBuilder query, SortBuilder sortBuilder) { - List result = new ArrayList(); + List result = new ArrayList<>(); SearchRequestBuilder searchRequestBuilder = getClient().prepareSearch(indexName).setTypes(typeName) .setSize(MAX_SEARCH_SIZE); if (query != null) { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java new file mode 100644 index 0000000000..5666f059b9 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IBasicDAO.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.api; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.neo4j.GraphNeighbourTable; +import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +import java.util.List; +import java.util.Map; + +public interface IBasicDAO { + + /** + * add the content of the graph neighbour table to the graph. + * + * @param graphNeighbourTable + * @param clazz + * - the type of the object to be returned + * @param nodeType + * - label of the node + * @return Neo4jNode implementation + */ + public Either create(GraphNeighbourTable graphNeighbourTable, + Class clazz, NodeTypeEnum nodeType); + + /** + * return the node data by unique id. + * + * @param id + * - unique id of the node + * @param clazz + * @param nodeType + * @return + */ + public Either getNodeData(String id, Class clazz, + NodeTypeEnum nodeType); + + public Either getNodeData(String keyName, String id, Class clazz, + NodeTypeEnum nodeType); + + public Either, Neo4jOperationStatus> getNodesData( + Map propertiesToMatch, Class clazz, NodeTypeEnum nodeTypeEnum); +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java index b59e956f9c..c463cc32e2 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ICatalogDAO.java @@ -20,12 +20,11 @@ package org.openecomp.sdc.be.dao.api; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.exception.ResourceDAOException; -import fj.data.Either; +import java.util.List; public interface ICatalogDAO { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java index f43bd2303f..a5e643b761 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IElementDAO.java @@ -20,11 +20,10 @@ package org.openecomp.sdc.be.dao.api; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; -import fj.data.Either; +import java.util.List; public interface IElementDAO { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java new file mode 100644 index 0000000000..17bded535c --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IPropertyDAO.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.api; + +public interface IPropertyDAO extends IBasicDAO { + + // Either + // createPropertyData(GraphNeighbourTable graphNeighbourTable); + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java new file mode 100644 index 0000000000..c349224feb --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IResourceDAO.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.api; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; + +import java.util.List; +import java.util.Map; + +public interface IResourceDAO extends IBasicDAO { + + Either getResourceData(String id); + + // Either + // createResourceData(GraphNeighbourTable graphNeighbourTable); + + /** + * the method retrieves all the resources according to the supplied + * properties, if none or null is supplied all the resources will be + * returned. + * + * @param propertiesToMatch + * a map of properties to match. + * @return + */ + Either, Neo4jOperationStatus> getAllResourcesData(Map propertiesToMatch); + + // ActionStatus updateUserData(UserData userData); + // + // ActionStatus deleteUserData(String id); + + void setNeo4jClient(Neo4jClient client); + + Either getNumberOfResourcesByName(String name); +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java index 441e8a9010..cbf844c5f7 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/IUsersDAO.java @@ -20,9 +20,8 @@ package org.openecomp.sdc.be.dao.api; -import org.openecomp.sdc.be.resources.data.UserData; - import fj.data.Either; +import org.openecomp.sdc.be.resources.data.UserData; public interface IUsersDAO { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java index df107787e7..8449e676ca 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ArtifactCassandraDao.java @@ -20,25 +20,22 @@ package org.openecomp.sdc.be.dao.cassandra; -import javax.annotation.PostConstruct; - +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Session; -import com.datastax.driver.mapping.MappingManager; - -import fj.data.Either; +import javax.annotation.PostConstruct; @Component("artifact-cassandra-dao") public class ArtifactCassandraDao extends CassandraDao { - private static Logger logger = LoggerFactory.getLogger(ArtifactCassandraDao.class.getName()); + private static Logger logger = Logger.getLogger(ArtifactCassandraDao.class.getName()); private ArtifactAccessor artifactAccessor; public ArtifactCassandraDao() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java index 72c3b9656d..c713ea9af2 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditAccessor.java @@ -20,15 +20,14 @@ package org.openecomp.sdc.be.dao.cassandra; -import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; -import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; -import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; -import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; - import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Param; import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; @Accessor public interface AuditAccessor { @@ -55,6 +54,12 @@ public interface AuditAccessor { Result getAuditByServiceIdAndCurrVersion(@Param("serviceInstanceId") String serviceInstanceId, @Param("currVersion") String currVersion); + @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'ArchiveComponent' ALLOW FILTERING") + Result getArchiveAuditByServiceInstanceId(@Param("serviceInstanceId") String serviceInstanceId); + + @Query("SELECT * FROM sdcaudit.resourceadminevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'RestoreComponent' ALLOW FILTERING") + Result getRestoreAuditByServiceInstanceId(@Param("serviceInstanceId") String serviceInstanceId); + // ***** distributiondeployevent table @Query("SELECT * FROM sdcaudit.distributiondeployevent WHERE SERVICE_INSTANCE_ID = :serviceInstanceId AND ACTION = 'DResult' ALLOW FILTERING") Result getServiceDistributionDeploy(@Param("serviceInstanceId") String serviceInstanceId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java index 1562f8a8d1..d5c8a19f06 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java @@ -20,38 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.PostConstruct; - +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import com.datastax.driver.mapping.Result; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.schema.Table; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; -import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; -import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; -import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; -import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.be.resources.data.auditing.*; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.datastax.driver.core.Session; -import com.datastax.driver.mapping.MappingManager; -import com.datastax.driver.mapping.Result; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; @Component("audit-cassandra-dao") public class AuditCassandraDao extends CassandraDao { private AuditAccessor auditAccessor; - private static Logger logger = LoggerFactory.getLogger(AuditCassandraDao.class.getName()); + private static Logger logger = Logger.getLogger(AuditCassandraDao.class.getName()); public AuditCassandraDao() { super(); @@ -90,7 +80,7 @@ public class AuditCassandraDao extends CassandraDao { * @return */ public Either, ActionStatus> getListOfDistributionStatuses(String did) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getListOfDistributionStatuses(did); @@ -113,7 +103,7 @@ public class AuditCassandraDao extends CassandraDao { public Either, ActionStatus> getDistributionDeployByStatus(String did, String action, String status) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getDistributionDeployByStatus(did, action, status); @@ -136,7 +126,7 @@ public class AuditCassandraDao extends CassandraDao { } public Either, ActionStatus> getDistributionRequest(String did, String action) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getDistributionRequest(did, action); @@ -158,7 +148,7 @@ public class AuditCassandraDao extends CassandraDao { } public Either, ActionStatus> getDistributionNotify(String did, String action) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getDistributionNotify(did, action); @@ -181,7 +171,7 @@ public class AuditCassandraDao extends CassandraDao { } public Either, ActionStatus> getByServiceInstanceId(String serviceInstanceId) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getByServiceInstanceId(serviceInstanceId); @@ -268,7 +258,7 @@ public class AuditCassandraDao extends CassandraDao { public Either, ActionStatus> getAuditByServiceIdAndPrevVersion(String serviceInstanceId, String prevVersion) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getAuditByServiceIdAndPrevVersion(serviceInstanceId, @@ -293,7 +283,7 @@ public class AuditCassandraDao extends CassandraDao { public Either, ActionStatus> getAuditByServiceIdAndCurrVersion(String serviceInstanceId, String currVersion) { - List remainingElements = new ArrayList(); + List remainingElements = new ArrayList<>(); try { Result events = auditAccessor.getAuditByServiceIdAndCurrVersion(serviceInstanceId, @@ -317,6 +307,53 @@ public class AuditCassandraDao extends CassandraDao { } } + public Either, ActionStatus> getArchiveAuditByServiceInstanceId(String serviceInstanceId) { + List remainingElements = new ArrayList<>(); + + try { + Result events = auditAccessor.getArchiveAuditByServiceInstanceId(serviceInstanceId); + if (events == null) { + logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId); + return Either.left(remainingElements); + } + events.all().forEach(event -> { + event.fillFields(); + remainingElements.add(event); + logger.debug(event.toString()); + }); + return Either.left(remainingElements); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("getArchiveAuditByServiceInstanceId"); + + logger.debug("failed getArchiveAuditByServiceInstanceId ", e); + return Either.right(ActionStatus.GENERAL_ERROR); + } + } + + public Either, ActionStatus> getRestoreAuditByServiceInstanceId(String serviceInstanceId) { + List remainingElements = new ArrayList<>(); + + try { + Result events = auditAccessor.getRestoreAuditByServiceInstanceId(serviceInstanceId); + if (events == null) { + logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId); + return Either.left(remainingElements); + } + events.all().forEach(event -> { + event.fillFields(); + remainingElements.add(event); + logger.debug(event.toString()); + }); + return Either.left(remainingElements); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("getRestoreAuditByServiceInstanceId"); + + logger.debug("failed getRestoreAuditByServiceInstanceId ", e); + return Either.right(ActionStatus.GENERAL_ERROR); + } + } + + /** * the method checks if the given table is empty in the audit keyspace * diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java index c343765c5c..8889cc212e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java @@ -20,32 +20,24 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.List; - -import javax.annotation.PreDestroy; - -import com.datastax.driver.core.SocketOptions; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; -import com.datastax.driver.core.policies.ConstantReconnectionPolicy; -import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; -import com.datastax.driver.core.policies.DefaultRetryPolicy; -import com.datastax.driver.core.policies.LoadBalancingPolicy; -import com.datastax.driver.core.policies.TokenAwarePolicy; +import com.datastax.driver.core.SocketOptions; +import com.datastax.driver.core.policies.*; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.MappingManager; - import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import javax.annotation.PreDestroy; +import java.util.List; @Component("cassandra-client") public class CassandraClient { - private static Logger logger = LoggerFactory.getLogger(CassandraClient.class.getName()); + private static Logger logger = Logger.getLogger(CassandraClient.class.getName()); private Cluster cluster; private boolean isConnected; @@ -65,7 +57,7 @@ public class CassandraClient { .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout)) .withRetryPolicy(DefaultRetryPolicy.INSTANCE); - cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host)); + cassandraHosts.forEach(clusterBuilder::addContactPoint); setSocketOptions(clusterBuilder); enableAuthentication(clusterBuilder); enableSsl(clusterBuilder); @@ -157,12 +149,13 @@ public class CassandraClient { Session session = cluster.connect(keyspace); if (session != null) { MappingManager manager = new MappingManager(session); - return Either.left(new ImmutablePair(session, manager)); + return Either.left(new ImmutablePair<>(session, manager)); } else { return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED); } } catch (Throwable e) { - logger.debug("Failed to connect to keyspace [{}], error :", keyspace, e); + logger.debug("Failed to connect to keyspace [{}], error ,", keyspace); + logger.debug("Exception :", e); return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED); } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java index 5ff2917c27..0efbb9fd31 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraDao.java @@ -20,21 +20,18 @@ package org.openecomp.sdc.be.dao.cassandra; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.mapping.MappingManager; - import fj.data.Either; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; public abstract class CassandraDao { - private static Logger logger = LoggerFactory.getLogger(CassandraDao.class.getName()); + private static Logger logger = Logger.getLogger(CassandraDao.class.getName()); protected Session session; protected MappingManager manager; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java index 828072a4e6..dcdd390485 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCacheAccessor.java @@ -20,14 +20,13 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.List; - -import org.openecomp.sdc.be.resources.data.ComponentCacheData; - import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Param; import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.sdc.be.resources.data.ComponentCacheData; + +import java.util.List; @Accessor public interface ComponentCacheAccessor { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java index 50c4f3f7e8..11643d16e8 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/ComponentCassandraDao.java @@ -20,34 +20,26 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; - +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import com.datastax.driver.mapping.Result; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.resources.data.ComponentCacheData; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.datastax.driver.core.Session; -import com.datastax.driver.mapping.MappingManager; -import com.datastax.driver.mapping.Result; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.*; +import java.util.stream.Collectors; @Component("component-cassandra-dao") public class ComponentCassandraDao extends CassandraDao { - private static Logger logger = LoggerFactory.getLogger(ComponentCassandraDao.class.getName()); + private static Logger logger = Logger.getLogger(ComponentCassandraDao.class.getName()); public final static Integer DEFAULT_FETCH_SIZE = 500; @@ -87,8 +79,8 @@ public class ComponentCassandraDao extends CassandraDao { */ public Either, ActionStatus> getComponents(List ids) { - List components = new ArrayList(); - if (ids == null || true == ids.isEmpty()) { + List components = new ArrayList<>(); + if (ids == null || ids.isEmpty()) { return Either.left(components); } @@ -118,7 +110,7 @@ public class ComponentCassandraDao extends CassandraDao { public Either, ActionStatus> getAllComponentIdTimeAndType() { try { - List components = new ArrayList(); + List components = new ArrayList<>(); Result events = componentCacheAccessor.getAllComponentIdTimeAndType(); if (events == null) { logger.trace("no component found "); @@ -201,12 +193,12 @@ public class ComponentCassandraDao extends CassandraDao { public Either, Set>, ActionStatus> getComponents( Map idToTimestampMap) { - List components = new ArrayList(); + List components = new ArrayList<>(); Set notFetchedFromCache = new HashSet<>(); - ImmutablePair, Set> result = new ImmutablePair, Set>( - components, notFetchedFromCache); + ImmutablePair, Set> result = new ImmutablePair<>( + components, notFetchedFromCache); - if (idToTimestampMap == null || true == idToTimestampMap.isEmpty()) { + if (idToTimestampMap == null || idToTimestampMap.isEmpty()) { return Either.left(result); } @@ -236,11 +228,11 @@ public class ComponentCassandraDao extends CassandraDao { logger.debug("Number of components to fetch was {}. Actually, {} components fetched", ids.size(), components.size()); - List foundComponents = components.stream().map(p -> p.getId()).collect(Collectors.toList()); + List foundComponents = components.stream().map(ComponentCacheData::getId).collect(Collectors.toList()); // fetch all ids which was not found in cache/found in cache and not // updated. Set notFoundComponents = idToTimestampMap.keySet().stream() - .filter(p -> false == foundComponents.contains(p)).collect(Collectors.toSet()); + .filter(p -> !foundComponents.contains(p)).collect(Collectors.toSet()); notFetchedFromCache.addAll(notFoundComponents); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java index a803f0b165..9ff82f41b1 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java @@ -1,27 +1,24 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.List; - -import javax.annotation.PostConstruct; - +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import com.datastax.driver.mapping.Result; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.datastax.driver.core.Session; -import com.datastax.driver.mapping.MappingManager; -import com.datastax.driver.mapping.Result; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.List; @Component("operational-environment-dao") public class OperationalEnvironmentDao extends CassandraDao { - private static Logger logger = LoggerFactory.getLogger(OperationalEnvironmentDao.class.getName()); + private static Logger logger = Logger.getLogger(OperationalEnvironmentDao.class.getName()); private OperationalEnvironmentsAccessor operationalEnvironmentsAccessor; public OperationalEnvironmentDao() { @@ -37,15 +34,15 @@ public class OperationalEnvironmentDao extends CassandraDao { session = result.left().value().left; manager = result.left().value().right; operationalEnvironmentsAccessor = manager.createAccessor(OperationalEnvironmentsAccessor.class); - logger.info("** OperationalEnvironmentDao created"); + logger.debug("** OperationalEnvironmentDao created"); } else { - logger.info("** OperationalEnvironmentDao failed"); + logger.error(EcompLoggerErrorCode.DATA_ERROR, "OperationalEnvironmentDao", "OperationalEnvironmentDao", "** OperationalEnvironmentDao failed"); throw new RuntimeException("OperationalEnvironment keyspace [" + keyspace + "] failed to connect with error : " + result.right().value()); } } else { - logger.info("** Cassandra client isn't connected"); - logger.info("** OperationalEnvironmentDao created, but not connected"); + logger.error(EcompLoggerErrorCode.DATA_ERROR, "OperationalEnvironmentDao", "OperationalEnvironmentDao", "** Cassandra client isn't connected"); + logger.error(EcompLoggerErrorCode.DATA_ERROR, "OperationalEnvironmentDao", "OperationalEnvironmentDao", "** OperationalEnvironmentDao created, but not connected"); } } public CassandraOperationStatus save(OperationalEnvironmentEntry operationalEnvironmentEntry) { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java index 74fcdf5058..e72df9b42d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java @@ -1,11 +1,10 @@ package org.openecomp.sdc.be.dao.cassandra; -import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; - import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Param; import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; @Accessor public interface OperationalEnvironmentsAccessor { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java index 5867e39360..ab1399ab83 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesAccessor.java @@ -20,12 +20,11 @@ package org.openecomp.sdc.be.dao.cassandra; -import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; - import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Param; import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; @Accessor public interface SdcSchemaFilesAccessor { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java index de14bac210..a9ca4e845b 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/SdcSchemaFilesCassandraDao.java @@ -20,27 +20,23 @@ package org.openecomp.sdc.be.dao.cassandra; -import java.util.List; - -import javax.annotation.PostConstruct; - +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import com.datastax.driver.mapping.Result; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.datastax.driver.core.Session; -import com.datastax.driver.mapping.MappingManager; -import com.datastax.driver.mapping.Result; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.List; @Component("sdc-schema-files-cassandra-dao") public class SdcSchemaFilesCassandraDao extends CassandraDao { - private static Logger logger = LoggerFactory.getLogger(SdcSchemaFilesCassandraDao.class.getName()); + private static Logger logger = Logger.getLogger(SdcSchemaFilesCassandraDao.class.getName()); private SdcSchemaFilesAccessor sdcSchemaFilesAccessor; public SdcSchemaFilesCassandraDao() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java index 010c3ee8fc..4622b4f1f7 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/ITableDescription.java @@ -20,12 +20,11 @@ package org.openecomp.sdc.be.dao.cassandra.schema; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; -import com.datastax.driver.core.DataType; +import java.util.List; +import java.util.Map; public interface ITableDescription { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java index 0618acc71a..14083c110d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaBuilder.java @@ -32,11 +32,13 @@ package org.openecomp.sdc.be.dao.cassandra.schema; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.cassandra.schema.tables.OldExternalApiEventTableDesc; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; - import org.slf4j.Logger; - import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import com.datastax.driver.core.AbstractTableMetadata; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.DataType; +import com.datastax.driver.core.IndexMetadata; import com.datastax.driver.core.KeyspaceMetadata; import com.datastax.driver.core.Session; import com.datastax.driver.core.schemabuilder.Alter; @@ -55,7 +57,7 @@ public class SdcSchemaBuilder { */ final static String CREATE_KEYSPACE_NETWORK_TOPOLOGY_STRATEGY = "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class':'NetworkTopologyStrategy', %s};"; - private static Logger log = LoggerFactory.getLogger(SdcSchemaBuilder.class.getName()); + private static Logger log = Logger.getLogger(SdcSchemaBuilder.class.getName()); //TODO remove after 1707_OS migration private static void handle1707OSMigration(Map>> cassndraMetadata, Map> schemeData){ @@ -103,7 +105,7 @@ public class SdcSchemaBuilder { } return true; } catch (Exception e) { - log.info("createSchema failed with exception.", e); + log.error(EcompLoggerErrorCode.SCHEMA_ERROR, "creating Schema for Cassandra", "Cassandra", e.getLocalizedMessage()); } finally { if (session != null) { session.close(); @@ -147,7 +149,7 @@ public class SdcSchemaBuilder { System.out.println(cassndraMetadata); return true; } catch (Exception e) { - log.info("deleteSchema failed with exception.", e); + log.error(EcompLoggerErrorCode.SCHEMA_ERROR, "deleting Schema for Cassandra", "Cassandra", e.getLocalizedMessage()); } finally { if (session != null) { session.close(); @@ -174,25 +176,24 @@ public class SdcSchemaBuilder { * @return a map of maps of lists holding parsed info */ private static Map>> parseKeyspaceMetadata(List keyspacesMetadata) { - Map>> cassndraMetadata = keyspacesMetadata.stream() - .collect(Collectors.toMap(keyspaceMetadata -> keyspaceMetadata.getName(), - keyspaceMetadata -> keyspaceMetadata.getTables().stream() - .collect(Collectors.toMap(tableMetadata -> tableMetadata.getName(), - tableMetadata -> tableMetadata.getIndexes().stream() - .map(indexMetadata -> indexMetadata.getName()) - .collect(Collectors.toList()))))); - return cassndraMetadata; + return keyspacesMetadata.stream() +.collect(Collectors.toMap(KeyspaceMetadata::getName, + keyspaceMetadata -> keyspaceMetadata.getTables().stream() + .collect(Collectors.toMap(AbstractTableMetadata::getName, + tableMetadata -> tableMetadata.getIndexes().stream() + .map(IndexMetadata::getName) + .collect(Collectors.toList()))))); } private static Map>> getMetadataTablesStructure( List keyspacesMetadata) { return keyspacesMetadata.stream().collect( - Collectors.toMap(keyspaceMetadata -> keyspaceMetadata.getName(), - keyspaceMetadata -> keyspaceMetadata.getTables().stream().collect( - Collectors.toMap(tableMetadata -> tableMetadata.getName(), - tableMetadata -> tableMetadata.getColumns().stream().map( - columnMetadata -> columnMetadata.getName().toLowerCase()).collect( - Collectors.toList()))))); + Collectors.toMap(KeyspaceMetadata::getName, + keyspaceMetadata -> keyspaceMetadata.getTables().stream().collect( + Collectors.toMap(AbstractTableMetadata::getName, + tableMetadata -> tableMetadata.getColumns().stream().map( + columnMetadata -> columnMetadata.getName().toLowerCase()).collect( + Collectors.toList()))))); } /** @@ -311,19 +312,19 @@ public class SdcSchemaBuilder { if (createKeyspaceQuery != null) { log.trace("exacuting: {}", createKeyspaceQuery); session.execute(createKeyspaceQuery); - log.info("keyspace:{} created.", keyspace); + log.debug("keyspace:{} created.", keyspace); return true; } else { return false; } } else { - log.info( + log.error( "keyspace:{} not present in configuration, no info on replications is available. operation failed.", keyspace); return false; } } else { - log.info("keyspace:{} already exists skipping.", keyspace); + log.debug("keyspace:{} already exists skipping.", keyspace); return true; } } @@ -334,7 +335,7 @@ public class SdcSchemaBuilder { * @return a map of keyspaces to there table info */ private static Map> getSchemeData() { - Map> tablesByKeyspace = new HashMap>(); + Map> tablesByKeyspace = new HashMap<>(); Table[] tables = Table.values(); for (Table table : tables) { String keyspace = table.getTableDescription().getKeyspace().toLowerCase(); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java index ca737b2a5d..434a6e6eab 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java @@ -20,19 +20,17 @@ package org.openecomp.sdc.be.dao.cassandra.schema; -import java.util.List; - +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; import com.datastax.driver.core.SocketOptions; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; +import java.util.List; public class SdcSchemaUtils { - private static Logger log = LoggerFactory.getLogger(SdcSchemaUtils.class.getName()); + private static Logger log = Logger.getLogger(SdcSchemaUtils.class.getName()); /** * the method creates the cluster object using the supplied cassandra nodes @@ -48,7 +46,7 @@ public class SdcSchemaUtils { } log.info("connecting to node:{}.", nodes); Cluster.Builder clusterBuilder = Cluster.builder(); - nodes.forEach(host -> clusterBuilder.addContactPoint(host)); + nodes.forEach(clusterBuilder::addContactPoint); clusterBuilder.withMaxSchemaAgreementWaitSeconds(60); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java index 96bd68ac79..2e4a6329aa 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java @@ -20,27 +20,7 @@ package org.openecomp.sdc.be.dao.cassandra.schema; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.ArtifactTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.AuthEventTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.CategoryEventTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.ComponentCacheTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.ConsumerEventTableDefinition; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDeployEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDownloadEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribEngineEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribNotifEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribStatusEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.EcompOperationalEnvironmentEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.ExternalApiEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetCatHierEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.OperationalEnvironmentsTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.ResAdminEventTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.SdcSchemaFilesTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAccessEventTableDescription; -import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription; +import org.openecomp.sdc.be.dao.cassandra.schema.tables.*; public enum Table { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java index ad7cffaa63..5a7ebb4a14 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ArtifactTableDescription.java @@ -20,23 +20,22 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ArtifactTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(ID_FIELD, DataType.varchar())); + keys.add(new ImmutablePair<>(ID_FIELD, DataType.varchar())); return keys; } @@ -45,7 +44,7 @@ public class ArtifactTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (ArtifactFieldsDescription field : ArtifactFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java index ab2b207888..c0218fd126 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/AuthEventTableDescription.java @@ -20,29 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class AuthEventTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -51,7 +50,7 @@ public class AuthEventTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (AEFieldsDescription field : AEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java index facbd5209a..63aab3220c 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/CategoryEventTableDescription.java @@ -20,29 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class CategoryEventTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -51,7 +50,7 @@ public class CategoryEventTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (CEFieldsDescription field : CEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java index 1d60bec1cc..cb13e0ea15 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ComponentCacheTableDescription.java @@ -20,23 +20,22 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ComponentCacheTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(ID_FIELD, DataType.varchar())); + keys.add(new ImmutablePair<>(ID_FIELD, DataType.varchar())); return keys; } @@ -45,7 +44,7 @@ public class ComponentCacheTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (PartialComponentFieldsDescription field : PartialComponentFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java index 46664c6df8..f829724f4e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ConsumerEventTableDefinition.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ConsumerEventTableDefinition implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -52,7 +51,7 @@ public class ConsumerEventTableDefinition implements ITableDescription { Map> columns = new HashMap<>(); for (DEEFieldsDescription field : DEEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java index d28140ec7d..6f5b8ea34e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java @@ -1,28 +1,27 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class DistribBaseEventTableDesc implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -36,7 +35,7 @@ public abstract class DistribBaseEventTableDesc implements ITableDescription { Map> columns = new HashMap<>(); for (DistFieldsDescription field : DistFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } updateColumnDistribDescription(columns); return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java index ceacdeab0e..fefe55313c 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java @@ -20,12 +20,11 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.Map; public class DistribDeployEventTableDesc extends DistribBaseEventTableDesc { @@ -38,13 +37,13 @@ public class DistribDeployEventTableDesc extends DistribBaseEventTableDesc { @Override protected void updateColumnDistribDescription(Map> columns) { for (DSEFieldsDescription field : DSEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } //replace the base indexed flag value with the correct one for a given table: columns.put(DistFieldsDescription.STATUS.getName(), - new ImmutablePair(DistFieldsDescription.STATUS.getType(), true)); + new ImmutablePair<>(DistFieldsDescription.STATUS.getType(), true)); columns.put(DistFieldsDescription.SERVICE_INST_ID.getName(), - new ImmutablePair(DistFieldsDescription.SERVICE_INST_ID.getType(), true)); + new ImmutablePair<>(DistFieldsDescription.SERVICE_INST_ID.getType(), true)); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java index 61968be9ec..5dc18341cc 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java @@ -20,19 +20,18 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.Map; public class DistribDownloadEventTableDesc extends DistribBaseEventTableDesc { @Override protected void updateColumnDistribDescription(Map> columns) { for (DSEFieldsDescription field : DSEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java index 5b1aaee04e..84ebf0bc4c 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java @@ -20,23 +20,22 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.Map; public class DistribEngineEventTableDesc extends DistribBaseEventTableDesc { @Override protected void updateColumnDistribDescription(Map> columns) { for (DEEFieldsDescription field : DEEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } //replace the base indexed flag value with the correct one for a given table: columns.put(DistFieldsDescription.REQUEST_ID.getName(), - new ImmutablePair(DistFieldsDescription.REQUEST_ID.getType(), true)); + new ImmutablePair<>(DistFieldsDescription.REQUEST_ID.getType(), true)); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java index 7db070f2d5..ec9cf216f2 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java @@ -20,23 +20,22 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.Map; public class DistribNotifEventTableDesc extends DistribBaseEventTableDesc { @Override protected void updateColumnDistribDescription(Map> columns) { for (DNEFieldsDescription field : DNEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } //replace the base indexed flag value with the correct one for a given table: columns.put(DistFieldsDescription.SERVICE_INST_ID.getName(), - new ImmutablePair(DistFieldsDescription.SERVICE_INST_ID.getType(), true)); + new ImmutablePair<>(DistFieldsDescription.SERVICE_INST_ID.getType(), true)); } @Override diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java index bc5dcec41b..def5fe2bc1 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java @@ -20,19 +20,18 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.Map; public class DistribStatusEventTableDesc extends DistribBaseEventTableDesc{ @Override protected void updateColumnDistribDescription(Map> columns) { for (DSEFieldsDescription field : DSEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java index 556824f7ec..69f8f9be6a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java @@ -1,16 +1,11 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.*; public class EcompOperationalEnvironmentEventTableDesc implements ITableDescription { @@ -19,14 +14,14 @@ public class EcompOperationalEnvironmentEventTableDesc implements ITableDescript @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(OPERATIONAL_ENVIRONMENT_ID, DataType.varchar())); + keys.add(new ImmutablePair<>(OPERATIONAL_ENVIRONMENT_ID, DataType.varchar())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java index e35acc3790..4a88232cd5 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ExternalApiEventTableDesc.java @@ -20,29 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ExternalApiEventTableDesc implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -51,7 +50,7 @@ public class ExternalApiEventTableDesc implements ITableDescription { Map> columns = new HashMap<>(); for (EGAEFieldsDescription field : EGAEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java index 4e44bd2975..e186fd206d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetCatHierEventTableDesc.java @@ -20,29 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class GetCatHierEventTableDesc implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -51,7 +50,7 @@ public class GetCatHierEventTableDesc implements ITableDescription { Map> columns = new HashMap<>(); for (DEEFieldsDescription field : DEEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java index 92b10772e6..461c9b73f6 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUebClusterEventTableDesc.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class GetUebClusterEventTableDesc implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -52,7 +51,7 @@ public class GetUebClusterEventTableDesc implements ITableDescription { Map> columns = new HashMap<>(); for (DEEFieldsDescription field : DEEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java index cdb603de6c..9d1bb45459 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/GetUsersListEventTableDesc.java @@ -20,29 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class GetUsersListEventTableDesc implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -51,7 +50,7 @@ public class GetUsersListEventTableDesc implements ITableDescription { Map> columns = new HashMap<>(); for (DEEFieldsDescription field : DEEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java index 2e8c5ff024..3c260747df 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java @@ -1,19 +1,14 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MAJOR_VERSION; -import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MINOR_VERSION; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.*; + +import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MAJOR_VERSION; +import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MINOR_VERSION; public class MigrationTasksTableDescription implements ITableDescription { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java index ec2dd368e3..c80d99ee61 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OldExternalApiEventTableDesc.java @@ -20,29 +20,28 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class OldExternalApiEventTableDesc implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -51,7 +50,7 @@ public class OldExternalApiEventTableDesc implements ITableDescription { Map> columns = new HashMap<>(); for (EGAEFieldsDescription field : EGAEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java index e054eaf004..03d0bbaf53 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java @@ -1,17 +1,11 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.*; public class OperationalEnvironmentsTableDescription implements ITableDescription { @@ -22,7 +16,7 @@ public class OperationalEnvironmentsTableDescription implements ITableDescriptio @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair( ENVIRONMENT_ID, DataType.varchar())); + keys.add(new ImmutablePair<>(ENVIRONMENT_ID, DataType.varchar())); return keys; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java index f6c5689973..75762a39ed 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/ResAdminEventTableDescription.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ResAdminEventTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -52,7 +51,7 @@ public class ResAdminEventTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (AEFieldsDescription field : AEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java index 6235fb7843..8f740c1c1d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/SdcSchemaFilesTableDescription.java @@ -20,16 +20,15 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class SdcSchemaFilesTableDescription implements ITableDescription { @@ -40,15 +39,15 @@ public class SdcSchemaFilesTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(SDC_RELEASE_NUM, DataType.varchar())); - keys.add(new ImmutablePair(CONFORMANCE_LEVEL, DataType.varchar())); + keys.add(new ImmutablePair<>(SDC_RELEASE_NUM, DataType.varchar())); + keys.add(new ImmutablePair<>(CONFORMANCE_LEVEL, DataType.varchar())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP, DataType.timestamp())); return keys; } @@ -57,7 +56,7 @@ public class SdcSchemaFilesTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (SdcSchemaFilesFieldsDescription field : SdcSchemaFilesFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java index 93f5640c30..4e778b8c43 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAccessEventTableDescription.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; +import com.datastax.driver.mapping.annotations.Column; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; -import com.datastax.driver.mapping.annotations.Column; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class UserAccessEventTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -52,7 +51,7 @@ public class UserAccessEventTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (UAEFieldsDescription field : UAEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java index 0cfdc2e462..9dc8243a21 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/UserAdminEventTableDescription.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.dao.cassandra.schema.tables; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.datastax.driver.core.DataType; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; -import com.datastax.driver.core.DataType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class UserAdminEventTableDescription implements ITableDescription { @Override public List> primaryKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMEBASED_UUID_FIELD, DataType.timeuuid())); + keys.add(new ImmutablePair<>(TIMEBASED_UUID_FIELD, DataType.timeuuid())); return keys; } @Override public List> clusteringKeys() { List> keys = new ArrayList<>(); - keys.add(new ImmutablePair(TIMESTAMP_FIELD, DataType.timestamp())); + keys.add(new ImmutablePair<>(TIMESTAMP_FIELD, DataType.timestamp())); return keys; } @@ -52,7 +51,7 @@ public class UserAdminEventTableDescription implements ITableDescription { Map> columns = new HashMap<>(); for (UAEFieldsDescription field : UAEFieldsDescription.values()) { - columns.put(field.getName(), new ImmutablePair(field.type, field.indexed)); + columns.put(field.getName(), new ImmutablePair<>(field.type, field.indexed)); } return columns; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java index 111c63e53c..6360af8e04 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java @@ -4,16 +4,20 @@ import org.openecomp.sdc.be.dao.DAOTitanStrategy; import org.openecomp.sdc.be.dao.TitanClientStrategy; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.transactions.SimpleTitanTransactionManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @ComponentScan({ "org.openecomp.sdc.be.dao.jsongraph", }) +@EnableTransactionManagement public class TitanSpringConfig { @Bean(name = "titan-generic-dao") @@ -32,4 +36,9 @@ public class TitanSpringConfig { public TitanClientStrategy titanClientStrategy() { return new DAOTitanStrategy(); } + + @Bean + public PlatformTransactionManager txManager() { + return new SimpleTitanTransactionManager(titanGraphClient(titanClientStrategy())); + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java index c5d7d68b55..47ce679c29 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java @@ -20,18 +20,6 @@ package org.openecomp.sdc.be.dao.es; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.apache.commons.lang.SystemUtils; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; @@ -40,11 +28,21 @@ import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.elasticsearch.shield.ShieldPlugin; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; + /** * Prepare the node to work with elastic search. * @@ -53,7 +51,7 @@ import org.springframework.stereotype.Component; @Component("elasticsearch-client") public class ElasticSearchClient { - private static Logger log = LoggerFactory.getLogger(ElasticSearchClient.class.getName()); + private static Logger log = Logger.getLogger(ElasticSearchClient.class.getName()); private Node node; private boolean isLocal; @@ -63,7 +61,7 @@ public class ElasticSearchClient { String serverHost; String serverPort; - ArrayList nodes = new ArrayList(); + ArrayList nodes = new ArrayList<>(); private boolean isTransportClient; @@ -80,7 +78,7 @@ public class ElasticSearchClient { settings = Settings.settingsBuilder().loadFromPath(classpathConfig).build(); } String configHome = System.getProperty("config.home"); - if (configHome != null && false == configHome.isEmpty()) { + if (configHome != null && !configHome.isEmpty()) { try { if (SystemUtils.IS_OS_WINDOWS) { url = new URL("file:///" + configHome + "/elasticsearch.yml"); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java index 38648e69db..a6bb026a71 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/GraphElementFactory.java @@ -20,51 +20,18 @@ package org.openecomp.sdc.be.dao.graph; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.AttributeData; -import org.openecomp.sdc.be.resources.data.AttributeValueData; -import org.openecomp.sdc.be.resources.data.CapabilityData; -import org.openecomp.sdc.be.resources.data.CapabilityInstData; -import org.openecomp.sdc.be.resources.data.CapabilityTypeData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.ConsumerData; -import org.openecomp.sdc.be.resources.data.DataTypeData; -import org.openecomp.sdc.be.resources.data.GraphNodeLock; -import org.openecomp.sdc.be.resources.data.GroupData; -import org.openecomp.sdc.be.resources.data.GroupInstanceData; -import org.openecomp.sdc.be.resources.data.GroupTypeData; -import org.openecomp.sdc.be.resources.data.HeatParameterData; -import org.openecomp.sdc.be.resources.data.HeatParameterValueData; -import org.openecomp.sdc.be.resources.data.InputValueData; -import org.openecomp.sdc.be.resources.data.InputsData; -import org.openecomp.sdc.be.resources.data.InterfaceData; -import org.openecomp.sdc.be.resources.data.OperationData; -import org.openecomp.sdc.be.resources.data.PolicyTypeData; -import org.openecomp.sdc.be.resources.data.ProductMetadataData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.RelationshipInstData; -import org.openecomp.sdc.be.resources.data.RequirementData; -import org.openecomp.sdc.be.resources.data.RequirementImplData; -import org.openecomp.sdc.be.resources.data.ResourceCategoryData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.ServiceCategoryData; -import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.openecomp.sdc.be.resources.data.TagData; -import org.openecomp.sdc.be.resources.data.UserData; -import org.openecomp.sdc.be.resources.data.UserFunctionalMenuData; +import org.openecomp.sdc.be.resources.data.*; import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.category.GroupingData; import org.openecomp.sdc.be.resources.data.category.SubCategoryData; +import java.util.Map; + public class GraphElementFactory { public static T createElement(String label, GraphElementTypeEnum type, @@ -257,6 +224,8 @@ public class GraphElementFactory { case GroupInstance: element = clazz.cast(new GroupInstanceData(properties)); break; + case AnnotationType: + element = clazz.cast(new AnnotationTypeData(properties)); default: break; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java index 2858a81a60..6afecc4e0a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdge.java @@ -20,10 +20,10 @@ package org.openecomp.sdc.be.dao.graph.datatype; -import java.util.Map; - import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import java.util.Map; + public class GraphEdge { private GraphEdgeLabels edgeType; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java index 42a55c2c68..5e1efbfa06 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java @@ -20,14 +20,13 @@ package org.openecomp.sdc.be.dao.graph.datatype; -import java.util.List; -import java.util.Map; - +import com.google.gson.Gson; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.Gson; +import java.util.List; +import java.util.Map; public abstract class GraphNode extends GraphElement { @@ -50,8 +49,7 @@ public abstract class GraphNode extends GraphElement { } public ImmutablePair getKeyValueId() { - ImmutablePair keyValue = new ImmutablePair(getUniqueIdKey(), getUniqueId()); - return keyValue; + return new ImmutablePair<>(getUniqueIdKey(), getUniqueId()); } protected void addIfExists(Map map, GraphPropertiesDictionary property, Object value) { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java index b2237332f2..0c6b66f6d9 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java @@ -32,12 +32,12 @@ public class GraphRelation extends GraphElement { public GraphRelation() { super(GraphElementTypeEnum.Relationship); - properties = new HashMap(); + properties = new HashMap<>(); } public GraphRelation(String type) { super(GraphElementTypeEnum.Relationship); - properties = new HashMap(); + properties = new HashMap<>(); setType(type); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java index 65f4314b26..6a67a99fcf 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.dao.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.annotation.PostConstruct; - +import fj.data.Either; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; @@ -38,23 +30,24 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.*; +import java.util.Map.Entry; @Component("auditingDao") public class AuditingDao extends ESTimeBasedDao { - private static final String SERVICE_INSTANCE_ID_FIELD = AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID + private static final String SERVICE_INSTANCE_ID_FIELD = AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID .getDisplayName(); // "serviceInstanceId"; - private static final String STATUS_FIELD = AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(); // "status"; - private static final String ACTION_FIELD = AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(); // "action"; - private static final String DISTRIBUTION_ID_FIELD = AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(); // "distributionId"; - private static Logger log = LoggerFactory.getLogger(AuditingDao.class.getName()); + private static final String STATUS_FIELD = AuditingFieldsKey.AUDIT_STATUS.getDisplayName(); // "status"; + private static final String ACTION_FIELD = AuditingFieldsKey.AUDIT_ACTION.getDisplayName(); // "action"; + private static final String DISTRIBUTION_ID_FIELD = AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName(); // "distributionId"; + private static Logger log = Logger.getLogger(AuditingDao.class.getName()); public static final String AUDITING_INDEX = "auditingevents"; @PostConstruct @@ -70,12 +63,12 @@ public class AuditingDao extends ESTimeBasedDao { return AUDITING_INDEX; } - public ActionStatus addRecord(Map params, String type) { + public ActionStatus addRecord(Map params, String type) { // TODO rhalili - remove? check debugEnabled? - Map displayFields = new HashMap(); + Map displayFields = new HashMap<>(); StringBuilder sb = new StringBuilder(); - for (Entry entry : params.entrySet()) { + for (Entry entry : params.entrySet()) { displayFields.put(entry.getKey().getDisplayName(), entry.getValue()); sb.append(entry.getKey().getDisplayName()).append(" = ").append(entry.getValue()).append(","); } @@ -118,7 +111,7 @@ public class AuditingDao extends ESTimeBasedDao { return Either.left(remainingElements); } else { log.debug("not found distribution statuses for did {}", did); - remainingElements = new ArrayList(); + remainingElements = new ArrayList<>(); return Either.left(remainingElements); } @@ -126,7 +119,7 @@ public class AuditingDao extends ESTimeBasedDao { public Either, ActionStatus> getServiceDistributionStatusesList(String serviceInstanceId) { - List resList = new ArrayList(); + List resList = new ArrayList<>(); QueryBuilder componentNameMatch = QueryBuilders.matchQuery(SERVICE_INSTANCE_ID_FIELD, serviceInstanceId); QueryBuilder componentVersionMatch = QueryBuilders.matchQuery(ACTION_FIELD, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); @@ -185,12 +178,12 @@ public class AuditingDao extends ESTimeBasedDao { } public Either, ActionStatus> getFilteredResourceAdminAuditingEvents( - Map filterMap) { + Map filterMap) { - Iterator> filterItr = filterMap.entrySet().iterator(); + Iterator> filterItr = filterMap.entrySet().iterator(); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); while (filterItr.hasNext()) { - Entry curr = filterItr.next(); + Entry curr = filterItr.next(); boolQuery = boolQuery.must(QueryBuilders.termQuery(curr.getKey().getDisplayName(), curr.getValue())); } @@ -235,25 +228,25 @@ public class AuditingDao extends ESTimeBasedDao { } - private void populateCommonFields(Map params, + private void populateCommonFields(Map params, AuditingGenericEvent timeBasedIndexedData) { - String dateStr = (String) params.get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP); + String dateStr = (String) params.get(AuditingFieldsKey.AUDIT_TIMESTAMP); if (dateStr != null) { timeBasedIndexedData.setTimestamp(dateStr); } - timeBasedIndexedData.setAction((String) params.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); - Object statusObj = params.get(AuditingFieldsKeysEnum.AUDIT_STATUS); + timeBasedIndexedData.setAction((String) params.get(AuditingFieldsKey.AUDIT_ACTION)); + Object statusObj = params.get(AuditingFieldsKey.AUDIT_STATUS); // For BC. status was Integer and is String if (statusObj != null) { timeBasedIndexedData.setStatus(String.valueOf(statusObj)); } else { timeBasedIndexedData.setStatus(null); } - // timeBasedIndexedData.setStatus((String)params.get(AuditingFieldsKeysEnum.AUDIT_STATUS)); - timeBasedIndexedData.setDesc((String) params.get(AuditingFieldsKeysEnum.AUDIT_DESC)); + // timeBasedIndexedData.setStatus((String)params.get(AuditingFieldsKey.AUDIT_STATUS)); + timeBasedIndexedData.setDesc((String) params.get(AuditingFieldsKey.AUDIT_DESC)); timeBasedIndexedData - .setServiceInstanceId((String) params.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID)); - timeBasedIndexedData.setRequestId((String) params.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID)); + .setServiceInstanceId((String) params.get(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID)); + timeBasedIndexedData.setRequestId((String) params.get(AuditingFieldsKey.AUDIT_REQUEST_ID)); } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java index 985875e200..c3dc886f85 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java @@ -20,14 +20,8 @@ package org.openecomp.sdc.be.dao.impl; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - +import com.fasterxml.jackson.core.JsonProcessingException; +import fj.data.Either; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.unit.TimeValue; @@ -39,19 +33,23 @@ import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.exception.ResourceDAOException; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonProcessingException; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; @Component("resource-dao") public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO { - private static Logger log = LoggerFactory.getLogger(ESCatalogDAO.class.getName()); - private static Logger healthCheckLogger = LoggerFactory.getLogger("elasticsearch.healthcheck"); + private static Logger log = Logger.getLogger(ESCatalogDAO.class.getName()); + + //TODO use LoggerMetric instead + private static Logger healthCheckLogger = Logger.getLogger("elasticsearch.healthcheck"); ///// HealthCheck///////// private static final String ES_HEALTH_CHECK_STR = "elasticsearchHealthCheck"; @@ -67,7 +65,7 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO { private class HealthCheckScheduledTask implements Runnable { @Override public void run() { - healthCheckLogger.trace("Executing ELASTICSEARCH Health Check Task - Start"); + log.trace("Executing ELASTICSEARCH Health Check Task - Start"); HealthCheckStatus healthStatus = null; try { @@ -77,7 +75,7 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO { getEsClient().getServerHost(), getEsClient().getServerPort(), e.getMessage(), e); healthStatus = HealthCheckStatus.DOWN; } - healthCheckLogger.trace("Executed ELASTICSEARCH Health Check Task - Status = {}", healthStatus); + log.trace("Executed ELASTICSEARCH Health Check Task - Status = {}", healthStatus); if (healthStatus != lastHealthState) { log.trace("ELASTICSEARCH Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); lastHealthState = healthStatus; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java index 252240b164..dc944d016e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java @@ -20,13 +20,8 @@ package org.openecomp.sdc.be.dao.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.elasticsearch.action.index.IndexResponse; @@ -41,16 +36,18 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class ESTimeBasedDao { private static final String SCORE_SCRIPT = "_score * ((doc.containsKey('alienScore') && !doc['alienScore'].empty) ? doc['alienScore'].value : 1)"; private static final int MAX_SEARCH_SIZE = 1000; - private static Logger log = LoggerFactory.getLogger(ESTimeBasedDao.class.getName()); + private static Logger log = Logger.getLogger(ESTimeBasedDao.class.getName()); private Gson gson; @@ -71,7 +68,7 @@ public abstract class ESTimeBasedDao { @Resource(name = "elasticsearch-client") private ElasticSearchClient esClient; - protected final Map> typesToClasses = new HashMap>(); + protected final Map> typesToClasses = new HashMap<>(); public abstract String getIndexPrefix(); @@ -99,7 +96,7 @@ public abstract class ESTimeBasedDao { res = ActionStatus.GENERAL_ERROR; } } catch (Exception e) { - log.error("Couldn't serialize object of type {} | error:", typeName, e); + log.error("Couldn't serialize object of type {}", typeName, e.getMessage()); res = ActionStatus.GENERAL_ERROR; } return res; @@ -137,7 +134,7 @@ public abstract class ESTimeBasedDao { } private void setIndexPrefix2CreationPeriod() { - indexPrefix2CreationPeriod = new HashMap(); + indexPrefix2CreationPeriod = new HashMap<>(); List indicesTimeFrequencyEntries = configurationManager.getConfiguration() .getElasticSearch().getIndicesTimeFrequency(); for (IndicesTimeFrequencyEntry entry : indicesTimeFrequencyEntries) { @@ -199,7 +196,7 @@ public abstract class ESTimeBasedDao { if (!somethingFound(response)) { return null; } else { - List hits = new ArrayList(); + List hits = new ArrayList<>(); for (int i = 0; i < response.getHits().getHits().length; i++) { String hit = response.getHits().getAt(i).sourceAsString(); @@ -226,7 +223,7 @@ public abstract class ESTimeBasedDao { if (!somethingFound(response)) { return null; } else { - List hits = new ArrayList(); + List hits = new ArrayList<>(); for (int i = 0; i < response.getHits().getHits().length; i++) { String hit = response.getHits().getAt(i).sourceAsString(); @@ -247,7 +244,7 @@ public abstract class ESTimeBasedDao { throws JSONException { List results = doCustomFindForEvent(typeName, query, sortBuilder, MAX_SEARCH_SIZE); if (results == null) { - results = new ArrayList(); + results = new ArrayList<>(); } return results; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java index 04d985bc83..d6502b71c8 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java @@ -20,19 +20,18 @@ package org.openecomp.sdc.be.dao.impl; -import javax.annotation.Resource; - import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; +import javax.annotation.Resource; + @Component("esHealthCheckDao") public class EsHealthCheckDao implements IEsHealthCheckDao { - private static Logger logger = LoggerFactory.getLogger(EsHealthCheckDao.class.getName()); + private static Logger logger = Logger.getLogger(EsHealthCheckDao.class.getName()); @Resource(name = "elasticsearch-client") private ElasticSearchClient esClient; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java new file mode 100644 index 0000000000..7a5f873549 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.api.IElementDAO; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.List; + +//@Component("elements-dao") +public class Neo4jElementDAO implements IElementDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jElementDAO.class.getName()); + + @Override + public Either, ActionStatus> getAllCategories() { + MatchFilter filter = new MatchFilter(); + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.ResourceCategory.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + return Either.left(value); + } + } + } + + @Override + public Either, ActionStatus> getAllTags() { + MatchFilter filter = new MatchFilter(); + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.Tag.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List value = status.left().value(); + if (value == null) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + return Either.left(value); + } + } + } + + @Override + public Either getCategory(String name) { + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.NAME.getProperty(), name); + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.ResourceCategory.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List value = status.left().value(); + if (value == null) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + return Either.left(value.get(0)); + } + } + + } + + /** + * FOR TEST ONLY + * + * @param neo4jClient + */ + public void setNeo4jClient(Neo4jClient neo4jClient) { + this.neo4jClient = neo4jClient; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java new file mode 100644 index 0000000000..8c3c5795a9 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import org.openecomp.sdc.be.dao.api.BasicDao; +import org.openecomp.sdc.be.dao.api.IPropertyDAO; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jGraphBatchBuilder; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; + +//@Component("neo4j-property-dao") +public class Neo4jPropertyDAO extends BasicDao implements IPropertyDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jPropertyDAO.class.getName()); + + Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder(); + + public Neo4jPropertyDAO() { + + } + + @PostConstruct + public void init() { + setNeo4jClient(neo4jClient); + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java new file mode 100644 index 0000000000..9cf75f15e3 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.BasicDao; +import org.openecomp.sdc.be.dao.api.IResourceDAO; +import org.openecomp.sdc.be.dao.graph.datatype.*; +import org.openecomp.sdc.be.dao.neo4j.*; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; + +//@Component("neo4j-resource-dao") +public class Neo4jResourceDAO extends BasicDao implements IResourceDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jResourceDAO.class.getName()); + + Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder(); + + public Neo4jResourceDAO() { + + } + + @PostConstruct + public void init() { + super.setNeo4jClient(neo4jClient); + } + + private String findResourceDataIdFromNodes(List nodes) { + + if (nodes != null) { + + for (GraphNode neo4jNode : nodes) { + String label = neo4jNode.getLabel(); + if (label.equals(NodeTypeEnum.Resource.getName())) { + return neo4jNode.getUniqueId().toString(); + } + } + } + + return null; + } + + private GraphRelation addStateRelation(RelationEndPoint from, RelationEndPoint to, GraphEdgeLabels edgeLabel, + String value) { + + GraphRelation relationState = new GraphRelation(); + relationState.setFrom(from); + relationState.setTo(to); + relationState.setType(edgeLabel.name()); + relationState.setAction(ActionEnum.Create); + return relationState; + } + + // private ActionStatus convertNeo4jOperationStatusToActionStatus( + // Neo4jOperationStatus value) { + // + // if (value == null) { + // return ActionStatus.GENERAL_ERROR; + // } + // + // switch (value) { + // case NOT_FOUND: + // return ActionStatus.RESOURCE_NOT_FOUND; + // case ERROR: + // return ActionStatus.GENERAL_ERROR; + // case NOT_SUPPORTED: + // return ActionStatus.INVALID_CONTENT; + // case WRONG_INPUT: + // return ActionStatus.INVALID_CONTENT; + // case OK: + // return ActionStatus.OK; + // default: + // return ActionStatus.GENERAL_ERROR; + // } + // + // } + + @Override + public Either getResourceData(String id) { + + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), id); + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.Resource.getName(), filter); + + if (status.isRight()) { + return Either.right(status.right().value()); + } else { + List value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(Neo4jOperationStatus.NOT_FOUND); + } else { + return Either.left((ResourceMetadataData) value.get(0)); + } + } + } + + @Override + public Either getNumberOfResourcesByName(String name) { + + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.NAME.getProperty(), name); + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.Resource.getName(), filter); + + if (status.isRight() || (status.left().value() == null)) { + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } else { + List value = status.left().value(); + return Either.left(value.size()); + } + } + + @Override + public void setNeo4jClient(Neo4jClient client) { + this.neo4jClient = client; + super.setNeo4jClient(client); + } + + @Override + public Either, Neo4jOperationStatus> getAllResourcesData( + Map propertiesToMatch) { + + RecursiveFilter filter = new RecursiveFilter(NodeTypeEnum.Resource); + // filter.addRelationType("typeof").addRelationType("belong").setProperties(propertiesToMatch); + + Either>, Neo4jOperationStatus> ret = neo4jClient.executeGet(filter); + if (ret.isRight()) { + return Either.right(ret.right().value()); + } + List> listOfListOfNeo4jElement = ret.left().value(); + + for (List row : listOfListOfNeo4jElement) { + + for (GraphElement elem : row) { + + } + } + return Either.right(null); + + /* + * MatchFilter filter = new MatchFilter(); if(propertiesToMatch != + * null){ for (Entry propertie : + * propertiesToMatch.entrySet()){ filter.addToMatch(propertie.getKey(), + * propertie.getValue()); } } Either, + * Neo4jOperationStatus> status = + * neo4jClient.getByFilter(GraphElementTypeEnum.Node, + * NodeTypeEnum.Resource.getName(), filter); if (status.isRight()) { + * return Either.right(status.right().value()); } else { + * List value = status.left().value(); if (value == null + * || value.isEmpty()) { return + * Either.right(Neo4jOperationStatus.NOT_FOUND); } else { + * List result=new ArrayList<>(); for(GraphElement element + * : value ){ result.add((ResourceData)element); } return + * Either.left(result); } } + */ + } + + // @Override + // public ActionStatus updateUserData(UserData userData) { + // UpdateFilter filter = new UpdateFilter(); + // filter.addToMatch("userId", userData.getUserId()); + // filter.setToUpdate(userData.toMap()); + // Neo4jOperationStatus status = + // neo4jClient.updateElement(Neo4JElementTypeEnum.Node, + // NodeTypeEnum.User.getName(), filter); + // if (status.equals(Neo4jOperationStatus.OK)) { + // return ActionStatus.OK; + // } else { + // return ActionStatus.GENERAL_ERROR; + // } + // } + // + // @Override + // public ActionStatus deleteUserData(String id) { + // MatchFilter filter = new MatchFilter(); + // filter.addToMatch("userId", id); + // Neo4jOperationStatus status = + // neo4jClient.deleteElement(Neo4JElementTypeEnum.Node, + // NodeTypeEnum.User.getName(), filter); + // if (status.equals(Neo4jOperationStatus.OK)) { + // return ActionStatus.OK; + // } else { + // return ActionStatus.GENERAL_ERROR; + // } + // } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java new file mode 100644 index 0000000000..448b3e31a1 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.api.IUsersDAO; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.UpdateFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +//@Component("users-dao") +public class Neo4jUsersDAO implements IUsersDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jUsersDAO.class.getName()); + + public Neo4jUsersDAO() { + + } + + @PostConstruct + public void init() { + } + + private void createIndexesAndConstraints() { + Either>, Neo4jOperationStatus> statusInd = neo4jClient + .getIndexes(NodeTypeEnum.User.getName()); + if (statusInd.isRight()) { + logger.error("Failed to get indexes from Neo4j graph"); + throw new RuntimeException("Failed to initialize Neo4jUsersDAO - Failed to get indexes from Neo4j graph"); + } + Map> indexes = statusInd.left().value(); + if (indexes == null || indexes.isEmpty()) { + logger.info("Define users indexes in Neo4j"); + List propertyNames = new ArrayList<>(); + propertyNames.add("firstName"); + propertyNames.add("lastName"); + propertyNames.add("email"); + propertyNames.add("role"); + logger.info("Start create Users indexes in Neo4jGraph"); + Neo4jOperationStatus createIndexStatus = neo4jClient.createIndex(NodeTypeEnum.User.getName(), + propertyNames); + if (createIndexStatus.equals(Neo4jOperationStatus.OK)) { + logger.info("Users indexes created in Neo4j"); + List propertyUnique = new ArrayList<>(); + propertyUnique.add("userId"); + + logger.info("Start create Users constraints in Neo4jGraph"); + Neo4jOperationStatus createUniquenessStatus = neo4jClient + .createUniquenessConstraints(NodeTypeEnum.User.getName(), propertyUnique); + if (createUniquenessStatus.equals(Neo4jOperationStatus.OK)) { + logger.info("Users constraints creatyed in Neo4j"); + } else { + logger.error("Failed to create constraints in Neo4j graph [{}]", createUniquenessStatus); + throw new RuntimeException( + "Failed to initialize Neo4jUsersDAO - Failed to create constraints in Neo4j graph"); + } + } else { + logger.error("Failed to create indexes in Neo4j graph [{}]", createIndexStatus); + throw new RuntimeException( + "Failed to initialize Neo4jUsersDAO - Failed to create indexes in Neo4j graph"); + } + } else { + logger.info("Users indexes already defined in Neo4j"); + } + } + + @Override + public Either getUserData(String id) { + MatchFilter filter = new MatchFilter(); + filter.addToMatch("userId", id); + Either, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.User.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(ActionStatus.USER_NOT_FOUND); + } else { + return Either.left((UserData) value.get(0)); + } + } + } + + @Override + public ActionStatus saveUserData(UserData userData) { + Neo4jOperationStatus status = neo4jClient.createElement(userData); + if (status.equals(Neo4jOperationStatus.OK)) { + return ActionStatus.OK; + } else { + return ActionStatus.GENERAL_ERROR; + } + } + + @Override + public ActionStatus updateUserData(UserData userData) { + UpdateFilter filter = new UpdateFilter(); + filter.addToMatch("userId", userData.getUserId()); + filter.setToUpdate(userData.toGraphMap()); + Neo4jOperationStatus status = neo4jClient.updateElement(GraphElementTypeEnum.Node, NodeTypeEnum.User.getName(), + filter); + if (status.equals(Neo4jOperationStatus.OK)) { + return ActionStatus.OK; + } else { + return ActionStatus.GENERAL_ERROR; + } + } + + @Override + public ActionStatus deleteUserData(String id) { + MatchFilter filter = new MatchFilter(); + filter.addToMatch("userId", id); + Neo4jOperationStatus status = neo4jClient.deleteElement(GraphElementTypeEnum.Node, NodeTypeEnum.User.getName(), + filter); + if (status.equals(Neo4jOperationStatus.OK)) { + return ActionStatus.OK; + } else { + return ActionStatus.GENERAL_ERROR; + } + } + + public Neo4jClient getNeo4jClient() { + return neo4jClient; + } + + public void setNeo4jClient(Neo4jClient neo4jClient) { + this.neo4jClient = neo4jClient; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java index d38e9c03df..74852944d0 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java @@ -20,19 +20,19 @@ package org.openecomp.sdc.be.dao.jsongraph; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - +import com.thinkaurelius.titan.core.TitanVertex; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.InstantiationTypes; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import com.thinkaurelius.titan.core.TitanVertex; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; public class GraphVertex { private String uniqueId; @@ -59,6 +59,7 @@ public class GraphVertex { public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; + addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); } public Map getJson() { @@ -86,8 +87,7 @@ public class GraphVertex { } public ComponentTypeEnum getType() { - ComponentTypeEnum type = ComponentTypeEnum.valueOf((String) getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)); - return type; + return ComponentTypeEnum.valueOf((String) getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)); } public void setType(ComponentTypeEnum type) { @@ -118,6 +118,14 @@ public class GraphVertex { this.metadataProperties = metadataProperties; } + public void getOrSetDefaultInstantiationTypeForToscaElementJson(){ + String toscaVertexJsonInstantiationType; + toscaVertexJsonInstantiationType = (String)(this.getJsonMetadataField(JsonPresentationFields.INSTANTIATION_TYPE)); + if (toscaVertexJsonInstantiationType == StringUtils.EMPTY || toscaVertexJsonInstantiationType == null){ + this.setJsonMetadataField(JsonPresentationFields.INSTANTIATION_TYPE, InstantiationTypes.A_LA_CARTE.getValue()); + }; + }; + public Map getMetadataJson() { return metadataJson; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java index d17a3d5b17..ab95cdbba9 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java @@ -20,21 +20,11 @@ package org.openecomp.sdc.be.dao.jsongraph; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import com.thinkaurelius.titan.core.*; +import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.*; import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; @@ -48,1073 +38,1041 @@ import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.TitanVertexQuery; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; -import fj.data.Either; +import static org.apache.commons.collections.CollectionUtils.isEmpty; @Component("titan-dao") public class TitanDao { - TitanGraphClient titanClient; - - private static Logger logger = LoggerFactory.getLogger(TitanDao.class.getName()); - - public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) { - this.titanClient = titanClient; - logger.info("** TitanDao created"); - } - - public TitanOperationStatus commit() { - logger.debug("doing commit."); - return titanClient.commit(); - } - - public TitanOperationStatus rollback() { - return titanClient.rollback(); - } - - public Either getGraph() { - return titanClient.getGraph(); - } - - /** - * - * @param graphVertex - * @return - */ - public Either createVertex(GraphVertex graphVertex) { - logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId()); - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanVertex vertex = tGraph.addVertex(); - - setVertexProperties(vertex, graphVertex); - - graphVertex.setVertex(vertex); - - return Either.left(graphVertex); - - } catch (Exception e) { - logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value()); - return Either.right(graph.right().value()); - } - } - - /** - * - * @param name - * @param value - * @param label - * @return - */ - public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, - VertexTypeEnum label) { - return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll); - } - - public Either getVertexByLabel(VertexTypeEnum label) { - return titanClient.getGraph().left() - .map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()) - .left().bind(titanVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, titanVertices)); - } - - private Either getFirstFoundVertex(JsonParseFlagEnum parseFlag, - Iterable vertices) { - Iterator iterator = vertices.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - return Either.left(graphVertex); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - /** - * - * @param name - * @param value - * @param label - * @param parseFlag - * @return - */ - public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, - VertexTypeEnum label, JsonParseFlagEnum parseFlag) { - - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable vertecies = tGraph.query().has(name.getProperty(), value) - .has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices(); - - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - return Either.left(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, - label); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, - graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - /** - * - * @param id - * @return - */ - public Either getVertexById(String id) { - return getVertexById(id, JsonParseFlagEnum.ParseAll); - } - - /** - * - * @param id - * @param parseFlag - * @return - */ - public Either getVertexById(String id, JsonParseFlagEnum parseFlag) { - - Either graph = titanClient.getGraph(); - if (id == null) { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id = {} ", id); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id) - .vertices(); - - java.util.Iterator iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - return Either.left(graphVertex); - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id = {}", id); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for id {} ", id); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException { - - if (graphVertex.getMetadataProperties() != null) { - for (Map.Entry entry : graphVertex.getMetadataProperties().entrySet()) { - if (entry.getValue() != null) { - vertex.property(entry.getKey().getProperty(), entry.getValue()); - } - } - } - vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName()); - - Map json = graphVertex.getJson(); - if (json != null) { - String jsonStr = JsonParserUtils.toJson(json); - vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); - - } - Map jsonMetadata = graphVertex.getMetadataJson(); - if (jsonMetadata != null) { - String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata); - vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr); - } - } - - public void setVertexProperties(Vertex vertex, Map properties) throws IOException { - for (Map.Entry entry : properties.entrySet()) { - if (entry.getValue() != null) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - } - - private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) { - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setVertex(vertex); - parseVertexProperties(graphVertex, parseFlag); - return graphVertex; - } - - public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) { - TitanVertex vertex = graphVertex.getVertex(); - Map properties = getVertexProperties(vertex); - VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); - for (Map.Entry entry : properties.entrySet()) { - GraphPropertyEnum key = entry.getKey(); - switch (key) { - case UNIQUE_ID: - graphVertex.setUniqueId((String) entry.getValue()); - break; - case LABEL: - graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue())); - break; - case COMPONENT_TYPE: - String type = (String) entry.getValue(); - if (type != null) { - graphVertex.setType(ComponentTypeEnum.valueOf(type)); - } - break; - case JSON: - if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) { - String json = (String) entry.getValue(); - Map jsonObj = JsonParserUtils.toMap(json, - label.getClassOfJson()); - graphVertex.setJson(jsonObj); - } - break; - case METADATA: - if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) { - String json = (String) entry.getValue(); - Map metadatObj = JsonParserUtils.toMap(json); - graphVertex.setMetadataJson(metadatObj); - } - break; - default: - graphVertex.addMetadataProperty(key, entry.getValue()); - break; - } - } - } - - public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, - Map properties) { - return createEdge(from.getVertex(), to.getVertex(), label, properties); - } - - public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, - Map properties) { - logger.trace("Try to connect {} with {} label {} properties {}", - from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties); - if (from == null || to == null) { - logger.trace("No Titan vertex for id from {} or id to {}", - from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - return TitanOperationStatus.NOT_FOUND; - } - Edge edge = from.addEdge(label.name(), to); - setEdgeProperties(edge, properties); - return TitanOperationStatus.OK; - } - - public Map getVertexProperties(Element element) { - - Map result = new HashMap(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map propertyMap = ElementHelper.propertyMap(element, - element.keys().toArray(new String[element.keys().size()])); - - for (Entry entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key); - if (valueOf != null) { - result.put(valueOf, value); - } - } - } - return result; - } - - public Map getEdgeProperties(Element element) { - - Map result = new HashMap(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map propertyMap = ElementHelper.propertyMap(element, - element.keys().toArray(new String[element.keys().size()])); - - for (Entry entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key); - if (valueOf != null) { - result.put(valueOf, value); - } - } - } - return result; - } - - public void setEdgeProperties(Element element, Map properties) { - - if (properties != null && !properties.isEmpty()) { - - Object[] propertyKeyValues = new Object[properties.size() * 2]; - int i = 0; - for (Entry entry : properties.entrySet()) { - propertyKeyValues[i++] = entry.getKey().getProperty(); - propertyKeyValues[i++] = entry.getValue(); - } - - ElementHelper.attachProperties(element, propertyKeyValues); - - } - - } - - public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, - Map props) { - return getByCriteria(type, props, JsonParseFlagEnum.ParseAll); - } - - public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, - Map props, JsonParseFlagEnum parseFlag) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - if (type != null) { - query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); - } - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - Iterable vertices = query.vertices(); - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator iterator = vertices.iterator(); - List result = new ArrayList(); - - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - - Map newProp = getVertexProperties(vertex); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - result.add(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug( - "Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", - type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, - graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, - Map props, Map hasNotProps, - JsonParseFlagEnum parseFlag) { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery query = tGraph.query(); - if (type != null) { - query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); - } - - if (props != null && !props.isEmpty()) { - for (Map.Entry entry : props.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - if (hasNotProps != null && !hasNotProps.isEmpty()) { - for (Map.Entry entry : hasNotProps.entrySet()) { - if (entry.getValue() instanceof List) { - buildMultipleNegateQueryFromList(entry, query); - } else { - query = query.hasNot(entry.getKey().getProperty(), entry.getValue()); - } - } - } - Iterable vertices = query.vertices(); - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator iterator = vertices.iterator(); - List result = new ArrayList(); - - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - - Map newProp = getVertexProperties(vertex); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - result.add(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug( - "Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", - type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, - graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either, TitanOperationStatus> getCatalogVerticies() { - Either graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - Iterable vCatalogIter = tGraph.query() - .has(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()).vertices(); - if (vCatalogIter == null) { - logger.debug("Failed to fetch catalog vertex"); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - TitanVertex catalogV = vCatalogIter.iterator().next(); - if (catalogV == null) { - logger.debug("Failed to fetch catalog vertex"); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - Iterator vertices = catalogV.vertices(Direction.OUT, EdgeLabelEnum.CATALOG_ELEMENT.name()); - - return Either.left(vertices); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria: ", e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria : ", graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - private void buildMultipleNegateQueryFromList(Map.Entry entry, TitanGraphQuery query) { - List negateList = (List) entry.getValue(); - for (Object listItem : negateList) { - query.hasNot(entry.getKey().getProperty(), listItem); - } - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, - JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, - edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, - JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, - parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - public Either getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, - JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, - parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - public Either getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, - JsonParseFlagEnum parseFlag) { - Either, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, - parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - List value = childrenVertecies.left().value(); - if (value.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - return Either.left(value.get(0)); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, - EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); - } - - public Either, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, - EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); - } - - public Either, TitanOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, - JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); - } - - private Either, TitanOperationStatus> getAdjacentVerticies(Vertex parentVertex, - EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { - List list = new ArrayList<>(); - try { - Either graphRes = titanClient.getGraph(); - if (graphRes.isRight()) { - logger.error("Failed to retrieve graph. status is {}", graphRes); - return Either.right(graphRes.right().value()); - } - Iterator edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name()); - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - TitanVertex vertex; - if (direction == Direction.IN) { - vertex = (TitanVertex) edge.outVertex(); - } else { - vertex = (TitanVertex) edge.inVertex(); - } - // GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - list.add(vertex); - } - } - if (true == list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - logger.error("Failed to perform graph operation ", e); - Either.right(TitanGraphClient.handleTitanException(e)); - } - - return Either.left(list); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either, TitanOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, - JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); - } - - private Either, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, - EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { - List list = new ArrayList(); - - Either, TitanOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), - edgeLabel, parseFlag, direction); - if (adjacentVerticies.isRight()) { - return Either.right(adjacentVerticies.right().value()); - } - adjacentVerticies.left().value().stream().forEach(vertex -> { - list.add(createAndFill((TitanVertex) vertex, parseFlag)); - }); - - return Either.left(list); - } - - /** - * Searches Edge by received label and criteria - * - * @param vertex - * @param label - * @param properties - * @return found edge or TitanOperationStatus - */ - public Either getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, - Map properties) { - - Either result = null; - Edge matchingEdge = null; - String notFoundMsg = "No edges in graph for criteria"; - try { - TitanVertexQuery query = vertex.getVertex().query().labels(label.name()); - - if (properties != null && !properties.isEmpty()) { - for (Map.Entry entry : properties.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - - Iterable edges = query.edges(); - if (edges == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } else { - Iterator eIter = edges.iterator(); - if (eIter.hasNext()) { - matchingEdge = eIter.next(); - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } - if (result == null) { - result = Either.left(matchingEdge); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Exception occured during getting edge by criteria for component with id {}. {}", - vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - /** - * Deletes Edge by received label and criteria - * - * @param vertex - * @param label - * @param properties - * @return - */ - public Either deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, - Map properties) { - Either result = null; - try { - result = getBelongingEdgeByCriteria(vertex, label, properties); - if (result.isLeft()) { - Edge edge = result.left().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, - "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), - vertex.getUniqueId()); - edge.remove(); - result = Either.left(edge); - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), - vertex.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Exception occured during deleting an edge by criteria for the component with id {}. {}", - vertex == null ? "NULL" : vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - @SuppressWarnings("unchecked") - /** - * Deletes an edge between vertices fromVertex and toVertex according to - * received label - * - * @param fromVertex - * @param toVertex - * @param label - * @return - */ - - public Either deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, - EdgeLabelEnum label) { - return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), - toVertex.getUniqueId()); - } - - public Either deleteEdge(TitanVertex fromVertex, TitanVertex toVertex, - EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo) { - Either result = null; - try { - Iterable edges = fromVertex.query().labels(label.name()).edges(); - Iterator eIter = edges.iterator(); - while (eIter.hasNext()) { - Edge edge = eIter.next(); - String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty()); - if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, - "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), - uniqueIdFrom, uniqueIdTo); - edge.remove(); - result = Either.left(edge); - break; - } - } - if (result == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), - uniqueIdFrom, uniqueIdTo); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", - label.name(), uniqueIdFrom, uniqueIdTo, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, - EdgeLabelEnum label) { - try { - Iterator edges = fromVertex.getVertex().edges(direction, label.name()); - - while (edges.hasNext()) { - Edge edge = edges.next(); - edge.remove(); - } - } catch (Exception e) { - logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, - direction, e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - /** - * Updates vertex properties. Note that graphVertex argument should contain - * updated data - * - * @param graphVertex - * @return - */ - public Either updateVertex(GraphVertex graphVertex) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, - "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId()); - try { - graphVertex.updateMetadataJsonWithCurrentMetadataProperties(); - setVertexProperties(graphVertex.getVertex(), graphVertex); - - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return Either.left(graphVertex); - } - - /** - * Fetches vertices by uniqueId according to received parse flag - * - * @param verticesToGet - * @return - */ - public Either, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag( - Map> verticesToGet) { - - Either, TitanOperationStatus> result = null; - Map vertices = new HashMap<>(); - TitanOperationStatus titatStatus; - Either getVertexRes = null; - for (Map.Entry> entry : verticesToGet.entrySet()) { - if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) { - getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue()); - } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) { - getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), - VertexTypeEnum.USER, entry.getValue().getValue()); - } - if (getVertexRes == null) { - titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus); - result = Either.right(titatStatus); - } - if (getVertexRes.isRight()) { - titatStatus = getVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus); - result = Either.right(titatStatus); - break; - } else { - vertices.put(entry.getKey(), getVertexRes.left().value()); - } - } - if (result == null) { - result = Either.left(vertices); - } - return result; - } - - /** - * Creates edge between "from" and "to" vertices with specified label and - * properties extracted from received edge - * - * @param from - * @param to - * @param label - * @param edgeToCopy - * @return - */ - public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) { - return createEdge(from, to, label, getEdgeProperties(edgeToCopy)); - } - - public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, - EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { - - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, - "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, - fromVertex == null ? "NULL" : fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - toVertex == null ? "NULL" : toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge); - if (result == TitanOperationStatus.OK) { - prevEdge.remove(); - } - return result; - } - - /** - * Replaces previous label of edge with new label - * - * @param fromVertex - * @param toVertex - * @param prevLabel - * @param newLabel - * @return - */ - public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, - EdgeLabelEnum newLabel) { - - TitanOperationStatus result = null; - Iterator prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name()); - if (prevEdgeIter == null || !prevEdgeIter.hasNext()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, - fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - result = TitanOperationStatus.NOT_FOUND; - } - if (result == null) { - result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel); - } - return result; - } - - /** - * Updates metadata properties of vertex on graph. Json metadata property of the - * vertex will be updated with received properties too. - * - * - * @param vertex - * @param properties - * @return - */ - public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, - Map properties) { - try { - if (!MapUtils.isEmpty(properties)) { - String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value(); - Map jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr); - for (Map.Entry property : properties.entrySet()) { - vertex.property(property.getKey().getProperty(), property.getValue()); - jsonMetadataMap.put(property.getKey().getProperty(), property.getValue()); - } - vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Exception occurred during update vertex metadata properties with json{}. {}", - vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage()); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, - EdgeLabelEnum label) { - try { - Iterator edges = vertex.getVertex().edges(direction, label.name()); - - while (edges.hasNext()) { - Edge edge = edges.next(); - Vertex secondVertex; - Direction reverseDirection; - if (direction == Direction.IN) { - secondVertex = edge.outVertex(); - reverseDirection = Direction.OUT; - } else { - secondVertex = edge.inVertex(); - reverseDirection = Direction.IN; - } - edge.remove(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, - "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex()); - - Iterator restOfEdges = secondVertex.edges(reverseDirection, label.name()); - if (restOfEdges.hasNext() == false) { - secondVertex.remove(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, - "This was last edge . Vertex {} was removed ", vertex.getUniqueId()); - } - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, - "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", - label.name(), direction, vertex.getUniqueId(), e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - public Object getProperty(TitanVertex vertex, String key) { - PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); - Object value = vertex.valueOrNull(propertyKey); - return value; - } - - public Object getProperty(Edge edge, EdgePropertyEnum key) { - Object value = null; - try { - Property property = edge.property(key.getProperty()); - if (property != null) { - return property.orElse(null); - } - } catch (Exception e) { - - } - return value; - } - - /** - * - * @param vertexA - * @param vertexB - * @param label - * @param direction - * @return - */ - public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, - Direction direction) { - TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label); - if (result != TitanOperationStatus.OK) { - logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result); - return result; - } - TitanOperationStatus createRelation; - if (direction == Direction.IN) { - createRelation = createEdge(vertexB, vertexA, label, null); - } else { - createRelation = createEdge(vertexA, vertexB, label, null); - } - if (createRelation != TitanOperationStatus.OK) { - return createRelation; - } - return TitanOperationStatus.OK; - } - - public Either getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, - Map properties) { - Either getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse); - if (getVertexRes.isRight()) { - return Either.right(getVertexRes.right().value()); - } - return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties); - } + TitanGraphClient titanClient; + + private static Logger logger = Logger.getLogger(TitanDao.class.getName()); + + public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) { + this.titanClient = titanClient; + logger.info("** TitanDao created"); + } + + public TitanOperationStatus commit() { + logger.debug("#commit - The operation succeeded. Doing commit..."); + return titanClient.commit(); + } + + public TitanOperationStatus rollback() { + logger.debug("#rollback - The operation failed. Doing rollback..."); + return titanClient.rollback(); + } + + public Either getGraph() { + return titanClient.getGraph(); + } + + /** + * + * @param graphVertex + * @return + */ + public Either createVertex(GraphVertex graphVertex) { + logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId()); + Either graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + TitanVertex vertex = tGraph.addVertex(); + + setVertexProperties(vertex, graphVertex); + + graphVertex.setVertex(vertex); + + return Either.left(graphVertex); + + } catch (Exception e) { + logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + } else { + logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value()); + return Either.right(graph.right().value()); + } + } + + /** + * + * @param name + * @param value + * @param label + * @return + */ + public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) { + return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll); + } + + public Either getVertexByLabel(VertexTypeEnum label) { + return titanClient.getGraph().left().map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()).left().bind(titanVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, titanVertices)); + } + + private Either getFirstFoundVertex(JsonParseFlagEnum parseFlag, Iterable vertices) { + Iterator iterator = vertices.iterator(); + if (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + return Either.left(graphVertex); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + /** + * + * @param name + * @param value + * @param label + * @param parseFlag + * @return + */ + public Either getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label, JsonParseFlagEnum parseFlag) { + + Either graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable vertecies = tGraph.query().has(name.getProperty(), value).has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices(); + + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + return Either.left(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + /** + * + * @param id + * @return + */ + public Either getVertexById(String id) { + return getVertexById(id, JsonParseFlagEnum.ParseAll); + } + + /** + * + * @param id + * @param parseFlag + * @return + */ + public Either getVertexById(String id, JsonParseFlagEnum parseFlag) { + + Either graph = titanClient.getGraph(); + if (id == null) { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id = {} ", id); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices(); + + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + return Either.left(graphVertex); + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id = {}", id); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to get vertex in graph for id {} ", id); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException { + + if (graphVertex.getMetadataProperties() != null) { + for (Map.Entry entry : graphVertex.getMetadataProperties().entrySet()) { + if (entry.getValue() != null) { + vertex.property(entry.getKey().getProperty(), entry.getValue()); + } + } + } + vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName()); + + Map json = graphVertex.getJson(); + if (json != null) { + String jsonStr = JsonParserUtils.toJson(json); + vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); + + } + Map jsonMetadata = graphVertex.getMetadataJson(); + if (jsonMetadata != null) { + String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata); + vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr); + } + } + + public void setVertexProperties(Vertex vertex, Map properties) throws IOException { + for (Map.Entry entry : properties.entrySet()) { + if (entry.getValue() != null) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) { + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setVertex(vertex); + parseVertexProperties(graphVertex, parseFlag); + return graphVertex; + } + + public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) { + TitanVertex vertex = graphVertex.getVertex(); + Map properties = getVertexProperties(vertex); + VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); + for (Map.Entry entry : properties.entrySet()) { + GraphPropertyEnum key = entry.getKey(); + switch (key) { + case UNIQUE_ID: + graphVertex.setUniqueId((String) entry.getValue()); + break; + case LABEL: + graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue())); + break; + case COMPONENT_TYPE: + String type = (String) entry.getValue(); + if (type != null) { + graphVertex.setType(ComponentTypeEnum.valueOf(type)); + } + break; + case JSON: + if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) { + String json = (String) entry.getValue(); + Map jsonObj = JsonParserUtils.toMap(json, label.getClassOfJson()); + graphVertex.setJson(jsonObj); + } + break; + case METADATA: + if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) { + String json = (String) entry.getValue(); + Map metadatObj = JsonParserUtils.toMap(json); + graphVertex.setMetadataJson(metadatObj); + } + break; + default: + graphVertex.addMetadataProperty(key, entry.getValue()); + break; + } + } + } + + public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map properties) { + return createEdge(from.getVertex(), to.getVertex(), label, properties); + } + + public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map properties) { + if (logger.isTraceEnabled()) { + logger.trace("Try to connect {} with {} label {} properties {}", + from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties); + } + if (from == null || to == null) { + logger.trace("No Titan vertex for id from {} or id to {}", + from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + return TitanOperationStatus.NOT_FOUND; + } + Edge edge = from.addEdge(label.name(), to); + TitanOperationStatus status; + try { + setEdgeProperties(edge, properties); + status = TitanOperationStatus.OK; + } catch (IOException e) { + logger.debug("Failed to set properties on edge properties [{}]", properties, e); + status = TitanOperationStatus.GENERAL_ERROR; + } + return status; + } + + public Map getVertexProperties(Element element) { + + Map result = new HashMap<>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); + + for (Entry entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key); + if (valueOf != null) { + result.put(valueOf, value); + } + } + } + return result; + } + + public Map getEdgeProperties(Element element) { + + Map result = new HashMap<>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); + + for (Entry entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key); + if (valueOf != null) { + if (valueOf == EdgePropertyEnum.INSTANCES) { + List list = JsonParserUtils.toList((String) value, String.class); + result.put(valueOf, list); + } else { + result.put(valueOf, value); + } + } + } + } + return result; + } + + public void setEdgeProperties(Element element, Map properties) throws IOException { + + if (properties != null && !properties.isEmpty()) { + + Object[] propertyKeyValues = new Object[properties.size() * 2]; + int i = 0; + for (Entry entry : properties.entrySet()) { + propertyKeyValues[i++] = entry.getKey().getProperty(); + Object value = entry.getValue(); + if (entry.getKey() == EdgePropertyEnum.INSTANCES) { + String jsonStr = JsonParserUtils.toJson(value); + propertyKeyValues[i++] = jsonStr; + } else { + propertyKeyValues[i++] = entry.getValue(); + } + } + ElementHelper.attachProperties(element, propertyKeyValues); + } + } + + public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map props) { + return getByCriteria(type, props, JsonParseFlagEnum.ParseAll); + } + + public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map props, JsonParseFlagEnum parseFlag) { + Either graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + TitanGraphQuery query = tGraph.query(); + if (type != null) { + query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); + } + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + + Map newProp = getVertexProperties(vertex); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + result.add(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map props, Map hasNotProps, JsonParseFlagEnum parseFlag) { + Either graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + TitanGraphQuery query = tGraph.query(); + if (type != null) { + query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); + } + + if (props != null && !props.isEmpty()) { + for (Map.Entry entry : props.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + if (hasNotProps != null && !hasNotProps.isEmpty()) { + for (Map.Entry entry : hasNotProps.entrySet()) { + if (entry.getValue() instanceof List) { + buildMultipleNegateQueryFromList(entry, query); + } else { + query = query.hasNot(entry.getKey().getProperty(), entry.getValue()); + } + } + } + Iterable vertices = query.vertices(); + if (vertices == null) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + Iterator iterator = vertices.iterator(); + List result = new ArrayList<>(); + + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + + Map newProp = getVertexProperties(vertex); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + result.add(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either, TitanOperationStatus> getCatalogOrArchiveVerticies(boolean isCatalog) { + Either graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + String name = isCatalog ? VertexTypeEnum.CATALOG_ROOT.getName() : VertexTypeEnum.ARCHIVE_ROOT.getName(); + Iterable vCatalogIter = tGraph.query().has(GraphPropertyEnum.LABEL.getProperty(), name).vertices(); + if (vCatalogIter == null) { + logger.debug("Failed to fetch catalog vertex"); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + TitanVertex catalogV = vCatalogIter.iterator().next(); + if (catalogV == null) { + logger.debug("Failed to fetch catalog vertex"); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + String edgeLabel = isCatalog ? EdgeLabelEnum.CATALOG_ELEMENT.name() : EdgeLabelEnum.ARCHIVE_ELEMENT.name(); + Iterator vertices = catalogV.vertices(Direction.OUT, edgeLabel); + + return Either.left(vertices); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria: ", e); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria : ", graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + private void buildMultipleNegateQueryFromList(Map.Entry entry, TitanGraphQuery query) { + List negateList = (List) entry.getValue(); + for (Object listItem : negateList) { + query.hasNot(entry.getKey().getProperty(), listItem); + } + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + public Either getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + if (isEmpty(childrenVertecies.left().value())){ + return Either.right(TitanOperationStatus.NOT_FOUND); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + public Either getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + Either, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); + if (childrenVertecies.isRight() ) { + return Either.right(childrenVertecies.right().value()); + } + if (isEmpty(childrenVertecies.left().value())){ + return Either.right(TitanOperationStatus.NOT_FOUND); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); + } + + public Either, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); + } + + public Either, TitanOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); + } + + private Either, TitanOperationStatus> getAdjacentVerticies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { + List list = new ArrayList<>(); + try { + Either graphRes = titanClient.getGraph(); + if (graphRes.isRight()) { + logger.error("Failed to retrieve graph. status is {}", graphRes); + return Either.right(graphRes.right().value()); + } + Iterator edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name()); + if (edgesCreatorIterator != null) { + while (edgesCreatorIterator.hasNext()) { + Edge edge = edgesCreatorIterator.next(); + TitanVertex vertex; + if (direction == Direction.IN) { + vertex = (TitanVertex) edge.outVertex(); + } else { + vertex = (TitanVertex) edge.inVertex(); + } + // GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + list.add(vertex); + } + } + if (list.isEmpty()) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + logger.error("Failed to perform graph operation ", e); + Either.right(TitanGraphClient.handleTitanException(e)); + } + + return Either.left(list); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either, TitanOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); + } + + private Either, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { + List list = new ArrayList<>(); + + Either, TitanOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), edgeLabel, parseFlag, direction); + if (adjacentVerticies.isRight()) { + return Either.right(adjacentVerticies.right().value()); + } + adjacentVerticies.left().value().stream().forEach(vertex -> { + list.add(createAndFill((TitanVertex) vertex, parseFlag)); + }); + + return Either.left(list); + } + + /** + * Searches Edge by received label and criteria + * + * @param vertex + * @param label + * @param properties + * @return found edge or TitanOperationStatus + */ + public Either getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map properties) { + + Either result = null; + Edge matchingEdge = null; + String notFoundMsg = "No edges in graph for criteria"; + try { + TitanVertexQuery query = vertex.getVertex().query().labels(label.name()); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry entry : properties.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + + Iterable edges = query.edges(); + if (edges == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } else { + Iterator eIter = edges.iterator(); + if (eIter.hasNext()) { + matchingEdge = eIter.next(); + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } + } + if (result == null) { + result = Either.left(matchingEdge); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + public Either getEdgeByChildrenVertexProperties(GraphVertex vertex, EdgeLabelEnum label, Map properties) { + Either result = null; + Edge matchingEdge = null; + String notFoundMsg = "No edges in graph for criteria"; + try { + + Iterator edges = vertex.getVertex().edges(Direction.OUT, label.name()); + while (edges.hasNext()) { + matchingEdge = edges.next(); + Vertex childV = matchingEdge.inVertex(); + Map vertexProperties = getVertexProperties(childV); + Optional> findNotMatch = properties.entrySet().stream().filter(e -> vertexProperties.get(e.getKey()) == null || !vertexProperties.get(e.getKey()).equals(e.getValue())).findFirst(); + if (!findNotMatch.isPresent()) { + result = Either.left(matchingEdge); + } + } + if (result == null) { + //no match + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + /** + * Deletes Edge by received label and criteria + * + * @param vertex + * @param label + * @param properties + * @return + */ + public Either deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map properties) { + Either result = null; + try { + result = getBelongingEdgeByCriteria(vertex, label, properties); + if (result.isLeft()) { + Edge edge = result.left().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); + edge.remove(); + result = Either.left(edge); + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}", vertex == null ? "NULL" : vertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + @SuppressWarnings("unchecked") + /** + * Deletes an edge between vertices fromVertex and toVertex according to received label + * + * @param fromVertex + * @param toVertex + * @param label + * @return + */ + + public Either deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { + return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), false); + } + + public Either deleteAllEdges(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { + return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), true); + } + + public Either deleteEdge(TitanVertex fromVertex, TitanVertex toVertex, EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo, boolean deleteAll) { + Either result = null; + try { + Iterable edges = fromVertex.query().labels(label.name()).edges(); + Iterator eIter = edges.iterator(); + while (eIter.hasNext()) { + Edge edge = eIter.next(); + String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); + edge.remove(); + result = Either.left(edge); + if (!deleteAll) { + break; + } + } + } + if (result == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), uniqueIdFrom, uniqueIdTo, e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) { + try { + Iterator edges = fromVertex.getVertex().edges(direction, label.name()); + + while (edges.hasNext()) { + Edge edge = edges.next(); + edge.remove(); + } + } catch (Exception e) { + logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e); + return TitanGraphClient.handleTitanException(e); + } + return TitanOperationStatus.OK; + } + + /** + * Updates vertex properties. Note that graphVertex argument should contain updated data + * + * @param graphVertex + * @return + */ + public Either updateVertex(GraphVertex graphVertex) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId()); + try { + graphVertex.updateMetadataJsonWithCurrentMetadataProperties(); + setVertexProperties(graphVertex.getVertex(), graphVertex); + + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return Either.left(graphVertex); + } + + /** + * Fetches vertices by uniqueId according to received parse flag + * + * @param verticesToGet + * @return + */ + public Either, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag(Map> verticesToGet) { + + Either, TitanOperationStatus> result = null; + Map vertices = new HashMap<>(); + TitanOperationStatus titatStatus; + Either getVertexRes = null; + for (Map.Entry> entry : verticesToGet.entrySet()) { + if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) { + getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue()); + } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) { + getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER, entry.getValue().getValue()); + } + if (getVertexRes == null) { + titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT; + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus); + return Either.right(titatStatus); + } + if (getVertexRes.isRight()) { + titatStatus = getVertexRes.right().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus); + result = Either.right(titatStatus); + break; + } else { + vertices.put(entry.getKey(), getVertexRes.left().value()); + } + } + if (result == null) { + result = Either.left(vertices); + } + return result; + } + + /** + * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge + * + * @param from + * @param to + * @param label + * @param edgeToCopy + * @return + */ + public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) { + return createEdge(from, to, label, getEdgeProperties(edgeToCopy)); + } + + public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex!=null ? fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL", + toVertex!=null ? toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL"); + + TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge); + if (result == TitanOperationStatus.OK) { + prevEdge.remove(); + } + return result; + } + + /** + * Replaces previous label of edge with new label + * + * @param fromVertex + * @param toVertex + * @param prevLabel + * @param newLabel + * @return + */ + public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { + + TitanOperationStatus result = null; + Iterator prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name()); + if (prevEdgeIter == null || !prevEdgeIter.hasNext()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + result = TitanOperationStatus.NOT_FOUND; + } + if (result == null) { + result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel); + } + return result; + } + + /** + * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too. + * + * + * @param vertex + * @param properties + * @return + */ + public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map properties) { + try { + if (!MapUtils.isEmpty(properties)) { + String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value(); + Map jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr); + for (Map.Entry property : properties.entrySet()) { + vertex.property(property.getKey().getProperty(), property.getValue()); + jsonMetadataMap.put(property.getKey().getProperty(), property.getValue()); + } + vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occurred during update vertex metadata properties with json{}. {}", vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage()); + return TitanGraphClient.handleTitanException(e); + } + return TitanOperationStatus.OK; + } + + public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) { + try { + Iterator edges = vertex.getVertex().edges(direction, label.name()); + + while (edges.hasNext()) { + Edge edge = edges.next(); + Vertex secondVertex; + Direction reverseDirection; + if (direction == Direction.IN) { + secondVertex = edge.outVertex(); + reverseDirection = Direction.OUT; + } else { + secondVertex = edge.inVertex(); + reverseDirection = Direction.IN; + } + edge.remove(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex()); + + Iterator restOfEdges = secondVertex.edges(reverseDirection, label.name()); + if (!restOfEdges.hasNext()) { + secondVertex.remove(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId()); + } + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction, vertex.getUniqueId(), e); + return TitanGraphClient.handleTitanException(e); + } + return TitanOperationStatus.OK; + } + + public Object getProperty(TitanVertex vertex, String key) { + PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); + return vertex.valueOrNull(propertyKey); + } + + public Object getProperty(Edge edge, EdgePropertyEnum key) { + Object value = null; + try { + Property property = edge.property(key.getProperty()); + if (property != null) { + value = property.orElse(null); + if (value != null && key == EdgePropertyEnum.INSTANCES) { + return JsonParserUtils.toList((String) value, String.class); + } + return value; + } + } catch (Exception e) { + + } + return value; + } + + /** + * + * @param vertexA + * @param vertexB + * @param label + * @param direction + * @return + */ + public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) { + TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label); + if (result != TitanOperationStatus.OK) { + logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result); + return result; + } + TitanOperationStatus createRelation; + if (direction == Direction.IN) { + createRelation = createEdge(vertexB, vertexA, label, null); + } else { + createRelation = createEdge(vertexA, vertexB, label, null); + } + if (createRelation != TitanOperationStatus.OK) { + return createRelation; + } + return TitanOperationStatus.OK; + } + + public Either getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, Map properties) { + Either getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse); + if (getVertexRes.isRight()) { + return Either.right(getVertexRes.right().value()); + } + return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties); + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java index eda2805087..1621a13c67 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java @@ -57,9 +57,13 @@ public enum EdgeLabelEnum { CALCULATED_CAP_PROPERTIES, POLICIES, EXTERNAL_REFS, - CATALOG_ELEMENT; - - /** + CATALOG_ELEMENT, + ARCHIVE_ELEMENT, + INSTANCE_OF, + PROXY_OF, + ALLOTTED_OF; + + /** * Returns EdgeLabelEnum according received name * @param name * @return diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java index e52c92e74b..e47a78d9f0 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgePropertyEnum.java @@ -22,7 +22,8 @@ package org.openecomp.sdc.be.dao.jsongraph.types; public enum EdgePropertyEnum { - STATE ("state"); + STATE ("state"), + INSTANCES("instances"); private String property; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java index 92880c1c97..3917179d5e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java @@ -20,23 +20,7 @@ package org.openecomp.sdc.be.dao.jsongraph.types; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; -import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; -import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; public enum VertexTypeEnum { @@ -65,15 +49,16 @@ public enum VertexTypeEnum { INST_INPUTS ("instInputs", MapPropertiesDataDefinition.class), INST_GROUPS ("instGroups", MapGroupsDataDefinition.class), SERVICE_API_ARTIFACTS ("serviceApiArtifacts", ArtifactDataDefinition.class), - CALCULATED_CAPABILITIES ("calculatedCapabilities", MapListCapabiltyDataDefinition.class), - FULLFILLED_CAPABILITIES ("fullfilledCapabilities", MapListCapabiltyDataDefinition.class), + CALCULATED_CAPABILITIES ("calculatedCapabilities", MapListCapabilityDataDefinition.class), + FULLFILLED_CAPABILITIES ("fullfilledCapabilities", MapListCapabilityDataDefinition.class), CALCULATED_REQUIREMENTS ("calculatedRequirements", MapListRequirementDataDefinition.class), FULLFILLED_REQUIREMENTS ("fullfilledRequirements", MapListRequirementDataDefinition.class), - CALCULATED_CAP_PROPERTIES ("calculatedCapProperties", MapCapabiltyProperty.class), + CALCULATED_CAP_PROPERTIES ("calculatedCapProperties", MapCapabilityProperty.class), FORWARDING_PATH ("path", ForwardingPathDataDefinition.class), POLICIES ("policies", PolicyDataDefinition.class), EXTERNAL_REF ("componentInstanceExtRefs", MapComponentInstanceExternalRefs.class), - CATALOG_ROOT ("catalogRoot", null); + CATALOG_ROOT ("catalogRoot", null), + ARCHIVE_ROOT ("archiveRoot", null); private String name; private Class classOfJson; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java index 7b0719e063..2d2d9b8962 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/IdBuilderUtils.java @@ -20,10 +20,10 @@ package org.openecomp.sdc.be.dao.jsongraph.utils; -import java.util.UUID; - import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import java.util.UUID; + public class IdBuilderUtils { private static String DOT = "."; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java index 198d3b456c..9a6e70b4d8 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java @@ -20,13 +20,6 @@ package org.openecomp.sdc.be.dao.jsongraph.utils; -import java.io.IOException; -import java.util.Map; - -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -34,9 +27,15 @@ import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.base.Strings; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.io.IOException; +import java.util.List; +import java.util.Map; public class JsonParserUtils { - private static final Logger log = LoggerFactory.getLogger(JsonParserUtils.class.getName()); + private static Logger log = Logger.getLogger(JsonParserUtils.class.getName()); private static final ObjectMapper mapper = buildObjectMapper(); private JsonParserUtils() { @@ -86,7 +85,24 @@ public class JsonParserUtils { .readValue(json); } catch (Exception e) { - log.debug("Failed to parse json {}", json, e); + log.debug("Failed to parse json {} to map", json, e); + } + return object; + } + public static List toList(String json, Class clazz) { + if (Strings.isNullOrEmpty(json)) { + return null; + } + List object = null; + try { + JavaType type = mapper.getTypeFactory() + .constructCollectionType(List.class, clazz); + + object = mapper.readerFor(type) + .readValue(json); + } + catch (Exception e) { + log.debug("Failed to parse json {} to list", json, e); } return object; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java deleted file mode 100644 index c71c8ae6c5..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchFacet.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.dao.model; - -import java.io.Serializable; - -/** - * A facet informations. - * - */ -@SuppressWarnings("PMD.UnusedPrivateField") -public class FacetedSearchFacet implements Serializable { - public FacetedSearchFacet(String facetValue, int count) { - this.count = count; - this.facetValue = facetValue; - } - - private FacetedSearchFacet() { - } - - public String getFacetValue() { - return facetValue; - } - - public void setFacetValue(String facetValue) { - this.facetValue = facetValue; - } - - public long getCount() { - return count; - } - - public void setCount(long count) { - this.count = count; - } - - private static final long serialVersionUID = 1L; - private String facetValue; - private long count; -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java deleted file mode 100644 index 3e14ee7d6c..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/FacetedSearchResult.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.dao.model; - -import java.util.HashMap; -import java.util.Map; - -/** - * Contains results for a search query. - * - */ - -@SuppressWarnings("PMD.UnusedPrivateField") -public class FacetedSearchResult extends GetMultipleDataResult { - private static final long serialVersionUID = 1L; - - private Map facets; - - /** - * Argument constructor. - * - * @param from - * The start index of the returned elements. - * @param to - * The end index of the returned elements. - * @param queryDuration - * The duration of the query. - * @param totalResults - * The total results for this query. - * @param types - * The types of data found. - * @param data - * The found data. - * @param hashMap - * The facets if any for the query. - */ - public FacetedSearchResult(final int from, final int to, final long queryDuration, final long totalResults, - final String[] types, final Object[] data, final HashMap hashMap) { - super(types, data, queryDuration, totalResults, from, to); - this.facets = hashMap; - } - - public Map getFacets() { - return facets; - } - - public void setFacets(Map facets) { - this.facets = facets; - } - - public FacetedSearchResult() { - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java deleted file mode 100644 index e1e0593a04..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResult.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.dao.model; - -import java.io.Serializable; - -/** - * Result for a multiple data query. - * - * @author luc boutier - */ -@SuppressWarnings("PMD.UnusedPrivateField") -public class GetMultipleDataResult implements Serializable { - public String[] getTypes() { - return types; - } - - public T[] getData() { - return data; - } - - public void setTypes(String[] types) { - this.types = types.clone(); - } - - public void setData(T[] data) { - this.data = data.clone(); - } - - public void setQueryDuration(long queryDuration) { - this.queryDuration = queryDuration; - } - - public void setTotalResults(long totalResults) { - this.totalResults = totalResults; - } - - public void setFrom(int from) { - this.from = from; - } - - public void setTo(int to) { - this.to = to; - } - - public long getQueryDuration() { - return queryDuration; - } - - public long getTotalResults() { - return totalResults; - } - - public int getFrom() { - return from; - } - - public int getTo() { - return to; - } - - private static final long serialVersionUID = 1L; - - private String[] types; - private T[] data; - private long queryDuration; - private long totalResults; - private int from; - private int to; - - /** - * Construct an object only with data and types - * - * @param types - * @param data - */ - public GetMultipleDataResult(String[] types, T[] data) { - this.types = types.clone(); - this.data = data.clone(); - } - - public GetMultipleDataResult(String[] types, Object[] data, long queryDuration, long totalResults, int from, - int to) { - - this.types = types.clone(); - this.data = (T[]) data.clone(); - this.queryDuration = queryDuration; - this.totalResults = totalResults; - this.from = from; - this.to = to; - } - - public GetMultipleDataResult() { - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java new file mode 100644 index 0000000000..9d30c20683 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/BatchBuilder.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; + +import java.util.ArrayList; +import java.util.List; + +public class BatchBuilder { + // private Map> nodes; + // private List relations; + // + private List elements; + + // TODO add filter + + protected BatchBuilder() { + // nodes = new HashMap>(); + // relations = new ArrayList(); + elements = new ArrayList<>(); + } + + public static BatchBuilder getBuilder() { + return new BatchBuilder(); + } + + public BatchBuilder add(GraphElement element) { + elements.add(element); + return this; + } + + public List getElements() { + return elements; + } + + // public BatchBuilder add( Neo4jNode element ){ + // String label = element.getLabel(); + // List list = nodes.get(label); + // if ( list == null ){ + // list = new ArrayList(); + // } + // list.add(element); + // nodes.put(label, list); + + // return this; + // } + // public BatchBuilder add( Neo4jRelation relation ){ + // relations.add(relation); + // return this; + // } + // + // public Map> getNodes() { + // return nodes; + // } + // + // public List getRelations() { + // return relations; + // } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java new file mode 100644 index 0000000000..b0b2cc20bb --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTemplates.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +public interface CypherTemplates { + + public static final String CypherUrlTemplate = "http://$host$:$port$/db/data/transaction/commit"; + public static final String batchTemplate = "http://$host$:$port$/db/data/batch"; + public static final String getAllIndexsTemplate = "http://$host$:$port$/db/data/schema/index"; + + public static final String CypherCreateNodeTemplate = "{\n\"statements\" : [ {\n \"statement\" : \"CREATE (n:$label$ { props } ) RETURN n\",\n \"parameters\" : { \n \"props\" : $props$ \n } } ] }"; + + public static final String CypherMatchTemplate = "{\"statements\": [{\"statement\": \"MATCH (n:$label$ {$filter$}) RETURN ($type$) \" }]}"; + + public static final String CypherUpdateTemplate = "{\"statements\": [{\"statement\": \"MATCH (n:$label$ {$filter$}) SET n += {props} RETURN ($type$) \",\"parameters\" : {\"props\" : {$props$}}}]}"; + public static final String CypherDeleteNodeTemplate = "{\"statements\": [{\"statement\": \"MATCH ( n:$label$ {$filter$} ) DELETE n \" }]}"; + + public static final String BatchTemplate = "{ \"statements\" : [ $statementList$ ] }"; + + public static final String RegularStatementTemplate = "{ \"statement\" : $statement$ }"; + + public static final String CreateSingleNodeTemplate = " \"CREATE (n:$label$ { props } ) RETURN n, labels(n)\", \"parameters\" : { \"props\" : $props$ }"; + + public static final String CreateRelationTemplate = "\"MATCH (a:$labelFrom$),(b:$labelTo$) WHERE a.$idNameFrom$ = '$idValueFrom$' AND b.$idNameTo$ = '$idvalueTo$' CREATE (a)-[r:$type$ { props } ]->(b) RETURN a, labels(a), b, labels(b), r, type(r)\", \"parameters\": {\"props\": $props$ } "; + + public static final String CreateRelationTemplateNoProps = "\"MATCH (a:$labelFrom$),(b:$labelTo$) WHERE a.$idNameFrom$ = '$idValueFrom$' AND b.$idNameTo$ = '$idvalueTo$' CREATE (a)-[r:$type$ ]->(b) RETURN a,labels(a), b, labels(b), r, type(r)\""; + + public static final String UpdateNodeStatementTemplate = "\"MATCH (n:$label$ {$filter$}) SET n += {props} \",\"parameters\" : {\"props\" : $props$}"; + + public static final String GetNodeRecursiveTemplate = "\"MATCH (m:$label$ {$filter$} )-[f$typesList$]->l RETURN m, labels(m), l, labels(l),f, type(f)\""; + + public static final String GetByRelationNodeRecursiveTemplate = "\"MATCH (n:$labelNode$ ($propsNode$} )-[r:$type$ {$propsRel$}]->(m:$labelSrc$)-[f$typesList$]->l RETURN n, labels(n), r, type(r), m, labels(m), l, labels(l),f, type(f)\""; + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java new file mode 100644 index 0000000000..2f53736c59 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/CypherTranslator.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveByRelationFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter; +import org.openecomp.sdc.be.dao.utils.DaoUtils; + +import java.util.List; +import java.util.Map; + +public class CypherTranslator { + + public String translate(BatchBuilder builder) { + String json = null; + StringBuilder statementList = new StringBuilder(); + + List elements = builder.getElements(); + int statementCounter = 0; + for (GraphElement element : elements) { + String singleStatementBody = null; + switch (element.getElementType()) { + case Node: + singleStatementBody = prepareNodeStatement(element); + break; + case Relationship: + singleStatementBody = prepareRelationStatement(element); + break; + } + if (singleStatementBody != null && !singleStatementBody.isEmpty()) { + + String singleStatement = CypherTemplates.RegularStatementTemplate.replace("$statement$", + singleStatementBody); + + statementList.append(singleStatement); + } + ++statementCounter; + if (statementCounter < elements.size() && singleStatementBody != null) { + statementList.append(","); + } + + } + json = CypherTemplates.BatchTemplate.replace("$statementList$", statementList.toString()); + return json; + } + + private String prepareNodeStatement(GraphElement element) { + if (element instanceof GraphNode) { + GraphNode node = (GraphNode) element; + + switch (node.getAction()) { + case Create: + return createNodeStatement(node); + case Update: + return updateNodeStatement(node); + case Delete: + // TODO + break; + default: + break; + } + } + return null; + } + + private String updateNodeStatement(GraphNode node) { + String singleStatement = CypherTemplates.UpdateNodeStatementTemplate.replace("$label$", node.getLabel()); + String filter = prepareKeyValueFilter(node); + + singleStatement = singleStatement.replace("$filter$", filter); + + singleStatement = singleStatement.replace("$props$", DaoUtils.convertToJson(node.toGraphMap())); + + return singleStatement; + } + + private String createNodeStatement(GraphNode node) { + String singleStatement = CypherTemplates.CreateSingleNodeTemplate.replace("$label$", node.getLabel()); + + singleStatement = singleStatement.replace("$props$", DaoUtils.convertToJson(node.toGraphMap())); + return singleStatement; + } + + private String prepareRelationStatement(GraphElement element) { + if (element instanceof GraphRelation) { + + GraphRelation relation = (GraphRelation) element; + + switch (relation.getAction()) { + case Create: + return createRelationStatement(relation); + case Update: + return updateRelationStatement(relation); + case Delete: + // TODO + break; + default: + break; + } + } + return null; + } + + private String createRelationStatement(GraphRelation relation) { + RelationEndPoint from = relation.getFrom(); + String singleStatement; + + Map props = relation.toGraphMap(); + if (props == null || props.isEmpty()) { + singleStatement = CypherTemplates.CreateRelationTemplateNoProps.replace("$labelFrom$", + from.getLabel().getName()); + } else { + singleStatement = CypherTemplates.CreateRelationTemplate.replace("$labelFrom$", from.getLabel().getName()); + singleStatement = singleStatement.replace("$props$", DaoUtils.convertToJson(props)); + } + + singleStatement = singleStatement.replace("$idNameFrom$", from.getIdName()); + singleStatement = singleStatement.replace("$idValueFrom$", from.getIdValue().toString()); + + RelationEndPoint to = relation.getTo(); + singleStatement = singleStatement.replace("$labelTo$", to.getLabel().getName()); + singleStatement = singleStatement.replace("$idNameTo$", to.getIdName()); + singleStatement = singleStatement.replace("$idvalueTo$", to.getIdValue().toString()); + + singleStatement = singleStatement.replace("$type$", relation.getType()); + return singleStatement; + } + + private String updateRelationStatement(GraphRelation relation) { + // TODO + return null; + } + + private String prepareKeyValueFilter(GraphNode node) { + StringBuilder sb = new StringBuilder(); + + ImmutablePair keyValueId = node.getKeyValueId(); + + sb.append(keyValueId.getKey()).append(":"); + if (keyValueId.getValue() instanceof String) { + sb.append("'"); + } + sb.append(keyValueId.getValue()); + + if (keyValueId.getValue() instanceof String) { + sb.append("'"); + } + + return sb.toString(); + } + + public String translateGet(RecursiveFilter filter) { + String requestJson = null; + String statement; + + if (filter instanceof RecursiveByRelationFilter) { + RecursiveByRelationFilter byRelationFilter = (RecursiveByRelationFilter) filter; + + statement = CypherTemplates.GetByRelationNodeRecursiveTemplate.replace("$labelNode$", + byRelationFilter.getNode().getLabel()); + String keyValueId = prepareKeyValueFilter(byRelationFilter.getNode()); + + statement = statement.replace("$propsNode$", keyValueId); + + statement = statement.replace("$type$", byRelationFilter.getRelationType()); + + String relationProps = prepareFilterBody(filter); + statement = statement.replace("$propsRel$", relationProps); + statement = statement.replace("$labelSrc$", filter.getNodeType().getName()); + + } else { + + statement = CypherTemplates.GetNodeRecursiveTemplate.replace("$label$", filter.getNodeType().getName()); + + // replace filter + if (filter.getProperties().isEmpty()) { + // get all records by label + statement = statement.replace("{$filter$}", ""); + } else { + String filterStr = prepareFilterBody(filter); + statement = statement.replace("$filter$", filterStr); + } + } + + if (filter.getChildRelationTypes() == null || filter.getChildRelationTypes().isEmpty()) { + statement = statement.replace("$typesList$", ""); + + } else { + StringBuilder typesList = new StringBuilder(); + int count = 0; + for (String type : filter.getChildRelationTypes()) { + typesList.append(":").append(type); + ++count; + if (count < filter.getChildRelationTypes().size()) { + typesList.append("|"); + } + } + statement = statement.replace("$typesList$", typesList.toString()); + } + String singleStatement = CypherTemplates.RegularStatementTemplate.replace("$statement$", statement); + requestJson = CypherTemplates.BatchTemplate.replace("$statementList$", singleStatement); + + return requestJson; + } + + public static String prepareFilterBody(MatchFilter filter) { + StringBuilder sb = new StringBuilder(); + int count = 0; + int size = filter.getProperties().entrySet().size(); + for (Map.Entry entry : filter.getProperties().entrySet()) { + sb.append(entry.getKey()).append(":"); + if (entry.getValue() instanceof String) { + sb.append("'"); + } + sb.append(entry.getValue()); + if (entry.getValue() instanceof String) { + sb.append("'"); + } + ++count; + if (count < size) { + sb.append(","); + } + } + return sb.toString(); + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java index 790e92ec55..5b386f18bb 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java @@ -28,7 +28,8 @@ public enum GraphEdgeLabels { // field name // STATE("STATE"), LAST_STATE("LAST_STATE"), CREATOR("CREATOR"), LAST_MODIFIER("LAST_MODIFIER"), ATTRIBUTE("EDGE_ATTRIBUTE"), PROPERTY("EDGE_PROPERTY"), CATEGORY("CATEGORY"), DERIVED_FROM("DERIVED_FROM"), REQUIREMENT("REQUIREMENT"), - CAPABILITY_TYPE("CAPABILITY_TYPE"), RELATIONSHIP_TYPE("RELATIONSHIP_TYPE"), CAPABILITY("CAPABILITY"), INSTANCE_OF("INSTANCE_OF"), INTERFACE("INTERFACE"), INTERFACE_OPERATION("INTERFACE_OPERATION"), ARTIFACT_REF("ARTIFACT_REF"), + CAPABILITY_TYPE("CAPABILITY_TYPE"), RELATIONSHIP_TYPE("RELATIONSHIP_TYPE"), CAPABILITY("CAPABILITY"), CAPABILITY_IMPL("CAPABILITY_IMPL"), + INSTANCE_OF("INSTANCE_OF"), INTERFACE("INTERFACE"), INTERFACE_OPERATION("INTERFACE_OPERATION"), ARTIFACT_REF("ARTIFACT_REF"), INPUTS("INPUTS"), REQUIREMENT_IMPL("REQUIREMENT_IMPL"), NODE_IMPL("NODE_IMPL"), IMPLEMENTATION_OF("IMPLEMENTATION_OF"), ATTRIBUTE_VALUE("ATTRIBUTE_VALUE"), INPUT_VALUE("INPUT_VALUE"), PROPERTY_VALUE("PROPERTY_VALUE"), CAPABILITY_INST("CAPABILITY_INST"), TYPE_OF("TYPE_OF"), RESOURCE_INST("RESOURCE_INST"), RELATIONSHIP_INST("RELATIONSHIP_INST"), CAPABILITY_NODE("CAPABILITY_NODE"), LAST_DISTRIBUTION_STATE_MODIFAIER("LAST_DISTRIBUTION_STATE_MODIFAIER"), ATTRIBUTE_IMPL("ATTRIBUTE_IMPL"), INPUT_IMPL("INPUT_IMPL"), PROPERTY_IMPL("PROPERTY_IMPL"), ADDITIONAL_INFORMATION("ADDITIONAL_INFORMATION"), HEAT_PARAMETER("HEAT_PARAMETER"), SUB_CATEGORY("SUB_CATEGORY"), GROUPING("GROUPING"), @@ -37,7 +38,8 @@ public enum GraphEdgeLabels { CALCULATED_REQUIREMENT("CALCULATED_REQUIREMENT"), CALCULATED_CAPABILITY("CALCULATED_CAPABILITY"), RELATIONSHIP_ORIGIN("RELATIONSHIP_ORIGIN"), CAPABILITY_ORIGIN("CAPABILITY_ORIGIN"), CALCULATED_REQUIREMENT_FULLFILLED("CALCULATED_REQUIREMENT_FULLFILLED"), CALCULATED_CAPABILITY_FULLFILLED("CALCULATED_CAPABILITY_FULLFILLED"), // Group - GROUP("GROUP"), GROUP_ARTIFACT_REF("GROUP_ARTIFACT_REF"), GROUP_MEMBER("GROUP_MEMBER"), INPUT("EDGE_INPUT"), GET_INPUT("GET_INPUT"), GROUP_INST("GROUP_INST"), GROUP_TYPE_CAPABILITY_TYPE("GROUP_TYPE_CAPABILITY_TYPE"); + GROUP("GROUP"), GROUP_ARTIFACT_REF("GROUP_ARTIFACT_REF"), GROUP_MEMBER("GROUP_MEMBER"), INPUT("EDGE_INPUT"), GET_INPUT("GET_INPUT"), GROUP_INST("GROUP_INST"), + GROUP_TYPE_CAPABILITY_TYPE("GROUP_TYPE_CAPABILITY_TYPE"), GROUP_TYPE_CAPABILITY("GROUP_TYPE_CAPABILITY"); private String property; @@ -55,7 +57,7 @@ public enum GraphEdgeLabels { public static List getAllProperties() { - List arrayList = new ArrayList(); + List arrayList = new ArrayList<>(); for (GraphEdgeLabels graphProperty : GraphEdgeLabels.values()) { arrayList.add(graphProperty.getProperty()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java index 6bba5dac9d..58bd098d77 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionary.java @@ -62,7 +62,7 @@ public enum GraphEdgePropertiesDictionary { public static List getAllProperties() { - List arrayList = new ArrayList(); + List arrayList = new ArrayList<>(); for (GraphEdgePropertiesDictionary graphProperty : GraphEdgePropertiesDictionary.values()) { arrayList.add(graphProperty.getProperty()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java new file mode 100644 index 0000000000..9a62e07a2d --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphNeighbourTable.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; + +import java.util.ArrayList; +import java.util.List; + +public class GraphNeighbourTable { + + List nodes = new ArrayList<>(); + + List directedEdges = new ArrayList<>(); + + public List getNodes() { + return nodes; + } + + public void setNodes(List nodes) { + this.nodes = nodes; + } + + public List getDirectedEdges() { + return directedEdges; + } + + public void setDirectedEdges(List directedEdges) { + this.directedEdges = directedEdges; + } + + public int addNode(GraphNode node) { + this.nodes.add(node); + return this.nodes.size() - 1; + } + + public void addEdge(NodeRelation directedEdge) { + this.directedEdges.add(directedEdge); + } + + @Override + public String toString() { + return "GraphNeighbourTable [nodes=" + nodes + ", directedEdges=" + directedEdges + "]"; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java index 6258346a40..1da09e0cc5 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphPropertiesDictionary.java @@ -25,11 +25,11 @@ public enum GraphPropertiesDictionary { // stored in graph index // Common LABEL ("nodeLabel", String.class, false, true), - HEALTH_CHECK ("healthcheckis", String.class, true, true), //yavivi + HEALTH_CHECK ("healthcheckis", String.class, true, true), // Resource NAME ("name", String.class, false, true), TOSCA_RESOURCE_NAME ("toscaResourceName", String.class, false, true), - CATEGORY_NAME ("categoryName", String.class, false, true), // ? + CATEGORY_NAME ("categoryName", String.class, false, true), VERSION ("version", String.class, false, true), CREATION_DATE ("creationDate", Long.class, false, false), LAST_UPDATE_DATE ("modificationDate", Long.class, false, false), @@ -145,8 +145,9 @@ public enum GraphPropertiesDictionary { FUNCTIONAL_MENU ("functionalMenu", String.class, false, false), REQUIRED_ARTIFACTS ("requiredArtifacts", String.class, false, false), CUSTOMIZATION_UUID ("customizationUUID", String.class, false, false), - ; - + IS_ARCHIVED ("isArchived", Boolean.class, false, true), + IS_VSP_ARCHIVED ("isVspArchived", Boolean.class, false, true), + ARCHIVE_TIME ("archiveTime", Long.class, false, true); private final String property; @@ -154,7 +155,6 @@ public enum GraphPropertiesDictionary { private final boolean unique; private final boolean indexed; - GraphPropertiesDictionary(String property,Class clazz, boolean unique,boolean indexed) { this.property = property; this.clazz = clazz; @@ -170,7 +170,7 @@ public enum GraphPropertiesDictionary { public Class getClazz() { return clazz; } - + public boolean isUnique() { return unique; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java new file mode 100644 index 0000000000..cc7a3fceb3 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jClient.java @@ -0,0 +1,983 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +import fj.data.Either; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpResponseException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.graph.GraphElementFactory; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.UpdateFilter; +import org.openecomp.sdc.be.dao.utils.DaoUtils; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.io.IOException; +import java.util.*; + +//@Component("neo4j-client") +public class Neo4jClient { + private CloseableHttpClient httpClient; + private JSONParser jsonParser; + + private CypherTranslator cypherTranslator; + + private static Logger logger = Logger.getLogger(Neo4jClient.class.getName()); + + private static final String getServiceRoot = "http://$host$:$port$/db/data/"; + // Error's Classification templates + private static final String ClientError = "ClientError"; + private static final String DatabaseError = "DatabaseError"; + private static final String TransientError = "TransientError"; + + // Error's Category templates + private static final String General = "General"; + private static final String LegacyIndex = "LegacyIndex"; + private static final String Request = "Request"; + private static final String Schema = "Schema"; + private static final String Security = "Security"; + private static final String Statement = "Statement"; + private static final String Transaction = "Transaction"; + + // Error's Title templates + private static final String EntityNotFound = "EntityNotFound"; + private static final String ConstraintViolation = "ConstraintViolation"; + + @PostConstruct + public void init() { + + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setMaxTotal(100); + connectionManager.setDefaultMaxPerRoute(20); + connectionManager.setValidateAfterInactivity(15000); + this.httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); + jsonParser = new JSONParser(); + cypherTranslator = new CypherTranslator(); + + } + + @PreDestroy + public void shutdown() { + try { + httpClient.close(); + logger.debug("Http client to Neo4j Graph closed"); + } catch (Exception e) { + logger.info("Failed to close http client", e); + } + } + + /** + * + * @param builder + * @return + */ + public Either>, Neo4jOperationStatus> execute(BatchBuilder builder) { + + String json = cypherTranslator.translate(builder); + logger.debug("Try to execute cypher request [{}]", json); + + Either result = sendPostCypher(json); + if (result.isRight()) { + return Either.right(result.right().value()); + } + List> batchResult; + try { + batchResult = parseResult(result.left().value(), false); + } catch (ParseException e) { + logger.error("Failed to parse batchresponse", e); + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + + return Either.left(batchResult); + } + + public Either>, Neo4jOperationStatus> executeGet(RecursiveFilter filter) { + String json = cypherTranslator.translateGet(filter); + logger.debug("Try to execute cypher request [{}]", json); + + Either result = sendPostCypher(json); + if (result.isRight()) { + return Either.right(result.right().value()); + } + List> batchResult; + try { + batchResult = parseResult(result.left().value(), true); + } catch (ParseException e) { + logger.error("Failed to parse batchresponse", e); + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + + return Either.left(batchResult); + + } + + /** + * + * @param element + * @param ip + * @param user + * @param password + * @return + */ + public Neo4jOperationStatus createElement(GraphElement element) { + Neo4jOperationStatus result = Neo4jOperationStatus.OK; + switch (element.getElementType()) { + case Node: + Either status = createNode(element); + if (status.isRight()) { + result = status.right().value(); + } + break; + case Relationship: + // TODO + break; + + default: + break; + } + + return result; + } + + public Either createSingleElement(GraphElement element) { + switch (element.getElementType()) { + case Node: + Either status = createNode(element); + if (status.isRight()) { + return Either.right(status.right().value()); + } + // parse response + String response = status.left().value(); + try { + List listElements = parseGetResponse(element.getElementType(), + ((GraphNode) element).getLabel(), response); + if (listElements == null || listElements.isEmpty()) { + return Either.right(Neo4jOperationStatus.NOT_FOUND); + } else { + return Either.left(listElements.get(0)); + } + } catch (Exception e) { + logger.error("Failed to parse fetched data from graph", e); + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + case Relationship: + // TODO + break; + + default: + break; + } + + return Either.right(Neo4jOperationStatus.NOT_SUPPORTED); + } + + /** + * + * @param type + * @param label + * @param filter + * @param ip + * @param user + * @param password + * @return + */ + public Either, Neo4jOperationStatus> getByFilter(GraphElementTypeEnum type, String label, + MatchFilter filter) { + + List result = null; + + String requestJson; + // replace return type + if (type.equals(GraphElementTypeEnum.Node)) { + requestJson = CypherTemplates.CypherMatchTemplate.replace("$type$", "n"); + } else { + requestJson = CypherTemplates.CypherMatchTemplate.replace("$type$", "r"); + } + // replace label + if (label != null && !label.isEmpty()) { + requestJson = requestJson.replace("$label$", label); + } else { + requestJson = requestJson.replace("$label$", ""); + } + + // replace filter + if (filter.getProperties().isEmpty()) { + // get all records by label + requestJson = requestJson.replace("{$filter$}", ""); + } else { + String filterStr = CypherTranslator.prepareFilterBody(filter); + requestJson = requestJson.replace("$filter$", filterStr); + } + logger.debug("Try to perform request []", requestJson); + + Either status = sendPostCypher(requestJson); + if (status.isRight()) { + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + // parse response + String response = status.left().value(); + try { + result = parseGetResponse(type, label, response); + } catch (Exception e) { + logger.error("Failed to parse fetched data from graph", e); + Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + + return Either.left(result); + } + + /** + * + * @param type + * @param label + * @param toMatch + * @param toUpdate + * @param ip + * @param user + * @param password + * @return + */ + public Neo4jOperationStatus updateElement(GraphElementTypeEnum type, String label, UpdateFilter toUpdate) { + + String requestJson; + // replace return type + if (type.equals(GraphElementTypeEnum.Node)) { + requestJson = CypherTemplates.CypherUpdateTemplate.replace("$type$", "n"); + } else { + requestJson = CypherTemplates.CypherUpdateTemplate.replace("$type$", "r"); + } + // replace label + if (label != null && !label.isEmpty()) { + requestJson = requestJson.replace("$label$", label); + } else { + requestJson = requestJson.replace("$label$", ""); + } + + // replace filter + if (toUpdate.getProperties().isEmpty()) { + // get all records by label + requestJson = requestJson.replace("{$filter$}", ""); + } else { + String filterStr = CypherTranslator.prepareFilterBody(toUpdate); + requestJson = requestJson.replace("$filter$", filterStr); + } + String props = preparePropertiesInStatement(toUpdate.getToUpdate()); + requestJson = requestJson.replace("$props$", props); + + logger.debug("Try to perform request [{}]", requestJson); + + Either result = sendPostCypher(requestJson); + if (result.isRight()) { + return Neo4jOperationStatus.GENERAL_ERROR; + } + return Neo4jOperationStatus.OK; + } + + /** + * + * @param type + * @param label + * @param response + * @return + * @throws ParseException + */ + + private List parseGetResponse(GraphElementTypeEnum type, String label, String response) + throws ParseException { + List result = new ArrayList<>(); + JSONObject responseData = (JSONObject) jsonParser.parse(response); + JSONArray results = (JSONArray) responseData.get("results"); + Iterator iteratorResults = results.iterator(); + while (iteratorResults.hasNext()) { + JSONObject elementResult = iteratorResults.next(); + // JSONArray data = (JSONArray) elementResult.get("row"); + JSONArray data = (JSONArray) elementResult.get("data"); + + Iterator iterator = data.iterator(); + JSONObject element; + while (iterator.hasNext()) { + element = (JSONObject) iterator.next(); + JSONArray row = (JSONArray) element.get("row"); + + Iterator iteratorRow = row.iterator(); + while (iteratorRow.hasNext()) { + JSONObject rowElement = iteratorRow.next(); + + Map props = new HashMap<>(); + + for (Map.Entry entry : (Set>) rowElement.entrySet()) { + // props.put(entry.getKey(), + // rowElement.get(entry.getValue())); + props.put(entry.getKey(), entry.getValue()); + } + GraphElement newElement = GraphElementFactory.createElement(label, type, props); + result.add(newElement); + } + } + } + return result; + } + + private List> parseResult(String response, boolean storeRelationNode) throws ParseException { + + List> batchList = new ArrayList<>(); + + JSONObject responseData = (JSONObject) jsonParser.parse(response); + JSONArray results = (JSONArray) responseData.get("results"); + Iterator iteratorResults = results.iterator(); + + while (iteratorResults.hasNext()) { + JSONObject elementResult = iteratorResults.next(); + JSONArray data = (JSONArray) elementResult.get("data"); + JSONArray columns = (JSONArray) elementResult.get("columns"); + Iterator iteratorData = data.iterator(); + List singleDataList = new ArrayList<>(); + while (iteratorData.hasNext()) { + + JSONObject singleData = iteratorData.next(); + JSONArray row = (JSONArray) singleData.get("row"); + if (columns.size() == 2) { + // node + JSONArray labelArray = (JSONArray) row.get(1); + JSONObject node = (JSONObject) row.get(0); + + Map props = jsonObjectToMap(node); + // get only first label on node. Now single label supported + GraphElement newElement = GraphElementFactory.createElement((String) labelArray.get(0), + GraphElementTypeEnum.Node, props); + singleDataList.add(newElement); + } + if (columns.size() == 10) { + // relation + JSONObject startNode = (JSONObject) row.get(0); + JSONArray startNodeArray = (JSONArray) row.get(1); + + JSONObject relationFromStart = (JSONObject) row.get(2); + String relationFromStartType = (String) row.get(3); + + JSONObject nodeFrom = (JSONObject) row.get(4); + JSONArray labelFromArray = (JSONArray) row.get(5); + + JSONObject nodeTo = (JSONObject) row.get(6); + JSONArray labelToArray = (JSONArray) row.get(7); + + JSONObject relation = (JSONObject) row.get(8); + String type = (String) row.get(9); + + Map propsStartNode = jsonObjectToMap(startNode); + Map propsRelationStartNode = jsonObjectToMap(relationFromStart); + + Map propsFrom = jsonObjectToMap(nodeFrom); + Map propsTo = jsonObjectToMap(nodeTo); + Map propsRelation = jsonObjectToMap(relation); + + GraphNode startN = (GraphNode) GraphElementFactory.createElement((String) startNodeArray.get(0), + GraphElementTypeEnum.Node, propsStartNode); + + GraphNode from = (GraphNode) GraphElementFactory.createElement((String) labelFromArray.get(0), + GraphElementTypeEnum.Node, propsFrom); + GraphNode to = (GraphNode) GraphElementFactory.createElement((String) labelToArray.get(0), + GraphElementTypeEnum.Node, propsTo); + + singleDataList.add(startN); + + GraphElement relationFromStartNode = GraphElementFactory.createRelation(type, + propsRelationStartNode, startN, from); + singleDataList.add(relationFromStartNode); + + singleDataList.add(from); + singleDataList.add(to); + // get only first type on relationship. Now single type + // supported + GraphElement newElement = GraphElementFactory.createRelation(type, propsRelation, from, to); + singleDataList.add(newElement); + } + if (columns.size() == 8) { + + } + } + batchList.add(singleDataList); + } + return batchList; + } + + private Map jsonObjectToMap(JSONObject node) { + Map props = new HashMap<>(); + + for (Map.Entry entry : (Set>) node.entrySet()) { + props.put(entry.getKey(), entry.getValue()); + } + return props; + } + + private String preparePropertiesInStatement(Map properties) { + StringBuilder sb = new StringBuilder(); + int count = 0; + int size = properties.entrySet().size(); + for (Map.Entry entry : properties.entrySet()) { + sb.append("\"").append(entry.getKey()).append("\"").append(":"); + if (entry.getValue() instanceof String) { + sb.append("\""); + } + sb.append(entry.getValue()); + if (entry.getValue() instanceof String) { + sb.append("\""); + } + ++count; + if (count < size) { + sb.append(","); + } + } + return sb.toString(); + } + + private Either createNode(GraphElement element) { + Either status; + if (element instanceof GraphNode) { + GraphNode node = (GraphNode) element; + String json = prepareCreateNodeBody(node); + + logger.debug("Try to save Node [{}] on graph", json); + + status = sendPostCypher(json); + + return status; + + } else { + return Either.right(Neo4jOperationStatus.WRONG_INPUT); + } + } + + private Either sendPostCypher(String json) { + Map neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration().getNeo4j(); + String host = (String) neo4jParams.get("host"); + Integer port = (Integer) neo4jParams.get("port"); + String user = (String) neo4jParams.get("user"); + String password = (String) neo4jParams.get("password"); + + String uri = CypherTemplates.CypherUrlTemplate.replace("$host$", host); + uri = uri.replace("$port$", port.toString()); + + HttpClientContext context = creatClientContext(host, user, password); + CloseableHttpResponse response = null; + + HttpPost post = new HttpPost(uri); + try { + StringEntity input = new StringEntity(json); + input.setContentType("application/json"); + post.setEntity(input); + + response = httpClient.execute(post, context); + + int status = response.getStatusLine().getStatusCode(); + String responseString; + responseString = new BasicResponseHandler().handleResponse(response); + logger.debug("response [{}]", responseString); + + if (status == 200 || status == 201) { + logger.debug("cypher request [{}] was succeeded", json); + Neo4jOperationStatus responseStatus = checkResponse(responseString); + if (Neo4jOperationStatus.OK.equals(responseStatus)) { + return Either.left(responseString); + } else { + return Either.right(responseStatus); + } + } else { + logger.debug("cypher request [{}] was failed : [{}]", json, responseString); + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + + } catch (HttpResponseException e) { + logger.debug("failed to perform cypher request [{}]", json, e); + if (e.getStatusCode() == 401) { + return Either.right(Neo4jOperationStatus.NOT_AUTHORIZED); + } else { + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } + } catch (ClientProtocolException e) { + logger.debug("failed to perform cypher request [{}]", json, e); + return Either.right(Neo4jOperationStatus.HTTP_PROTOCOL_ERROR); + } catch (IOException e) { + logger.debug("failed to perform cypher request [{}]", json, e); + return Either.right(Neo4jOperationStatus.NOT_CONNECTED); + } finally { + releaseResource(response); + } + } + + private Neo4jOperationStatus checkResponse(String responseString) { + try { + JSONObject response = (JSONObject) jsonParser.parse(responseString); + JSONArray errors = (JSONArray) response.get("errors"); + if (errors.size() == 0) { + return Neo4jOperationStatus.OK; + } else { + Iterator iterator = errors.iterator(); + JSONObject error; + while (iterator.hasNext()) { + error = (JSONObject) iterator.next(); + String code = (String) error.get("code"); + String message = (String) error.get("message"); + + return mapToNeoError(code, message); + } + return Neo4jOperationStatus.GENERAL_ERROR; + } + } catch (ParseException e) { + logger.error("Failed to parse response", e); + return Neo4jOperationStatus.GENERAL_ERROR; + } + } + + private Neo4jOperationStatus mapToNeoError(String code, String message) { + Neo4jOperationStatus error; + + String[] errorCode = code.split("\\."); + if (errorCode.length < 4) { + error = Neo4jOperationStatus.GENERAL_ERROR; + } else { + // by Classification + switch (errorCode[1]) { + case ClientError: + // by Category + switch (errorCode[2]) { + case General: + error = Neo4jOperationStatus.DB_READ_ONLY; + break; + case LegacyIndex: + error = Neo4jOperationStatus.LEGACY_INDEX_ERROR; + break; + case Request: + error = Neo4jOperationStatus.BAD_REQUEST; + break; + case Schema: + if (errorCode[3].equals(ConstraintViolation)) { + error = Neo4jOperationStatus.ENTITY_ALREADY_EXIST; + } else { + error = Neo4jOperationStatus.SCHEMA_ERROR; + } + break; + case Security: + error = Neo4jOperationStatus.NOT_AUTHORIZED; + break; + case Statement: + // by Title + if (errorCode[3].equals(EntityNotFound)) { + error = Neo4jOperationStatus.NOT_FOUND; + } else { + if (errorCode[3].equals(ConstraintViolation)) { + error = Neo4jOperationStatus.ENTITY_ALREADY_EXIST; + } else { + error = Neo4jOperationStatus.BAD_REQUEST; + } + } + break; + case Transaction: + error = Neo4jOperationStatus.TRANSACTION_ERROR; + break; + default: + error = Neo4jOperationStatus.GENERAL_ERROR; + break; + } + break; + case DatabaseError: + // by Category + switch (errorCode[2]) { + case General: + error = Neo4jOperationStatus.GENERAL_ERROR; + break; + case Schema: + error = Neo4jOperationStatus.SCHEMA_ERROR; + break; + case Statement: + error = Neo4jOperationStatus.EXECUTION_FAILED; + break; + case Transaction: + error = Neo4jOperationStatus.TRANSACTION_ERROR; + break; + default: + error = Neo4jOperationStatus.GENERAL_ERROR; + break; + } + break; + case TransientError: + error = Neo4jOperationStatus.DB_NOT_AVAILABLE; + break; + default: + error = Neo4jOperationStatus.GENERAL_ERROR; + break; + } + error.setOriginError(code).setMessage(message); + String errorFromCfg = code.replace(".", "_"); + String helpMessage = ConfigurationManager.getConfigurationManager().getNeo4jErrorsConfiguration() + .getErrorMessage(errorFromCfg); + if (helpMessage != null && !helpMessage.isEmpty()) { + error.setHelpErrorMsg(helpMessage); + } + } + return error; + } + + private String prepareCreateNodeBody(GraphNode node) { + + String body = CypherTemplates.CypherCreateNodeTemplate.replace("$label$", node.getLabel()); + + body = body.replace("$props$", DaoUtils.convertToJson(node.toGraphMap())); + + return body; + } + + /** + * the method returns all the indexes for the given label if no label is + * supplied ( null or "") all indexes will be returned + * + * @param label + * the name of the label + * @param ip + * @param user + * @param password + * @return a map of labels and there properties + */ + public Either>, Neo4jOperationStatus> getIndexes(String label) { + Map neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration().getNeo4j(); + String host = (String) neo4jParams.get("host"); + Integer port = (Integer) neo4jParams.get("port"); + String user = (String) neo4jParams.get("user"); + String password = (String) neo4jParams.get("password"); + + String uri = null; + if (label == null || "".equals(label)) { + uri = CypherTemplates.getAllIndexsTemplate.replace("$host$", host); + } else { + uri = CypherTemplates.getAllIndexsTemplate.replace("$host$", host) + "/" + label; + } + uri = uri.replace("$port$", port.toString()); + + HttpClientContext context = creatClientContext(host, user, password); + CloseableHttpResponse response = null; + + HttpGet get = new HttpGet(uri); + get.setHeader("Content-Type", "application/json"); + get.setHeader("Accept", "application/json; charset=UTF-8"); + + try { + + response = httpClient.execute(get, context); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + logger.error("failed to get indexes requeste returned {}", statusCode); + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } else { + Map> labels = getLeablesFromJson(response); + return Either.left(labels); + } + } catch (Exception e) { + logger.debug("failed to get indexes ", e); + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } finally { + releaseResource(response); + + } + + } + + private Map> getLeablesFromJson(CloseableHttpResponse response) + throws HttpResponseException, IOException, ParseException { + Map> labels = new HashMap<>(); + String responseString = new BasicResponseHandler().handleResponse(response); + JSONArray results = (JSONArray) jsonParser.parse(responseString); + Iterator iteratorResults = results.iterator(); + while (iteratorResults.hasNext()) { + JSONObject elementResult = iteratorResults.next(); + String label = (String) elementResult.get("label"); + List props = labels.get(label); + if (props == null) { + props = new ArrayList<>(); + labels.put(label, props); + } + JSONArray properties = (JSONArray) elementResult.get("property_keys"); + Iterator iterator = properties.iterator(); + while (iterator.hasNext()) { + props.add(iterator.next()); + } + } + return labels; + } + + public Neo4jOperationStatus createIndex(String label, List propertyNames) { + + Neo4jOperationStatus result = Neo4jOperationStatus.OK; + if (propertyNames != null && !propertyNames.isEmpty()) { + + Map neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration() + .getNeo4j(); + String host = (String) neo4jParams.get("host"); + Integer port = (Integer) neo4jParams.get("port"); + String user = (String) neo4jParams.get("user"); + String password = (String) neo4jParams.get("password"); + + String uri = CypherTemplates.batchTemplate.replace("$host$", host); + uri = uri.replace("$port$", port.toString()); + + String opertionUri = "/schema/index/" + label; + + HttpClientContext context = creatClientContext(host, user, password); + + CloseableHttpResponse response = null; + + HttpPost post = new HttpPost(uri); + + String json = createBatchJson(HttpMethod.POST, opertionUri, propertyNames); + + try { + StringEntity input = new StringEntity(json); + input.setContentType("application/json"); + post.setEntity(input); + response = httpClient.execute(post, context); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + logger.error("failed to create index for label [{}] with properties:{} requeste returned {}",label,propertyNames,statusCode); + result = Neo4jOperationStatus.GENERAL_ERROR; + } else { + logger.debug("index for label [{}] with properties: {} created", label, propertyNames); + } + } catch (Exception e) { + logger.debug("failed to create index for label [{}] with properties: {}", label, propertyNames); + result = Neo4jOperationStatus.GENERAL_ERROR; + } finally { + + releaseResource(response); + + } + + } + + else { + logger.debug("no index was created for label :{} the recived propertyNames list: {} is invalide",label,propertyNames); + return Neo4jOperationStatus.WRONG_INPUT; + } + + return result; + } + + public Neo4jOperationStatus createUniquenessConstraints(String label, List propertyNames) { + Neo4jOperationStatus result = Neo4jOperationStatus.OK; + if (propertyNames != null && !propertyNames.isEmpty()) { + + Map neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration() + .getNeo4j(); + String host = (String) neo4jParams.get("host"); + Integer port = (Integer) neo4jParams.get("port"); + String user = (String) neo4jParams.get("user"); + String password = (String) neo4jParams.get("password"); + + String uri = CypherTemplates.batchTemplate.replace("$host$", host); + uri = uri.replace("$port$", port.toString()); + + String opertionUri = "/schema/constraint/" + label + "/uniqueness/"; + + HttpClientContext context = creatClientContext(host, user, password); + + CloseableHttpResponse response = null; + + HttpPost post = new HttpPost(uri); + + String json = createBatchJson(HttpMethod.POST, opertionUri, propertyNames); + + try { + StringEntity input = new StringEntity(json); + input.setContentType("application/json"); + post.setEntity(input); + response = httpClient.execute(post, context); + + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + logger.error("failed to create uniqueness constraint for label [{}] on properties:{}. request returned ", + label,propertyNames,statusCode); + result = Neo4jOperationStatus.GENERAL_ERROR; + } else { + logger.debug("uniqueness constraint for label [{}] on properties:{} created",label,propertyNames); + } + } catch (Exception e) { + logger.error("failed to create uniqueness constraint [{}] with properties:{}",label,propertyNames,e); + result = Neo4jOperationStatus.GENERAL_ERROR; + } finally { + releaseResource(response); + } + + } + + else { + logger.debug("no index was created for label :{} the recived propertyNames list: {} is invalide",label,propertyNames); + return Neo4jOperationStatus.WRONG_INPUT; + } + + return result; + } + + public Neo4jOperationStatus deleteElement(GraphElementTypeEnum type, String label, MatchFilter filter) { + + String requestJson; + // replace return type + if (type.equals(GraphElementTypeEnum.Node)) { + logger.debug("removing node label: {}", label); + requestJson = createDeleteNodeStatment(label, filter); + + } else { + logger.error(" delete on type {} is not yet supported", type); + throw new RuntimeException(" delete on type " + type + " is not yet supported"); + } + + logger.debug("Try to perform request [{}]", requestJson); + + Either status = sendPostCypher(requestJson); + if (status.isRight()) { + logger.error(" delete request failed with: {}", status.right()); + return Neo4jOperationStatus.GENERAL_ERROR; + } else { + return Neo4jOperationStatus.OK; + } + } + + public String getNeo4jVersion() throws Exception { + Map neo4jParams = ConfigurationManager.getConfigurationManager().getConfiguration().getNeo4j(); + String host = (String) neo4jParams.get("host"); + Integer port = (Integer) neo4jParams.get("port"); + String user = (String) neo4jParams.get("user"); + String password = (String) neo4jParams.get("password"); + + String uri = getServiceRoot.replace("$host$", host).replace("$port$", port.toString()); + + HttpClientContext context = creatClientContext(host, user, password); + CloseableHttpResponse response = null; + String result = null; + + HttpGet get = new HttpGet(uri); + get.setHeader("Content-Type", "application/json"); + get.setHeader("Accept", "application/json; charset=UTF-8"); + + try { + response = httpClient.execute(get, context); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + throw new Exception("Couldn't get Neo4j service root, HTTP status " + statusCode); + } else { + // Parse response + String responseString = new BasicResponseHandler().handleResponse(response); + JSONObject responseData = (JSONObject) jsonParser.parse(responseString); + Object obj = responseData.get("neo4j_version"); + if (obj != null) { + result = (String) obj; + } + return result; + } + } finally { + releaseResource(response); + } + } + + private String createDeleteNodeStatment(String label, MatchFilter filter) { + String requestJson; + requestJson = CypherTemplates.CypherDeleteNodeTemplate; + + if (label != null && !label.isEmpty()) { + requestJson = requestJson.replace("$label$", label); + } else { + requestJson = requestJson.replace("$label$", ""); + } + + // replace filter + if (filter.getProperties().isEmpty()) { + // get all records by label + requestJson = requestJson.replace("{$filter$}", ""); + } else { + String filterStr = CypherTranslator.prepareFilterBody(filter); + requestJson = requestJson.replace("$filter$", filterStr); + } + return requestJson; + } + + /* + * removed do to fortify scan CredentialsProvider cp = new + * BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new + * UsernamePasswordCredentials(user, password)); AuthCache authCache = new + * BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); + * authCache.put(new HttpHost(ip, 7474, "http"), basicAuth); + * context.setAuthCache(authCache); context.setCredentialsProvider(cp); + * + */ + private HttpClientContext creatClientContext(String ip, String user, String password) { + + return HttpClientContext.create(); + } + + private void releaseResource(CloseableHttpResponse response) { + if (response != null) { + try { + HttpEntity entity = response.getEntity(); + EntityUtils.consume(entity); + response.close(); + } catch (Exception e) { + logger.error("failed to close connection exception", e); + } + } + } + + private String createBatchJson(HttpMethod method, String opertionUri, List propertyNames) { + StringBuilder sb = new StringBuilder(); + sb.append("[ "); + for (int i = 0; i < propertyNames.size(); i++) { + sb.append("{ \"method\" : \"" + method + "\" , \"to\" : \"" + opertionUri + + "\" , \"body\" : { \"property_keys\" : [ \"" + propertyNames.get(i) + "\" ] } }"); + if (i + 1 < propertyNames.size()) { + sb.append(","); + } + } + sb.append(" ]"); + return sb.toString(); + } + + enum HttpMethod { + GET, PUT, POST, DELETE + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java new file mode 100644 index 0000000000..bdd17b6512 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jEdge.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; + +import java.util.Map; + +public class Neo4jEdge { + + private GraphEdgeLabels edgeType; + private Map properties; + private ActionEnum action; + + public Neo4jEdge(GraphEdgeLabels edgeType, Map properties, ActionEnum actionEnum) { + super(); + this.edgeType = edgeType; + this.properties = properties; + this.action = actionEnum; + } + + public GraphEdgeLabels getEdgeType() { + return edgeType; + } + + public void setEdgeType(GraphEdgeLabels edgeType) { + this.edgeType = edgeType; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public ActionEnum getAction() { + return action; + } + + public void setAction(ActionEnum action) { + this.action = action; + } + + @Override + public String toString() { + return "Neo4jEdge [edgeType=" + edgeType + ", properties=" + properties + ", action=" + action + "]"; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java new file mode 100644 index 0000000000..f28baf0017 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jGraphBatchBuilder.java @@ -0,0 +1,179 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.graph.datatype.*; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.*; + +public class Neo4jGraphBatchBuilder { + + private static Logger logger = Logger.getLogger(Neo4jGraphBatchBuilder.class.getName()); + + public Either buildBatchBuilderFromTable( + GraphNeighbourTable graphNeighbourTable) { + + logger.debug("The table sent in order to build BatchBuilder is {}", graphNeighbourTable); + + List nodes = graphNeighbourTable.getNodes(); + if (nodes != null && nodes.size() > 0) { + List directedEdges = graphNeighbourTable.getDirectedEdges(); + + List relationEndPoints = new ArrayList<>(nodes.size()); + Set nodesInRelations = findDistinctNodesIndex(directedEdges); + + buildRelationEndPoints(nodes, nodesInRelations, relationEndPoints); + + BatchBuilder batchBuilder = BatchBuilder.getBuilder(); + + for (GraphElement neo4jElement : nodes) { + if (neo4jElement.getAction() != ActionEnum.Delete) { + logger.debug("Goint to add node {} to batch builder.", neo4jElement); + batchBuilder.add(neo4jElement); + } + } + + if (directedEdges != null) { + for (NodeRelation nodeRelation : directedEdges) { + GraphRelation relation = buildNeo4jRelation(relationEndPoints, nodeRelation); + logger.debug("Goint to add relation {} to batch builder.", relation); + batchBuilder.add(relation); + } + } + + for (GraphElement neo4jElement : nodes) { + if (neo4jElement.getAction() == ActionEnum.Delete) { + logger.debug("Goint to add node {} to batch builder.", neo4jElement); + batchBuilder.add(neo4jElement); + } + } + + return Either.left(batchBuilder); + + } else { + logger.error("No node was sent in order to create the resource."); + return Either.right(Neo4jOperationStatus.BAD_REQUEST); + } + } + + private Pair getUniqueIdKeyValue(GraphNode neo4jNode) { + + // String label = neo4jNode.getLabel(); + // NodeTypeEnum nodeTypeEnum = NodeTypeEnum.getByName(label); + // + return Pair.createPair(neo4jNode.getUniqueIdKey(), neo4jNode.getUniqueId().toString()); + } + + private Set findDistinctNodesIndex(List directedEdges) { + + HashSet nodesIndex = new HashSet<>(); + + if (directedEdges != null) { + for (NodeRelation nodeRelation : directedEdges) { + nodesIndex.add(nodeRelation.getFromIndex()); + nodesIndex.add(nodeRelation.getToIndex()); + } + } + + return nodesIndex; + } + + private String findResourceDataIdFromNodes(List nodes) { + + if (nodes != null) { + + for (GraphNode neo4jNode : nodes) { + String label = neo4jNode.getLabel(); + if (label.equals(NodeTypeEnum.Resource.getName())) { + return neo4jNode.getUniqueId().toString(); + } + } + } + + return null; + } + + private GraphRelation buildNeo4jRelation(List relationEndPoints, NodeRelation nodeRelation) { + GraphRelation relation = new GraphRelation(); + int fromIndex = nodeRelation.getFromIndex(); + int toIndex = nodeRelation.getToIndex(); + Neo4jEdge neo4jEdge = nodeRelation.getEdge(); + relation.setFrom(relationEndPoints.get(fromIndex)); + relation.setTo(relationEndPoints.get(toIndex)); + relation.setType(neo4jEdge.getEdgeType().getProperty()); + + // TODO: fix it after change + Map edgeProps = neo4jEdge.getProperties(); + if (edgeProps != null && !edgeProps.isEmpty()) { + relation.addPropertis(edgeProps); + } + + relation.setAction(neo4jEdge.getAction()); + return relation; + } + + private void buildRelationEndPoints(List nodes, Set nodesInRelations, + List relationEndPoints) { + + if (nodesInRelations != null) { + for (Integer nodeIndex : nodesInRelations) { + + GraphElement neo4jElement = nodes.get(nodeIndex); + GraphNode neo4jNode = (GraphNode) neo4jElement; + String label = neo4jNode.getLabel(); + Pair uniqueKeyValue = getUniqueIdKeyValue(neo4jNode); + + RelationEndPoint endPoint = new RelationEndPoint(NodeTypeEnum.getByName(label), uniqueKeyValue.getKey(), + uniqueKeyValue.getValue()); + relationEndPoints.add(nodeIndex, endPoint); + + } + } + + } + + public static class Pair { + + private final K key; + private final V value; + + public static Pair createPair(K key, V value) { + return new Pair<>(key, value); + } + + public Pair(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java new file mode 100644 index 0000000000..154449b521 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/Neo4jOperationStatus.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +public enum Neo4jOperationStatus { + + OK, NOT_CONNECTED, NOT_AUTHORIZED, HTTP_PROTOCOL_ERROR, DB_NOT_AVAILABLE, DB_READ_ONLY, BAD_REQUEST, LEGACY_INDEX_ERROR, SCHEMA_ERROR, TRANSACTION_ERROR, EXECUTION_FAILED, ENTITY_ALREADY_EXIST, + + WRONG_INPUT, GENERAL_ERROR, NOT_SUPPORTED, NOT_FOUND; + + private String originError; + private String message; + private String helpErrorMsg; + + private static final String NA = "NA"; + + Neo4jOperationStatus() { + originError = NA; + message = NA; + helpErrorMsg = NA; + } + + public Neo4jOperationStatus setOriginError(String originError) { + this.originError = originError; + return this; + } + + public Neo4jOperationStatus setMessage(String message) { + if (message != null && !message.isEmpty()) { + this.message = message; + } + return this; + } + + public Neo4jOperationStatus setHelpErrorMsg(String helpErrorMsg) { + this.helpErrorMsg = helpErrorMsg; + return this; + } + + public String getOriginError() { + return originError; + } + + public String getMessage() { + return message; + } + + public String getHelpErrorMsg() { + return helpErrorMsg; + } + + public String printError() { + StringBuilder sb = new StringBuilder(); + sb.append("[").append(toString()).append("-").append(originError).append("-").append(helpErrorMsg).append("-") + .append(message).append("]"); + return sb.toString(); + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java new file mode 100644 index 0000000000..c1402f402f --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/NodeRelation.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j; + +public class NodeRelation { + + private int fromIndex; + private int toIndex; + private Neo4jEdge edge; + + public NodeRelation(int fromIndex, int toIndex, Neo4jEdge edge) { + super(); + this.fromIndex = fromIndex; + this.toIndex = toIndex; + this.edge = edge; + } + + public int getFromIndex() { + return fromIndex; + } + + public void setFromIndex(int fromIndex) { + this.fromIndex = fromIndex; + } + + public int getToIndex() { + return toIndex; + } + + public void setToIndex(int toIndex) { + this.toIndex = toIndex; + } + + public Neo4jEdge getEdge() { + return edge; + } + + public void setEdge(Neo4jEdge edge) { + this.edge = edge; + } + + @Override + public String toString() { + return "NodeRelation [fromIndex=" + fromIndex + ", toIndex=" + toIndex + ", edge=" + edge + "]"; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java new file mode 100644 index 0000000000..7933efbb84 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/MatchFilter.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j.filters; + +import java.util.HashMap; +import java.util.Map; + +public class MatchFilter { + private Map toMatchProperties; + + public MatchFilter() { + toMatchProperties = new HashMap<>(); + } + + public MatchFilter(Map toMatchProperties) { + super(); + this.toMatchProperties = toMatchProperties; + } + + public Map getProperties() { + return toMatchProperties; + } + + public void setProperties(Map properties) { + this.toMatchProperties = properties; + } + + public MatchFilter addToMatch(String propName, Object value) { + toMatchProperties.put(propName, value); + return this; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java new file mode 100644 index 0000000000..698077d45b --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveByRelationFilter.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j.filters; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +public class RecursiveByRelationFilter extends RecursiveFilter { + + private GraphNode node; + private String relationType; + + public RecursiveByRelationFilter() { + super(); + } + + public RecursiveByRelationFilter(NodeTypeEnum nodeType, GraphNode node) { + super(nodeType); + this.node = node; + } + + public RecursiveByRelationFilter(NodeTypeEnum nodeType) { + super(nodeType); + } + + public RecursiveByRelationFilter(NodeTypeEnum nodeType, GraphNode node, String relationType) { + super(nodeType); + this.node = node; + this.relationType = relationType; + } + + public RecursiveByRelationFilter addNode(GraphNode node) { + this.node = node; + return this; + } + + public RecursiveByRelationFilter addRelation(String relationType) { + this.relationType = relationType; + return this; + } + + public GraphNode getNode() { + return node; + } + + public void setNode(GraphNode node) { + this.node = node; + } + + public String getRelationType() { + return relationType; + } + + public void setRelationType(String relationType) { + this.relationType = relationType; + } + + @Override + public String toString() { + return "RecursiveByRelationFilter [node=" + node + ", relationType=" + relationType + "]"; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java new file mode 100644 index 0000000000..6dafd51930 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/RecursiveFilter.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j.filters; + +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +import java.util.ArrayList; +import java.util.List; + +public class RecursiveFilter extends MatchFilter { + + private List childRelationTypes; + NodeTypeEnum nodeType; + + public RecursiveFilter() { + childRelationTypes = new ArrayList<>(); + } + + public RecursiveFilter(NodeTypeEnum nodeType) { + childRelationTypes = new ArrayList<>(); + this.nodeType = nodeType; + } + + public RecursiveFilter addChildRelationType(String type) { + childRelationTypes.add(type); + return this; + } + + public List getChildRelationTypes() { + return childRelationTypes; + } + + public void setChildRelationTypes(List childRelationTypes) { + this.childRelationTypes = childRelationTypes; + } + + public NodeTypeEnum getNodeType() { + return nodeType; + } + + public void setNodeType(NodeTypeEnum nodeType) { + this.nodeType = nodeType; + } + + @Override + public String toString() { + return "RecursiveFilter [childRelationTypes=" + childRelationTypes + ", nodeType=" + nodeType + "]"; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java new file mode 100644 index 0000000000..190993668d --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/filters/UpdateFilter.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.neo4j.filters; + +import java.util.HashMap; +import java.util.Map; + +public class UpdateFilter extends MatchFilter { + + private Map toUpdate; + + public UpdateFilter(Map toUpdate) { + super(); + this.toUpdate = toUpdate; + } + + public UpdateFilter() { + super(); + toUpdate = new HashMap<>(); + } + + public UpdateFilter(Map toMatch, Map toUpdate) { + super(toMatch); + this.toUpdate = toUpdate; + } + + public Map getToUpdate() { + return toUpdate; + } + + public void setToUpdate(Map toUpdate) { + this.toUpdate = toUpdate; + } + + public void addToUpdate(String property, Object value) { + toUpdate.put(property, value); + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java index d065a672b5..459e98379b 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java @@ -20,69 +20,59 @@ package org.openecomp.sdc.be.dao.titan; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.StreamSupport; - +import com.thinkaurelius.titan.core.*; +import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.*; import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.graph.GraphElementFactory; -import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; -import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; -import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; -import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; -import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint; +import org.openecomp.sdc.be.dao.graph.datatype.*; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.resources.data.GraphNodeLock; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanGraphQuery; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.TitanVertexQuery; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; - -import fj.data.Either; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; @Component("titan-generic-dao") public class TitanGenericDao { private TitanGraphClient titanClient; - - private static Logger logger = LoggerFactory.getLogger(TitanGenericDao.class.getName()); + private static Logger log = Logger.getLogger(TitanGenericDao.class.getName()); private static final String LOCK_NODE_PREFIX = "lock_"; public TitanGenericDao(TitanGraphClient titanClient) { this.titanClient = titanClient; - logger.info("** TitanGenericDao created"); + log.info("** TitanGenericDao created"); } public TitanOperationStatus commit() { - logger.debug("doing commit."); + log.debug("doing commit."); return titanClient.commit(); } public TitanOperationStatus rollback() { + log.error("Going to execute rollback on graph."); return titanClient.rollback(); } + public void handleTransactionCommitRollback(boolean inTransaction, Either result) { + if (!inTransaction) { + if (result == null || result.isRight()) { + rollback(); + } else { + commit(); + } + } + } + public Either getGraph() { return titanClient.getGraph(); } @@ -99,7 +89,7 @@ public class TitanGenericDao { * @return */ public Either createNode(T node, Class clazz) { - logger.debug("try to create node for ID [{}]", node.getKeyValueId()); + log.debug("try to create node for ID [{}]", node.getKeyValueId()); Either graph = titanClient.getGraph(); if (graph.isLeft()) { T newNode; @@ -116,23 +106,23 @@ public class TitanGenericDao { } Map newProps = getProperties(vertex); newNode = GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProps, clazz); - logger.debug("created node for props : {}", newProps); - logger.debug("Node was created for ID [{}]", node.getKeyValueId()); + log.debug("created node for props : {}", newProps); + log.debug("Node was created for ID [{}]", node.getKeyValueId()); return Either.left(newNode); } catch (Exception e) { - logger.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); + log.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - logger.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); + log.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); return Either.right(graph.right().value()); } } public Either createNode(GraphNode node) { - logger.debug("try to create node for ID [{}]", node.getKeyValueId()); + log.debug("try to create node for ID [{}]", node.getKeyValueId()); Either graph = titanClient.getGraph(); if (graph.isLeft()) { try { @@ -146,16 +136,16 @@ public class TitanGenericDao { if (properties != null) { setProperties(vertex, properties); } - logger.debug("Node was created for ID [{}]", node.getKeyValueId()); + log.debug("Node was created for ID [{}]", node.getKeyValueId()); return Either.left(vertex); } catch (Exception e) { - logger.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); + log.debug("Failed to create Node for ID [{}]", node.getKeyValueId(), e); return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - logger.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); + log.debug("Failed to create Node for ID [{}] {}", node.getKeyValueId(), graph.right().value()); return Either.right(graph.right().value()); } } @@ -166,12 +156,12 @@ public class TitanGenericDao { * @return */ public Either createRelation(GraphRelation relation) { - logger.debug("try to create relation from [{}] to [{}] ", relation.getFrom(), relation.getTo()); + log.debug("try to create relation from [{}] to [{}] ", relation.getFrom(), relation.getTo()); RelationEndPoint from = relation.getFrom(); RelationEndPoint to = relation.getTo(); - ImmutablePair fromKeyId = new ImmutablePair(from.getIdName(), from.getIdValue()); - ImmutablePair toKeyId = new ImmutablePair(to.getIdName(), to.getIdValue()); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); return createEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap()); @@ -220,11 +210,11 @@ public class TitanGenericDao { return Either.left(newRelation); } catch (Exception e) { - logger.debug("Failed to create edge from [{}] to [{}]", from, to, e); + log.debug("Failed to create edge from [{}] to [{}]", from, to, e); return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - logger.debug("Failed to create edge from [{}] to [{}] {}", from, to, graph.right().value()); + log.debug("Failed to create edge from [{}] to [{}] {}", from, to, graph.right().value()); return Either.right(graph.right().value()); } } @@ -233,7 +223,7 @@ public class TitanGenericDao { try { Edge edge = addEdge(vertexOut, vertexIn, type, properties); } catch (Exception e) { - logger.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e); + log.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e); return TitanGraphClient.handleTitanException(e); } return TitanOperationStatus.OK; @@ -270,7 +260,7 @@ public class TitanGenericDao { Edge edge = addEdge(vertexOut, vertexIn, type, properties); return Either.left(edge); } catch (Exception e) { - logger.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e); + log.debug("Failed to create edge from [{}] to [{}]", vertexOut, vertexIn, e); return Either.right(TitanGraphClient.handleTitanException(e)); } @@ -301,13 +291,13 @@ public class TitanGenericDao { * @return */ public Either createRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map properties) { - logger.debug("try to create relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + log.debug("try to create relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); return createEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties); } public Either replaceRelationLabel(GraphNode from, GraphNode to, GraphEdgeLabels label, GraphEdgeLabels newLabel) { - logger.debug("try to replace relation {} to {} from [{}] to [{}]", label.name(), newLabel.name(), from.getKeyValueId(), to.getKeyValueId()); + log.debug("try to replace relation {} to {} from [{}] to [{}]", label.name(), newLabel.name(), from.getKeyValueId(), to.getKeyValueId()); Either getRelationResult = getRelation(from, to, label); if (getRelationResult.isRight()) { return getRelationResult; @@ -335,7 +325,7 @@ public class TitanGenericDao { */ public Either getNode(String keyName, Object keyValue, Class clazz) { - logger.debug("Try to get node for key [{}] with value [{}] ", keyName, keyValue); + log.debug("Try to get node for key [{}] with value [{}] ", keyName, keyValue); Either vertexByProperty = getVertexByProperty(keyName, keyValue); @@ -346,11 +336,11 @@ public class TitanGenericDao { T node = GraphElementFactory.createElement((String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()), GraphElementTypeEnum.Node, properties, clazz); return Either.left(node); } catch (Exception e) { - logger.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, e); + log.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, e); return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - logger.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, vertexByProperty.right().value()); + log.debug("Failed to get node for key [{}] with value [{}] ", keyName, keyValue, vertexByProperty.right().value()); return Either.right(vertexByProperty.right().value()); } } @@ -363,7 +353,7 @@ public class TitanGenericDao { * @return */ public Either getRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) { - logger.debug("try to get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + log.debug("try to get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); Either edge = getEdgeByNodes(from, to, label); @@ -373,11 +363,11 @@ public class TitanGenericDao { GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, from, to); return Either.left(relation); } catch (Exception e) { - logger.debug("Failed to get get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId(), e); + log.debug("Failed to get get relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId(), e); return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - logger.debug("Failed to get get relation from [{}] to [{}] {}", from.getKeyValueId(), to.getKeyValueId(), edge.right().value()); + log.debug("Failed to get get relation from [{}] to [{}] {}", from.getKeyValueId(), to.getKeyValueId(), edge.right().value()); return Either.right(edge.right().value()); } } @@ -396,7 +386,7 @@ public class TitanGenericDao { Either graph = getGraph(); if (graph.isLeft()) { Edge edge = edgeByCriteria.left().value(); - logger.debug("delete edge {} to {} ", label.getProperty(), to.getUniqueId()); + log.debug("delete edge {} to {} ", label.getProperty(), to.getUniqueId()); edge.remove(); Map properties = getProperties(edge); Vertex fromVertex = edge.outVertex(); @@ -405,12 +395,12 @@ public class TitanGenericDao { GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to); return Either.left(relation); } else { - logger.debug("failed to get graph"); + log.debug("failed to get graph"); return Either.right(graph.right().value()); } } else { - logger.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); + log.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); return Either.right(edgeByCriteria.right().value()); } @@ -430,12 +420,12 @@ public class TitanGenericDao { GraphRelation relation = GraphElementFactory.createRelation(label.getProperty(), properties, nodeFrom, to); return Either.left(relation); } else { - logger.debug("failed to get graph"); + log.debug("failed to get graph"); return Either.right(graph.right().value()); } } else { - logger.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); + log.debug("failed to find edge {} to {}", label.getProperty(), to.getUniqueId()); return Either.right(edgeByCriteria.right().value()); } @@ -462,17 +452,16 @@ public class TitanGenericDao { Edge matchingEdge = null; Iterable edges = query.edges(); if (edges == null) { - logger.debug("No edges in graph for criteria"); + log.debug("No edges in graph for criteria"); return Either.right(TitanOperationStatus.NOT_FOUND); } Iterator eIter = edges.iterator(); if (eIter.hasNext()) { - TitanEdge edge = eIter.next(); - matchingEdge = edge; + matchingEdge = eIter.next(); } if (matchingEdge == null) { - logger.debug("No edges in graph for criteria"); + log.debug("No edges in graph for criteria"); return Either.right(TitanOperationStatus.NOT_FOUND); } return Either.left(matchingEdge); @@ -496,10 +485,10 @@ public class TitanGenericDao { return Either.left(edge); } } - logger.debug("No relation in graph from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo); + log.debug("No relation in graph from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo); return Either.right(TitanOperationStatus.NOT_FOUND); } catch (Exception e) { - logger.debug("Failed to get get relation from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo, e); + log.debug("Failed to get get relation from [{}={}] to [{}={}]", keyNameFrom, keyValueFrom, keyNameTo, keyValueTo, e); return Either.right(TitanGraphClient.handleTitanException(e)); } } else { @@ -559,7 +548,7 @@ public class TitanGenericDao { * @return */ public Either updateRelation(GraphNode from, GraphNode to, GraphEdgeLabels label, Map properties) { - logger.debug("try to update relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + log.debug("try to update relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); return updateEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel(), properties); } @@ -581,19 +570,19 @@ public class TitanGenericDao { GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); GraphRelation newRelation = GraphElementFactory.createRelation(edge.label(), getProperties(edge), nodeOut, nodeIn); - if (logger.isDebugEnabled()) { - logger.debug("Relation was updated from [{}] to [{}] ", from, to); + if (log.isDebugEnabled()) { + log.debug("Relation was updated from [{}] to [{}] ", from, to); } return Either.left(newRelation); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to update relation from [{}] to [{}] ", from, to, e); + if (log.isDebugEnabled()) { + log.debug("Failed to update relation from [{}] to [{}] ", from, to, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed to update relation from [{}] to [{}] {}", from, to, edgeS.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed to update relation from [{}] to [{}] {}", from, to, edgeS.right().value()); } return Either.right(edgeS.right().value()); } @@ -605,11 +594,11 @@ public class TitanGenericDao { * @return */ public Either updateRelation(GraphRelation relation) { - logger.debug("try to update relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); + log.debug("try to update relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); RelationEndPoint from = relation.getFrom(); RelationEndPoint to = relation.getTo(); - ImmutablePair fromKeyId = new ImmutablePair(from.getIdName(), from.getIdValue()); - ImmutablePair toKeyId = new ImmutablePair(to.getIdName(), to.getIdValue()); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); return updateEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName(), relation.toGraphMap()); @@ -630,20 +619,20 @@ public class TitanGenericDao { Vertex vertex = iterator.next(); return Either.left(vertex); } - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key =" + name + " and value = " + value + " label = " + label); + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key =" + name + " and value = " + value + " label = " + label); } return Either.right(TitanOperationStatus.NOT_FOUND); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}",name,value,label); + if (log.isDebugEnabled()) { + log.debug("Failed to get vertex in graph for key ={} and value = {} label = {}",name,value,label); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key ={} and value = {} label = {} error : {}",name,value,label,graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key ={} and value = {} label = {} error : {}",name,value,label,graph.right().value()); } return Either.right(graph.right().value()); } @@ -653,8 +642,8 @@ public class TitanGenericDao { Either graph = titanClient.getGraph(); if (value == null) { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key = {} and value = {}", name, value); + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key = {} and value = {}", name, value); } return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -670,20 +659,20 @@ public class TitanGenericDao { TitanVertex vertex = iterator.next(); return Either.left(vertex); } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key ={} and value = {}", name, value); + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key ={} and value = {}", name, value); } return Either.right(TitanOperationStatus.NOT_FOUND); } } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for key = {} and value = ", name, value); + if (log.isDebugEnabled()) { + log.debug("Failed to get vertex in graph for key = {} and value = ", name, value); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key = {} and value = {} error : {}", name, value, graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("No vertex in graph for key = {} and value = {} error : {}", name, value, graph.right().value()); } return Either.right(graph.right().value()); } @@ -714,7 +703,7 @@ public class TitanGenericDao { } Iterator iterator = vertices.iterator(); - List result = new ArrayList(); + List result = new ArrayList<>(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); @@ -724,8 +713,8 @@ public class TitanGenericDao { T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); result.add(element); } - if (logger.isDebugEnabled()) { - logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties has = {}, properties hasNot = {} is {}", type, hasProps, hasNotProps, result.size()); + if (log.isDebugEnabled()) { + log.debug("Number of fetced nodes in graph for criteria : from type = {} and properties has = {}, properties hasNot = {} is {}", type, hasProps, hasNotProps, result.size()); } if (result.size() == 0) { return Either.right(TitanOperationStatus.NOT_FOUND); @@ -733,15 +722,15 @@ public class TitanGenericDao { return Either.left(result); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {}", type, e); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {}", type, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); } return Either.right(graph.right().value()); } @@ -768,7 +757,7 @@ public class TitanGenericDao { } Iterator iterator = vertices.iterator(); - List result = new ArrayList(); + List result = new ArrayList<>(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); @@ -784,15 +773,15 @@ public class TitanGenericDao { return Either.left(result); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {}", type, e); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {}", type, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type ={} error : {}", type, graph.right().value()); } return Either.right(graph.right().value()); } @@ -818,7 +807,7 @@ public class TitanGenericDao { } Iterator iterator = vertices.iterator(); - List result = new ArrayList(); + List result = new ArrayList<>(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); @@ -828,8 +817,8 @@ public class TitanGenericDao { T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz); result.add(element); } - if (logger.isDebugEnabled()) { - logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); + if (log.isDebugEnabled()) { + log.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); } if (result.size() == 0) { return Either.right(TitanOperationStatus.NOT_FOUND); @@ -837,15 +826,15 @@ public class TitanGenericDao { return Either.left(result); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); } return Either.right(graph.right().value()); } @@ -875,7 +864,7 @@ public class TitanGenericDao { } Iterator iterator = vertices.iterator(); - List result = new ArrayList(); + List result = new ArrayList<>(); while (iterator.hasNext()) { Vertex vertex = iterator.next(); @@ -887,20 +876,20 @@ public class TitanGenericDao { if (result.size() == 0) { return Either.right(TitanOperationStatus.NOT_FOUND); } - if (logger.isDebugEnabled()) { - logger.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props); + if (log.isDebugEnabled()) { + log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props); } return Either.left(result); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {} error : {}", type, props, graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed get by criteria for type = {} and properties = {} error : {}", type, props, graph.right().value()); } return Either.right(graph.right().value()); } @@ -917,7 +906,7 @@ public class TitanGenericDao { * @return */ public Either updateNode(GraphNode node, Class clazz) { - logger.debug("Try to update node for {}", node.getKeyValueId()); + log.debug("Try to update node for {}", node.getKeyValueId()); ImmutablePair keyValueId = node.getKeyValueId(); Either vertexByProperty = getVertexByPropertyAndLabel(keyValueId.getKey(), keyValueId.getValue(), node.getLabel()); @@ -943,14 +932,14 @@ public class TitanGenericDao { return Either.left(updateNode); } } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to update node for {}", node.getKeyValueId(), e); + if (log.isDebugEnabled()) { + log.debug("Failed to update node for {}", node.getKeyValueId(), e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed to update node for {} error :{}", node.getKeyValueId(), vertexByProperty.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed to update node for {} error :{}", node.getKeyValueId(), vertexByProperty.right().value()); } return Either.right(vertexByProperty.right().value()); } @@ -958,7 +947,7 @@ public class TitanGenericDao { } public TitanOperationStatus updateVertex(GraphNode node, Vertex vertex) { - logger.debug("Try to update node for {}", node.getKeyValueId()); + log.debug("Try to update node for {}", node.getKeyValueId()); try { Map mapProps = node.toGraphMap(); @@ -970,8 +959,8 @@ public class TitanGenericDao { } } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to update node for {}", node.getKeyValueId(), e); + if (log.isDebugEnabled()) { + log.debug("Failed to update node for {}", node.getKeyValueId(), e); } return TitanGraphClient.handleTitanException(e); } @@ -986,7 +975,7 @@ public class TitanGenericDao { * @return */ public Either deleteNode(GraphNode node, Class clazz) { - logger.debug("Try to delete node for {}", node.getKeyValueId()); + log.debug("Try to delete node for {}", node.getKeyValueId()); ImmutablePair keyValueId = node.getKeyValueId(); return deleteNode(keyValueId.getKey(), keyValueId.getValue(), clazz); } @@ -1020,20 +1009,20 @@ public class TitanGenericDao { } return Either.left(node); } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); + if (log.isDebugEnabled()) { + log.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); } return Either.right(TitanOperationStatus.MISSING_NODE_LABEL); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); + if (log.isDebugEnabled()) { + log.debug("Failed to delete node for {} = {} Missing label property on node", keyName, keyValue); } return Either.right(TitanOperationStatus.MISSING_NODE_LABEL); } } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to delete node for {} = {}", keyName, keyValue, e); + if (log.isDebugEnabled()) { + log.debug("Failed to delete node for {} = {}", keyName, keyValue, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } @@ -1044,11 +1033,11 @@ public class TitanGenericDao { } public Either deleteRelation(GraphRelation relation) { - logger.debug("try to delete relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); + log.debug("try to delete relation from [{}] to [{}]", relation.getFrom(), relation.getTo()); RelationEndPoint from = relation.getFrom(); RelationEndPoint to = relation.getTo(); - ImmutablePair fromKeyId = new ImmutablePair(from.getIdName(), from.getIdValue()); - ImmutablePair toKeyId = new ImmutablePair(to.getIdName(), to.getIdValue()); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); return deleteEdge(relation.getType(), fromKeyId, toKeyId, from.getLabel().getName(), to.getLabel().getName()); @@ -1063,7 +1052,7 @@ public class TitanGenericDao { } public Either deleteRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) { - logger.debug("try to delete relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); + log.debug("try to delete relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId()); return deleteEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel()); } @@ -1087,21 +1076,21 @@ public class TitanGenericDao { edge.remove(); ; } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed to delete relation {} from {} to {} error : {}",type,fromKeyId,toKeyId,graph.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed to delete relation {} from {} to {} error : {}",type,fromKeyId,toKeyId,graph.right().value()); } return Either.right(graph.right().value()); } return Either.left(newRelation); } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to delete relation {} from {} to {}", type, fromKeyId, toKeyId, e); + if (log.isDebugEnabled()) { + log.debug("Failed to delete relation {} from {} to {}", type, fromKeyId, toKeyId, e); } return Either.right(TitanGraphClient.handleTitanException(e)); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed to delete relation {} from {} to {} error : {}", type, fromKeyId, toKeyId, edgeS.right().value()); + if (log.isDebugEnabled()) { + log.debug("Failed to delete relation {} from {} to {} error : {}", type, fromKeyId, toKeyId, edgeS.right().value()); } return Either.right(edgeS.right().value()); } @@ -1114,7 +1103,7 @@ public class TitanGenericDao { public Either deleteIncomingRelation(GraphRelation relation) { RelationEndPoint to = relation.getTo(); - ImmutablePair toKeyId = new ImmutablePair(to.getIdName(), to.getIdValue()); + ImmutablePair toKeyId = new ImmutablePair<>(to.getIdName(), to.getIdValue()); return deleteIncomingEdge(relation.getType(), toKeyId); @@ -1142,11 +1131,11 @@ public class TitanGenericDao { return Either.right(TitanOperationStatus.NOT_FOUND); } - logger.debug("Find the tail vertex of the edge of type {} to vertex {}", type, toKeyId); + log.debug("Find the tail vertex of the edge of type {} to vertex {}", type, toKeyId); Vertex vertexOut = edge.outVertex(); String fromLabel = vertexOut.value(GraphPropertiesDictionary.LABEL.getProperty()); String toLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); - logger.debug("The label of the outgoing vertex is {}", fromLabel); + log.debug("The label of the outgoing vertex is {}", fromLabel); GraphNode nodeOut = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(vertexOut), GraphNode.class); GraphNode nodeIn = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class); @@ -1174,7 +1163,7 @@ public class TitanGenericDao { public Either deleteOutgoingRelation(GraphRelation relation) { RelationEndPoint from = relation.getFrom(); - ImmutablePair fromKeyId = new ImmutablePair(from.getIdName(), from.getIdValue()); + ImmutablePair fromKeyId = new ImmutablePair<>(from.getIdName(), from.getIdValue()); return deleteOutgoingEdge(relation.getType(), fromKeyId); @@ -1202,11 +1191,11 @@ public class TitanGenericDao { return Either.right(TitanOperationStatus.NOT_FOUND); } - logger.debug("Find the tail vertex of the edge of type {} to vertex ", type, toKeyId); + log.debug("Find the tail vertex of the edge of type {} to vertex ", type, toKeyId); Vertex vertexIn = edge.inVertex(); String toLabel = vertexIn.value(GraphPropertiesDictionary.LABEL.getProperty()); String fromLabel = rootVertex.value(GraphPropertiesDictionary.LABEL.getProperty()); - logger.debug("The label of the tail vertex is {}", toLabel); + log.debug("The label of the tail vertex is {}", toLabel); GraphNode nodeFrom = GraphElementFactory.createElement(fromLabel, GraphElementTypeEnum.Node, getProperties(rootVertex), GraphNode.class); GraphNode nodeTo = GraphElementFactory.createElement(toLabel, GraphElementTypeEnum.Node, getProperties(vertexIn), GraphNode.class); @@ -1257,7 +1246,7 @@ public class TitanGenericDao { Either lockNodeNew = createNode(lockNode, GraphNodeLock.class); if (lockNodeNew.isLeft()) { - logger.debug("before commit, Lock node created for {}", lockId); + log.debug("before commit, Lock node created for {}", lockId); return titanClient.commit(); } else { Either graph = titanClient.getGraph(); @@ -1281,19 +1270,19 @@ public class TitanGenericDao { Long time = vertex.left().value().value(GraphPropertiesDictionary.CREATION_DATE.getProperty()); Long lockTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanLockTimeout(); if (time + lockTimeout * 1000 < System.currentTimeMillis()) { - logger.debug("Found not released lock node with id {}", lockNode.getUniqueId()); + log.debug("Found not released lock node with id {}", lockNode.getUniqueId()); vertex.left().value().remove(); lockNodeNew = createNode(lockNode, GraphNodeLock.class); if (lockNodeNew.isLeft()) { - logger.debug("Lock node created for {}", lockNode.getUniqueIdKey()); + log.debug("Lock node created for {}", lockNode.getUniqueIdKey()); return titanClient.commit(); } else { - logger.debug("Failed Lock node for {} . Commit transacton for deleted previous vertex .", lockNode.getUniqueIdKey()); + log.debug("Failed Lock node for {} . Commit transacton for deleted previous vertex .", lockNode.getUniqueIdKey()); titanClient.commit(); status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew); } } else { - logger.debug("Failed Lock node for {} rollback transacton", lockNode.getUniqueIdKey()); + log.debug("Failed Lock node for {} rollback transacton", lockNode.getUniqueIdKey()); titanClient.rollback(); status = checkLockError(lockNode.getUniqueIdKey(), lockNodeNew); } @@ -1302,18 +1291,18 @@ public class TitanGenericDao { public Either>, TitanOperationStatus> getChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz, boolean withEdges) { - List> immutablePairs = new ArrayList>(); + List> immutablePairs = new ArrayList<>(); Either graphRes = titanClient.getGraph(); if (graphRes.isRight()) { - logger.error("Failed to retrieve graph. status is {}", graphRes); + log.error("Failed to retrieve graph. status is {}", graphRes); return Either.right(graphRes.right().value()); } TitanGraph titanGraph = graphRes.left().value(); @SuppressWarnings("unchecked") Iterable vertices = titanGraph.query().has(key, uniqueId).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { + if (vertices == null || !vertices.iterator().hasNext()) { return Either.right(TitanOperationStatus.INVALID_ID); } @@ -1335,12 +1324,12 @@ public class TitanGenericDao { Map properties = getProperties(outgoingVertex); T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - ImmutablePair immutablePair = new ImmutablePair(clazz.cast(data), graphEdge); + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); immutablePairs.add(immutablePair); } } - if (true == immutablePairs.isEmpty()) { + if (immutablePairs.isEmpty()) { return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -1350,18 +1339,18 @@ public class TitanGenericDao { public Either>, TitanOperationStatus> getChildrenVertecies(String key, String uniqueId, GraphEdgeLabels edgeType) { - List> immutablePairs = new ArrayList>(); + List> immutablePairs = new ArrayList<>(); Either graphRes = titanClient.getGraph(); if (graphRes.isRight()) { - logger.error("Failed to retrieve graph. status is {}", graphRes); + log.error("Failed to retrieve graph. status is {}", graphRes); return Either.right(graphRes.right().value()); } TitanGraph titanGraph = graphRes.left().value(); @SuppressWarnings("unchecked") Iterable vertices = titanGraph.query().has(key, uniqueId).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { + if (vertices == null || !vertices.iterator().hasNext()) { return Either.right(TitanOperationStatus.INVALID_ID); } @@ -1373,11 +1362,11 @@ public class TitanGenericDao { Edge edge = edgesCreatorIterator.next(); TitanVertex vertex = (TitanVertex) edge.inVertex(); - ImmutablePair immutablePair = new ImmutablePair(vertex, edge); + ImmutablePair immutablePair = new ImmutablePair<>(vertex, edge); immutablePairs.add(immutablePair); } } - if (true == immutablePairs.isEmpty()) { + if (immutablePairs.isEmpty()) { return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -1392,7 +1381,7 @@ public class TitanGenericDao { private TitanOperationStatus checkLockError(String lockId, Either lockNodeNew) { TitanOperationStatus status; TitanOperationStatus error = lockNodeNew.right().value(); - logger.debug("Failed to Lock node for {} error = {}", lockId, error); + log.debug("Failed to Lock node for {} error = {}", lockId, error); if (error.equals(TitanOperationStatus.TITAN_SCHEMA_VIOLATION) || error.equals(TitanOperationStatus.ILLEGAL_ARGUMENT)) { status = TitanOperationStatus.ALREADY_LOCKED; } else { @@ -1417,12 +1406,12 @@ public class TitanGenericDao { Either lockNodeNew = deleteNode(lockNode, GraphNodeLock.class); if (lockNodeNew.isLeft()) { - logger.debug("Lock node released for lock id = {}", lockId); + log.debug("Lock node released for lock id = {}", lockId); return titanClient.commit(); } else { titanClient.rollback(); TitanOperationStatus error = lockNodeNew.right().value(); - logger.debug("Failed to Release node for lock id {} error = {}", lockId, error); + log.debug("Failed to Release node for lock id {} error = {}", lockId, error); return error; } } @@ -1464,28 +1453,28 @@ public class TitanGenericDao { if (edges.hasNext()) { // get only first edge Edge edge = edges.next(); - pair = new ImmutablePair((TitanVertex) edge.inVertex(), edge); + pair = new ImmutablePair<>((TitanVertex) edge.inVertex(), edge); } return pair; } public Either>, TitanOperationStatus> getParentNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - List> immutablePairs = new ArrayList>(); + List> immutablePairs = new ArrayList<>(); T data = null; GraphEdge graphEdge = null; Either graphRes = titanClient.getGraph(); if (graphRes.isRight()) { - logger.error("Failed to retrieve graph. status is {}", graphRes); + log.error("Failed to retrieve graph. status is {}", graphRes); return Either.right(graphRes.right().value()); } TitanGraph titanGraph = graphRes.left().value(); @SuppressWarnings("unchecked") Iterable vertices = titanGraph.query().has(key, uniqueId).vertices(); - if (vertices == null || false == vertices.iterator().hasNext()) { + if (vertices == null || !vertices.iterator().hasNext()) { return Either.right(TitanOperationStatus.INVALID_ID); } @@ -1503,12 +1492,12 @@ public class TitanGenericDao { Map properties = getProperties(outgoingVertex); data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - ImmutablePair immutablePair = new ImmutablePair(clazz.cast(data), graphEdge); + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); immutablePairs.add(immutablePair); } } - if (true == immutablePairs.isEmpty()) { + if (immutablePairs.isEmpty()) { return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -1521,7 +1510,7 @@ public class TitanGenericDao { Either>, TitanOperationStatus> parentNodesRes = this.getParentNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); if (parentNodesRes.isRight()) { - logger.debug("failed to get edge key:{} uniqueId:{} edgeType {} nodeTypeEnum: {}, reason:{}", key, uniqueId, edgeType, nodeTypeEnum, parentNodesRes.right().value()); + log.debug("failed to get edge key:{} uniqueId:{} edgeType {} nodeTypeEnum: {}, reason:{}", key, uniqueId, edgeType, nodeTypeEnum, parentNodesRes.right().value()); return Either.right(parentNodesRes.right().value()); } @@ -1539,7 +1528,7 @@ public class TitanGenericDao { Either outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(key, uniqueId, edgeType, edgeProperties); if (outgoingEdgeByCriteria.isRight()) { TitanOperationStatus status = outgoingEdgeByCriteria.right().value(); - logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}" + uniqueId, edgeType, edgeProperties); + log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}" + uniqueId, edgeType, edgeProperties); return Either.right(status); } @@ -1552,7 +1541,7 @@ public class TitanGenericDao { Map properties = getProperties(outgoingVertex); T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - ImmutablePair immutablePair = new ImmutablePair(clazz.cast(data), graphEdge); + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); return Either.left(immutablePair); } @@ -1562,14 +1551,14 @@ public class TitanGenericDao { Either outgoingEdgeByCriteria = getOutgoingEdgeByCriteria(vertex, edgeType, edgeProperties); if (outgoingEdgeByCriteria.isRight()) { TitanOperationStatus status = outgoingEdgeByCriteria.right().value(); - logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertex, edgeType, edgeProperties); + log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertex, edgeType, edgeProperties); return Either.right(status); } Edge edge = outgoingEdgeByCriteria.left().value(); TitanVertex outgoingVertex = (TitanVertex) edge.inVertex(); - ImmutablePair immutablePair = new ImmutablePair(outgoingVertex, edge); + ImmutablePair immutablePair = new ImmutablePair<>(outgoingVertex, edge); return Either.left(immutablePair); } @@ -1601,17 +1590,16 @@ public class TitanGenericDao { Edge matchingEdge = null; Iterable edges = query.edges(); if (edges == null) { - logger.debug("No edges in graph for criteria"); + log.debug("No edges in graph for criteria"); return Either.right(TitanOperationStatus.NOT_FOUND); } Iterator eIter = edges.iterator(); if (eIter.hasNext()) { - Edge edge = eIter.next(); - matchingEdge = edge; + matchingEdge = eIter.next(); } if (matchingEdge == null) { - logger.debug("No edges in graph for criteria"); + log.debug("No edges in graph for criteria"); return Either.right(TitanOperationStatus.NOT_FOUND); } return Either.left(matchingEdge); @@ -1619,7 +1607,7 @@ public class TitanGenericDao { public Either>, TitanOperationStatus> deleteChildrenNodes(String key, String uniqueId, GraphEdgeLabels edgeType, NodeTypeEnum nodeTypeEnum, Class clazz) { - List> result = new ArrayList>(); + List> result = new ArrayList<>(); Either>, TitanOperationStatus> childrenNodesRes = getChildrenNodes(key, uniqueId, edgeType, nodeTypeEnum, clazz); @@ -1634,10 +1622,10 @@ public class TitanGenericDao { Either deleteNodeRes = this.deleteNode(node, clazz); if (deleteNodeRes.isRight()) { TitanOperationStatus status = deleteNodeRes.right().value(); - logger.error("Failed to delete node {} . status is {}", node, status); + log.error("Failed to delete node {} . status is {}", node, status); return Either.right(status); } - ImmutablePair deletedPair = new ImmutablePair(node, pair.getValue()); + ImmutablePair deletedPair = new ImmutablePair<>(node, pair.getValue()); result.add(deletedPair); } @@ -1647,7 +1635,7 @@ public class TitanGenericDao { public void setProperties(Element element, Map properties) { - if (properties != null && false == properties.isEmpty()) { + if (properties != null && !properties.isEmpty()) { Object[] propertyKeyValues = new Object[properties.size() * 2]; int i = 0; @@ -1664,7 +1652,7 @@ public class TitanGenericDao { public Map getProperties(Element element) { - Map result = new HashMap(); + Map result = new HashMap<>(); if (element != null && element.keys() != null && element.keys().size() > 0) { Map propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); @@ -1681,8 +1669,7 @@ public class TitanGenericDao { public Object getProperty(TitanVertex vertex, String key) { PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); - Object value = vertex.valueOrNull(propertyKey); - return value; + return vertex.valueOrNull(propertyKey); } public Object getProperty(Edge edge, String key) { @@ -1702,7 +1689,7 @@ public class TitanGenericDao { Either, TitanOperationStatus> outgoingEdgeByCriteria = getOutgoingEdgesByCriteria(vertex, edgeType, edgeProperties); if (outgoingEdgeByCriteria.isRight()) { TitanOperationStatus status = outgoingEdgeByCriteria.right().value(); - logger.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertexUniqueId, edgeType, edgeProperties); + log.debug("Cannot find outgoing edge from vertex {} with label {} and properties {}", vertexUniqueId, edgeType, edgeProperties); return Either.right(status); } @@ -1717,7 +1704,7 @@ public class TitanGenericDao { Map properties = getProperties(outgoingVertex); T data = GraphElementFactory.createElement(nodeTypeEnum.getName(), GraphElementTypeEnum.Node, properties, clazz); - ImmutablePair immutablePair = new ImmutablePair(clazz.cast(data), graphEdge); + ImmutablePair immutablePair = new ImmutablePair<>(clazz.cast(data), graphEdge); result.add(immutablePair); } } @@ -1742,8 +1729,8 @@ public class TitanGenericDao { Iterable edges = query.edges(); Iterator eIter = edges.iterator(); - if (edges == null || false == eIter.hasNext()) { - logger.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); + if (edges == null || !eIter.hasNext()) { + log.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -1753,7 +1740,7 @@ public class TitanGenericDao { } if (edgesResult.isEmpty()) { - logger.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); + log.debug("No edges found in graph for criteria (label = {} properties={})", label.getProperty(), props); return Either.right(TitanOperationStatus.NOT_FOUND); } return Either.left(edgesResult); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java index 6575e1f395..e13b0ee9c5 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java @@ -20,18 +20,15 @@ package org.openecomp.sdc.be.dao.titan; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - +import com.thinkaurelius.titan.core.*; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import com.thinkaurelius.titan.core.util.TitanCleanup; +import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; +import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; +import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; +import fj.data.Either; import org.apache.commons.configuration.BaseConfiguration; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -40,36 +37,20 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.DAOTitanStrategy; import org.openecomp.sdc.be.dao.TitanClientStrategy; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.InvalidElementException; -import com.thinkaurelius.titan.core.InvalidIDException; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.QueryException; -import com.thinkaurelius.titan.core.SchemaViolationException; -import com.thinkaurelius.titan.core.TitanConfigurationException; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.TitanVertexProperty; -import com.thinkaurelius.titan.core.schema.ConsistencyModifier; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import com.thinkaurelius.titan.core.util.TitanCleanup; -import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; -import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; -import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.*; @Component("titan-client") public class TitanGraphClient { - private static Logger logger = LoggerFactory.getLogger(TitanGraphClient.class.getName()); - private static Logger healthLogger = LoggerFactory.getLogger("titan.healthcheck"); + private static Logger logger = Logger.getLogger(TitanGraphClient.class.getName()); + private static Logger healthLogger = Logger.getLogger("titan.healthcheck"); private static final String HEALTH_CHECK = GraphPropertiesDictionary.HEALTH_CHECK.getProperty(); private static final String OK = "GOOD"; @@ -245,7 +226,8 @@ public class TitanGraphClient { } catch (Exception e) { this.graph = null; - logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e); + logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile); + logger.debug("createGraph : failed with exception.", e); return TitanOperationStatus.NOT_CONNECTED; } @@ -390,7 +372,7 @@ public class TitanGraphClient { private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck"; private void logAlarm() { - if (lastHealthState == true) { + if (lastHealthState) { BeEcompErrorManager.getInstance().logBeHealthCheckTitanRecovery(TITAN_HEALTH_CHECK_STR); } else { BeEcompErrorManager.getInstance().logBeHealthCheckTitanError(TITAN_HEALTH_CHECK_STR); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java index 25a12ed7b6..163ef807fb 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.dao.titan; -import static com.thinkaurelius.titan.core.attribute.Contain.NOT_IN; -import static java.util.Collections.emptyMap; -import static org.apache.commons.collections.CollectionUtils.isEmpty; +import com.thinkaurelius.titan.graphdb.query.TitanPredicate; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import static com.thinkaurelius.titan.core.attribute.Contain.NOT_IN; +import static java.util.Collections.emptyMap; +import static org.apache.commons.collections.CollectionUtils.isEmpty; public class TitanUtils { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java new file mode 100644 index 0000000000..2e5b7ea84c --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/transactions/SimpleTitanTransactionManager.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.dao.titan.transactions; + +import com.thinkaurelius.titan.core.TitanException; +import com.thinkaurelius.titan.core.TitanGraph; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.SimpleTransactionStatus; + +import javax.annotation.PostConstruct; + +/** + * Simple transaction manager for the titan database. + * This manager does not deal with transactions propagation and relies on the fact that transactions are automatically created with the first operation on the graph + */ +@Component +public class SimpleTitanTransactionManager implements PlatformTransactionManager { + + private static final Logger log = Logger.getLogger(SimpleTitanTransactionManager.class.getName()); + private final TitanGraphClient titanClient; + private TitanGraph titanGraph; + + public SimpleTitanTransactionManager(TitanGraphClient titanClient) { + this.titanClient = titanClient; + } + + @PostConstruct + public void onInit() { + titanGraph = titanClient.getGraph().left().on(this::onFailingToStartTitan); + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition transactionDefinition) { + log.debug("#getTransaction - returning simple transaction status"); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus transactionStatus) { + log.debug("#commit - committing transaction"); + try { + titanGraph.tx().commit(); + } catch (TitanException e) { + log.debug("#commit - failed to commit transaction", e); + throw new TransactionSystemException("failed to commit transaction", e); + } + } + + @Override + public void rollback(TransactionStatus transactionStatus) { + log.debug("#rollback - committing transaction"); + try { + titanGraph.tx().rollback(); + } catch (TitanException e) { + log.debug("#rollback - failed to rollback transaction", e); + throw new TransactionSystemException("failed to rollback transaction", e); + } + } + + private TitanGraph onFailingToStartTitan(TitanOperationStatus err) { + log.debug("#onFailingToStartTitan - could not open titan client"); + throw new IllegalStateException("titan could not be initialized: " + err); + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java index 7177e4c9fa..7336859fd7 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/CollectionUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,106 +20,110 @@ package org.openecomp.sdc.be.dao.utils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; public final class CollectionUtils { - private CollectionUtils() { - } + private CollectionUtils() { + } - /** - * Add the content of the 'source' Set to the 'target' set and return the - * union set. - * - * If 'source' is null then a new set is created and returned. If 'target' - * is null then no content is added to the 'source' Set or newly created - * set. - * - * @param source - * The Set to merge in the target Set. - * @param target - * The Set in which the source set will be merged (through - * addAll). - * @return The target Set with addition of source Set elements, or a new Set - * (including content of source set) if target was null. - */ - public static Set merge(Set source, Set target) { - Set merged = new HashSet(); - if (target != null) { - merged.addAll(target); - } - if (source != null) { - merged.addAll(source); - } - return merged.isEmpty() ? null : merged; - } + /** + * Add the content of the 'source' Set to the 'target' set and return the + * union set. + *

+ * If 'source' is null then a new set is created and returned. If 'target' + * is null then no content is added to the 'source' Set or newly created + * set. + * + * @param source The Set to merge in the target Set. + * @param target The Set in which the source set will be merged (through + * addAll). + * @return The target Set with addition of source Set elements, or a new Set + * (including content of source set) if target was null. + */ + public static Set merge(Set source, Set target) { + Set merged = new HashSet<>(); + if (target != null) { + merged.addAll(target); + } + if (source != null) { + merged.addAll(source); + } + return merged.isEmpty() ? null : merged; + } - /** - *

- * Add the content of the 'source' Map to the 'target' set and return the - * union Map. - *

- *

- * If 'source' is null then a new Map is created and returned. If 'target' - * is null then no content is added to the 'source' Map or newly created - * Map. - *

- * - * @param source - * The Map to merge in the target Map. - * @param target - * The Map in which the source Map will be merged (through - * addAll). - * @param override - * If an key from the source map already exists in the target - * map, should it override (true) or not (false) the value. - * @return The target Map with addition of source Map elements, or a new Map - * (including content of source set) if target was null. - */ - public static Map merge(Map source, Map target, boolean override) { - if (target == null) { - target = new HashMap(); - } + /** + *

+ * Add the content of the 'source' Map to the 'target' set and return the + * union Map. + *

+ *

+ * If 'source' is null then a new Map is created and returned. If 'target' + * is null then no content is added to the 'source' Map or newly created + * Map. + *

+ * + * @param source The Map to merge in the target Map. + * @param target The Map in which the source Map will be merged (through + * addAll). + * @param override If an key from the source map already exists in the target + * map, should it override (true) or not (false) the value. + * @return The target Map with addition of source Map elements, or a new Map + * (including content of source set) if target was null. + */ + public static Map merge(Map source, Map target, boolean override) { + if (target == null) { + target = new HashMap(); + } - if (source != null) { - for (Entry entry : source.entrySet()) { - if (override || !target.containsKey(entry.getKey())) { - target.put(entry.getKey(), entry.getValue()); - } - } - } - return target.isEmpty() ? null : target; - } + if (source != null) { + for (Entry entry : source.entrySet()) { + if (override || !target.containsKey(entry.getKey())) { + target.put(entry.getKey(), entry.getValue()); + } + } + } + return target.isEmpty() ? null : target; + } - /** - * Merge two lists, the merge is performed based on the contains method so - * elements presents both in source and target are not added twice to the - * list. - * - * @param source - * The source list. - * @param target - * The target list. - * @return A list that represents the merged collections. - */ - public static List merge(List source, List target) { - List merged = target == null ? new ArrayList() : target; + /** + * Merge two lists, the merge is performed based on the contains method so + * elements presents both in source and target are not added twice to the + * list. + * + * @param source The source list. + * @param target The target list. + * @return A list that represents the merged collections. + */ + public static List merge(List source, List target) { + List merged = target == null ? new ArrayList<>() : target; - if (source == null) { - return merged; - } + if (source == null) { + return merged; + } - for (T t : source) { - if (!merged.contains(t)) { - merged.add(t); - } - } + for (T t : source) { + if (!merged.contains(t)) { + merged.add(t); + } + } - return merged; - } + return merged; + } + + /** + * Returns a new list containing the second list appended to the + * first list. The {@link List#addAll(Collection)} operation is + * used to append the two given lists into a new list. + * + * @param list1 the first list + * @param list2 the second list + * @return a new list containing the union of those lists + * @throws NullPointerException if either list is null + */ + public static List union(List list1, List list2) { + List result = new ArrayList<>(list1); + result.addAll(list2); + return result; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java deleted file mode 100644 index 4eb691a4b7..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageQuality.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.dao.utils; - -/** - * Available qualities for images in Alien 4 Cloud. - * - * @author luc boutier - */ -public enum ImageQuality { - QUALITY_16(16), QUALITY_32(32), QUALITY_64(64), QUALITY_128(128), QUALITY_512(512), QUALITY_BEST(-1); - - private final int size; - - private ImageQuality(int size) { - this.size = size; - } - - public int getSize() { - return size; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java deleted file mode 100644 index 4db8c72e5a..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/ImageResizeUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.dao.utils; - -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; - -/** - * Utility to resize images. - * - * @author luc boutier - */ -public final class ImageResizeUtil { - private ImageResizeUtil() { - } - - /** - * Resize an image with default quality settings. - * - * @param originalImage - * The image to resize. - * @param width - * The target width. - * @param height - * The target height. - * @param preserveDimensions - * Flag to know if we should preserve original image dimensions. - * @return The resized image. - */ - public static BufferedImage resizeImage(final BufferedImage originalImage, final int width, final int height, - final boolean preserveDimensions) { - return resizeImage(originalImage, width, height, preserveDimensions, false); - } - - /** - *

- * Resize an image with high quality settings. - *

- *
    - *
  • g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - * RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  • - *
  • g.setRenderingHint(RenderingHints.KEY_RENDERING, - * RenderingHints.VALUE_RENDER_QUALITY);
  • - *
  • g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - * RenderingHints.VALUE_ANTIALIAS_ON);
  • - *
- * - * @param originalImage - * The image to resize. - * @param width - * The target width. - * @param height - * The target height. - * @param preserveDimensions - * Flag to know if we should preserve original image dimensions. - * @return The resized image. - */ - public static BufferedImage resizeImageWithHint(BufferedImage originalImage, final int width, final int height, - final boolean preserveDimensions) { - return resizeImage(originalImage, width, height, preserveDimensions, true); - } - - private static BufferedImage resizeImage(BufferedImage originalImage, final int width, final int height, - final boolean preserveDimensions, final boolean enableHighQuality) { - int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); - - int targetWidth = width; - int targetHeight = height; - - if (preserveDimensions) { - int[] targetDimentions = computeDimensions(width, height, originalImage.getWidth(), - originalImage.getHeight()); - targetWidth = targetDimentions[0]; - targetHeight = targetDimentions[1]; - } - - BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, type); - - Graphics2D g = resizedImage.createGraphics(); - if (enableHighQuality) { - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - } - - g.drawImage(originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null); - g.dispose(); - - return resizedImage; - } - - /** - * Compute target width and height based on requested width and height but - * making sure the original dimensions of the image will be preserved. - * - * @param width - * The ideal (and max) target width. - * @param height - * The ideal (and max) target height. - * @param originalWidth - * The original width. - * @param originalHeight - * The original height. - * @return An array of int that contains the ideal width and height to - * preserve dimensions. - */ - public static int[] computeDimensions(final int width, final int height, final int originalWidth, - final int originalHeight) { - int targetWidth = width; - int targetHeight = height; - - float targetDimensions = Float.valueOf(width).floatValue() / Float.valueOf(height).floatValue(); - float sourceDimensions = Float.valueOf(originalWidth).floatValue() / Float.valueOf(originalHeight).floatValue(); - if (targetDimensions > sourceDimensions) { - targetWidth = Float.valueOf(width * sourceDimensions / targetDimensions).intValue(); - } else { - targetHeight = Float.valueOf(height * targetDimensions / sourceDimensions).intValue(); - } - - return new int[] { targetWidth, targetHeight }; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java index 00b6d5e894..92ba61bcc7 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/JsonUtil.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.dao.utils; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; @@ -34,6 +28,12 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * Simple utility for JSon processing. */ @@ -47,33 +47,9 @@ public final class JsonUtil { } private JsonUtil() { + // No instances allowed } - // /** - // * Parse a {@link RestResponse} by using the specified dataType as the - // expected data object's class. - // * - // * @param responseAsString - // * The {@link RestResponse} as a JSon String - // * @param dataType - // * The type of the data object. - // * @return The parsed {@link RestResponse} object matching the given JSon. - // * @throws JsonParseException - // * In case of a JSon parsing issue. - // * @throws JsonMappingException - // * In case of a JSon parsing issue. - // * @throws IOException - // * In case of an IO error. - // */ - // public static RestResponse read(String responseAsString, Class - // dataType) throws IOException { - // ObjectMapper mapper = getOneObjectMapper(); - // JavaType restResponseType = - // mapper.getTypeFactory().constructParametricType(RestResponse.class, - // dataType); - // return mapper.readValue(responseAsString, restResponseType); - // } - /** * Deserialize json text to object * @@ -117,36 +93,6 @@ public final class JsonUtil { return getOneObjectMapper().readValue(objectText, typeRef); } - // /** - // * Parse a {@link RestResponse} without being interested in parameterized - // type - // * - // * @param responseAsString - // * @return - // * @throws JsonParseException - // * @throws JsonMappingException - // * @throws IOException - // */ - // public static RestResponse read(String responseAsString) throws - // IOException { - // return getOneObjectMapper().readValue(responseAsString, - // RestResponse.class); - // } - - // /** - // * Serialize the given object in a JSon String. - // * - // * @param obj - // * The object to serialize. - // * @return The JSon serialization of the given object. - // * @throws JsonProcessingException - // * In case of a failure in serialization. - // */ - // public static String toString(Object obj) throws JsonProcessingException - // { - // return getOneObjectMapper().writeValueAsString(obj); - // } - /** * Deserialize the given json string to a map * diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java deleted file mode 100644 index 13561f60a0..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapEntry.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.dao.utils; - -/** - * A map/set entry as a key/value object to be serialized as is. - * - * @author luc boutier - */ -public class MapEntry { - private T key; - private V value; - - public MapEntry() { - } - - public MapEntry(T key, V value) { - this.key = key; - this.value = value; - } - - public T getKey() { - return key; - } - - public void setKey(T key) { - this.key = key; - } - - public V getValue() { - return value; - } - - public void setValue(V value) { - this.value = value; - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java index e8b2e0c9ad..5b0ad9cc24 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,105 +20,153 @@ package org.openecomp.sdc.be.dao.utils; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; +import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; +import static java.util.stream.Collectors.toList; /** * Utility class to ease map manipulation. */ public final class MapUtil { - private MapUtil() { - } + private MapUtil() { + } - /** - * Try to get a value following a path in the map. For example : - * MapUtil.get(map, "a.b.c") correspond to: map.get(a).get(b).get(c) - * - * @param map - * the map to search for path - * @param path - * keys in the map separated by '.' - */ - public static Object get(Map map, String path) { - String[] tokens = path.split("\\."); - if (tokens.length == 0) { - return null; - } else { - Object value = map; - for (String token : tokens) { - if (!(value instanceof Map)) { - return null; - } else { - @SuppressWarnings("unchecked") - Map nested = (Map) value; - if (nested.containsKey(token)) { - value = nested.get(token); - } else { - return null; - } - } - } - return value; - } - } + /** + * Try to get a value following a path in the map. For example : + * MapUtil.get(map, "a.b.c") correspond to: map.get(a).get(b).get(c) + * + * @param map the map to search for path + * @param path keys in the map separated by '.' + */ + public static Object get(Map map, String path) { + String[] tokens = path.split("\\."); + if (tokens.length == 0) { + return null; + } else { + Object value = map; + for (String token : tokens) { + if (!(value instanceof Map)) { + return null; + } else { + @SuppressWarnings("unchecked") + Map nested = (Map) value; + if (nested.containsKey(token)) { + value = nested.get(token); + } else { + return null; + } + } + } + return value; + } + } - /** - * - * @param valuesToMap the list of values to group - * @param groupingFunction the function to group the list values by - * @return a map of list of values grouped by a key, as specified in the {@code groupingFunction} - */ - public static Map> groupListBy(Collection valuesToMap, Function groupingFunction) { - return valuesToMap.stream().collect(Collectors.groupingBy(groupingFunction)); - } + /** + * @param valuesToMap the list of values to group + * @param groupingFunction the function to group the list values by + * @return a map of list of values grouped by a key, as specified in the {@code groupingFunction} + */ + public static Map> groupListBy(Collection valuesToMap, Function groupingFunction) { + return valuesToMap.stream().collect(Collectors.groupingBy(groupingFunction)); + } - /** - * - * @param valuesToMap list of values to map - * @param mappingFunction a function which specifies how to map each element on the list - * @return a map created by mapping each element from the {@code valuesToMap} as specified in the {@code mappingFunction} - */ - public static Map toMap(Collection valuesToMap, Function mappingFunction) { - return Optional.ofNullable(valuesToMap).orElse(new ArrayList<>()).stream().collect(Collectors.toMap(mappingFunction, Function.identity())); - } + /** + * @param valuesToMap list of values to map + * @param mappingFunction a function which specifies how to map each element on the list + * @return a map created by mapping each element from the {@code valuesToMap} as specified in the {@code mappingFunction} + */ + public static Map toMap(Collection valuesToMap, Function mappingFunction) { + return toMap(valuesToMap, mappingFunction, throwingMerger()); + } + + public static Map toMap(Collection valuesToMap, Function mappingFunction, BinaryOperator mergeFunction) { + return streamOfNullable(valuesToMap).collect(Collectors.toMap(mappingFunction, Function.identity(), mergeFunction)); + } - /** - * - * @param map the map of which it keys to convert - * @param keyMappingFunction a function which converts the key object - * @return a map with converted keys. - */ - public static Map> convertMapKeys(Map> map, Function keyMappingFunction) { - return map.entrySet().stream() - .collect(Collectors.toMap(entry -> keyMappingFunction.apply(entry.getKey()), - Map.Entry::getValue)); - } - /** - * Create a new hash map and fills it from the given keys and values - * (keys[index] -> values[index]. - * - * @param keys - * The array of keys. - * @param values - * The array of values. - * @return A map that contains for each key element in the keys array a - * value from the values array at the same index. - */ - public static Map newHashMap(K[] keys, V[] values) { - Map map = new HashMap(); - if (keys == null || values == null || keys.length != values.length) { - throw new IllegalArgumentException("keys and values must be non-null and have the same size."); - } - for (int i = 0; i < keys.length; i++) { - map.put(keys[i], values[i]); - } - return map; - } + /** + * merge two maps. if a key exists in both maps, takes the value from {@code first} + * + * @param first the first map to merge + * @param second the second map to merge + * @return the merged map + */ + public static Map mergeMaps(Map first, Map second) { + if (first == null && second == null) { + return new HashMap<>(); + } + if (first != null && second == null) { + return new HashMap<>(first); + } + if (first == null) { + return new HashMap<>(second); + } + Map mergedMap = new HashMap<>(first); + second.forEach(mergedMap::putIfAbsent); + return mergedMap; + } + + public static List flattenMapValues(Map> mapToFlatten) { + if (mapToFlatten == null) { + return new ArrayList<>(); + } + return mapToFlatten.values().stream().flatMap(Collection::stream).collect(toList()); + } + + /** + * @param map the map of which it keys to convert + * @param keyMappingFunction a function which converts the key object + * @return a map with converted keys. + */ + public static Map> convertMapKeys(Map> map, Function keyMappingFunction) { + return map.entrySet().stream() + .collect(Collectors.toMap(entry -> keyMappingFunction.apply(entry.getKey()), + Map.Entry::getValue)); + } + + /** + * Create a new hash map and fills it from the given keys and values + * (keys[index] -> values[index]. + * + * @param keys The array of keys. + * @param values The array of values. + * @return A map that contains for each key element in the keys array a + * value from the values array at the same index. + */ + public static Map newHashMap(K[] keys, V[] values) { + Map map = new HashMap<>(); + if (keys == null || values == null || keys.length != values.length) { + throw new IllegalArgumentException("keys and values must be non-null and have the same size."); + } + for (int i = 0; i < keys.length; i++) { + map.put(keys[i], values[i]); + } + return map; + } + + + /** + * Returns a merge function, suitable for use in + * {@link Map#merge(Object, Object, BiFunction) Map.merge()} or + * {@link #toMap(Function, Function, BinaryOperator) toMap()}, which always + * throws {@code IllegalStateException}. This can be used to enforce the + * assumption that the elements being collected are distinct. + * + * @param the type of input arguments to the merge function + * @return a merge function which always throw {@code IllegalStateException} + */ + private static BinaryOperator throwingMerger() { + return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); }; + } + + public static Stream streamOfNullable(Collection collection) { + return collection == null? Stream.empty(): collection.stream(); + } + + public static Stream streamOfNullable(T t) { + return t == null ? Stream.empty() : Stream.of(t); + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java index 1f7e692598..6c860dd269 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/TypeMap.java @@ -24,12 +24,12 @@ import java.util.HashMap; import java.util.Map; public class TypeMap { - private Map, Map> cacheMap = new HashMap, Map>(); + private Map, Map> cacheMap = new HashMap<>(); private Map getMap(Class clazz) { Map map = cacheMap.get(clazz); if (map == null) { - cacheMap.put(clazz, new HashMap()); + cacheMap.put(clazz, new HashMap<>()); } return cacheMap.get(clazz); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java index dbe9b84a5e..f66914eb9e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/UserStatusEnum.java @@ -20,9 +20,8 @@ package org.openecomp.sdc.be.dao.utils; -import org.openecomp.sdc.common.util.MethodActivationStatusEnum; - import fj.data.Either; +import org.openecomp.sdc.common.util.MethodActivationStatusEnum; public enum UserStatusEnum { ACTIVE, INACTIVE; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java index 46599ed2d8..cbac24ad3d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/api/IResourceUploader.java @@ -20,11 +20,10 @@ package org.openecomp.sdc.be.resources.api; +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.resources.data.ESArtifactData; -import fj.data.Either; - /** * DAO to manage image upload and retrieval. * diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java index 95f88ca958..41bdad9e5b 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java @@ -20,16 +20,15 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; public class AdditionalInfoParameterData extends GraphNode { @@ -90,7 +89,7 @@ public class AdditionalInfoParameterData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, additionalInfoParameterDataDefinition.getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AnnotationTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AnnotationTypeData.java new file mode 100644 index 0000000000..5255468b1f --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AnnotationTypeData.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.resources.data; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.datatypes.elements.AnnotationTypeDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +import java.util.HashMap; +import java.util.Map; + +public class AnnotationTypeData extends GraphNode { + + private AnnotationTypeDataDefinition annotationTypeDataDefinition; + + public AnnotationTypeData() { + super(NodeTypeEnum.AnnotationType); + annotationTypeDataDefinition = new AnnotationTypeDataDefinition(); + } + + public AnnotationTypeData(AnnotationTypeDataDefinition annotationTypeDataDefinition) { + super(NodeTypeEnum.AnnotationType); + this.annotationTypeDataDefinition = annotationTypeDataDefinition; + } + + public AnnotationTypeData(Map properties) { + this(); + annotationTypeDataDefinition + .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty())); + annotationTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty())); + annotationTypeDataDefinition + .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty())); + annotationTypeDataDefinition.setHighestVersion( + (boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty())); + annotationTypeDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty())); + annotationTypeDataDefinition + .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty())); + annotationTypeDataDefinition + .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty())); + } + + @Override + public String getUniqueId() { + return annotationTypeDataDefinition.getUniqueId(); + } + + @Override + public Map toGraphMap() { + Map map = new HashMap<>(); + addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, annotationTypeDataDefinition.getUniqueId()); + addIfExists(map, GraphPropertiesDictionary.TYPE, annotationTypeDataDefinition.getType()); + addIfExists(map, GraphPropertiesDictionary.VERSION, annotationTypeDataDefinition.getVersion()); + addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, annotationTypeDataDefinition.isHighestVersion()); + addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, annotationTypeDataDefinition.getDescription()); + addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, annotationTypeDataDefinition.getCreationTime()); + addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, annotationTypeDataDefinition.getModificationTime()); + return map; + } + + public void setInitialCreationProperties(String uniqueId) { + annotationTypeDataDefinition.setUniqueId(uniqueId); + Long creationDate = annotationTypeDataDefinition.getCreationTime(); + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + } + annotationTypeDataDefinition.setCreationTime(creationDate); + annotationTypeDataDefinition.setModificationTime(creationDate); + } + + public void setUpdateProperties(AnnotationTypeDataDefinition originalDefinition) { + annotationTypeDataDefinition.setUniqueId(originalDefinition.getUniqueId()); + annotationTypeDataDefinition.setCreationTime(originalDefinition.getCreationTime()); + annotationTypeDataDefinition.setModificationTime(System.currentTimeMillis()); + } + + public AnnotationTypeDataDefinition getAnnotationTypeDataDefinition() { + return annotationTypeDataDefinition; + } + + @Override + public String toString() { + return "AnnotationTypeData [annotationTypeDataDefinition=" + annotationTypeDataDefinition + "]"; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java index a5eca2e86d..9781f572eb 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java @@ -20,18 +20,17 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ArtifactData extends GraphNode { @@ -110,7 +109,7 @@ public class ArtifactData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, artifactDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.ARTIFACT_TYPE, artifactDataDefinition.getArtifactType()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java index a99529d950..bb23f7434c 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeData.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; @@ -31,7 +28,9 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; public class AttributeData extends GraphNode { PropertyDataDefinition attributeDataDefinition; @@ -98,7 +97,7 @@ public class AttributeData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, attributeDataDefinition.getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java index 7c8ce1dbb6..7826862cba 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AttributeValueData.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + public class AttributeValueData extends GraphNode { private String uniqueId; @@ -95,7 +95,7 @@ public class AttributeValueData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java index 6ccf365ffc..16357f557e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java @@ -20,93 +20,99 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class CapabilityData extends GraphNode { + private CapabilityDataDefinition capabilityDataDefiniton; public CapabilityData() { - super(NodeTypeEnum.Capability); - + this(new CapabilityDataDefinition()); + } + + public CapabilityData(CapabilityDataDefinition capabilityDataDefiniton) { + super(NodeTypeEnum.Capability); + this.capabilityDataDefiniton = capabilityDataDefiniton; } public CapabilityData(Map properties) { this(); - this.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty())); + capabilityDataDefiniton.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty())); + capabilityDataDefiniton.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty())); Type listType = new TypeToken>() { }.getType(); List validSourceTypesfromJson = getGson().fromJson( (String) properties.get(GraphPropertiesDictionary.VALID_SOURCE_TYPES.getProperty()), listType); - this.setValidSourceTypes(validSourceTypesfromJson); + capabilityDataDefiniton.setValidSourceTypes(validSourceTypesfromJson); this.setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty())); this.setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty())); - this.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty())); - this.setMinOccurrences((String) properties.get(GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty())); - this.setMaxOccurrences((String) properties.get(GraphPropertiesDictionary.MAX_OCCURRENCES.getProperty())); + capabilityDataDefiniton.setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty())); + capabilityDataDefiniton.setMinOccurrences((String) properties.get(GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty())); + capabilityDataDefiniton.setMaxOccurrences((String) properties.get(GraphPropertiesDictionary.MAX_OCCURRENCES.getProperty())); } - private String uniqueId; - - private String description; - - /** Identifies the type of the capability. */ - private String type; - - private List validSourceTypes; - private Long creationTime; private Long modificationTime; - private String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; - private String maxOccurrences = CapabilityDataDefinition.MAX_OCCURRENCES; - @Override public String getUniqueId() { - return uniqueId; + return capabilityDataDefiniton.getUniqueId(); + } + + + public CapabilityDataDefinition getCapabilityDataDefinition() { + return capabilityDataDefiniton; } public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; + capabilityDataDefiniton.setUniqueId(uniqueId); } public String getDescription() { - return description; + return capabilityDataDefiniton.getDescription(); } public void setDescription(String description) { - this.description = description; + capabilityDataDefiniton.setDescription(description); } + /** + * Get the type of the capability + * @return + */ public String getType() { - return type; + return capabilityDataDefiniton.getType(); } + /** + * Set the type of the capability + * @return + */ public void setType(String type) { - this.type = type; + capabilityDataDefiniton.setType(type); } public List getValidSourceTypes() { - return validSourceTypes; + return capabilityDataDefiniton.getValidSourceTypes(); } public void setValidSourceTypes(List validSourceTypes) { - this.validSourceTypes = validSourceTypes; + capabilityDataDefiniton.setValidSourceTypes(validSourceTypes); } public Long getCreationTime() { @@ -126,57 +132,51 @@ public class CapabilityData extends GraphNode { } public String getMinOccurrences() { - return minOccurrences; + return capabilityDataDefiniton.getMinOccurrences(); } public void setMinOccurrences(String minOccurrences) { if (minOccurrences != null) { - this.minOccurrences = minOccurrences; + capabilityDataDefiniton.setMinOccurrences(minOccurrences); } } public String getMaxOccurrences() { - return maxOccurrences; + return capabilityDataDefiniton.getMaxOccurrences(); } public void setMaxOccurrences(String maxOccurrences) { if (maxOccurrences != null) { - this.maxOccurrences = maxOccurrences; + capabilityDataDefiniton.setMaxOccurrences(maxOccurrences); } } @Override public Map toGraphMap() { - Map map = new HashMap(); - - addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); - - // String validSourceTypesToJson = getGson().toJson(validSourceTypes); + Map map = new HashMap<>(); - // addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES, - // validSourceTypesToJson); - // addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES, - // validSourceTypes); + addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, capabilityDataDefiniton.getUniqueId()); - addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES, validSourceTypes); + addIfExists(map, GraphPropertiesDictionary.VALID_SOURCE_TYPES, capabilityDataDefiniton.getValidSourceTypes()); + + addIfExists(map, GraphPropertiesDictionary.TYPE, capabilityDataDefiniton.getType()); addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, creationTime); addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, modificationTime); - addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, description); - addIfExists(map, GraphPropertiesDictionary.MIN_OCCURRENCES, minOccurrences); - addIfExists(map, GraphPropertiesDictionary.MAX_OCCURRENCES, maxOccurrences); + addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, capabilityDataDefiniton.getDescription()); + addIfExists(map, GraphPropertiesDictionary.MIN_OCCURRENCES, capabilityDataDefiniton.getMinOccurrences()); + addIfExists(map, GraphPropertiesDictionary.MAX_OCCURRENCES, capabilityDataDefiniton.getMaxOccurrences()); return map; } @Override public String toString() { - return "CapabilityData [uniqueId=" + uniqueId + ", description=" + description + ", type=" + type - + ", validSourceTypes=" + validSourceTypes + ", creationTime=" + creationTime + ", modificationTime=" - + modificationTime + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]"; + return "CapabilityData [capabilityDataDefiniton=" + capabilityDataDefiniton + + ", creationTime=" + creationTime + ", modificationTime=" + modificationTime + "]"; } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java index feadf734d2..e85a670aa0 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java @@ -20,16 +20,15 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class CapabilityInstData extends GraphNode { @@ -101,7 +100,7 @@ public class CapabilityInstData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java index 81e8ce9174..67929953bc 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityTypeData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.CapabilityTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class CapabilityTypeData extends GraphNode { @@ -60,6 +59,9 @@ public class CapabilityTypeData extends GraphNode { capabilityTypeDataDefinition .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty())); + + capabilityTypeDataDefinition + .setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty())); Type listType = new TypeToken>() { }.getType(); @@ -85,13 +87,15 @@ public class CapabilityTypeData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, capabilityTypeDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.TYPE, capabilityTypeDataDefinition.getType()); addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, capabilityTypeDataDefinition.getDescription()); + + addIfExists(map, GraphPropertiesDictionary.VERSION, capabilityTypeDataDefinition.getVersion()); // String validSourceTypesToJson = // getGson().toJson(capabilityTypeDataDefinition.getValidSourceTypes()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java index 5c2a1b60d6..5576f0db9f 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java @@ -20,13 +20,13 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public abstract class CategoryData extends GraphNode { private String name; @@ -54,7 +54,7 @@ public abstract class CategoryData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.NAME, name); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); addIfExists(map, GraphPropertiesDictionary.NORMALIZED_NAME, normalizedName); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java index acd4ff41a5..cb7af866be 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentCacheData.java @@ -20,13 +20,13 @@ package org.openecomp.sdc.be.resources.data; -import java.nio.ByteBuffer; -import java.util.Date; - import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.nio.ByteBuffer; +import java.util.Date; + @Table(keyspace = "sdccomponent", name = "componentcache") public class ComponentCacheData { public final static String RRESOURCE_ID_FIELD = "resourceId"; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java index b55b208048..315bf83e2a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentInstanceData.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class ComponentInstanceData extends GraphNode { ComponentInstanceDataDefinition componentInstDataDefinition; @@ -75,7 +75,7 @@ public class ComponentInstanceData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.TYPE, componentInstDataDefinition.getComponentUid()); addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, componentInstDataDefinition.getCreationTime()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java index 018949e433..32a6c18d0d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class ComponentMetadataData extends GraphNode { @@ -75,12 +74,20 @@ public abstract class ComponentMetadataData extends GraphNode { metadataDataDefinition.setImportedToscaChecksum((String) properties.get(GraphPropertiesDictionary.IMPORTED_TOSCA_CHECKSUM.getProperty())); metadataDataDefinition.setInvariantUUID((String) properties.get(GraphPropertiesDictionary.INVARIANT_UUID.getProperty())); // metadataDataDefinition.setComponentType(ComponentTypeEnum.valueOf((String) properties.get(GraphPropertyEnum.COMPONENT_TYPE.getProperty()))); + metadataDataDefinition.setArchived((Boolean) properties.get(GraphPropertiesDictionary.IS_ARCHIVED.getProperty())); + metadataDataDefinition.setVspArchived((Boolean) properties.get(GraphPropertiesDictionary.IS_VSP_ARCHIVED.getProperty())); + Object archiveTime = properties.get(GraphPropertiesDictionary.ARCHIVE_TIME.getProperty()); + if (archiveTime instanceof Integer){ + metadataDataDefinition.setArchiveTime(new Long((Integer) archiveTime)); + } else if (archiveTime instanceof Long) { + metadataDataDefinition.setArchiveTime((Long)archiveTime); + } componentInstanceCounter = (Integer) properties.get(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty()); } @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, metadataDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.VERSION, metadataDataDefinition.getVersion()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java index 32402e2230..97a3ade391 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class ConsumerData extends GraphNode { private ConsumerDataDefinition consumerDataDefinition; @@ -77,7 +77,7 @@ public class ConsumerData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.CONSUMER_NAME, this.consumerDataDefinition.getConsumerName()); addIfExists(map, GraphPropertiesDictionary.CONSUMER_PASSWORD, this.consumerDataDefinition.getConsumerPassword()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java index 2f745243c6..897c24ff5b 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/DataTypeData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class DataTypeData extends GraphNode { DataTypeDataDefinition dataTypeDataDefinition; @@ -68,7 +68,7 @@ public class DataTypeData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, dataTypeDataDefinition.getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java index 0ae1fd5bcd..fca13d5f74 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ESArtifactData.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.be.resources.data; -import java.nio.ByteBuffer; - import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.nio.ByteBuffer; + @Table(keyspace = "sdcartifact", name = "resources") public class ESArtifactData { public static final String RRESOURCE_ID_FIELD = "resourceId"; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java index d41248702f..a7981edcde 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java @@ -20,13 +20,13 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class GraphNodeLock extends GraphNode { private String uniqueId; @@ -57,7 +57,7 @@ public class GraphNodeLock extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, time); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java index 9c9276e185..54d55d2645 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class GroupData extends GraphNode { GroupDataDefinition groupDataDefinition; @@ -69,7 +69,7 @@ public class GroupData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.NAME, groupDataDefinition.getName()); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.TYPE, groupDataDefinition.getType()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java index 88f7ad9342..88ff20e730 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupInstanceData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class GroupInstanceData extends GraphNode { @@ -74,7 +74,7 @@ public class GroupInstanceData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.TYPE, groupDataDefinition.getGroupUid()); addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, groupDataDefinition.getCreationTime()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java index 3a92819231..860358ce22 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupTypeData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class GroupTypeData extends GraphNode { @@ -39,9 +38,9 @@ public class GroupTypeData extends GraphNode { private static Type mapType = new TypeToken>() { }.getType(); - GroupTypeDataDefinition groupTypeDataDefinition; + private GroupTypeDataDefinition groupTypeDataDefinition; - public GroupTypeData() { + private GroupTypeData() { super(NodeTypeEnum.GroupType); groupTypeDataDefinition = new GroupTypeDataDefinition(); } @@ -54,7 +53,8 @@ public class GroupTypeData extends GraphNode { public GroupTypeData(Map properties) { this(); - + groupTypeDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty())); + groupTypeDataDefinition.setIcon((String) properties.get(GraphPropertiesDictionary.ICON.getProperty())); groupTypeDataDefinition.setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty())); groupTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty())); @@ -88,12 +88,16 @@ public class GroupTypeData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupTypeDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.TYPE, groupTypeDataDefinition.getType()); + addIfExists(map, GraphPropertiesDictionary.NAME, groupTypeDataDefinition.getName()); + + addIfExists(map, GraphPropertiesDictionary.ICON, groupTypeDataDefinition.getIcon()); + addIfExists(map, GraphPropertiesDictionary.VERSION, groupTypeDataDefinition.getVersion()); addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, groupTypeDataDefinition.isHighestVersion()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java index 50b9fa95dc..fc27393c80 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java @@ -20,16 +20,16 @@ package org.openecomp.sdc.be.resources.data; -import java.math.BigDecimal; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + public class HeatParameterData extends GraphNode { private HeatParameterDataDefinition heatDataDefinition; @@ -140,7 +140,7 @@ public class HeatParameterData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java index 68623238fb..71f8f46050 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class HeatParameterValueData extends GraphNode { public HeatParameterValueData() { @@ -70,7 +70,7 @@ public class HeatParameterValueData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java index 284729129f..3888c78d59 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + public class InputValueData extends GraphNode { private String uniqueId; @@ -96,7 +96,7 @@ public class InputValueData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java index d48b794a62..77e0c02fc4 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; @@ -32,7 +28,10 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class InputsData extends GraphNode { @@ -90,7 +89,7 @@ public class InputsData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, propertyDataDefinition.getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java index 4ad07d70eb..c5ba3cba14 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InterfaceData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class InterfaceData extends GraphNode { private InterfaceDataDefinition interfaceDataDefinition; @@ -77,7 +77,7 @@ public class InterfaceData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, interfaceDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.TYPE, interfaceDataDefinition.getType()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java index be3ace6420..4421d135d3 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Date; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.util.Date; + @Table(keyspace = "sdcrepository", name = "migrationTasks") public class MigrationTaskEntry { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java index df3a1006c9..8246c2f9ff 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class OperationData extends GraphNode { OperationDataDefinition operationDataDefinition; @@ -75,7 +75,7 @@ public class OperationData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, operationDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, operationDataDefinition.getCreationDate()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java index f3ecc7b91e..5b3c282bd7 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java @@ -1,14 +1,13 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; - import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; @Table(keyspace = "sdcrepository", name = "operationalEnvironment") public class OperationalEnvironmentEntry { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java index 8847262e87..c09622d17a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class PolicyTypeData extends GraphNode { @@ -65,7 +64,8 @@ public class PolicyTypeData extends GraphNode { .fromJson((String) properties.get(GraphPropertiesDictionary.TARGETS.getProperty()), listType); policyTypeDataDefinition.setTargets(members); policyTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty())); - + policyTypeDataDefinition.setName((String) properties.get(GraphPropertiesDictionary.NAME.getProperty())); + policyTypeDataDefinition.setIcon((String) properties.get(GraphPropertiesDictionary.ICON.getProperty())); policyTypeDataDefinition .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty())); @@ -87,12 +87,16 @@ public class PolicyTypeData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, policyTypeDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.TYPE, policyTypeDataDefinition.getType()); + addIfExists(map, GraphPropertiesDictionary.NAME, policyTypeDataDefinition.getName()); + + addIfExists(map, GraphPropertiesDictionary.ICON, policyTypeDataDefinition.getIcon()); + addIfExists(map, GraphPropertiesDictionary.VERSION, policyTypeDataDefinition.getVersion()); addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, policyTypeDataDefinition.isHighestVersion()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java index 9bf3ce2a03..77f2d90632 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ProductMetadataData.java @@ -20,15 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; public class ProductMetadataData extends ComponentMetadataData { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java index abaf061165..1047d2bb40 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; @@ -32,7 +28,10 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class PropertyData extends GraphNode { @@ -90,7 +89,7 @@ public class PropertyData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, propertyDataDefinition.getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java index fcc75e79e2..1ec949dace 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java @@ -20,18 +20,17 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.Constants; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class PropertyValueData extends GraphNode { @@ -129,7 +128,7 @@ public class PropertyValueData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java index 7fc9a601c9..0deba18c02 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipInstData.java @@ -20,13 +20,13 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class RelationshipInstData extends GraphNode { private String type; @@ -69,7 +69,7 @@ public class RelationshipInstData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java index 2e434955e6..32a86e42ce 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RelationshipTypeData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class RelationshipTypeData extends GraphNode { @@ -82,7 +81,7 @@ public class RelationshipTypeData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, relationshipTypeDataDefinition.getUniqueId()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java index 69fa9279c4..de1b9c62aa 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class RequirementData extends GraphNode { private String uniqueId; @@ -68,7 +68,7 @@ public class RequirementData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java index 1224f873d2..36d6d8d718 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/RequirementImplData.java @@ -20,13 +20,13 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class RequirementImplData extends GraphNode { private String name; @@ -66,7 +66,7 @@ public class RequirementImplData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java index 012780c5a7..95d8b0b6be 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceCategoryData.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Map; - import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.Map; + public class ResourceCategoryData extends CategoryData { private String categoryName; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java index efb89db0da..bc7f34c125 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ResourceMetadataData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Map; - import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import java.util.Map; + public class ResourceMetadataData extends ComponentMetadataData { public ResourceMetadataData() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java index 3454a882d2..2b92aa3b8d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/SdcSchemaFilesData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.nio.ByteBuffer; -import java.util.Date; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.nio.ByteBuffer; +import java.util.Date; + @Table(keyspace = "sdcartifact", name = "sdcschemafiles") public class SdcSchemaFilesData { @PartitionKey(0) diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java index 666e2e51b6..3228cbfc23 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceCategoryData.java @@ -20,10 +20,10 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Map; - import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.Map; + public class ServiceCategoryData extends CategoryData { public ServiceCategoryData() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java index 12f011d72f..a50d7ff6c8 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ServiceMetadataData.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Map; - import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.Map; + public class ServiceMetadataData extends ComponentMetadataData { public ServiceMetadataData() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java index 0f798c188c..43b52e2a54 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java @@ -20,13 +20,13 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class TagData extends GraphNode { private String name; @@ -51,7 +51,7 @@ public class TagData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.NAME, name); return map; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java index e194f5815b..fd3b8659a1 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.Map; + public class UniqueIdData extends GraphNode { private String uniqueId; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java index b484f45051..420bb7ee79 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.be.resources.data; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.DaoUtils; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + public class UserData extends GraphNode { private String firstName; @@ -196,7 +196,7 @@ public class UserData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.USERID, userId); addIfExists(map, GraphPropertiesDictionary.EMAIL, email); addIfExists(map, GraphPropertiesDictionary.FIRST_NAME, firstName); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java index 08b4870962..18ff96bbf0 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.utils.DaoUtils; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class UserFunctionalMenuData extends GraphNode { private String uniqueId; @@ -74,7 +74,7 @@ public class UserFunctionalMenuData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, uniqueId); addIfExists(map, GraphPropertiesDictionary.FUNCTIONAL_MENU, functionalMenu); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java deleted file mode 100644 index bae33384e4..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.resources.data.auditing; - -import java.util.Map; - -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - -public final class AuditRecordFactory { - public static AuditingGenericEvent createAuditRecord(Map auditingFields) { - if (auditingFields == null) { - return null; - } - AuditingActionEnum actionEnum = AuditingActionEnum - .getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); - if (actionEnum == null) { - return null; - } - String tableName = actionEnum.getAuditingEsType(); - AuditingGenericEvent event = null; - switch (tableName) { - case AuditingTypesConstants.USER_ADMIN_EVENT_TYPE: - event = new UserAdminEvent(auditingFields); - break; - case AuditingTypesConstants.AUTH_EVENT_TYPE: - event = new AuthEvent(auditingFields); - break; - case AuditingTypesConstants.CATEGORY_EVENT_TYPE: - event = new CategoryEvent(auditingFields); - break; - case AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE: - event = new ResourceAdminEvent(auditingFields); - break; - case AuditingTypesConstants.USER_ACCESS_EVENT_TYPE: - event = new UserAccessEvent(auditingFields); - break; - case AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE: - event = new DistributionStatusEvent(auditingFields); - break; - case AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE: - event = new DistributionDownloadEvent(auditingFields); - break; - case AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE: - event = new DistributionEngineEvent(auditingFields); - break; - case AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE: - event = new DistributionNotificationEvent(auditingFields); - break; - case AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE: - event = new DistributionDeployEvent(auditingFields); - break; - case AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE: - event = new AuditingGetUebClusterEvent(auditingFields); - break; - case AuditingTypesConstants.CONSUMER_EVENT_TYPE: - event = new ConsumerEvent(auditingFields); - break; - case AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE: - event = new GetUsersListEvent(auditingFields); - break; - case AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE: - event = new GetCategoryHierarchyEvent(auditingFields); - break; - case AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE: - event = new ExternalApiEvent(auditingFields); - break; - case AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE: - event = new EcompOperationalEnvironmentEvent(auditingFields); - break; - } - - return event; - } - -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java index 0c1352f4ec..da5eab8747 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java @@ -20,120 +20,127 @@ package org.openecomp.sdc.be.resources.data.auditing; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; //TODO rename to AuditAction public enum AuditingActionEnum { - // User admininstration - ADD_USER("AddUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE), - UPDATE_USER("UpdateUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE), - DELETE_USER("DeleteUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE), - USER_ACCESS("Access", AuditingTypesConstants.USER_ACCESS_EVENT_TYPE), - GET_USERS_LIST("GetUsersList", AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE), - - // Resource/service administration - CREATE_RESOURCE("Create", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - IMPORT_RESOURCE("ResourceImport", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - CHECKOUT_RESOURCE("Checkout", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - UNDO_CHECKOUT_RESOURCE("UndoCheckout", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - CHECKIN_RESOURCE("Checkin", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - CERTIFICATION_REQUEST_RESOURCE("CertificationRequest", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - START_CERTIFICATION_RESOURCE("CertificationStart", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - FAIL_CERTIFICATION_RESOURCE("CertificationFailure", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - CANCEL_CERTIFICATION_RESOURCE("CertificationCancel", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - CERTIFICATION_SUCCESS_RESOURCE("CertificationSuccess", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - UPDATE_RESOURCE_METADATA("UpdateResourceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - UPDATE_SERVICE_METADATA("UpdateServiceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - ARTIFACT_UPLOAD("ArtifactUpload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - //External API - ARTIFACT_UPLOAD_BY_API("ArtifactUploadByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - ARTIFACT_UPDATE_BY_API("ArtifactUpdateByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - ARTIFACT_DELETE_BY_API("ArtifactDeleteByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - DOWNLOAD_ARTIFACT("DownloadArtifact",AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - CREATE_RESOURCE_BY_API("CreateResourceByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - CHANGE_LIFECYCLE_BY_API("ChangeLifecycleByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - ACTIVATE_SERVICE_BY_API("ActivateServiceByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - - - ARTIFACT_PAYLOAD_UPDATE("ArtifactPayloadUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - ARTIFACT_METADATA_UPDATE("ArtifactMetadataUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - ARTIFACT_DELETE("ArtifactDelete", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - ARTIFACT_DOWNLOAD("ArtifactDownload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - - - // Distribution - DISTRIBUTION_ARTIFACT_DOWNLOAD("DArtifactDownload", AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE), - DISTRIBUTION_STATE_CHANGE_REQUEST("DRequest", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - DISTRIBUTION_STATE_CHANGE_APPROV("DApprove", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - DISTRIBUTION_STATE_CHANGE_REJECT("DReject", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), - CREATE_DISTRIBUTION_TOPIC("CreateDistributionTopic", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), - ADD_KEY_TO_TOPIC_ACL("AddKeyToTopicACL", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), - REMOVE_KEY_FROM_TOPIC_ACL("RemoveKeyFromTopicACL", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), - DISTRIBUTION_REGISTER("DRegister", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), - DISTRIBUTION_UN_REGISTER("DUnRegister", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), - DISTRIBUTION_NOTIFY("DNotify", AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE), - DISTRIBUTION_STATUS("DStatus", AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE), - DISTRIBUTION_DEPLOY("DResult",AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE), - GET_UEB_CLUSTER("GetUebCluster", AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE), - GET_VALID_ARTIFACT_TYPES("GetValidArtifactTypes", AuditingTypesConstants.DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE), - - //Environment + // User admininstration + ADD_USER("AddUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE), + UPDATE_USER("UpdateUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE), + DELETE_USER("DeleteUser", AuditingTypesConstants.USER_ADMIN_EVENT_TYPE), + USER_ACCESS("Access", AuditingTypesConstants.USER_ACCESS_EVENT_TYPE), + GET_USERS_LIST("GetUsersList", AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE), + + // Resource/service administration + CREATE_RESOURCE("Create", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + IMPORT_RESOURCE("ResourceImport", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CHECKOUT_RESOURCE("Checkout", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + UNDO_CHECKOUT_RESOURCE("UndoCheckout", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CHECKIN_RESOURCE("Checkin", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CERTIFICATION_REQUEST_RESOURCE("CertificationRequest", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + START_CERTIFICATION_RESOURCE("CertificationStart", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + FAIL_CERTIFICATION_RESOURCE("CertificationFailure", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CANCEL_CERTIFICATION_RESOURCE("CertificationCancel", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CERTIFICATION_SUCCESS_RESOURCE("CertificationSuccess", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CREATE_SERVICE("CreateService", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + UPDATE_RESOURCE_METADATA("UpdateResourceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + UPDATE_SERVICE_METADATA("UpdateServiceMetadata", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + ARTIFACT_UPLOAD("ArtifactUpload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + //External API + ARTIFACT_UPLOAD_BY_API("ArtifactUploadByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + ARTIFACT_UPDATE_BY_API("ArtifactUpdateByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + ARTIFACT_DELETE_BY_API("ArtifactDeleteByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + DOWNLOAD_ARTIFACT("DownloadArtifact",AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + CREATE_RESOURCE_BY_API("CreateResourceByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + CHANGE_LIFECYCLE_BY_API("ChangeLifecycleByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + ACTIVATE_SERVICE_BY_API("ActivateServiceByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + + ARTIFACT_PAYLOAD_UPDATE("ArtifactPayloadUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + ARTIFACT_METADATA_UPDATE("ArtifactMetadataUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + ARTIFACT_DELETE("ArtifactDelete", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + ARTIFACT_DOWNLOAD("ArtifactDownload", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + + //Automated upgrade + UPDATE_SERVICE_REFERENCE("UpdateServiceReference", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + VF_UPGRADE_SERVICES("VfUpgradeServices", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + + //Archive/Restore Components + ARCHIVE_COMPONENT("ArchiveComponent", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + RESTORE_COMPONENT("RestoreComponent", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + + // Distribution + DISTRIBUTION_ARTIFACT_DOWNLOAD("DArtifactDownload", AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE), + DISTRIBUTION_STATE_CHANGE_REQUEST("DRequest", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + DISTRIBUTION_STATE_CHANGE_APPROV("DApprove", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + DISTRIBUTION_STATE_CHANGE_REJECT("DReject", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE), + CREATE_DISTRIBUTION_TOPIC("CreateDistributionTopic", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), + ADD_KEY_TO_TOPIC_ACL("AddKeyToTopicACL", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), + REMOVE_KEY_FROM_TOPIC_ACL("RemoveKeyFromTopicACL", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), + DISTRIBUTION_REGISTER("DRegister", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), + DISTRIBUTION_UN_REGISTER("DUnRegister", AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE), + DISTRIBUTION_NOTIFY("DNotify", AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE), + DISTRIBUTION_STATUS("DStatus", AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE), + DISTRIBUTION_DEPLOY("DResult",AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE), + GET_UEB_CLUSTER("GetUebCluster", AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE), + GET_VALID_ARTIFACT_TYPES("GetValidArtifactTypes", AuditingTypesConstants.DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE), + + //Environment CREATE_ENVIRONMENT("CreateEnvironment", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE), UPDATE_ENVIRONMENT("UpdateEnvironment", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE), DELETE_ENVIRONMENT("DeleteEnvironment", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE), UNKNOWN_ENVIRONMENT_NOTIFICATION("UnknownEnvironmentNotification", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE), UNSUPPORTED_ENVIRONMENT_TYPE("UnsupportedEnvironmentType", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE), - // .... - AUTH_REQUEST("HttpAuthentication", AuditingTypesConstants.AUTH_EVENT_TYPE), - ADD_ECOMP_USER_CREDENTIALS("AddECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), - GET_ECOMP_USER_CREDENTIALS("GetECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), - DELETE_ECOMP_USER_CREDENTIALS("DeleteECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), - UPDATE_ECOMP_USER_CREDENTIALS("UpdateECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), - // Category - ADD_CATEGORY("AddCategory", AuditingTypesConstants.CATEGORY_EVENT_TYPE), - ADD_SUB_CATEGORY("AddSubCategory", AuditingTypesConstants.CATEGORY_EVENT_TYPE), - ADD_GROUPING("AddGrouping", AuditingTypesConstants.CATEGORY_EVENT_TYPE), - GET_CATEGORY_HIERARCHY("GetCategoryHierarchy", AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE), - - // Assets - - GET_ASSET_LIST("GetAssetList", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - GET_FILTERED_ASSET_LIST("GetFilteredAssetList", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - GET_ASSET_METADATA("GetAssetMetadata", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), - GET_TOSCA_MODEL("GetToscaModel", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE); + + AUTH_REQUEST("HttpAuthentication", AuditingTypesConstants.AUTH_EVENT_TYPE), + ADD_ECOMP_USER_CREDENTIALS("AddECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), + GET_ECOMP_USER_CREDENTIALS("GetECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), + DELETE_ECOMP_USER_CREDENTIALS("DeleteECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), + UPDATE_ECOMP_USER_CREDENTIALS("UpdateECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE), + + // Category + ADD_CATEGORY("AddCategory", AuditingTypesConstants.CATEGORY_EVENT_TYPE), + ADD_SUB_CATEGORY("AddSubCategory", AuditingTypesConstants.CATEGORY_EVENT_TYPE), + ADD_GROUPING("AddGrouping", AuditingTypesConstants.CATEGORY_EVENT_TYPE), + GET_CATEGORY_HIERARCHY("GetCategoryHierarchy", AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE), + + // Assets + GET_ASSET_LIST("GetAssetList", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + GET_FILTERED_ASSET_LIST("GetFilteredAssetList", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + GET_ASSET_METADATA("GetAssetMetadata", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE), + GET_TOSCA_MODEL("GetToscaModel", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE); private final String name; private final String auditingEsType; - private static Logger log = LoggerFactory.getLogger(AuditingActionEnum.class.getName()); - - private AuditingActionEnum(String name, String auditingEsType) { - this.name = name; - this.auditingEsType = auditingEsType; - } - - public String getName() { - return name; - } - - public String getAuditingEsType() { - return auditingEsType; - } - - public static AuditingActionEnum getActionByName(String name) { - AuditingActionEnum res = null; - AuditingActionEnum[] values = values(); - for (AuditingActionEnum value : values) { - if (value.getName().equals(name)) { - res = value; - break; - } - } - if (res == null) { - log.debug("No auditing action is mapped to name {}", name); - } - return res; - } + + private static Logger log = Logger.getLogger(AuditingActionEnum.class.getName()); + + AuditingActionEnum(String name, String auditingEsType) { + this.name = name; + this.auditingEsType = auditingEsType; + } + + public String getName() { + return name; + } + + public String getAuditingEsType() { + return auditingEsType; + } + + public static AuditingActionEnum fromName(String name) { + AuditingActionEnum res = null; + AuditingActionEnum[] values = values(); + for (AuditingActionEnum value : values) { + if (value.getName().equals(name)) { + res = value; + break; + } + } + if (res == null) { + log.debug("No auditing action is mapped to name {}", name); + } + return res; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java index 7789e47766..92e5f4bf2f 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGenericEvent.java @@ -22,63 +22,72 @@ package org.openecomp.sdc.be.resources.data.auditing; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; +import java.util.Date; + public class AuditingGenericEvent extends ESTimeBasedEvent { - protected String requestId; - protected String serviceInstanceId; - protected String action; - protected String status; + protected String requestId; + protected String serviceInstanceId; + protected String action; + protected String status; - protected String desc; + protected String desc; - // protected Map fields = new HashMap(); + public AuditingGenericEvent() { + super(); + } - public AuditingGenericEvent() { - super(); - } + public String getRequestId() { + return requestId; + } - public String getRequestId() { - return requestId; - } + public void setRequestId(String requestId) { + this.requestId = requestId; - public void setRequestId(String requestId) { - this.requestId = requestId; + } - } + public String getServiceInstanceId() { + return serviceInstanceId; + } - public String getServiceInstanceId() { - return serviceInstanceId; - } + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } + public String getAction() { + return action; + } - public String getAction() { - return action; - } + public void setAction(String action) { + this.action = action; + } - public void setAction(String action) { - this.action = action; - } + public String getStatus() { + return status; + } - public String getStatus() { - return status; - } + public void setStatus(String status) { + this.status = status; + } - public void setStatus(String status) { - this.status = status; - } + public String getDesc() { + return desc; + } - public String getDesc() { - return desc; - } + public void setDesc(String desc) { + this.desc = desc; + } - public void setDesc(String desc) { - this.desc = desc; - } + public void fillFields() { - public void fillFields() { + } - } + protected Date parseDateFromString(final String timestamp) { + try { + return simpleDateFormat.parse(timestamp); + } + catch (Exception e) { + return new Date(); + } + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java index d293bd8cfe..f0b1e63989 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java @@ -20,25 +20,21 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE) public class AuditingGetUebClusterEvent extends AuditingGenericEvent { - private static String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TEMPLATE = "action=\"%s\" " - + " consumerId=\"%s\" statusTime=\"%s\" status=\"%s\" status_desc=\"%s\" "; @PartitionKey protected UUID timebaseduuid; @@ -62,70 +58,38 @@ public class AuditingGetUebClusterEvent extends AuditingGenericEvent { @Column(name = "consumer_id") private String consumerId; + //Required to be public as it is used by Cassandra driver on get operation public AuditingGetUebClusterEvent() { - super(); timestamp1 = new Date(); timebaseduuid = UUIDs.timeBased(); } - public AuditingGetUebClusterEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } else { - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC); - if (value != null) { - setDesc((String) value); - } - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID); - if (value != null) { - setConsumerId((String) value); - } - - } - public AuditingGetUebClusterEvent(String action, CommonAuditData commonAuditData, String consumerId) { this(); this.action = action; this.requestId = commonAuditData.getRequestId(); this.serviceInstanceId = commonAuditData.getServiceInstanceId(); this.status = commonAuditData.getStatus(); - //if no desc, keep distr desc this.desc = commonAuditData.getDescription(); this.consumerId = consumerId; } + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java index 26cc463725..b7ca47600a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java @@ -22,31 +22,32 @@ package org.openecomp.sdc.be.resources.data.auditing; public interface AuditingTypesConstants { - String ARTIFACT_KEYSPACE = "sdcartifact"; - String REPO_KEYSPACE = "sdcrepository"; - String AUDIT_KEYSPACE = "sdcaudit"; - String COMPONENT_KEYSPACE = "sdccomponent"; - String TITAN_KEYSPACE = "titan"; + String ARTIFACT_KEYSPACE = "sdcartifact"; + String REPO_KEYSPACE = "sdcrepository"; + String AUDIT_KEYSPACE = "sdcaudit"; + String COMPONENT_KEYSPACE = "sdccomponent"; + String TITAN_KEYSPACE = "titan"; - String USER_ADMIN_EVENT_TYPE = "useradminevent"; - String USER_ACCESS_EVENT_TYPE = "useraccessevent"; - String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent"; - String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent"; + String USER_ADMIN_EVENT_TYPE = "useradminevent"; + String USER_ACCESS_EVENT_TYPE = "useraccessevent"; + String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent"; + String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent"; - String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent"; - String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent"; - String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent"; - String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent"; - String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent"; - String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent"; + String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent"; + String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent"; + String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent"; + String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent"; + String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent"; + //TODO remove if not in use + String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent"; - String ECOMP_OPERATIONAL_ENV_EVENT_TYPE = "ecompopenvironmentevent"; - String AUTH_EVENT_TYPE = "authevent"; - String CONSUMER_EVENT_TYPE = "consumerevent"; - String CATEGORY_EVENT_TYPE = "categoryevent"; - String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent"; - String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent"; - String EXTERNAL_API_EVENT_TYPE = "externalapievent"; - String ENVIRONMENT_ENGINE_EVENT_TYPE = "environmentengineevent"; + String ECOMP_OPERATIONAL_ENV_EVENT_TYPE = "ecompopenvironmentevent"; + String AUTH_EVENT_TYPE = "authevent"; + String CONSUMER_EVENT_TYPE = "consumerevent"; + String CATEGORY_EVENT_TYPE = "categoryevent"; + String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent"; + String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent"; + String EXTERNAL_API_EVENT_TYPE = "externalapievent"; + String ENVIRONMENT_ENGINE_EVENT_TYPE = "environmentengineevent"; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java index a684a009f5..dfa0ed972a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java @@ -20,203 +20,164 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = "sdcaudit", name = AuditingTypesConstants.AUTH_EVENT_TYPE) public class AuthEvent extends AuditingGenericEvent { - private static String AUTH_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "URL=\"%s\" USER=\"%s\" AUTH_STATUS=\"%s\" " + "REALM=\"%s\" status=\"%s\" desc=\"%s\""; + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; - @PartitionKey - protected UUID timebaseduuid; + @Column + private String url; + @Column + private String user; - @ClusteringColumn - protected Date timestamp1; + @Column(name = "auth_status") + private String authStatus; - @Column - private String url; - @Column - private String user; + @Column + private String realm; + @Column + protected String action; + @Column + protected String status; - @Column(name = "auth_status") - private String authStatus; + @Column(name = "description") + protected String desc; - @Column - private String realm; - @Column - protected String action; - @Column - protected String status; - - @Column(name = "description") - protected String desc; - - @Column(name = "request_id") - protected String requestId; - - public AuthEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getAuthStatus() { - return authStatus; - } - - public void setAuthStatus(String authStatus) { - this.authStatus = authStatus; - } - - public String getRealm() { - return realm; - } - - public void setRealm(String realm) { - this.realm = realm; - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp1) { - this.timestamp1 = timestamp1; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public AuthEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_URL); - if (value != null) { - setUrl((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_USER); - if (value != null) { - setUser((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS); - if (value != null) { - setAuthStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM); - if (value != null) { - setRealm((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - - } - - public AuthEvent(String action, CommonAuditData commonAuditData, String user, String authUrl, String realm, String authStatus) { - this(); + @Column(name = "request_id") + protected String requestId; + + public AuthEvent(String action, CommonAuditData commonAuditData, String user, String authUrl, String realm, String authStatus) { + this(); this.action = action; this.requestId = commonAuditData.getRequestId(); - this.desc = commonAuditData.getDescription(); - this.status = commonAuditData.getStatus(); - this.authStatus = authStatus; - this.url = authUrl; - this.realm = realm; - this.user = user; - } - - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL.getDisplayName(), getUrl()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER.getDisplayName(), getUser()); - fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS.getDisplayName(), getAuthStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM.getDisplayName(), getRealm()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } + this.desc = commonAuditData.getDescription(); + this.status = commonAuditData.getStatus(); + this.authStatus = authStatus; + this.url = authUrl; + this.realm = realm; + this.user = user; + } + + //Required to be public as it is used by Cassandra driver on get operation + public AuthEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getAuthStatus() { + return authStatus; + } + + public void setAuthStatus(String authStatus) { + this.authStatus = authStatus; + } + + public String getRealm() { + return realm; + } + + public void setRealm(String realm) { + this.realm = realm; + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp1) { + this.timestamp1 = timestamp1; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_AUTH_URL.getDisplayName(), getUrl()); + + fields.put(AuditingFieldsKey.AUDIT_AUTH_USER.getDisplayName(), getUser()); + fields.put(AuditingFieldsKey.AUDIT_AUTH_STATUS.getDisplayName(), getAuthStatus()); + fields.put(AuditingFieldsKey.AUDIT_AUTH_REALM.getDisplayName(), getRealm()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java index 2e4f6c8fc4..95d31d9216 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java @@ -20,237 +20,194 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.CATEGORY_EVENT_TYPE) public class CategoryEvent extends AuditingGenericEvent { - @PartitionKey - protected UUID timebaseduuid; - - @ClusteringColumn - protected Date timestamp1; - - @Column - String action; - @Column - String status; - @Column(name = "description") - String desc; - - @Column(name = "category_name") - String categoryName; - - @Column(name = "sub_category_name") - String subCategoryName; - - @Column(name = "grouping_name") - String groupingName; - - @Column - String modifier; - - @Column(name = "service_instance_id") - String serviceInstanceId; - - @Column(name = "resource_type") - String resourceType; - - @Column(name = "request_id") - String requestId; - - public CategoryEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public CategoryEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME); - if (value != null) { - setCategoryName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME); - if (value != null) { - setSubCategoryName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME); - if (value != null) { - setGroupingName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE); - if (value != null) { - setResourceType((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - - } - - public CategoryEvent(String action, CommonAuditData commonAuditData, String modifier, String categoryName, String subCategoryName, + + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; + + @Column + String action; + @Column + String status; + @Column(name = "description") + String desc; + + @Column(name = "category_name") + String categoryName; + + @Column(name = "sub_category_name") + String subCategoryName; + + @Column(name = "grouping_name") + String groupingName; + + @Column + String modifier; + + @Column(name = "service_instance_id") + String serviceInstanceId; + + @Column(name = "resource_type") + String resourceType; + + @Column(name = "request_id") + String requestId; + + public CategoryEvent(String action, CommonAuditData commonAuditData, String modifier, String categoryName, String subCategoryName, String groupingName, String resourceType) { - this(); - this.action = action; - this.requestId = commonAuditData.getRequestId(); - this.status = commonAuditData.getStatus(); - this.desc = commonAuditData.getDescription(); - this.serviceInstanceId = commonAuditData.getServiceInstanceId(); - this.resourceType = resourceType; - this.modifier = modifier; - this.categoryName = categoryName; - this.subCategoryName = subCategoryName; - this.groupingName = groupingName; - } - - @Override - public void fillFields() { - - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME.getDisplayName(), getCategoryName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME.getDisplayName(), getSubCategoryName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME.getDisplayName(), getGroupingName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public String getCategoryName() { - return categoryName; - } - - public void setCategoryName(String categoryName) { - this.categoryName = categoryName; - } - - public String getSubCategoryName() { - return subCategoryName; - } - - public void setSubCategoryName(String subCategoryName) { - this.subCategoryName = subCategoryName; - } - - public String getGroupingName() { - return groupingName; - } - - public void setGroupingName(String groupingName) { - this.groupingName = groupingName; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp1) { - this.timestamp1 = timestamp1; - } - - public String getModifier() { - return modifier; - } - - public void setModifier(String modifier) { - this.modifier = modifier; - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getResourceType() { - return resourceType; - } - - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } + this(); + this.action = action; + this.requestId = commonAuditData.getRequestId(); + this.status = commonAuditData.getStatus(); + this.desc = commonAuditData.getDescription(); + this.serviceInstanceId = commonAuditData.getServiceInstanceId(); + this.resourceType = resourceType; + this.modifier = modifier; + this.categoryName = categoryName; + this.subCategoryName = subCategoryName; + this.groupingName = groupingName; + } + + //Required to be public as it is used by Cassandra driver on get operation + public CategoryEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_CATEGORY_NAME.getDisplayName(), getCategoryName()); + fields.put(AuditingFieldsKey.AUDIT_SUB_CATEGORY_NAME.getDisplayName(), getSubCategoryName()); + fields.put(AuditingFieldsKey.AUDIT_GROUPING_NAME.getDisplayName(), getGroupingName()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getCategoryName() { + return categoryName; + } + + public void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + public String getSubCategoryName() { + return subCategoryName; + } + + public void setSubCategoryName(String subCategoryName) { + this.subCategoryName = subCategoryName; + } + + public String getGroupingName() { + return groupingName; + } + + public void setGroupingName(String groupingName) { + this.groupingName = groupingName; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp1) { + this.timestamp1 = timestamp1; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java index 3fceb8bb50..546b71070d 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java @@ -20,25 +20,21 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.CONSUMER_EVENT_TYPE) public class ConsumerEvent extends AuditingGenericEvent { - private static String CONSUMER_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "modifier=\"%s\" ecompUser=\"%s\" status=\"%s\" desc=\"%s\""; @PartitionKey protected UUID timebaseduuid; @@ -62,41 +58,6 @@ public class ConsumerEvent extends AuditingGenericEvent { @Column(name = "ecomp_user") private String ecompUser; - public ConsumerEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public ConsumerEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER); - if (value != null) { - setEcompUser((String) value); - } - } - public ConsumerEvent(String action, CommonAuditData commonAuditData, String ecompUser, String modifier) { this(); this.action = action; @@ -107,18 +68,28 @@ public class ConsumerEvent extends AuditingGenericEvent { this.ecompUser = ecompUser; } + //Required to be public as it is used by Cassandra driver on get operation + public ConsumerEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER.getDisplayName(), getEcompUser()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + fields.put(AuditingFieldsKey.AUDIT_ECOMP_USER.getDisplayName(), getEcompUser()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); } public String getModifier() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java index f3bd870eb0..0423a08fac 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java @@ -20,28 +20,23 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE) public class DistributionDeployEvent extends AuditingGenericEvent { - private static String DISTRIBUTION_DEPLOY_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "resourceName=\"%s\" resourceType=\"%s\" currVersion=\"%s\" " - + "modifierName=\"%s\" modifierUid=\"%s\" did=\"%s\" " + "status=\"%s\" desc=\"%s\""; - @PartitionKey protected UUID timebaseduuid; @@ -76,60 +71,13 @@ public class DistributionDeployEvent extends AuditingGenericEvent { @Column private String did; - public DistributionDeployEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public DistributionDeployEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID); - if (value != null) { - setDid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION); - if (value != null) { - setCurrVersion((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME); - if (value != null) { - setResourceName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE); - if (value != null) { - setResourceType((String) value); - } + public DistributionDeployEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); } - - public DistributionDeployEvent(String action, CommonAuditData commonAuditData, String did, String modifier, - String currVersion, String resourceName, String resourceType) { + public DistributionDeployEvent(String action, CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, String did, String modifier, + String currVersion) { this(); this.action = action; this.requestId = commonAuditData.getRequestId(); @@ -139,27 +87,31 @@ public class DistributionDeployEvent extends AuditingGenericEvent { this.did = did; this.modifier = modifier; this.currVersion = currVersion; - this.resourceName = resourceName; - this.resourceType = resourceType; + this.resourceName = resourceCommonInfo.getResourceName(); + this.resourceType = resourceCommonInfo.getResourceType(); + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); } @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } public String getResourceName() { return resourceName; @@ -258,11 +210,11 @@ public class DistributionDeployEvent extends AuditingGenericEvent { } @Override - public String toString() { - return "DistributionDeployEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" - + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status - + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType=" + resourceType - + ", currVersion=" + currVersion + ", modifier=" + modifier + ", did=" + did + "]"; - } + public String toString() { + return "DistributionDeployEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" + + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status + + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType=" + resourceType + + ", currVersion=" + currVersion + ", modifier=" + modifier + ", did=" + did + "]"; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java index 1a205cbbbe..d3ffd33074 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java @@ -20,28 +20,23 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE) public class DistributionDownloadEvent extends AuditingGenericEvent { - private static String DISTRIBUTION_DOWNLOAD_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "consumerId=\"%s\" resourceUrl=\"%s\" status=\"%s\" desc=\"%s\""; - @PartitionKey protected UUID timebaseduuid; @@ -68,46 +63,12 @@ public class DistributionDownloadEvent extends AuditingGenericEvent { @Column(name = "resource_url") private String resourceUrl; + //Required to be public as it is used by Cassandra driver on get operation public DistributionDownloadEvent() { - super(); - timestamp1 = new Date(); timebaseduuid = UUIDs.timeBased(); } - public DistributionDownloadEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID); - if (value != null) { - setConsumerId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL); - if (value != null) { - setResourceUrl((String) value); - } - } - public DistributionDownloadEvent(String action, CommonAuditData commonAuditData, DistributionData distributionData) { this(); this.action = action; @@ -119,20 +80,24 @@ public class DistributionDownloadEvent extends AuditingGenericEvent { this.resourceUrl = distributionData.getResourceUrl(); } - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceUrl()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceUrl()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } public String getConsumerId() { return consumerId; @@ -202,15 +167,16 @@ public class DistributionDownloadEvent extends AuditingGenericEvent { return desc; } + @Override public void setDesc(String desc) { this.desc = desc; } @Override - public String toString() { - return "DistributionDownloadEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 - + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action - + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceUrl=" + resourceUrl + "]"; - } + public String toString() { + return "DistributionDownloadEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceUrl=" + resourceUrl + "]"; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java index 46bff73eb0..b7513ff468 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java @@ -20,27 +20,23 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE) public class DistributionEngineEvent extends AuditingGenericEvent { - private static String DISTRIBUTION_ENGINE_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "environmentName=\"%s\" topicName=\"%s\" role=\"%s\" apiKey=\"%s\" " + "status=\"%s\" "; - @PartitionKey protected UUID timebaseduuid; @@ -79,68 +75,14 @@ public class DistributionEngineEvent extends AuditingGenericEvent { @Column(name = "api_key") private String apiKey; + //Required to be public as it is used by Cassandra driver on get operation public DistributionEngineEvent() { - super(); timestamp1 = new Date(); timebaseduuid = UUIDs.timeBased(); } - public DistributionEngineEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } else { - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC); - if (value != null) { - setDesc((String) value); - } - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID); - if (value != null) { - setConsumerId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME); - if (value != null) { - setDstatusTopic((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME); - if (value != null) { - setDnotifTopic((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY); - if (value != null) { - setApiKey((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME); - if (value != null) { - setEnvironmentName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE); - if (value != null) { - setRole((String) value); - } - } - - public DistributionEngineEvent(String action, CommonAuditData commonAuditData, String consumerId, String distStatusTopic, String distNotifTopic, - String apiKey, String envName, String role) { + public DistributionEngineEvent(String action, CommonAuditData commonAuditData, String consumerId, DistributionTopicData distributionTopicData, + String apiKey, String envName, String role) { this(); this.action = action; this.requestId = commonAuditData.getRequestId(); @@ -149,33 +91,37 @@ public class DistributionEngineEvent extends AuditingGenericEvent { //if no desc, keep distr desc this.desc = commonAuditData.getDescription(); this.consumerId = consumerId; - this.dstatusTopic = distStatusTopic; - this.dnotifTopic = distNotifTopic; + this.dstatusTopic = distributionTopicData.getStatusTopic(); + this.dnotifTopic = distributionTopicData.getNotificationTopic(); this.apiKey = apiKey; this.environmentName = envName; this.role = role; } + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY.getDisplayName(), getApiKey()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME.getDisplayName(), getEnvironmentName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE.getDisplayName(), getRole()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME.getDisplayName(), getDstatusTopic()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME.getDisplayName(), - getDnotifTopic()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_API_KEY.getDisplayName(), getApiKey()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME.getDisplayName(), getEnvironmentName()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ROLE.getDisplayName(), getRole()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME.getDisplayName(), getDstatusTopic()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME.getDisplayName(), + getDnotifTopic()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } public String getDstatusTopic() { return dstatusTopic; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java index 4b783fbc33..12b8c0c453 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java @@ -20,340 +20,274 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE) public class DistributionNotificationEvent extends AuditingGenericEvent { - private static String DISTRIBUTION_NOTIFICATION_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "resourceName=\"%s\" resourceType=\"%s\" currVersion=\"%s\" " + "modifierName=\"%s\" modifierUid=\"%s\" " - + "currState=\"%s\" distributionId=\"%s\" " + "topicName=\"%s\" status=\"%s\" description=\"%s\""; - - @PartitionKey - protected UUID timebaseduuid; - - @ClusteringColumn - protected Date timestamp1; - - @Column(name = "request_id") - protected String requestId; - - @Column(name = "service_instance_id") - protected String serviceInstanceId; - @Column - protected String action; - @Column - protected String status; - - @Column(name = "description") - protected String desc; - - @Column(name = "resource_name") - private String resourceName; - - @Column(name = "resource_type") - private String resourceType; - - @Column(name = "curr_version") - private String currVersion; - - @Column - private String modifier; - - @Column(name = "curr_state") - private String currState; - - @Column(name = "topic_name") - private String topicName; - - @Column - private String did; - - @Column(name = "env_id") - private String envId; - - @Column(name = "vnf_workload_context") - private String vnfWorkloadContext; - - @Column(name = "tenant") - private String tenant; - - public DistributionNotificationEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public DistributionNotificationEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID); - if (value != null) { - setDid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE); - if (value != null) { - setCurrState((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION); - if (value != null) { - setCurrVersion((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME); - if (value != null) { - setResourceName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE); - if (value != null) { - setResourceType((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME); - if (value != null) { - setTopicName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID); - if (value != null) { - setEnvId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT); - if (value != null) { - setVnfWorkloadContext((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT); - if (value != null) { - setTenant((String) value); - } - - } - - public DistributionNotificationEvent(String action, CommonAuditData commonAuditData, String did, String modifier, String resourceCurrState, - String resourceCurrVersion, String resourceName, String resourceType, String topicName, + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; + + @Column(name = "request_id") + protected String requestId; + + @Column(name = "service_instance_id") + protected String serviceInstanceId; + @Column + protected String action; + @Column + protected String status; + + @Column(name = "description") + protected String desc; + + @Column(name = "resource_name") + private String resourceName; + + @Column(name = "resource_type") + private String resourceType; + + @Column(name = "curr_version") + private String currVersion; + + @Column + private String modifier; + + @Column(name = "curr_state") + private String currState; + + @Column(name = "topic_name") + private String topicName; + + @Column + private String did; + + @Column(name = "env_id") + private String envId; + + @Column(name = "vnf_workload_context") + private String vnfWorkloadContext; + + @Column(name = "tenant") + private String tenant; + + public DistributionNotificationEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public DistributionNotificationEvent(String action, CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, + ResourceVersionInfo resourceVersionInfo, + String did, String modifier, String topicName, OperationalEnvAuditData opEnvFields) { - this(); + this(); + this.action = action; + this.requestId = commonAuditData.getRequestId(); + this.serviceInstanceId = commonAuditData.getServiceInstanceId(); + this.status = commonAuditData.getStatus(); + this.desc = commonAuditData.getDescription(); + this.did = did; + this.modifier = modifier; + this.currState = resourceVersionInfo.getState(); + this.currVersion = resourceVersionInfo.getVersion(); + this.resourceName = resourceCommonInfo.getResourceName(); + this.resourceType = resourceCommonInfo.getResourceType(); + this.topicName = topicName; + this.envId = opEnvFields.getEnvId(); + this.vnfWorkloadContext = opEnvFields.getVnfWorkloadContext(); + this.tenant = opEnvFields.getTenant(); + + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ENVIRONMENT_ID.getDisplayName(), getEnvId()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT.getDisplayName(), getVnfWorkloadContext()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_TENANT.getDisplayName(), getTenant()); + + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_TOPIC_NAME.getDisplayName(), getTopicName()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getCurrVersion() { + return currVersion; + } + + public void setCurrVersion(String currVersion) { + this.currVersion = currVersion; + } + + public String getCurrState() { + return currState; + } + + public void setCurrState(String currState) { + this.currState = currState; + } + + public String getTopicName() { + return topicName; + } + + public void setTopicName(String topicName) { + this.topicName = topicName; + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp1) { + this.timestamp1 = timestamp1; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { this.action = action; - this.requestId = commonAuditData.getRequestId(); - this.serviceInstanceId = commonAuditData.getServiceInstanceId(); - this.status = commonAuditData.getStatus(); - this.desc = commonAuditData.getDescription(); - this.did = did; - this.modifier = modifier; - this.currState = resourceCurrState; - this.currVersion = resourceCurrVersion; - this.resourceName = resourceName; - this.resourceType = resourceType; - this.topicName = topicName; - this.envId = opEnvFields.getEnvId(); - this.vnfWorkloadContext = opEnvFields.getVnfWorkloadContext(); - this.tenant = opEnvFields.getTenant(); - - } - - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID.getDisplayName(), getEnvId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT.getDisplayName(), getVnfWorkloadContext()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT.getDisplayName(), getTenant()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME.getDisplayName(), getTopicName()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceType() { - return resourceType; - } - - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - public String getCurrVersion() { - return currVersion; - } - - public void setCurrVersion(String currVersion) { - this.currVersion = currVersion; - } - - public String getCurrState() { - return currState; - } - - public void setCurrState(String currState) { - this.currState = currState; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp1) { - this.timestamp1 = timestamp1; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public String getModifier() { - return modifier; - } - - public void setModifier(String modifier) { - this.modifier = modifier; - } - - public String getDid() { - return did; - } - - public void setDid(String did) { - this.did = did; - } - - public String getVnfWorkloadContext() { - return vnfWorkloadContext; - } - - public void setVnfWorkloadContext(String vnfWorkloadContext) { - this.vnfWorkloadContext = vnfWorkloadContext; - } - - public String getEnvId() { - return envId; - } - - public void setEnvId(String envId) { - this.envId = envId; - } - - public String getTenant() { - return tenant; - } - - public void setTenant(String tenant) { - this.tenant = tenant; - } - - @Override - public String toString() { - return "DistributionNotificationEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 - + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action - + ", status=" + status + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType=" - + resourceType + ", currVersion=" + currVersion + ", modifier=" + modifier + ", currState=" + currState - + ", topicName=" + topicName + ", did=" + did + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getDid() { + return did; + } + + public void setDid(String did) { + this.did = did; + } + + public String getVnfWorkloadContext() { + return vnfWorkloadContext; + } + + public void setVnfWorkloadContext(String vnfWorkloadContext) { + this.vnfWorkloadContext = vnfWorkloadContext; + } + + public String getEnvId() { + return envId; + } + + public void setEnvId(String envId) { + this.envId = envId; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + @Override + public String toString() { + return "DistributionNotificationEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + + ", status=" + status + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType=" + + resourceType + ", currVersion=" + currVersion + ", modifier=" + modifier + ", currState=" + currState + + ", topicName=" + topicName + ", did=" + did + ", envId=" + envId + ", vnfWorkloadContext=" + vnfWorkloadContext + ", tenant=" + tenant + "]"; - } + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java index dd429c4e21..369fd555ca 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java @@ -20,251 +20,206 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE) public class DistributionStatusEvent extends AuditingGenericEvent { - private static String DISTRIBUTION_STATUS_NOTIFICATION_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "did=\"%s\" consumerId=\"%s\" topicName=\"%s\" resoureURL=\"%s\" statusTime=\"%s\" status=\"%s\" "; - - @PartitionKey - protected UUID timebaseduuid; - - @ClusteringColumn - protected Date timestamp1; - - @Column(name = "request_id") - protected String requestId; - - @Column(name = "service_instance_id") - protected String serviceInstanceId; - - @Column - protected String action; - @Column - protected String status; - - @Column(name = "description") - protected String desc; - - @Column - private String did; - - @Column(name = "consumer_id") - private String consumerId; - - @Column(name = "topic_name") - private String topicName; - - @Column(name = "resoure_url") - private String resoureURL; - - @Column(name = "status_time") - private String statusTime; - - public DistributionStatusEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - - } - - public DistributionStatusEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID); - if (value != null) { - setDid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID); - if (value != null) { - setConsumerId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME); - if (value != null) { - setTopicName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL); - if (value != null) { - setResoureURL((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME); - if (value != null) { - setStatusTime((String) value); - } - } - - public DistributionStatusEvent(String action, CommonAuditData commonAuditData, String did, String consumerId, String topicName, - String resourceURL, String statusTime) { - this(); - this.action = action; - this.requestId = commonAuditData.getRequestId(); - this.serviceInstanceId = commonAuditData.getServiceInstanceId(); - this.status = commonAuditData.getStatus(); - this.desc = commonAuditData.getDescription(); - this.did = did; - this.consumerId = consumerId; - this.topicName = topicName; - this.resoureURL = resourceURL; - this.statusTime = statusTime; - } - - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName(), getStatusTime()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME.getDisplayName(), getTopicName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResoureURL()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - - } - - public String getDid() { - return did; - } - - public void setDid(String did) { - this.did = did; - } - - public String getConsumerId() { - return consumerId; - } - - public void setConsumerId(String consumerId) { - this.consumerId = consumerId; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - public String getResoureURL() { - return resoureURL; - } - - public void setResoureURL(String resoureURL) { - this.resoureURL = resoureURL; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp) { - this.timestamp1 = timestamp; - } - - public String getStatusTime() { - return statusTime; - } - - public void setStatusTime(String statusTime) { - this.statusTime = statusTime; - } - - @Override - public String toString() { - return "DistributionStatusEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" - + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status - + ", desc=" + desc + ", did=" + did + ", consumerId=" + consumerId + ", topicName=" + topicName - + ", resoureURL=" + resoureURL + ", statusTime=" + statusTime + "]"; - } + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; + + @Column(name = "request_id") + protected String requestId; + + @Column(name = "service_instance_id") + protected String serviceInstanceId; + + @Column + protected String action; + @Column + protected String status; + + @Column(name = "description") + protected String desc; + + @Column + private String did; + + @Column(name = "consumer_id") + private String consumerId; + + @Column(name = "topic_name") + private String topicName; + + @Column(name = "resoure_url") + private String resoureURL; + + @Column(name = "status_time") + private String statusTime; + + //Required to be public as it is used by Cassandra driver on get operation + public DistributionStatusEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + + } + + public DistributionStatusEvent(String action, CommonAuditData commonAuditData, DistributionData distributionData, + String did, String topicName, String statusTime) { + this(); + this.action = action; + this.requestId = commonAuditData.getRequestId(); + this.serviceInstanceId = commonAuditData.getServiceInstanceId(); + this.status = commonAuditData.getStatus(); + this.desc = commonAuditData.getDescription(); + this.did = did; + this.consumerId = distributionData.getConsumerId(); + this.topicName = topicName; + this.resoureURL = distributionData.getResourceUrl(); + this.statusTime = statusTime; + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); + + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName(), getStatusTime()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_TOPIC_NAME.getDisplayName(), getTopicName()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResoureURL()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + + } + + public String getDid() { + return did; + } + + public void setDid(String did) { + this.did = did; + } + + public String getConsumerId() { + return consumerId; + } + + public void setConsumerId(String consumerId) { + this.consumerId = consumerId; + } + + public String getTopicName() { + return topicName; + } + + public void setTopicName(String topicName) { + this.topicName = topicName; + } + + public String getResoureURL() { + return resoureURL; + } + + public void setResoureURL(String resoureURL) { + this.resoureURL = resoureURL; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp) { + this.timestamp1 = timestamp; + } + + public String getStatusTime() { + return statusTime; + } + + public void setStatusTime(String statusTime) { + this.statusTime = statusTime; + } + + @Override + public String toString() { + return "DistributionStatusEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" + + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status + + ", desc=" + desc + ", did=" + did + ", consumerId=" + consumerId + ", topicName=" + topicName + + ", resoureURL=" + resoureURL + ", statusTime=" + statusTime + "]"; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java index 854a7aca48..d78f0e0e5b 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java @@ -1,16 +1,16 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; - -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +//import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE) public class EcompOperationalEnvironmentEvent extends AuditingGenericEvent { @@ -37,41 +37,11 @@ public class EcompOperationalEnvironmentEvent extends AuditingGenericEvent { protected String tenantContext; + //Required to be public as it is used by Cassandra driver on get operation public EcompOperationalEnvironmentEvent() { - super(); timestamp1 = new Date(); } - public EcompOperationalEnvironmentEvent(Map auditingFields) { - this(); - Object value; - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID); - if (value != null) { - setOperationalEnvironmentId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME); - if (value != null) { - setOperationalEnvironmentName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE); - if (value != null) { - setOperational_environment_type((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION); - if (value != null) { - setOperationalEnvironmentAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT); - if (value != null) { - setTenantContext((String) value); - } - } - public EcompOperationalEnvironmentEvent(String action, String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType, String operationalEnvironmentAction, String tenantContext) { this(); @@ -143,15 +113,15 @@ public class EcompOperationalEnvironmentEvent extends AuditingGenericEvent { @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID.getDisplayName(), getOperationalEnvironmentId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME.getDisplayName(), getOperationalEnvironmentName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE.getDisplayName(), getOperationalEnvironmentType()); - fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION.getDisplayName(), getOperationalEnvironmentAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT.getDisplayName(), getTenantContext()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_OPERATIONAL_ENVIRONMENT_ID.getDisplayName(), getOperationalEnvironmentId()); + fields.put(AuditingFieldsKey.AUDIT_OPERATIONAL_ENVIRONMENT_NAME.getDisplayName(), getOperationalEnvironmentName()); + fields.put(AuditingFieldsKey.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE.getDisplayName(), getOperationalEnvironmentType()); + fields.put(AuditingFieldsKey.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION.getDisplayName(), getOperationalEnvironmentAction()); + fields.put(AuditingFieldsKey.AUDIT_TENANT_CONTEXT.getDisplayName(), getTenantContext()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); } @Override diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java index 6f4abb1480..d04a7dfa56 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java @@ -20,21 +20,21 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; /** * This class Represents the Audit for External API @@ -98,103 +98,24 @@ public class ExternalApiEvent extends AuditingGenericEvent { @Column(name = "artifact_data") private String artifactData; + //Required to be public as it is used by Cassandra driver on get operation public ExternalApiEvent() { - super(); timestamp1 = new Date(); timebaseduuid = UUIDs.timeBased(); } - public ExternalApiEvent(Map auditingFields) { - this(); - Object value; - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID); - if (value != null) { - setConsumerId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL); - if (value != null) { - setResourceURL((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME); - if (value != null) { - setResourceName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE); - if (value != null) { - setResourceType((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID); - if (value != null) { - setInvariantUuid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION); - if (value != null) { - setPrevVersion((String) value); - } - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION); - if (value != null) { - setCurrVersion((String) value); - } - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE); - if (value != null) { - setPrevState((String) value); - } - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE); - if (value != null) { - setCurrState((String) value); - } - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); - if (value != null) { - setPrevArtifactUuid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); - if (value != null) { - setCurrArtifactUuid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); - if (value != null) { - setArtifactData((String) value); - } - } - - public ExternalApiEvent(String action, CommonAuditData commonAuditData, String resourceType, String resourceName, - String distConsumerId, String distResourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + public ExternalApiEvent(String action, CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, + DistributionData distributionData, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String modifier, String invariantUuid, String artifactData) { this(); this.action = action; this.status = commonAuditData.getStatus(); this.desc = commonAuditData.getDescription(); this.requestId = commonAuditData.getRequestId(); - this.consumerId = distConsumerId; - this.resourceURL = distResourceUrl; - this.resourceName = resourceName; - this.resourceType = resourceType; + this.consumerId = distributionData.getConsumerId(); + this.resourceURL = distributionData.getResourceUrl(); + this.resourceName = resourceCommonInfo.getResourceName(); + this.resourceType = resourceCommonInfo.getResourceType(); this.serviceInstanceId = commonAuditData.getServiceInstanceId(); this.invariantUuid = invariantUuid; this.modifier = modifier; @@ -209,28 +130,28 @@ public class ExternalApiEvent extends AuditingGenericEvent { @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUuid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUuid()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceURL()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUuid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUuid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData()); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceURL()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState()); + + fields.put(AuditingFieldsKey.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUuid()); + fields.put(AuditingFieldsKey.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUuid()); + fields.put(AuditingFieldsKey.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData()); } public UUID getTimebaseduuid() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java index 09f45c6934..8037a090ba 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java @@ -20,20 +20,18 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE) public class GetCategoryHierarchyEvent extends AuditingGenericEvent { @@ -60,41 +58,12 @@ public class GetCategoryHierarchyEvent extends AuditingGenericEvent { @Column private String details; + //Required to be public as it is used by Cassandra driver on get operation public GetCategoryHierarchyEvent() { - super(); timestamp1 = new Date(); timebaseduuid = UUIDs.timeBased(); } - public GetCategoryHierarchyEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS); - if (value != null) { - setDetails((String) value); - } - } - public GetCategoryHierarchyEvent(String action, CommonAuditData commonAuditData, String modifier, String details) { this(); this.action = action; @@ -105,18 +74,22 @@ public class GetCategoryHierarchyEvent extends AuditingGenericEvent { this.details = details; } - @Override + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS.getDisplayName(), getDetails()); + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_DETAILS.getDisplayName(), getDetails()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); } public UUID getTimebaseduuid() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java index ef5abcf9fe..441cbc42f0 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java @@ -20,20 +20,18 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE) public class GetUsersListEvent extends AuditingGenericEvent { @@ -59,46 +57,12 @@ public class GetUsersListEvent extends AuditingGenericEvent { @Column private String details; + //Required to be public as it is used by Cassandra driver on get operation public GetUsersListEvent() { - super(); timestamp1 = new Date(); timebaseduuid = UUIDs.timeBased(); } - public GetUsersListEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS); - if (value != null) { - setDetails((String) value); - } else { - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS); - if (value != null) { - setDetails((String) value); - } - } - } - public GetUsersListEvent(String action, CommonAuditData commonAuditData, String modifier, String userDetails) { this(); this.action = action; @@ -109,19 +73,22 @@ public class GetUsersListEvent extends AuditingGenericEvent { this.details = userDetails; } + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } @Override public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS.getDisplayName(), getDetails()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_USER_DETAILS.getDisplayName(), getDetails()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); } public UUID getTimebaseduuid() { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java index f07cb213a0..82e1fca9ca 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java @@ -20,447 +20,351 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE) public class ResourceAdminEvent extends AuditingGenericEvent { - private static String RESOURCE_ADMIN_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "resourceName=\"%s\" resourceType=\"%s\" prevVersion=\"%s\" currVersion=\"%s\" " - + "modifierName=\"%s\" modifierUid=\"%s\" " + "prevState=\"%s\" currState=\"%s\" " - + "checkinComment=\"%s\" prevArtifactUuid=\"%s\" currArtifactUuid=\"%s\" " + "artifactData=\"%s\" " - + "status=\"%s\" desc=\"%s\""; + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; + + @Column + protected String action; - @PartitionKey - protected UUID timebaseduuid; + @Column(name = "resource_type") + protected String resourceType; - @ClusteringColumn - protected Date timestamp1; - - @Column - protected String action; - - @Column(name = "resource_type") - protected String resourceType; - - @Column(name = "prev_version") - protected String prevVersion; - - @Column(name = "prev_state") - protected String prevState; - - @Column(name = "curr_state") - protected String currState; - - @Column(name = "resource_name") - private String resourceName; - - @Column(name = "curr_version") - private String currVersion; - - @Column(name = "request_id") - protected String requestId; - - @Column(name = "service_instance_id") - protected String serviceInstanceId; - - @Column - protected String status; - - @Column(name = "description") - protected String desc; - - @Column - protected String modifier; - - @Column(name = "prev_artifact_UUID") - protected String prevArtifactUUID; - - @Column(name = "curr_artifact_UUID") - protected String currArtifactUUID; - - @Column(name = "artifact_data") - protected String artifactData; - - @Column - protected String did; - - @Column(name = "dprev_status") - protected String dprevStatus; - - @Column(name = "dcurr_status") - protected String dcurrStatus; - - @Column(name = "tosca_node_type") - protected String toscaNodeType; - - @Column - protected String comment; - - @Column(name = "invariant_UUID") - protected String invariantUUID; - - public ResourceAdminEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public ResourceAdminEvent(String action, CommonAuditData commonAuditData, ResourceAuditData prevParams, ResourceAuditData currParams, String resourceType, - String resourceName, String invariantUuid, String modifier, String artifactData, String comment, String did, String toscaNodeType) { - this(); - this.action = action; - this.requestId = commonAuditData.getRequestId(); - this.desc = commonAuditData.getDescription(); - this.status = commonAuditData.getStatus(); - this.serviceInstanceId = commonAuditData.getServiceInstanceId(); - this.currState = currParams.getState(); - this.currVersion = currParams.getVersion(); - this.currArtifactUUID = currParams.getArtifactUuid(); - this.prevState = prevParams.getState(); - this.prevVersion = prevParams.getVersion(); - this.prevArtifactUUID = prevParams.getArtifactUuid(); - this.resourceName = resourceName; - this.resourceType = resourceType; - this.comment = comment; - this.dcurrStatus = currParams.getDistributionStatus(); - this.dprevStatus = prevParams.getDistributionStatus(); - this.artifactData = artifactData; - this.modifier = modifier; - this.invariantUUID = invariantUuid; - this.did = did; - this.toscaNodeType = toscaNodeType; - } - - public ResourceAdminEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE); - if (value != null) { - setResourceType((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION); - if (value != null) { - setPrevVersion((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE); - if (value != null) { - setPrevState((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME); - if (value != null) { - setResourceName((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION); - if (value != null) { - setCurrVersion((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE); - if (value != null) { - setCurrState((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); - if (value != null) { - setPrevArtifactUUID((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); - if (value != null) { - setCurrArtifactUUID((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); - if (value != null) { - setArtifactData((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); - if (value != null) { - setComment((String) value); - } - - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS); - if (value != null) { - setDcurrStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS); - if (value != null) { - setDprevStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID); - if (value != null) { - setDid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE); - if (value != null) { - setToscaNodeType((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID); - if (value != null) { - setInvariantUUID((String) value); - } - - } - - - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - fields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUUID()); - fields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUUID()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT.getDisplayName(), getComment()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS.getDisplayName(), getDcurrStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS.getDisplayName(), getDprevStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE.getDisplayName(), getToscaNodeType()); - fields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUUID()); - - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceType() { - return resourceType; - } - - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - public String getPrevVersion() { - return prevVersion; - } - - public void setPrevVersion(String prevVersion) { - this.prevVersion = prevVersion; - } - - public String getCurrVersion() { - return currVersion; - } - - public void setCurrVersion(String currVersion) { - this.currVersion = currVersion; - } - - public String getPrevState() { - return prevState; - } - - public void setPrevState(String prevState) { - this.prevState = prevState; - } - - public String getCurrState() { - return currState; - } - - public void setCurrState(String currState) { - this.currState = currState; - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp1) { - this.timestamp1 = timestamp1; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public String getModifier() { - return modifier; - } - - public void setModifier(String modifier) { - this.modifier = modifier; - } - - public String getPrevArtifactUUID() { - return prevArtifactUUID; - } - - public void setPrevArtifactUUID(String prevArtifactUUID) { - this.prevArtifactUUID = prevArtifactUUID; - } - - public String getCurrArtifactUUID() { - return currArtifactUUID; - } - - public void setCurrArtifactUUID(String currArtifactUUID) { - this.currArtifactUUID = currArtifactUUID; - } - - public String getArtifactData() { - return artifactData; - } - - public void setArtifactData(String artifactData) { - this.artifactData = artifactData; - } - - public String getDid() { - return did; - } - - public void setDid(String did) { - this.did = did; - } - - public String getDprevStatus() { - return dprevStatus; - } - - public void setDprevStatus(String dprevStatus) { - this.dprevStatus = dprevStatus; - } - - public String getDcurrStatus() { - return dcurrStatus; - } - - public void setDcurrStatus(String dcurrStatus) { - this.dcurrStatus = dcurrStatus; - } - - public String getToscaNodeType() { - return toscaNodeType; - } - - public void setToscaNodeType(String toscaNodeType) { - this.toscaNodeType = toscaNodeType; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getInvariantUUID() { - return invariantUUID; - } - - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - @Override - public String toString() { - return "ResourceAdminEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action=" - + action + ", resourceType=" + resourceType + ", prevVersion=" + prevVersion + ", prevState=" - + prevState + ", currState=" + currState + ", resourceName=" + resourceName + ", currVersion=" - + currVersion + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", status=" - + status + ", desc=" + desc + ", modifier=" + modifier + ", prevArtifactUUID=" + prevArtifactUUID - + ", currArtifactUUID=" + currArtifactUUID + ", artifactData=" + artifactData + ", invariantUUID=" - + invariantUUID + "]"; - } + @Column(name = "prev_version") + protected String prevVersion; + + @Column(name = "prev_state") + protected String prevState; + + @Column(name = "curr_state") + protected String currState; + + @Column(name = "resource_name") + private String resourceName; + + @Column(name = "curr_version") + private String currVersion; + + @Column(name = "request_id") + protected String requestId; + + @Column(name = "service_instance_id") + protected String serviceInstanceId; + + @Column + protected String status; + + @Column(name = "description") + protected String desc; + + @Column + protected String modifier; + + @Column(name = "prev_artifact_UUID") + protected String prevArtifactUUID; + + @Column(name = "curr_artifact_UUID") + protected String currArtifactUUID; + + @Column(name = "artifact_data") + protected String artifactData; + + @Column + protected String did; + + @Column(name = "dprev_status") + protected String dprevStatus; + + @Column(name = "dcurr_status") + protected String dcurrStatus; + + @Column(name = "tosca_node_type") + protected String toscaNodeType; + + @Column + protected String comment; + + @Column(name = "invariant_UUID") + protected String invariantUUID; + + public ResourceAdminEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public ResourceAdminEvent(String action, CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams, + String invariantUuid, String modifier, String artifactData, String comment, String did, String toscaNodeType) { + this(); + this.action = action; + this.requestId = commonAuditData.getRequestId(); + this.desc = commonAuditData.getDescription(); + this.status = commonAuditData.getStatus(); + this.serviceInstanceId = commonAuditData.getServiceInstanceId(); + this.currState = currParams.getState(); + this.currVersion = currParams.getVersion(); + this.currArtifactUUID = currParams.getArtifactUuid(); + this.prevState = prevParams.getState(); + this.prevVersion = prevParams.getVersion(); + this.prevArtifactUUID = prevParams.getArtifactUuid(); + this.resourceName = resourceCommonInfo.getResourceName(); + this.resourceType = resourceCommonInfo.getResourceType(); + this.comment = comment; + this.dcurrStatus = currParams.getDistributionStatus(); + this.dprevStatus = prevParams.getDistributionStatus(); + this.artifactData = artifactData; + this.modifier = modifier; + this.invariantUUID = invariantUuid; + this.did = did; + this.toscaNodeType = toscaNodeType; + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + fields.put(AuditingFieldsKey.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUUID()); + fields.put(AuditingFieldsKey.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUUID()); + fields.put(AuditingFieldsKey.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_COMMENT.getDisplayName(), getComment()); + fields.put(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_DCURR_STATUS.getDisplayName(), getDcurrStatus()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_DPREV_STATUS.getDisplayName(), getDprevStatus()); + fields.put(AuditingFieldsKey.AUDIT_RESOURCE_TOSCA_NODE_TYPE.getDisplayName(), getToscaNodeType()); + fields.put(AuditingFieldsKey.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUUID()); + + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getPrevVersion() { + return prevVersion; + } + + public void setPrevVersion(String prevVersion) { + this.prevVersion = prevVersion; + } + + public String getCurrVersion() { + return currVersion; + } + + public void setCurrVersion(String currVersion) { + this.currVersion = currVersion; + } + + public String getPrevState() { + return prevState; + } + + public void setPrevState(String prevState) { + this.prevState = prevState; + } + + public String getCurrState() { + return currState; + } + + public void setCurrState(String currState) { + this.currState = currState; + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp1) { + this.timestamp1 = timestamp1; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getPrevArtifactUUID() { + return prevArtifactUUID; + } + + public void setPrevArtifactUUID(String prevArtifactUUID) { + this.prevArtifactUUID = prevArtifactUUID; + } + + public String getCurrArtifactUUID() { + return currArtifactUUID; + } + + public void setCurrArtifactUUID(String currArtifactUUID) { + this.currArtifactUUID = currArtifactUUID; + } + + public String getArtifactData() { + return artifactData; + } + + public void setArtifactData(String artifactData) { + this.artifactData = artifactData; + } + + public String getDid() { + return did; + } + + public void setDid(String did) { + this.did = did; + } + + public String getDprevStatus() { + return dprevStatus; + } + + public void setDprevStatus(String dprevStatus) { + this.dprevStatus = dprevStatus; + } + + public String getDcurrStatus() { + return dcurrStatus; + } + + public void setDcurrStatus(String dcurrStatus) { + this.dcurrStatus = dcurrStatus; + } + + public String getToscaNodeType() { + return toscaNodeType; + } + + public void setToscaNodeType(String toscaNodeType) { + this.toscaNodeType = toscaNodeType; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + @Override + public String toString() { + return "ResourceAdminEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action=" + + action + ", resourceType=" + resourceType + ", prevVersion=" + prevVersion + ", prevState=" + + prevState + ", currState=" + currState + ", resourceName=" + resourceName + ", currVersion=" + + currVersion + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", status=" + + status + ", desc=" + desc + ", modifier=" + modifier + ", prevArtifactUUID=" + prevArtifactUUID + + ", currArtifactUUID=" + currArtifactUUID + ", artifactData=" + artifactData + ", invariantUUID=" + + invariantUUID + "]"; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java index 7ead342827..74c85f6ea9 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java @@ -20,180 +20,149 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.USER_ACCESS_EVENT_TYPE) public class UserAccessEvent extends AuditingGenericEvent { - private static String USER_ACCESS_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" " - + "userUid=\"%s\" userName=\"%s\" status=\"%s\" desc=\"%s\""; - - @PartitionKey - protected UUID timebaseduuid; - - @ClusteringColumn - protected Date timestamp1; - - @Column(name = "REQUEST_ID") - protected String requestId; - - @Column(name = "USER") - private String userUid; - - @Column - private String status; - - @Column(name = "DESCRIPTION") - private String desc; - - @Column - private String action; - - @Column(name = "service_instance_id") - private String serviceInstanceId; - - public UserAccessEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public UserAccessEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID); - if (value != null) { - setUserUid((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - - } - - public UserAccessEvent(String action, CommonAuditData commonAuditData, String user) { - this(); - this.action = action; - this.requestId = commonAuditData.getRequestId(); - this.userUid = user; - this.status = commonAuditData.getStatus(); - this.desc = commonAuditData.getDescription(); - this.serviceInstanceId = commonAuditData.getServiceInstanceId(); - } - - - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID.getDisplayName(), getUserUid()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } - - public String getUserUid() { - return userUid; - } - - public void setUserUid(String userUid) { - this.userUid = userUid; - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - @Override - public String getServiceInstanceId() { return serviceInstanceId; } - - @Override - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp) { - this.timestamp1 = timestamp; - } - - @Override - public String toString() { - return "UserAccessEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" - + requestId + ", userUid=" + userUid + ", status=" + status + ", desc=" + desc + ", action=" + action - + ", serviceInstanceId=" + serviceInstanceId + "]"; - } + + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; + + @Column(name = "REQUEST_ID") + protected String requestId; + + @Column(name = "USER") + private String userUid; + + @Column + private String status; + + @Column(name = "DESCRIPTION") + private String desc; + + @Column + private String action; + + @Column(name = "service_instance_id") + private String serviceInstanceId; + + //Required to be public as it is used by Cassandra driver on get operation + public UserAccessEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public UserAccessEvent(String action, CommonAuditData commonAuditData, String user) { + this(); + this.action = action; + this.requestId = commonAuditData.getRequestId(); + this.userUid = user; + this.status = commonAuditData.getStatus(); + this.desc = commonAuditData.getDescription(); + this.serviceInstanceId = commonAuditData.getServiceInstanceId(); + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_USER_UID.getDisplayName(), getUserUid()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } + + public String getUserUid() { + return userUid; + } + + public void setUserUid(String userUid) { + this.userUid = userUid; + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Override + public String getServiceInstanceId() { return serviceInstanceId; } + + @Override + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp) { + this.timestamp1 = timestamp; + } + + @Override + public String toString() { + return "UserAccessEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" + + requestId + ", userUid=" + userUid + ", status=" + status + ", desc=" + desc + ", action=" + action + + ", serviceInstanceId=" + serviceInstanceId + "]"; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java index eb0d8db6f3..db5155f382 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java @@ -20,217 +20,175 @@ package org.openecomp.sdc.be.resources.data.auditing; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.TimeZone; -import java.util.UUID; - -import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - import com.datastax.driver.core.utils.UUIDs; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; @Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.USER_ADMIN_EVENT_TYPE) public class UserAdminEvent extends AuditingGenericEvent { - private static String USER_ADMIN_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" modifierName=\"%s\" modifierUid=\"%s\" " - + "userUid=\"%s\" userName=\"%s\" userEmail=\"%s\" userRole=\"%s\" " - + "userBeforeUid=\"%s\" userBeforeName=\"%s\" userBeforeEmail=\"%s\" userBeforeRole=\"%s\" " - + "userAfterUid=\"%s\" userAfterName=\"%s\" userAfterEmail=\"%s\" userAfterRole=\"%s\" " - + "status=\"%s\" desc=\"%s\""; - - @PartitionKey - protected UUID timebaseduuid; - - @ClusteringColumn - protected Date timestamp1; - - @Column(name = "REQUEST_ID") - protected String requestId; - - @Column(name = "SERVICE_INSTANCE_ID") - protected String serviceInstanceId; - - @Column(name = "ACTION") - protected String action; - @Column - protected String status; - - @Column(name = "description") - protected String desc; - - @Column - private String modifier; - - @Column(name = "user_before") - private String userBefore; - - @Column(name = "user_after") - private String userAfter; - - public UserAdminEvent() { - super(); - timestamp1 = new Date(); - timebaseduuid = UUIDs.timeBased(); - } - - public UserAdminEvent(Map auditingFields) { - this(); - Object value; - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID); - if (value != null) { - setRequestId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - if (value != null) { - setStatus((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID); - if (value != null) { - setModifier((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - if (value != null) { - setAction((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID); - if (value != null) { - setServiceInstanceId((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - if (value != null) { - setDesc((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE); - if (value != null) { - setUserBefore((String) value); - } - value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_AFTER); - if (value != null) { - setUserAfter((String) value); - } - - } - - public UserAdminEvent(String action, CommonAuditData commonAuditData, String modifier, String userBefore, String userAfter) { - this(); - this.action = action; - this.requestId = commonAuditData.getRequestId(); - this.status = commonAuditData.getStatus(); - this.modifier = modifier; - this.serviceInstanceId = commonAuditData.getServiceInstanceId(); - this.desc = commonAuditData.getDescription(); - this.userBefore = userBefore; - this.userAfter = userAfter; - } - - @Override - public void fillFields() { - fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); - - fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); - fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction()); - fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus()); - fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc()); - fields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE.getDisplayName(), getUserBefore()); - fields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER.getDisplayName(), getUserAfter()); - fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); - } - - public String getModifier() { - return modifier; - } - - public void setModifier(String modifier) { - this.modifier = modifier; - } - - public String getUserBefore() { - return userBefore; - } - - public void setUserBefore(String userBeforeName) { - this.userBefore = userBeforeName; - } - - public String getUserAfter() { - return userAfter; - } - - public void setUserAfter(String userAfterName) { - this.userAfter = userAfterName; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getServiceInstanceId() { - return serviceInstanceId; - } - - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public UUID getTimebaseduuid() { - return timebaseduuid; - } - - public void setTimebaseduuid(UUID timebaseduuid) { - this.timebaseduuid = timebaseduuid; - } - - public Date getTimestamp1() { - return timestamp1; - } - - public void setTimestamp1(Date timestamp) { - this.timestamp1 = timestamp; - } - - @Override - public String toString() { - return "UserAdminEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" - + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status - + ", desc=" + desc + ", modifierUid=" + modifier + ", userBefore=" + userBefore + ", userAfter=" - + userAfter + "]"; - } + @PartitionKey + protected UUID timebaseduuid; + + @ClusteringColumn + protected Date timestamp1; + + @Column(name = "REQUEST_ID") + protected String requestId; + + @Column(name = "SERVICE_INSTANCE_ID") + protected String serviceInstanceId; + + @Column(name = "ACTION") + protected String action; + @Column + protected String status; + + @Column(name = "description") + protected String desc; + + @Column + private String modifier; + + @Column(name = "user_before") + private String userBefore; + + @Column(name = "user_after") + private String userAfter; + + //Required to be public as it is used by Cassandra driver on get operation + public UserAdminEvent() { + timestamp1 = new Date(); + timebaseduuid = UUIDs.timeBased(); + } + + public UserAdminEvent(String action, CommonAuditData commonAuditData, String modifier, String userBefore, String userAfter) { + this(); + this.action = action; + this.requestId = commonAuditData.getRequestId(); + this.status = commonAuditData.getStatus(); + this.modifier = modifier; + this.serviceInstanceId = commonAuditData.getServiceInstanceId(); + this.desc = commonAuditData.getDescription(); + this.userBefore = userBefore; + this.userAfter = userAfter; + } + + public void setTimestamp1(String timestamp) { + this.timestamp1 = parseDateFromString(timestamp); + } + + @Override + public void fillFields() { + fields.put(AuditingFieldsKey.AUDIT_REQUEST_ID.getDisplayName(), getRequestId()); + + fields.put(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId()); + fields.put(AuditingFieldsKey.AUDIT_ACTION.getDisplayName(), getAction()); + fields.put(AuditingFieldsKey.AUDIT_STATUS.getDisplayName(), getStatus()); + fields.put(AuditingFieldsKey.AUDIT_DESC.getDisplayName(), getDesc()); + fields.put(AuditingFieldsKey.AUDIT_USER_BEFORE.getDisplayName(), getUserBefore()); + fields.put(AuditingFieldsKey.AUDIT_USER_AFTER.getDisplayName(), getUserAfter()); + fields.put(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName(), getModifier()); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + fields.put(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1)); + } + + public String getModifier() { + return modifier; + } + + public void setModifier(String modifier) { + this.modifier = modifier; + } + + public String getUserBefore() { + return userBefore; + } + + public void setUserBefore(String userBeforeName) { + this.userBefore = userBeforeName; + } + + public String getUserAfter() { + return userAfter; + } + + public void setUserAfter(String userAfterName) { + this.userAfter = userAfterName; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public UUID getTimebaseduuid() { + return timebaseduuid; + } + + public void setTimebaseduuid(UUID timebaseduuid) { + this.timebaseduuid = timebaseduuid; + } + + public Date getTimestamp1() { + return timestamp1; + } + + public void setTimestamp1(Date timestamp) { + this.timestamp1 = timestamp; + } + + @Override + public String toString() { + return "UserAdminEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId=" + + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status + + ", desc=" + desc + ", modifierUid=" + modifier + ", userBefore=" + userBefore + ", userAfter=" + + userAfter + "]"; + } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java index ae5a02ee75..34e2bdd479 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java @@ -18,6 +18,10 @@ public class CommonAuditData { return description; } + public void setRequestId(String requestId) { + this.requestId = requestId; + } + public String getRequestId() { return requestId; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionTopicData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionTopicData.java new file mode 100644 index 0000000000..378acd6f4b --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionTopicData.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.be.resources.data.auditing.model; + +public class DistributionTopicData { + private String statusTopic; + private String notificationTopic; + + private DistributionTopicData() { + } + + public String getStatusTopic() { + return statusTopic; + } + + public String getNotificationTopic() { + return notificationTopic; + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder { + + private final DistributionTopicData instance; + + public Builder() { + instance = new DistributionTopicData(); + } + + public Builder statusTopic(String statusTopic) { + this.instance.statusTopic = statusTopic; + return this; + } + + public Builder notificationTopic(String notificationTopic) { + this.instance.notificationTopic = notificationTopic; + return this; + } + + public DistributionTopicData build() { + return instance; + } + + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java deleted file mode 100644 index d66050a5f9..0000000000 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.openecomp.sdc.be.resources.data.auditing.model; - -public class ResourceAuditData { - private String artifactUuid; - private String state; - private String version; - private String distributionStatus; - - private ResourceAuditData() { - //for builder - } - - public static Builder newBuilder() { - return new Builder(); - } - - public String getArtifactUuid() { - return artifactUuid; - } - public String getState() { - return state; - } - public String getVersion() { - return version; - } - public String getDistributionStatus() { return distributionStatus; } - - - public static class Builder { - private final ResourceAuditData instance; - - private Builder() { - instance = new ResourceAuditData(); - } - - public Builder artifactUuid(String artifactUuid) { - instance.artifactUuid = artifactUuid; - return this; - } - - public Builder state(String state) { - instance.state = state; - return this; - } - - public Builder version(String version) { - instance.version = version; - return this; - } - - public Builder distributionStatus(String distributionStatus) { - instance.distributionStatus = distributionStatus; - return this; - } - - public ResourceAuditData build() { - return instance; - } - } -} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceCommonInfo.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceCommonInfo.java new file mode 100644 index 0000000000..eb9357de14 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceCommonInfo.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.be.resources.data.auditing.model; + +public class ResourceCommonInfo { + + private String resourceName; + private String resourceType; + + public ResourceCommonInfo(){} + + public ResourceCommonInfo(String resourceName, String resourceType) { + this.resourceName = resourceName; + this.resourceType = resourceType; + } + + public ResourceCommonInfo(String resourceType) { + this.resourceType = resourceType; + } + + public String getResourceName() { + return resourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceVersionInfo.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceVersionInfo.java new file mode 100644 index 0000000000..7e29fec2e5 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceVersionInfo.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.resources.data.auditing.model; + +public class ResourceVersionInfo { + private String artifactUuid; + private String state; + private String version; + private String distributionStatus; + + private ResourceVersionInfo() { + //for builder + } + + public static Builder newBuilder() { + return new Builder(); + } + + public String getArtifactUuid() { + return artifactUuid; + } + public String getState() { + return state; + } + public String getVersion() { + return version; + } + public String getDistributionStatus() { return distributionStatus; } + + + public static class Builder { + private final ResourceVersionInfo instance; + + private Builder() { + instance = new ResourceVersionInfo(); + } + + public Builder artifactUuid(String artifactUuid) { + instance.artifactUuid = artifactUuid; + return this; + } + + public Builder state(String state) { + instance.state = state; + return this; + } + + public Builder version(String version) { + instance.version = version; + return this; + } + + public Builder distributionStatus(String distributionStatus) { + instance.distributionStatus = distributionStatus; + return this; + } + + public ResourceVersionInfo build() { + return instance; + } + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java index d84f0ddf2b..f5e76ae8aa 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data.category; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class CategoryData extends GraphNode { private CategoryDataDefinition categoryDataDefinition; @@ -71,7 +70,7 @@ public class CategoryData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, categoryDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.NAME, categoryDataDefinition.getName()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java index 928329527b..1991c48f48 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.be.resources.data.category; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import java.util.HashMap; +import java.util.Map; + public class GroupingData extends GraphNode { private GroupingDataDefinition groupingDataDefinition; @@ -62,7 +62,7 @@ public class GroupingData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, groupingDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.NAME, groupingDataDefinition.getName()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java index a8605305a2..cbae4561e1 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.be.resources.data.category; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.reflect.TypeToken; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class SubCategoryData extends GraphNode { @@ -73,7 +72,7 @@ public class SubCategoryData extends GraphNode { @Override public Map toGraphMap() { - Map map = new HashMap(); + Map map = new HashMap<>(); addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, subCategoryDataDefinition.getUniqueId()); addIfExists(map, GraphPropertiesDictionary.NAME, subCategoryDataDefinition.getName()); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java index e4642c821f..8b5dee4e8b 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java @@ -20,9 +20,7 @@ package org.openecomp.sdc.be.resources.impl; -import javax.annotation.PostConstruct; -import javax.annotation.Resource; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ICatalogDAO; @@ -30,11 +28,11 @@ import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.resources.api.IResourceUploader; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.exception.ResourceDAOException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.PostConstruct; +import javax.annotation.Resource; @Component("resource-upload") public class ResourceUploader implements IResourceUploader { @@ -43,7 +41,7 @@ public class ResourceUploader implements IResourceUploader { @Resource private ICatalogDAO resourceDAO; - private static Logger log = LoggerFactory.getLogger(ResourceUploader.class.getName()); + private static Logger log = Logger.getLogger(ResourceUploader.class.getName()); @PostConstruct public void init() { -- cgit 1.2.3-korg