add facade code to Onap 12/98412/7
authorYuli Shlosberg <ys9693@att.com>
Thu, 14 Nov 2019 12:41:05 +0000 (14:41 +0200)
committerShabanov, Marina (ms656r) <ms656r@intl.att.com>
Tue, 24 Dec 2019 09:05:42 +0000 (11:05 +0200)
Issue-ID: SDC-2657
Change-Id: I602a4f5858830f5c2afefe6d4f01f18fdea0f222
Signed-off-by: Yuli Shlosberg <ys9693@att.com>
105 files changed:
.gitignore [new file with mode: 0644]
.gitreview [new file with mode: 0644]
catalog-facade-ms/pom.xml [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/CatalogFacadeMsMainApplication.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IBeDataRetriever.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IBusinessLogic.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICache.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICacheHandler.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogElement.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogQuery.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUIElement.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestamp.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateTimestampContainer.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICatalogUpdateValidatorTask.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ICategory.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IComponentMessage.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IHealthCheckBuilder.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ILatestElements.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/ILeftPalletUIElement.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueConfiguration.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IMessageQueueHandlerConsumer.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/api/IStatus.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/controllers/BaseController.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/controllers/CatalogController.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/controllers/HealthCheckController.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/ChangeTypeEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/ComponentTypeEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/CustomHeadersEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/DistributionStatusEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/LifecycleStateEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResourceTypeEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/ResultStatusEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/SdcResponseFieldEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserOperationEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserRoleEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/enums/UserStatusEnum.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/exception/RestrictionAccessFilterException.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeFilter.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/filter/FacadeUserThreadLocalImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/filter/FilterConfiguration.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/filter/PortalConfiguration.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/CatalogFacadeHealth.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/DmaapHealth.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/healthcheck/HealthCheckInfo.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/http/IResponse.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/http/ISimpleHttpClient.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/http/SimpleHttpClient.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/BeDataRetrieverImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/BusinessLogicImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheHandlerImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/CacheImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogElementImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUIElementImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/CatalogUpdateValidatorTaskImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/Category.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/LatestElementsImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/LeftPalletUIElementImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImpl.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainer.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ComponentMessage.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ConsumerAdapter.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapClientFactory.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumer.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/DmaapConsumerConfiguration.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementFilterFieldsContainer.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/message/ElementViewFieldsContainer.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/impl/users/UserElement.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/logger/FacadeLogUtils.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/repositories/CatalogElementRepository.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/services/ServletHelper.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/CatalogElementsUtils.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/EncryptionUtils.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/FunctionalCodeUtils.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/MessageUtils.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/Wrapper.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryCompositionBuilder.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilder.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForCategory.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForComponentType.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForDistributionStatus.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLastUpdater.java [new file with mode: 0644]
catalog-facade-ms/src/main/java/org/onap/sdc/utils/queries/QueryFilterBuilderForLifecycleState.java [new file with mode: 0644]
catalog-facade-ms/src/main/resources/DME2preferredRouter.txt [new file with mode: 0644]
catalog-facade-ms/src/main/resources/application.yml [new file with mode: 0644]
catalog-facade-ms/src/main/resources/key.properties [new file with mode: 0644]
catalog-facade-ms/src/main/resources/keystore [new file with mode: 0644]
catalog-facade-ms/src/main/resources/logback.xml [new file with mode: 0644]
catalog-facade-ms/src/main/resources/truststore [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/controllers/CatalogControllerTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/controllers/ControllersTestsUtils.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/controllers/HealthCheckControllerTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/CatalogFacadeHealthCheckTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/healthcheck/DmaapHealthTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/BusinessLogicImplTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheHandlerImplTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/CacheImplTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/CatalogElementUtils.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampImplTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/CatalogUpdateTimestampSyncContainerTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/ComponentMessageTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerConfigurationTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/impl/message/DmaapConsumerTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/utils/Utils.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryCompositionBuilderTest.java [new file with mode: 0644]
catalog-facade-ms/src/test/java/org/onap/sdc/utils/queries/QueryFilterBuilderTest.java [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..d27a5f8
--- /dev/null
@@ -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 (file)
index 0000000..a0133d9
--- /dev/null
@@ -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 (file)
index 0000000..c185fd3
--- /dev/null
@@ -0,0 +1,293 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.onap.sdc</groupId>
+    <artifactId>catalog-facade-ms</artifactId>
+    <version>1.6.0-SNAPSHOT</version>
+    <packaging>jar</packaging>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.0.2.RELEASE</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <maven.compiler.target>1.8</maven.compiler.target>
+        <maven.compiler.source>1.8</maven.compiler.source>
+               <nexus.proxy>https://nexus.onap.org</nexus.proxy>
+        <security.util-lib.version>1.6.0</security.util-lib.version>
+        <common-app-api.version>1.3.0-SNAPSHOT</common-app-api.version>
+        <ecomp.version>2.5.0</ecomp.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.springframework.boot</groupId>
+                    <artifactId>spring-boot-starter-tomcat</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-jetty</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.onap.logging-analytics</groupId>
+            <artifactId>logging-filter-base</artifactId>
+            <version>1.6.1</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy -->
+        <dependency>
+            <groupId>org.codehaus.groovy</groupId>
+            <artifactId>groovy</artifactId>
+            <version>2.4.15</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId>
+            <artifactId>dmaapClient</artifactId>
+            <version>1.1.3</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.glassfish.jersey.core</groupId>
+                    <artifactId>jersey-client</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.glassfish.jersey.core</groupId>
+                    <artifactId>jersey-common</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
+        <dependency>
+            <groupId>org.glassfish.jersey.core</groupId>
+            <artifactId>jersey-client</artifactId>
+            <!-- Need this specific versio for DMAAP -->
+            <version>2.25.1</version>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
+        <dependency>
+            <groupId>org.glassfish.jersey.core</groupId>
+            <artifactId>jersey-common</artifactId>
+            <!-- Need this specific versio for DMAAP -->
+            <version>2.25.1</version>
+        </dependency>
+
+
+        <!-- Enhance Collections -->
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-collections4</artifactId>
+            <version>4.0</version>
+        </dependency>
+
+        <!-- For StringUtils -->
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+        </dependency>
+
+        <!-- Apache Http Client -->
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <version>18.0</version>
+            <scope>compile</scope>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
+        <dependency>
+            <groupId>org.codehaus.groovy</groupId>
+            <artifactId>groovy-all</artifactId>
+            <version>2.4.15</version>
+        </dependency>
+
+        <dependency>
+            <groupId>janino</groupId>
+            <artifactId>janino</artifactId>
+            <!-- Needed For Logback.xml Filtering -->
+            <version>2.5.10</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.18.0</version>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.data</groupId>
+            <artifactId>spring-data-rest-hal-browser</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.onap.sdc.sdc-be-common</groupId>
+            <artifactId>security-util-lib</artifactId>
+            <version>${security.util-lib.version}</version>
+            <scope>compile</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.glassfish.jersey.ext</groupId>
+                    <artifactId>jersey-bean-validation</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <dependency>
+            <groupId>org.openecomp.sdc</groupId>
+            <artifactId>common-app-api</artifactId>
+            <version>${common-app-api.version}</version>
+            <scope>compile</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.onap.sdc.securityutil</groupId>
+                    <artifactId>sdc-security-util</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.7.0</version><!-- 3.1 is the minimum -->
+            </plugin>
+        </plugins>
+
+    </build>
+    <repositories>
+        <!-- LF repositories -->
+        <repository>
+            <id>ecomp-releases</id>
+            <name>Release Repository</name>
+            <url>${nexus.proxy}/content/repositories/releases/</url>
+        </repository>
+        <repository>
+            <id>ecomp-snapshots</id>
+            <name>Snapshots Repository</name>
+            <url>${nexus.proxy}/content/repositories/snapshots/</url>
+        </repository>
+        <repository>
+            <id>ecomp-public</id>
+            <name>Public Repository</name>
+            <url>${nexus.proxy}/content/repositories/public/</url>
+        </repository>
+        <!-- LF repositories END-->
+    </repositories>
+
+
+    <profiles>
+        <profile>
+            <id>docker</id>
+            <activation>
+                <activeByDefault>false</activeByDefault>
+            </activation>
+            <properties>
+                <fabric8.version>0.23.0</fabric8.version>
+                <docker.registry>nexus3.onap.org:10001</docker.registry>
+                <docker.username>docker</docker.username>
+                <docker.password>docker</docker.password>
+                <docker.namespace>onap/</docker.namespace>
+            </properties>
+            <build>
+                <plugins>
+                    <plugin>
+                        <groupId>io.fabric8</groupId>
+                        <artifactId>docker-maven-plugin</artifactId>
+                        <version>${fabric8.version}</version>
+
+                        <configuration>
+                            <verbose>true</verbose>
+                            <apiVersion>1.23</apiVersion>
+                            <registry>${docker.registry}</registry>
+                            <authConfig>
+                                <username>${docker.username}</username>
+                                <password>${docker.password}</password>
+                            </authConfig>
+                            <images>
+                                <!-- Build backend image -->
+                                <image>
+                                    <name>${docker.namespace}${project.artifactId}</name>
+                                    <alias>${project.artifactId}</alias>
+                                    <build>
+                                        <cleanup>try</cleanup>
+                                        <dockerFileDir>${project.basedir}</dockerFileDir>
+                                        <tags>
+                                            <tag>${docker.tag}</tag>
+                                            <tag>${project.version}-STAGING-latest</tag>
+                                        </tags>
+                                    </build>
+                                </image>
+                            </images>
+                        </configuration>
+                        <executions>
+                            <execution>
+                                <id>clean-images</id>
+                                <phase>pre-clean</phase>
+                                <goals>
+                                    <goal>remove</goal>
+                                </goals>
+                                <configuration>
+                                    <removeAll>true</removeAll>
+                                </configuration>
+                            </execution>
+                            <execution>
+                                <id>generate-images</id>
+                                <phase>install</phase>
+                                <goals>
+                                    <goal>build</goal>
+                                </goals>
+                            </execution>
+                            <execution>
+                                <id>push-images</id>
+                                <phase>deploy</phase>
+                                <goals>
+                                    <goal>push</goal>
+                                </goals>
+                            </execution>
+                        </executions>
+                    </plugin>
+                </plugins>
+            </build>
+        </profile>
+    </profiles>
+
+    <pluginRepositories>
+        <pluginRepository>
+            <id>bintray</id>
+            <name>Groovy Bintray</name>
+            <url>https://dl.bintray.com/groovy/maven</url>
+            <releases>
+                <updatePolicy>never</updatePolicy>
+            </releases>
+            <snapshots>
+                <enabled>false</enabled>
+            </snapshots>
+        </pluginRepository>
+    </pluginRepositories>
+</project>
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 (file)
index 0000000..c3671a2
--- /dev/null
@@ -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> facadeFilter() throws RestrictionAccessFilterException{
+               FilterRegistrationBean<FacadeFilter> 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<AuditLogServletFilter> loggingFilter() {
+               FilterRegistrationBean<AuditLogServletFilter> 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 (file)
index 0000000..f90a481
--- /dev/null
@@ -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 (file)
index 0000000..02a39af
--- /dev/null
@@ -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.<br>
+ * @author ms172g
+ *
+ */
+public interface IBusinessLogic {
+       
+       /**
+        * Needs to define the callback and activate the init method of the message Queue Handler{@link IMessageQueueHandler#init(Consumer)}.<br>
+        * @return
+        */
+       IStatus init();
+       
+       /**
+        * Returns the catalog elements to the servlet.<br>
+        * @param query
+        * @return
+        */
+       List<ICatalogElement> getCatalogElements(ICatalogQuery query);
+       
+       
+       /**
+        * This method activate the logic upon retrieval of a new IComponentMessage or UserMessage.<br>
+        * @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 (file)
index 0000000..9cb056d
--- /dev/null
@@ -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<K,T> {
+
+    ICache<K,T> evict(T... values);
+
+    /**
+     * @param values
+     */
+    ICache<K,T> 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<K,T> clear();
+
+
+
+    /*
+     * get element by unique identifier
+     * */
+    List<T> get(Predicate<T> predicate);
+
+    /*
+     * get element by unique identifier
+     * */
+    List<T> get(Predicate<T> predicate, Comparator<T> comparator);
+
+    /**
+     *
+     * cache size
+     *
+     ***/
+    int count();
+
+    boolean isEmpty();
+
+    /**
+     * This Method Replaces the Given Map With a ConcurrentHashMap to be used by the cache.<br>
+     * @param inputMap
+     */
+    void fillCacheSafety(List<T> 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 (file)
index 0000000..191fe36
--- /dev/null
@@ -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.<br>
+ * 
+ * @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.<br>
+        * Will create a cache element and either create/update or delete it in
+        * cache according to message.<br>
+        * 
+        * @return
+        */
+       IStatus handleComponentMessage(IComponentMessage message);
+
+       /**
+        * create an element to the cache.<br>
+        * 
+        * @param element
+        * @return
+        */
+       
+       IStatus handleRestoreMessage(ICatalogElement message) ;
+
+    IStatus handleArchiveMessage(ICatalogElement message) ;
+
+    IStatus handleLifecycleMessage(ICatalogElement message) ;
+    
+    /**
+     * delete an element to the cache.<br>
+     * 
+     * @param element
+     * @return
+     */
+    IStatus handleDeleteMessage(ICatalogElement element);
+    
+
+       /**
+        * update an element to the cache.<br>
+        * 
+        * @param element
+        * @return
+        */
+       IStatus updateCatalogElementInCache(ICatalogElement element);
+
+       
+
+       /**
+        * Returns List of the catalog elements found in cache that match to the
+        * query.<br>
+        * 
+        * @param query
+        * @return
+        */
+       List<ICatalogElement> 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 (file)
index 0000000..1103b82
--- /dev/null
@@ -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.<br>
+ *
+ * @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<String> getTags();
+
+       Boolean getIsHighestVersion();
+       
+       List<ICategory> 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<String, List<ICatalogElement>> 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<HashMap<String, List<CatalogElementImpl>>> typeRef = new TypeReference<HashMap<String, List<CatalogElementImpl>>>() {
+               };
+               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 (file)
index 0000000..eaae7d9
--- /dev/null
@@ -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.<br>
+ * 
+ * @author ms172g
+ *
+ */
+@FunctionalInterface
+public interface ICatalogQuery {
+       /**
+        * Query filters, when this query executes only {@link ICatalogElement} that
+        * pass all the filters should be returned.<br>
+        * 
+        * @return
+        */
+       List<Predicate<ICatalogElement>> 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 (file)
index 0000000..794a97f
--- /dev/null
@@ -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<String> 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 (file)
index 0000000..371ceb6
--- /dev/null
@@ -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<CatalogUpdateTimestampImpl> typeRef = new TypeReference<CatalogUpdateTimestampImpl>() {};
+        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 (file)
index 0000000..794823e
--- /dev/null
@@ -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 (file)
index 0000000..3a64c1e
--- /dev/null
@@ -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 (file)
index 0000000..f77dfca
--- /dev/null
@@ -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<String> getIcons();
+    List<ICategory> 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 (file)
index 0000000..0945bda
--- /dev/null
@@ -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.<br>
+ * 
+ * @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 (file)
index 0000000..4f546c2
--- /dev/null
@@ -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 (file)
index 0000000..ec4c70c
--- /dev/null
@@ -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<ICatalogElement> 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 (file)
index 0000000..9f81d32
--- /dev/null
@@ -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<ICategory> getCategories();
+       
+       /**
+     * Returns the list of tags of this component 
+     * 
+     * @return
+     */ 
+       List<String> 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 (file)
index 0000000..70a05c7
--- /dev/null
@@ -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 (file)
index 0000000..08a2352
--- /dev/null
@@ -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.<br> 
+ * @author ms172g
+ *
+ */
+public interface IMessageQueueHandlerConsumer {
+       
+               
+       /**
+        * This method receives a callback that will be activated when a new message is added to the message broker.<br>
+        * @param callback
+        * @return
+        */
+       IStatus init(Consumer<String> 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 (file)
index 0000000..08cc9ff
--- /dev/null
@@ -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 (file)
index 0000000..f0632f0
--- /dev/null
@@ -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 (file)
index 0000000..28d13c4
--- /dev/null
@@ -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<String, List<ICatalogUIElement>> getCatalogQueryResponse(
+                       @RequestParam(value = "ct", required = false) List<String> componentTypeList,
+                       @RequestParam(value = "ds", required = false) List<String> distributionStatusList,
+                       @RequestParam(value = "cat", required = false) List<String> 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<String, List<ICatalogUIElement>> 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<String, Map<String, List<ILeftPalletUIElement>>> getLeftPaletteComposition(
+                       @PathVariable("componentType") String componentType,
+                       @RequestParam(value = "internalComponentType", required = true) String internalComponentType) {
+               final String methodName = "getLeftPaletteComposition";
+
+               List<ILeftPalletUIElement> 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<String, List<ICatalogUIElement>> fillResponseMap(ICatalogQuery query) {
+               List<ICatalogElement> 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 (file)
index 0000000..bf65a8a
--- /dev/null
@@ -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<String, List<HealthCheckInfo>> getHealthCheckInfo() {
+        Map<String, List<HealthCheckInfo>> 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 (file)
index 0000000..e81b8cc
--- /dev/null
@@ -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.<br> 
+ * @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 (file)
index 0000000..414a3a6
--- /dev/null
@@ -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 (file)
index 0000000..376ab51
--- /dev/null
@@ -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 (file)
index 0000000..f8e7610
--- /dev/null
@@ -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 (file)
index 0000000..13c7682
--- /dev/null
@@ -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 (file)
index 0000000..4d1b88c
--- /dev/null
@@ -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 (file)
index 0000000..427e310
--- /dev/null
@@ -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 (file)
index 0000000..b3640fa
--- /dev/null
@@ -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 (file)
index 0000000..b1343cb
--- /dev/null
@@ -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 (file)
index 0000000..fface92
--- /dev/null
@@ -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 (file)
index 0000000..a04f775
--- /dev/null
@@ -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 (file)
index 0000000..7179394
--- /dev/null
@@ -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 (file)
index 0000000..f2d6e05
--- /dev/null
@@ -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<String> 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 (file)
index 0000000..fe41a09
--- /dev/null
@@ -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<UserElement> currentThreadUserElement = new ThreadLocal<>();
+    @Override
+    public void setUserContext(AuthenticationCookie authenticationCookie) {
+        String role = "";
+        UserElement userElement = new UserElement();
+        userElement.setUserId(authenticationCookie.getUserID());
+        Set roles = authenticationCookie.getRoles();
+        Optional<String> 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 (file)
index 0000000..d380c5c
--- /dev/null
@@ -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<String> 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 (file)
index 0000000..cf062cd
--- /dev/null
@@ -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 (file)
index 0000000..83283c6
--- /dev/null
@@ -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<String> 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 (file)
index 0000000..36863f4
--- /dev/null
@@ -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 (file)
index 0000000..1c5ec4b
--- /dev/null
@@ -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<HealthCheckInfo> 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<HealthCheckInfo> 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 (file)
index 0000000..efa7723
--- /dev/null
@@ -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 (file)
index 0000000..72d073d
--- /dev/null
@@ -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.<br>
+        * Returns a pair with the Response object (already closed) and the Response Body.<br>
+        * @param url
+        * @param headers
+        * @return
+        */
+       IResponse doGet(String url, Map<String, String> headers);
+       
+       /**
+        * Perform Post Request on url.<br>
+        * Returns a pair with the Response object (already closed) and the Response Body.<br>
+        * @param url
+        * @param body 
+        * @param headers
+        * @return
+        */
+       IResponse doPost(String url, String body, Map<String, String> headers);
+
+       IResponse doPut(String url, String body, Map<String, String> headers);
+       /**
+        * Perform Delete Request on url.<br>
+        * Returns the Response object .<br>
+        * @param url
+        * @param headers
+        * @return
+        */
+       IResponse doDelete(String url, Map<String, String> 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 (file)
index 0000000..6dedfb6
--- /dev/null
@@ -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<String, String> 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<String, String> headers) {
+               LOG.debug("Sending POST Request to url:{} with Headers: {} and Body: {}", url, headers, body);
+
+               final HttpPost httpPostRequest = new HttpPost(url);
+               Optional<Boolean> 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<String, String> headers) {
+               LOG.debug("Sending Put Request to url:{} with Headers: {} and Body: {}", url, headers, body);
+
+               final HttpPut httpPutRequest = new HttpPut(url);
+               Optional<Boolean> 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<String, String> headers, HttpRequest httpRequest) {
+               if (!isEmpty(headers)) {
+                       headers.entrySet()
+                                       .stream()
+                                       .forEach(entry -> httpRequest.setHeader(entry.getKey(), entry.getValue()));
+               }
+       }
+
+       private IResponse excecuteRequest(HttpUriRequest httpRequest,
+                       Map<String, String> 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<String, String> 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 (file)
index 0000000..e6c98a6
--- /dev/null
@@ -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<String, String> headers = new HashMap<>();
+        setHeaders(headers, userId);
+        setMDCFields(headers);
+        return httpClient.doGet(
+                format(path, sdcBeSchema, sdcBeHost, sdcBePort), headers);
+    }
+
+    private void setHeaders(Map<String, String> 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<String, String> 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 (file)
index 0000000..9c7e509
--- /dev/null
@@ -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<ICatalogElement> getCatalogElements(ICatalogQuery query) {
+               LOG.debug("Start handling Query: {}", query);
+               List<ICatalogElement> 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 (file)
index 0000000..427c002
--- /dev/null
@@ -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<String, ICatalogElement> 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<String, List<ICatalogElement>> nonArchivedComponents = buildFromSdcHttpResponse(
+                               beDataRetriever.getCatalogResponseBody());
+
+               Map<String, List<ICatalogElement>> 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<List<ICatalogElement>> mergeFunction = (listOne,
+                               listTwo) -> concat(listOne.stream(), listTwo.stream()).collect(Collectors.toList());
+
+               Map<String, List<ICatalogElement>> 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<ICatalogElement> 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<ICatalogElement> buildJoinedPredicate(List<Predicate<ICatalogElement>> predicates) {
+               if (isEmpty(predicates)) {
+                       return element -> true;
+               } else {
+                       final Wrapper<Predicate<ICatalogElement>> 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 (file)
index 0000000..1075d85
--- /dev/null
@@ -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<String, ICatalogElement> {
+
+       private Map<String, ILatestElements> cache = new ConcurrentHashMap<>();
+       private static final Logger LOG = Logger.getLogger(CacheImpl.class);
+       private static final List<LifecycleStateEnum> nonCertifiedStates =
+                       Arrays.asList(NOT_CERTIFIED_CHECKIN, CHECKIN, NOT_CERTIFIED_CHECKOUT, CHECKOUT);
+       private static final List<LifecycleStateEnum> certifiedStates =
+                       Arrays.asList(CERTIFIED, CERTIFY);
+
+       @Override
+       public ICache<String, ICatalogElement> evict(ICatalogElement... values) {
+               Collection<ICatalogElement> 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<String, ICatalogElement> put(ICatalogElement... values) {
+               return put(cache, values);
+       }
+
+       ICache<String, ICatalogElement> put(Map<String, ILatestElements> map, ICatalogElement... values) {
+               LOG.debug("Start to add element to cache");
+               Collection<ILatestElements> 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<ICatalogElement> get(Predicate<ICatalogElement> 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<ICatalogElement> get(Predicate<ICatalogElement> filterPredicate, Comparator<ICatalogElement> 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<ICatalogElement> 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<String, ILatestElements> 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<String, ILatestElements> getCache() {
+               return cache;
+       }
+
+       public void setCache(Map<String, ILatestElements> 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 (file)
index 0000000..fe64996
--- /dev/null
@@ -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<String> tags;
+       @JsonProperty("isHighestVersion")
+       protected Boolean isHighestVersion;
+
+       private List<ICategory> categories;
+       
+       public void setCategories(List<ICategory> categories) {
+               this.categories = categories;
+       }
+
+
+       @JsonProperty("categories")
+       @Override
+       public List<ICategory> 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 (file)
index 0000000..e4d3a52
--- /dev/null
@@ -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<String> 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 (file)
index 0000000..1d3b016
--- /dev/null
@@ -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 (file)
index 0000000..664cacc
--- /dev/null
@@ -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<String> icons;
+    private List<ICategory> 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<String> getIcons() {
+        return icons;
+    }
+    
+    public void setIcons(List<String> icons) {
+        this.icons = icons;
+    }
+
+    @JsonProperty("subcategories")
+    @Override
+    public List<ICategory> getSubcategories() {
+        return subcategories;
+    }
+    
+    public void setSubcategories(List<ICategory> 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 (file)
index 0000000..0edb38a
--- /dev/null
@@ -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<ICatalogElement> getAllElements() {
+               List<ICatalogElement> 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 (file)
index 0000000..0f6836f
--- /dev/null
@@ -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<String> tags;
+
+       protected List<ICategory> 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<String> 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 (file)
index 0000000..7f5ea77
--- /dev/null
@@ -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 (file)
index 0000000..5d2439d
--- /dev/null
@@ -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 (file)
index 0000000..343bf7e
--- /dev/null
@@ -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 (file)
index 0000000..48817f3
--- /dev/null
@@ -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<String> fetch() throws Exception {
+        if (active && consumer != null) {
+            return consumer.fetch();
+        }
+        LOG.debug("Dmaap is Disabled");
+        return Collections.emptyList();
+    }
+
+    public Iterable<String> 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 (file)
index 0000000..2de50b8
--- /dev/null
@@ -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 (file)
index 0000000..84f84b3
--- /dev/null
@@ -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<String> notificationCallback;
+    private static final Logger LOG = Logger.getLogger(DmaapConsumer.class);
+
+    @Override
+    public IStatus init(Consumer<String> 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<String> 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 (file)
index 0000000..0f7d3df
--- /dev/null
@@ -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 (file)
index 0000000..2c89772
--- /dev/null
@@ -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 (file)
index 0000000..fe1a14e
--- /dev/null
@@ -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 (file)
index 0000000..9826076
--- /dev/null
@@ -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<UserElement> 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<List<UserElement>> typeRef = new TypeReference<List<UserElement>>() {
+        };
+        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 (file)
index 0000000..cf71dd9
--- /dev/null
@@ -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 (file)
index 0000000..00c1ca0
--- /dev/null
@@ -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<CatalogElementImpl, Long> {
+    List<CatalogElementImpl> 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<CatalogElementImpl> findByNameIn(@Param("name") List<String> name);
+    List<CatalogElementImpl> findByNameAndResourceTypeAndVersionAndIcon(@Param("name") String name
+                                                                        ,@Param("resourceType") ResourceTypeEnum resourceType
+                                                                        ,@Param("version") String version
+                                                                        ,@Param("icon") String icon);
+    List<CatalogElementImpl> findByNameStartsWith(@Param("name") String name, Pageable pageable);
+    //http://localhost:8080/catalogElementImpls/search/findByComponentTypeInAndResourceTypeInAndDistributionStatusIn?
+    List<CatalogElementImpl> findByComponentTypeInAndResourceTypeInAndDistributionStatusIn(
+            List<ComponentTypeEnum> componentTypeEnums, List<ResourceTypeEnum> resourceTypeEnums, List<DistributionStatusEnum> 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 (file)
index 0000000..43b03fd
--- /dev/null
@@ -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<String,Collection> 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<ResourceTypeEnum> resourceType, ICatalogElement... catalogItems){
+        return filterByProperty("resourceType", resourceType , catalogItems);
+    }
+
+    public Collection filterByLifecycleState(Collection<LifecycleStateEnum> lifecycleState, ICatalogElement... catalogItems){
+        return filterByProperty("lifecycleState", lifecycleState , catalogItems);
+    }
+
+    public Collection filterForService(ICatalogElement... catalogItems){
+        Collection<ICatalogElement> collectionByType = filterByComponentType( of(VF,CP,PNF,VL,ServiceProxy,Configuration) , catalogItems);
+        Collection<ICatalogElement> collectionByStatus = filterByLifecycleState( of(CERTIFIED,NOT_CERTIFIED_CHECKIN),  (ICatalogElement[]) collectionByType.toArray());
+        //todo- filter by latest
+        return collectionByStatus;
+    }
+
+    public Collection filterForVf(ICatalogElement... catalogItems){
+        Collection<ICatalogElement> collectionByType = filterByComponentType( of(VFC,CR,CVFC,VFCMT) , catalogItems);
+        Collection<ICatalogElement> 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 (file)
index 0000000..dd8ca8e
--- /dev/null
@@ -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<ICatalogUIElement> prepareValueList(List<ICatalogElement> inputList) {
+        if (inputList == null) {
+            return Collections.emptyList();
+        }
+        return inputList.stream()
+                .map(CatalogUIElementImpl::buildUIElement)
+                .collect(Collectors.toList());
+    }
+
+    public static Map<String, List<ICatalogUIElement>> convertElementsListToUIMap
+            (List<ICatalogElement> elementsList){
+        elementsList = elementsList!=null? elementsList : new ArrayList<>();
+
+        Map<ComponentTypeEnum, List<ICatalogElement>> componentMap = elementsList
+                .stream()
+                .collect(Collectors.groupingBy(ICatalogElement::getComponentType));
+
+        Map<String, List<ICatalogUIElement>> 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 (file)
index 0000000..e5551e1
--- /dev/null
@@ -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 (file)
index 0000000..209fac9
--- /dev/null
@@ -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.<br>
+        * In case exception occurred returns Optional containing the
+        * resultOnException.<br>
+        * Otherwise returns an Empty optional.
+        * 
+        * @param runnable
+        * @param resultOnException
+        * @param serviceName
+        * @return
+        */
+       public static <T, E extends Exception> Optional<T> wrapWithTryCatch(RunnableThrows<E> runnable,
+                       T resultOnException, String serviceName) {
+               Optional<T> 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.<br>
+        * In case exception occurred logs the Exception.<br>
+        * resultOnException.<br>
+        * Otherwise returns an Empty optional.
+        * 
+        * @param runnable
+        * @param resultOnException
+        * @return
+        */
+       public static <E extends Exception> void wrapWithTryCatch(RunnableThrows<E> runnable, String serviceName) {
+               wrapWithTryCatch(runnable, serviceName);
+       }
+
+       /**
+        * Functional Interface Similar to Runnable except that throws Exception
+        * 
+        * @author ms172g
+        *
+        * @param <E>
+        */
+       @FunctionalInterface
+       public interface RunnableThrows<E extends Exception> {
+               /**
+                * 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 extends Enum<T>> T findByPredicate(Predicate<T> predicate, T[] values) {
+
+               final Optional<T> 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.<br>
+        * In case the method passes without any Assertion Errors finishes.<br>
+        * In case there is an assertion error keeps running the method every  retryIntervalMS.<br> until there is no Errors or maxWaitTimeMs has passed. <br>
+        * If there are still Assertion Errors in the last Run they are returned to the user.<br>
+        * 
+        * @param methodToRun
+        * @param maxWaitTimeMs
+        * @param retryIntervalMS
+        */
+       public static 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 <R>
+        * @param <E>
+        */
+       public interface SupplierThrows<R, E extends Exception> {
+               /**
+                * 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.
+        * <br>
+        * In case Exception Occurred replaces it with RunTimeException. <br>
+        * This is useful for two cases:<br>
+        * 1.using methods that throws exceptions in streams.<br>
+        * 2.replacing declared exception with undeclared exception (Runtime).<br>
+        * See below Use Case:<br>
+        * Instead of: intList.stream().map(e -> fooThrowsAndReturnsBoolean(e)); -
+        * does not compile !<br>
+        * Use This : intList.stream().map(e -> swallowException( () ->
+        * fooThrowsAndReturnsBoolean(e))); - compiles !<br>
+        * 
+        * @param methodToRun
+        * @return
+        */
+       public static <R, E extends Exception> R replaceWithUncheckedException(SupplierThrows<R, E> methodToRun) {
+               try {
+                       return methodToRun.get();
+               } catch (Exception e) {
+                       throw new RuntimeException(e);
+               }
+       }
+
+       /**
+        * Runs a method that declares throwing an Exception without return value.
+        * <br>
+        * In case Exception Occurred replaces it with RunTimeException. <br>
+        * This is useful for two cases:<br>
+        * 1.using methods that throws exceptions in streams.<br>
+        * 2.replacing declared exception with undeclared exception (Runtime).<br>
+        * See below Use Case:<br>
+        * 
+        * @param methodToRun
+        */
+       public static <E extends Exception> void replaceWithUncheckedException(RunnableThrows<E> methodToRun) {
+
+               SupplierThrows<Boolean, E> runnableWrapper = () -> {
+                       methodToRun.run();
+                       return true;
+               };
+               replaceWithUncheckedException(runnableWrapper);
+       }
+
+
+       /**
+        * This method runs the given method.<br>
+        * In case given method finished running within timeoutInMs limit it returns true.<br>
+        * In case given method did not finish running within timeoutInMs limit it returns false.<br>
+        
+        * 
+        * @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<Boolean> 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 (file)
index 0000000..37925f4
--- /dev/null
@@ -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> T  buildFromMessage(String message, Class<T> 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 (file)
index 0000000..cceb316
--- /dev/null
@@ -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 <T>
+ */
+public class Wrapper<T>{
+       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 (file)
index 0000000..c0fb765
--- /dev/null
@@ -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<ICatalogElement> predicateDenyByResourceType;
+       private static Predicate<ICatalogElement> 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<Predicate<ICatalogElement>> queryList = new ArrayList<>();
+               Predicate<ICatalogElement> 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<ICatalogElement> getQueryByInternalComponentType(String internalComponentType) {
+               if ("service".equalsIgnoreCase(internalComponentType)) {
+                       return getTopologyTemplateQuery();
+               }
+               return getNodeTypeQuery(internalComponentType);
+       }
+
+       static Predicate<ICatalogElement> getTopologyTemplateQuery() {
+               Predicate<ICatalogElement> predicate = c -> c.getResourceType() != ResourceTypeEnum.VFC;
+               return predicate.and(c -> c.getResourceType() != ResourceTypeEnum.VFCMT)
+                               .or(c -> c.getComponentType() == ComponentTypeEnum.SERVICE);
+       }
+
+       static Predicate<ICatalogElement> 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 (file)
index 0000000..b49a492
--- /dev/null
@@ -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<String> elements = new ArrayList<>();
+
+    QueryFilterBuilder(List<String> values) {
+        elements.addAll(values);
+    }
+
+    Predicate<ICatalogElement> getQueryForParameter() {
+        Predicate<ICatalogElement> predicate = c -> false;
+        for (String element: elements) {
+            predicate = predicate.or(buildQueryForElement(element));
+        }
+        return predicate;
+    }
+
+    public abstract Predicate<ICatalogElement> buildQueryForElement(String element);
+
+    protected ArrayList<String> parseComplexValue(String value, String separator) {
+        final String methodName = "parseComplexValue";
+
+        LOG.debug(methodName + ": Parsing value list: {}", value);
+        ArrayList<String> 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<String> componentTypeList, List<String> categoryList, List<String> distributedList,
+                                               List<String> lifecycleStateList,List<String> lastUpdaterList, Boolean archive) {
+        List<Predicate<ICatalogElement>> 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 (file)
index 0000000..6a39277
--- /dev/null
@@ -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<String> values) {
+        super(values);
+    }
+
+    @Override
+    public Predicate<ICatalogElement> buildQueryForElement(String element) {
+        Predicate<ICatalogElement> predicate = c -> true;
+        ArrayList<String> 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 (file)
index 0000000..5973375
--- /dev/null
@@ -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<String> values) {
+        super(values);
+    }
+
+    @Override
+    public Predicate<ICatalogElement> buildQueryForElement(String element) {
+        Predicate<ICatalogElement> predicate = c->true;
+        ArrayList<String> 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 (file)
index 0000000..fc014f1
--- /dev/null
@@ -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<String> statuses) {
+        super(statuses);
+    }
+
+    @Override
+    public Predicate<ICatalogElement> 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 (file)
index 0000000..342ec48
--- /dev/null
@@ -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<String> values) {
+        super(values);
+    }
+
+    @Override
+    public Predicate<ICatalogElement> 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 (file)
index 0000000..e9469fa
--- /dev/null
@@ -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<String> values) {
+        super(values);
+    }
+
+    @Override
+    public Predicate<ICatalogElement> 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 (file)
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 (file)
index 0000000..181c7db
--- /dev/null
@@ -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 (file)
index 0000000..0315075
--- /dev/null
@@ -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 (file)
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 (file)
index 0000000..1ca6c94
--- /dev/null
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration scan="true" scanPeriod="5 seconds">
+
+    <property scope="system" name="ECOMP-component-name" value="SDC" />
+    <property scope="system" name="ECOMP-subcomponent-name" value="CATALOG_FACADE_MS" />
+    <property name="p_msg" value="%replace(%replace(%replace(%replace(%msg){'\t','\\\\t'}){'\n', '\\\\n'}){'\\\|', '-'}){'\r','\\\\r'}"/>
+    <property name="p_ex" value="%replace(%replace(%replace(%replace(%exception{full}){'\t','\\\\t'}){'\n', '\\\\n'}){'\\\|', '-'}){'\r','\\\\r'}"/>
+    <property name="p_debugInfo" value="%replace(%replace(%replace(%replace(%thread # %level # %logger{35} # %msg){'\t','\\\\t'}){'\n', '\\\\n'}){'\\\|', '-'}){'\r','\\\\r'}"/>
+
+    <property name="error-log-pattern"
+              value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestID}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|${p_msg} ${p_ex}|%n%nopex" />
+
+    <property name="debug-log-pattern" value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestID}|${p_debugInfo} ${p_ex}|^\n%n%nopex"/>
+
+    <!-- Error log -->
+    <appender name="ERROR_ROLLING"
+              class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <file>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log
+        </file>
+
+        <!-- deny all events with a level below INFO, that is TRACE and DEBUG -->
+        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+            <level>WARN</level>
+        </filter>
+
+        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+            <fileNamePattern>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/error.log.%i
+            </fileNamePattern>
+            <minIndex>1</minIndex>
+            <maxIndex>10</maxIndex>
+        </rollingPolicy>
+
+        <triggeringPolicy
+                class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+            <maxFileSize>20MB</maxFileSize>
+        </triggeringPolicy>
+        <encoder>
+            <pattern>${error-log-pattern}</pattern>
+        </encoder>
+    </appender>
+
+    <!-- Debug log -->
+    <appender name="DEBUG_ROLLING"
+              class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <file>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log
+        </file>
+
+        <!-- accept DEBUG, TRACE and INFO level -->
+        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
+            <evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator">
+                <expression>
+                    e.level.toInt() &lt;= INFO.toInt()
+                </expression>
+            </evaluator>
+            <OnMismatch>DENY</OnMismatch>
+            <!--<OnMatch>NEUTRAL</OnMatch>-->
+            <OnMatch>ACCEPT</OnMatch>
+        </filter>
+
+        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+            <fileNamePattern>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log.%i
+            </fileNamePattern>
+            <minIndex>1</minIndex>
+            <maxIndex>10</maxIndex>
+        </rollingPolicy>
+
+        <triggeringPolicy
+                class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+            <maxFileSize>20MB</maxFileSize>
+        </triggeringPolicy>
+        <encoder>
+            <pattern>${debug-log-pattern}</pattern>
+        </encoder>
+    </appender>
+
+
+    <!-- Asynchronicity Configurations -->
+    <appender name="ASYNC_DEBUG" class="ch.qos.logback.classic.AsyncAppender">
+        <appender-ref ref="DEBUG_ROLLING" />
+    </appender>
+
+    <appender name="ASYNC_ERROR" class="ch.qos.logback.classic.AsyncAppender">
+        <appender-ref ref="ERROR_ROLLING" />
+    </appender>
+
+
+    <root level="INFO">
+        <appender-ref ref="ASYNC_ERROR" />
+        <appender-ref ref="ASYNC_DEBUG" />
+    </root>
+
+    <logger name="org.onap.sdc" level="DEBUG" />
+
+</configuration>
\ 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 (file)
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 (file)
index 0000000..17ad87d
--- /dev/null
@@ -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<ICatalogQuery> 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<ICatalogElement> 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<ICatalogElement> 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<ICatalogElement> 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<Predicate<ICatalogElement>> predicates = query.getQueryFilters();
+               assertThat(predicates.get(0)
+                               .test(element)
+                               && predicates.get(1)
+                                               .test(element)).isFalse();
+
+       }
+
+       @Test
+       public void getCompositionForService() {
+               Map<String, Map<String, List<ILeftPalletUIElement>>> 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 (file)
index 0000000..f1bc1a7
--- /dev/null
@@ -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<String, List<ICatalogElement>> 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 (file)
index 0000000..d815297
--- /dev/null
@@ -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<HealthCheckInfo> 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<HealthCheckInfo> 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 (file)
index 0000000..cfc16d4
--- /dev/null
@@ -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 (file)
index 0000000..b1d32a6
--- /dev/null
@@ -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 (file)
index 0000000..5eb50aa
--- /dev/null
@@ -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 (file)
index 0000000..981220e
--- /dev/null
@@ -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<String, ICatalogElement> cache;
+       @Mock
+       private IBeDataRetriever beDataRetriever;
+       @Mock
+       private ICatalogUpdateTimestampContainer catalogUpdateTimestampContainer;
+
+       // Other Mocks
+       @Mock
+       private ICatalogElement catalogElement;
+       @Mock
+       private IComponentMessage componentMessage;
+
+       @Captor
+       private ArgumentCaptor<ICatalogElement> eventCaptor;
+       @Captor
+       private ArgumentCaptor<List<ICatalogElement>> 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<ICatalogElement> 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<ICatalogElement> 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<ICatalogElement> 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<ICatalogElement> 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<ICatalogElement> elements = cacheHandler.getCatalogElements(query);
+
+               assertThat(elements.size()).isEqualTo(NumberUtils.INTEGER_ZERO);
+       }
+
+       @SuppressWarnings("unchecked")
+       private void mockCacheWithPredicate() {
+               List<ICatalogElement> elementsInCache = Arrays.asList(v1NotArchived, v2NotArchived, v1Archived, v2Archived);
+
+               doAnswer((Answer<List<ICatalogElement>>) invocation -> {
+                       Predicate<ICatalogElement> pred = (Predicate<ICatalogElement>) 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 (file)
index 0000000..4bc0fc8
--- /dev/null
@@ -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<String, ILatestElements> cache ;
+    @Captor
+    private ArgumentCaptor<ILatestElements> eventCaptor;
+    @Captor
+    private ArgumentCaptor<String> 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<String, ILatestElements> 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<String, ILatestElements> 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<String, ILatestElements> 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<String, ILatestElements> 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 (file)
index 0000000..3a2232e
--- /dev/null
@@ -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 (file)
index 0000000..4ac30c9
--- /dev/null
@@ -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 (file)
index 0000000..90e0005
--- /dev/null
@@ -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 (file)
index 0000000..0944702
--- /dev/null
@@ -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 (file)
index 0000000..267093e
--- /dev/null
@@ -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 (file)
index 0000000..cbba562
--- /dev/null
@@ -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 (file)
index 0000000..f3fb641
--- /dev/null
@@ -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<ICatalogElement> convertComponentsFromJson(String jsonStr) throws IOException {
+        ObjectMapper objectMapper = new ObjectMapper();
+        return objectMapper.readValue(jsonStr, new TypeReference<List<CatalogElementImpl>>() {});
+    }
+
+    public static List<HealthCheckInfo> convertHealthCheckResponseFromJson(String beJsonResponse) throws Exception {
+        ObjectMapper mapper = new ObjectMapper();
+        Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>() {});
+        if (healthCheckMap.containsKey("componentsInfo")) {
+            return mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {});
+        }
+        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 (file)
index 0000000..6a1fe90
--- /dev/null
@@ -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<ICatalogElement> 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<ICatalogElement> 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<ICatalogElement> predicate = QueryCompositionBuilder.getNodeTypeQuery("cvfc");
+        assertThat(predicate.test(element)).isFalse();
+    }
+
+    @Test
+    public void testNodeTypePredicateForWrongNodeTypeIsNull() {
+        assertThat(QueryCompositionBuilder.getNodeTypeQuery("tp")).isNull();
+    }
+
+
+    @Test
+    public void testTopologyTemplatePredicate() {
+        Predicate<ICatalogElement> 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 (file)
index 0000000..b6b61c6
--- /dev/null
@@ -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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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<Predicate<ICatalogElement>> 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);
+       }
+}