diff options
Diffstat (limited to 'dcae-analytics-aai')
20 files changed, 1605 insertions, 0 deletions
diff --git a/dcae-analytics-aai/pom.xml b/dcae-analytics-aai/pom.xml new file mode 100644 index 0000000..bd3d59a --- /dev/null +++ b/dcae-analytics-aai/pom.xml @@ -0,0 +1,110 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ ===============================LICENSE_START====================================== + ~ dcae-analytics + ~ ================================================================================ + ~ Copyright © 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=========================================== + --> + +<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> + + <parent> + <artifactId>dcae-analytics</artifactId> + <groupId>org.onap.dcaegen2.analytics.tca</groupId> + <version>2.0.0-SNAPSHOT</version> + </parent> + + + <artifactId>dcae-analytics-aai</artifactId> + <packaging>jar</packaging> + + <!-- THIS MODULE CONTAINS CODE FOR DMaaP API --> + <name>DCAE Analytics A&AI</name> + <description>A&AI(Active and Available Inventory) API for DCAE Analytics</description> + + <properties> + <main.basedir>${project.parent.basedir}</main.basedir> + </properties> + + <dependencies> + + <!-- DCAE COMMON DEPENDENCIES --> + <dependency> + <groupId>org.onap.dcaegen2.analytics.tca</groupId> + <artifactId>dcae-analytics-common</artifactId> + <version>2.0.0-SNAPSHOT</version> + </dependency> + + <!-- APACHE CLIENT --> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + + <!-- LOGGING --> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-core</artifactId> + </dependency> + + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-classic</artifactId> + </dependency> + + <dependency> + <groupId>com.google.code.findbugs</groupId> + <artifactId>jsr305</artifactId> + </dependency> + <dependency> + <groupId>com.google.code.findbugs</groupId> + <artifactId>annotations</artifactId> + </dependency> + + + <!-- JACKSON JSON --> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-core</artifactId> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-annotations</artifactId> + </dependency> + + <!-- TEST DEPENDENCIES --> + <dependency> + <groupId>org.onap.dcaegen2.analytics.tca</groupId> + <artifactId>dcae-analytics-test</artifactId> + <version>2.0.0-SNAPSHOT</version> + <scope>test</scope> + </dependency> + </dependencies> + +</project> diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/AAIClientFactory.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/AAIClientFactory.java new file mode 100644 index 0000000..0a8d4ca --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/AAIClientFactory.java @@ -0,0 +1,74 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; +import org.openecomp.dcae.apod.analytics.aai.module.AnalyticsAAIModule; +import org.openecomp.dcae.apod.analytics.aai.service.AAIEnrichmentClient; +import org.openecomp.dcae.apod.analytics.aai.service.AAIEnrichmentClientFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Factory to create A&AI API Client. + * + * @author Rajiv Singla . Creation Date: 9/18/2017. + */ +public class AAIClientFactory { + + private static final Logger LOG = LoggerFactory.getLogger(AAIClientFactory.class); + + private final Injector injector; + + public AAIClientFactory(final AbstractModule guiceModule) { + LOG.info("Creating instance of AAI Client Factory with Module: {}", guiceModule.getClass().getSimpleName()); + this.injector = Guice.createInjector(guiceModule); + } + + /** + * Creates an instance of {@link AAIEnrichmentClient}. + * + * @param aaiHttpClientConfig A&AI Http Client Config + * + * @return An instance of A&AI Enrichment Client to fetch enrichment details from A&AI API. + */ + public AAIEnrichmentClient getEnrichmentClient(final AAIHttpClientConfig aaiHttpClientConfig) { + LOG.info("Creating instance of A&AI Enrichment Client with A&AI HttpClientConfig: {}", aaiHttpClientConfig); + final AAIEnrichmentClientFactory aaiEnrichmentClientFactory = + injector.getInstance(AAIEnrichmentClientFactory.class); + return aaiEnrichmentClientFactory.create(aaiHttpClientConfig); + } + + + /** + * Static method used to create an instance of {@link AAIClientFactory} itself using default + * guice {@link AnalyticsAAIModule} + * + * @return An instance of AAI Client Factory with {@link AnalyticsAAIModule} guice module configuration + */ + public static AAIClientFactory create() { + return new AAIClientFactory(new AnalyticsAAIModule()); + } + +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIEnrichmentConfig.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIEnrichmentConfig.java new file mode 100644 index 0000000..19c284f --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIEnrichmentConfig.java @@ -0,0 +1,33 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.domain.config; + +import java.io.Serializable; + +/** + * <p> + * Marker interface for all A&AI API Enrichment Configs + * </p> + * + * @author Rajiv Singla . Creation Date: 9/14/2017. + */ +public interface AAIEnrichmentConfig extends Serializable { +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIHttpClientConfig.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIHttpClientConfig.java new file mode 100644 index 0000000..37190a0 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIHttpClientConfig.java @@ -0,0 +1,131 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.domain.config; + +import com.google.common.base.Objects; + +import java.net.URL; + +/** + * Contains parameters required to create an instance of A&AI Http Client + * + * @author Rajiv Singla . Creation Date: 9/21/2017. + */ +public class AAIHttpClientConfig implements AAIEnrichmentConfig { + + private static final long serialVersionUID = 1L; + + private final String aaiHost; + private final Integer aaiHostPortNumber; + private final String aaiProtocol; + private final String aaiUserName; + private final String aaiUserPassword; + private final URL aaiProxyURL; + private final boolean aaiIgnoreSSLCertificateErrors; + + AAIHttpClientConfig(final String aaiHost, final Integer aaiHostPortNumber, final String aaiProtocol, + final String aaiUserName, final String aaiUserPassword, final URL aaiProxyURL, + final boolean aaiIgnoreSSLCertificateErrors) { + this.aaiHost = aaiHost; + this.aaiHostPortNumber = aaiHostPortNumber; + this.aaiProtocol = aaiProtocol; + this.aaiUserName = aaiUserName; + this.aaiUserPassword = aaiUserPassword; + this.aaiProxyURL = aaiProxyURL; + this.aaiIgnoreSSLCertificateErrors = aaiIgnoreSSLCertificateErrors; + } + + /** + * Provides A&AI Http Client Host + * + * @return A&AI Http Client Host + */ + public String getAaiHost() { + return aaiHost; + } + + /** + * Provides A&AI Http Client Host Port Number + * + * @return A&AI Http Client Host Port Number + */ + public Integer getAaiHostPortNumber() { + return aaiHostPortNumber; + } + + /** + * Provides A&AI Http Client Protocol + * + * @return A&AI Http Client Protocol + */ + public String getAaiProtocol() { + return aaiProtocol; + } + + /** + * Provides A&AI Http Client UserName + * + * @return A&AI Http Client UserName + */ + public String getAaiUserName() { + return aaiUserName; + } + + /** + * Provides A&AI Http Client UserPassword + * + * @return A&AI Http Client UserPassword + */ + public String getAaiUserPassword() { + return aaiUserPassword; + } + + /** + * Returns A&AI Proxy url + * + * @return A&AI Proxy url + */ + public URL getAaiProxyURL() { + return aaiProxyURL; + } + + /** + * Returns true if SSL Certificate errors can be ignored for A&AI Http client + * + * @return true if SSL Certificate errors can be ignored for A&AI Http client + */ + public boolean isAaiIgnoreSSLCertificateErrors() { + return aaiIgnoreSSLCertificateErrors; + } + + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("aaiHost", aaiHost) + .add("aaiHostPortNumber", aaiHostPortNumber) + .add("aaiProtocol", aaiProtocol) + .add("aaiUserName", aaiUserName) + .add("aaiProxyHost", aaiProxyURL == null ? null : aaiProxyURL.getHost()) + .add("aaiIgnoreSSLCertificateErrors", aaiIgnoreSSLCertificateErrors) + .toString(); + } +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIHttpClientConfigBuilder.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIHttpClientConfigBuilder.java new file mode 100644 index 0000000..3df0050 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/domain/config/AAIHttpClientConfigBuilder.java @@ -0,0 +1,89 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.domain.config; + +import org.openecomp.dcae.apod.analytics.common.AnalyticsConstants; + +import java.io.Serializable; +import java.net.URL; + +/** + * A&AI Http Client Config Builder used to create immutable instance of {@link AAIHttpClientConfig} + * + * @author Rajiv Singla . Creation Date: 9/21/2017. + */ +public class AAIHttpClientConfigBuilder implements Serializable { + + private static final long serialVersionUID = 1L; + + private String aaiHost; + private Integer aaiHostPortNumber; + private String aaiProtocol; + private String aaiUserName; + private String aaiUserPassword; + private URL aaiProxyURL; + private boolean aaiIgnoreSSLCertificateErrors; + + public AAIHttpClientConfigBuilder(final String aaiHost) { + this.aaiHost = aaiHost; + this.aaiHostPortNumber = AnalyticsConstants.DEFAULT_PORT_NUMBER; + this.aaiProtocol = AnalyticsConstants.DEFAULT_PROTOCOL; + this.aaiUserName = AnalyticsConstants.DEFAULT_USER_NAME; + this.aaiUserPassword = AnalyticsConstants.DEFAULT_USER_PASSWORD; + this.aaiIgnoreSSLCertificateErrors = AnalyticsConstants + .TCA_DEFAULT_AAI_ENRICHMENT_IGNORE_SSL_CERTIFICATE_ERRORS; + } + + public AAIHttpClientConfigBuilder setAaiHostPortNumber(final Integer aaiHostPortNumber) { + this.aaiHostPortNumber = aaiHostPortNumber; + return this; + } + + public AAIHttpClientConfigBuilder setAaiProtocol(final String aaiProtocol) { + this.aaiProtocol = aaiProtocol; + return this; + } + + public AAIHttpClientConfigBuilder setAaiUserName(final String aaiUserName) { + this.aaiUserName = aaiUserName; + return this; + } + + public AAIHttpClientConfigBuilder setAaiUserPassword(final String aaiUserPassword) { + this.aaiUserPassword = aaiUserPassword; + return this; + } + + public AAIHttpClientConfigBuilder setAaiProxyURL(final URL aaiProxyURL) { + this.aaiProxyURL = aaiProxyURL; + return this; + } + + public AAIHttpClientConfigBuilder setAaiIgnoreSSLCertificateErrors(final boolean aaiIgnoreSSLCertificateErrors) { + this.aaiIgnoreSSLCertificateErrors = aaiIgnoreSSLCertificateErrors; + return this; + } + + public AAIHttpClientConfig build() { + return new AAIHttpClientConfig(aaiHost, aaiHostPortNumber, aaiProtocol, aaiUserName, aaiUserPassword, + aaiProxyURL, aaiIgnoreSSLCertificateErrors); + } +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/module/AnalyticsAAIModule.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/module/AnalyticsAAIModule.java new file mode 100644 index 0000000..9074798 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/module/AnalyticsAAIModule.java @@ -0,0 +1,54 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.module; + +import com.google.inject.AbstractModule; +import com.google.inject.assistedinject.FactoryModuleBuilder; +import org.openecomp.dcae.apod.analytics.aai.service.AAIEnrichmentClient; +import org.openecomp.dcae.apod.analytics.aai.service.AAIEnrichmentClientFactory; +import org.openecomp.dcae.apod.analytics.aai.service.AAIEnrichmentClientImpl; +import org.openecomp.dcae.apod.analytics.aai.service.AAIHttpClient; +import org.openecomp.dcae.apod.analytics.aai.service.AAIHttpClientFactory; +import org.openecomp.dcae.apod.analytics.aai.service.AAIHttpClientImpl; + +/** + * <p> + * Guice Module to bind concrete implementation of interfaces used in Analytics A&AI API + * </p> + * + * @author Rajiv Singla . Creation Date: 9/18/2017. + */ +public class AnalyticsAAIModule extends AbstractModule { + + /** + * Configures A&AI API guice modules + */ + @Override + protected void configure() { + + install(new FactoryModuleBuilder().implement(AAIHttpClient.class, AAIHttpClientImpl.class) + .build(AAIHttpClientFactory.class)); + + install(new FactoryModuleBuilder().implement(AAIEnrichmentClient.class, AAIEnrichmentClientImpl.class) + .build(AAIEnrichmentClientFactory.class)); + + } +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClient.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClient.java new file mode 100644 index 0000000..8813cdf --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClient.java @@ -0,0 +1,45 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import java.util.Map; + +/** + * <p> + * A client used to get enrichment details from A&AI + * </p> + * + * @author Rajiv Singla . Creation Date: 9/15/2017. + */ +public interface AAIEnrichmentClient { + + /** + * Provides enrichment details from A&AI API and returns them as string. If no enrichment lookup fails returns null + * + * @param aaiAPIPath A&AI API Path + * @param queryParams A&AI Query Params map + * @param headers A&AI HTTP Headers + * + * @return Enrichment details from A&AI API and returns them as string. If enrichment lookup fails returns null + */ + String getEnrichmentDetails(String aaiAPIPath, Map<String, String> queryParams, Map<String, String> headers); + +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientFactory.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientFactory.java new file mode 100644 index 0000000..bd4a4f2 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientFactory.java @@ -0,0 +1,40 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; + +/** + * Factory to initialize instance of {@link AAIEnrichmentClient} for Guice DI injection purposes. + * + * @author Rajiv Singla . Creation Date: 9/19/2017. + */ +public interface AAIEnrichmentClientFactory { + + /** + * Provides an instance of A&AI Enrichment Client used to get details from A&AI API + * + * @param aaiHttpClientConfig A&AI Http Client config used to create A&AI Enrichment client + * + * @return an instance of A&AI Enrichment Client used to get details from A&AI API + */ + AAIEnrichmentClient create(AAIHttpClientConfig aaiHttpClientConfig); +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientImpl.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientImpl.java new file mode 100644 index 0000000..229ab17 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientImpl.java @@ -0,0 +1,202 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import com.google.common.base.Optional; +import com.google.inject.Inject; +import com.google.inject.assistedinject.Assisted; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; +import org.openecomp.dcae.apod.analytics.common.utils.HTTPUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Iterator; +import java.util.Map; + +import javax.annotation.Nonnull; + + +/** + * A concrete implementation for {@link AAIEnrichmentClient} which uses A&AI REST API to get A&AI Enrichment details + * + * @author Rajiv Singla . Creation Date: 9/18/2017. + */ +public class AAIEnrichmentClientImpl implements AAIEnrichmentClient { + + private static final Logger LOG = LoggerFactory.getLogger(AAIEnrichmentClientImpl.class); + + private final CloseableHttpClient closeableHttpClient; + private final String aaiProtocol; + private final String aaiHost; + private final Integer aaiHostPortNumber; + + @Inject + public AAIEnrichmentClientImpl(@Assisted final AAIHttpClientConfig aaiHttpClientConfig, + final AAIHttpClientFactory aaiHttpClientFactory) { + final AAIHttpClient aaiHttpClient = aaiHttpClientFactory.create(aaiHttpClientConfig); + closeableHttpClient = aaiHttpClient.getAAIHttpClient(); + aaiProtocol = aaiHttpClientConfig.getAaiProtocol(); + aaiHost = aaiHttpClientConfig.getAaiHost(); + aaiHostPortNumber = aaiHttpClientConfig.getAaiHostPortNumber(); + } + + + /** + * Provides enrichment details from A&AI API and returns them as string. If no enrichment lookup fails returns null + * + * @param aaiAPIPath A&AI API Path + * @param queryParams A&AI Query Params map + * @param headers A&AI HTTP Headers + * + * @return Enrichment details from A&AI API and returns them as string. If enrichment lookup fails returns null + */ + @Override + public String getEnrichmentDetails(final String aaiAPIPath, final Map<String, String> queryParams, + final Map<String, String> headers) { + + final URI enrichmentURI = + createAAIEnrichmentURI(aaiProtocol, aaiHost, aaiHostPortNumber, aaiAPIPath, queryParams); + + if (enrichmentURI == null) { + return null; + } + + // create new get request + final HttpGet getRequest = new HttpGet(enrichmentURI); + // add http headers + for (Map.Entry<String, String> headersEntry : headers.entrySet()) { + getRequest.addHeader(headersEntry.getKey(), headersEntry.getValue()); + } + + Optional<String> enrichmentDetails = Optional.absent(); + // execute http get request + try { + enrichmentDetails = closeableHttpClient.execute(getRequest, aaiResponseHandler()); + } catch (IOException ex) { + LOG.error("Failed to get A&AI Enrichment Details for A&AI Enrichment URI: {} A&AI Error: {}", + enrichmentURI, ex); + } + + // return response + if (enrichmentDetails.isPresent()) { + return enrichmentDetails.get(); + } else { + return null; + } + } + + /** + * Create A&AI API Enrichment URI. If invalid URI - null will be returned + * + * @param protocol A&AI API protocol + * @param hostName A&AI API hostname + * @param portNumber A&AI API port number + * @param path A&AI API path + * @param queryParams A&AI API query parameters + * + * @return A&AI API Enrichment URI + */ + private URI createAAIEnrichmentURI(final String protocol, final String hostName, + final Integer portNumber, final String path, + Map<String, String> queryParams) { + + final URIBuilder uriBuilder = new URIBuilder().setScheme(protocol).setHost(hostName).setPort(portNumber) + .setPath(path); + + // creates custom query string which is not encoded + final String customQuery = createCustomQuery(queryParams); + if (StringUtils.isNoneBlank(customQuery)) { + uriBuilder.setCustomQuery(customQuery); + } + + URI enrichmentURI = null; + try { + enrichmentURI = uriBuilder.build(); + } catch (URISyntaxException e) { + LOG.error("URI Syntax Exception when creating A&AI Enrichment URI. " + + "Protocol: {}, HostName: {}, Port: {}, Path: {}, Custom Query String: {}, Exception: {}", + protocol, hostName, portNumber, path, customQuery, e); + } + + LOG.trace("Created A&AI Enrichment URI: {}", enrichmentURI); + return enrichmentURI; + } + + /** + * Creates Custom Query string to be used for A&AI API URI as A&AI currently does not expect encoded + * query params. + * + * @param queryParams query param map + * + * @return custom query string which does not encode query param values + */ + private static String createCustomQuery(@Nonnull final Map<String, String> queryParams) { + final StringBuilder queryStringBuilder = new StringBuilder(""); + final Iterator<Map.Entry<String, String>> queryParamIterator = queryParams.entrySet().iterator(); + while (queryParamIterator.hasNext()) { + final Map.Entry<String, String> queryParamsEntry = queryParamIterator.next(); + queryStringBuilder.append(queryParamsEntry.getKey()); + queryStringBuilder.append("="); + queryStringBuilder.append(queryParamsEntry.getValue()); + if (queryParamIterator.hasNext()) { + queryStringBuilder.append("&"); + } + } + return queryStringBuilder.toString(); + } + + /** + * Response Handler for A&AI Enrichment API + * + * @return Response Handler that + */ + static ResponseHandler<Optional<String>> aaiResponseHandler() { + return new ResponseHandler<Optional<String>>() { + @Override + public Optional<String> handleResponse(final HttpResponse response) throws IOException { + final int responseCode = response.getStatusLine().getStatusCode(); + final HttpEntity responseEntity = response.getEntity(); + if (HTTPUtils.isSuccessfulResponseCode(responseCode) && null != responseEntity) { + final String aaiResponse = EntityUtils.toString(responseEntity); + return Optional.of(aaiResponse); + } else { + String aaiResponse = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; + LOG.error("Unable to fetch response from A&AI API. A&AI Response Code: {}, " + + "A&AI Response Message: {}", responseCode, aaiResponse); + return Optional.absent(); + } + } + }; + } + +} + diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClient.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClient.java new file mode 100644 index 0000000..a4adad9 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClient.java @@ -0,0 +1,39 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import org.apache.http.impl.client.CloseableHttpClient; + +/** + * An HTTP Client used to make REST calls to A&AI Enrichment API + * + * @author Rajiv Singla . Creation Date: 9/19/2017. + */ +public interface AAIHttpClient { + + /** + * Provides an instance of {@link CloseableHttpClient} used to make REST calls to A&AI Enrichment API + * + * @return An instance of Closeable HTTP Client used to make A&AI API Rest calls + */ + CloseableHttpClient getAAIHttpClient(); + +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientFactory.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientFactory.java new file mode 100644 index 0000000..e977639 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientFactory.java @@ -0,0 +1,41 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; + +/** + * Factory to initialize instance of {@link AAIHttpClient} for Guice DI injection purposes. + * + * @author Rajiv Singla . Creation Date: 9/22/2017. + */ +public interface AAIHttpClientFactory { + + /** + * Provides an instance of A&AI HTTP Client + * + * @param aaiHttpClientConfig A&AI HTTP Client Config + * + * @return An instance of A&AI HTTP Client + */ + AAIHttpClient create(AAIHttpClientConfig aaiHttpClientConfig); + +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientImpl.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientImpl.java new file mode 100644 index 0000000..34631b1 --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientImpl.java @@ -0,0 +1,159 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import com.google.inject.Inject; +import com.google.inject.assistedinject.Assisted; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.Credentials; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.DefaultProxyRoutePlanner; +import org.apache.http.ssl.SSLContextBuilder; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; +import org.openecomp.dcae.apod.analytics.aai.utils.ssl.AlwaysTrustingTrustStrategy; +import org.openecomp.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +/** + * <p> + * A concrete implementation of {@link AAIHttpClient} which provides Apache {@link CloseableHttpClient} for + * making rest calls to A&AI Enrichment API. + * </p> + * + * @author Rajiv Singla . Creation Date: 9/19/2017. + */ +public class AAIHttpClientImpl implements AAIHttpClient { + + private static final Logger LOG = LoggerFactory.getLogger(AAIHttpClientImpl.class); + + private final AAIHttpClientConfig aaiHttpClientConfig; + + @Inject + public AAIHttpClientImpl(@Assisted final AAIHttpClientConfig aaiHttpClientConfig) { + this.aaiHttpClientConfig = aaiHttpClientConfig; + } + + /** + * Provides an instance of {@link CloseableHttpClient} used to make REST calls to A&AI Enrichment API + * + * @return An instance of Closeable HTTP Client used to make A&AI API Rest calls + */ + @Override + public CloseableHttpClient getAAIHttpClient() { + + final HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); + final boolean aaiIgnoreSSLCertificateErrors = aaiHttpClientConfig.isAaiIgnoreSSLCertificateErrors(); + + // Setup SSL Context to ignore SSL certificate issues if ignoreSSLCertificateErrors is true + LOG.info("SSL Certificate Errors attributed is set to : {}", aaiIgnoreSSLCertificateErrors); + + if (aaiIgnoreSSLCertificateErrors) { + LOG.warn("SSL Certificate Errors will be ignored for this A&AI Http Client Instance"); + try { + SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); + sslContextBuilder.loadTrustMaterial(null, new AlwaysTrustingTrustStrategy()); + httpClientBuilder.setSSLContext(sslContextBuilder.build()); + } catch (NoSuchAlgorithmException e) { + final String errorMessage = "NoSuchAlgorithmException while setting SSL Context for AAI HTTP Client."; + throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e); + } catch (KeyStoreException e) { + final String errorMessage = "KeyStoreException while setting SSL Context for AAI HTTP Client."; + throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e); + } catch (KeyManagementException e) { + final String errorMessage = "KeyManagementException while setting SSL Context for AAI HTTP Client."; + throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e); + } + + httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); + + } else { + LOG.info("SSL Certification Errors will be enforced for A&AI Http Client instance"); + } + + // Setup credentials and proxy + final String aaiUserName = aaiHttpClientConfig.getAaiUserName(); + + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + + if (aaiUserName != null) { + final String aaiHost = aaiHttpClientConfig.getAaiHost(); + final Integer aaiHostPortNumber = aaiHttpClientConfig.getAaiHostPortNumber(); + final String aaiUserPassword = aaiHttpClientConfig.getAaiUserPassword(); + LOG.info("Setting A&AI host credentials for AAI Host: {}", aaiHost); + final AuthScope aaiHostPortAuthScope = new AuthScope(aaiHost, aaiHostPortNumber); + final Credentials aaiCredentials = new UsernamePasswordCredentials(aaiUserName, aaiUserPassword); + credentialsProvider.setCredentials(aaiHostPortAuthScope, aaiCredentials); + } else { + LOG.warn("A&AI userName not present. No credentials set for A&AI authentication"); + } + + final URL aaiProxyURL = aaiHttpClientConfig.getAaiProxyURL(); + + if (aaiProxyURL != null) { + final String aaiProxyHost = aaiProxyURL.getHost(); + final Integer aaiProxyPortNumber = aaiProxyURL.getPort(); + final String aaiProxyProtocol = aaiProxyURL.getProtocol(); + final HttpHost proxy = new HttpHost(aaiProxyHost, aaiProxyPortNumber, aaiProxyProtocol); + LOG.info("Setting A&AI Http Client default proxy as: {}", proxy); + final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); + httpClientBuilder.setRoutePlanner(routePlanner); + + final String userInfo = aaiProxyURL.getUserInfo(); + if (StringUtils.isNotBlank(userInfo)) { + final String[] userInfoArray = userInfo.split(":"); + final String aaiProxyUsername = userInfoArray[0]; + String aaiProxyPassword = null; + if (userInfoArray.length > 1) { + aaiProxyPassword = userInfoArray[1]; + } + LOG.info("Setting A&AI Http Client proxy credentials with username: {}", aaiProxyUsername); + final AuthScope aaiProxyAuthScope = new AuthScope(aaiProxyHost, aaiProxyPortNumber); + final Credentials aaiProxyCredentials = new UsernamePasswordCredentials(aaiProxyUsername, + aaiProxyPassword); + credentialsProvider.setCredentials(aaiProxyAuthScope, aaiProxyCredentials); + } else { + LOG.debug("NO A&AI Proxy Username present.Bypassing setting up A&AI Proxy authentication credentials"); + } + } else { + LOG.debug("A&AI proxy not Enabled - bypassing setting A&AI Proxy settings"); + } + + // setup credentials provider + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + + return httpClientBuilder.build(); + } + +} diff --git a/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/utils/ssl/AlwaysTrustingTrustStrategy.java b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/utils/ssl/AlwaysTrustingTrustStrategy.java new file mode 100644 index 0000000..b11680b --- /dev/null +++ b/dcae-analytics-aai/src/main/java/org/openecomp/dcae/apod/analytics/aai/utils/ssl/AlwaysTrustingTrustStrategy.java @@ -0,0 +1,55 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.utils.ssl; + +import org.apache.http.ssl.TrustStrategy; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * An implementation of SSL Trust Strategy which does no SSL certificate validation effectively + * bypassing any SSL certificate related issues + * + * @author Rajiv Singla . Creation Date: 9/19/2017. + */ +public class AlwaysTrustingTrustStrategy implements TrustStrategy { + /** + * Determines whether the certificate chain can be trusted without consulting the trust manager + * configured in the actual SSL context. This method can be used to override the standard JSSE + * certificate verification process. + * <p> + * Please note that, if this method returns {@code false}, the trust manager configured + * in the actual SSL context can still clear the certificate as trusted. + * + * @param chain the peer certificate chain + * @param authType the authentication type based on the client certificate + * + * @return {@code true} if the certificate can be trusted without verification by + * the trust manager, {@code false} otherwise. + * + * @throws CertificateException thrown if the certificate is not trusted or invalid. + */ + @Override + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } +} diff --git a/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/BaseAnalyticsAAIGuiceUnitTest.java b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/BaseAnalyticsAAIGuiceUnitTest.java new file mode 100644 index 0000000..8c18a74 --- /dev/null +++ b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/BaseAnalyticsAAIGuiceUnitTest.java @@ -0,0 +1,31 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai; + +import org.junit.runner.RunWith; +import org.openecomp.dcae.apod.analytics.test.runner.GuiceJUnitRunner; + +/** + * @author Rajiv Singla . Creation Date: 10/20/2016. + */ +@RunWith(GuiceJUnitRunner.class) +public abstract class BaseAnalyticsAAIGuiceUnitTest extends BaseAnalyticsAAIUnitTest { +} diff --git a/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/BaseAnalyticsAAIUnitTest.java b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/BaseAnalyticsAAIUnitTest.java new file mode 100644 index 0000000..955b5b1 --- /dev/null +++ b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/BaseAnalyticsAAIUnitTest.java @@ -0,0 +1,83 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai; + +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfigBuilder; +import org.openecomp.dcae.apod.analytics.test.BaseDCAEAnalyticsUnitTest; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author Rajiv Singla . Creation Date: 9/18/2017. + */ +public class BaseAnalyticsAAIUnitTest extends BaseDCAEAnalyticsUnitTest { + + protected static final String AAI_HOST_NAME = "1.2.3.4"; + protected static final Integer AAI_HOST_PORT_NUMBER = 1234; + protected static final String AAI_HOST_PROTOCOL = "https"; + protected static final String AAI_VNF_ENRICHMENT_PATH = "/aai/v11/network/generic-vnfs/generic-vnf"; + protected static final String AAI_VSERVER_NODE_QUERY_PATH = "/aai/v11/search/nodes-query"; + protected static final String AAI_VSERVER_QUERY_RESPONSE_LOCATION = "data/json/aai/aai_vserver_resource_data.json"; + + protected static final Map<String, String> AAI_HEADERS = new LinkedHashMap<>(); + + static { + AAI_HEADERS.put("X-FromAppId", "vv-temp"); + AAI_HEADERS.put("X-TransactionId", "vv-temp"); + AAI_HEADERS.put("Accept", "application/json"); + AAI_HEADERS.put("Real-Time", "true"); + AAI_HEADERS.put("Content-Type", "application/json"); + } + + protected static final String PROXY_HOST = "proxy.att.com"; + protected static final Integer PROXY_PORT = 80; + protected static final String PROXY_URL = String.format("http://username:password@%s:%s", PROXY_HOST, PROXY_PORT); + + protected static final String AAI_USER_NAME = "DCAE"; + protected static final String AAI_USER_PASSWORD = "DCAE"; + protected static final boolean IGNORE_SSL_CERTIFICATE_ERRORS = true; + + protected AAIHttpClientConfig getAAIHttpClientTestConfig(final boolean ignoreSSLCertificateErrors, + final String proxyURLString) { + URL proxyURL; + if (proxyURLString != null) { + try { + proxyURL = new URL(proxyURLString); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Proxy URL format is Invalid", e); + } + } else { + proxyURL = null; + } + return new AAIHttpClientConfigBuilder(AAI_HOST_NAME) + .setAaiProtocol(AAI_HOST_PROTOCOL) + .setAaiHostPortNumber(AAI_HOST_PORT_NUMBER) + .setAaiUserName(AAI_USER_NAME) + .setAaiUserPassword(AAI_USER_PASSWORD) + .setAaiProxyURL(proxyURL) + .setAaiIgnoreSSLCertificateErrors(ignoreSSLCertificateErrors).build(); + } + +} diff --git a/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/it/AAIClientFactoryIT.java b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/it/AAIClientFactoryIT.java new file mode 100644 index 0000000..5ebca27 --- /dev/null +++ b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/it/AAIClientFactoryIT.java @@ -0,0 +1,81 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.it; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.dcae.apod.analytics.aai.AAIClientFactory; +import org.openecomp.dcae.apod.analytics.aai.service.AAIEnrichmentClient; + +import java.util.Collections; +import java.util.Map; + +/** + * @author Rajiv Singla . Creation Date: 9/19/2017. + */ +@Ignore +public class AAIClientFactoryIT extends BaseAnalyticsAAIIT { + + private AAIEnrichmentClient enrichmentClient; + + @Before + public void before() { + enrichmentClient = AAIClientFactory.create().getEnrichmentClient(getAAIHttpClientConfig()); + } + + @Test + public void testGetEnrichmentClientForVNF() throws Exception { + final String vnfName = "vCPEInfraVNF13"; + Map<String, String> queryParams = ImmutableMap.of("vnf-name", vnfName); + final String vCPEInfraVNF13 = + enrichmentClient.getEnrichmentDetails(AAI_VNF_ENRICHMENT_PATH, queryParams, AAI_HEADERS); + LOG.info("Fetched VNF A&AI Enrichment Response: \n{}", vCPEInfraVNF13); + + } + + @Test + public void testGetVServerObjectResourceLink() throws Exception { + final String vServerName = "example-vserver-name-val-2"; + Map<String, String> queryParams = ImmutableMap.of("search-node-type", "vserver", "filter", + "vserver-name:EQUALS:" + vServerName); + final String serverResourceLink = + enrichmentClient.getEnrichmentDetails(AAI_VSERVER_NODE_QUERY_PATH, queryParams, AAI_HEADERS); + + LOG.info("Fetched Vserver Object Resource Link A&AI Enrichment Response: \n{}", serverResourceLink); + + } + + @Test + public void testGetVServerEnrichmentDetails() throws Exception { + final String serverResourceLink = fromStream(AAI_VSERVER_QUERY_RESPONSE_LOCATION); + final ObjectMapper objectMapper = new ObjectMapper(); + final JsonNode jsonNode = objectMapper.readTree(serverResourceLink); + final String resourceLink = jsonNode.findPath("resource-link").asText(); + final String vServerEnrichmentDetails = + enrichmentClient.getEnrichmentDetails(resourceLink, Collections.<String, String>emptyMap(), + AAI_HEADERS); + LOG.info("Fetched Vserver enrichment details: \n{}", vServerEnrichmentDetails); + } +} diff --git a/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/it/BaseAnalyticsAAIIT.java b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/it/BaseAnalyticsAAIIT.java new file mode 100644 index 0000000..8f54f77 --- /dev/null +++ b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/it/BaseAnalyticsAAIIT.java @@ -0,0 +1,76 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.it; + +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfigBuilder; +import org.openecomp.dcae.apod.analytics.test.BaseDCAEAnalyticsIT; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author Rajiv Singla . Creation Date: 9/18/2017. + */ +public abstract class BaseAnalyticsAAIIT extends BaseDCAEAnalyticsIT { + + protected static final String AAI_HOST_NAME = "1.2.3.4"; + protected static final Integer AAI_HOST_PORT_NUMBER = 1234; + protected static final String AAI_HOST_PROTOCOL = "https"; + protected static final String AAI_VNF_ENRICHMENT_PATH = "/aai/v11/network/generic-vnfs/generic-vnf"; + protected static final String AAI_VSERVER_NODE_QUERY_PATH = "/aai/v11/search/nodes-query"; + protected static final Map<String, String> AAI_HEADERS = new LinkedHashMap<>(); + + + protected static final String AAI_VSERVER_QUERY_RESPONSE_LOCATION = "data/json/aai/aai_vserver_resource_data.json"; + + static { + AAI_HEADERS.put("X-FromAppId", "vv-temp"); + AAI_HEADERS.put("X-TransactionId", "vv-temp"); + AAI_HEADERS.put("Accept", "application/json"); + AAI_HEADERS.put("Real-Time", "true"); + AAI_HEADERS.put("Content-Type", "application/json"); + } + + protected static final String AAI_USER_NAME = "DCAE"; + protected static final String AAI_USER_PASSWORD = "DCAE"; + protected static final boolean IGNORE_SSL_CERTIFICATE_ERRORS = true; + + + protected AAIHttpClientConfig getAAIHttpClientConfig() { + try { + URL proxyURL = new URL("http://username:password@proxy.att.com:80"); + return new AAIHttpClientConfigBuilder(AAI_HOST_NAME) + .setAaiProtocol(AAI_HOST_PROTOCOL) + .setAaiHostPortNumber(AAI_HOST_PORT_NUMBER) + .setAaiUserName(AAI_USER_NAME) + .setAaiUserPassword(AAI_USER_PASSWORD) + .setAaiProxyURL(proxyURL) + .setAaiIgnoreSSLCertificateErrors(IGNORE_SSL_CERTIFICATE_ERRORS).build(); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + } + + +} diff --git a/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientImplTest.java b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientImplTest.java new file mode 100644 index 0000000..0fbd0e7 --- /dev/null +++ b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/service/AAIEnrichmentClientImplTest.java @@ -0,0 +1,96 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableMap; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.dcae.apod.analytics.aai.BaseAnalyticsAAIUnitTest; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * @author Rajiv Singla . Creation Date: 9/25/2017. + */ +public class AAIEnrichmentClientImplTest extends BaseAnalyticsAAIUnitTest { + + + @Test + public void testGetEnrichmentDetails() throws Exception { + + final String enrichmentResponseJson = "{}"; + + final String vnfName = "vCPEInfraVNF13"; + final AAIHttpClientConfig aaiHttpClientTestConfig = getAAIHttpClientTestConfig(true, PROXY_URL); + Map<String, String> queryParams = ImmutableMap.of("vnf-name", vnfName); + final AAIHttpClientFactory aaiHttpClientFactory = mock(AAIHttpClientFactory.class); + final CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class); + final AAIHttpClient aaiHttpClient = mock(AAIHttpClient.class); + when(aaiHttpClientFactory.create(any(AAIHttpClientConfig.class))).thenReturn(aaiHttpClient); + when(aaiHttpClient.getAAIHttpClient()).thenReturn(closeableHttpClient); + when(closeableHttpClient.execute(any(HttpGet.class), any(ResponseHandler.class))) + .thenReturn(Optional.of(enrichmentResponseJson)); + final AAIEnrichmentClientImpl aaiEnrichmentClient = new AAIEnrichmentClientImpl( + aaiHttpClientTestConfig, aaiHttpClientFactory); + + final String enrichmentDetails = aaiEnrichmentClient.getEnrichmentDetails(AAI_VNF_ENRICHMENT_PATH, + queryParams, AAI_HEADERS); + assertThat("Enrichment response is same", enrichmentDetails, is(enrichmentResponseJson)); + + } + + @Test + public void testAAiResponseHandler() throws Exception { + final ResponseHandler<Optional<String>> aaiResponseHandler = + AAIEnrichmentClientImpl.aaiResponseHandler(); + final HttpResponse httpResponse = mock(HttpResponse.class); + final HttpEntity httpEntity = mock(HttpEntity.class); + final String response = "{}"; + InputStream inputStream = new ByteArrayInputStream(response.getBytes()); + when(httpEntity.getContent()).thenReturn(inputStream); + when(httpResponse.getEntity()).thenReturn(httpEntity); + final StatusLine statusLine = mock(StatusLine.class); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(statusLine.getStatusCode()).thenReturn(200); + final Optional<String> result = aaiResponseHandler.handleResponse(httpResponse); + assertThat("Response must match", result.get(), is(response)); + } + +} diff --git a/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientImplTest.java b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientImplTest.java new file mode 100644 index 0000000..0bb7307 --- /dev/null +++ b/dcae-analytics-aai/src/test/java/org/openecomp/dcae/apod/analytics/aai/service/AAIHttpClientImplTest.java @@ -0,0 +1,109 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.openecomp.dcae.apod.analytics.aai.service; + +import org.apache.http.HttpHost; +import org.apache.http.config.ConnectionConfig; +import org.apache.http.config.Registry; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator; +import org.apache.http.impl.conn.DefaultProxyRoutePlanner; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.impl.conn.SystemDefaultRoutePlanner; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.dcae.apod.analytics.aai.BaseAnalyticsAAIUnitTest; +import org.openecomp.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig; +import sun.security.ssl.SSLContextImpl; +import sun.security.ssl.SSLSocketFactoryImpl; + +import javax.net.ssl.HostnameVerifier; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +/** + * @author Rajiv Singla . Creation Date: 9/25/2017. + */ +public class AAIHttpClientImplTest extends BaseAnalyticsAAIUnitTest { + + @Test + public void getAAIHttpClientWithIgnoredSSLErrorsAndProxySettings() throws Exception { + + final AAIHttpClientConfig aaiHttpClientTestConfig = + getAAIHttpClientTestConfig(true, PROXY_URL); + final AAIHttpClientImpl aaiHttpClient = new AAIHttpClientImpl(aaiHttpClientTestConfig); + final CloseableHttpClient closeableHttpClient = aaiHttpClient.getAAIHttpClient(); + + final HostnameVerifier hostnameVerifier = getHostNameVerifier(closeableHttpClient); + + assertTrue("HostName Verifier must be NoOpHostnameVerifier", + NoopHostnameVerifier.INSTANCE.getClass().equals(hostnameVerifier.getClass())); + + final DefaultProxyRoutePlanner routePlanner = getPrivateFiledValue(closeableHttpClient, "routePlanner", + DefaultProxyRoutePlanner.class); + + final HttpHost proxyHost = getPrivateFiledValue(routePlanner, "proxy", HttpHost.class); + + final String hostName = proxyHost.getHostName(); + final int port = proxyHost.getPort(); + + assertThat("Proxy Host name must match", hostName, is(PROXY_HOST)); + assertThat("Proxy Port number must match", port, is(PROXY_PORT)); + + } + + @Test + public void getAAIHttpClientWithNoIgnoredSSLErrorsAndProxySettings() throws Exception { + + final AAIHttpClientConfig aaiHttpClientTestConfig = + getAAIHttpClientTestConfig(false, null); + final AAIHttpClientImpl aaiHttpClient = new AAIHttpClientImpl(aaiHttpClientTestConfig); + final CloseableHttpClient closeableHttpClient = aaiHttpClient.getAAIHttpClient(); + final HostnameVerifier hostnameVerifier = getHostNameVerifier(closeableHttpClient); + + assertTrue("HostName Verifier must be DefaultHostNameVerifier", + hostnameVerifier instanceof DefaultHostnameVerifier); + + getPrivateFiledValue(closeableHttpClient, "routePlanner", + SystemDefaultRoutePlanner.class); + } + + + private HostnameVerifier getHostNameVerifier(final CloseableHttpClient closeableHttpClient) { + final PoolingHttpClientConnectionManager connManager = + getPrivateFiledValue(closeableHttpClient, "connManager", + PoolingHttpClientConnectionManager.class); + final DefaultHttpClientConnectionOperator connectionOperator = getPrivateFiledValue(connManager, + "connectionOperator", DefaultHttpClientConnectionOperator.class); + final Registry socketFactoryRegistry = getPrivateFiledValue(connectionOperator, "socketFactoryRegistry", + Registry.class); + final SSLConnectionSocketFactory sslConnectionSocketFactory = (SSLConnectionSocketFactory) + socketFactoryRegistry.lookup("https"); + final HostnameVerifier hostnameVerifier = getPrivateFiledValue(sslConnectionSocketFactory, + "hostnameVerifier", HostnameVerifier.class); + return hostnameVerifier; + } +} diff --git a/dcae-analytics-aai/src/test/resources/logback-test.xml b/dcae-analytics-aai/src/test/resources/logback-test.xml new file mode 100644 index 0000000..f4ba1aa --- /dev/null +++ b/dcae-analytics-aai/src/test/resources/logback-test.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!-- + ~ ===============================LICENSE_START====================================== + ~ dcae-analytics + ~ ================================================================================ + ~ Copyright © 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=========================================== + --> +<configuration debug="false"> + + <!-- + Disabling some chatty loggers. + --> + <logger name="org.apache.commons.beanutils" level="ERROR"/> + <logger name="org.apache.zookeeper.server" level="ERROR"/> + <logger name="org.apache.zookeeper" level="ERROR"/> + <logger name="com.ning" level="WARN"/> + <logger name="org.apache.spark" level="WARN"/> + <logger name="org.spark-project" level="WARN"/> + <logger name="org.apache.hadoop" level="WARN"/> + <logger name="org.apache.hive" level="WARN"/> + <logger name="org.quartz.core" level="WARN"/> + <logger name="org.eclipse.jetty" level="WARN"/> + <logger name="io.netty.util.internal" level="WARN"/> + + <logger name="org.apache.http" level="DEBUG"/> + + <logger name="org.apache.twill" level="WARN"/> + <logger name="co.cask.cdap" level="INFO"/> + <logger name="org.openecomp.dcae.apod.analytics" level="DEBUG"/> + + <appender name="Console" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern>%d{ISO8601} - %-5p [%t:%C{1}@%L] - %m%n</pattern> + </encoder> + </appender> + + <root level="ERROR"> + <appender-ref ref="Console"/> + </root> + + +</configuration> + |