From 0ce3cf966de490dea5225ce8f095cddb6669db08 Mon Sep 17 00:00:00 2001 From: Yuli Shlosberg Date: Thu, 14 Nov 2019 14:41:05 +0200 Subject: [PATCH] add facade code to Onap Issue-ID: SDC-2657 Change-Id: I602a4f5858830f5c2afefe6d4f01f18fdea0f222 Signed-off-by: Yuli Shlosberg --- .gitignore | 10 + .gitreview | 4 + catalog-facade-ms/pom.xml | 293 +++++++++++++++++ .../onap/sdc/CatalogFacadeMsMainApplication.java | 84 +++++ .../java/org/onap/sdc/api/IBeDataRetriever.java | 43 +++ .../main/java/org/onap/sdc/api/IBusinessLogic.java | 53 +++ .../src/main/java/org/onap/sdc/api/ICache.java | 83 +++++ .../main/java/org/onap/sdc/api/ICacheHandler.java | 94 ++++++ .../java/org/onap/sdc/api/ICatalogElement.java | 195 +++++++++++ .../main/java/org/onap/sdc/api/ICatalogQuery.java | 42 +++ .../java/org/onap/sdc/api/ICatalogUIElement.java | 128 ++++++++ .../org/onap/sdc/api/ICatalogUpdateTimestamp.java | 54 ++++ .../sdc/api/ICatalogUpdateTimestampContainer.java | 27 ++ .../onap/sdc/api/ICatalogUpdateValidatorTask.java | 25 ++ .../src/main/java/org/onap/sdc/api/ICategory.java | 38 +++ .../java/org/onap/sdc/api/IComponentMessage.java | 45 +++ .../java/org/onap/sdc/api/IHealthCheckBuilder.java | 27 ++ .../java/org/onap/sdc/api/ILatestElements.java | 45 +++ .../org/onap/sdc/api/ILeftPalletUIElement.java | 121 +++++++ .../onap/sdc/api/IMessageQueueConfiguration.java | 59 ++++ .../onap/sdc/api/IMessageQueueHandlerConsumer.java | 41 +++ .../src/main/java/org/onap/sdc/api/IStatus.java | 44 +++ .../org/onap/sdc/controllers/BaseController.java | 27 ++ .../onap/sdc/controllers/CatalogController.java | 101 ++++++ .../sdc/controllers/HealthCheckController.java | 48 +++ .../java/org/onap/sdc/enums/ChangeTypeEnum.java | 30 ++ .../java/org/onap/sdc/enums/ComponentTypeEnum.java | 52 +++ .../java/org/onap/sdc/enums/CustomHeadersEnum.java | 36 +++ .../org/onap/sdc/enums/DistributionStatusEnum.java | 79 +++++ .../org/onap/sdc/enums/LifecycleStateEnum.java | 76 +++++ .../java/org/onap/sdc/enums/ResourceTypeEnum.java | 159 +++++++++ .../java/org/onap/sdc/enums/ResultStatusEnum.java | 30 ++ .../org/onap/sdc/enums/SdcResponseFieldEnum.java | 50 +++ .../java/org/onap/sdc/enums/UserOperationEnum.java | 25 ++ .../main/java/org/onap/sdc/enums/UserRoleEnum.java | 35 ++ .../java/org/onap/sdc/enums/UserStatusEnum.java | 32 ++ .../RestrictionAccessFilterException.java | 29 ++ .../java/org/onap/sdc/filter/FacadeFilter.java | 47 +++ .../onap/sdc/filter/FacadeUserThreadLocalImpl.java | 45 +++ .../org/onap/sdc/filter/FilterConfiguration.java | 114 +++++++ .../org/onap/sdc/filter/PortalConfiguration.java | 165 ++++++++++ .../onap/sdc/healthcheck/CatalogFacadeHealth.java | 78 +++++ .../java/org/onap/sdc/healthcheck/DmaapHealth.java | 73 +++++ .../org/onap/sdc/healthcheck/HealthCheckInfo.java | 88 +++++ .../src/main/java/org/onap/sdc/http/IResponse.java | 68 ++++ .../java/org/onap/sdc/http/ISimpleHttpClient.java | 61 ++++ .../java/org/onap/sdc/http/SimpleHttpClient.java | 124 +++++++ .../org/onap/sdc/impl/BeDataRetrieverImpl.java | 117 +++++++ .../java/org/onap/sdc/impl/BusinessLogicImpl.java | 94 ++++++ .../java/org/onap/sdc/impl/CacheHandlerImpl.java | 234 ++++++++++++++ .../src/main/java/org/onap/sdc/impl/CacheImpl.java | 240 ++++++++++++++ .../java/org/onap/sdc/impl/CatalogElementImpl.java | 103 ++++++ .../org/onap/sdc/impl/CatalogUIElementImpl.java | 92 ++++++ .../sdc/impl/CatalogUpdateValidatorTaskImpl.java | 54 ++++ .../src/main/java/org/onap/sdc/impl/Category.java | 94 ++++++ .../java/org/onap/sdc/impl/LatestElementsImpl.java | 76 +++++ .../org/onap/sdc/impl/LeftPalletUIElementImpl.java | 128 ++++++++ .../impl/message/CatalogUpdateTimestampImpl.java | 94 ++++++ .../CatalogUpdateTimestampSyncContainer.java | 93 ++++++ .../onap/sdc/impl/message/ComponentMessage.java | 75 +++++ .../org/onap/sdc/impl/message/ConsumerAdapter.java | 55 ++++ .../onap/sdc/impl/message/DmaapClientFactory.java | 136 ++++++++ .../org/onap/sdc/impl/message/DmaapConsumer.java | 120 +++++++ .../impl/message/DmaapConsumerConfiguration.java | 106 ++++++ .../impl/message/ElementFilterFieldsContainer.java | 68 ++++ .../impl/message/ElementViewFieldsContainer.java | 69 ++++ .../java/org/onap/sdc/impl/users/UserElement.java | 63 ++++ .../java/org/onap/sdc/logger/FacadeLogUtils.java | 40 +++ .../sdc/repositories/CatalogElementRepository.java | 49 +++ .../java/org/onap/sdc/services/ServletHelper.java | 146 +++++++++ .../org/onap/sdc/utils/CatalogElementsUtils.java | 60 ++++ .../java/org/onap/sdc/utils/EncryptionUtils.java | 200 ++++++++++++ .../org/onap/sdc/utils/FunctionalCodeUtils.java | 275 ++++++++++++++++ .../main/java/org/onap/sdc/utils/MessageUtils.java | 40 +++ .../src/main/java/org/onap/sdc/utils/Wrapper.java | 65 ++++ .../sdc/utils/queries/QueryCompositionBuilder.java | 96 ++++++ .../onap/sdc/utils/queries/QueryFilterBuilder.java | 112 +++++++ .../queries/QueryFilterBuilderForCategory.java | 50 +++ .../QueryFilterBuilderForComponentType.java | 66 ++++ .../QueryFilterBuilderForDistributionStatus.java | 43 +++ .../queries/QueryFilterBuilderForLastUpdater.java | 40 +++ .../QueryFilterBuilderForLifecycleState.java | 43 +++ .../src/main/resources/DME2preferredRouter.txt | 0 .../src/main/resources/application.yml | 135 ++++++++ .../src/main/resources/key.properties | 41 +++ catalog-facade-ms/src/main/resources/keystore | 0 catalog-facade-ms/src/main/resources/logback.xml | 94 ++++++ catalog-facade-ms/src/main/resources/truststore | 0 .../sdc/controllers/CatalogControllerTest.java | 171 ++++++++++ .../sdc/controllers/ControllersTestsUtils.java | 44 +++ .../sdc/controllers/HealthCheckControllerTest.java | 108 +++++++ .../healthcheck/CatalogFacadeHealthCheckTest.java | 96 ++++++ .../org/onap/sdc/healthcheck/DmaapHealthTest.java | 64 ++++ .../org/onap/sdc/impl/BusinessLogicImplTest.java | 76 +++++ .../org/onap/sdc/impl/CacheHandlerImplTest.java | 360 +++++++++++++++++++++ .../test/java/org/onap/sdc/impl/CacheImplTest.java | 131 ++++++++ .../org/onap/sdc/impl/CatalogElementUtils.java | 85 +++++ .../message/CatalogUpdateTimestampImplTest.java | 90 ++++++ .../CatalogUpdateTimestampSyncContainerTest.java | 98 ++++++ .../sdc/impl/message/ComponentMessageTest.java | 59 ++++ .../message/DmaapConsumerConfigurationTest.java | 39 +++ .../onap/sdc/impl/message/DmaapConsumerTest.java | 46 +++ .../src/test/java/org/onap/sdc/utils/Utils.java | 58 ++++ .../utils/queries/QueryCompositionBuilderTest.java | 105 ++++++ .../sdc/utils/queries/QueryFilterBuilderTest.java | 303 +++++++++++++++++ 105 files changed, 8866 insertions(+) create mode 100644 .gitignore create mode 100644 .gitreview create mode 100644 catalog-facade-ms/pom.xml create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/CatalogFacadeMsMainApplication.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IBeDataRetriever.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IBusinessLogic.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICache.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICacheHandler.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogElement.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogQuery.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUIElement.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestamp.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestampContainer.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateValidatorTask.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ICategory.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IComponentMessage.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IHealthCheckBuilder.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ILatestElements.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/ILeftPalletUIElement.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueConfiguration.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueHandlerConsumer.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/api/IStatus.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/controllers/BaseController.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/controllers/CatalogController.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/controllers/HealthCheckController.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/ChangeTypeEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/ComponentTypeEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/CustomHeadersEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/DistributionStatusEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/LifecycleStateEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResourceTypeEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResultStatusEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/SdcResponseFieldEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserOperationEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserRoleEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserStatusEnum.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/exception/RestrictionAccessFilterException.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeFilter.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeUserThreadLocalImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/filter/FilterConfiguration.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/filter/PortalConfiguration.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/CatalogFacadeHealth.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/DmaapHealth.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/HealthCheckInfo.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/http/IResponse.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/http/ISimpleHttpClient.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/http/SimpleHttpClient.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/BeDataRetrieverImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/BusinessLogicImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheHandlerImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogElementImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUIElementImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUpdateValidatorTaskImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/Category.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/LatestElementsImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/LeftPalletUIElementImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImpl.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainer.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ComponentMessage.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ConsumerAdapter.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapClientFactory.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumer.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumerConfiguration.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementFilterFieldsContainer.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementViewFieldsContainer.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/impl/users/UserElement.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/logger/FacadeLogUtils.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/repositories/CatalogElementRepository.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/services/ServletHelper.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/CatalogElementsUtils.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/EncryptionUtils.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/FunctionalCodeUtils.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/MessageUtils.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/Wrapper.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryCompositionBuilder.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilder.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForCategory.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForComponentType.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForDistributionStatus.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLastUpdater.java create mode 100644 catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLifecycleState.java create mode 100644 catalog-facade-ms/src/main/resources/DME2preferredRouter.txt create mode 100644 catalog-facade-ms/src/main/resources/application.yml create mode 100644 catalog-facade-ms/src/main/resources/key.properties create mode 100644 catalog-facade-ms/src/main/resources/keystore create mode 100644 catalog-facade-ms/src/main/resources/logback.xml create mode 100644 catalog-facade-ms/src/main/resources/truststore create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/controllers/CatalogControllerTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/controllers/ControllersTestsUtils.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/controllers/HealthCheckControllerTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/CatalogFacadeHealthCheckTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/DmaapHealthTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/BusinessLogicImplTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheHandlerImplTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheImplTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/CatalogElementUtils.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImplTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainerTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/ComponentMessageTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerConfigurationTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/utils/Utils.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryCompositionBuilderTest.java create mode 100644 catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryFilterBuilderTest.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d27a5f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.idea/ +*.iml +.classpath +.project +.settings/ +.checkstyle +target/ +logs/ +debug-logs/ +*.log diff --git a/.gitreview b/.gitreview new file mode 100644 index 0000000..a0133d9 --- /dev/null +++ b/.gitreview @@ -0,0 +1,4 @@ +[gerrit] +host=gerrit.onap.org +port=29418 +project=sdc/microservices.git diff --git a/catalog-facade-ms/pom.xml b/catalog-facade-ms/pom.xml new file mode 100644 index 0000000..c185fd3 --- /dev/null +++ b/catalog-facade-ms/pom.xml @@ -0,0 +1,293 @@ + + + 4.0.0 + + org.onap.sdc + catalog-facade-ms + 1.6.0-SNAPSHOT + jar + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + UTF-8 + 1.8 + 1.8 + https://nexus.onap.org + 1.6.0 + 1.3.0-SNAPSHOT + 2.5.0 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + org.springframework.boot + spring-boot-starter-jetty + + + + org.onap.logging-analytics + logging-filter-base + 1.6.1 + + + + + org.codehaus.groovy + groovy + 2.4.15 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.onap.dmaap.messagerouter.dmaapclient + dmaapClient + 1.1.3 + + + org.glassfish.jersey.core + jersey-client + + + org.glassfish.jersey.core + jersey-common + + + + + + org.glassfish.jersey.core + jersey-client + + 2.25.1 + + + + org.glassfish.jersey.core + jersey-common + + 2.25.1 + + + + + + org.apache.commons + commons-collections4 + 4.0 + + + + + org.apache.commons + commons-lang3 + + + + + org.apache.httpcomponents + httpclient + + + + com.google.guava + guava + 18.0 + compile + + + + org.codehaus.groovy + groovy-all + 2.4.15 + + + + janino + janino + + 2.5.10 + + + + org.projectlombok + lombok + 1.18.0 + compile + + + org.springframework.data + spring-data-rest-hal-browser + + + + org.onap.sdc.sdc-be-common + security-util-lib + ${security.util-lib.version} + compile + + + org.glassfish.jersey.ext + jersey-bean-validation + + + + + + org.openecomp.sdc + common-app-api + ${common-app-api.version} + compile + + + org.onap.sdc.securityutil + sdc-security-util + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + maven-compiler-plugin + 3.7.0 + + + + + + + + ecomp-releases + Release Repository + ${nexus.proxy}/content/repositories/releases/ + + + ecomp-snapshots + Snapshots Repository + ${nexus.proxy}/content/repositories/snapshots/ + + + ecomp-public + Public Repository + ${nexus.proxy}/content/repositories/public/ + + + + + + + + docker + + false + + + 0.23.0 + nexus3.onap.org:10001 + docker + docker + onap/ + + + + + io.fabric8 + docker-maven-plugin + ${fabric8.version} + + + true + 1.23 + ${docker.registry} + + ${docker.username} + ${docker.password} + + + + + ${docker.namespace}${project.artifactId} + ${project.artifactId} + + try + ${project.basedir} + + ${docker.tag} + ${project.version}-STAGING-latest + + + + + + + + clean-images + pre-clean + + remove + + + true + + + + generate-images + install + + build + + + + push-images + deploy + + push + + + + + + + + + + + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + never + + + false + + + + diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/CatalogFacadeMsMainApplication.java b/catalog-facade-ms/src/main/java/org/onap/sdc/CatalogFacadeMsMainApplication.java new file mode 100644 index 0000000..c3671a2 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/CatalogFacadeMsMainApplication.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc; + +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.onap.logging.filter.base.AuditLogServletFilter; +import org.onap.sdc.filter.FacadeFilter; +import org.onap.sdc.filter.FacadeUserThreadLocalImpl; +import org.onap.sdc.filter.FilterConfiguration; +import org.onap.sdc.filter.PortalConfiguration; +import org.onap.sdc.security.PortalClient; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.onap.sdc.security.RestrictionAccessFilterException; + +@EnableScheduling +@ServletComponentScan +@SpringBootApplication()//scanBasePackageClasses = {PortalClient.class}) +@ComponentScan("org.onap.sdc") +public class CatalogFacadeMsMainApplication { + @Autowired + private FilterConfiguration filterConfiguration; + @Autowired + private PortalConfiguration portalConfiguration; + @Autowired + private FacadeUserThreadLocalImpl facadeUserThreadLocalImpl; + + public static void main(String[] args) { + SpringApplication.run(CatalogFacadeMsMainApplication.class, args); + } + +// @Bean + public PortalClient getPortalClient() { + return new PortalClient(getHttpClient(), portalConfiguration); + } + + @Bean + public CloseableHttpClient getHttpClient() { + return HttpClients.createDefault(); + } + + @Bean + public FilterRegistrationBean facadeFilter() throws RestrictionAccessFilterException{ + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new FacadeFilter(filterConfiguration, facadeUserThreadLocalImpl, getPortalClient())); + registrationBean.addUrlPatterns("/uicache/v1/followed", "/uicache/v1/catalog"); + registrationBean.setOrder(Integer.MAX_VALUE); + return registrationBean; + } + + @Bean + public FilterRegistrationBean loggingFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new AuditLogServletFilter()); + registrationBean.setOrder(Integer.MAX_VALUE-1); + return registrationBean; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IBeDataRetriever.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IBeDataRetriever.java new file mode 100644 index 0000000..f90a481 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IBeDataRetriever.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import org.onap.sdc.http.IResponse; + +/** + * This Class handles retrieving data used by the mService from asdc BE + * + */ +public interface IBeDataRetriever { + + /** + * Get All Non Archive Components. + */ + String getCatalogResponseBody(); + + /** + * Get All Archive Components. + */ + String getArchiveCatalogResponseBody(); + + String getUpdateTimeResponseBody(); + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IBusinessLogic.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IBusinessLogic.java new file mode 100644 index 0000000..02a39af --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IBusinessLogic.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.List; +import java.util.function.Consumer; + +/** + * Business Logic Interface for catalog mService.
+ * @author ms172g + * + */ +public interface IBusinessLogic { + + /** + * Needs to define the callback and activate the init method of the message Queue Handler{@link IMessageQueueHandler#init(Consumer)}.
+ * @return + */ + IStatus init(); + + /** + * Returns the catalog elements to the servlet.
+ * @param query + * @return + */ + List getCatalogElements(ICatalogQuery query); + + + /** + * This method activate the logic upon retrieval of a new IComponentMessage or UserMessage.
+ * @param message + */ + IStatus doOnMessageReceive(String message); + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICache.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICache.java new file mode 100644 index 0000000..9cb056d --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICache.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.Comparator; +import java.util.List; +import java.util.function.Predicate; + +public interface ICache { + + ICache evict(T... values); + + /** + * @param values + */ + ICache put(T... values); + + /** + * @param values + */ + boolean update(T values); + + /** + * @param values + */ + boolean updateOrCreate(T values); + + /** + * @param isArchive + * @param value + */ + boolean archiveRestore(boolean isArchive, T value); + + /* + * clear entire cache + * */ + ICache clear(); + + + + /* + * get element by unique identifier + * */ + List get(Predicate predicate); + + /* + * get element by unique identifier + * */ + List get(Predicate predicate, Comparator comparator); + + /** + * + * cache size + * + ***/ + int count(); + + boolean isEmpty(); + + /** + * This Method Replaces the Given Map With a ConcurrentHashMap to be used by the cache.
+ * @param inputMap + */ + void fillCacheSafety(List inputMap); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICacheHandler.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICacheHandler.java new file mode 100644 index 0000000..191fe36 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICacheHandler.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.List; + +/** + * Represents the handler that works with the cache interface.
+ * + * @author ms172g + * + */ +public interface ICacheHandler { + /** + * This Method fills in the cache from sdc be on the initial start of the mService. + * @return + */ + IStatus init(); + /** + * Handles a new component message received.
+ * Will create a cache element and either create/update or delete it in + * cache according to message.
+ * + * @return + */ + IStatus handleComponentMessage(IComponentMessage message); + + /** + * create an element to the cache.
+ * + * @param element + * @return + */ + + IStatus handleRestoreMessage(ICatalogElement message) ; + + IStatus handleArchiveMessage(ICatalogElement message) ; + + IStatus handleLifecycleMessage(ICatalogElement message) ; + + /** + * delete an element to the cache.
+ * + * @param element + * @return + */ + IStatus handleDeleteMessage(ICatalogElement element); + + + /** + * update an element to the cache.
+ * + * @param element + * @return + */ + IStatus updateCatalogElementInCache(ICatalogElement element); + + + + /** + * Returns List of the catalog elements found in cache that match to the + * query.
+ * + * @param query + * @return + */ + List getCatalogElements(ICatalogQuery query); + + /** + * Retrieves last update timestamp from BE and compares it to the handled one + * Loads Catalog data from BE if they don't match + * @return + */ + IStatus loadCatalogIfNotificationsLost(); + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogElement.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogElement.java new file mode 100644 index 0000000..1103b82 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogElement.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.common.annotations.VisibleForTesting; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; +import org.onap.sdc.impl.CatalogElementImpl; + +import java.io.IOException; +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Represents one element (service, resource etc...) of data that is stored in + * the cache.
+ * + * @author ms172g + * + */ +public interface ICatalogElement extends Serializable { + /** + * Flag that indicates whether the component is archived or not. + * + * @return + */ + boolean isArchived(); + + /** + * Unique id of the component. + * + * @return + */ + String getUniqueId(); + + /** + * Version id of the component. + * + * @return + */ + String getVersion(); + + /** + * Component Type + * + * @return + */ + ComponentTypeEnum getComponentType(); + + /** + * Component Name + * + * @return + */ + String getName(); + + /** + * Returns the resource type (or null in case it is a service) + * + * @return + */ + ResourceTypeEnum getResourceType(); + + /** + * Returns the Lifecycle of the Component. + * + * @return + */ + LifecycleStateEnum getLifecycleState(); + + /** + * Returns the name of the icon used by the UI for this Component. + * + * @return + */ + String getIcon(); + + /** + * Returns the last date (system ms seconds) this component was updated. + * + * @return + */ + long getLastUpdateDate(); + + /** + * Returns the category name this Component belongs to. + * + * @return + */ + String getCategory(); + + /** + * Returns the subCategory name this Component belongs to. + * + * @return + */ + String getSubCategory(); + + /** + * Returns the distribution status of this component (null if not a + * Service). + * + * @return + */ + DistributionStatusEnum getDistributionStatus(); + /** + * Returns the uuid of this component + * + * @return + */ + String getUuid() ; + + /** + * Returns the system name of this component + * + * @return + */ + String getSystemName(); + /** + * Returns the invariant uuid of this component + * + * @return + */ + String getInvariantUUID(); + /** + * Returns the description of this component + * + * @return + */ + String getDescription(); + /** + * Returns the list of tags of this component + * + * @return + */ + List getTags(); + + Boolean getIsHighestVersion(); + + List getCategories(); + + String getLastUpdaterUserId(); + + void setLastUpdaterUserId(String lastUpdaterUserId); + + @VisibleForTesting + void setInvariantUUID(String invariantUUID); + + @VisibleForTesting + void setLifecycleState(LifecycleStateEnum lifecycleState); + + /** + * Builds Map of Catalog elements from sdc be response. + * + * @param responseBody + * @return + * @throws IOException + */ + static Map> buildFromSdcHttpResponse(String responseBody) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); + TypeReference>> typeRef = new TypeReference>>() { + }; + return objectMapper.readValue(responseBody, typeRef); + } + + void setArchived(boolean isArchived); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogQuery.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogQuery.java new file mode 100644 index 0000000..eaae7d9 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogQuery.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.List; +import java.util.function.Predicate; + + +/** + * Represents a query object sent from FE to the mService.
+ * + * @author ms172g + * + */ +@FunctionalInterface +public interface ICatalogQuery { + /** + * Query filters, when this query executes only {@link ICatalogElement} that + * pass all the filters should be returned.
+ * + * @return + */ + List> getQueryFilters(); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUIElement.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUIElement.java new file mode 100644 index 0000000..794a97f --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUIElement.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.List; + +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +/** + * Represents Catalog Element that is shown in the UI + * @author ms172g + * + */ +public interface ICatalogUIElement { + + + /** + * Unique id of the component. + * + * @return + */ + String getUniqueId(); + + /** + * Version id of the component. + * + * @return + */ + String getVersion(); + + /** + * Component Type + * + * @return + */ + ComponentTypeEnum getComponentType(); + + /** + * Component Name + * + * @return + */ + String getName(); + + /** + * Returns the resource type (or null in case it is a service) + * + * @return + */ + ResourceTypeEnum getResourceType(); + + /** + * Returns the Lifecycle of the Component. + * + * @return + */ + LifecycleStateEnum getLifecycleState(); + + /** + * Returns the name of the icon used by the UI for this Component. + * + * @return + */ + String getIcon(); + + /** + * Returns the last date (system ms seconds) this component was updated. + * + * @return + */ + long getLastUpdateDate(); + + /** + * Returns the category name this Component belongs to. + * + * @return + */ + String getCategory(); + + /** + * Returns the subCategory name this Component belongs to. + * + * @return + */ + String getSubCategory(); + + /** + * Returns the distribution status of this component (null if not a + * Service). + * + * @return + */ + DistributionStatusEnum getDistributionStatus(); + + /** + * Returns the list of tags of this component + * + * @return + */ + List getTags(); + + String getLastUpdaterUserId(); + + void setLastUpdaterUserId(String lastUpdaterUserId); + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestamp.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestamp.java new file mode 100644 index 0000000..371ceb6 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestamp.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.onap.sdc.impl.message.CatalogUpdateTimestampImpl; + +import java.io.IOException; +import java.io.Serializable; + +public interface ICatalogUpdateTimestamp extends Serializable { + + @JsonProperty("currentUpdateTime") + long getCurrentUpdateTime(); + @JsonProperty("previousUpdateTime") + long getPreviousUpdateTime(); + + void setCurrentUpdateTime(long currentUpdateTime); + void setPreviousUpdateTime(long previousUpdateTime); + boolean isSameUpdate(ICatalogUpdateTimestamp catalogUpdateTimestamp); + boolean isNextUpdate(ICatalogUpdateTimestamp catalogUpdateTimestamp); + void set(ICatalogUpdateTimestamp catalogUpdateTimestamp); + + static CatalogUpdateTimestampImpl buildFromHttpResponse(String responseBody) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + TypeReference typeRef = new TypeReference() {}; + return objectMapper.readValue(responseBody, typeRef); + } + + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestampContainer.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestampContainer.java new file mode 100644 index 0000000..794823e --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestampContainer.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +public interface ICatalogUpdateTimestampContainer { + boolean updatesLostAsPerNotification(ICatalogUpdateTimestamp catalogUpdateTimestamp); + boolean updatesLostAsPerHttpBeRequest(ICatalogUpdateTimestamp catalogUpdateTimestamp); + boolean isUpdatedAlready(ICatalogUpdateTimestamp catalogUpdateTimestamp); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateValidatorTask.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateValidatorTask.java new file mode 100644 index 0000000..3a64c1e --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateValidatorTask.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +public interface ICatalogUpdateValidatorTask { + void run(); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICategory.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICategory.java new file mode 100644 index 0000000..f77dfca --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ICategory.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import org.onap.sdc.impl.Category; + +import java.io.Serializable; +import java.util.List; + +@JsonDeserialize(as=Category.class) +public interface ICategory extends Serializable { + + String getName(); + String getNormalizedName(); + String getUniqueId(); + List getIcons(); + List getSubcategories(); + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IComponentMessage.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IComponentMessage.java new file mode 100644 index 0000000..0945bda --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IComponentMessage.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import org.onap.sdc.enums.ChangeTypeEnum; + +import java.io.Serializable; + +/** + * Represent Component (service, resource etc...) change message added to the + * message queue by sdc backend.
+ * + * @author ms172g + * + */ +public interface IComponentMessage extends ICatalogElement, Serializable { + /** + * Change Type + * @return the change type value + */ + ChangeTypeEnum getChangeType(); + + ICatalogUpdateTimestamp getCatalogUpdateTimestamp(); +} + + + diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IHealthCheckBuilder.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IHealthCheckBuilder.java new file mode 100644 index 0000000..4f546c2 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IHealthCheckBuilder.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import org.onap.sdc.healthcheck.HealthCheckInfo; + +public interface IHealthCheckBuilder { + HealthCheckInfo getHealthCheckInfo(); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ILatestElements.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ILatestElements.java new file mode 100644 index 0000000..ec4c70c --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ILatestElements.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.List; + +/** + * Interface that holds latest catalog elements Certified and non certified. + * @author ms172g + * + */ +public interface ILatestElements { + ICatalogElement getNonCertifiedElement(); + + ICatalogElement getCertifiedElement(); + void setNonCertifiedElement(ICatalogElement element); + + void setCertifiedElement(ICatalogElement element); + boolean isEmpty(); + + /** + * List Containing all non null catalog element in ILatestElements + * @return + */ + List getAllElements(); + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/ILeftPalletUIElement.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ILeftPalletUIElement.java new file mode 100644 index 0000000..9f81d32 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/ILeftPalletUIElement.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.ResourceTypeEnum; +import org.openecomp.sdc.common.util.ICategorizedElement; + +import java.util.List; + +/** + * Represents Left Pallet Element that is shown in the UI + * + * @author ms172g + * + */ +public interface ILeftPalletUIElement extends ICategorizedElement { + /** + * Unique id of the component. + * + * @return + */ + String getUniqueId(); + + /** + * Version id of the component. + * + * @return + */ + String getVersion(); + + /** + * Component Type + * + * @return + */ + ComponentTypeEnum getComponentType(); + + /** + * Component Name + * + * @return + */ + String getName(); + + /** + * Returns the resource type (or null in case it is a service) + * + * @return + */ + ResourceTypeEnum getResourceType(); + + /** + * Returns the Lifecycle of the Component. + * + * @return + */ +// LifecycleStateEnum getLifecycleState(); + + /** + * Returns the name of the icon used by the UI for this Component. + * + * @return + */ + String getIcon(); + + /** + * Returns the uuid of this component + * + * @return + */ + String getUuid(); + + /** + * Returns the system name of this component + * + * @return + */ + String getSystemName(); + + /** + * Returns the invariant uuid of this component + * + * @return + */ + String getInvariantUUID(); + + /** + * Returns the description of this component + * + * @return + */ + String getDescription(); + + List getCategories(); + + /** + * Returns the list of tags of this component + * + * @return + */ + List getTags(); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueConfiguration.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueConfiguration.java new file mode 100644 index 0000000..70a05c7 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueConfiguration.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +public interface IMessageQueueConfiguration { + + /** + * MessageQueue address. Value can be either hostname (with or without + * port), IP:port or FQDN (Fully Qualified Domain Name). + * + * @return MessageQueue address. + */ + String getMessageQueueURL(); + + /** + * User Name for MessageQueue authentication. + * + * @return User Name. + */ + String getUser(); + + /** + * User Password for MessageQueue authentication. + * + * @return User Name. + */ + String getPassword(); + + /** + * Returns the topict name (testing, production etc...). + * + * @return + */ + String getTopicName(); + + /** + * Toggle For the feature. + * @return + */ + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueHandlerConsumer.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueHandlerConsumer.java new file mode 100644 index 0000000..08a2352 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueHandlerConsumer.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import java.util.function.Consumer; + + +/** + * This Class Handles Pulling / Pushing Messages From the Message Queue.
+ * @author ms172g + * + */ +public interface IMessageQueueHandlerConsumer { + + + /** + * This method receives a callback that will be activated when a new message is added to the message broker.
+ * @param callback + * @return + */ + IStatus init(Consumer callback); + void run(); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/api/IStatus.java b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IStatus.java new file mode 100644 index 0000000..08cc9ff --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/api/IStatus.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.api; + +import org.onap.sdc.enums.ResultStatusEnum; + +/** + * Represents fail/success status status + * + * @author ms172g + * + */ +@FunctionalInterface +public interface IStatus { + + static IStatus getSuccessStatus() { + + return () -> ResultStatusEnum.SUCCESS; + } + + static IStatus getFailStatus() { + return () -> ResultStatusEnum.FAIL; + } + ResultStatusEnum getResultStatus(); + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/BaseController.java b/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/BaseController.java new file mode 100644 index 0000000..f0632f0 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/BaseController.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.controllers; + +import org.springframework.web.bind.annotation.RequestMapping; + +@RequestMapping("/uicache") +public class BaseController { +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/CatalogController.java b/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/CatalogController.java new file mode 100644 index 0000000..28d13c4 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/CatalogController.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.controllers; + +import static org.onap.sdc.enums.SdcResponseFieldEnum.RESOURCES_LIST; +import static org.onap.sdc.enums.SdcResponseFieldEnum.SERVICES_LIST; +import static org.openecomp.sdc.common.util.GeneralUtility.getCategorizedComponents; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.onap.sdc.api.IBusinessLogic; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.api.ICatalogUIElement; +import org.onap.sdc.api.ILeftPalletUIElement; +import org.onap.sdc.impl.LeftPalletUIElementImpl; +import org.onap.sdc.utils.CatalogElementsUtils; +import org.onap.sdc.utils.queries.QueryCompositionBuilder; +import org.onap.sdc.utils.queries.QueryFilterBuilder; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CatalogController extends BaseController { + + private static final String CATALOG_PATH = "/v1/catalog"; + private static final Logger LOG = Logger.getLogger(CatalogController.class); + + @Autowired + private IBusinessLogic businessLogic; + + @RequestMapping(value = CATALOG_PATH, method = RequestMethod.GET) + public @ResponseBody Map> getCatalogQueryResponse( + @RequestParam(value = "ct", required = false) List componentTypeList, + @RequestParam(value = "ds", required = false) List distributionStatusList, + @RequestParam(value = "cat", required = false) List categoryList, + @RequestParam(value = "arc", required = false) Boolean archive, + @RequestParam(value = "sort", required = false) String sort, + @RequestParam(value = "order", required = false) String sortOrder, + @RequestParam(value = "page", required = false) Integer page, + @RequestParam(value = "lud", required = false) String lastUpdateDate, + @RequestParam(value = "bulk", required = false) Integer bulk) { + + final String methodName = "getCatalogQueryResponse"; + Map> responseMap = fillResponseMap( + QueryFilterBuilder.getFilterQuery(componentTypeList, categoryList, distributionStatusList,null, null, archive)); + LOG.debug(methodName + ": Found {} components", responseMap.get(RESOURCES_LIST.getJsonName()) + .size() + + responseMap.get(SERVICES_LIST.getJsonName()) + .size()); + return responseMap; + } + + @RequestMapping(value = CATALOG_PATH + + "/{componentType}/latestversion/notabstract/metadata", method = RequestMethod.GET) + public @ResponseBody Map>> getLeftPaletteComposition( + @PathVariable("componentType") String componentType, + @RequestParam(value = "internalComponentType", required = true) String internalComponentType) { + final String methodName = "getLeftPaletteComposition"; + + List leftPalletElements = businessLogic + .getCatalogElements(QueryCompositionBuilder.getQuery(internalComponentType)) + .stream() + .map(LeftPalletUIElementImpl::buildUIElement) + .collect(Collectors.toList()); + LOG.debug(methodName + ": Found {} elements", leftPalletElements.size()); + return getCategorizedComponents(leftPalletElements); + } + + private Map> fillResponseMap(ICatalogQuery query) { + List catalogElements = businessLogic.getCatalogElements(query); + return CatalogElementsUtils.convertElementsListToUIMap(catalogElements); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/HealthCheckController.java b/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/HealthCheckController.java new file mode 100644 index 0000000..bf65a8a --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/controllers/HealthCheckController.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.controllers; + +import com.google.common.collect.Maps; +import org.onap.sdc.healthcheck.CatalogFacadeHealth; +import org.onap.sdc.healthcheck.HealthCheckInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@RestController +public class HealthCheckController { + @Autowired + CatalogFacadeHealth catalogFacadeHealth; + + @RequestMapping(value = "/healthCheck", method = RequestMethod.GET) + public @ResponseBody Map> getHealthCheckInfo() { + Map> responseMap = Maps.newHashMap(); + responseMap.put(HealthCheckInfo.COMPONENTS_INFO_KEY, Collections.singletonList(catalogFacadeHealth.getHealthCheckInfo())); + return responseMap; + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ChangeTypeEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ChangeTypeEnum.java new file mode 100644 index 0000000..e81b8cc --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ChangeTypeEnum.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +/** + * Represents The change type SDC Backend requests on the Component.
+ * @author ms172g + * + */ +public enum ChangeTypeEnum { + LIFECYCLE, DELETE, ARCHIVE, RESTORE +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ComponentTypeEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ComponentTypeEnum.java new file mode 100644 index 0000000..414a3a6 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ComponentTypeEnum.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.utils.FunctionalCodeUtils; + +/** + * This Enum Represent the componentType field value returned in sdc catalog + * query json response. + * + * @author ms172g + * + */ +public enum ComponentTypeEnum { + //@formatter:off + RESOURCE("RESOURCE"), + SERVICE("SERVICE"); + //@formatter:on + private String headerName; + + ComponentTypeEnum(String headerName) { + this.headerName = headerName; + } + + public String getHeaderName() { + return headerName; + } + + public static ComponentTypeEnum findByHeaderName(String headerName) { + return FunctionalCodeUtils.findByPredicate(x -> StringUtils.equals(x.getHeaderName(), headerName), values()); + + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/CustomHeadersEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/CustomHeadersEnum.java new file mode 100644 index 0000000..376ab51 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/CustomHeadersEnum.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +public enum CustomHeadersEnum { + //@formatter:off + USER_ID("USER_ID"); + //@formatter:on + private String headerName; + + CustomHeadersEnum(String headerName) { + this.headerName = headerName; + } + + public String getHeaderName() { + return headerName; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/DistributionStatusEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/DistributionStatusEnum.java new file mode 100644 index 0000000..f8e7610 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/DistributionStatusEnum.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========================================================= + */ + +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +/** + * Represents Distribution Status on a Service. + * @author ms172g + * + */ +public enum DistributionStatusEnum { + // TODO remove this from sdc code + //@formatter:off + DISTRIBUTION_NOT_APPROVED("Distribution not approved"), + DISTRIBUTION_APPROVED("Distribution approved"), + DISTRIBUTED("Distributed"), + DISTRIBUTION_REJECTED("Distribution rejected"); + //@formatter:on + private String value; + + DistributionStatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static DistributionStatusEnum findState(String state) { + + for (DistributionStatusEnum distributionStatus : DistributionStatusEnum.values()) { + if (distributionStatus.name() + .equalsIgnoreCase(state) + || distributionStatus.getValue() + .equalsIgnoreCase(state)) { + return distributionStatus; + } + } + return null; + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/LifecycleStateEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/LifecycleStateEnum.java new file mode 100644 index 0000000..13c7682 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/LifecycleStateEnum.java @@ -0,0 +1,76 @@ +/*- + * ============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========================================================= + */ + +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +/** + * Represents Lifecycle current state of an sdc component. + * @author ms172g + * + */ +public enum LifecycleStateEnum { + //@formatter:off + CERTIFIED("CERTIFIED"), + NOT_CERTIFIED_CHECKIN("NOT_CERTIFIED_CHECKIN"), + NOT_CERTIFIED_CHECKOUT("NOT_CERTIFIED_CHECKOUT"), + CHECKIN("checkin"), + CHECKOUT("checkout"), + CERTIFY("certify"); + + private String name; + + private LifecycleStateEnum(String name) { + this.name = name; + } + public String getName() { + return name; + } + + //@formatter:on + public static LifecycleStateEnum findState(String state) { + + for (LifecycleStateEnum lifecycleStateEnum : LifecycleStateEnum.values()) { + if (lifecycleStateEnum.name().equals(state)) { + return lifecycleStateEnum; + } + } + return null; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResourceTypeEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResourceTypeEnum.java new file mode 100644 index 0000000..4d1b88c --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResourceTypeEnum.java @@ -0,0 +1,159 @@ +/*- + * ============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========================================================= + */ + +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.utils.FunctionalCodeUtils; + +/** + * Resource Type Enum + * + * @author mshitrit + * + */ +public enum ResourceTypeEnum { + // TODO remove this from sdc code + //@formatter:off + VFC("VFC"/* (Virtual Function Component)"*/, true), + VF("VF"/* (Virtual Function)" */, false), + CR("CR"/* (Complex Resource"*/, false), + CP("CP"/* (Connection Point)"*/, true), + PNF("PNF"/* (Physical Network Function)" */, false), + CVFC("CVFC"/* Complex Virtual Function Component*/, false), + VL("VL"/* (Virtual Link)"*/, true), + VFCMT("VFCMT"/* (VFC Monitoring Template)"*/, true), + Configuration("Configuration ()", true), + ServiceProxy("ServiceProxy ()", true), + ABSTRACT("Abstract (Generic VFC/VF/PNF/Service Type)", true); + //@formatter:on + private String typeName; + private boolean isAtomicType; + + ResourceTypeEnum(String value, boolean isAtomicType) { + this.typeName = value; + this.isAtomicType = isAtomicType; + } + + public String getValue() { + return typeName; + } + + public boolean isAtomicType() { + return isAtomicType; + } + + public static ResourceTypeEnum findByTypeName(String headerName) { + return FunctionalCodeUtils.findByPredicate(x -> StringUtils.equals(x.getValue(), headerName), values()); + + } + public static ResourceTypeEnum getType(String type) { + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name() + .equals(type)) { + return e; + } + } + return null; + } + + public static ResourceTypeEnum getTypeByName(String type) { + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name() + .equalsIgnoreCase(type)) { + return e; + } + } + return null; + } + + /** + * Returns ResourceTypeEnum matching to received String ignore case + * + * @param type + * @return + */ + public static ResourceTypeEnum getTypeIgnoreCase(String type) { + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name() + .toLowerCase() + .equals(type.toLowerCase())) { + return e; + } + } + return null; + } + + /** + * Checks if enum exist with given type + * + * @param type + * @return + */ + public static boolean containsName(String type) { + + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name() + .equals(type)) { + return true; + } + } + return false; + } + + /** + * Checks if enum exist with given type ignore case + * + * @param type + * @return + */ + public static boolean containsIgnoreCase(String type) { + + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name() + .toLowerCase() + .equals(type.toLowerCase())) { + return true; + } + } + return false; + } + +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResultStatusEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResultStatusEnum.java new file mode 100644 index 0000000..427e310 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResultStatusEnum.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +/** + * Simple Status Enum + * @author ms172g + * + */ +public enum ResultStatusEnum { + SUCCESS, FAIL +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/SdcResponseFieldEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/SdcResponseFieldEnum.java new file mode 100644 index 0000000..b3640fa --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/SdcResponseFieldEnum.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +public enum SdcResponseFieldEnum { + //@formatter:off + SERVICES_LIST("services"), + RESOURCES_LIST("resources"), + + //ICatalogElement Fields + UNIQUE_ID("uniqueId"), + VERSION("version"), + NAME("name"), + RESOURCE_TYPE("resourceType"), + LIFECYCLE_STATE("lifecycleState"), + ICON("icon"), + COMPONENT_TYPE("componentType"), + LAST_UPDATE_DATE("lastUpdateDate"), + CATEGORY("categoryNormalizedName"), + SUB_CATEGORY("subCategoryNormalizedName"), + DISTRIBUTION_STATUS("distributionStatus"); + //@formatter:on + private String jsonName; + + SdcResponseFieldEnum(String jsonName) { + this.jsonName = jsonName; + } + + public String getJsonName() { + return jsonName; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserOperationEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserOperationEnum.java new file mode 100644 index 0000000..b1343cb --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserOperationEnum.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +public enum UserOperationEnum { + CREATE, CHANGE_ROLE, DEACTIVATE +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserRoleEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserRoleEnum.java new file mode 100644 index 0000000..fface92 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserRoleEnum.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +public enum UserRoleEnum { + ADMIN("ADMIN"), DESIGNER("DESIGNER"); + + private String name; + + UserRoleEnum(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserStatusEnum.java b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserStatusEnum.java new file mode 100644 index 0000000..a04f775 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserStatusEnum.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.enums; + +public enum UserStatusEnum { + ACTIVE("active"), + INACTIVE("inactive"); + + private String name; + + UserStatusEnum(String name) { + this.name = name; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/exception/RestrictionAccessFilterException.java b/catalog-facade-ms/src/main/java/org/onap/sdc/exception/RestrictionAccessFilterException.java new file mode 100644 index 0000000..7179394 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/exception/RestrictionAccessFilterException.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.exception; + +public class RestrictionAccessFilterException extends RuntimeException { + + public RestrictionAccessFilterException(Exception exception) { + super(exception); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeFilter.java b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeFilter.java new file mode 100644 index 0000000..f2d6e05 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeFilter.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.filter; + +import org.onap.sdc.security.PortalClient; +import org.onap.sdc.security.filters.RestrictionAccessFilter; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.servlet.annotation.WebFilter; +import java.util.List; + +//TODO find spring filter annotation and change to correct path +@WebFilter(urlPatterns = {"/uicache/v1/followed", "/uicache/v1/catalog"}) +public class FacadeFilter extends RestrictionAccessFilter { + + private static final Logger LOG = Logger.getLogger(FacadeFilter.class); + + + public FacadeFilter(FilterConfiguration configuration, FacadeUserThreadLocalImpl facadeUserThreadLocal, + PortalClient portalClient) { + super(configuration, facadeUserThreadLocal, portalClient); + LOG.debug("Printing excludedUrls"); + List excludedUrls = configuration.getExcludedUrls(); + excludedUrls.stream().forEach(u->LOG.debug("excludedUrl: {}", u)); + } +} + + + diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeUserThreadLocalImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeUserThreadLocalImpl.java new file mode 100644 index 0000000..fe41a09 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeUserThreadLocalImpl.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.filter; + +import org.onap.sdc.enums.UserRoleEnum; +import org.onap.sdc.impl.users.UserElement; +import org.onap.sdc.security.AuthenticationCookie; +import org.onap.sdc.security.IUsersThreadLocalHolder; +import org.springframework.stereotype.Component; + +import java.util.Optional; +import java.util.Set; + +@Component +public class FacadeUserThreadLocalImpl implements IUsersThreadLocalHolder { + private static final ThreadLocal currentThreadUserElement = new ThreadLocal<>(); + @Override + public void setUserContext(AuthenticationCookie authenticationCookie) { + String role = ""; + UserElement userElement = new UserElement(); + userElement.setUserId(authenticationCookie.getUserID()); + Set roles = authenticationCookie.getRoles(); + Optional roleOptional = roles.stream().findFirst(); + roleOptional.ifPresent(r->userElement.setRole(UserRoleEnum.valueOf(r.toUpperCase()))); + currentThreadUserElement.set(userElement); + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FilterConfiguration.java b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FilterConfiguration.java new file mode 100644 index 0000000..d380c5c --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/FilterConfiguration.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.filter; + +import com.google.common.annotations.VisibleForTesting; +import lombok.Data; +import org.apache.commons.lang3.StringUtils; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.sdc.security.ISessionValidationFilterConfiguration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.security.InvalidParameterException; +import java.util.Arrays; +import java.util.List; + +@Component +public class FilterConfiguration implements ISessionValidationFilterConfiguration { + + private static final String PROPERTY_NOT_SET = "%s property value is not set in portal.properties file"; + + @Value("${authCookie.securityKey}") + private String securityKey; + @Value("${authCookie.maxSessionTimeOut}") + private long maxSessionTimeOut; + @Value("${authCookie.sessionIdleTimeOut}") + private long sessionIdleTimeOut; + @Value("${authCookie.cookieName}") + private String cookieName; + @Value("${authCookie.redirectURL}") + private String redirectURL; + @Value("${authCookie.excludedUrls}") + private String[] excludedUrls; + @Value("${authCookie.domain}") + private String domain; + @Value("${authCookie.path}") + private String path; + @Value("${authCookie.isHttpOnly}") + private boolean isHttpOnly; + + @VisibleForTesting + String getPortalProperty(String key) { + String value = PortalApiProperties.getProperty(key); + if (StringUtils.isEmpty(value)) { + throw new InvalidParameterException(String.format(PROPERTY_NOT_SET, key)); + } + return value; + } + + @Override + public String getSecurityKey() { + return securityKey; + } + + @Override + public long getMaxSessionTimeOut() { + return maxSessionTimeOut; + } + + @Override + public long getSessionIdleTimeOut() { + return sessionIdleTimeOut; + } + + @Override + public String getCookieName() { + return cookieName; + } + + @Override + public String getCookieDomain() { + return domain; + } + + @Override + public String getCookiePath() { + return path; + } + + @Override + public boolean isCookieHttpOnly() { + return isHttpOnly; + } + + @Override + public String getRedirectURL() { + return redirectURL; + } + + @Override + public List getExcludedUrls() { + return Arrays.asList(excludedUrls); + } + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/filter/PortalConfiguration.java b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/PortalConfiguration.java new file mode 100644 index 0000000..cf062cd --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/filter/PortalConfiguration.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.filter; + +import org.onap.sdc.security.IPortalConfiguration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class PortalConfiguration implements IPortalConfiguration { + @Value("${portal.portal.api.prefix}") + private String portalApiPrefix; + @Value("${portal.max.idle.time}") + private long maxIdleTime; + @Value("${portal.user.attribute.name}") + private String userAttributeName; + @Value("${portal.use_rest_for_functional_menu}") + private boolean useRestForFunctionalMenu; + @Value("${portal.portal.api.impl.class}") + private String portalApiImplClass; + @Value("${portal.role_access_centralized}") + private String roleAccessCentralized; + @Value("${portal.ecomp_redirect_url}") + private String ecompRedirectUrl; + @Value("${portal.ecomp_rest_url}") + private String ecompRestUrl; + @Value("${portal.ueb_listeners_enable}") + private boolean uebListenersEnable; + + @Value("${portal.portal_user}") + private String portalUser; + @Value("${portal.portal_pass}") + private String portalPass; + @Value("${portal.portal_app_name}") + private String portalAppName; + @Value("${portal.ueb_app_key}") + private String uebAppKey; + @Value("${portal.aafNamespace}") + private String aafNamespace; + + @Value("${portal.auth_namespace}") + private String auth_namespace; + @Value("${portal.csp_cookie_name}") + private String csp_cookie_name; + @Value("${portal.csp_gate_keeper_prod_key}") + private String csp_gate_keeper_prod_key; + @Value("${portal.ext_req_connection_timeout}") + private String ext_req_connection_timeout; + @Value("${portal.ext_req_read_timeout}") + private String ext_req_read_timeout; + + @Override + public String getPortalApiPrefix() { + return portalApiPrefix; + } + + @Override + public long getMaxIdleTime() { + return maxIdleTime; + } + + @Override + public String getUserAttributeName() { + return userAttributeName; + } + + @Override + public boolean IsUseRestForFunctionalMenu() { + return useRestForFunctionalMenu; + } + + @Override + public String getPortalApiImplClass() { + return portalApiImplClass; + } + + @Override + public String getRoleAccessCentralized() { + return roleAccessCentralized; + } + + @Override + public boolean getUebListenersEnable() { + return uebListenersEnable; + } + + @Override + public String getEcompRedirectUrl() { + return ecompRedirectUrl; + } + + @Override + public String getEcompRestUrl() { + return ecompRestUrl; + } + + @Override + public String getPortalUser() { + return portalUser; + } + + @Override + public String getPortalPass() { + return portalPass; + } + + @Override + public String getPortalAppName() { + return portalAppName; + } + + @Override + public String getUebAppKey() { + return uebAppKey; + } + + @Override + public String getAafNamespace() { + return aafNamespace; + } + + @Override + public String getAuthNamespace() { + return auth_namespace; + } + + @Override + public String getCspCookieName() { + return csp_cookie_name; + } + + @Override + public String getCspGateKeeperProdKey() { + return csp_gate_keeper_prod_key; + } + + @Override + public String getExtReqConnectionTimeout() { + return ext_req_connection_timeout; + } + + @Override + public String getExtReqReadTimeout() { + return ext_req_read_timeout; + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/CatalogFacadeHealth.java b/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/CatalogFacadeHealth.java new file mode 100644 index 0000000..83283c6 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/CatalogFacadeHealth.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.healthcheck; + +import org.onap.sdc.api.IHealthCheckBuilder; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +public class CatalogFacadeHealth implements IHealthCheckBuilder { + private static final Logger LOG = Logger.getLogger(CatalogFacadeHealth.class); + + @Value("${health.mandatory.services}") + private List mandatoryServices; + + @Value("${info.app.version}") + private String version; + + @Autowired + DmaapHealth dmaapHealth; + + public static final String HC_COMPONENT_NAME = "CATALOG_FACADE_MS"; + + @Override + public HealthCheckInfo getHealthCheckInfo() { + HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_NAME, HealthCheckInfo.HealthCheckStatus.UP, version, CatalogFacadeMsStatusDescription.OK.getDescription()); + + HealthCheckInfo dmaapHealthCheckInfo = dmaapHealth.getHealthCheckInfo(); + if (isDmaapMandatory() + && HealthCheckInfo.HealthCheckStatus.UP != dmaapHealthCheckInfo.getHealthCheckStatus()) { + //change the HC status if DMAAP HC is mandatory and it is DOWN/UNKNOWN + healthCheckInfo.setHealthCheckStatus(HealthCheckInfo.HealthCheckStatus.DOWN); + healthCheckInfo.setDescription(CatalogFacadeMsStatusDescription.DOWN.getDescription()); + } + LOG.debug(HC_COMPONENT_NAME + " health check info: {}", healthCheckInfo); + return healthCheckInfo; + } + + private boolean isDmaapMandatory() { + return mandatoryServices.indexOf(DmaapHealth.HC_COMPONENT_DMAAP) != -1; + + } + + public enum CatalogFacadeMsStatusDescription { + OK("OK"), UNAVAILABLE("Microservice is not available"),DOWN("DOWN"); + + private String desc; + CatalogFacadeMsStatusDescription (String desc) { + this.desc = desc; + } + public String getDescription() { + return desc; + } + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/DmaapHealth.java b/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/DmaapHealth.java new file mode 100644 index 0000000..36863f4 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/DmaapHealth.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.healthcheck; + + +import org.onap.sdc.api.IHealthCheckBuilder; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +@Component +public class DmaapHealth implements IHealthCheckBuilder { + + public static final String HC_COMPONENT_DMAAP = "DMAAP"; + private static final Logger LOG = Logger.getLogger(DmaapHealth.class); + + private volatile HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + + public enum HealthCheckInfoResult { + OK(new HealthCheckInfo(HC_COMPONENT_DMAAP, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(HC_COMPONENT_DMAAP, HealthCheckInfo.HealthCheckStatus.UNKNOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())), + DOWN(new HealthCheckInfo(HC_COMPONENT_DMAAP, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription())); + + private HealthCheckInfo healthCheckInfo; + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + } + public enum DmaapStatusDescription { + OK("OK"), UNAVAILABLE("Dmaap is not available"),DOWN("DOWN"), NOT_CONFIGURED("Dmaap configuration is missing/wrong "); + + private String desc; + DmaapStatusDescription(String desc) { + this.desc = desc; + } + public String getDescription() { + return desc; + } + + } + + public void report(HealthCheckInfoResult infoResult) { + healthCheckInfo = infoResult.getHealthCheckInfo(); + LOG.debug(HC_COMPONENT_DMAAP + " health check info: {}", healthCheckInfo); + } + + @Override + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/HealthCheckInfo.java b/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/HealthCheckInfo.java new file mode 100644 index 0000000..1c5ec4b --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/HealthCheckInfo.java @@ -0,0 +1,88 @@ +/*- + * ============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========================================================= + */ + +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.healthcheck; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +@Data +public class HealthCheckInfo { + @JsonProperty("healthCheckComponent") + private String healthCheckComponent; + @JsonProperty("healthCheckStatus") + private HealthCheckStatus healthCheckStatus; + @JsonProperty("version") + private String version; + @JsonProperty("description") + private String description; + @JsonProperty("componentsInfo") + private List componentsInfo; + + public static final String COMPONENTS_INFO_KEY = "componentsInfo"; + + public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, + String version, String description) { + this.healthCheckComponent = healthCheckComponent; + this.healthCheckStatus = healthCheckStatus; + this.version = version; + this.description = description; + } + + public HealthCheckInfo(String healthCheckComponent, HealthCheckStatus healthCheckStatus, + String version, String description, List componentsInfo) { + this.healthCheckComponent = healthCheckComponent; + this.healthCheckStatus = healthCheckStatus; + this.version = version; + this.description = description; + this.componentsInfo = componentsInfo; +} + + public HealthCheckInfo() { + } + + public enum HealthCheckStatus { + UP, DOWN, UNKNOWN + } + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/http/IResponse.java b/catalog-facade-ms/src/main/java/org/onap/sdc/http/IResponse.java new file mode 100644 index 0000000..efa7723 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/http/IResponse.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.http; + +import org.apache.http.client.methods.CloseableHttpResponse; + +/** + * Represents a Simple Http Response + * @author ms172g + * + */ +public interface IResponse { + /** + * Returns response body or empty string if there is none. + * @return + */ + String getBody(); + /** + * The response message. + * @return + */ + String getMessage(); + /** + * http status code. + * @return + */ + int getStatusCode(); + + + static IResponse buildIResponse(CloseableHttpResponse response, String body) { + return new IResponse() { + + @Override + public int getStatusCode() { + return response.getStatusLine() + .getStatusCode(); + } + + @Override + public String getMessage() { + return response.getStatusLine().getReasonPhrase(); + } + + @Override + public String getBody() { + return body; + } + }; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/http/ISimpleHttpClient.java b/catalog-facade-ms/src/main/java/org/onap/sdc/http/ISimpleHttpClient.java new file mode 100644 index 0000000..72d073d --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/http/ISimpleHttpClient.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.http; + +import java.util.Map; + +/** + * Simple Http Client + * @author ms172g + * + */ +public interface ISimpleHttpClient { + + /** + * Perform Get Request on url.
+ * Returns a pair with the Response object (already closed) and the Response Body.
+ * @param url + * @param headers + * @return + */ + IResponse doGet(String url, Map headers); + + /** + * Perform Post Request on url.
+ * Returns a pair with the Response object (already closed) and the Response Body.
+ * @param url + * @param body + * @param headers + * @return + */ + IResponse doPost(String url, String body, Map headers); + + IResponse doPut(String url, String body, Map headers); + /** + * Perform Delete Request on url.
+ * Returns the Response object .
+ * @param url + * @param headers + * @return + */ + IResponse doDelete(String url, Map headers); + +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/http/SimpleHttpClient.java b/catalog-facade-ms/src/main/java/org/onap/sdc/http/SimpleHttpClient.java new file mode 100644 index 0000000..6dedfb6 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/http/SimpleHttpClient.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.http; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpRequest; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.onap.sdc.impl.BeDataRetrieverImpl; +import org.onap.sdc.logger.FacadeLogUtils; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import java.util.Map; +import java.util.Optional; + +import static java.lang.String.format; +import static org.apache.commons.collections4.MapUtils.isEmpty; +import static org.onap.sdc.logger.FacadeLogUtils.*; +import static org.onap.sdc.utils.FunctionalCodeUtils.wrapWithTryCatch; + +@Component +public class SimpleHttpClient implements ISimpleHttpClient { + private static final Logger LOG = Logger.getLogger(SimpleHttpClient.class); + + @Override + public IResponse doGet(String url, Map headers) { + LOG.debug("Sending GET Request to url:{} with Headers: {}", url, headers); + return excecuteRequest(new HttpGet(url), headers); + } + + @Override + public IResponse doPost(String url, String body, Map headers) { + LOG.debug("Sending POST Request to url:{} with Headers: {} and Body: {}", url, headers, body); + + final HttpPost httpPostRequest = new HttpPost(url); + Optional optionalError = wrapWithTryCatch(() -> httpPostRequest.setEntity(new StringEntity(body)), + Boolean.FALSE, serviceNameFromMDC()); + if (optionalError.isPresent()) { + final String errorMessage = format("Error when building post request body from:%s ", body); + LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceNameFromMDC(), fullOptionalData(BE_TARGET_ENTITY, httpPostRequest.getURI().getPath()), errorMessage); + throw new RuntimeException(errorMessage); + } + return excecuteRequest(httpPostRequest, headers); + } + + @Override + public IResponse doPut(String url, String body, Map headers) { + LOG.debug("Sending Put Request to url:{} with Headers: {} and Body: {}", url, headers, body); + + final HttpPut httpPutRequest = new HttpPut(url); + Optional optionalError = wrapWithTryCatch(() -> httpPutRequest.setEntity(new StringEntity(body)), + Boolean.FALSE, serviceNameFromMDC()); + if (optionalError.isPresent()) { + final String errorMessage = format("Error when building put request body from:%s ", body); + LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceNameFromMDC(), fullOptionalData(BE_TARGET_ENTITY, httpPutRequest.getURI().getPath()), errorMessage); + throw new RuntimeException(errorMessage); + } + return excecuteRequest(httpPutRequest, headers); + } + + private void setHeaders(Map headers, HttpRequest httpRequest) { + if (!isEmpty(headers)) { + headers.entrySet() + .stream() + .forEach(entry -> httpRequest.setHeader(entry.getKey(), entry.getValue())); + } + } + + private IResponse excecuteRequest(HttpUriRequest httpRequest, + Map headers) { + setHeaders(headers, httpRequest); + try (CloseableHttpClient client = HttpClients.createMinimal(); + CloseableHttpResponse response = client.execute(httpRequest)) { + String body = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : StringUtils.EMPTY; + LOG.debug("Http {} Request performed to url {}. Status Code is :{}", httpRequest.getMethod(), + httpRequest.getURI() + .toURL() + .toString(), + response.getStatusLine() + .getStatusCode()); + return IResponse.buildIResponse(response, body); + + } catch (Exception e) { + LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, BeDataRetrieverImpl.class.getName(), FacadeLogUtils.fullOptionalData(BE_TARGET_ENTITY, httpRequest.getURI().getPath()), + "Exception Occurred when running request. error message:{}", e.getMessage()); + LOG.debug("Exception Occurred when running request. error message:{}", e); + throw new RuntimeException(e); + } + } + + @Override + public IResponse doDelete(String url, Map headers) { + LOG.debug("Sending DELETE Request to url:{} with Headers: {}", url, headers); + return excecuteRequest(new HttpDelete(url), headers); + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/BeDataRetrieverImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/BeDataRetrieverImpl.java new file mode 100644 index 0000000..e6c98a6 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/BeDataRetrieverImpl.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.sdc.api.IBeDataRetriever; +import org.onap.sdc.http.IResponse; +import org.onap.sdc.http.ISimpleHttpClient; +import org.onap.sdc.logger.FacadeLogUtils; +import org.onap.sdc.security.utils.RestUtils; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; +import org.openecomp.sdc.common.log.elements.LoggerBase; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +import static java.lang.String.format; +import static org.onap.sdc.enums.CustomHeadersEnum.USER_ID; + +@Component +public class BeDataRetrieverImpl implements IBeDataRetriever { + + @Value("${sdc.be.schema}") + private String sdcBeSchema; + + @Value("${sdc.be.host}") + private String sdcBeHost; + + @Value("${sdc.be.port}") + private String sdcBePort; + + @Value("${sdc.userid}") + private String userId; + + @Value("${sdc.authorization.username}") + private String beUsername; + + @Value("${sdc.authorization.password}") + private String bePassword; + + private ISimpleHttpClient httpClient; + + private LogFieldsMdcHandler logFieldsMdcHandler; + + private static final String SDC_GET_CATALOG_QUERY = "%s://%s:%s/sdc2/rest/v1/screen?excludeTypes=VFCMT"; + private static final String SDC_GET_CATALOG_ARCHIVE_QUERY = "%s://%s:%s/sdc2/rest/v1/catalog/archive"; + private static final String SDC_GET_CATALOG_UPDATE_TIME = "%s://%s:%s/sdc2/rest/v1/catalogUpdateTime"; + + @Autowired + public BeDataRetrieverImpl(ISimpleHttpClient httpClient) { + this.httpClient = httpClient; + logFieldsMdcHandler = LogFieldsMdcHandler.getInstance(); + } + + @Override + public String getCatalogResponseBody(){ + return sendGetReqToBE(SDC_GET_CATALOG_QUERY); + } + + @Override + public String getUpdateTimeResponseBody() { + return sendGetReqToBE(SDC_GET_CATALOG_UPDATE_TIME); + } + + @Override + public String getArchiveCatalogResponseBody() { + return sendGetReqToBE(SDC_GET_CATALOG_ARCHIVE_QUERY); + } + + private String sendGetReqToBE(String path) { + return sendGetReqToBE(path, this.userId).getBody(); + } + + private IResponse sendGetReqToBE(String path, String userId) { + Map headers = new HashMap<>(); + setHeaders(headers, userId); + setMDCFields(headers); + return httpClient.doGet( + format(path, sdcBeSchema, sdcBeHost, sdcBePort), headers); + } + + private void setHeaders(Map headers, String userId) { + headers.put(USER_ID.getHeaderName(), userId); + headers.put(ONAPLogConstants.Headers.REQUEST_ID, LoggerBase.generateKeyRequestId()); + headers.put(ONAPLogConstants.Headers.PARTNER_NAME, FacadeLogUtils.PARTNER_NAME); + RestUtils.addBasicAuthHeaderWithEncryptedPassword(headers, beUsername, bePassword); + } + + private void setMDCFields(Map headers) { + logFieldsMdcHandler.setKeyRequestId(headers.get(ONAPLogConstants.Headers.REQUEST_ID)); + logFieldsMdcHandler.setPartnerName(headers.get(ONAPLogConstants.Headers.PARTNER_NAME)); + } + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/BusinessLogicImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/BusinessLogicImpl.java new file mode 100644 index 0000000..9c7e509 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/BusinessLogicImpl.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import org.onap.sdc.api.IBusinessLogic; +import org.onap.sdc.api.ICacheHandler; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.api.IComponentMessage; +import org.onap.sdc.api.IMessageQueueHandlerConsumer; +import org.onap.sdc.api.IStatus; +import org.onap.sdc.enums.ResultStatusEnum; +import org.onap.sdc.impl.message.ComponentMessage; +import org.onap.sdc.impl.message.DmaapConsumer; +import org.onap.sdc.utils.MessageUtils; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.io.IOException; +import java.util.List; + +@Component +public class BusinessLogicImpl implements IBusinessLogic { + private static final Logger LOG = Logger.getLogger(BusinessLogicImpl.class); + private ICacheHandler cacheHandler; + private IMessageQueueHandlerConsumer messageHandler; + + @Autowired + public BusinessLogicImpl(ICacheHandler cacheHandler, IMessageQueueHandlerConsumer messageHandler) { + this.cacheHandler = cacheHandler; + this.messageHandler = messageHandler; + } + + @PostConstruct + @Override + public IStatus init() { + LOG.debug("Start initializing"); + final IStatus initStatus = messageHandler.init(this::doOnMessageReceive); + LOG.debug("initialized with status {}", initStatus.getResultStatus()); + return initStatus; + } + + @Override + public List getCatalogElements(ICatalogQuery query) { + LOG.debug("Start handling Query: {}", query); + List response = cacheHandler.getCatalogElements(query); + LOG.debug("Response size: {}", response.size()); + return response; + } + + @Override + public IStatus doOnMessageReceive(String message) { + LOG.debug("Start handling Message: {}", message); + IStatus status; + + try { + IComponentMessage componentMessage = MessageUtils.buildFromMessage(message, ComponentMessage.class); + status = cacheHandler.handleComponentMessage(componentMessage); + } + + catch(IOException e) { + LOG.error(EcompLoggerErrorCode.DATA_ERROR, DmaapConsumer.class.getName(), new ErrorLogOptionalData(),"The exception occurred upon parsing message {}. {}", message, e.getMessage()); + LOG.debug("The exception occurred upon parsing DMAAP message: ", e); + status = IStatus.getFailStatus(); + } + + if (status.getResultStatus() != ResultStatusEnum.SUCCESS) { + LOG.error(EcompLoggerErrorCode.DATA_ERROR, DmaapConsumer.class.getName(),new ErrorLogOptionalData(),"Error while handling Message {}, Status Returned is {} ", message, status); + } + return status; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheHandlerImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheHandlerImpl.java new file mode 100644 index 0000000..427c002 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheHandlerImpl.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import static java.util.stream.Stream.concat; +import static org.apache.commons.collections4.CollectionUtils.isEmpty; +import static org.onap.sdc.api.ICatalogElement.buildFromSdcHttpResponse; +import static org.onap.sdc.api.IStatus.getFailStatus; +import static org.onap.sdc.api.IStatus.getSuccessStatus; +import static org.onap.sdc.utils.FunctionalCodeUtils.wrapWithTryCatch; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.BinaryOperator; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.NotImplementedException; +import org.onap.sdc.api.IBeDataRetriever; +import org.onap.sdc.api.ICache; +import org.onap.sdc.api.ICacheHandler; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.api.ICatalogUpdateTimestamp; +import org.onap.sdc.api.ICatalogUpdateTimestampContainer; +import org.onap.sdc.api.IComponentMessage; +import org.onap.sdc.api.IStatus; +import org.onap.sdc.enums.ChangeTypeEnum; +import org.onap.sdc.impl.message.DmaapConsumer; +import org.onap.sdc.logger.FacadeLogUtils; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.onap.sdc.utils.Wrapper; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.google.common.annotations.VisibleForTesting; + +@Component +public class CacheHandlerImpl implements ICacheHandler { + private static final Logger LOG = Logger.getLogger(ICacheHandler.class); + + @Autowired + private ICache cache; + @Autowired + private IBeDataRetriever beDataRetriever; + @Autowired + private ICatalogUpdateTimestampContainer catalogUpdateTimestampContainer; + + @PostConstruct + @Override + public IStatus init() { + LogFieldsMdcHandler.getInstance().addInfoForErrorAndDebugLogging(FacadeLogUtils.PARTNER_NAME); + LOG.debug("Start initializing"); + IStatus status = wrapWithTryCatch(()->loadCacheFromSdcBe(), getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + LOG.debug("initialized with status {}", status.getResultStatus().name()); + return status; + } + + private void initLogMDCs() throws IOException { + LogFieldsMdcHandler.getInstance().addInfoForErrorAndDebugLogging(FacadeLogUtils.PARTNER_NAME); + LogFieldsMdcHandler.getInstance().setKeyRequestId(LogFieldsMdcHandler.getInstance().getKeyRequestId()); + } + + private void loadCacheFromSdcBe() throws IOException { + initLogMDCs(); + LOG.debug("Start to load cache from SDC BE"); + Map> nonArchivedComponents = buildFromSdcHttpResponse( + beDataRetriever.getCatalogResponseBody()); + + Map> archivedComponents = buildFromSdcHttpResponse( + beDataRetriever.getArchiveCatalogResponseBody()); + //Set Archive Flag + archivedComponents.values().stream().flatMap(Collection::stream).forEach(e -> e.setArchived(true)); + + // Joins Archived and Non Archived to a single map + final BinaryOperator> mergeFunction = (listOne, + listTwo) -> concat(listOne.stream(), listTwo.stream()).collect(Collectors.toList()); + + Map> joinedComponents = concat(nonArchivedComponents.entrySet() + .stream(), + archivedComponents.entrySet() + .stream()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, mergeFunction)); + + cache.fillCacheSafety(joinedComponents.values().stream().flatMap(List::stream).collect(Collectors.toList())); + // update timestamp - it might be updated during the time the cache has + // being reloaded + catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest( + ICatalogUpdateTimestamp.buildFromHttpResponse(beDataRetriever.getUpdateTimeResponseBody())); + } + + + public IStatus createCatalogElementInCache(ICatalogElement element) { + return wrapWithTryCatch(() -> cache.put(element), IStatus.getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + } + + + public IStatus updateCatalogElementInCache(ICatalogElement element) { + return wrapWithTryCatch(() -> cache.update(element), IStatus.getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + } + + + + @Override + public IStatus handleRestoreMessage(ICatalogElement element) { + + return wrapWithTryCatch(() -> cache.archiveRestore(false, element), IStatus.getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + } + + @Override + public IStatus handleArchiveMessage(ICatalogElement element) { + + return wrapWithTryCatch(() -> cache.archiveRestore(true, element), IStatus.getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + } + + + @Override + public IStatus handleLifecycleMessage(ICatalogElement element) { + + return wrapWithTryCatch(() -> cache.updateOrCreate(element), IStatus.getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + } + + + @Override + public IStatus handleDeleteMessage(ICatalogElement element) { + return wrapWithTryCatch(() -> cache.evict(element), IStatus.getFailStatus(), CacheHandlerImpl.class.getName()) + .orElse(getSuccessStatus()); + } + + @Override + public IStatus handleComponentMessage(IComponentMessage message) { + if (message == null || message.getChangeType() == null) { + LOG.error(EcompLoggerErrorCode.DATA_ERROR, DmaapConsumer.class.getName(), new ErrorLogOptionalData(), + "Illegal message or change type received on message: {}", message); + return getFailStatus(); + } + + /*if (ignoreNotification(message.getCatalogUpdateTimestamp())) { + // this notification should not be processed: + // all catalog data is already received either right now or + // previously via BE HTTP request response + return getSuccessStatus(); + }*/ + return processMessageByChangeType(message); + } + + @Override + public List getCatalogElements(ICatalogQuery query) { + return cache.get(buildJoinedPredicate(query.getQueryFilters())); + } + + @Override + public IStatus loadCatalogIfNotificationsLost() { + return wrapWithTryCatch(()->loadCacheFromSdcBe(), getFailStatus(), CacheHandlerImpl.class.getName()).orElse(getSuccessStatus()); + } + + + private IStatus processMessageByChangeType(IComponentMessage message) { + final ChangeTypeEnum operation = message.getChangeType(); + + switch (operation) { + case LIFECYCLE: + return handleLifecycleMessage(message); + case DELETE: + return handleDeleteMessage(message); + case ARCHIVE: + return handleArchiveMessage(message); + case RESTORE: + return handleRestoreMessage(message); + default: + LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, CacheHandlerImpl.class.getName(), new ErrorLogOptionalData(), "Unknown message change type: {}", + message.getChangeType()); + throw new NotImplementedException(String.format("Not Implemented for %s with value %s", + ChangeTypeEnum.class.getName(), message.getChangeType())); + } + } + + + + @VisibleForTesting + boolean reloadCatalogIfRequired(ICatalogUpdateTimestamp catalogUpdateTimestamp, boolean asPerNotification) { + if (asPerNotification && catalogUpdateTimestampContainer.updatesLostAsPerNotification(catalogUpdateTimestamp) + || !asPerNotification + && catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(catalogUpdateTimestamp)) { + LOG.debug("Some update notifications seem to be lost - load SDC Catalog from BE"); + return wrapWithTryCatch(this::loadCacheFromSdcBe, IStatus.getFailStatus(), CacheHandlerImpl.class.getName()) + .orElse(getSuccessStatus()) == getSuccessStatus(); + } + return false; + } + + private void reloadCatalogIfRequired() throws IOException { + reloadCatalogIfRequired( + ICatalogUpdateTimestamp.buildFromHttpResponse(beDataRetriever.getUpdateTimeResponseBody()), false); + } + + private Predicate buildJoinedPredicate(List> predicates) { + if (isEmpty(predicates)) { + return element -> true; + } else { + final Wrapper> predicateWrapper = new Wrapper<>(x -> true); + + predicates.stream() + .forEach(currPred -> predicateWrapper.setInnerElement(predicateWrapper.getInnerElement() + .and(currPred))); + return predicateWrapper.getInnerElement(); + } + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheImpl.java new file mode 100644 index 0000000..1075d85 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheImpl.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import org.onap.sdc.api.ICache; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ILatestElements; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; +import static org.onap.sdc.enums.LifecycleStateEnum.*; + +@Component +public class CacheImpl implements ICache { + + private Map cache = new ConcurrentHashMap<>(); + private static final Logger LOG = Logger.getLogger(CacheImpl.class); + private static final List nonCertifiedStates = + Arrays.asList(NOT_CERTIFIED_CHECKIN, CHECKIN, NOT_CERTIFIED_CHECKOUT, CHECKOUT); + private static final List certifiedStates = + Arrays.asList(CERTIFIED, CERTIFY); + + @Override + public ICache evict(ICatalogElement... values) { + Collection removedItems = new HashSet<>(); + for (ICatalogElement element : values) { + String invariantUUID = element.getInvariantUUID(); + if(cache.containsKey(invariantUUID)){ + ILatestElements cacheElement = cache.get(invariantUUID); + LifecycleStateEnum state = element.getLifecycleState(); + if( state.equals(LifecycleStateEnum.CERTIFIED) || state.equals(LifecycleStateEnum.CERTIFY)){ + cacheElement.setCertifiedElement(null); + }else{ + cacheElement.setNonCertifiedElement(null); + } + if(cacheElement.isEmpty()){ + cache.remove(cacheElement); + } + removedItems.add(element); + } + } + LOG.debug("Removed {} items", removedItems.size()); + if (values.length > removedItems.size()) + LOG.debug("Couldn't remove all items"); + + return this; + } + + @Override + public ICache put(ICatalogElement... values) { + return put(cache, values); + } + + ICache put(Map map, ICatalogElement... values) { + LOG.debug("Start to add element to cache"); + Collection overridden = new HashSet<>(); + for (ICatalogElement element : values) { + ILatestElements newElement = map.get(element.getInvariantUUID()); + + if (newElement == null) { + newElement = new LatestElementsImpl(); + } + setElementState(element, newElement); + ILatestElements prev = map.put(element.getInvariantUUID(), newElement); + if (prev != null) { + overridden.add(prev); + } + } + + if (isNotEmpty(overridden)) { + LOG.debug("Overridden {} elements => {}", overridden.size(), overridden); + } + return this; + } + + private void setElementState(ICatalogElement element, ILatestElements newElement) { + LifecycleStateEnum elementLifecycleState = element.getLifecycleState(); + + if (nonCertifiedStates.contains(elementLifecycleState)) { + newElement.setNonCertifiedElement(element); + } else if (certifiedStates.contains(elementLifecycleState)) { + newElement.setCertifiedElement(element); + } else { + LOG.warn("Invalid lifecycle state of resource {}. Version: {}", element.getName() ,element.getVersion()); + } + } + + /* update only if object exists */ + @Override + public boolean update(ICatalogElement element) { + if (!cache.containsKey(element.getUniqueId())) + return false; + put(element); + return true; + } + + @Override + public boolean updateOrCreate(ICatalogElement element){ + LifecycleStateEnum lifecycleStateEnum = element.getLifecycleState(); + switch(lifecycleStateEnum){ + case NOT_CERTIFIED_CHECKIN: + case CHECKIN: + if (!cache.containsKey(element.getInvariantUUID())) + return false; + cache.get(element.getInvariantUUID()).setNonCertifiedElement(element); + return true; + case NOT_CERTIFIED_CHECKOUT: + case CHECKOUT: + if (!cache.containsKey(element.getInvariantUUID())){ + ILatestElements newElement = new LatestElementsImpl (); + cache.put(element.getInvariantUUID(), newElement); + } + cache.get(element.getInvariantUUID()).setNonCertifiedElement(element); + return true; + case CERTIFIED: + case CERTIFY: + ILatestElements newElement; + if (!cache.containsKey(element.getInvariantUUID())){ + newElement = new LatestElementsImpl (); + cache.put(element.getInvariantUUID(), newElement); + } + newElement = cache.get(element.getInvariantUUID()); + newElement.setCertifiedElement(element); + newElement.setNonCertifiedElement(null); + return true; + default: + return false; + } + + } + + @Override + public CacheImpl clear() { + cache.clear(); + + return this; + } + + /* + * @return all elements in the cache matching the filter predicate + */ + @Override + public List get(Predicate filterPredicate) { + return isNotEmpty(cache.values()) ? cache.values() + .stream() + .flatMap( latest -> latest.getAllElements().stream()) + .filter(filterPredicate) + .collect(Collectors.toList()) : Collections.emptyList(); + } + + /* + * @return all elements in the cache matching the filter predicate + */ + @Override + public List get(Predicate filterPredicate, Comparator orderBy) { + return isNotEmpty(cache.values()) ? cache.values() + .stream() + .flatMap( latest -> latest.getAllElements().stream()) + .filter(filterPredicate) + .sorted(orderBy) + .collect(Collectors.toList()) : Collections.emptyList(); + + } + + @Override + public int count() { + return cache.size(); + } + + @Override + public boolean isEmpty() { + return cache.isEmpty(); + } + + @Override + public void fillCacheSafety(List catalogList) { + // fillMap and replace the cache - it has to be atomic operation + // so that it won't be needed to synchronize cleanup and fill the cache + // up + LOG.debug("Start to fill cache"); + Map newCache = new ConcurrentHashMap<>(); + catalogList.forEach(c -> put(newCache, c)); + // atomic replacement of the old cache content by the new one + this.cache = newCache; + LOG.debug("Cache filling is complete"); + } + + // testing operator + public void leftShift(ICatalogElement... elements) { + put(elements); + } + + @Override + public boolean archiveRestore(boolean isArchive, ICatalogElement element) { + if (!cache.containsKey(element.getInvariantUUID())){ + return false; + } + ILatestElements latestElements = cache.get(element.getInvariantUUID()); + if(latestElements.getNonCertifiedElement() != null){ + latestElements.getNonCertifiedElement().setArchived(isArchive); + } + if(latestElements.getCertifiedElement() != null){ + latestElements.getCertifiedElement().setArchived(isArchive); + } + return true; + } + + public Map getCache() { + return cache; + } + + public void setCache(Map cache) { + this.cache = cache; + } +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogElementImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogElementImpl.java new file mode 100644 index 0000000..fe64996 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogElementImpl.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICategory; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import java.util.List; + +@JsonInclude(value = JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +@Data +public class CatalogElementImpl implements ICatalogElement { + + + private static final long serialVersionUID = -7069561395745786141L; + @JsonProperty("uniqueId") + protected String uniqueId; + @JsonProperty("uuid") + protected String uuid; + // View + @JsonProperty("name") + protected String name; + @JsonProperty("resourceType") + protected ResourceTypeEnum resourceType; + @JsonProperty("version") + protected String version; + @JsonProperty("lifecycleState") + protected LifecycleStateEnum lifecycleState; + @JsonProperty("icon") + protected String icon; + + // Filtered + @JsonProperty("componentType") + protected ComponentTypeEnum componentType; + @JsonProperty("lastUpdateDate") + protected long lastUpdateDate; + @JsonProperty("categoryNormalizedName") + protected String category; + @JsonProperty("subCategoryNormalizedName") + protected String subCategory; + @JsonIgnore + @JsonProperty("distributionStatus") + protected DistributionStatusEnum distributionStatus; + @JsonProperty("archived") + protected boolean archived; + + @JsonProperty("systemName") + protected String systemName; + @JsonProperty("invariantUUID") + protected String invariantUUID; + @JsonProperty("description") + protected String description; + @JsonProperty("tags") + private List tags; + @JsonProperty("isHighestVersion") + protected Boolean isHighestVersion; + + private List categories; + + public void setCategories(List categories) { + this.categories = categories; + } + + + @JsonProperty("categories") + @Override + public List getCategories() { + return categories; + } + + @JsonProperty("lastUpdaterUserId") + protected String lastUpdaterUserId; + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUIElementImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUIElementImpl.java new file mode 100644 index 0000000..e4d3a52 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUIElementImpl.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import java.util.List; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogUIElement; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; +@Data +public class CatalogUIElementImpl implements ICatalogUIElement { + @JsonProperty("uniqueId") + protected String uniqueId; + + // View + @JsonProperty("name") + protected String name; + @JsonProperty("resourceType") + protected ResourceTypeEnum resourceType; + @JsonProperty("version") + protected String version; + @JsonProperty("lifecycleState") + protected LifecycleStateEnum lifecycleState; + @JsonProperty("icon") + protected String icon; + + // Filtered + @JsonProperty("componentType") + protected ComponentTypeEnum componentType; + @JsonProperty("lastUpdateDate") + protected long lastUpdateDate; + @JsonProperty("categoryNormalizedName") + protected String category; + @JsonProperty("subCategoryNormalizedName") + protected String subCategory; + @JsonIgnore + @JsonProperty("distributionStatus") + protected DistributionStatusEnum distributionStatus; + + @JsonProperty("tags") + protected List tags; + @JsonProperty("lastUpdaterUserId") + protected String lastUpdaterUserId; + + public static ICatalogUIElement buildUIElement(ICatalogElement element) { + CatalogUIElementImpl ret = new CatalogUIElementImpl(); + ret.setFields(element); + return ret; + } + + protected void setFields(ICatalogElement element){ + setUniqueId(element.getUniqueId()); + setName(element.getName()); + setResourceType(element.getResourceType()); + setVersion(element.getVersion()); + setLifecycleState(element.getLifecycleState()); + setIcon(element.getIcon()); + setComponentType(element.getComponentType()); + setLastUpdateDate(element.getLastUpdateDate()); + setCategory(element.getCategory()); + setSubCategory(element.getSubCategory()); + setDistributionStatus(element.getDistributionStatus()); + setTags(element.getTags()); + setLastUpdaterUserId(element.getLastUpdaterUserId()); + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUpdateValidatorTaskImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUpdateValidatorTaskImpl.java new file mode 100644 index 0000000..1d3b016 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUpdateValidatorTaskImpl.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import static org.onap.sdc.utils.FunctionalCodeUtils.runMethodWithTimeOut; + +import org.onap.sdc.api.ICacheHandler; +import org.onap.sdc.api.ICatalogUpdateValidatorTask; +import org.onap.sdc.logger.FacadeLogUtils; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +public class CatalogUpdateValidatorTaskImpl implements ICatalogUpdateValidatorTask { + private static final Logger LOG = Logger.getLogger(CatalogUpdateValidatorTaskImpl.class); + private ICacheHandler cacheHandler; + + @Autowired + public CatalogUpdateValidatorTaskImpl(ICacheHandler cacheHandler) { + this.cacheHandler = cacheHandler; + } + + @Override + @Scheduled(fixedRateString = "${scheduling.job.rate.updateCatalogTimestamp}") + public void run() { + LogFieldsMdcHandler.getInstance().addInfoForErrorAndDebugLogging(FacadeLogUtils.PARTNER_NAME); + LOG.debug("Start awaiting data from be"); + //Limit time to try to fetch Catalog From BE to 60 Second + runMethodWithTimeOut(()->cacheHandler.loadCatalogIfNotificationsLost(), + 1000L * 60, CatalogUpdateValidatorTaskImpl.class.getName()); + LOG.debug("Stop awaiting data from be"); + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/Category.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/Category.java new file mode 100644 index 0000000..664cacc --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/Category.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import org.onap.sdc.api.ICategory; + +import java.util.List; + +@JsonInclude(value = JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +@Data +public class Category implements ICategory { + + @JsonProperty("name") + private String name; + @JsonProperty("normalizedName") + private String normalizedName; + @JsonProperty("uniqueId") + private String uniqueId; + @JsonProperty("icons") + private List icons; + private List subcategories; + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getNormalizedName() { + return normalizedName; + } + + public void setNormalizedName(String normalizedName) { + this.normalizedName = normalizedName; + } + + @Override + public String getUniqueId() { + return uniqueId; + } + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + @Override + public List getIcons() { + return icons; + } + + public void setIcons(List icons) { + this.icons = icons; + } + + @JsonProperty("subcategories") + @Override + public List getSubcategories() { + return subcategories; + } + + public void setSubcategories(List subcategories) { + this.subcategories = subcategories; + } + + + + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/LatestElementsImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/LatestElementsImpl.java new file mode 100644 index 0000000..0edb38a --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/LatestElementsImpl.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ILatestElements; + +public class LatestElementsImpl implements ILatestElements{ + private ICatalogElement nonCertifiedElement; + private ICatalogElement certifiedElement; + + @Override + public ICatalogElement getNonCertifiedElement() { + return nonCertifiedElement; + } + + @Override + public ICatalogElement getCertifiedElement() { + return certifiedElement; + } + + @Override + public void setNonCertifiedElement(ICatalogElement element) { + nonCertifiedElement = element; + + } + + @Override + public void setCertifiedElement(ICatalogElement element) { + certifiedElement = element; + + } + + @Override + public boolean isEmpty() { + if(nonCertifiedElement == null && certifiedElement == null){ + return true; + } + return false; + } + + @Override + public List getAllElements() { + List allElements = new ArrayList<>(); + if( !Objects.isNull(nonCertifiedElement) ){ + allElements.add(nonCertifiedElement); + } + if( !Objects.isNull(certifiedElement) ){ + allElements.add(certifiedElement); + } + return allElements; + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/LeftPalletUIElementImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/LeftPalletUIElementImpl.java new file mode 100644 index 0000000..0f6836f --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/LeftPalletUIElementImpl.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICategory; +import org.onap.sdc.api.ILeftPalletUIElement; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; +import org.openecomp.sdc.common.util.ICategorizedElement; + +@Data +public class LeftPalletUIElementImpl implements ILeftPalletUIElement { + @JsonProperty("uniqueId") + protected String uniqueId; + @JsonProperty("uuid") + protected String uuid; + + // View + @JsonProperty("version") + protected String version; + @JsonProperty("icon") + protected String icon; + @JsonProperty("name") + protected String name; + + @JsonProperty("resourceType") + protected ResourceTypeEnum resourceType; + + // Filtered + @JsonProperty("description") + protected String description; + @JsonProperty("systemName") + protected String systemName; + @JsonProperty("invariantUUID") + protected String invariantUUID; + @JsonProperty("componentType") + protected ComponentTypeEnum componentType; + + protected List tags; + + protected List categories; + @JsonProperty("categoryName") + protected String categoryName; + @JsonProperty("subCategoryName") + protected String subCategoryName; + @JsonProperty("searchFilterTerms") + protected String searchFilterTerms; + + + + public static ILeftPalletUIElement buildUIElement(ICatalogElement element) { + LeftPalletUIElementImpl ret = new LeftPalletUIElementImpl(); + ret.setFields(element); + return ret; + } + + protected void setFields(ICatalogElement element) { + setUuid(element.getUuid()); + setSystemName(element.getSystemName()); + setInvariantUUID(element.getInvariantUUID()); + setDescription(element.getDescription()); + setCategories(element.getCategories()); + setUniqueId(element.getUniqueId()); + setName(element.getName()); + setResourceType(element.getResourceType()); + setVersion(element.getVersion()); + setIcon(element.getIcon()); + setComponentType(element.getComponentType()); + setTags(element.getTags()); + setCategoryName(getCategoryName()); + setSubCategoryName(getSubcategoryName()); + String tagString = convertListResultToString(tags); + setSearchFilterTerms(name + " " + description + " " + tagString + version); + } + + @Override + public String getComponentTypeAsString() { + return getComponentType().name(); + } + + @Override + public String getCategoryName() { + return getCategories().get(0).getName(); + } + + @Override + public String getSubcategoryName() { + if(getCategories().get(0).getSubcategories() == null || getCategories().get(0).getSubcategories().isEmpty()){ + return null; + } + return getCategories().get(0).getSubcategories().get(0).getName(); + } + + private String convertListResultToString(List tags) { + StringBuilder sb = new StringBuilder(); + tags.forEach(t->sb.append(t + " ")); + return sb.toString().toLowerCase(); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImpl.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImpl.java new file mode 100644 index 0000000..7f5ea77 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImpl.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.onap.sdc.api.ICatalogUpdateTimestamp; +import org.springframework.stereotype.Component; + +@Component +public class CatalogUpdateTimestampImpl implements ICatalogUpdateTimestamp { + + @Override + public long getCurrentUpdateTime() { + return currentUpdateTime; + } + + @Override + public long getPreviousUpdateTime() { + return previousUpdateTime; + } + + private long previousUpdateTime; + private long currentUpdateTime; + + public CatalogUpdateTimestampImpl() { + } + + public CatalogUpdateTimestampImpl(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + this.previousUpdateTime = catalogUpdateTimestamp.getPreviousUpdateTime(); + this.currentUpdateTime = catalogUpdateTimestamp.getCurrentUpdateTime(); + } + + @Override + public void setPreviousUpdateTime(long previousUpdateTime) { + this.previousUpdateTime = previousUpdateTime; + } + + @Override + public boolean isSameUpdate(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + return this.equals(catalogUpdateTimestamp); + } + + @Override + public void setCurrentUpdateTime(long currentUpdateTime) { + this.currentUpdateTime = currentUpdateTime; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof CatalogUpdateTimestampImpl + && ((this.getCurrentUpdateTime() == ((CatalogUpdateTimestampImpl) obj).getCurrentUpdateTime() + && this.getPreviousUpdateTime() == ((CatalogUpdateTimestampImpl) obj).getPreviousUpdateTime()) + || super.equals(obj)); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public String toString() { + return "CatalogUpdateTimestamp [currentUpdateTime = " + currentUpdateTime + ", previousUpdateTime = " + previousUpdateTime + "]"; + } + + @Override + public boolean isNextUpdate(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + return getCurrentUpdateTime() == catalogUpdateTimestamp.getPreviousUpdateTime(); + } + + @Override + public void set(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + this.previousUpdateTime = catalogUpdateTimestamp.getPreviousUpdateTime(); + this.currentUpdateTime = catalogUpdateTimestamp.getCurrentUpdateTime(); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainer.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainer.java new file mode 100644 index 0000000..5d2439d --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainer.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.onap.sdc.api.ICatalogUpdateTimestamp; +import org.onap.sdc.api.ICatalogUpdateTimestampContainer; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +@Component +public class CatalogUpdateTimestampSyncContainer implements ICatalogUpdateTimestampContainer { + + private static final Logger LOG = Logger.getLogger(CatalogUpdateTimestampSyncContainer.class); + + private ReadWriteLock rwLock = new ReentrantReadWriteLock(); + private Lock readLock = rwLock.readLock(); + private Lock writeLock = rwLock.writeLock(); + + @Autowired + private ICatalogUpdateTimestamp catalogUpdateTimestamp; + + @Override + public boolean updatesLostAsPerNotification(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + boolean updatesLost = !getTimestamp().isNextUpdate(catalogUpdateTimestamp); + setTimestamp(catalogUpdateTimestamp); + LOG.debug("updatesLostAsPerNotification: is {}", updatesLost); + return updatesLost; + } + + @Override + public boolean updatesLostAsPerHttpBeRequest(ICatalogUpdateTimestamp catalogUpdateTimestamp){ + boolean updatesLost = !getTimestamp().isSameUpdate(catalogUpdateTimestamp); + setTimestamp(catalogUpdateTimestamp); + LOG.debug("updatesLostAsPerHttpBeRequest: is {}", updatesLost); + return updatesLost; + } + + @Override + public boolean isUpdatedAlready(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + //the stored current timestamp is at least as the received one - the MS's catalog data + //is up to date (in case the data is received with the HTTP catalog request response) + boolean isUpdated = getTimestamp().getCurrentUpdateTime() >= catalogUpdateTimestamp.getCurrentUpdateTime(); + LOG.debug("isUpdatedAlready: is {}", isUpdated); + return isUpdated; + } + + private ICatalogUpdateTimestamp getTimestamp() { + ICatalogUpdateTimestamp tempTimestamp; + readLock.lock(); + try { + tempTimestamp = this.catalogUpdateTimestamp; + } + finally { + readLock.unlock(); + } + return tempTimestamp; + } + + private void setTimestamp(ICatalogUpdateTimestamp catalogUpdateTimestamp) { + writeLock.lock(); + try { + this.catalogUpdateTimestamp.set(catalogUpdateTimestamp); + } + finally { + writeLock.unlock(); + } + } + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ComponentMessage.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ComponentMessage.java new file mode 100644 index 0000000..343bf7e --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ComponentMessage.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.onap.sdc.api.IComponentMessage; +import org.onap.sdc.enums.ChangeTypeEnum; +import org.onap.sdc.impl.CatalogElementImpl; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; +import lombok.EqualsAndHashCode; +@Data +@EqualsAndHashCode(callSuper = true) +@JsonInclude(value = JsonInclude.Include.NON_NULL) +public class ComponentMessage extends CatalogElementImpl implements IComponentMessage { + + private static final long serialVersionUID = 7403223489248493460L; + @JsonProperty("changeTypeEnum") + private ChangeTypeEnum changeType; + @JsonProperty("catalogUpdateTimestamp") + private CatalogUpdateTimestampImpl catalogUpdateTimestamp; + + public ComponentMessage(){ + super(); + + } + + public ComponentMessage(String uniqueId, ChangeTypeEnum changeTypeEnum, ElementViewFieldsContainer viewFields, + ElementFilterFieldsContainer filterFields, CatalogUpdateTimestampImpl catalogUpdateTimestampImpl){ + super(); + this.changeType = changeTypeEnum; + this.uniqueId = uniqueId; + + //View Fields + this.name = viewFields.getName(); + this.resourceType = viewFields.getResourceType(); + this.version = viewFields.getVersion(); + this.lifecycleState = viewFields.getLifeCycleState(); + this.icon = viewFields.getIcon(); + + //Filter Fields + this.componentType = filterFields.getComponentType(); + this.lastUpdateDate = filterFields.getLastUpdateDate(); + this.category = filterFields.getCategory(); + this.subCategory = filterFields.getSubCategory(); + this.distributionStatus = filterFields.getDistributionStatus(); + this.archived = filterFields.isArchived(); + this.catalogUpdateTimestamp = catalogUpdateTimestampImpl; + } + + + + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ConsumerAdapter.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ConsumerAdapter.java new file mode 100644 index 0000000..48817f3 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ConsumerAdapter.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import com.att.nsa.mr.client.MRConsumer; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.Collections; + +@AllArgsConstructor +@Data +public class ConsumerAdapter { + + private static final Logger LOG = Logger.getLogger(DmaapConsumer.class); + + private Boolean active; + private MRConsumer consumer; + + public Iterable fetch() throws Exception { + if (active && consumer != null) { + return consumer.fetch(); + } + LOG.debug("Dmaap is Disabled"); + return Collections.emptyList(); + } + + public Iterable fetch(int timeoutMs, int limit) throws Exception { + if (active && consumer != null) { + return consumer.fetch(timeoutMs, limit); + } + LOG.debug("Dmaap is Disabled"); + return Collections.emptyList(); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapClientFactory.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapClientFactory.java new file mode 100644 index 0000000..2de50b8 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapClientFactory.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import java.io.File; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Properties; + +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.onap.sdc.utils.EncryptionUtils; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; + + + +/** + * Allows to create DMAAP client of type MRConsumer according received configuration parameters + */ +@Component +public class DmaapClientFactory { + private static final Logger LOG = Logger.getLogger(DmaapClientFactory.class.getName()); + + /** + * Creates DMAAP consumer according to received parameters + * @param parameters + * @return an instance object of type MRConsumer + * @throws IOException + */ + public ConsumerAdapter create(DmaapConsumerConfiguration parameters) throws Exception { + if (parameters.getActive()) { + MRConsumer mrConsumer = MRClientFactory.createConsumer(buildProperties(parameters)); + LOG.debug("MRConsumer created for topic {}", parameters.getTopic()); + return new ConsumerAdapter(parameters.getActive(), mrConsumer); + } + LOG.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, "INIT", + "Dmaap is Disabled!! will not consume, please set dmaapConsumerConfiguration.isActive=true in order to consume"); + return new ConsumerAdapter(parameters.getActive(), null); + } + + private Properties buildProperties(DmaapConsumerConfiguration parameters) throws GeneralSecurityException, IOException { + + String passkey = ""; + Properties props = new Properties(); + try + { + passkey = EncryptionUtils.decrypt(parameters.getPassword()); + }catch (Exception e){ + throw new GeneralSecurityException("invalid password, cannot build properties"); + } + props.setProperty("Latitude", Double.toString(parameters.getLatitude())); + props.setProperty("Longitude", Double.toString(parameters.getLongitude())); + props.setProperty("Version", parameters.getVersion()); + props.setProperty("ServiceName", parameters.getServiceName()); + props.setProperty("Environment", parameters.getEnvironment()); + props.setProperty("Partner", parameters.getPartner()); + props.setProperty("routeOffer", parameters.getRouteOffer()); + props.setProperty("Protocol", parameters.getProtocol()); + props.setProperty("username", parameters.getUsername()); + props.setProperty("password", passkey ); + props.setProperty("contenttype", parameters.getContenttype()); + props.setProperty("host", parameters.getHosts()); + props.setProperty("topic", parameters.getTopic()); + props.setProperty("group", parameters.getConsumerGroup()); + props.setProperty("id", parameters.getConsumerId()); + props.setProperty("timeout", Integer.toString(parameters.getTimeoutMs())); + props.setProperty("limit", Integer.toString(parameters.getLimit())); + //props.setProperty("AFT_DME2_REQ_TRACE_ON", Boolean.toString(parameters.getDme2TraceOn())); + //props.setProperty("AFT_ENVIRONMENT", parameters.getAftEnvironment()); + // props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", Integer.toString(parameters.getAftDme2ConnectionTimeoutMs())); + //props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", Integer.toString(parameters.getAftDme2RoundtripTimeoutMs())); + //props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", Integer.toString(parameters.getAftDme2ReadTimeoutMs())); + + props.setProperty("AFT_DME2_SSL_ENABLE", Boolean.toString(parameters.getAftDme2SslEnable())); + props.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", Boolean.toString(parameters.getAftDme2ClientIgnoreSslConfig())); + props.setProperty("AFT_DME2_CLIENT_KEYSTORE", parameters.getAftDme2ClientKeystore()); + props.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", parameters.getAftDme2ClientKeystorePassword()); + props.setProperty("AFT_DME2_CLIENT_SSL_CERT_ALIAS", parameters.getAftDme2ClientSslCertAlias()); + + + props.setProperty("maxBatchSize","1"); + props.setProperty("maxAgeMs","250"); + props.setProperty("partition","1"); + props.setProperty("MessageSentThreadOccurance","10"); + props.setProperty("Authorization","Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2"); + + + String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath(); + ensureFileExists(dme2PreferredRouterFilePath); + props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath); + + props.setProperty("TransportType", parameters.getTransportType()); + props.setProperty("SubContextPath", "/"); + props.setProperty("MethodType", "GET"); + props.setProperty("authKey", ""); + props.setProperty("authDate", ""); + props.setProperty("filter", ""); + props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", ""); + props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", ""); + props.setProperty("sessionstickinessrequired", "no"); + + + return props; + } + + private void ensureFileExists(String filePath) throws IOException { + File file = new File(filePath); + if(file.createNewFile()) { + LOG.debug("The file {} has been created on the disk", file.getAbsolutePath()); + } + else{ + LOG.debug("The file {} already exists", file.getAbsolutePath()); + } + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumer.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumer.java new file mode 100644 index 0000000..84f84b3 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumer.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + + +import static org.onap.sdc.utils.FunctionalCodeUtils.runMethodWithTimeOut; + +import java.util.function.Consumer; + +import org.onap.sdc.api.IMessageQueueHandlerConsumer; +import org.onap.sdc.api.IStatus; +import org.onap.sdc.healthcheck.DmaapHealth; +import org.onap.sdc.healthcheck.DmaapHealth.HealthCheckInfoResult; +import org.onap.sdc.logger.FacadeLogUtils; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** + * Allows consuming DMAAP topic according to received consumer parameters + * Allows processing received messages. + */ +@Component +public class DmaapConsumer implements IMessageQueueHandlerConsumer { + @Autowired + private DmaapConsumerConfiguration dmaapConsumerParams; + @Autowired + private DmaapHealth dmaapHealth; + @Autowired + private DmaapClientFactory dmaapClientFactory; + + private ConsumerAdapter consumer; + private Consumer notificationCallback; + private static final Logger LOG = Logger.getLogger(DmaapConsumer.class); + + @Override + public IStatus init(Consumer callback) { + notificationCallback = callback; + LOG.debug("Starting to consume topic {} for DMAAP consumer with the next parameters {}. ", dmaapConsumerParams.getTopic(), dmaapConsumerParams); + try { + consumer = dmaapClientFactory.create(dmaapConsumerParams); + } catch (Exception e) { + LOG.error(EcompLoggerErrorCode.DATA_ERROR, DmaapConsumer.class.getName(), new ErrorLogOptionalData() + , "An error occurred upon consuming topic by Dmaap consumer client: {}", e.getStackTrace()); + return IStatus.getFailStatus(); + } + return IStatus.getSuccessStatus(); + } + + @Value("${scheduling.job.rate.dmaapConsumerMaxFetchTimeMs}") + private String dmaapConsumerMaxFetchTimeMs; + @Scheduled(fixedRateString = "${scheduling.job.rate.dmaapConsumer}", initialDelay = 1000) + public void run() { + //Limit time to try to fetch Dmaap Update to 10 Second + runMethodWithTimeOut(this::fetchMessagesFromDmaap, Long.valueOf(dmaapConsumerMaxFetchTimeMs), DmaapConsumer.class.getName()); + } + + private void fetchMessagesFromDmaap() { + LogFieldsMdcHandler.getInstance().addInfoForErrorAndDebugLogging(FacadeLogUtils.PARTNER_NAME); + String topic = dmaapConsumerParams.getTopic(); + + if (LOG.isDebugEnabled()) { + LOG.debug("Trying to fetch messages from topic: {}", topic); + } + boolean isTopicAvailable = false; + try { + LOG.debug("awaiting consumption on {}", topic); + Iterable messages = consumer.fetch(); + isTopicAvailable = true; + if (messages != null) { + for (String msg : messages) { + LOG.debug("The DMAAP message {} received. The topic is {}.", msg, topic); + notificationCallback.accept(msg); + } + } + + LOG.debug("Finishing to fetch messages from messages {}, topic: {}", messages, topic); + + } catch (Exception e) { + LOG.error(EcompLoggerErrorCode.DATA_ERROR, DmaapConsumer.class.getName(), new ErrorLogOptionalData(), "The exception occurred upon fetching DMAAP message {}", e.getMessage()); + LOG.debug("The exception occurred upon fetching DMAAP message {}", e); + } + dmaapHealth.report(prepareDmaapReport(isTopicAvailable)); + } + + private HealthCheckInfoResult prepareDmaapReport(boolean isTopicAvailable) { + HealthCheckInfoResult result; + if (isTopicAvailable) { + result = DmaapHealth.HealthCheckInfoResult.OK; + } else if (dmaapConsumerParams.getActive()) { + result = DmaapHealth.HealthCheckInfoResult.DOWN; + } else { + result = DmaapHealth.HealthCheckInfoResult.UNAVAILABLE; + } + return result; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumerConfiguration.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumerConfiguration.java new file mode 100644 index 0000000..0f7d3df --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumerConfiguration.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import lombok.Data; +import lombok.ToString; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Data +@Component +public class DmaapConsumerConfiguration { + + @Value("${sdc.dmaapConsumerConfiguration.active}") + private Boolean active; + @Value("${sdc.dmaapConsumerConfiguration.hosts}") + private String hosts; + @Value("${sdc.dmaapConsumerConfiguration.transportType}") + private String transportType; + @Value("${sdc.dmaapConsumerConfiguration.consumerGroup}") + private String consumerGroup; + @Value("${sdc.dmaapConsumerConfiguration.consumerId}") + private String consumerId; + @Value("${sdc.dmaapConsumerConfiguration.timeoutMs}") + private Integer timeoutMs; + @Value("${sdc.dmaapConsumerConfiguration.limit}") + private Integer limit; + @Value("${sdc.dmaapConsumerConfiguration.topic}") + private String topic; + @Value("${sdc.dmaapConsumerConfiguration.protocol}") + private String protocol; + @Value("${sdc.dmaapConsumerConfiguration.contenttype}") + private String contenttype; + @Value("${sdc.dmaapConsumerConfiguration.dme2preferredRouterFilePath}") + private String dme2preferredRouterFilePath; + @Value("${sdc.dmaapConsumerConfiguration.credential.username}") + private String username; + @ToString.Exclude + @Value("${sdc.dmaapConsumerConfiguration.credential.password}") + private String password; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2SslEnable}") + private Boolean aftDme2SslEnable; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2ClientIgnoreSslConfig}") + private Boolean aftDme2ClientIgnoreSslConfig; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2ClientKeystore}") + private String aftDme2ClientKeystore; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2ClientKeystorePassword}") + private String aftDme2ClientKeystorePassword; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2ClientSslCertAlias}") + private String aftDme2ClientSslCertAlias; + @Value("${sdc.dmaapConsumerConfiguration.pollingInterval}") + private Integer pollingInterval; + @Value("${sdc.dmaapConsumerConfiguration.latitude}") + private Double latitude; + @Value("${sdc.dmaapConsumerConfiguration.longitude}") + private Double longitude; + @Value("${sdc.dmaapConsumerConfiguration.version}") + private String version; + @Value("${sdc.dmaapConsumerConfiguration.serviceName}") + private String serviceName; + @Value("${sdc.dmaapConsumerConfiguration.environment}") + private String environment; + @Value("${sdc.dmaapConsumerConfiguration.partner}") + private String partner; + @Value("${sdc.dmaapConsumerConfiguration.routeOffer}") + private String routeOffer; + @Value("${sdc.dmaapConsumerConfiguration.dme2TraceOn}") + private Boolean dme2TraceOn; + @Value("${sdc.dmaapConsumerConfiguration.aftEnvironment}") + private String aftEnvironment; + + @Value("${sdc.dmaapConsumerConfiguration.aftDme2ConnectionTimeoutMs}") + private Integer aftDme2ConnectionTimeoutMs; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2RoundtripTimeoutMs}") + private Integer aftDme2RoundtripTimeoutMs; + @Value("${sdc.dmaapConsumerConfiguration.aftDme2ReadTimeoutMs}") + private Integer aftDme2ReadTimeoutMs; + @Value("${sdc.dmaapConsumerConfiguration.timeLimitForNotificationHandleMs}") + private Integer timeLimitForNotificationHandleMs; + + + + + + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementFilterFieldsContainer.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementFilterFieldsContainer.java new file mode 100644 index 0000000..2c89772 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementFilterFieldsContainer.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; + +public class ElementFilterFieldsContainer { + private final ComponentTypeEnum componentType; + private final long lastUpdateDate; + private final String category; + private final String subCategory; + private final DistributionStatusEnum distributionStatus; + private final boolean isArchived; + + public ElementFilterFieldsContainer(ComponentTypeEnum componentType, long lastUpdateDate, String category, + String subCategory, DistributionStatusEnum distributionStatus, boolean isArchived) { + super(); + this.componentType = componentType; + this.lastUpdateDate = lastUpdateDate; + this.category = category; + this.subCategory = subCategory; + this.distributionStatus = distributionStatus; + this.isArchived = isArchived; + } + + public ComponentTypeEnum getComponentType() { + return componentType; + } + + public long getLastUpdateDate() { + return lastUpdateDate; + } + + public String getCategory() { + return category; + } + + public String getSubCategory() { + return subCategory; + } + + public DistributionStatusEnum getDistributionStatus() { + return distributionStatus; + } + + public boolean isArchived() { + return isArchived; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementViewFieldsContainer.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementViewFieldsContainer.java new file mode 100644 index 0000000..fe1a14e --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementViewFieldsContainer.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +/** + * Pojo container class to be used by the constructor ComponentMessage + * @author ms172g + * + */ +class ElementViewFieldsContainer { + private final String name; + private final ResourceTypeEnum resourceType; + private final String version; + private final LifecycleStateEnum lifeCycleState; + private final String icon; + + public ElementViewFieldsContainer(String name, ResourceTypeEnum resourceType, String version, + LifecycleStateEnum lifeCycleState, String icon) { + super(); + this.name = name; + this.resourceType = resourceType; + this.version = version; + this.lifeCycleState = lifeCycleState; + this.icon = icon; + } + + public String getName() { + return name; + } + + public ResourceTypeEnum getResourceType() { + return resourceType; + } + + public String getVersion() { + return version; + } + + public LifecycleStateEnum getLifeCycleState() { + return lifeCycleState; + } + + public String getIcon() { + return icon; + } + + +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/impl/users/UserElement.java b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/users/UserElement.java new file mode 100644 index 0000000..9826076 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/impl/users/UserElement.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.users; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import lombok.Data; +import org.onap.sdc.enums.*; + +import java.io.IOException; +import java.util.List; + +@JsonInclude(value = JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +@Data +public class UserElement { + private static final long serialVersionUID = 2615425881811561124L; + @JsonProperty("userId") + protected String userId; + @JsonProperty("role") + protected UserRoleEnum role; + @JsonProperty("status") + protected UserStatusEnum status; + + /** + * Builds Map of User elements from sdc be response. + * + * @param responseBody + * @return list of users + * @throws IOException + */ + static List buildFromSdcHttpResponse(String responseBody) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); + TypeReference> typeRef = new TypeReference>() { + }; + return objectMapper.readValue(responseBody, typeRef); + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/logger/FacadeLogUtils.java b/catalog-facade-ms/src/main/java/org/onap/sdc/logger/FacadeLogUtils.java new file mode 100644 index 0000000..cf71dd9 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/logger/FacadeLogUtils.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.logger; + +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; + +public class FacadeLogUtils { + public static String PARTNER_NAME = "SDC.CATALOG_FACADE_MS"; + public static String BE_TARGET_ENTITY = "SDC.BE"; + + + public static ErrorLogOptionalData fullOptionalData(String targetEntity, String targetServiceName) { + return ErrorLogOptionalData.newBuilder().targetEntity(targetEntity) + .targetServiceName(targetServiceName).build(); + } + + public static String serviceNameFromMDC() { + return LogFieldsMdcHandler.getInstance().getServiceName(); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/repositories/CatalogElementRepository.java b/catalog-facade-ms/src/main/java/org/onap/sdc/repositories/CatalogElementRepository.java new file mode 100644 index 0000000..00c1ca0 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/repositories/CatalogElementRepository.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.repositories; + +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.ResourceTypeEnum; +import org.onap.sdc.impl.CatalogElementImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +//@RepositoryRestController +//@Repository +public interface CatalogElementRepository extends PagingAndSortingRepository { + List findByName(@Param("name") String name); + + //http://localhost:8080/catalogElementImpls/search/findByNameIn?name=shay&name=shayservice + //http://localhost:8080/catalogElementImpls/search/findByNameIn?name=shay,shayservice + List findByNameIn(@Param("name") List name); + List findByNameAndResourceTypeAndVersionAndIcon(@Param("name") String name + ,@Param("resourceType") ResourceTypeEnum resourceType + ,@Param("version") String version + ,@Param("icon") String icon); + List findByNameStartsWith(@Param("name") String name, Pageable pageable); + //http://localhost:8080/catalogElementImpls/search/findByComponentTypeInAndResourceTypeInAndDistributionStatusIn? + List findByComponentTypeInAndResourceTypeInAndDistributionStatusIn( + List componentTypeEnums, List resourceTypeEnums, List distributionStatusEnums); +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/services/ServletHelper.java b/catalog-facade-ms/src/main/java/org/onap/sdc/services/ServletHelper.java new file mode 100644 index 0000000..43b03fd --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/services/ServletHelper.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.services; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.Map; + +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static java.util.Collections.emptyList; +import static java.util.EnumSet.of; +import static java.util.stream.Collectors.toList; +import static org.onap.sdc.enums.LifecycleStateEnum.CERTIFIED; +import static org.onap.sdc.enums.LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; +import static org.onap.sdc.enums.ResourceTypeEnum.CP; +import static org.onap.sdc.enums.ResourceTypeEnum.CR; +import static org.onap.sdc.enums.ResourceTypeEnum.CVFC; +import static org.onap.sdc.enums.ResourceTypeEnum.Configuration; +import static org.onap.sdc.enums.ResourceTypeEnum.PNF; +import static org.onap.sdc.enums.ResourceTypeEnum.ServiceProxy; +import static org.onap.sdc.enums.ResourceTypeEnum.VF; +import static org.onap.sdc.enums.ResourceTypeEnum.VFC; +import static org.onap.sdc.enums.ResourceTypeEnum.VFCMT; +import static org.onap.sdc.enums.ResourceTypeEnum.VL; + +@Component +public class ServletHelper { + + private static final Logger log = LoggerFactory.getLogger(ServletHelper.class); + + public Collection filterByProperty(String fieldName, Collection expectedValues, Object... items) { + if (items != null && fieldName != null) { + try{ + return stream(items) + .filter( obj -> { + Object propertyValue = extractProp(fieldName, obj); + return isNoneNull(propertyValue,expectedValues) ? + expectedValues.contains(propertyValue) : + propertyValue==expectedValues ; + }) + .collect(toList()); + }catch(Exception e){ + log.warn("cannot filter property {} ", fieldName, e); + } + } + + return emptyList(); + } + + + public Collection filterByPropertyMap(Map propertyToValues, Collection items) { + if (items != null && propertyToValues != null) { + try{ + return (Collection) items.stream() + .filter( obj -> + propertyToValues.entrySet().stream().allMatch( (entry) -> !filterByProperty(entry.getKey() , entry.getValue() , obj).isEmpty() ) + ).collect(toList()); + }catch(Exception e){ + log.warn("cannot filter ", e); + } + } + + return emptyList(); + } + + + public Collection filterByProperty(String fieldName, Object expectedValue, Object... list) { + return filterByProperty(fieldName, asList(expectedValue),list); + } + + public Object extractProp(String fieldName, Object item) {//throws ReflectiveOperationException { + Class aClass = item.getClass(); + try { + Field field = aClass.getDeclaredField(fieldName); + if (!field.isAccessible()) { + log.warn("field {} is not accessible for {}", fieldName, aClass); + } + field.setAccessible(true); + return field.get(item); + } catch (IllegalAccessException e) { + log.warn("cannot access property {} for {} ", fieldName, aClass ,e); + //throw e; + } catch (NoSuchFieldException e) { + log.warn("cannot extract property {} for {}", fieldName, aClass ,e); + //throw e; + } + return null; + } + + /** + * @return true iff all @param{items} are not null + * + * **/ + public boolean isNoneNull(Object... items){ + return stream(items).allMatch((item)-> item!=null ); + } + + public Collection filterByComponentType(Collection resourceType, ICatalogElement... catalogItems){ + return filterByProperty("resourceType", resourceType , catalogItems); + } + + public Collection filterByLifecycleState(Collection lifecycleState, ICatalogElement... catalogItems){ + return filterByProperty("lifecycleState", lifecycleState , catalogItems); + } + + public Collection filterForService(ICatalogElement... catalogItems){ + Collection collectionByType = filterByComponentType( of(VF,CP,PNF,VL,ServiceProxy,Configuration) , catalogItems); + Collection collectionByStatus = filterByLifecycleState( of(CERTIFIED,NOT_CERTIFIED_CHECKIN), (ICatalogElement[]) collectionByType.toArray()); + //todo- filter by latest + return collectionByStatus; + } + + public Collection filterForVf(ICatalogElement... catalogItems){ + Collection collectionByType = filterByComponentType( of(VFC,CR,CVFC,VFCMT) , catalogItems); + Collection collectionByStatus = filterByLifecycleState( of(CERTIFIED,NOT_CERTIFIED_CHECKIN), (ICatalogElement[]) collectionByType.toArray()); + //todo- filter by latest + return collectionByStatus; + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/CatalogElementsUtils.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/CatalogElementsUtils.java new file mode 100644 index 0000000..dd8ca8e --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/CatalogElementsUtils.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogUIElement; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.impl.CatalogUIElementImpl; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.onap.sdc.enums.SdcResponseFieldEnum.RESOURCES_LIST; +import static org.onap.sdc.enums.SdcResponseFieldEnum.SERVICES_LIST; + +public final class CatalogElementsUtils { + static final Logger LOG = Logger.getLogger(CatalogElementsUtils.class); + + private static List prepareValueList(List inputList) { + if (inputList == null) { + return Collections.emptyList(); + } + return inputList.stream() + .map(CatalogUIElementImpl::buildUIElement) + .collect(Collectors.toList()); + } + + public static Map> convertElementsListToUIMap + (List elementsList){ + elementsList = elementsList!=null? elementsList : new ArrayList<>(); + + Map> componentMap = elementsList + .stream() + .collect(Collectors.groupingBy(ICatalogElement::getComponentType)); + + Map> responseMap = new HashMap<>(); + responseMap.put(RESOURCES_LIST.getJsonName(), prepareValueList(componentMap.get(ComponentTypeEnum.RESOURCE))); + responseMap.put(SERVICES_LIST.getJsonName(), prepareValueList(componentMap.get(ComponentTypeEnum.SERVICE))); + return responseMap; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/EncryptionUtils.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/EncryptionUtils.java new file mode 100644 index 0000000..e5551e1 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/EncryptionUtils.java @@ -0,0 +1,200 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.SecretKeySpec; + +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; + +/** + * Utility Class For Encryption Functionalities + * + * @author ms172g + * + */ +public final class EncryptionUtils { + static final Logger LOG = Logger.getLogger(EncryptionUtils.class); + private static final byte[] KEY = new byte[] { -64, 5, -32, -117, -44, 8, -39, 1, -9, 36, -46, -81, 62, -15, -63, + -75 }; + + private static final String ALGORITHM = "AES"; + static final String CHARSET = StandardCharsets.UTF_8.name(); + + static Key secKey = null; + + static { + try { + secKey = EncryptionUtils.generateKey(KEY, ALGORITHM); + } catch (Exception e) { + LOG.error(EcompLoggerErrorCode.PERMISSION_ERROR, EncryptionUtils.class.getName(), new ErrorLogOptionalData(),"cannot generate key for {}", ALGORITHM); + } + } + + private EncryptionUtils() { + throw new UnsupportedOperationException("Do not instantiate utility class"); + } + + public static Key generateKey(final byte[] KEY, String algorithm) { + return new SecretKeySpec(KEY, algorithm); + } + + public static String encrypt(String strDataToEncrypt) throws Exception { + final String methodName = "encrypt"; + if (strDataToEncrypt != null) { + try { + FunctionalCodeUtils.LOG.debug("Encrypt key -> {}", secKey); + Cipher aesCipherForEncryption = Cipher.getInstance("AES"); // Must + // specify + // the + // mode + // explicitly + // as + // most + // JCE + // providers + // default + // to + // ECB + // mode!! + aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secKey); + byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); + byte[] byteCipherText = aesCipherForEncryption.doFinal(byteDataToEncrypt); + String strCipherText = new String(java.util.Base64.getMimeEncoder() + .encode(byteCipherText), CHARSET); + FunctionalCodeUtils.LOG.debug("Cipher Text generated using AES is {}", strCipherText); + return strCipherText; + } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { + FunctionalCodeUtils.LOG.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, methodName, + "cannot encrypt data unknown algorithm or missing encoding for {}", + secKey.getAlgorithm()); + throw e; + } catch (InvalidKeyException e) { + FunctionalCodeUtils.LOG.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, methodName, + new ErrorLogOptionalData(), + "invalid key received - > {} | {}", java.util.Base64.getDecoder() + .decode(secKey.getEncoded()), + e.getMessage()); + throw e; + } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) { + FunctionalCodeUtils.LOG.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, methodName, + "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding", + e.getMessage()); + throw e; + } + } else { + throw new InvalidKeyException("empty key received"); + } + } + + /** + * Decrypt the Data + * + * @param byteCipherText + * - should be valid bae64 input in the length of 16bytes + * @param isBase64Decoded + * - is data already base64 encoded&aligned to 16 bytes a. + * Initialize a new instance of Cipher for Decryption (normally + * don't reuse the same object) b. Decrypt the cipher bytes using + * doFinal method + */ + public static String decrypt(byte[] byteCipherText, boolean isBase64Decoded) throws Exception { + final String methodName = "decrypt"; + if (byteCipherText != null) { + byte[] alignedCipherText = byteCipherText; + try { + if (isBase64Decoded) + alignedCipherText = Base64.getDecoder() + .decode(byteCipherText); + FunctionalCodeUtils.LOG.debug("Decrypt key -> " + secKey.getEncoded()); + Cipher aesCipherForDecryption = Cipher.getInstance("AES"); // Must + // specify + // the + // mode + // explicitly + // as + // most + // JCE + // providers + // default + // to + // ECB + // mode!! + aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secKey); + byte[] byteDecryptedText = aesCipherForDecryption.doFinal(alignedCipherText); + String strDecryptedText = new String(byteDecryptedText); + FunctionalCodeUtils.LOG.debug("Decrypted Text message is: {}", + EncryptionUtils.obfuscateKey(strDecryptedText)); + return strDecryptedText; + } catch (NoSuchAlgorithmException e) { + FunctionalCodeUtils.LOG.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, methodName, + "cannot encrypt data unknown algorithm or missing encoding for {}", + secKey.getAlgorithm()); + throw e; + } catch (InvalidKeyException e) { + FunctionalCodeUtils.LOG.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, methodName, + new ErrorLogOptionalData(), + "invalid key recieved - > {} | {}", java.util.Base64.getDecoder() + .decode(secKey.getEncoded()), + e.getMessage()); + throw e; + } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) { + FunctionalCodeUtils.LOG.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, methodName, + "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding", + e.getMessage()); + throw e; + } + } + throw new InvalidKeyException("Decrypt FAILED"); + } + + public static String decrypt(String byteCipherText) throws Exception { + + return decrypt(byteCipherText.getBytes(CHARSET), true); + + } + + // obfuscates key prefix -> ********** + public static String obfuscateKey(String sensitiveData) { + + if (sensitiveData != null) { + int len = sensitiveData.length(); + StringBuilder builder = new StringBuilder(sensitiveData); + for (int i = 0; i < len / 2; i++) { + builder.setCharAt(i, '*'); + } + return builder.toString(); + } + return sensitiveData; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/FunctionalCodeUtils.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/FunctionalCodeUtils.java new file mode 100644 index 0000000..209fac9 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/FunctionalCodeUtils.java @@ -0,0 +1,275 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils; + +import static java.util.Arrays.asList; +import static org.onap.sdc.logger.FacadeLogUtils.serviceNameFromMDC; + +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Predicate; + +import org.apache.commons.lang3.NotImplementedException; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.time.StopWatch; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; + +/** + * Utility class for functional code + * + * @author ms172g + * + */ +public final class FunctionalCodeUtils { + static final Logger LOG = Logger.getLogger(FunctionalCodeUtils.class); + + + + private FunctionalCodeUtils() { + throw new UnsupportedOperationException("Do not instantiate utility class"); + } + + /** + * Wraps the execution of the Runnable with try catch.
+ * In case exception occurred returns Optional containing the + * resultOnException.
+ * Otherwise returns an Empty optional. + * + * @param runnable + * @param resultOnException + * @param serviceName + * @return + */ + public static Optional wrapWithTryCatch(RunnableThrows runnable, + T resultOnException, String serviceName) { + Optional optionalError; + try { + runnable.run(); + optionalError = Optional.empty(); + } catch (Exception e) { + logException(e, serviceName); + optionalError = Optional.of(resultOnException); + } + return optionalError; + } + + /** + * Wraps the execution of the Runnable with try catch.
+ * In case exception occurred logs the Exception.
+ * resultOnException.
+ * Otherwise returns an Empty optional. + * + * @param runnable + * @param resultOnException + * @return + */ + public static void wrapWithTryCatch(RunnableThrows runnable, String serviceName) { + wrapWithTryCatch(runnable, serviceName); + } + + /** + * Functional Interface Similar to Runnable except that throws Exception + * + * @author ms172g + * + * @param + */ + @FunctionalInterface + public interface RunnableThrows { + /** + * Similar to run of Runnable except that throws Exception + * + * @throws E + */ + void run() throws E; + + } + + private static void logException(Exception e, String serviceName) { + LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName, new ErrorLogOptionalData(),"Error was caught : {}", e.getMessage()); + LOG.debug("Error was caught ", e); + } + + /** + * Finds a value in an enum array by predicate + * + * @param predicate + * @param values + * @return + */ + public static > T findByPredicate(Predicate predicate, T[] values) { + + final Optional optionalFound = asList(values).stream() + .filter(predicate) + .findAny(); + return optionalFound.orElseThrow(() -> new NotImplementedException( + String.format("Enum: %s Not Found for predicate: %s ", values.getClass() + .getName(), predicate.toString()))); + } + + /** + * Runs the given method.
+ * In case the method passes without any Assertion Errors finishes.
+ * In case there is an assertion error keeps running the method every retryIntervalMS.
until there is no Errors or maxWaitTimeMs has passed.
+ * If there are still Assertion Errors in the last Run they are returned to the user.
+ * + * @param methodToRun + * @param maxWaitTimeMs + * @param retryIntervalMS + */ + public static void retryMethodOnAssertionError(Runnable methodToRun, long maxWaitTimeMs, long retryIntervalMS, String serviceName) { + if (maxWaitTimeMs <= 0) { + throw new UnsupportedOperationException("Number maxWaitTimeMs be greater than 0"); + } + StopWatch watch = new StopWatch(); + watch.start(); + boolean isLastTry = watch.getTime() + retryIntervalMS > maxWaitTimeMs; + boolean isSuccessfull = false; + + while (!isLastTry && !isSuccessfull) { + try { + methodToRun.run(); + isSuccessfull = true; + } catch (AssertionError e) { + wrapWithTryCatch(() -> Thread.sleep(retryIntervalMS), serviceName); + //Dummy Code to prevent sonar Issue + boolean flag = false; + if( flag ){ + LOG.debug(e.getMessage(), e); + } + } + isLastTry = watch.getTime() + retryIntervalMS > maxWaitTimeMs; + if (isLastTry) { + methodToRun.run(); + } + } + + + } + /** + * @author mshitrit Supplier that throws an exception + * @param + * @param + */ + public interface SupplierThrows { + /** + * Same get method, but throws an exception + * + * @return + * @throws E + */ + R get() throws E; + } + + + /** + * Runs a method that declares throwing an Exception and has a return value. + *
+ * In case Exception Occurred replaces it with RunTimeException.
+ * This is useful for two cases:
+ * 1.using methods that throws exceptions in streams.
+ * 2.replacing declared exception with undeclared exception (Runtime).
+ * See below Use Case:
+ * Instead of: intList.stream().map(e -> fooThrowsAndReturnsBoolean(e)); - + * does not compile !
+ * Use This : intList.stream().map(e -> swallowException( () -> + * fooThrowsAndReturnsBoolean(e))); - compiles !
+ * + * @param methodToRun + * @return + */ + public static R replaceWithUncheckedException(SupplierThrows methodToRun) { + try { + return methodToRun.get(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Runs a method that declares throwing an Exception without return value. + *
+ * In case Exception Occurred replaces it with RunTimeException.
+ * This is useful for two cases:
+ * 1.using methods that throws exceptions in streams.
+ * 2.replacing declared exception with undeclared exception (Runtime).
+ * See below Use Case:
+ * + * @param methodToRun + */ + public static void replaceWithUncheckedException(RunnableThrows methodToRun) { + + SupplierThrows runnableWrapper = () -> { + methodToRun.run(); + return true; + }; + replaceWithUncheckedException(runnableWrapper); + } + + + /** + * This method runs the given method.
+ * In case given method finished running within timeoutInMs limit it returns true.
+ * In case given method did not finish running within timeoutInMs limit it returns false.
+ + * + * @param runnable + * @param timeoutInMs + * @param serviceName + * @return + */ + public static boolean runMethodWithTimeOut(Runnable runnable, long timeoutInMs, String serviceName) { + boolean isFinishedWithingTimeOut; + if (timeoutInMs <= NumberUtils.LONG_ZERO) { + isFinishedWithingTimeOut = false; + } else { + ExecutorService pool = Executors.newSingleThreadExecutor(); + Future future = pool.submit(runnable, Boolean.TRUE); + + try { + isFinishedWithingTimeOut = future.get(timeoutInMs, TimeUnit.MILLISECONDS); + + } catch (NullPointerException | RejectedExecutionException | InterruptedException | ExecutionException | TimeoutException e) { + isFinishedWithingTimeOut = false; + LOG.debug("method run was canceled because it has passed its time limit of {} MS ", timeoutInMs, e); + + } + catch (Exception e){ + isFinishedWithingTimeOut = false; + logException(e, serviceName); + }finally { + pool.shutdownNow(); + } + } + return isFinishedWithingTimeOut; + } + + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/MessageUtils.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/MessageUtils.java new file mode 100644 index 0000000..37925f4 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/MessageUtils.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +import java.io.IOException; + +public class MessageUtils { + private MessageUtils() { + } + + public static T buildFromMessage(String message, Class clazz) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + return objectMapper.readValue(message, clazz); + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/Wrapper.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/Wrapper.java new file mode 100644 index 0000000..cceb316 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/Wrapper.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * 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========================================================= + */ + +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils; +/** + * Very Basic Wrapper class. + * @author mshitrit + * + * @param + */ +public class Wrapper{ + private T innerElement; + public Wrapper(T innerElement){ + this.innerElement = innerElement; + } + public Wrapper(){ + this.innerElement = null; + } + public T getInnerElement() { + return innerElement; + } + public void setInnerElement(T innerElement) { + this.innerElement = innerElement; + } + public boolean isEmpty(){ + return innerElement == null; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryCompositionBuilder.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryCompositionBuilder.java new file mode 100644 index 0000000..c0fb765 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryCompositionBuilder.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.apache.commons.lang3.NotImplementedException; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +public final class QueryCompositionBuilder { + + private static Predicate predicateDenyByResourceType; + private static Predicate predicateAllowByResourceType; + + private QueryCompositionBuilder() { + throw new NotImplementedException("Should not instantiate Utility class"); + } + + static { + predicateDenyByResourceType = c -> c.getResourceType() != ResourceTypeEnum.VFCMT; + + predicateAllowByResourceType = c -> c.getResourceType() == ResourceTypeEnum.VFC; + predicateAllowByResourceType = predicateAllowByResourceType.or(c -> c.getResourceType() == ResourceTypeEnum.CP) + .or(c -> c.getResourceType() == ResourceTypeEnum.VL) + .or(c -> c.getResourceType() == ResourceTypeEnum.Configuration); + } + + public static ICatalogQuery getQuery(String internalComponentType) { + List> queryList = new ArrayList<>(); + Predicate predicate = getQueryByInternalComponentType(internalComponentType); + if (predicate != null) { + queryList.add(predicate); + } + // TODO - what should be returned if the first predicate is null? should + // it be c-> false? + queryList.add(c -> !c.isArchived()); + queryList.add(ICatalogElement::getIsHighestVersion); + queryList.add(c -> c.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + return () -> queryList; + + } + + private static Predicate getQueryByInternalComponentType(String internalComponentType) { + if ("service".equalsIgnoreCase(internalComponentType)) { + return getTopologyTemplateQuery(); + } + return getNodeTypeQuery(internalComponentType); + } + + static Predicate getTopologyTemplateQuery() { + Predicate predicate = c -> c.getResourceType() != ResourceTypeEnum.VFC; + return predicate.and(c -> c.getResourceType() != ResourceTypeEnum.VFCMT) + .or(c -> c.getComponentType() == ComponentTypeEnum.SERVICE); + } + + static Predicate getNodeTypeQuery(String internalComponentType) { + ResourceTypeEnum internalResourceType = ResourceTypeEnum.getTypeByName(internalComponentType); + if (internalResourceType == null) { + return null; + } + + switch (internalResourceType) { + case VF: + case CR: + case PNF: + return predicateDenyByResourceType.and(predicateAllowByResourceType); + default: + return c -> false; + } + } + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilder.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilder.java new file mode 100644 index 0000000..b49a492 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilder.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.regex.PatternSyntaxException; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.enums.ResourceTypeEnum; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import static org.onap.sdc.logger.FacadeLogUtils.serviceNameFromMDC; + +public abstract class QueryFilterBuilder { + + private static final Logger LOG = Logger.getLogger(QueryFilterBuilder.class); + + static final String SUB_TYPE_SEPARATOR = "\\."; + + private final ArrayList elements = new ArrayList<>(); + + QueryFilterBuilder(List values) { + elements.addAll(values); + } + + Predicate getQueryForParameter() { + Predicate predicate = c -> false; + for (String element: elements) { + predicate = predicate.or(buildQueryForElement(element)); + } + return predicate; + } + + public abstract Predicate buildQueryForElement(String element); + + protected ArrayList parseComplexValue(String value, String separator) { + final String methodName = "parseComplexValue"; + + LOG.debug(methodName + ": Parsing value list: {}", value); + ArrayList valueList = new ArrayList<>(); + try { + Collections.addAll(valueList, value.split(separator)); + } + catch (PatternSyntaxException ex) { + LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceNameFromMDC(), new ErrorLogOptionalData(),"Exception occured at method {}, message: {}", methodName, ex.getMessage()); + LOG.debug("Exception occured at method {}, message: {}", methodName, ex.getMessage(), ex); + valueList.add(value); + } + return valueList; + } + + public static ICatalogQuery getFilterQuery(List componentTypeList, List categoryList, List distributedList, + List lifecycleStateList,List lastUpdaterList, Boolean archive) { + List> queryList = new ArrayList<>(); + if (componentTypeList != null && !componentTypeList.isEmpty()) { + queryList.add(new QueryFilterBuilderForComponentType(componentTypeList).getQueryForParameter()); + } + + if (categoryList != null && !categoryList.isEmpty()) { + queryList.add(new QueryFilterBuilderForCategory(categoryList).getQueryForParameter()); + } + + if (distributedList != null && !distributedList.isEmpty()) { + queryList.add(new QueryFilterBuilderForDistributionStatus(distributedList).getQueryForParameter()); + } + + if (lifecycleStateList != null && !lifecycleStateList.isEmpty()) { + queryList.add(new QueryFilterBuilderForLifecycleState(lifecycleStateList).getQueryForParameter()); + } + + if (lastUpdaterList != null && !lastUpdaterList.isEmpty()) { + queryList.add(new QueryFilterBuilderForLastUpdater(lastUpdaterList).getQueryForParameter()); + } + + if (archive != null && archive) { + queryList.add(ICatalogElement::isArchived); + } + //Default should be not archived + else{ + queryList.add(e -> !e.isArchived()); + } + queryList.add(c -> c.getResourceType() != ResourceTypeEnum.Configuration); + return () -> queryList; + } + + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForCategory.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForCategory.java new file mode 100644 index 0000000..6a39277 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForCategory.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.api.ICatalogElement; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +public class QueryFilterBuilderForCategory extends QueryFilterBuilder { + + QueryFilterBuilderForCategory(List values) { + super(values); + } + + @Override + public Predicate buildQueryForElement(String element) { + Predicate predicate = c -> true; + ArrayList categoryWithSubcategory = parseComplexValue(element, SUB_TYPE_SEPARATOR); + + if (!StringUtils.isEmpty(categoryWithSubcategory.get(0))) { + predicate = predicate.and(c -> categoryWithSubcategory.get(0).equals(c.getCategory())); + } + if (categoryWithSubcategory.size() > 1 && !StringUtils.isEmpty(categoryWithSubcategory.get(1))) { + predicate = predicate.and(c -> categoryWithSubcategory.get(1).equals(c.getSubCategory())); + } + return predicate; + + } +} \ No newline at end of file diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForComponentType.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForComponentType.java new file mode 100644 index 0000000..5973375 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForComponentType.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; + +public class QueryFilterBuilderForComponentType extends QueryFilterBuilder { + + QueryFilterBuilderForComponentType(List values) { + super(values); + } + + @Override + public Predicate buildQueryForElement(String element) { + Predicate predicate = c->true; + ArrayList componentWithResourceType = parseComplexValue(element, SUB_TYPE_SEPARATOR); + + ComponentTypeEnum componentTypeEnum = getComponentType(componentWithResourceType.get(0)); + if (componentTypeEnum != null) { + predicate = c->c.getComponentType() == componentTypeEnum; + } + if (componentWithResourceType.size() > 1) { + ResourceTypeEnum resourceTypeEnum = getResourceType(componentWithResourceType.get(1)); + if (resourceTypeEnum != null) { + predicate = predicate.and(c-> c.getResourceType() == resourceTypeEnum); + } + } + return predicate; + } + + private static ComponentTypeEnum getComponentType(String componentType) { + return componentType != null ? + ComponentTypeEnum.findByHeaderName(componentType) : null; + } + + private static ResourceTypeEnum getResourceType(String resourceType) { + return resourceType != null ? + ResourceTypeEnum.getType(resourceType) : null; + } + + +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForDistributionStatus.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForDistributionStatus.java new file mode 100644 index 0000000..fc014f1 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForDistributionStatus.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.enums.DistributionStatusEnum; + +import java.util.List; +import java.util.function.Predicate; + +public class QueryFilterBuilderForDistributionStatus extends QueryFilterBuilder { + + QueryFilterBuilderForDistributionStatus(List statuses) { + super(statuses); + } + + @Override + public Predicate buildQueryForElement(String element){ + DistributionStatusEnum distributionStatusEnum = DistributionStatusEnum.findState(element); + if (distributionStatusEnum != null) { + return c -> c.getDistributionStatus() == distributionStatusEnum; + } + return c -> true; + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLastUpdater.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLastUpdater.java new file mode 100644 index 0000000..342ec48 --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLastUpdater.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.onap.sdc.api.ICatalogElement; + +import java.util.List; +import java.util.function.Predicate; + +public class QueryFilterBuilderForLastUpdater extends QueryFilterBuilder { + QueryFilterBuilderForLastUpdater(List values) { + super(values); + } + + @Override + public Predicate buildQueryForElement(String element) { + if (element != null) { + return c -> element.equals(c.getLastUpdaterUserId()); + } + return c -> null == c.getLastUpdaterUserId(); + } +} diff --git a/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLifecycleState.java b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLifecycleState.java new file mode 100644 index 0000000..e9469fa --- /dev/null +++ b/catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLifecycleState.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.enums.LifecycleStateEnum; + +import java.util.List; +import java.util.function.Predicate; + +public class QueryFilterBuilderForLifecycleState extends QueryFilterBuilder{ + + QueryFilterBuilderForLifecycleState(List values) { + super(values); + } + + @Override + public Predicate buildQueryForElement(String element) { + LifecycleStateEnum lifecycleStateEnum = LifecycleStateEnum.findState(element); + if (lifecycleStateEnum != null) { + return c -> c.getLifecycleState() == lifecycleStateEnum; + } + return c -> true; + } +} diff --git a/catalog-facade-ms/src/main/resources/DME2preferredRouter.txt b/catalog-facade-ms/src/main/resources/DME2preferredRouter.txt new file mode 100644 index 0000000..e69de29 diff --git a/catalog-facade-ms/src/main/resources/application.yml b/catalog-facade-ms/src/main/resources/application.yml new file mode 100644 index 0000000..181c7db --- /dev/null +++ b/catalog-facade-ms/src/main/resources/application.yml @@ -0,0 +1,135 @@ +# Cache micro service configuration file +sdc: + be: + schema: http + host: 192.168.33.10 + port: 8080 + authorization: + username: user + password: password + dmaapConsumerConfiguration: + active: true + transportType: HTTPAAF + hosts: host.com:3904 + consumerGroup: asdc + consumerId: mama #mama - in Order To Consume Remove This String And Replace It With -> mama + timeoutMs: 15000 + limit: 1 + pollingInterval: 2 + topic: com.topic + latitude: 32.109333 + longitude: 34.855499 + version: 1.0 + serviceName: dmaap.com/events + environment: TEST + partner: BOT_R + routeOffer: MR1 + protocol: http + contenttype: application/json + dme2TraceOn: true + aftEnvironment: AFTUAT + aftDme2ConnectionTimeoutMs: 15000 + aftDme2RoundtripTimeoutMs: 240000 + aftDme2ReadTimeoutMs: 50000 + dme2preferredRouterFilePath: DME2preferredRouter.txt + timeLimitForNotificationHandleMs: 120000 + credential: + username: user + password: password + aftDme2SslEnable: true + aftDme2ClientIgnoreSslConfig: false + aftDme2ClientKeystore: /var/opt/catalog-facade-ms/config/truststore + aftDme2ClientKeystorePassword: Password + aftDme2ClientSslCertAlias: certman + + userid: cs0008 + +# the ms host and port need to be updated once deployed on vagrant +server: + address: localhost + port: 8080 + + server.ssl.trust-store: classpath:trustore + server.ssl.trust-store-password: password + server.ssl.trust-store-type: JKS + + server.ssl.key-store: classpath:keystore + server.ssl.key-store-password: password + server.ssl.key-store-type: JKS + #server.ssl.key-alias: tomcat + +scheduling: + job: + rate: + updateCatalogTimestamp: 180000000 + updateUsersTimestamp: 180000000 + dmaapConsumer: 2000 + #Max Time Before Dmaap fetch is cancelled + dmaapConsumerMaxFetchTimeMs: 15000 + +health: + mandatory: + services: #DMAAP + +info: + app: + version: "@project.version@" + +# access restriction +authCookie: + securityKey: "securityKey" + maxSessionTimeOut: 24*60*60*1000 + sessionIdleTimeOut: 2*60*60*1000 + cookieName: "AuthenticationCookie" + path: / + domain: "" + isHttpOnly: true +# redirect variable name from portal_2.properties file + redirectURL: "ecomp_redirect_url" + excludedUrls: /config, /configmgr, /kibanaProxy, /healthcheck, /v1/catalog, /v1/catalog/archive, /v1/catalog/upload.*, /v1/consumers, /v1/screen, /v1/catalogUpdateTime + +aafAuthNeeded: false + +# portal.properties +portal: + portal.api.prefix: /api + max.idle.time: 5 + user.attribute.name: user_attribute +#Use REST API instead of UEB to fetch the functional menu data + use_rest_for_functional_menu: true +########################################################################## +# The following properties MUST be changed by partner applications. +########################################################################## + +# Name of java class that implements the OnBoardingApiService interface. + portal.api.impl.class: org.openecomp.sdc.be.ecomp.PortalRestAPICentralServiceImpl +# Use this tag if the app is centralized remote/local + role_access_centralized: remote + +# URL of the Portal where this app is onboarded + ecomp_redirect_url: http://portal.api.simpledemo.onap.org:8989/ONAPPORTAL/login.htm + +# URL of the ECOMP Portal REST API + ecomp_rest_url: http://portal.api.simpledemo.onap.org:8989/ecompportal/auxapi + +# Applications do not need to run a UEB listener after 1607. + ueb_listeners_enable: false + +#Portal user & key + portal_user: portal_user + portal_pass: portal_pass + portal_app_name: portal_app_name + +# UEB Configuration +# If key ueb_listeners_enable is set to false, +# then only the ueb_app_key is required. + ueb_app_key: REPLACE-ME-UEB-APP-KEY-EPSDK-APP-OS + + aafNamespace: com.sdc + + auth_namespace: com.sdc + csp_cookie_name: ESSec + csp_gate_keeper_prod_key: PROD + ext_req_connection_timeout: 15000 + ext_req_read_timeout: 20000 + diff --git a/catalog-facade-ms/src/main/resources/key.properties b/catalog-facade-ms/src/main/resources/key.properties new file mode 100644 index 0000000..0315075 --- /dev/null +++ b/catalog-facade-ms/src/main/resources/key.properties @@ -0,0 +1,41 @@ +### +# ============LICENSE_START========================================== +# ONAP Portal SDK +# =================================================================== +# Copyright © 2017 AT&T Intellectual Property. All rights reserved. +# =================================================================== +# +# Unless otherwise specified, all software contained herein is licensed +# under the Apache License, Version 2.0 (the “License”); +# you may not use this software 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. +# +# Unless otherwise specified, all documentation contained herein is licensed +# under the Creative Commons License, Attribution 4.0 Intl. (the “License”); +# you may not use this documentation except in compliance with the License. +# You may obtain a copy of the License at +# +# https://creativecommons.org/licenses/by/4.0/ +# +# Unless required by applicable law or agreed to in writing, documentation +# 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============================================ +# +# +### + +# Properties read by the ECOMP Framework library (epsdk-fw) + +cipher.enc.key = AGLDdG4D04BKm2IxIWEr8o== \ No newline at end of file diff --git a/catalog-facade-ms/src/main/resources/keystore b/catalog-facade-ms/src/main/resources/keystore new file mode 100644 index 0000000..e69de29 diff --git a/catalog-facade-ms/src/main/resources/logback.xml b/catalog-facade-ms/src/main/resources/logback.xml new file mode 100644 index 0000000..1ca6c94 --- /dev/null +++ b/catalog-facade-ms/src/main/resources/logback.xml @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log + + + + + WARN + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log.%i + + 1 + 10 + + + + 20MB + + + ${error-log-pattern} + + + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log + + + + + + + e.level.toInt() <= INFO.toInt() + + + DENY + + ACCEPT + + + + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log.%i + + 1 + 10 + + + + 20MB + + + ${debug-log-pattern} + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/catalog-facade-ms/src/main/resources/truststore b/catalog-facade-ms/src/main/resources/truststore new file mode 100644 index 0000000..e69de29 diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/CatalogControllerTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/CatalogControllerTest.java new file mode 100644 index 0000000..17ad87d --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/CatalogControllerTest.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.controllers; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.IBusinessLogic; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.api.ILeftPalletUIElement; +import org.onap.sdc.enums.SdcResponseFieldEnum; +import org.onap.sdc.utils.Utils; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +@RunWith(MockitoJUnitRunner.class) +public class CatalogControllerTest { + + private static final String path = "/uicache/v1/catalog"; + private MockMvc mockMvc; + + @Mock + private IBusinessLogic businessLogic; + @Mock + private ICatalogElement element; + @Captor + private ArgumentCaptor captor; + + @InjectMocks + private CatalogController controller; + + @Before + public void setUp() { + mockMvc = MockMvcBuilders.standaloneSetup(controller) + // .setControllerAdvice(new ExceptionHandler()) + .build(); + } + + @Test + public void getCatalogWithoutParameters_AndReturnEmptyLists() throws Exception { + when(businessLogic.getCatalogElements(any(ICatalogQuery.class))).thenReturn(Collections.emptyList()); + MockHttpServletResponse response = mockMvc.perform(get(path).accept(MediaType.APPLICATION_JSON)) + .andReturn() + .getResponse(); + ControllersTestsUtils.verifyResponse(response, 0, 0); + } + + @Test + public void getCatalogWithDistribStatusAndReturnAllComponents() throws Exception { + List elements = new ArrayList<>(); + elements.addAll(Utils.convertComponentsFromJson(Utils.resourcesJson)); + elements.addAll(Utils.convertComponentsFromJson(Utils.servicesJson)); + + when(businessLogic.getCatalogElements(any(ICatalogQuery.class))).thenReturn(elements); + MockHttpServletResponse response = mockMvc.perform(get(path + "?ds=distributed")) + .andReturn() + .getResponse(); + verify(businessLogic, times(1)).getCatalogElements(captor.capture()); + ICatalogQuery query = captor.getValue(); + // ds=distributed, getResourceType() != ResourceTypeEnum.Configuration + // (Always added), arc=false (default value for archive) + assertThat(query.getQueryFilters()).hasSize(3); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + ControllersTestsUtils.verifyResponse(response, 4, 4); + } + + @Test + public void getCatalogWithResourceAndCategoriesParameters() throws Exception { + List elements = Utils.convertComponentsFromJson(Utils.resourcesJson); + when(businessLogic.getCatalogElements(any(ICatalogQuery.class))).thenReturn(elements); + MockHttpServletResponse response = mockMvc + .perform(get(path + "?ct=RESOURCE&cat=database.test").accept(MediaType.APPLICATION_JSON)) + .andReturn() + .getResponse(); + verify(businessLogic).getCatalogElements(captor.capture()); + ICatalogQuery query = captor.getValue(); + // ?ct=RESOURCE, cat=database.test, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(query.getQueryFilters()).hasSize(4); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + ControllersTestsUtils.verifyResponse(response, 4, 0); + } + + @Test + public void getCatalogWithServiceAndDistributedParameters() throws Exception { + List elements = Utils.convertComponentsFromJson(Utils.servicesJson); + when(businessLogic.getCatalogElements(any(ICatalogQuery.class))).thenReturn(elements); + MockHttpServletResponse response = mockMvc + .perform(get(path + "?ct=SERVICE&ds=distributed").accept(MediaType.APPLICATION_JSON)) + .andReturn() + .getResponse(); + verify(businessLogic).getCatalogElements(captor.capture()); + ICatalogQuery query = captor.getValue(); + // ct=SERVICE, ds=distributed, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(query.getQueryFilters()).hasSize(4); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + ControllersTestsUtils.verifyResponse(response, 0, 4); + } + + @Test + public void validateQueryWithServiceAndCategoryParameters() throws Exception { + when(businessLogic.getCatalogElements(any(ICatalogQuery.class))).thenReturn(Collections.emptyList()); + mockMvc.perform(get(path + "?ct=SERVICE&ds=distributed").accept(MediaType.APPLICATION_JSON)) + .andReturn() + .getResponse(); + verify(businessLogic).getCatalogElements(captor.capture()); + ICatalogQuery query = captor.getValue(); + // ct=SERVICE, ds=distributed, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(query.getQueryFilters()).hasSize(4); + List> predicates = query.getQueryFilters(); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isFalse(); + + } + + @Test + public void getCompositionForService() { + Map>> elements = + controller.getLeftPaletteComposition("services", "service"); + + } + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/ControllersTestsUtils.java b/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/ControllersTestsUtils.java new file mode 100644 index 0000000..f1bc1a7 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/ControllersTestsUtils.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.controllers; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.enums.SdcResponseFieldEnum; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class ControllersTestsUtils { + + static void verifyResponse(MockHttpServletResponse response, int resourceCnt, int serviceCnt) throws IOException { + Map> responseMap = ICatalogElement + .buildFromSdcHttpResponse(response.getContentAsString()); + assertThat(responseMap).hasSize(2); + assertThat(responseMap.get(SdcResponseFieldEnum.RESOURCES_LIST.getJsonName())).hasSize(resourceCnt); + assertThat(responseMap.get(SdcResponseFieldEnum.SERVICES_LIST.getJsonName())).hasSize(serviceCnt); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/HealthCheckControllerTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/HealthCheckControllerTest.java new file mode 100644 index 0000000..d815297 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/controllers/HealthCheckControllerTest.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.controllers; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.healthcheck.CatalogFacadeHealth; +import org.onap.sdc.healthcheck.HealthCheckInfo; +import org.onap.sdc.healthcheck.DmaapHealth; +import org.onap.sdc.utils.Utils; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +@RunWith(MockitoJUnitRunner.class) +public class HealthCheckControllerTest { + + private static final String path = "/healthCheck"; + private MockMvc mockMvc; + + @Mock + private CatalogFacadeHealth catalogFacadeHealth; + + @InjectMocks + private HealthCheckController controller; + + @Before + public void setUp() { + mockMvc = MockMvcBuilders.standaloneSetup(controller) + .build(); + } + + @Test + public void getHealthCheckWhenMsIsUp() throws Exception { + HealthCheckInfo dmaapHC = new HealthCheckInfo(DmaapHealth.HC_COMPONENT_DMAAP, HealthCheckInfo.HealthCheckStatus.UP, + null, DmaapHealth.DmaapStatusDescription.OK.getDescription()); + HealthCheckInfo catalogHC = new HealthCheckInfo(CatalogFacadeHealth.HC_COMPONENT_NAME, HealthCheckInfo.HealthCheckStatus.UP, + null, CatalogFacadeHealth.CatalogFacadeMsStatusDescription.OK.getDescription(), Collections.singletonList(dmaapHC)); + + when(catalogFacadeHealth.getHealthCheckInfo()).thenReturn(catalogHC); + + MockHttpServletResponse response = mockMvc.perform(get(path) + .accept(MediaType.APPLICATION_JSON)) + .andReturn().getResponse(); + List list = Utils.convertHealthCheckResponseFromJson(response.getContentAsString()); + verifyResponse(list.get(0), catalogHC, true); + } + + + @Test + public void getHealthCheckWhenMsIsDown() throws Exception { + HealthCheckInfo dmaapHC = new HealthCheckInfo(DmaapHealth.HC_COMPONENT_DMAAP, HealthCheckInfo.HealthCheckStatus.DOWN, + null, DmaapHealth.DmaapStatusDescription.DOWN.getDescription()); + HealthCheckInfo catalogHC = new HealthCheckInfo(CatalogFacadeHealth.HC_COMPONENT_NAME, HealthCheckInfo.HealthCheckStatus.DOWN, + null, CatalogFacadeHealth.CatalogFacadeMsStatusDescription.DOWN.getDescription(), Collections.singletonList(dmaapHC)); + + when(catalogFacadeHealth.getHealthCheckInfo()).thenReturn(catalogHC); + + MockHttpServletResponse response = mockMvc.perform(get(path) + .accept(MediaType.APPLICATION_JSON)) + .andReturn().getResponse(); + List list = Utils.convertHealthCheckResponseFromJson(response.getContentAsString()); + verifyResponse(list.get(0), catalogHC, true); + } + + private void verifyResponse(HealthCheckInfo actual, HealthCheckInfo expected, boolean isExternal) { + assertThat(actual.getHealthCheckComponent()).isEqualTo(expected.getHealthCheckComponent()); + assertThat(actual.getHealthCheckStatus()).isEqualTo(expected.getHealthCheckStatus()); + assertThat(actual.getVersion()).isEqualTo(expected.getVersion()); + assertThat(actual.getDescription()).isEqualTo(expected.getDescription()); + if (isExternal) { + assertThat(actual.getComponentsInfo()).hasSize(1); + verifyResponse(actual.getComponentsInfo().get(0), expected.getComponentsInfo().get(0), false); + } + } + + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/CatalogFacadeHealthCheckTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/CatalogFacadeHealthCheckTest.java new file mode 100644 index 0000000..cfc16d4 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/CatalogFacadeHealthCheckTest.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.healthcheck; + +import org.assertj.core.util.Lists; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class CatalogFacadeHealthCheckTest { + @Mock + private DmaapHealth dmaapHealth; + @InjectMocks + private CatalogFacadeHealth catalogFacadeHealth; + + @Test + public void getHealthWhenDmaapStatusIsUnknownAndDmaapIsMandatory() { + ReflectionTestUtils.setField(catalogFacadeHealth, "mandatoryServices", Lists.newArrayList(DmaapHealth.HC_COMPONENT_DMAAP, "SDC")); + when(dmaapHealth.getHealthCheckInfo()).thenReturn(DmaapHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo()); + HealthCheckInfo healthCheckInfo = catalogFacadeHealth.getHealthCheckInfo(); + + assertThat(healthCheckInfo.getDescription()).isEqualTo(CatalogFacadeHealth.CatalogFacadeMsStatusDescription.DOWN.getDescription()); + assertThat(healthCheckInfo.getHealthCheckComponent()).isEqualTo(CatalogFacadeHealth.HC_COMPONENT_NAME); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.DOWN); + } + + @Test + public void getHealthWhenDmaapStatusIsUnknownAndDmaapIsNotMandatory() { + ReflectionTestUtils.setField(catalogFacadeHealth, "mandatoryServices", Lists.newArrayList("SDC")); + when(dmaapHealth.getHealthCheckInfo()).thenReturn(DmaapHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo()); + HealthCheckInfo healthCheckInfo = catalogFacadeHealth.getHealthCheckInfo(); + + assertThat(healthCheckInfo.getDescription()).isEqualTo(CatalogFacadeHealth.CatalogFacadeMsStatusDescription.OK.getDescription()); + assertThat(healthCheckInfo.getHealthCheckComponent()).isEqualTo(CatalogFacadeHealth.HC_COMPONENT_NAME); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.UP); + } + + @Test + public void getHealthWhenDmaapStatusIsDownAndDmaapIsNotMandatory() { + ReflectionTestUtils.setField(catalogFacadeHealth, "mandatoryServices", Lists.newArrayList("SDC")); + when(dmaapHealth.getHealthCheckInfo()).thenReturn(DmaapHealth.HealthCheckInfoResult.DOWN.getHealthCheckInfo()); + HealthCheckInfo healthCheckInfo = catalogFacadeHealth.getHealthCheckInfo(); + + assertThat(healthCheckInfo.getDescription()).isEqualTo(CatalogFacadeHealth.CatalogFacadeMsStatusDescription.OK.getDescription()); + assertThat(healthCheckInfo.getHealthCheckComponent()).isEqualTo(CatalogFacadeHealth.HC_COMPONENT_NAME); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.UP); + } + + @Test + public void getHealthWhenDmaapStatusIsUpAndMsStatusIsUpAndDmaapIsMandatory() { + ReflectionTestUtils.setField(catalogFacadeHealth, "mandatoryServices", Lists.newArrayList(DmaapHealth.HC_COMPONENT_DMAAP)); + when(dmaapHealth.getHealthCheckInfo()).thenReturn(DmaapHealth.HealthCheckInfoResult.OK.getHealthCheckInfo()); + HealthCheckInfo healthCheckInfo = catalogFacadeHealth.getHealthCheckInfo(); + + assertThat(healthCheckInfo.getComponentsInfo()).isNull(); + assertThat(healthCheckInfo.getDescription()).isEqualTo(CatalogFacadeHealth.CatalogFacadeMsStatusDescription.OK.getDescription()); + assertThat(healthCheckInfo.getHealthCheckComponent()).isEqualTo(CatalogFacadeHealth.HC_COMPONENT_NAME); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.UP); + } + + @Test + public void getHealthWhenDmaapStatusIsDownAndMsStatusIsUpAndDmaapIsMandatory() { + ReflectionTestUtils.setField(catalogFacadeHealth, "mandatoryServices", Lists.newArrayList(DmaapHealth.HC_COMPONENT_DMAAP)); + when(dmaapHealth.getHealthCheckInfo()).thenReturn(DmaapHealth.HealthCheckInfoResult.DOWN.getHealthCheckInfo()); + HealthCheckInfo healthCheckInfo = catalogFacadeHealth.getHealthCheckInfo(); + + assertThat(healthCheckInfo.getDescription()).isEqualTo(CatalogFacadeHealth.CatalogFacadeMsStatusDescription.DOWN.getDescription()); + assertThat(healthCheckInfo.getHealthCheckComponent()).isEqualTo(CatalogFacadeHealth.HC_COMPONENT_NAME); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.DOWN); + } +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/DmaapHealthTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/DmaapHealthTest.java new file mode 100644 index 0000000..b1d32a6 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/DmaapHealthTest.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.healthcheck; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.sdc.healthcheck.DmaapHealth.HealthCheckInfoResult.DOWN; +import static org.onap.sdc.healthcheck.DmaapHealth.HealthCheckInfoResult.OK; + +@RunWith(MockitoJUnitRunner.class) +public class DmaapHealthTest { + private DmaapHealth dmaapHealth; + + @Before + public void setUp() { + dmaapHealth = new DmaapHealth(); + } + + @Test + public void getHealthWhenDmaapUp() { + dmaapHealth.report(OK); + HealthCheckInfo healthCheckInfo = dmaapHealth.getHealthCheckInfo(); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.UP); + assertThat(healthCheckInfo.getDescription()).isEqualTo(DmaapHealth.DmaapStatusDescription.OK.getDescription()); + } + + @Test + public void getHealthWhenDmaapStatusUnknown() { + HealthCheckInfo healthCheckInfo = dmaapHealth.getHealthCheckInfo(); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.UNKNOWN); + assertThat(healthCheckInfo.getDescription()).isEqualTo(DmaapHealth.DmaapStatusDescription.UNAVAILABLE.getDescription()); + } + + @Test + public void getHealthWhenDmaapDown() { + dmaapHealth.report(DOWN); + HealthCheckInfo healthCheckInfo = dmaapHealth.getHealthCheckInfo(); + assertThat(healthCheckInfo.getHealthCheckStatus()).isEqualTo(HealthCheckInfo.HealthCheckStatus.DOWN); + assertThat(healthCheckInfo.getDescription()).isEqualTo(DmaapHealth.DmaapStatusDescription.DOWN.getDescription()); + } + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/BusinessLogicImplTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/BusinessLogicImplTest.java new file mode 100644 index 0000000..5eb50aa --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/BusinessLogicImplTest.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.ICacheHandler; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.api.IComponentMessage; +import org.onap.sdc.api.IMessageQueueHandlerConsumer; +import org.onap.sdc.api.IStatus; +import org.onap.sdc.enums.ResultStatusEnum; +import org.onap.sdc.utils.Utils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class BusinessLogicImplTest { + + BusinessLogicImpl bl; + @Mock + ICacheHandler cacheHandler; + @Mock + IMessageQueueHandlerConsumer messageHandler; + @Mock + IComponentMessage message; + + @Before + public void setUp() { + bl = new BusinessLogicImpl(cacheHandler, messageHandler); + } + + @Test + public void testGetCatalogElements() { + ICatalogQuery query = mock(ICatalogQuery.class); + bl.getCatalogElements(query); + verify(cacheHandler, times(1)).getCatalogElements(query); + + } + + @Test + public void testDoOnComponentMessageReceive() { + when(cacheHandler.handleComponentMessage(any())).thenReturn(IStatus.getSuccessStatus()); + IStatus status = bl.doOnMessageReceive(Utils.componentMsgJson); + verify(cacheHandler, times(1)).handleComponentMessage(any()); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + + } + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheHandlerImplTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheHandlerImplTest.java new file mode 100644 index 0000000..981220e --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheHandlerImplTest.java @@ -0,0 +1,360 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.sdc.enums.SdcResponseFieldEnum.RESOURCES_LIST; +import static org.onap.sdc.enums.SdcResponseFieldEnum.SERVICES_LIST; + +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.NotImplementedException; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.onap.sdc.api.*; +import org.onap.sdc.enums.ChangeTypeEnum; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.ResultStatusEnum; +import org.onap.sdc.impl.message.CatalogUpdateTimestampImpl; +import org.onap.sdc.utils.Utils; + +@RunWith(MockitoJUnitRunner.class) +public class CacheHandlerImplTest { + @InjectMocks + private CacheHandlerImpl cacheHandler; + // Injected Mocks + @Mock + private ICache cache; + @Mock + private IBeDataRetriever beDataRetriever; + @Mock + private ICatalogUpdateTimestampContainer catalogUpdateTimestampContainer; + + // Other Mocks + @Mock + private ICatalogElement catalogElement; + @Mock + private IComponentMessage componentMessage; + + @Captor + private ArgumentCaptor eventCaptor; + @Captor + private ArgumentCaptor> listEventCaptor; + + private ICatalogElement v1NotArchived = CatalogElementUtils.createMockCatalogElement("1.0", false); + private ICatalogElement v2NotArchived = CatalogElementUtils.createMockCatalogElement("2.0", false); + + private ICatalogElement v1Archived = CatalogElementUtils.createMockCatalogElement("1.0", true); + private ICatalogElement v2Archived = CatalogElementUtils.createMockCatalogElement("2.0", true); + + + @Before + public void beforeTests() { + when(componentMessage.getUniqueId()).thenReturn(UUID.randomUUID() + .toString()); + when(beDataRetriever.getArchiveCatalogResponseBody()) + .thenReturn(format("{\"%s\":[],\"%s\":[]}", RESOURCES_LIST.getJsonName(), SERVICES_LIST.getJsonName())); + mockCacheWithPredicate(); + } + + @Test + public void testInitilizeCacheHandler() { + assertThat(cacheHandler).isNotNull(); + } + + @Test + public void testInitUnhappyFlow() { + IStatus iStatus = cacheHandler.init(); + assertThat(iStatus.getResultStatus() == ResultStatusEnum.FAIL).isTrue(); + } + + @Test + public void testInitHappyFlowEmptyResponse() { + when(beDataRetriever.getCatalogResponseBody()) + .thenReturn(format("{\"%s\":[],\"%s\":[]}", RESOURCES_LIST.getJsonName(), SERVICES_LIST.getJsonName())); + when(beDataRetriever.getUpdateTimeResponseBody()).thenReturn(Utils.timestampJson); + IStatus iStatus = cacheHandler.init(); + assertThat(iStatus.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + } + + @Test + public void testInitHappyFlowWithSdcDataReturned() { + when(beDataRetriever.getCatalogResponseBody()) + .thenReturn(format("{\"%s\":[%s,%s],\"%s\":[%s]}", RESOURCES_LIST.getJsonName(), CatalogElementUtils.PORT_RESOURCE, + CatalogElementUtils.NETWORK_REOSURCE, SERVICES_LIST.getJsonName(), CatalogElementUtils.TEST_SERVICE)); + when(beDataRetriever.getUpdateTimeResponseBody()).thenReturn(Utils.timestampJson); + IStatus iStatus = cacheHandler.init(); + assertThat(iStatus.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + verify(cache, times(1)).fillCacheSafety(listEventCaptor.capture()); + List cacheMap = listEventCaptor.getValue(); + + assertThat(cacheMap) + .anyMatch(e -> StringUtils.equals(e.getUniqueId(), CatalogElementUtils.UNIQUE_ID_PORT_RESOURCE)) + .anyMatch(e -> StringUtils.equals(e.getUniqueId(), CatalogElementUtils.UNIQUE_ID_NETWORK_RESOURCE)) + .filteredOn(e -> e.getComponentType() == ComponentTypeEnum.RESOURCE) + .hasSize(2); + assertThat(cacheMap) + .anyMatch(e -> StringUtils.equals(e.getUniqueId(), CatalogElementUtils.UNIQUE_ID_SERVICE)) + .anyMatch(e -> e.getComponentType() == ComponentTypeEnum.SERVICE) + .anyMatch(e -> e.getDistributionStatus() == DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + } + + @Test + public void testInitHappyFlowWithWrongDistributionStatusWhenSdcDataIsReturnedSuccessfully() { + when(beDataRetriever.getCatalogResponseBody()) + .thenReturn(format("{\"%s\":[%s,%s],\"%s\":[%s]}", RESOURCES_LIST.getJsonName(), CatalogElementUtils.PORT_RESOURCE, + CatalogElementUtils.NETWORK_REOSURCE, SERVICES_LIST.getJsonName(), CatalogElementUtils.TEST_SERVICE_WRONG_DISTRIB_STATUS)); + when(beDataRetriever.getUpdateTimeResponseBody()).thenReturn(Utils.timestampJson); + IStatus iStatus = cacheHandler.init(); + assertThat(iStatus.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + verify(cache, times(1)).fillCacheSafety(listEventCaptor.capture()); + List cacheMap = listEventCaptor.getValue(); + assertThat(cacheMap) + .anyMatch(e -> StringUtils.equals(e.getUniqueId(), CatalogElementUtils.UNIQUE_ID_PORT_RESOURCE)) + .anyMatch(e -> StringUtils.equals(e.getUniqueId(), CatalogElementUtils.UNIQUE_ID_NETWORK_RESOURCE)) + .filteredOn(e -> e.getComponentType() == ComponentTypeEnum.RESOURCE) + .hasSize(2); + assertThat(cacheMap) + .anyMatch(e -> StringUtils.equals(e.getUniqueId(), CatalogElementUtils.UNIQUE_ID_SERVICE)) + .anyMatch(e -> e.getComponentType() == ComponentTypeEnum.SERVICE) + // distribution status is ignored as it was wrong + .anyMatch(e -> e.getDistributionStatus() == null); + } + + @Test + public void testCreateHappyFlow() { + IStatus status = cacheHandler.createCatalogElementInCache(catalogElement); + verify(cache, times(1)).put(catalogElement); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + } + + @Test + public void reloadCatalogWhenBeHttpResponseShowsThatSomeUpdatesGotLost() { + when(catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(any(CatalogUpdateTimestampImpl.class))) + .thenReturn(true); + when(beDataRetriever.getCatalogResponseBody()) + .thenReturn(format("{\"%s\":[%s,%s],\"%s\":[%s]}", RESOURCES_LIST.getJsonName(), CatalogElementUtils.PORT_RESOURCE, + CatalogElementUtils.NETWORK_REOSURCE, SERVICES_LIST.getJsonName(), CatalogElementUtils.TEST_SERVICE)); + when(beDataRetriever.getUpdateTimeResponseBody()).thenReturn(Utils.timestampJson); + assertThat(cacheHandler.reloadCatalogIfRequired(new CatalogUpdateTimestampImpl(), false)).isTrue(); + } + + @Test + public void reloadCatalogFailedWhenBeHttpResponseShowsThatSomeUpdatesGotLost() { + when(catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(any(CatalogUpdateTimestampImpl.class))) + .thenReturn(true); + when(beDataRetriever.getCatalogResponseBody()).thenReturn(""); + assertThat(cacheHandler.reloadCatalogIfRequired(new CatalogUpdateTimestampImpl(), false)).isFalse(); + } + + @Test + public void reloadCatalogFailedWhenReceivedNotificationShowsThatSomeUpdatesGotLost() { + when(catalogUpdateTimestampContainer.updatesLostAsPerNotification(any(CatalogUpdateTimestampImpl.class))) + .thenReturn(true); + when(beDataRetriever.getCatalogResponseBody()).thenReturn(""); + assertThat(cacheHandler.reloadCatalogIfRequired(new CatalogUpdateTimestampImpl(), true)).isFalse(); + } + + @Test + public void reloadCatalogNotNeededWhenNothingIsLostByNotification() { + when(catalogUpdateTimestampContainer.updatesLostAsPerNotification(any(CatalogUpdateTimestampImpl.class))) + .thenReturn(false); + assertThat(cacheHandler.reloadCatalogIfRequired(new CatalogUpdateTimestampImpl(), true)).isFalse(); + } + + @Test + public void reloadCatalogNotNeededWhenNothingIsLostByHttpRequest() { + when(catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(any(CatalogUpdateTimestampImpl.class))) + .thenReturn(false); + assertThat(cacheHandler.reloadCatalogIfRequired(new CatalogUpdateTimestampImpl(), false)).isFalse(); + } + + @Test + public void testHandleNewMessageWhenCacheReloadFailed() { + when(componentMessage.getChangeType()).thenReturn(ChangeTypeEnum.DELETE); + IStatus status = cacheHandler.handleComponentMessage(componentMessage); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + verify(cache, times(0)).fillCacheSafety(anyList()); + verify(cache, times(1)).evict(Mockito.any(ICatalogElement.class)); + } + + @Test + public void sendHttpGetTimestampRequestAndReloadCache() { + when(beDataRetriever.getUpdateTimeResponseBody()).thenReturn(Utils.timestampJson); + when(catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(any(ICatalogUpdateTimestamp.class))) + .thenReturn(true); + when(beDataRetriever.getCatalogResponseBody()) + .thenReturn(format("{\"%s\":[%s,%s],\"%s\":[%s]}", RESOURCES_LIST.getJsonName(), CatalogElementUtils.PORT_RESOURCE, + CatalogElementUtils.NETWORK_REOSURCE, SERVICES_LIST.getJsonName(), CatalogElementUtils.TEST_SERVICE)); + IStatus status = cacheHandler.loadCatalogIfNotificationsLost(); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + verify(cache, times(1)).fillCacheSafety(anyList()); + } + + @Test + public void testCreateUnhappyFlow() { + doThrow(new NotImplementedException("Some Mock Cache Error")).when(cache) + .put(catalogElement); + IStatus status = cacheHandler.createCatalogElementInCache(catalogElement); + verify(cache, times(1)).put(catalogElement); + assertThat(status.getResultStatus() == ResultStatusEnum.FAIL).isTrue(); + } + + @Test + public void testUpdateHappyFlow() { + IStatus status = cacheHandler.updateCatalogElementInCache(catalogElement); + verify(cache, times(1)).update(catalogElement); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + } + + @Test + public void testUpdateUnhappyFlow() { + doThrow(new NotImplementedException("Some Mock Update Cache Error")).when(cache) + .update(catalogElement); + IStatus status = cacheHandler.updateCatalogElementInCache(catalogElement); + verify(cache, times(1)).update(catalogElement); + assertThat(status.getResultStatus() == ResultStatusEnum.FAIL).isTrue(); + } + + @Test + public void testHandleNewComponentMessageWithCreate() { + when(componentMessage.getChangeType()).thenReturn(ChangeTypeEnum.LIFECYCLE); + IStatus status = cacheHandler.handleComponentMessage(componentMessage); + verify(cache, times(1)).updateOrCreate(eventCaptor.capture()); + verify(cache, times(0)).evict(catalogElement); + verify(cache, times(0)).update(any()); + ICatalogElement element = eventCaptor.getValue(); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + assertThat(StringUtils.equals(element.getUniqueId(), componentMessage.getUniqueId())).isTrue(); + + } + + @Test + public void testHandleNewComponentMessageWithDelete() { + when(componentMessage.getChangeType()).thenReturn(ChangeTypeEnum.DELETE); + IStatus status = cacheHandler.handleComponentMessage(componentMessage); + verify(cache, times(0)).put(any()); + verify(cache, times(1)).evict(componentMessage); + verify(cache, times(0)).update(any()); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + } + + @Test + public void testHandleNewComponentMessageWithUpdate() { + when(componentMessage.getChangeType()).thenReturn(ChangeTypeEnum.LIFECYCLE); + IStatus status = cacheHandler.handleComponentMessage(componentMessage); + verify(cache, times(0)).put(any()); + verify(cache, times(0)).evict(catalogElement); + verify(cache, times(1)).updateOrCreate(eventCaptor.capture()); + + ICatalogElement element = eventCaptor.getValue(); + assertThat(status.getResultStatus() == ResultStatusEnum.SUCCESS).isTrue(); + assertThat(StringUtils.equals(element.getUniqueId(), componentMessage.getUniqueId())).isTrue(); + } + + @Test + public void testHandleNewComponentMessageWithWrongChangeType() { + when(componentMessage.getChangeType()).thenReturn(null); + IStatus status = cacheHandler.handleComponentMessage(componentMessage); + verify(cache, times(0)).put(any()); + verify(cache, times(0)).evict(catalogElement); + verify(cache, times(0)).update(any()); + assertThat(status.getResultStatus() == ResultStatusEnum.FAIL).isTrue(); + } + + @Test + public void testFilterCatalogElementsOneElementReturned() { + + ICatalogQuery query = mock(ICatalogQuery.class); + + when(query.getQueryFilters()) + .thenReturn(Arrays.asList(e -> StringUtils.equals(e.getVersion(), "1.0"), ICatalogElement::isArchived)); + + List elements = cacheHandler.getCatalogElements(query); + + assertThat(elements.size()).isEqualTo(NumberUtils.INTEGER_ONE); + assertThat(elements).contains(v1Archived); + } + + @Test + public void testFilterCatalogElementsMultipleElementReturned() { + + ICatalogQuery query = mock(ICatalogQuery.class); + + when(query.getQueryFilters()).thenReturn(Collections.singletonList(ICatalogElement::isArchived)); + + List elements = cacheHandler.getCatalogElements(query); + + assertThat(elements.size()).isEqualTo(2); + assertThat(elements).contains(v1Archived, v2Archived); + } + + @Test + public void testFilterCatalogElementsNoElementReturned() { + + ICatalogQuery query = mock(ICatalogQuery.class); + + when(query.getQueryFilters()) + .thenReturn(Arrays.asList(e -> StringUtils.equals(e.getVersion(), "1.1"), ICatalogElement::isArchived)); + + List elements = cacheHandler.getCatalogElements(query); + + assertThat(elements.size()).isEqualTo(NumberUtils.INTEGER_ZERO); + } + + @SuppressWarnings("unchecked") + private void mockCacheWithPredicate() { + List elementsInCache = Arrays.asList(v1NotArchived, v2NotArchived, v1Archived, v2Archived); + + doAnswer((Answer>) invocation -> { + Predicate pred = (Predicate) invocation.getArguments()[0]; + return elementsInCache.stream() + .filter(pred) + .collect(Collectors.toList()); + }).when(cache) + .get(any(Predicate.class)); + } + + + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheImplTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheImplTest.java new file mode 100644 index 0000000..4bc0fc8 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheImplTest.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ILatestElements; +import org.onap.sdc.enums.LifecycleStateEnum; + +@RunWith(MockitoJUnitRunner.class) +public class CacheImplTest { + @InjectMocks + private CacheImpl cacheImpl = new CacheImpl() ; + @Mock + private Map cache ; + @Captor + private ArgumentCaptor eventCaptor; + @Captor + private ArgumentCaptor idCaptor; + + private ICatalogElement v1NotArchived = mock(ICatalogElement.class); + + private ILatestElements latestElement = CatalogElementUtils.createMockLatestElements(); + + private String uniqueId = CatalogElementUtils.UNIQUE_ID_NETWORK_RESOURCE; + + @Before + public void beforeTests() { + cacheImpl.setCache(cache); + } + + @Test + public void testHandleNewComponentMessageWithCreate() { + when(v1NotArchived.getLifecycleState()).thenReturn(LifecycleStateEnum.CHECKOUT); + when(v1NotArchived.getInvariantUUID()).thenReturn(CatalogElementUtils.UNIQUE_ID_NETWORK_RESOURCE); + when(cache.get(CatalogElementUtils.UNIQUE_ID_NETWORK_RESOURCE)).thenReturn(latestElement); + + cacheImpl.updateOrCreate(v1NotArchived); + + verify(cache, times(1)).put(idCaptor.capture(), eventCaptor.capture()); + } + + @Test + public void testReplaceNonCertifiedElementInCache(){ + Map cache = new ConcurrentHashMap<>(); + ILatestElements latestElement = new LatestElementsImpl(); + ICatalogElement newElement = createNewCacheElement(LifecycleStateEnum.CHECKOUT); + cache.put(uniqueId, latestElement); + + cacheImpl.put(cache, newElement); + + ILatestElements element = cache.get(uniqueId); + assertThat(element.getNonCertifiedElement().getLifecycleState()).isEqualTo(LifecycleStateEnum.CHECKOUT); + } + + @Test + public void testPutNonCertifiedElementInCache(){ + Map cache = new ConcurrentHashMap<>(); + ICatalogElement newElement = createNewCacheElement(LifecycleStateEnum.CHECKOUT); + + cacheImpl.put(cache, newElement); + + ILatestElements element = cache.get(uniqueId); + assertThat(element.getNonCertifiedElement().getLifecycleState()).isEqualTo(LifecycleStateEnum.CHECKOUT); + } + + @Test + public void testReplaceCertifiedElementInCache(){ + Map cache = new ConcurrentHashMap<>(); + ILatestElements latestElement = new LatestElementsImpl(); + ICatalogElement newElement = createNewCacheElement(LifecycleStateEnum.CERTIFIED); + cache.put(uniqueId, latestElement); + + cacheImpl.put(cache, newElement); + + ILatestElements element = cache.get(uniqueId); + assertThat(element.getCertifiedElement().getLifecycleState()).isEqualTo(LifecycleStateEnum.CERTIFIED); + } + + @Test + public void testPutCertifiedElementInCache(){ + Map cache = new ConcurrentHashMap<>(); + ICatalogElement newElement = createNewCacheElement(LifecycleStateEnum.CERTIFIED); + + cacheImpl.put(cache, newElement); + + ILatestElements element = cache.get(uniqueId); + assertThat(element.getCertifiedElement().getLifecycleState()).isEqualTo(LifecycleStateEnum.CERTIFIED); + } + + private ICatalogElement createNewCacheElement(LifecycleStateEnum lifeCycleState){ + ICatalogElement newElement = new CatalogElementImpl(); + String uniqueId = CatalogElementUtils.UNIQUE_ID_NETWORK_RESOURCE; + + newElement.setInvariantUUID(uniqueId); + newElement.setLifecycleState(lifeCycleState); + + return newElement; + } +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CatalogElementUtils.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CatalogElementUtils.java new file mode 100644 index 0000000..3a2232e --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/CatalogElementUtils.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl; + +import static java.lang.String.format; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ILatestElements; + +public class CatalogElementUtils { + + public static final String UNIQUE_ID_PORT_RESOURCE = "c330307d-7f2e-4817-ae05-e3324fc118fe"; + public static final String UNIQUE_ID_NETWORK_RESOURCE = "0ddce645-3dcd-4cad-91eb-33a4bc46f94c"; + public static final String UNIQUE_ID_SERVICE = "ad2a58da-cf73-44da-862b-c3274175173a"; + + public static ICatalogElement createMockCatalogElement(final String version, final boolean isArchive) { + ICatalogElement e1 = mock(ICatalogElement.class); + when(e1.isArchived()).thenReturn(isArchive); + when(e1.getVersion()).thenReturn(version); + return e1; + } + + public static ILatestElements createMockLatestElements() { + ILatestElements e1 = mock(ILatestElements.class); + + return e1; + } + + public static final String NETWORK_REOSURCE = format(" {\r\n" + " \"version\": \"1.0\",\r\n" + + " \"componentType\": \"RESOURCE\",\r\n" + " \"icon\": \"network\",\r\n" + + " \"uniqueId\": \"%s\",\r\n" + " \"lifecycleState\": \"CERTIFIED\",\r\n" + + " \"lastUpdateDate\": 1526280416111,\r\n" + " \"name\": \"NeutronNet\",\r\n" + + " \"resourceType\": \"VL\",\r\n" + " \"categoryNormalizedName\": \"generic\",\r\n" + + " \"subCategoryNormalizedName\": \"network elements\"\r\n" + " }", + UNIQUE_ID_NETWORK_RESOURCE); + + public static final String PORT_RESOURCE = format(" {\r\n" + " \"version\": \"1.0\",\r\n" + + " \"componentType\": \"RESOURCE\",\r\n" + " \"icon\": \"port\",\r\n" + + " \"uniqueId\": \"%s\",\r\n" + " \"lifecycleState\": \"CERTIFIED\",\r\n" + + " \"lastUpdateDate\": 1526280384338,\r\n" + " \"name\": \"Port\",\r\n" + + " \"resourceType\": \"CP\",\r\n" + " \"categoryNormalizedName\": \"generic\",\r\n" + + " \"subCategoryNormalizedName\": \"network elements\"\r\n" + " }", + UNIQUE_ID_PORT_RESOURCE); + + public static final String TEST_SERVICE = format( + "{\r\n" + " \"version\": \"0.1\",\r\n" + " \"componentType\": \"SERVICE\",\r\n" + + " \"icon\": \"defaulticon\",\r\n" + " \"uniqueId\": \"%s\",\r\n" + + " \"lifecycleState\": \"NOT_CERTIFIED_CHECKOUT\",\r\n" + + " \"lastUpdateDate\": 1526283324377,\r\n" + + " \"name\": \"Service4Test\",\r\n" + + " \"categoryNormalizedName\": \"mobility\",\r\n" + + " \"distributionStatus\": \"DISTRIBUTION_NOT_APPROVED\"\r\n" + " }", + UNIQUE_ID_SERVICE); + + public static final String TEST_SERVICE_WRONG_DISTRIB_STATUS = format( + "{\r\n" + " \"version\": \"0.1\",\r\n" + " \"componentType\": \"SERVICE\",\r\n" + + " \"icon\": \"defaulticon\",\r\n" + " \"uniqueId\": \"%s\",\r\n" + + " \"lifecycleState\": \"NOT_CERTIFIED_CHECKOUT\",\r\n" + + " \"lastUpdateDate\": 1526283324377,\r\n" + + " \"name\": \"Service4Test\",\r\n" + + " \"categoryNormalizedName\": \"mobility\",\r\n" + + " \"distributionStatus\": \"Distribution not approved\"\r\n" + " }", + UNIQUE_ID_SERVICE); + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImplTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImplTest.java new file mode 100644 index 0000000..4ac30c9 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImplTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.junit.Before; +import org.junit.Test; +import org.onap.sdc.api.ICatalogUpdateTimestamp; +import org.onap.sdc.utils.Utils; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class CatalogUpdateTimestampImplTest { + + private ICatalogUpdateTimestamp catalogUpdateTimestamp; + private ICatalogUpdateTimestamp anotherTimestamp; + + @Before + public void setUp() { + catalogUpdateTimestamp = new CatalogUpdateTimestampImpl(); + anotherTimestamp = new CatalogUpdateTimestampImpl(); + + } + @Test + public void setTimestamp() { + anotherTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + anotherTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + assertThat(catalogUpdateTimestamp.getCurrentUpdateTime()).isEqualTo(0); + assertThat(catalogUpdateTimestamp.getPreviousUpdateTime()).isEqualTo(0); + catalogUpdateTimestamp.set(anotherTimestamp); + assertThat(catalogUpdateTimestamp.getCurrentUpdateTime()).isEqualTo(Utils.currUpdateTime); + assertThat(catalogUpdateTimestamp.getPreviousUpdateTime()).isEqualTo(Utils.prevUpdateTime); + } + + @Test + public void isSameUpdateReturnsTrue() { + anotherTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + anotherTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + catalogUpdateTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + catalogUpdateTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + assertThat(catalogUpdateTimestamp.isSameUpdate(anotherTimestamp)).isTrue(); + } + + @Test + public void isSameUpdateReturnsFalse() { + anotherTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + anotherTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + catalogUpdateTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + catalogUpdateTimestamp.setCurrentUpdateTime(Utils.currUpdateTime + 1234); + assertThat(catalogUpdateTimestamp.isSameUpdate(anotherTimestamp)).isFalse(); + } + + @Test + public void isNextUpdateReturnsTrue() { + anotherTimestamp.setPreviousUpdateTime(Utils.currUpdateTime); + anotherTimestamp.setCurrentUpdateTime(Utils.currUpdateTime + 12345); + catalogUpdateTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + catalogUpdateTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + assertThat(catalogUpdateTimestamp.isNextUpdate(anotherTimestamp)).isTrue(); + } + + @Test + public void isNextUpdateReturnsFalse() { + anotherTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + anotherTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + catalogUpdateTimestamp.setPreviousUpdateTime(Utils.prevUpdateTime); + catalogUpdateTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + assertThat(catalogUpdateTimestamp.isNextUpdate(anotherTimestamp)).isFalse(); + } + + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainerTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainerTest.java new file mode 100644 index 0000000..90e0005 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainerTest.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.ICatalogUpdateTimestamp; +import org.onap.sdc.utils.Utils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class CatalogUpdateTimestampSyncContainerTest { + @InjectMocks + private CatalogUpdateTimestampSyncContainer catalogUpdateTimestampContainer; + @Mock + private ICatalogUpdateTimestamp timestamp; + + @Test + public void isUpdateAlreadyDone() { + ICatalogUpdateTimestamp notifyTimestamp = new CatalogUpdateTimestampImpl(); + notifyTimestamp.setCurrentUpdateTime(Utils.currUpdateTime); + when(timestamp.getCurrentUpdateTime()).thenReturn(Utils.currUpdateTime); + assertThat(catalogUpdateTimestampContainer.isUpdatedAlready(notifyTimestamp)).isTrue(); + verify(timestamp, times(0)).set(any(CatalogUpdateTimestampImpl.class)); + } + + @Test + public void isUpdateAlreadyDoneFalse() { + ICatalogUpdateTimestamp notifyTimestamp = new CatalogUpdateTimestampImpl(); + notifyTimestamp.setCurrentUpdateTime(Utils.currUpdateTime + 1000); + when(timestamp.getCurrentUpdateTime()).thenReturn(Utils.currUpdateTime); + assertThat(catalogUpdateTimestampContainer.isUpdatedAlready(notifyTimestamp)) + .isFalse(); + verify(timestamp, times(0)).set(any(CatalogUpdateTimestampImpl.class)); + + } + + @Test + public void isNextUpdateNotification() { + when(timestamp.isNextUpdate(any(ICatalogUpdateTimestamp.class))).thenReturn(true); + assertThat(catalogUpdateTimestampContainer.updatesLostAsPerNotification(new CatalogUpdateTimestampImpl())) + .isFalse(); + verify(timestamp, times(1)).set(any(CatalogUpdateTimestampImpl.class)); + + } + @Test + public void someUpdatesLostAsPerLastNotification() { + when(timestamp.isNextUpdate(any(ICatalogUpdateTimestamp.class))).thenReturn(false); + assertThat(catalogUpdateTimestampContainer.updatesLostAsPerNotification(new CatalogUpdateTimestampImpl())) + .isTrue(); + verify(timestamp, times(1)).set(any(CatalogUpdateTimestampImpl.class)); + + } + + @Test + public void noUpdatesLostAsPerHttpRequest() { + when(timestamp.isSameUpdate(any())).thenReturn(true); + assertThat(catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(new CatalogUpdateTimestampImpl())) + .isFalse(); + verify(timestamp, times(1)).set(any(CatalogUpdateTimestampImpl.class)); + + } + @Test + public void someUpdatesLostAsPerHttpRequest() { + when(timestamp.isSameUpdate(any())).thenReturn(false); + assertThat(catalogUpdateTimestampContainer.updatesLostAsPerHttpBeRequest(new CatalogUpdateTimestampImpl())) + .isTrue(); + verify(timestamp, times(1)).set(any(CatalogUpdateTimestampImpl.class)); + } + + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/ComponentMessageTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/ComponentMessageTest.java new file mode 100644 index 0000000..0944702 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/ComponentMessageTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.IComponentMessage; +import org.onap.sdc.enums.ChangeTypeEnum; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.utils.MessageUtils; +import org.onap.sdc.utils.Utils; +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentMessageTest { + + @Test + public void loadFromJson() throws IOException { + IComponentMessage message = MessageUtils.buildFromMessage(Utils.componentMsgJson, ComponentMessage.class); + assertThat(message.getChangeType()).isEqualTo(ChangeTypeEnum.LIFECYCLE); + assertThat(message.getCatalogUpdateTimestamp().getCurrentUpdateTime()).isEqualTo(Utils.currUpdateTime); + assertThat(message.getCatalogUpdateTimestamp().getPreviousUpdateTime()).isEqualTo(Utils.prevUpdateTime); + assertThat(message.getComponentType()).isEqualTo(ComponentTypeEnum.RESOURCE); + assertThat(message.getLifecycleState()).isEqualTo(LifecycleStateEnum.CERTIFIED); + } + + @Test + public void loadFromJsonFailedWhenTimeStampNotProvided() throws IOException { + IComponentMessage message = MessageUtils.buildFromMessage(Utils.componentMsgJsonWithoutTimestamp, ComponentMessage.class); + assertThat(message.getChangeType()).isEqualTo(ChangeTypeEnum.DELETE); + assertThat(message.getCatalogUpdateTimestamp()).isNull(); + assertThat(message.getComponentType()).isNull(); + assertThat(message.getLifecycleState()).isNull(); + } +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerConfigurationTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerConfigurationTest.java new file mode 100644 index 0000000..267093e --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerConfigurationTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.impl.message; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class DmaapConsumerConfigurationTest { + + @Test + public void testConsumerConfigPasswordHidden() { + DmaapConsumerConfiguration consumer = new DmaapConsumerConfiguration(); + String secret = "Top Secret,U Cannot read me!!"; + String topic = "topicName"; + consumer.setTopic(topic); + consumer.setPassword(secret); + assertThat(consumer.toString()).doesNotContain(secret).contains(topic); + } +} \ No newline at end of file diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerTest.java new file mode 100644 index 0000000..cbba562 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerTest.java @@ -0,0 +1,46 @@ +/* + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/* +package org.onap.sdc.impl.message; + +import com.att.nsa.mr.client.MRConsumer; +import org.junit.Test; + +import java.util.Iterator; + +import static com.att.nsa.mr.client.MRClientFactory.createConsumer; + +public class DmaapConsumerTest { + + @Test + public void consumeTest() throws Exception { + MRConsumer mrConsumer = createConsumer("C:\\Projects\\asdc\\catalog-facade-ms\\catalog-facade-ms\\src\\main\\resources\\consumer.properties"); + System.out.println(mrConsumer.toString()); + while (true) { + Iterator itr = mrConsumer.fetch(5000, -1).iterator(); + while (itr.hasNext()) { + String msg = (String) itr.next(); + System.out.println("Message Received: " + msg); + } + System.out.println("awaiting consume..."); + } + } +} */ diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/utils/Utils.java b/catalog-facade-ms/src/test/java/org/onap/sdc/utils/Utils.java new file mode 100644 index 0000000..f3fb641 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/utils/Utils.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.healthcheck.HealthCheckInfo; +import org.onap.sdc.impl.CatalogElementImpl; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class Utils { + + public static long prevUpdateTime = 12345678; + public static long currUpdateTime = 12345678 + 12345; + private static final String singleResourceJson = "\"version\":\"1.0\",\"componentType\":\"RESOURCE\",\"icon\":\"objectStorage\",\"uniqueId\":\"b7581da0-2ea9-41a8-918d-c75e946c6d8c\",\"lifecycleState\":\"CERTIFIED\",\"lastUpdateDate\":1525348424433,\"name\":\"ObjectStorage\",\"resourceType\":\"VFC\",\"categoryNormalizedName\":\"generic\",\"subCategoryNormalizedName\":\"infrastructure\""; + public static final String resourcesJson = "[{" + singleResourceJson + "},{\"version\":\"6.0\",\"componentType\":\"RESOURCE\",\"icon\":\"network\",\"uniqueId\":\"2d83c6fc-5d57-48a5-878b-3a201fa6facc\",\"lifecycleState\":\"CERTIFIED\",\"lastUpdateDate\":1525885954599,\"name\":\"ContrailV2VirtualMachineInterface\",\"resourceType\":\"VFC\",\"categoryNormalizedName\":\"generic\",\"subCategoryNormalizedName\":\"network elements\"},{\"version\":\"2.0\",\"componentType\":\"RESOURCE\",\"icon\":\"port\",\"uniqueId\":\"c1a4cb0a-f502-4ad1-ab85-28826ff66ff6\",\"lifecycleState\":\"CERTIFIED\",\"lastUpdateDate\":1525885936247,\"name\":\"Port\",\"resourceType\":\"CP\",\"categoryNormalizedName\":\"generic\",\"subCategoryNormalizedName\":\"network elements\"},{\"version\":\"1.0\",\"componentType\":\"RESOURCE\",\"icon\":\"defaulticon\",\"uniqueId\":\"92430644-b897-48b8-8ddf-e0174f125623\",\"lifecycleState\":\"CERTIFIED\",\"lastUpdateDate\":1525348472402,\"name\":\"NovaServer\",\"resourceType\":\"VFC\",\"categoryNormalizedName\":\"generic\",\"subCategoryNormalizedName\":\"infrastructure\"}]"; + public static final String servicesJson = "[{\"version\":\"0.1\",\"componentType\":\"SERVICE\",\"icon\":\"defaulticon\",\"uniqueId\":\"99218968-b2b8-4968-9dec-787b5a53faae\",\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\",\"lastUpdateDate\":1526389884436,\"name\":\"ciServicec2e98fe5998a\",\"categoryNormalizedName\":\"mobility\",\"distributionStatus\":\"DISTRIBUTION_NOT_APPROVED\"},{\"version\":\"0.2\",\"componentType\":\"SERVICE\",\"icon\":\"defaulticon\",\"uniqueId\":\"104a6ec5-e42d-431b-8dce-9c516d45a910\",\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\",\"lastUpdateDate\":1526316232459,\"name\":\"ciServiceb203b2d546d3\",\"categoryNormalizedName\":\"mobility\",\"distributionStatus\":\"DISTRIBUTED\"},{\"version\":\"1.0\",\"componentType\":\"SERVICE\",\"icon\":\"defaulticon\",\"uniqueId\":\"12baacdb-a695-4237-895c-681ec9e202c6\",\"lifecycleState\":\"CERTIFIED\",\"lastUpdateDate\":1525608777143,\"name\":\"ciService7ef4911cec91\",\"categoryNormalizedName\":\"mobility\",\"distributionStatus\":\"DISTRIBUTED\"},{\"version\":\"0.2\",\"componentType\":\"SERVICE\",\"icon\":\"defaulticon\",\"uniqueId\":\"376fe442-7cba-461f-bece-4d853d2b99b4\",\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\",\"lastUpdateDate\":1526315942531,\"name\":\"ciService921a40e809f3\",\"categoryNormalizedName\":\"mobility\",\"distributionStatus\":\"DISTRIBUTION_NOT_APPROVED\"}]"; + public static final String timestampJson = "{\"previousUpdateTime\":\"" + Long.toString(prevUpdateTime) + "\",\"currentUpdateTime\":\"" + Long.toString(currUpdateTime) + "\"}"; + public static final String componentMsgJson = "{\"changeTypeEnum\":\"LIFECYCLE\",\"catalogUpdateTimestamp\":" + timestampJson + "," + singleResourceJson + "}"; + public static final String componentMsgJsonWithoutTimestamp = "{\"changeTypeEnum\":\"DELETE\"},{" + singleResourceJson + "}"; + + public static List convertComponentsFromJson(String jsonStr) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.readValue(jsonStr, new TypeReference>() {}); + } + + public static List convertHealthCheckResponseFromJson(String beJsonResponse) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + Map healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference>() {}); + if (healthCheckMap.containsKey("componentsInfo")) { + return mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference>() {}); + } + return null; + } +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryCompositionBuilderTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryCompositionBuilderTest.java new file mode 100644 index 0000000..6a1fe90 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryCompositionBuilderTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import java.util.function.Predicate; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class QueryCompositionBuilderTest { + @Mock + ICatalogElement element; + + @Test + public void testNodeTypePredicateForVF() { + Predicate predicate = QueryCompositionBuilder.getNodeTypeQuery("vf"); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.CP); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VFCMT); + assertThat(predicate.test(element)).isFalse(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.Configuration); + assertThat(predicate.test(element)).isTrue(); + } + + @Test + public void testNodeTypePredicateForCR() { + Predicate predicate = QueryCompositionBuilder.getNodeTypeQuery("cr"); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.CP); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VL); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.Configuration); + assertThat(predicate.test(element)).isTrue(); + } + + @Test + public void testNodeTypePredicateForCVFC() { + Predicate predicate = QueryCompositionBuilder.getNodeTypeQuery("cvfc"); + assertThat(predicate.test(element)).isFalse(); + } + + @Test + public void testNodeTypePredicateForWrongNodeTypeIsNull() { + assertThat(QueryCompositionBuilder.getNodeTypeQuery("tp")).isNull(); + } + + + @Test + public void testTopologyTemplatePredicate() { + Predicate predicate = QueryCompositionBuilder.getTopologyTemplateQuery(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VL); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicate.test(element)).isFalse(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.Configuration); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.PNF); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.ServiceProxy); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicate.test(element)).isTrue(); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.VFCMT); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicate.test(element)).isFalse(); + } + + + +} diff --git a/catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryFilterBuilderTest.java b/catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryFilterBuilderTest.java new file mode 100644 index 0000000..b6b61c6 --- /dev/null +++ b/catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryFilterBuilderTest.java @@ -0,0 +1,303 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-microservices + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.utils.queries; + +import com.google.common.collect.Lists; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.api.ICatalogElement; +import org.onap.sdc.api.ICatalogQuery; +import org.onap.sdc.enums.ComponentTypeEnum; +import org.onap.sdc.enums.DistributionStatusEnum; +import org.onap.sdc.enums.LifecycleStateEnum; +import org.onap.sdc.enums.ResourceTypeEnum; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class QueryFilterBuilderTest { + @Mock + private ICatalogElement element; + + @Test + public void validateQueryWithArchiveAndCategory() { + final String category = "generic"; + ICatalogQuery query = QueryFilterBuilder.getFilterQuery(null, Lists.newArrayList(category),null, null, null, true); + List> predicates = query.getQueryFilters(); + assertThat(predicates).hasSize(3); + /* category and archive params are not in the query or don't match */ + when(element.getCategory()).thenReturn("other"); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isFalse(); + /* category and archive params are in the query and match */ + when(element.getCategory()).thenReturn(category); + when(element.isArchived()).thenReturn(true); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isTrue(); + /* one of params doesn't match */ + when(element.getCategory()).thenReturn(category); + when(element.isArchived()).thenReturn(false); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isFalse(); + } + + @Test + public void validateResourcesQueryWithDistribStatus() { + ICatalogQuery query = QueryFilterBuilder.getFilterQuery( + Lists.newArrayList(ComponentTypeEnum.RESOURCE.getHeaderName()), null, + Lists.newArrayList(DistributionStatusEnum.DISTRIBUTION_APPROVED.getValue()), null, null,false); + List> predicates = query.getQueryFilters(); + // ct=RESOURCE, ds=distributed, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(predicates).hasSize(4); + /* all element fields values don't match the requested ones */ + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isFalse(); + /* some element fields values don't match the requested ones */ + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTED); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isFalse(); + /* some element fields values don't match the requested ones */ + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTION_APPROVED); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isFalse(); + /* the queried element fields values match the requested ones */ + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTION_APPROVED); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicates.get(0) + .test(element) + && predicates.get(1) + .test(element)).isTrue(); + } + + @Test + public void validatePreficatesForQueryWithAllParameters() { + ICatalogQuery query = QueryFilterBuilder.getFilterQuery( + Lists.newArrayList("RESOURCE.VFC", "RESOURCE.CP", "RESOURCE.CR", "SERVICE"), + Lists.newArrayList("resourceNewCategory.network1", "resourceNewCategory.network2", + "serviceNewCategory.mobility"), + Lists.newArrayList("Distribution approved", "Distributed"), null, null,true); + List> predicates = query.getQueryFilters(); + assertThat(predicates).hasSize(5); + // all predicates will return true + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTED); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.Configuration); + when(element.getCategory()).thenReturn("serviceNewCategory"); + when(element.getSubCategory()).thenReturn("mobility"); + when(element.isArchived()).thenReturn(true); + // verify that all predicates return true + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + + // only two predicates will return true + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); // the + // predicate + // will + // return + // false + when(element.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE); + when(element.getCategory()).thenReturn("serviceNewCategory"); + when(element.getSubCategory()).thenReturn("network2"); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + } + + @Test + public void validatePreficatesForConfigurationOnlyExistsIfParametersNotSet() { + // getResourceType() != ResourceTypeEnum.Configuration (Always added), + // arc=false (default value for archive) + assertThat(QueryFilterBuilder.getFilterQuery(null, null, null, null, null,false) + .getQueryFilters()).hasSize(2); + } + + @Test + public void validatePreficatesForCategoryParameters() { + ICatalogQuery query = QueryFilterBuilder.getFilterQuery(null, Lists.newArrayList("resourceNewCategory.network1", + "resourceNewCategory.network2", "serviceNewCategory.mobility", "common"), + Lists.newArrayList("Distributed"), null, null, false); + + List> predicates = query.getQueryFilters(); + // category, ds=distributed, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(predicates).hasSize(4); + + // verify that only 2 predicates return true + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTED); + when(element.getCategory()).thenReturn("common"); + when(element.isArchived()).thenReturn(true); + when(element.getSubCategory()).thenReturn("mobility"); + when(element.getResourceType()).thenReturn(ResourceTypeEnum.Configuration); + + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + + // verify that only 1 predicates return true + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + when(element.getCategory()).thenReturn("serviceNewCategory"); + when(element.getSubCategory()).thenReturn("mobility"); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(1); + } + + @Test + public void validatePredicateWithLifecycleStatesAndLastUpdater() { + ICatalogQuery query = QueryFilterBuilder.getFilterQuery(null, null, null, + Arrays.asList(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()), + Arrays.asList("carlos", ""), false); + + List> predicates = query.getQueryFilters(); + // ls=certification_in_progress/ready_for_certification, + // lastUpdater = carlos/"" + // getResourceType() != ResourceTypeEnum.Configuration (Always added), + // arc=false (default value for archive) + assertThat(predicates.size()).isEqualTo(4); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.CHECKOUT); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + when(element.getLastUpdaterUserId()).thenReturn("carlos"); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLastUpdaterUserId()).thenReturn(""); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLastUpdaterUserId()).thenReturn("chaya"); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + } + + @Test + public void validateServicesQueryWithLifecycleState() { + ICatalogQuery filterQuery = QueryFilterBuilder.getFilterQuery(Arrays.asList(ComponentTypeEnum.SERVICE.name()), + null, null, + Arrays.asList(LifecycleStateEnum.CERTIFIED.name()), null, null); + + List> predicates = filterQuery.getQueryFilters(); + // ct=SERVICE, ls=certified, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(predicates.size()).isEqualTo(4); + + // verify only default predicates are satisfied (getResourceType() != + // ResourceTypeEnum.Configuration and archive==false + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.CERTIFIED); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(4); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.CERTIFIED); + when(element.getComponentType()).thenReturn(ComponentTypeEnum.RESOURCE); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + } + + @Test + public void validateServicesQueryWithLifecycleStateAndDistributionStatus() { + ICatalogQuery filterQuery = QueryFilterBuilder.getFilterQuery(Arrays.asList(ComponentTypeEnum.SERVICE.name()), + null, + Arrays.asList(DistributionStatusEnum.DISTRIBUTION_APPROVED.name(), DistributionStatusEnum.DISTRIBUTED.name()), + Arrays.asList(LifecycleStateEnum.CERTIFIED.name()), null, null); + + List> predicates = filterQuery.getQueryFilters(); + // ct=SERVICE, ls=certified, ds=approved/distributed, getResourceType() != + // ResourceTypeEnum.Configuration (Always added), arc=false (default + // value for archive) + assertThat(predicates.size()).isEqualTo(5); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + + when(element.getComponentType()).thenReturn(ComponentTypeEnum.SERVICE); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTION_APPROVED); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(4); + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTED); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(4); + when(element.getDistributionStatus()).thenReturn(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.CERTIFIED); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(4); + when(element.getLifecycleState()).thenReturn(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + } + + @Test + public void validateQueryWithNullValuesOnLastUpdaterList() { + ICatalogQuery filterQuery = QueryFilterBuilder.getFilterQuery(null, + null, + null, + null, Arrays.asList("carlos", null), null); + + List> predicates = filterQuery.getQueryFilters(); + assertThat(predicates.size()).isEqualTo(3); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLastUpdaterUserId()).thenReturn("carlos"); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(3); + when(element.getLastUpdaterUserId()).thenReturn("chaya"); + assertThat(predicates.stream() + .filter(p -> p.test(element))).hasSize(2); + } +} -- 2.16.6