summaryrefslogtreecommitdiffstats
path: root/sdc-distribution-client/src/main/java/org/onap/sdc/http
diff options
context:
space:
mode:
authorYuli Shlosberg <ys9693@att.com>2018-03-07 16:29:57 +0200
committerYuli Shlosberg <ys9693@att.com>2018-03-08 14:23:18 +0200
commite8d8a37da95c6fea435e0b3e93a477b5aa45b9b1 (patch)
tree415c9e5643f051e792ee414d887f8fe996a2b372 /sdc-distribution-client/src/main/java/org/onap/sdc/http
parent2f2d71255620b40e6021a54fe514783ebc2d5260 (diff)
update distribution-client package namesv1.3.02.0.0-ONAPbeijing2.0.0-ONAP
Change-Id: Ic6f81bc8fdd3b021033c7c68e44f876a6ee1d21a Issue-ID: SDC-952 Signed-off-by: Yuli Shlosberg <ys9693@att.com>
Diffstat (limited to 'sdc-distribution-client/src/main/java/org/onap/sdc/http')
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java30
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java351
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java71
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java33
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java398
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java41
6 files changed, 924 insertions, 0 deletions
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java
new file mode 100644
index 0000000..72a51d3
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/AsdcUrls.java
@@ -0,0 +1,30 @@
+/*-
+ * ============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=========================================================
+ */
+
+package org.onap.sdc.http;
+
+public class AsdcUrls {
+
+ public static final String GET_CLUSTER_SERVER_LIST = "/sdc/v1/distributionUebCluster";
+ public static final String GET_VALID_ARTIFACT_TYPES = "/sdc/v1/artifactTypes";
+ public static final String POST_FOR_TOPIC_REGISTRATION = "/sdc/v1/registerForDistribution";
+ public static final String POST_FOR_UNREGISTER = "/sdc/v1/unRegisterForDistribution";
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java
new file mode 100644
index 0000000..c241bec
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcClient.java
@@ -0,0 +1,351 @@
+/*-
+ * ============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=========================================================
+ */
+
+package org.onap.sdc.http;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.ConnectException;
+import java.net.UnknownHostException;
+import java.security.KeyStore;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.StringEntity;
+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.message.BasicHeader;
+import org.apache.http.ssl.SSLContextBuilder;
+import org.apache.http.ssl.TrustStrategy;
+import org.onap.sdc.api.consumer.IConfiguration;
+import org.onap.sdc.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpAsdcClient implements IHttpAsdcClient {
+
+ private static final String TLS = "TLSv1.2";
+ private static final String AUTHORIZATION_HEADER = "Authorization";
+ private static final String HTTPS = "https://";
+ private static Logger log = LoggerFactory.getLogger(HttpAsdcClient.class.getName());
+ private CloseableHttpClient httpClient = null;
+ private String serverFqdn = null;
+ private String authHeaderValue = "";
+
+ public HttpAsdcClient(IConfiguration configuraion) {
+ this.serverFqdn = configuraion.getAsdcAddress();
+
+ String username = configuraion.getUser();
+ String password = configuraion.getPassword();
+ initSSL(username, password, configuraion.getKeyStorePath(), configuraion.getKeyStorePassword(), configuraion.activateServerTLSAuth());
+
+ String userNameAndPassword = username + ":" + password;
+ this.authHeaderValue = "Basic " + Base64.encodeBase64String(userNameAndPassword.getBytes());
+ }
+
+ // @SuppressWarnings("deprecation")
+ private void initSSL(String username, String password, String keyStorePath, String keyStoePass, boolean isSupportSSLVerification) {
+
+ try {
+ HostnameVerifier hostnameVerifier = new HostnameVerifier() {
+
+ @Override
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ };
+
+ // SSLContextBuilder is not thread safe
+ // @SuppressWarnings("deprecation")
+ CredentialsProvider credsProvider = new BasicCredentialsProvider();
+ credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials(username, password));
+ SSLContext sslContext;
+ sslContext = SSLContext.getInstance(TLS);
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ KeyStore trustStore = null;
+ tmf.init(trustStore);
+ TrustManager[] tms = tmf.getTrustManagers();
+ if (isSupportSSLVerification) {
+
+ if (keyStorePath != null && !keyStorePath.isEmpty()) {
+ // trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ // trustStore.load(new FileInputStream(keyStorePath), keyStoePass.toCharArray());
+
+ // Using null here initialises the TMF with the default trust store.
+
+ // Get hold of the default trust manager
+ X509TrustManager defaultTm = null;
+ for (TrustManager tm : tmf.getTrustManagers()) {
+ if (tm instanceof X509TrustManager) {
+ defaultTm = (X509TrustManager) tm;
+ break;
+ }
+ }
+
+ // Do the same with your trust store this time
+ // Adapt how you load the keystore to your needs
+ trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ trustStore.load(new FileInputStream(keyStorePath), keyStoePass.toCharArray());
+
+ tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(trustStore);
+
+ // Get hold of the default trust manager
+ X509TrustManager myTm = null;
+ for (TrustManager tm : tmf.getTrustManagers()) {
+ if (tm instanceof X509TrustManager) {
+ myTm = (X509TrustManager) tm;
+ break;
+ }
+ }
+
+ // Wrap it in your own class.
+ final X509TrustManager finalDefaultTm = defaultTm;
+ final X509TrustManager finalMyTm = myTm;
+ X509TrustManager customTm = new X509TrustManager() {
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ // If you're planning to use client-cert auth,
+ // merge results from "defaultTm" and "myTm".
+ return finalDefaultTm.getAcceptedIssuers();
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ try {
+ finalMyTm.checkServerTrusted(chain, authType);
+ } catch (CertificateException e) {
+ // This will throw another CertificateException if this fails too.
+ finalDefaultTm.checkServerTrusted(chain, authType);
+ }
+ }
+
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ // If you're planning to use client-cert auth,
+ // do the same as checking the server.
+ finalDefaultTm.checkClientTrusted(chain, authType);
+ }
+ };
+
+ tms = new TrustManager[] { customTm };
+
+ }
+
+ sslContext.init(null, tms, null);
+ SSLContext.setDefault(sslContext);
+
+
+
+ } else {
+
+ SSLContextBuilder builder = new SSLContextBuilder();
+
+ builder.loadTrustMaterial(null, new TrustStrategy() {
+ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ return true;
+ }
+ });
+
+ sslContext = builder.build();
+ }
+
+ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null, hostnameVerifier);
+ httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslsf).build();
+
+ } catch (Exception e) {
+ log.error("Failed to create https client", e);
+
+ }
+
+ return;
+ }
+
+ public HttpAsdcResponse postRequest(String requestUrl, HttpEntity entity, Map<String, String> headersMap) {
+ return postRequest(requestUrl, entity, headersMap, true).getFirst();
+ }
+
+ public Pair<HttpAsdcResponse, CloseableHttpResponse> postRequest(String requestUrl, HttpEntity entity, Map<String, String> headersMap, boolean closeTheRequest) {
+ Pair<HttpAsdcResponse, CloseableHttpResponse> ret;
+ CloseableHttpResponse httpResponse = null;
+ HttpAsdcResponse response = null;
+ HttpPost httpPost = new HttpPost(HTTPS + serverFqdn + requestUrl);
+ List<Header> headers = addHeadersToHttpRequest(headersMap);
+ for (Header header : headers) {
+ httpPost.addHeader(header);
+ }
+
+ httpPost.setHeader(AUTHORIZATION_HEADER, this.authHeaderValue);
+
+ httpPost.setEntity(entity);
+ try {
+ httpResponse = httpClient.execute(httpPost);
+ response = new HttpAsdcResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getEntity());
+
+ } catch (IOException e) {
+ log.error("failed to send request to url: " + requestUrl);
+ StringEntity errorEntity = null;
+ try {
+ errorEntity = new StringEntity("failed to send request");
+ } catch (UnsupportedEncodingException e1) {
+ }
+
+ response = new HttpAsdcResponse(500, errorEntity);
+
+ } finally {
+ if (closeTheRequest) {
+ if (httpResponse != null) {
+ try {
+ httpResponse.close();
+
+ } catch (IOException e) {
+ log.error("failed to close http response");
+ }
+ }
+ ret = new Pair<>(response, null);
+ } else {
+ ret = new Pair<>(response, httpResponse);
+ }
+ }
+
+ return ret;
+ }
+
+ public HttpAsdcResponse getRequest(String requestUrl, Map<String, String> headersMap) {
+
+ return getRequest(requestUrl, headersMap, true).getFirst();
+
+ }
+
+ public Pair<HttpAsdcResponse, CloseableHttpResponse> getRequest(String requestUrl, Map<String, String> headersMap, boolean closeTheRequest) {
+ Pair<HttpAsdcResponse, CloseableHttpResponse> ret;
+ CloseableHttpResponse httpResponse = null;
+ String url = HTTPS + serverFqdn + requestUrl;
+ log.debug("url to send {}", url);
+ HttpGet httpGet = new HttpGet(url);
+ List<Header> headers = addHeadersToHttpRequest(headersMap);
+ for (Header header : headers) {
+ httpGet.addHeader(header);
+ }
+
+ httpGet.setHeader(AUTHORIZATION_HEADER, this.authHeaderValue);
+
+ HttpAsdcResponse response = null;
+ try {
+ httpResponse = httpClient.execute(httpGet);
+
+ log.debug("GET Response Status {}", httpResponse.getStatusLine().getStatusCode());
+ Header[] headersRes = httpResponse.getAllHeaders();
+ Map<String, String> headersResMap = new HashMap<>();
+ for (Header header : headersRes) {
+ headersResMap.put(header.getName(), header.getValue());
+ }
+ response = new HttpAsdcResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getEntity(), headersResMap);
+
+ } catch (UnknownHostException | ConnectException e) {
+ log.error("failed to connect to url: {}", requestUrl, e);
+ StringEntity errorEntity = null;
+ try {
+ errorEntity = new StringEntity("failed to connect");
+ } catch (UnsupportedEncodingException e1) {
+ }
+
+ response = new HttpAsdcResponse(HttpStatus.SC_BAD_GATEWAY, errorEntity);
+
+ } catch (IOException e) {
+ log.error("failed to send request to url: " + requestUrl + " error " + e.getMessage());
+ StringEntity errorEntity = null;
+ try {
+ errorEntity = new StringEntity("failed to send request " + e.getMessage());
+ } catch (UnsupportedEncodingException e1) {
+ }
+
+ response = new HttpAsdcResponse(HttpStatus.SC_BAD_GATEWAY, errorEntity);
+
+ } finally {
+
+ if (closeTheRequest) {
+ if (httpResponse != null) {
+ try {
+ httpResponse.close();
+
+ } catch (IOException e) {
+ log.error("failed to close http response");
+ }
+ }
+ ret = new Pair<HttpAsdcResponse, CloseableHttpResponse>(response, null);
+ } else {
+ ret = new Pair<HttpAsdcResponse, CloseableHttpResponse>(response, httpResponse);
+ }
+ }
+
+ return ret;
+
+ }
+
+ public void closeHttpClient() {
+ try {
+ httpClient.close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ log.error("failed to close http client");
+ }
+
+ }
+
+ private List<Header> addHeadersToHttpRequest(Map<String, String> headersMap) {
+
+ List<Header> requestHeaders = new ArrayList<Header>();
+
+ Set<String> headersKyes = headersMap.keySet();
+ for (String key : headersKyes) {
+ Header requestHeader = new BasicHeader(key, headersMap.get(key));
+ requestHeaders.add(requestHeader);
+ }
+
+ return requestHeaders;
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java
new file mode 100644
index 0000000..9734a32
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/HttpAsdcResponse.java
@@ -0,0 +1,71 @@
+/*-
+ * ============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=========================================================
+ */
+
+package org.onap.sdc.http;
+
+import java.util.Map;
+
+import org.apache.http.HttpEntity;
+
+public class HttpAsdcResponse {
+
+ int status;
+ HttpEntity message;
+ Map<String, String> headersMap;
+
+ public HttpAsdcResponse(int status, HttpEntity message) {
+ super();
+ this.status = status;
+ this.message = message;
+ }
+
+ public HttpAsdcResponse(int status, HttpEntity message, Map<String, String> headersMap) {
+ super();
+ this.status = status;
+ this.message = message;
+ this.headersMap = headersMap;
+ }
+
+ public Map<String, String> getHeadersMap() {
+ return headersMap;
+ }
+
+ public void setHeadersMap(Map<String, String> headersMap) {
+ this.headersMap = headersMap;
+ }
+
+ public int getStatus() {
+ return status;
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public HttpEntity getMessage() {
+ return message;
+ }
+
+ public void setMessage(HttpEntity message) {
+ this.message = message;
+ }
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java
new file mode 100644
index 0000000..a3cc5e5
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/IHttpAsdcClient.java
@@ -0,0 +1,33 @@
+/*-
+ * ============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=========================================================
+ */
+
+package org.onap.sdc.http;
+
+import java.util.Map;
+
+import org.apache.http.HttpEntity;
+
+public interface IHttpAsdcClient {
+
+ HttpAsdcResponse postRequest(String requestUrl, HttpEntity entity, Map<String, String> headersMap);
+ HttpAsdcResponse getRequest(String requestUrl, Map<String, String> headersMap);
+ void closeHttpClient();
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java
new file mode 100644
index 0000000..41d78ba
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/SdcConnectorClient.java
@@ -0,0 +1,398 @@
+/*-
+ * ============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=========================================================
+ */
+
+package org.onap.sdc.http;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHeaders;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.impl.DistributionClientResultImpl;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+import org.onap.sdc.utils.GeneralUtils;
+import org.onap.sdc.api.asdc.RegistrationRequest;
+import org.onap.sdc.api.asdc.ServerListResponse;
+import org.onap.sdc.api.consumer.IConfiguration;
+import org.onap.sdc.impl.DistributionClientDownloadResultImpl;
+import org.onap.sdc.utils.DistributionClientConstants;
+import org.onap.sdc.utils.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.att.nsa.apiClient.credentials.ApiCredential;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+
+import fj.data.Either;
+
+public class SdcConnectorClient {
+ String contentDispositionHeader = "Content-Disposition";
+ private static Logger log = LoggerFactory.getLogger(SdcConnectorClient.class.getName());
+ private IConfiguration configuration;
+ private HttpAsdcClient httpClient = null;
+
+ public void init(IConfiguration configuraion) {
+ this.configuration = configuraion;
+ httpClient = new HttpAsdcClient(configuration);
+ }
+
+ public void close() {
+ if (httpClient != null) {
+ httpClient.closeHttpClient();
+ }
+ }
+
+ public IConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ public void setConfiguration(IConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ public HttpAsdcClient getHttpClient() {
+ return httpClient;
+ }
+
+ public void setHttpClient(HttpAsdcClient httpClient) {
+ this.httpClient = httpClient;
+ }
+
+
+ public Either<List<String>, IDistributionClientResult> getValidArtifactTypesList() {
+ Pair<HttpAsdcResponse, CloseableHttpResponse> getServersResponsePair = performAsdcServerRequest(AsdcUrls.GET_VALID_ARTIFACT_TYPES);
+ HttpAsdcResponse getArtifactTypeResponse = getServersResponsePair.getFirst();
+
+ Either<List<String>, IDistributionClientResult> response;
+ if (getArtifactTypeResponse.getStatus() == HttpStatus.SC_OK) {
+ response = parseGetValidArtifactTypesResponse(getArtifactTypeResponse);
+ } else {
+ IDistributionClientResult asdcError = handleAsdcError(getArtifactTypeResponse);
+ response = Either.right(asdcError);
+
+ }
+ handeAsdcConnectionClose(getServersResponsePair);
+ return response;
+
+ }
+
+ private void handeAsdcConnectionClose(Pair<HttpAsdcResponse, CloseableHttpResponse> getServersResponsePair) {
+ if (getServersResponsePair.getSecond() != null) {
+ try {
+ getServersResponsePair.getSecond().close();
+
+ } catch (IOException e) {
+ log.error("failed to close http response");
+ }
+
+ }
+ }
+
+ private Pair<HttpAsdcResponse, CloseableHttpResponse> performAsdcServerRequest(final String url) {
+ String requestId = UUID.randomUUID().toString();
+ Map<String, String> requestHeaders = addHeadersToHttpRequest(requestId);
+ log.debug("about to perform getServerList. requestId= {} url= {}", requestId, url);
+ Pair<HttpAsdcResponse, CloseableHttpResponse> getServersResponsePair = httpClient.getRequest(url, requestHeaders, false);
+ return getServersResponsePair;
+ }
+
+ public Either<TopicRegistrationResponse, DistributionClientResultImpl> registerAsdcTopics(ApiCredential credential) {
+
+ Either<TopicRegistrationResponse, DistributionClientResultImpl> response = null;
+
+ String requestId = UUID.randomUUID().toString();
+ Map<String, String> requestHeaders = addHeadersToHttpRequest(requestId);
+
+ RegistrationRequest registrationRequest = new RegistrationRequest(credential.getApiKey(), configuration.getEnvironmentName(), configuration.isConsumeProduceStatusTopic(), configuration.getMsgBusAddress());
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ String jsonRequest = gson.toJson(registrationRequest);
+ StringEntity body = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON);
+
+ log.debug("about to perform registerAsdcTopics. requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_TOPIC_REGISTRATION);
+ Pair<HttpAsdcResponse, CloseableHttpResponse> registerResponsePair = httpClient.postRequest(AsdcUrls.POST_FOR_TOPIC_REGISTRATION, body, requestHeaders, false);
+ HttpAsdcResponse registerResponse = registerResponsePair.getFirst();
+ int status = registerResponse.getStatus();
+
+ if (status == HttpStatus.SC_OK) {
+ response = parseRegistrationResponse(registerResponse);
+
+ } else {
+ DistributionClientResultImpl asdcError = handleAsdcError(registerResponse);
+ return Either.right(asdcError);
+ }
+ handeAsdcConnectionClose(registerResponsePair);
+
+ log.debug("registerAsdcTopics response= " + status + ". requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_TOPIC_REGISTRATION);
+ return response;
+
+ }
+
+ public IDistributionClientResult unregisterTopics(ApiCredential credential) {
+
+ DistributionClientResultImpl response = null;
+
+ String requestId = UUID.randomUUID().toString();
+ HttpAsdcClient httpClient = new HttpAsdcClient(configuration);
+ Map<String, String> requestHeaders = addHeadersToHttpRequest(requestId);
+
+ RegistrationRequest registrationRequest = new RegistrationRequest(credential.getApiKey(), configuration.getEnvironmentName(), configuration.isConsumeProduceStatusTopic(), configuration.getMsgBusAddress());
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ String jsonRequest = gson.toJson(registrationRequest);
+ StringEntity body = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON);
+
+ log.debug("about to perform unregisterTopics. requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_UNREGISTER);
+ Pair<HttpAsdcResponse, CloseableHttpResponse> unRegisterResponsePair = httpClient.postRequest(AsdcUrls.POST_FOR_UNREGISTER, body, requestHeaders, false);
+ HttpAsdcResponse unRegisterResponse = unRegisterResponsePair.getFirst();
+ int status = unRegisterResponse.getStatus();
+ if (status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_OK) {
+ response = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "unregistration successful");
+
+ } else {
+ response = handleAsdcError(unRegisterResponse);
+ }
+
+ handeAsdcConnectionClose(unRegisterResponsePair);
+
+ log.debug("unregisterTopics response = " + status + ". requestId= " + requestId + " url= " + AsdcUrls.POST_FOR_UNREGISTER);
+
+ return response;
+
+ }
+
+ public DistributionClientDownloadResultImpl dowloadArtifact(IArtifactInfo artifactInfo) {
+ DistributionClientDownloadResultImpl response = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to download artifact from ASDC");
+
+ String requestId = UUID.randomUUID().toString();
+ Map<String, String> requestHeaders = new HashMap<String, String>();
+ requestHeaders.put(DistributionClientConstants.HEADER_REQUEST_ID, requestId);
+ requestHeaders.put(DistributionClientConstants.HEADER_INSTANCE_ID, configuration.getConsumerID());
+ requestHeaders.put(HttpHeaders.ACCEPT, ContentType.APPLICATION_OCTET_STREAM.toString());
+ String requestUrl = artifactInfo.getArtifactURL();
+ Pair<HttpAsdcResponse, CloseableHttpResponse> downloadPair = httpClient.getRequest(requestUrl, requestHeaders, false);
+ HttpAsdcResponse downloadResponse = downloadPair.getFirst();
+
+ int status = downloadResponse.getStatus();
+ if (status == 200) {
+
+ response = parseDownloadArtifactResponse(artifactInfo, downloadResponse);
+ } else {
+ response = handleAsdcDownloadArtifactError(downloadResponse);
+
+ }
+ handeAsdcConnectionClose(downloadPair);
+ return response;
+ }
+
+ /* **************************** private methods ********************************************/
+
+ private Either<List<String>, IDistributionClientResult> parseGetServersResponse(HttpAsdcResponse getServersResponse) {
+ Either<List<String>, IDistributionClientResult> result;
+ try {
+ String jsonMessage = IOUtils.toString(getServersResponse.getMessage().getContent());
+
+ Gson gson = new GsonBuilder().create();
+ ServerListResponse serverListResponse = gson.fromJson(jsonMessage, ServerListResponse.class);
+ List<String> serverList = serverListResponse.getUebServerList();
+ result = Either.left(serverList);
+
+ } catch (UnsupportedOperationException | IOException e) {
+ result = handleParsingError(e);
+ }
+
+ return result;
+ }
+
+ private Either<List<String>, IDistributionClientResult> parseGetValidArtifactTypesResponse(HttpAsdcResponse getArtifactTypesResponse) {
+ Either<List<String>, IDistributionClientResult> result;
+ try {
+ String jsonMessage = IOUtils.toString(getArtifactTypesResponse.getMessage().getContent());
+ Type listType = new TypeToken<ArrayList<String>>() {
+ }.getType();
+ Gson gson = new GsonBuilder().create();
+ List<String> artifactTypesList = gson.fromJson(jsonMessage, listType);
+ result = Either.left(artifactTypesList);
+
+ } catch (UnsupportedOperationException | IOException e) {
+ result = handleParsingError(e);
+ }
+
+ return result;
+ }
+
+ private Either<List<String>, IDistributionClientResult> handleParsingError(Exception e) {
+ Either<List<String>, IDistributionClientResult> result;
+ log.error("failed to parse response from ASDC. error: " + e.getMessage());
+ IDistributionClientResult response = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to parse response from ASDC");
+ result = Either.right(response);
+ return result;
+ }
+
+ Either<TopicRegistrationResponse, DistributionClientResultImpl> parseRegistrationResponse(HttpAsdcResponse registerResponse) {
+
+ String jsonMessage;
+ try {
+ jsonMessage = IOUtils.toString(registerResponse.getMessage().getContent());
+
+ Gson gson = new GsonBuilder().create();
+ TopicRegistrationResponse registrationResponse = gson.fromJson(jsonMessage, TopicRegistrationResponse.class);
+
+ if (registrationResponse.getDistrNotificationTopicName() == null) {
+ DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.FAIL, "failed to receive notification topic from ASDC");
+ return Either.right(response);
+ }
+
+ if (registrationResponse.getDistrStatusTopicName() == null) {
+ DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.FAIL, "failed to receive status topic from ASDC");
+ return Either.right(response);
+ }
+ return Either.left(registrationResponse);
+
+ } catch (UnsupportedOperationException | IOException e) {
+ log.error("failed to pars response from ASDC. error: " + e.getMessage());
+ DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to parse response from ASDC");
+ return Either.right(response);
+ }
+ }
+
+ protected Map<String, String> addHeadersToHttpRequest(String requestId) {
+ Map<String, String> requestHeaders = new HashMap<>();
+ requestHeaders.put(DistributionClientConstants.HEADER_REQUEST_ID, requestId);
+ requestHeaders.put(DistributionClientConstants.HEADER_INSTANCE_ID, configuration.getConsumerID());
+ requestHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
+
+ return requestHeaders;
+ }
+
+ private DistributionClientResultImpl handleAsdcError(HttpAsdcResponse registerResponse) {
+ int status = registerResponse.getStatus();
+ DistributionClientResultImpl errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to send request to ASDC");
+ if (status == HttpStatus.SC_UNAUTHORIZED) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_AUTHENTICATION_FAILED, "authentication to ASDC failed for user " + configuration.getUser());
+ } else if (status == HttpStatus.SC_FORBIDDEN) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_AUTHORIZATION_FAILED, "authorization failure for user " + configuration.getUser());
+ } else if (status == HttpStatus.SC_BAD_REQUEST) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.BAD_REQUEST, "ASDC call failed due to missing information");
+ } else if (status == HttpStatus.SC_NOT_FOUND) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_NOT_FOUND, "ASDC not found");
+ } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "ASDC server problem");
+ } else if (status == HttpStatus.SC_BAD_GATEWAY) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, "ASDC server problem");
+ } else if (status == HttpStatus.SC_GATEWAY_TIMEOUT) {
+ errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, "ASDC server problem");
+ }
+ log.error("status from ASDC is " + registerResponse);
+ log.error(errorResponse.toString());
+ try {
+ String errorString = IOUtils.toString(registerResponse.getMessage().getContent());
+ log.debug("error from ASDC is: " + errorString);
+ } catch (UnsupportedOperationException | IOException e) {
+ }
+ return errorResponse;
+
+ }
+
+ private DistributionClientDownloadResultImpl handleAsdcDownloadArtifactError(HttpAsdcResponse registerResponse) {
+ int status = registerResponse.getStatus();
+ DistributionClientDownloadResultImpl errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "failed to send request to ASDC");
+ if (status == HttpStatus.SC_UNAUTHORIZED) {
+ errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_AUTHENTICATION_FAILED, "authentication to ASDC failed for user " + configuration.getUser());
+ } else if (status == HttpStatus.SC_FORBIDDEN) {
+ errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_AUTHORIZATION_FAILED, "authorization failure for user " + configuration.getUser());
+ } else if (status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_NOT_FOUND) {
+ errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ARTIFACT_NOT_FOUND, "Specified artifact is not found");
+ // } else if (status == 404){
+ // errorResponse = new DistributionClientDownloadResultImpl(
+ // DistributionActionResultEnum.ASDC_NOT_FOUND,
+ // "ASDC not found");
+ } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
+ errorResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "ASDC server problem");
+ }
+ log.error("status from ASDC is " + registerResponse);
+ log.error(errorResponse.toString());
+ try {
+ String errorString = IOUtils.toString(registerResponse.getMessage().getContent());
+ log.debug("error from ASDC is: " + errorString);
+ } catch (UnsupportedOperationException | IOException e) {
+ }
+ return errorResponse;
+
+ }
+
+ private DistributionClientDownloadResultImpl parseDownloadArtifactResponse(IArtifactInfo artifactInfo, HttpAsdcResponse getServersResponse) {
+ HttpEntity entity = getServersResponse.getMessage();
+ InputStream is;
+ try {
+ is = entity.getContent();
+ String artifactName = "";
+ if (getServersResponse.getHeadersMap().containsKey(contentDispositionHeader))
+ artifactName = getServersResponse.getHeadersMap().get(contentDispositionHeader);
+
+ byte[] payload = IOUtils.toByteArray(is);
+ if (artifactInfo.getArtifactChecksum() == null || artifactInfo.getArtifactChecksum().isEmpty()) {
+ return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.DATA_INTEGRITY_PROBLEM, "failed to get artifact from ASDC. Empty checksum");
+ }
+
+ DistributionClientDownloadResultImpl resResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "success", artifactName, payload);
+ return resResponse;
+
+ //Validate checksum removed as fix to bug 293657
+ /*if (validateChecksum(artifactInfo, payload)) {
+ DistributionClientDownloadResultImpl resResponse = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "success", artifactName, payload);
+ return resResponse;
+
+ } else {
+
+ return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Invalid checksum. ArtifactInfo checksum ");
+ }*/
+
+ } catch (UnsupportedOperationException | IOException e) {
+ log.error("failed to get artifact from response ");
+ return new DistributionClientDownloadResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "UnsupportedOperationException ");
+ }
+
+ }
+
+ private boolean validateChecksum(IArtifactInfo artifactInfo, byte[] payload) {
+ boolean bRes = false;
+ String calculatedMD5 = GeneralUtils.calculateMD5(payload);
+ if (artifactInfo.getArtifactChecksum().equals(calculatedMD5)) {
+ bRes = true;
+ }
+
+ return bRes;
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java
new file mode 100644
index 0000000..e8d0545
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/http/TopicRegistrationResponse.java
@@ -0,0 +1,41 @@
+/*-
+ * ============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=========================================================
+ */
+
+package org.onap.sdc.http;
+
+public class TopicRegistrationResponse {
+ String distrNotificationTopicName;
+ String distrStatusTopicName;
+
+
+ public void setDistrNotificationTopicName(String distrNotificationTopicName) {
+ this.distrNotificationTopicName = distrNotificationTopicName;
+ }
+ public void setDistrStatusTopicName(String distrStatusTopicName) {
+ this.distrStatusTopicName = distrStatusTopicName;
+ }
+
+ public String getDistrNotificationTopicName() {
+ return distrNotificationTopicName;
+ }
+ public String getDistrStatusTopicName() {
+ return distrStatusTopicName;
+ }
+}