aboutsummaryrefslogtreecommitdiffstats
path: root/sdc-distribution-client/src/main/java/org/onap/sdc
diff options
context:
space:
mode:
Diffstat (limited to 'sdc-distribution-client/src/main/java/org/onap/sdc')
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java210
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java25
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java56
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java36
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java7
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java157
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java28
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java28
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java9
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java29
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java35
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java104
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java71
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java65
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java65
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java63
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java45
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java28
-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
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java192
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java225
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java74
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java34
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java779
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java50
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java113
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java148
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java158
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java181
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java179
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java66
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java95
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java61
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java78
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java37
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java127
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java46
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java58
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java44
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java56
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java92
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java39
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java45
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java155
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java42
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java207
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java93
-rw-r--r--sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java75
53 files changed, 5534 insertions, 0 deletions
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java
new file mode 100644
index 0000000..d3a8188
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionClient.java
@@ -0,0 +1,210 @@
+/*-
+ * ============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.api;
+
+import java.util.List;
+
+import org.onap.sdc.api.consumer.*;
+import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.api.consumer.*;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.notification.IVfModuleMetadata;
+
+public interface IDistributionClient {
+
+ /**
+ * Update the configuration of the distribution client <br>
+ * Updatable configuration parameters are: pollingInterval, pollingTimeout,
+ * consumerGroup and relevantArtifactTypes
+ *
+ * @param newConf
+ * - contains updated configuration
+ *
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult updateConfiguration(IConfiguration newConf);
+
+ /**
+ * Retrieve the configuration of the distribution client <br>
+ *
+ * @return IConfiguration
+ */
+ IConfiguration getConfiguration();
+
+ /**
+ * Start distribution client <br>
+ * - start polling notification topic <br>
+ *
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult start();
+
+ /**
+ * Stop distribution client <br>
+ * - stop polling notification topic <br>
+ * - unregister topics (via ASDC) <br>
+ * - delete keys from UEB
+ *
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult stop();
+
+ /**
+ * Downloads an artifact from ASDC Catalog <br>
+ *
+ * @param artifactInfo
+ * @return IDistributionClientDownloadResult
+ */
+ IDistributionClientDownloadResult download(IArtifactInfo artifactInfo);
+
+ /**
+ * Initialize the distribution client <br>
+ * - fetch the UEB server list from ASDC <br>
+ * - create keys in UEB <br>
+ * - register for topics (via ASDC) <br>
+ * - set the notification callback <br>
+ *
+ * Note: all configuration fields are mandatory. <br>
+ * Password must be in clear text and not encrypted <br>
+ * ONAP-Component MUST store password as SHA-2 (256) hashed with
+ * dynamically generated salt value <br>
+ *
+ * @param conf
+ * @param callback
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult init(IConfiguration conf, INotificationCallback callback);
+
+ /**
+ * Initialize the distribution client <br>
+ * - fetch the UEB server list from ASDC <br>
+ * - create keys in UEB <br>
+ * - register for topics (via ASDC) <br>
+ * - set the notification callback <br>
+ *
+ * Note: all configuration fields are mandatory. <br>
+ * Password must be in clear text and not encrypted <br>
+ * ONAP-Component MUST store password as SHA-2 (256) hashed with
+ * dynamically generated salt value <br>
+ *
+ * @param conf
+ * @param notificationCallback
+ * @param statusCallback
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback,
+ IStatusCallback statusCallback);
+
+ /**
+ * Build and publish Distribution Download Status event to Distribution
+ * Status Topic
+ *
+ * @param statusMessage
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage);
+
+ /**
+ * Build and publish Distribution Download Status event to Distribution
+ * Status Topic With Error Reason.
+ *
+ * @param statusMessage
+ * @param errorReason
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage, String errorReason);
+
+ /**
+ * Build and publish Distribution Deployment Status event to Distribution
+ * Status Topic
+ *
+ * @param statusMessage
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage);
+
+ /**
+ * Build and publish Distribution Deployment Status event to Distribution
+ * Status Topic With Error Reason.
+ *
+ * @param statusMessage
+ * @param errorReason
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage, String errorReason);
+
+ /**
+ * Build and publish Distribution Component Status event to Distribution
+ * Status Topic
+ *
+ * @param statusMessage
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage);
+
+ /**
+ * Build and publish Distribution Component Status event to Distribution
+ * Status Topic With Error Reason.
+ *
+ * @param statusMessage
+ * @param errorReason
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage, String errorReason);
+
+
+ /**
+ * Build and publish Distribution Final Status event to Distribution
+ * Status Topic
+ *
+ * @param statusMessage
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage);
+
+
+ /**
+ * Build and publish Distribution Final Status event to Distribution
+ * Status Topic With Error Reason.
+ *
+ * @param statusMessage
+ * @param errorReason
+ * @return IDistributionClientResult
+ */
+ IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, String errorReason);
+
+
+ /**
+ * This method parses artifact of type VF_MODULES_METADATA payload data
+ * .<br>
+ * Method is deprecated due to VF Module changes. Only backward
+ * compatibility is supported.<br>
+ *
+ * @param artifactPayload
+ * @return IVfModuleMetadata list
+ */
+ @Deprecated
+ List<IVfModuleMetadata> decodeVfModuleArtifact(byte[] artifactPayload);
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java
new file mode 100644
index 0000000..6db00fa
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/IDistributionStatusMessageJsonBuilder.java
@@ -0,0 +1,25 @@
+/*-
+ * ============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.api;
+
+public interface IDistributionStatusMessageJsonBuilder {
+ String build();
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java
new file mode 100644
index 0000000..6e64396
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/RegistrationRequest.java
@@ -0,0 +1,56 @@
+/*-
+ * ============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.api.asdc;
+
+import java.util.List;
+
+public class RegistrationRequest {
+
+ String apiPublicKey;
+ String distrEnvName;
+ Boolean isConsumerToSdcDistrStatusTopic;
+ List<String> distEnvEndPoints;
+
+ public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic, List<String> distEnvEndPoints) {
+ this.apiPublicKey = apiPublicKey;
+ this.distrEnvName = distrEnvName;
+ this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic;
+ this.distEnvEndPoints = distEnvEndPoints;
+ }
+
+ public String getApiPublicKey() {
+ return apiPublicKey;
+ }
+
+ public String getDistrEnvName() {
+ return distrEnvName;
+ }
+
+ public Boolean getIsConsumerToSdcDistrStatusTopic() {
+ return isConsumerToSdcDistrStatusTopic;
+ }
+
+ public List<String> getDistEnvEndPoints() {
+ return distEnvEndPoints;
+ }
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java
new file mode 100644
index 0000000..8d3b823
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java
@@ -0,0 +1,36 @@
+/*-
+ * ============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.api.asdc;
+
+import java.util.List;
+
+public class ServerListResponse {
+
+ private List<String> uebServerList;
+
+ public List<String> getUebServerList() {
+ return uebServerList;
+ }
+
+ public void setUebServerList(List<String> uebServerList) {
+ this.uebServerList = uebServerList;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java
new file mode 100644
index 0000000..e9b4359
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IComponentDoneStatusMessage.java
@@ -0,0 +1,7 @@
+package org.onap.sdc.api.consumer;
+
+public interface IComponentDoneStatusMessage extends IDistributionStatusMessageBasic {
+ String getComponentName();
+ default String getArtifactURL(){return "";}
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java
new file mode 100644
index 0000000..c5a1857
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IConfiguration.java
@@ -0,0 +1,157 @@
+/*-
+ * ============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.api.consumer;
+
+import java.util.List;
+import org.onap.sdc.api.notification.INotificationData;
+
+public interface IConfiguration {
+ /**
+ * SDC Distribution Engine address. Value can be either hostname (with or
+ * without port), IP:port or FQDN (Fully Qualified Domain Name). * @return
+ * SDC Distribution Engine address.
+ */
+ String getAsdcAddress();
+
+ /**SDC Distribution Addresses from ONAP Component
+ * Values need to be set from impl
+ */
+ List<String> getMsgBusAddress();
+
+ /**
+ * User Name for SDC distribution consumer authentication.
+ *
+ * @return User Name.
+ */
+ String getUser();
+
+ /**
+ * User Password for SDC distribution consumer authentication.
+ *
+ * @return User Password.
+ */
+ String getPassword();
+
+ /**
+ * Distribution Client Polling Interval towards UEB in seconds. Can Be
+ * reconfigured in runtime.
+ *
+ * @return Distribution Client Polling Interval.
+ */
+ int getPollingInterval();
+
+ /**
+ * Distribution Client Timeout in seconds waiting to UEB server response in
+ * each fetch interval. Can Be reconfigured in runtime.
+ *
+ * @return Distribution Client Timeout in seconds.
+ */
+ int getPollingTimeout();
+
+ /**
+ * List of artifact types.<br>
+ * If the service contains any of the artifacts in the list, the callback
+ * will be activated. Can Be reconfigured in runtime.
+ *
+ * @return List of artifact types.
+ */
+ List<String> getRelevantArtifactTypes();
+
+ /**
+ * Returns the consumer group defined for this ECOMP component, if no
+ * consumer group is defined return null.
+ *
+ * @return Consumer group.
+ */
+ String getConsumerGroup();
+
+ /**
+ * Returns the environment name (testing, production etc...). Can Be
+ * reconfigured in runtime.
+ *
+ * @return
+ */
+ String getEnvironmentName();
+
+ /**
+ * Unique ID of ECOMP component instance (e.x INSTAR name).
+ *
+ * @return
+ */
+ String getConsumerID();
+
+ /**
+ * Return full path to Client's Key Store that contains either CA
+ * certificate or the ASDC's public key (e.g /etc/keystore/asdc-client.jks)
+ * file will be deployed with sdc-distribution jar.
+ *
+ * @return
+ */
+ String getKeyStorePath();
+
+ /**
+ * @return Returns client's Key Store password
+ */
+ String getKeyStorePassword();
+
+ /**
+ * Sets whether SDC server TLS authentication is activated. If set to false,
+ * Key Store path and password are not needed to be set.
+ *
+ * @return
+ */
+ boolean activateServerTLSAuth();
+
+ /**
+ * If set to true the method {@link INotificationData#getResources()} will
+ * return all found resources.<br>
+ * That means that metadata of resources that do not contain relevant
+ * artifacts types (artifacts that are defined in
+ * {@link #getRelevantArtifactTypes()} will be returned.<br>
+ * Setting the method to false will activate the legacy behavior, in which
+ * empty resources are not part of the notification.<br>
+ *
+ * @return
+ */
+ boolean isFilterInEmptyResources();
+
+ /**
+ * By default, Distribution Client will use HTTPS (TLS 1.2) when connecting
+ * to DMAAP. This param can be null, then default (HTTPS) behavior will be
+ * applied. If set to false, distribution client will use HTTP when
+ * connecting to DMAAP.
+ *
+ * @return
+ */
+ Boolean isUseHttpsWithDmaap();
+
+ /**
+ * By default, (false value) Distribution Client will trigger the regular registration
+ * towards SDC (register component as consumer to the SDC-DISTR-NOTIF-TOPIC-[ENV] topic and register component as producer to the SDC-DISTR-STATUS-TOPIC-[ENV]).<br>
+ * If set to true, distribution client trigger Register to SDC indicating
+ * that this component request to be consumer and producer of the
+ * SDC-DISTR-STATUS-TOPIC-[ENV] topic.<br>
+ * @return
+ */
+ default boolean isConsumeProduceStatusTopic() {
+ return false;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java
new file mode 100644
index 0000000..fd73bac
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessage.java
@@ -0,0 +1,28 @@
+/*-
+ * ============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.api.consumer;
+
+public interface IDistributionStatusMessage extends IDistributionStatusMessageBasic{
+
+ /**Resource URL of the downloaded/deployed artifact - URL specified in the distribution notification message*/
+ String getArtifactURL();
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java
new file mode 100644
index 0000000..59dcc57
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IDistributionStatusMessageBasic.java
@@ -0,0 +1,28 @@
+package org.onap.sdc.api.consumer;
+
+import org.onap.sdc.utils.DistributionStatusEnum;
+
+public interface IDistributionStatusMessageBasic {
+ /**
+ * Distribution ID published in the distribution notification.<br>
+ * Should be used to link the distribution status reports to the appropriate
+ * distribution activation.<br>
+ * Global Distribution Identifier: UUID generated by SDC per each
+ * distribution activation.<br>
+ * Generated UUID is compliant with RFC 4122. It is a 128-bit value
+ * formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ String getDistributionID();
+
+ /**Unique ID of ONAP component instance (e.x INSTAR name)*/
+ String getConsumerID();
+
+ /**
+ * Timestamp of the distribution status report creation.<br>
+ * The number of seconds that have elapsed since January 1, 1970.
+ */
+ long getTimestamp();
+ /**Download/Deployment status*/
+ DistributionStatusEnum getStatus();
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java
new file mode 100644
index 0000000..0869a67
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IFinalDistrStatusMessage.java
@@ -0,0 +1,9 @@
+package org.onap.sdc.api.consumer;
+
+
+
+public interface IFinalDistrStatusMessage extends IDistributionStatusMessageBasic{
+
+ default String getConsumerID(){return "";}
+ default String getComponentName(){return "";}
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java
new file mode 100644
index 0000000..5121407
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/INotificationCallback.java
@@ -0,0 +1,29 @@
+/*-
+ * ============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.api.consumer;
+
+import org.onap.sdc.api.notification.INotificationData;
+/**When a relevant notification will be found activateCallback method will be activated with the notification data.<br>
+ * Please implement it according to your desired callback logic.*/
+public interface INotificationCallback {
+ void activateCallback(INotificationData data);
+}
+
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java
new file mode 100644
index 0000000..5bcc4a2
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/consumer/IStatusCallback.java
@@ -0,0 +1,35 @@
+/*-
+ * ============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.api.consumer;
+
+import org.onap.sdc.api.notification.IStatusData;
+
+/**
+ * When a relevant status will be found activateCallback method will be
+ * activated with the status data.<br>
+ * Please implement it according to your desired callback logic.
+ */
+@FunctionalInterface
+public interface IStatusCallback {
+ void activateCallback(IStatusData data);
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java
new file mode 100644
index 0000000..8c34185
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IArtifactInfo.java
@@ -0,0 +1,104 @@
+/*-
+ * ============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.api.notification;
+
+import java.util.List;
+
+
+public interface IArtifactInfo {
+
+ /**
+ * @return String of the Artifact File Name.
+ */
+ String getArtifactName();
+
+ /**
+ * Artifact Type.<br>
+ * Following are valid values : HEAT , DG_XML. <br>
+ * List of values will be extended in post-1510 releases.
+ *
+ * @return String of the artifact type.
+ */
+ String getArtifactType();
+
+ /**
+ * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br>
+ * The full artifact URL will be in the following format :<br>
+ * https://{serverBaseURL}/{resourcePath}<br>
+ * serverBaseURL - Hostname ( SDC LB FQDN) + optional port <br>
+ * resourcePath - "artifactURL" <br>
+ * Ex : https://sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml
+ *
+ * @return String of the Relative artifact's URL.
+ */
+ String getArtifactURL();
+
+ /**
+ * Base-64 encoded MD5 checksum of the artifact's payload.<br>
+ * Should be used for data integrity validation when an artifact's payload is downloaded.<br>
+ *
+ * @return String of the checksum of the artifact's payload.
+ */
+ String getArtifactChecksum();
+
+ /**
+ * Installation timeout in minutes.<br>
+ * Used by the Orchestrator to determine how much time to wait for a heat (or other deployment artifact)<br>
+ * This field is only relevant for artifacts of ArtifactTypeEnum HEAT, for other artifacts it will be null.<br>
+ * deployment process to finish.<br>
+ *
+ * @return String of the Installation timeout in minutes.
+ */
+ Integer getArtifactTimeout();
+
+ /**
+ * Artifact description
+ * @return
+ */
+ String getArtifactDescription();
+
+ /**
+ * Artifact Version
+ * @return
+ */
+ String getArtifactVersion();
+
+ /**
+ * Artifact Unique ID
+ * @return
+ */
+ String getArtifactUUID();
+
+
+ /**
+ * Returns the artifact it is generated from (relevant for heat_env), or null if there is no such artifact.
+ * @return
+ */
+ IArtifactInfo getGeneratedArtifact();
+
+ /**
+ * Returns the list of related artifacts (relevant for HEAT_NESTED or HEAT_ARTIFACT), or null if there is no such artifacts.
+ * @return
+ */
+ List<IArtifactInfo> getRelatedArtifacts();
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.java
new file mode 100644
index 0000000..ecc4a5b
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/INotificationData.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.api.notification;
+
+import java.util.List;
+
+
+
+
+
+public interface INotificationData {
+ /** Global Distribution Identifier: UUID generated by ASDC per each distribution activation.<br>
+ * Generated UUID is compliant with RFC 4122.<br>
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
+ Ex.: AA97B177-9383-4934-8543-0F91A7A02836 */
+ String getDistributionID();
+
+ /**Logical Service Name.*/
+ String getServiceName();
+
+ /** Service Version.<br>
+ * Two dot (".") separated digit blocks.<br>
+ Ex. : "2.0"*/
+ String getServiceVersion();
+
+ /**Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
+ It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
+ Ex. : AA97B177-9383-4934-8543-0F91A7A02836*/
+ String getServiceUUID();
+
+ /**
+ * Service description
+ */
+ String getServiceDescription();
+
+ /** List of the resource instances */
+ List<IResourceInstance> getResources();
+
+ /** List of Artifacts On Service Level */
+ List<IArtifactInfo> getServiceArtifacts();
+
+ /**This method allows getting details of the artifact by its uuid.*/
+ IArtifactInfo getArtifactMetadataByUUID(String artifactUUID);
+
+ /**
+ * Invariant UUID
+ */
+ String getServiceInvariantUUID();
+
+ String getWorkloadContext();
+
+ void setWorkloadContext(String workloadContext);
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java
new file mode 100644
index 0000000..0cc3ca4
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IResourceInstance.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * sdc-distribution-client
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.sdc.api.notification;
+
+import java.util.List;
+
+public interface IResourceInstance {
+ /**Logical Resource Instance Name. <br>
+ * Unique Identifier of the instance of the specific resource in the service context.**/
+ String getResourceInstanceName();
+
+ /**resource name */
+ String getResourceName();
+
+ /**resource version */
+ String getResourceVersion();
+
+ /**Resource Type (For Example: VF (Virtual Function) - A subsystem in a service, it can include one or more VFCs. This is what NFV spec refers as VNF.)**/
+ String getResourceType();
+
+ /**Global UUID of the resource that specific artifact belongs to.<br>
+ It is generated by SDC per each resource version.<br>
+ Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-"). <br>
+ Ex.: AA97B177-9383-4934-8543-0F91A7A02836**/
+ String getResourceUUID();
+
+ /**List of resource instance deployment artifacts.**/
+ List<IArtifactInfo> getArtifacts();
+
+ /**Invariant (constant) resource UUID generated on resource creation.**/
+ String getResourceInvariantUUID();
+
+ /**This UUID is unique in the context of the service.<br>
+ It is regenerated whenever a designer makes changes to the resource instance.<br>
+ A change may be updating HEAT value, updating property value or name of the resource instance.<br>
+ It is also regenerated when an artifact is uploaded to the resource instance.**/
+ String getResourceCustomizationUUID();
+
+ /**The category of the resource model.<br>
+ E.g. "Application L4+".**/
+ String getCategory();
+
+ /**The subcategory of the resource model.<br>
+ E.g. "Call Control"**/
+ String getSubcategory();
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java
new file mode 100644
index 0000000..734c200
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IStatusData.java
@@ -0,0 +1,65 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * sdc-distribution-client
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.sdc.api.notification;
+
+import org.onap.sdc.utils.DistributionStatusEnum;
+
+public interface IStatusData {
+ /**
+ * Global Distribution Identifier: UUID generated by SDC per each
+ * distribution activation.<br>
+ * Generated UUID is compliant with RFC 4122.<br>
+ * It is a 128-bit value formatted into blocks of hexadecimal digits
+ * separated by a hyphen ("-").<br>
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ String getDistributionID();
+
+ /** Unique ID of ONAP component instance (e.x INSTAR name). */
+ String getConsumerID();
+
+ /** The predefined ONAP component name configured on the component. */
+ String getComponentName();
+
+ /**
+ * Timestamp of the distribution status report creation. The number of
+ * seconds that have elapsed since January 1, 1970
+ */
+ Long getTimestamp();
+ /**
+ * Resource URL of the downloaded/deployed artifact - URL specified in the
+ * distribution notification message.
+ */
+ String getArtifactURL();
+ /**
+ * Status Event type
+ */
+ DistributionStatusEnum getStatus();
+ /**
+ * Error Reason describing the Status Event.
+ */
+ String getErrorReason();
+
+
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java
new file mode 100644
index 0000000..3613c94
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/notification/IVfModuleMetadata.java
@@ -0,0 +1,63 @@
+/*-
+ * ============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.api.notification;
+
+import java.util.List;
+/**VF Module in the resource (VF) context*/
+public interface IVfModuleMetadata {
+ /**Logical VF Module Name. Unique Identifier of VF Module in the resource (VF) context.<br>
+ Ex. : "PCRF-module-0"
+ */
+ String getVfModuleModelName();
+
+ /**Invariant VF Module UUID generated on VF Module creation according to RFC 4122 <br>
+ It is generated on service creation and stays invariant even if service name /version are updated.
+ */
+ String getVfModuleModelInvariantUUID();
+
+ /**
+ Resource Version . Ex. : "1"
+ */
+ String getVfModuleModelVersion();
+
+ /**Global UUID of the VF Module.<br>
+ It is generated by ASDC per each new VF module version. Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
+ Ex.: AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ String getVfModuleModelUUID();
+
+
+ /**
+ * VF Module textual description. Can be empty.
+ */
+ String getVfModuleModelDescription();
+
+
+ /**
+ * Is this VF module is the base module of the VF.
+ * */
+ boolean isBase();
+
+ /**
+ * Array of VF Module deployment artifacts UUID.
+ * */
+ List<String> getArtifacts();
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java
new file mode 100644
index 0000000..47fe023
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientDownloadResult.java
@@ -0,0 +1,45 @@
+/*-
+ * ============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.api.results;
+
+/**Distribution Client Result For Download API*/
+public interface IDistributionClientDownloadResult extends IDistributionClientResult{
+
+
+ byte[] getArtifactPayload();
+
+
+ /**
+ * @deprecated
+ * This method is deprecated and will be removed in 1710.
+ * It returns <b>attachment; filename="filename"</b> rather than <b>"filename"</b>.
+ * Please use {@link #getArtifactFilename()}.
+ * @return
+ */
+ @Deprecated
+ String getArtifactName();
+
+ /**
+ * Returns the filename of the artifact.
+ * @return the filename of the artifact.
+ */
+ String getArtifactFilename();
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java
new file mode 100644
index 0000000..4f33555
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/results/IDistributionClientResult.java
@@ -0,0 +1,28 @@
+/*-
+ * ============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.api.results;
+
+import org.onap.sdc.utils.DistributionActionResultEnum;
+/**General Distribution Client Result*/
+public interface IDistributionClientResult {
+ DistributionActionResultEnum getDistributionActionResult();
+ String getDistributionMessageResult();
+}
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;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java
new file mode 100644
index 0000000..6a3da83
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/ArtifactInfoImpl.java
@@ -0,0 +1,192 @@
+/*-
+ * ============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.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.sdc.api.notification.IArtifactInfo;
+
+class ArtifactInfoImpl implements IArtifactInfo {
+
+ private String artifactName;
+ private String artifactType;
+ private String artifactURL;
+ private String artifactChecksum;
+ private String artifactDescription;
+ private Integer artifactTimeout;
+ private String artifactVersion;
+ private String artifactUUID;
+ private String generatedFromUUID;
+ private IArtifactInfo generatedArtifact;
+ private List<String> relatedArtifacts;
+ private List<IArtifactInfo> relatedArtifactsInfo;
+ ArtifactInfoImpl(){}
+
+ private ArtifactInfoImpl(IArtifactInfo iArtifactInfo){
+ artifactName = iArtifactInfo.getArtifactName();
+ artifactType = iArtifactInfo.getArtifactType();
+ artifactURL = iArtifactInfo.getArtifactURL();
+ artifactChecksum = iArtifactInfo.getArtifactChecksum();
+ artifactDescription = iArtifactInfo.getArtifactDescription();
+ artifactTimeout = iArtifactInfo.getArtifactTimeout();
+ artifactVersion = iArtifactInfo.getArtifactVersion();
+ artifactUUID = iArtifactInfo.getArtifactUUID();
+ generatedArtifact = iArtifactInfo.getGeneratedArtifact();
+ relatedArtifactsInfo = iArtifactInfo.getRelatedArtifacts();
+ relatedArtifacts = fillRelatedArtifactsUUID(relatedArtifactsInfo);
+
+ }
+
+
+ private List<String> fillRelatedArtifactsUUID(List<IArtifactInfo> relatedArtifactsInfo) {
+ List<String> relatedArtifactsUUID = null;
+ if( relatedArtifactsInfo != null && !relatedArtifactsInfo.isEmpty()){
+ relatedArtifactsUUID = new ArrayList<>();
+ for(IArtifactInfo curr: relatedArtifactsInfo){
+ relatedArtifactsUUID.add(curr.getArtifactUUID());
+ }
+ }
+ return relatedArtifactsUUID;
+ }
+
+ public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(List<IArtifactInfo> list){
+ List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
+ if( list != null ){
+ for(IArtifactInfo artifactInfo : list ){
+ ret.add(new ArtifactInfoImpl(artifactInfo));
+ }
+ }
+ return ret;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getArtifactType() {
+ return artifactType;
+ }
+
+ public void setArtifactType(String artifactType) {
+ this.artifactType = artifactType;
+ }
+
+ public String getArtifactURL() {
+ return artifactURL;
+ }
+
+ public void setArtifactURL(String artifactURL) {
+ this.artifactURL = artifactURL;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getArtifactDescription() {
+ return artifactDescription;
+ }
+
+ public void setArtifactDescription(String artifactDescription) {
+ this.artifactDescription = artifactDescription;
+ }
+
+ public Integer getArtifactTimeout() {
+ return artifactTimeout;
+ }
+
+ public void setArtifactTimeout(Integer artifactTimeout) {
+ this.artifactTimeout = artifactTimeout;
+ }
+
+ @Override
+ public String toString() {
+ return "BaseArtifactInfoImpl [artifactName=" + artifactName
+ + ", artifactType=" + artifactType + ", artifactURL="
+ + artifactURL + ", artifactChecksum=" + artifactChecksum
+ + ", artifactDescription=" + artifactDescription
+ + ", artifactVersion=" + artifactVersion
+ + ", artifactUUID=" + artifactUUID
+ + ", artifactTimeout=" + artifactTimeout + "]";
+ }
+
+ public String getArtifactVersion() {
+ return artifactVersion;
+ }
+
+ public void setArtifactVersion(String artifactVersion) {
+ this.artifactVersion = artifactVersion;
+ }
+
+ public String getArtifactUUID() {
+ return artifactUUID;
+ }
+
+ public void setArtifactUUID(String artifactUUID) {
+ this.artifactUUID = artifactUUID;
+ }
+
+ public String getGeneratedFromUUID() {
+ return generatedFromUUID;
+ }
+
+ public void setGeneratedFromUUID(String generatedFromUUID) {
+ this.generatedFromUUID = generatedFromUUID;
+ }
+
+ public IArtifactInfo getGeneratedArtifact() {
+ return generatedArtifact;
+ }
+
+ public void setGeneratedArtifact(IArtifactInfo generatedArtifact) {
+ this.generatedArtifact = generatedArtifact;
+ }
+
+ public List<IArtifactInfo> getRelatedArtifacts(){
+ List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
+ if( relatedArtifactsInfo != null ){
+ temp.addAll(relatedArtifactsInfo);
+ }
+ return temp;
+ }
+
+ public void setRelatedArtifacts(List<String> relatedArtifacts) {
+ this.relatedArtifacts = relatedArtifacts;
+ }
+
+ public void setRelatedArtifactsInfo(List<IArtifactInfo> relatedArtifactsInfo) {
+ this.relatedArtifactsInfo = relatedArtifactsInfo;
+ }
+
+ public List<String> getRelatedArtifactsUUID(){
+ return relatedArtifacts;
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java
new file mode 100644
index 0000000..a33f911
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/Configuration.java
@@ -0,0 +1,225 @@
+/*-
+ * ============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.impl;
+
+import java.util.List;
+
+import org.onap.sdc.utils.DistributionClientConstants;
+import org.onap.sdc.api.consumer.IConfiguration;
+
+public class Configuration implements IConfiguration {
+
+ private List<String> msgBusAddressList;
+ private String asdcAddress;
+ private String user;
+ private String password;
+ private int pollingInterval = DistributionClientConstants.MIN_POLLING_INTERVAL_SEC;
+ private int pollingTimeout = DistributionClientConstants.POLLING_TIMEOUT_SEC;
+ private List<String> relevantArtifactTypes;
+ private String consumerGroup;
+ private String environmentName;
+ private String comsumerID;
+ private String keyStorePath;
+ private String keyStorePassword;
+ private boolean activateServerTLSAuth;
+ private boolean filterInEmptyResources;
+ private Boolean useHttpsWithDmaap;
+ private boolean consumeProduceStatusTopic;
+
+ public Configuration(IConfiguration other) {
+ this.asdcAddress = other.getAsdcAddress();
+ this.msgBusAddressList = other.getMsgBusAddress();
+ this.comsumerID = other.getConsumerID();
+ this.consumerGroup = other.getConsumerGroup();
+ this.environmentName = other.getEnvironmentName();
+ this.password = other.getPassword();
+ this.pollingInterval = other.getPollingInterval();
+ this.pollingTimeout = other.getPollingTimeout();
+ this.relevantArtifactTypes = other.getRelevantArtifactTypes();
+ this.user = other.getUser();
+ this.keyStorePath = other.getKeyStorePath();
+ this.keyStorePassword = other.getKeyStorePassword();
+ this.activateServerTLSAuth = other.activateServerTLSAuth();
+ this.filterInEmptyResources = other.isFilterInEmptyResources();
+ this.useHttpsWithDmaap = other.isUseHttpsWithDmaap();
+ this.consumeProduceStatusTopic = other.isConsumeProduceStatusTopic();
+ }
+
+ @Override
+ public String getAsdcAddress() {
+ return asdcAddress;
+ }
+
+ @Override
+ public List<String> getMsgBusAddress() {
+ return msgBusAddressList;
+ }
+
+ @Override
+ public String getUser() {
+ return user;
+ }
+
+ @Override
+ public String getPassword() {
+ return password;
+ }
+
+ @Override
+ public int getPollingInterval() {
+ return pollingInterval;
+ }
+
+ @Override
+ public int getPollingTimeout() {
+ return pollingTimeout;
+ }
+
+ @Override
+ public List<String> getRelevantArtifactTypes() {
+ return relevantArtifactTypes;
+ }
+
+ @Override
+ public String getConsumerGroup() {
+ return consumerGroup;
+ }
+
+ @Override
+ public String getEnvironmentName() {
+ return environmentName;
+ }
+
+ @Override
+ public String getConsumerID() {
+ return comsumerID;
+ }
+
+ @Override
+ public String getKeyStorePath() {
+ return keyStorePath;
+ }
+
+ @Override
+ public String getKeyStorePassword() {
+ return keyStorePassword;
+ }
+
+ public String getComsumerID() {
+ return comsumerID;
+ }
+
+ public void setComsumerID(String comsumerID) {
+ this.comsumerID = comsumerID;
+ }
+
+ public void setAsdcAddress(String asdcAddress) {
+ this.asdcAddress = asdcAddress;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public void setPollingInterval(int pollingInterval) {
+ this.pollingInterval = pollingInterval;
+ }
+
+ public void setPollingTimeout(int pollingTimeout) {
+ this.pollingTimeout = pollingTimeout;
+ }
+
+ public void setRelevantArtifactTypes(List<String> relevantArtifactTypes) {
+ this.relevantArtifactTypes = relevantArtifactTypes;
+ }
+
+ public void setConsumerGroup(String consumerGroup) {
+ this.consumerGroup = consumerGroup;
+ }
+
+ public void setEnvironmentName(String environmentName) {
+ this.environmentName = environmentName;
+ }
+
+ public void setKeyStorePath(String keyStorePath) {
+ this.keyStorePath = keyStorePath;
+ }
+
+ public void setKeyStorePassword(String keyStorePassword) {
+ this.keyStorePassword = keyStorePassword;
+ }
+
+ public void setactivateServerTLSAuth(boolean activateServerTLSAuth) {
+ this.activateServerTLSAuth = activateServerTLSAuth;
+ }
+
+ @Override
+ public boolean activateServerTLSAuth() {
+ return this.activateServerTLSAuth;
+ }
+
+ @Override
+ public boolean isFilterInEmptyResources() {
+ return this.filterInEmptyResources;
+ }
+
+ @Override
+ public Boolean isUseHttpsWithDmaap() {
+ return this.useHttpsWithDmaap;
+ }
+
+ public void setUseHttpsWithDmaap(boolean useHttpsWithDmaap) {
+ this.useHttpsWithDmaap = useHttpsWithDmaap;
+ }
+
+ @Override
+ public boolean isConsumeProduceStatusTopic() {
+ return this.consumeProduceStatusTopic;
+ }
+
+ @Override
+ public String toString() {
+ //@formatter:off
+ return "Configuration ["+
+ "asdcAddress=" + asdcAddress +
+ ", user=" + user +
+ ", password=" + password +
+ ", pollingInterval=" + pollingInterval +
+ ", pollingTimeout=" + pollingTimeout +
+ ", relevantArtifactTypes=" + relevantArtifactTypes +
+ ", consumerGroup=" + consumerGroup +
+ ", environmentName=" + environmentName +
+ ", comsumerID=" + comsumerID +
+ ", keyStorePath=" + keyStorePath +
+ ", keyStorePassword=" + keyStorePassword +
+ ", activateServerTLSAuth=" + activateServerTLSAuth +
+ ", filterInEmptyResources=" + filterInEmptyResources +
+ ", useHttpsWithDmaap=" + useHttpsWithDmaap +
+ ", consumeProduceStatusTopic=" + consumeProduceStatusTopic +
+ "]";
+ //@formatter:on
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java
new file mode 100644
index 0000000..6323113
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientDownloadResultImpl.java
@@ -0,0 +1,74 @@
+/*-
+ * ============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.impl;
+
+import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+
+public class DistributionClientDownloadResultImpl extends DistributionClientResultImpl implements IDistributionClientDownloadResult {
+ byte[] artifactPayload;
+ String artifactName;
+
+
+ public DistributionClientDownloadResultImpl(
+ DistributionActionResultEnum responseStatus, String responseMessage) {
+ super(responseStatus, responseMessage);
+
+ }
+
+ public DistributionClientDownloadResultImpl(
+ DistributionActionResultEnum responseStatus,
+ String responseMessage, String artifactName, byte[] artifactPayload) {
+ super(responseStatus, responseMessage);
+ this.artifactPayload = artifactPayload;
+ this.artifactName = artifactName;
+ }
+
+
+ public void setArtifactPayload(byte[] payload) {
+ this.artifactPayload = payload;
+ }
+
+
+ public byte[] getArtifactPayload() {
+
+ return artifactPayload;
+ }
+
+ public String getArtifactName(){
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName){
+ this.artifactName = artifactName;
+ }
+
+ @Override
+ public String getArtifactFilename() {
+ //Fix of bug 292443 in TDP
+ if (artifactName == null || !artifactName.matches("attachment;\\s*filename=\".*?\"")){
+ return artifactName;
+ }
+ String fileName = "filename=\"";
+ return artifactName.substring(artifactName.indexOf(fileName)+fileName.length(), artifactName.lastIndexOf("\""));
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java
new file mode 100644
index 0000000..96aabc2
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientFactory.java
@@ -0,0 +1,34 @@
+/*-
+ * ============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.impl;
+
+import org.onap.sdc.api.IDistributionClient;
+import org.onap.sdc.impl.mock.DistributionClientStubImpl;
+
+public class DistributionClientFactory {
+ public static IDistributionClient createDistributionClient(){
+ return new DistributionClientImpl();
+ }
+
+ public static IDistributionClient createMockDistributionClient(){
+ return new DistributionClientStubImpl();
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java
new file mode 100644
index 0000000..5d15046
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientImpl.java
@@ -0,0 +1,779 @@
+/*-
+ * ============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.impl;
+
+import static java.util.Objects.isNull;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.net.MalformedURLException;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+
+import org.onap.sdc.api.IDistributionClient;
+import org.onap.sdc.api.IDistributionStatusMessageJsonBuilder;
+import org.onap.sdc.api.consumer.*;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.http.SdcConnectorClient;
+import org.onap.sdc.http.TopicRegistrationResponse;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+import org.onap.sdc.utils.DistributionClientConstants;
+import org.onap.sdc.utils.GeneralUtils;
+import org.onap.sdc.utils.Wrapper;
+import org.onap.sdc.api.consumer.*;
+import org.onap.sdc.api.notification.IVfModuleMetadata;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.att.nsa.apiClient.credentials.ApiCredential;
+import com.att.nsa.apiClient.http.HttpException;
+import com.att.nsa.cambria.client.CambriaBatchingPublisher;
+import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
+import com.att.nsa.cambria.client.CambriaClientBuilders.AbstractAuthenticatedManagerBuilder;
+import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder;
+import com.att.nsa.cambria.client.CambriaClientBuilders.IdentityManagerBuilder;
+import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
+import com.att.nsa.cambria.client.CambriaConsumer;
+import com.att.nsa.cambria.client.CambriaIdentityManager;
+import com.att.nsa.cambria.client.CambriaPublisher.message;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+
+import fj.data.Either;
+
+public class DistributionClientImpl implements IDistributionClient {
+
+ private static Logger log = LoggerFactory.getLogger(DistributionClientImpl.class.getName());
+
+ protected SdcConnectorClient asdcConnector = new SdcConnectorClient();
+ private ScheduledExecutorService executorPool = null;
+ protected CambriaIdentityManager cambriaIdentityManager = null;
+ private List<String> brokerServers;
+ protected ApiCredential credential;
+ protected Configuration configuration;
+ private INotificationCallback callback;
+ private IStatusCallback statusCallback;
+ private String notificationTopic;
+ private String statusTopic;
+ private boolean isConsumerGroupGenerated = false;
+
+ private boolean isInitialized, isStarted, isTerminated;
+
+ @Override
+ public IConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ @Override
+ /* see javadoc */
+ public synchronized IDistributionClientResult updateConfiguration(IConfiguration conf) {
+
+ log.info("update DistributionClient configuration");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+
+ IDistributionClientResult updateResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "configuration updated successfuly");
+
+ boolean needToUpdateCambriaConsumer = false;
+
+ if (conf.getRelevantArtifactTypes() != null && !conf.getRelevantArtifactTypes().isEmpty()) {
+ configuration.setRelevantArtifactTypes(conf.getRelevantArtifactTypes());
+ needToUpdateCambriaConsumer = true;
+ }
+ if (isPollingIntervalValid(conf.getPollingInterval())) {
+ configuration.setPollingInterval(conf.getPollingInterval());
+ needToUpdateCambriaConsumer = true;
+ }
+ if (isPollingTimeoutValid(conf.getPollingTimeout())) {
+ configuration.setPollingTimeout(conf.getPollingTimeout());
+ needToUpdateCambriaConsumer = true;
+ }
+ if (conf.getConsumerGroup() != null) {
+ configuration.setConsumerGroup(conf.getConsumerGroup());
+ isConsumerGroupGenerated = false;
+ needToUpdateCambriaConsumer = true;
+ } else if (!isConsumerGroupGenerated) {
+ generateConsumerGroup();
+ }
+
+ if (needToUpdateCambriaConsumer) {
+ updateResult = restartConsumer();
+ }
+
+ return updateResult;
+ }
+
+ @Override
+ /**
+ * Start polling the Notification topic
+ */
+ public synchronized IDistributionClientResult start() {
+
+ log.info("start DistributionClient");
+ IDistributionClientResult startResult;
+ CambriaConsumer cambriaNotificationConsumer = null;
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ validateNotStarted(errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ try {
+ cambriaNotificationConsumer = new ConsumerBuilder().authenticatedBy(credential.getApiKey(), credential.getApiSecret()).knownAs(configuration.getConsumerGroup(), configuration.getConsumerID()).onTopic(notificationTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers)
+ .withSocketTimeout(configuration.getPollingTimeout() * 1000).build();
+
+ } catch (MalformedURLException | GeneralSecurityException e) {
+ handleCambriaInitFailure(errorWrapper, e);
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+
+ List<String> relevantArtifactTypes = configuration.getRelevantArtifactTypes();
+ // Remove nulls from list - workaround for how configuration is built
+ while (relevantArtifactTypes.remove(null));
+
+ NotificationConsumer consumer = new NotificationConsumer(cambriaNotificationConsumer, callback, relevantArtifactTypes, this);
+ executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE);
+ executorPool.scheduleAtFixedRate(consumer, 0, configuration.getPollingInterval(), TimeUnit.SECONDS);
+
+ handleStatusConsumer(errorWrapper, executorPool);
+ }
+ if (!errorWrapper.isEmpty()) {
+ startResult = errorWrapper.getInnerElement();
+ }
+ else{
+ startResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client started successfuly");
+ isStarted = true;
+ }
+ return startResult;
+ }
+
+ private void handleStatusConsumer(Wrapper<IDistributionClientResult> errorWrapper, ScheduledExecutorService executorPool) {
+ if( configuration.isConsumeProduceStatusTopic()){
+ CambriaConsumer cambriaStatusConsumer = null;
+ try {
+ cambriaStatusConsumer = new ConsumerBuilder().authenticatedBy(credential.getApiKey(), credential.getApiSecret()).knownAs(configuration.getConsumerGroup(), configuration.getConsumerID()).onTopic(statusTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers)
+ .withSocketTimeout(configuration.getPollingTimeout() * 1000).build();
+ StatusConsumer statusConsumer = new StatusConsumer(cambriaStatusConsumer, statusCallback);
+ executorPool.scheduleAtFixedRate(statusConsumer, 0, configuration.getPollingInterval(), TimeUnit.SECONDS);
+ } catch (MalformedURLException | GeneralSecurityException e) {
+ handleCambriaInitFailure(errorWrapper, e);
+ }
+ }
+ }
+
+ @Override
+ /* see javadoc */
+ public synchronized IDistributionClientResult stop() {
+
+ log.info("stop DistributionClient");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ // 1. stop polling notification topic
+ shutdownExecutor();
+
+ // 2. send to ASDC unregister to topic
+ IDistributionClientResult unregisterResult = asdcConnector.unregisterTopics(credential);
+ if (unregisterResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ log.info("client failed to unregister from topics");
+ } else {
+ log.info("client unregistered from topics successfully");
+ }
+ asdcConnector.close();
+
+ try {
+ cambriaIdentityManager.deleteCurrentApiKey();
+ } catch (HttpException | IOException e) {
+ log.debug("failed to delete cambria keys", e);
+ }
+ cambriaIdentityManager.close();
+
+ isInitialized = false;
+ isTerminated = true;
+
+ DistributionClientResultImpl stopResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client stopped successfuly");
+ return stopResult;
+ }
+
+ @Override
+ public IDistributionClientDownloadResult download(IArtifactInfo artifactInfo) {
+ log.info("DistributionClient - download");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ IDistributionClientResult result = errorWrapper.getInnerElement();
+ IDistributionClientDownloadResult downloadResult = new DistributionClientDownloadResultImpl(result.getDistributionActionResult(), result.getDistributionMessageResult());
+ return downloadResult;
+ }
+ return asdcConnector.dowloadArtifact(artifactInfo);
+ }
+ @Override
+ public synchronized IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback,
+ IStatusCallback statusCallback) {
+ IDistributionClientResult initResult;
+ if( !conf.isConsumeProduceStatusTopic() ){
+ initResult = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, "configuration is invalid: isConsumeProduceStatusTopic() should be set to 'true'" );
+
+ }
+ else if( isNull(statusCallback) ){
+ initResult = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG, "configuration is invalid: statusCallback is not defined" );
+ }
+ else{
+ this.statusCallback = statusCallback;
+ initResult = init(conf, notificationCallback);
+ }
+ return initResult;
+ }
+
+ @Override
+ /*
+ * see javadoc
+ */
+ public synchronized IDistributionClientResult init(IConfiguration conf, INotificationCallback callback) {
+
+ log.info("DistributionClient - init");
+
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateNotInitilized(errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ validateNotTerminated(errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ validateAndInitConfiguration(errorWrapper, conf);
+ }
+ // 1. get ueb server list from configuration
+ if (errorWrapper.isEmpty()) {
+ initUebServerList(errorWrapper);
+ }
+ // 2.validate artifact types against asdc server
+ if (errorWrapper.isEmpty()) {
+ validateArtifactTypesWithAsdcServer(conf, errorWrapper);
+ }
+ // 3. create keys
+ if (errorWrapper.isEmpty()) {
+ this.callback = callback;
+ createUebKeys(errorWrapper);
+ }
+ // 4. register for topics
+ if (errorWrapper.isEmpty()) {
+ registerForTopics(errorWrapper);
+ }
+
+ IDistributionClientResult result;
+ if (errorWrapper.isEmpty()) {
+ isInitialized = true;
+ result = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "distribution client initialized successfuly");
+ } else {
+ result = errorWrapper.getInnerElement();
+ }
+
+ return result;
+ }
+
+ private void registerForTopics(Wrapper<IDistributionClientResult> errorWrapper) {
+ Either<TopicRegistrationResponse, DistributionClientResultImpl> registerAsdcTopics = asdcConnector.registerAsdcTopics(credential);
+ if (registerAsdcTopics.isRight()) {
+
+ try {
+ cambriaIdentityManager.deleteCurrentApiKey();
+ } catch (HttpException | IOException e) {
+ log.debug("failed to delete cambria keys", e);
+ }
+ errorWrapper.setInnerElement(registerAsdcTopics.right().value());
+ } else {
+ TopicRegistrationResponse topics = registerAsdcTopics.left().value();
+ notificationTopic = topics.getDistrNotificationTopicName();
+ statusTopic = topics.getDistrStatusTopicName();
+ }
+
+ }
+
+ private void createUebKeys(Wrapper<IDistributionClientResult> errorWrapper) {
+ initCambriaClient(errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ log.debug("create keys");
+ DistributionClientResultImpl createKeysResponse = createUebKeys();
+ if (createKeysResponse.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ errorWrapper.setInnerElement(createKeysResponse);
+ }
+ }
+ }
+
+ private void validateArtifactTypesWithAsdcServer(IConfiguration conf, Wrapper<IDistributionClientResult> errorWrapper) {
+ asdcConnector.init(configuration);
+ Either<List<String>, IDistributionClientResult> eitherValidArtifactTypesList = asdcConnector.getValidArtifactTypesList();
+ if (eitherValidArtifactTypesList.isRight()) {
+ DistributionActionResultEnum errorType = eitherValidArtifactTypesList.right().value().getDistributionActionResult();
+ // Support the case of a new client and older ASDC Server which does not have the API
+ if (errorType != DistributionActionResultEnum.ASDC_NOT_FOUND) {
+ errorWrapper.setInnerElement(eitherValidArtifactTypesList.right().value());
+ }
+ } else {
+ final List<String> artifactTypesFromAsdc = eitherValidArtifactTypesList.left().value();
+ boolean isArtifactTypesValid = artifactTypesFromAsdc.containsAll(conf.getRelevantArtifactTypes());
+ if (!isArtifactTypesValid) {
+ List<String> invalidArtifactTypes = new ArrayList<>();
+ invalidArtifactTypes.addAll(conf.getRelevantArtifactTypes());
+ invalidArtifactTypes.removeAll(artifactTypesFromAsdc);
+ DistributionClientResultImpl errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.CONF_CONTAINS_INVALID_ARTIFACT_TYPES,
+ "configuration contains invalid artifact types:" + invalidArtifactTypes + " valid types are:" + artifactTypesFromAsdc);
+ errorWrapper.setInnerElement(errorResponse);
+ } else {
+ log.debug("Artifact types: {} were validated with ASDC server", conf.getRelevantArtifactTypes());
+ }
+ }
+ }
+
+ private void initUebServerList(Wrapper<IDistributionClientResult> errorWrapper) {
+ log.debug("get ueb cluster server list from component(configuration file)");
+
+ Either<List<String>, IDistributionClientResult> serverListResponse = getUEBServerList();
+ if (serverListResponse.isRight()) {
+ errorWrapper.setInnerElement(serverListResponse.right().value());
+ } else {
+
+ brokerServers = serverListResponse.left().value();
+ }
+
+ }
+
+ private void validateNotInitilized(Wrapper<IDistributionClientResult> errorWrapper) {
+ if (isInitialized) {
+ log.warn("distribution client already initialized");
+ DistributionClientResultImpl alreadyInitResponse = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, "distribution client already initialized");
+ errorWrapper.setInnerElement(alreadyInitResponse);
+ }
+ }
+
+ @Override
+ public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage) {
+ log.info("DistributionClient - sendDownloadStatus");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage));
+ }
+
+ private IDistributionClientResult sendStatus(IDistributionStatusMessageJsonBuilder builder) {
+ DistributionClientResultImpl statusResult = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Failed to send status");
+ log.info("DistributionClient - sendStatus");
+ Either<CambriaBatchingPublisher, IDistributionClientResult> eitherPublisher = getCambriaPublisher();
+ if (eitherPublisher.isRight()) {
+ return eitherPublisher.right().value();
+ }
+ CambriaBatchingPublisher pub = eitherPublisher.left().value();
+
+ log.debug("after create publisher server list " + brokerServers.toString());
+ String jsonRequest = builder.build();
+
+ log.debug("try to send status " + jsonRequest);
+
+ try {
+ pub.send("MyPartitionKey", jsonRequest);
+ Thread.sleep(1000L);
+ } catch (IOException e) {
+ log.debug("DistributionClient - sendDownloadStatus. Failed to send download status");
+ } catch (InterruptedException e) {
+ log.debug("DistributionClient - sendDownloadStatus. thread was interrupted");
+ }
+
+ finally {
+
+ try {
+ List<message> stuck = pub.close(10L, TimeUnit.SECONDS);
+
+ if (!stuck.isEmpty()) {
+ log.debug("DistributionClient - sendDownloadStatus. " + stuck.size() + " messages unsent");
+ } else {
+ statusResult = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "messages successfully sent");
+ }
+ } catch (IOException | InterruptedException e) {
+ log.debug("DistributionClient - sendDownloadStatus. failed to send messages and close publisher ");
+ }
+
+ }
+ return statusResult;
+ }
+
+ private Either<CambriaBatchingPublisher, IDistributionClientResult> getCambriaPublisher() {
+ CambriaBatchingPublisher cambriaPublisher = null;
+ try {
+ cambriaPublisher = new PublisherBuilder().onTopic(statusTopic).usingHttps(configuration.isUseHttpsWithDmaap()).usingHosts(brokerServers).build();
+ cambriaPublisher.setApiCredentials(credential.getApiKey(), credential.getApiSecret());
+ } catch (MalformedURLException | GeneralSecurityException e) {
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ handleCambriaInitFailure(errorWrapper, e);
+ return Either.right(errorWrapper.getInnerElement());
+ }
+ return Either.left(cambriaPublisher);
+ }
+
+ @Override
+ public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage) {
+ log.info("DistributionClient - sendDeploymentStatus");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage));
+ }
+
+ IDistributionClientResult sendNotificationStatus(long currentTimeMillis, String distributionId, ArtifactInfoImpl artifactInfo, boolean isNotified) {
+ log.info("DistributionClient - sendNotificationStatus");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.prepareBuilderForNotificationStatus(getConfiguration().getConsumerID(), currentTimeMillis, distributionId, artifactInfo, isNotified));
+ }
+
+ /* *************************** Private Methods *************************************************** */
+
+ protected DistributionClientResultImpl createUebKeys() {
+ DistributionClientResultImpl response = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "keys created successfuly");
+ try {
+ String description = String.format(DistributionClientConstants.CLIENT_DESCRIPTION, configuration.getConsumerID());
+ credential = cambriaIdentityManager.createApiKey(DistributionClientConstants.EMAIL, description);
+ cambriaIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret());
+
+ } catch (HttpException | CambriaApiException | IOException e) {
+ response = new DistributionClientResultImpl(DistributionActionResultEnum.UEB_KEYS_CREATION_FAILED, "failed to create keys: " + e.getMessage());
+ log.error(response.toString());
+ }
+ return response;
+ }
+
+ private IDistributionClientResult restartConsumer() {
+ shutdownExecutor();
+ return start();
+ }
+
+ protected DistributionActionResultEnum validateAndInitConfiguration(Wrapper<IDistributionClientResult> errorWrapper, IConfiguration conf) {
+ DistributionActionResultEnum result = DistributionActionResultEnum.SUCCESS;
+
+ if (conf == null) {
+ result = DistributionActionResultEnum.CONFIGURATION_IS_MISSING;
+ } else if (conf.getConsumerID() == null || conf.getConsumerID().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID;
+ } else if (conf.getUser() == null || conf.getUser().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_USERNAME;
+ } else if (conf.getPassword() == null || conf.getPassword().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_PASSWORD;
+ } else if (conf.getMsgBusAddress() == null || conf.getMsgBusAddress().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_MSG_BUS_ADDRESS;
+ } else if (conf.getAsdcAddress() == null || conf.getAsdcAddress().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN;
+ } else if (!isValidFqdn(conf.getAsdcAddress())) {
+ result = DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN;
+ } else if (!isValidFqdns(conf.getMsgBusAddress())){
+ result = DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS;
+ } else if (conf.getEnvironmentName() == null || conf.getEnvironmentName().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME;
+ } else if (conf.getRelevantArtifactTypes() == null || conf.getRelevantArtifactTypes().isEmpty()) {
+ result = DistributionActionResultEnum.CONF_MISSING_ARTIFACT_TYPES;
+ }
+ else if( conf.isConsumeProduceStatusTopic() && Objects.isNull(statusCallback) ){
+ result = DistributionActionResultEnum.CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG;
+ }
+ // DistributionActionResultEnum.SUCCESS
+ else {
+ handleValidConf(conf);
+ }
+
+ if (result != DistributionActionResultEnum.SUCCESS) {
+
+ DistributionClientResultImpl initResult = new DistributionClientResultImpl(result, "configuration is invalid: " + result.name());
+
+ log.error(initResult.toString());
+ errorWrapper.setInnerElement(initResult);
+ }
+ return result;
+ }
+
+ private void handleValidConf(IConfiguration conf) {
+ this.configuration = new Configuration(conf);
+ if (!isPollingIntervalValid(conf.getPollingInterval())) {
+ configuration.setPollingInterval(DistributionClientConstants.MIN_POLLING_INTERVAL_SEC);
+ }
+ if (!isPollingTimeoutValid(conf.getPollingTimeout())) {
+ configuration.setPollingTimeout(DistributionClientConstants.POLLING_TIMEOUT_SEC);
+ }
+ if (conf.getConsumerGroup() == null) {
+ generateConsumerGroup();
+ }
+
+ //Default use HTTPS with DMAAP
+ if (conf.isUseHttpsWithDmaap() == null){
+ configuration.setUseHttpsWithDmaap(true);
+ }
+ }
+
+ private void generateConsumerGroup() {
+ String generatedConsumerGroup = UUID.randomUUID().toString();
+ configuration.setConsumerGroup(generatedConsumerGroup);
+ isConsumerGroupGenerated = true;
+ }
+
+ protected boolean isValidFqdn(String fqdn) {
+ try {
+ Matcher matcher = DistributionClientConstants.FQDN_PATTERN.matcher(fqdn);
+ return matcher.matches();
+ } catch (Exception e) {
+ }
+ return false;
+ }
+ protected boolean isValidFqdns(List<String> fqdns) {
+ if (fqdns != null && !fqdns.isEmpty()) {
+ for (String fqdn : fqdns) {
+ if (isValidFqdn(fqdn)) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private void shutdownExecutor() {
+ if (executorPool == null)
+ return;
+
+ executorPool.shutdown(); // Disable new tasks from being submitted
+ try {
+ // Wait a while for existing tasks to terminate
+ if (!executorPool.awaitTermination(60, TimeUnit.SECONDS)) {
+ executorPool.shutdownNow(); // Cancel currently executing tasks
+ // Wait a while for tasks to respond to being cancelled
+ if (!executorPool.awaitTermination(60, TimeUnit.SECONDS))
+ log.error("Pool did not terminate");
+ }
+ } catch (InterruptedException ie) {
+ // (Re-)Cancel if current thread also interrupted
+ executorPool.shutdownNow();
+ // Preserve interrupt status
+ Thread.currentThread().interrupt();
+ } finally {
+ isStarted = false;
+ }
+ }
+
+ private void validateRunReady(Wrapper<IDistributionClientResult> errorWrapper) {
+ if (errorWrapper.isEmpty()) {
+ validateInitilized(errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ validateNotTerminated(errorWrapper);
+ }
+
+ }
+
+ private void validateInitilized(Wrapper<IDistributionClientResult> errorWrapper) {
+ if (!isInitialized) {
+ log.debug("client was not initialized");
+ IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED, "distribution client was not initialized");
+ errorWrapper.setInnerElement(result);
+ }
+ }
+
+ private void validateNotStarted(Wrapper<IDistributionClientResult> errorWrapper) {
+ if (isStarted) {
+ log.debug("client already started");
+ IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_STARTED, "distribution client already started");
+ errorWrapper.setInnerElement(result);
+ }
+ }
+
+ private void validateNotTerminated(Wrapper<IDistributionClientResult> errorWrapper) {
+ if (isTerminated) {
+ log.debug("client was terminated");
+ IDistributionClientResult result = new DistributionClientResultImpl(DistributionActionResultEnum.DISTRIBUTION_CLIENT_IS_TERMINATED, "distribution client was terminated");
+ errorWrapper.setInnerElement(result);
+ }
+ }
+
+ private boolean isPollingTimeoutValid(int timeout) {
+ boolean isValid = (timeout >= DistributionClientConstants.POLLING_TIMEOUT_SEC);
+ if (!isValid) {
+ log.warn("polling interval is out of range. value should be greater than or equals to " + DistributionClientConstants.POLLING_TIMEOUT_SEC);
+ log.warn("setting polling interval to default: " + DistributionClientConstants.POLLING_TIMEOUT_SEC);
+ }
+ return isValid;
+ }
+
+ private boolean isPollingIntervalValid(int pollingInt) {
+ boolean isValid = (pollingInt >= DistributionClientConstants.MIN_POLLING_INTERVAL_SEC);
+ if (!isValid) {
+ log.warn("polling interval is out of range. value should be greater than or equals to " + DistributionClientConstants.MIN_POLLING_INTERVAL_SEC);
+ log.warn("setting polling interval to default: " + DistributionClientConstants.MIN_POLLING_INTERVAL_SEC);
+ }
+ return isValid;
+ }
+
+ private synchronized void initCambriaClient(Wrapper<IDistributionClientResult> errorWrapper) {
+ if (cambriaIdentityManager == null) {
+ try {
+ AbstractAuthenticatedManagerBuilder<CambriaIdentityManager> managerBuilder = new IdentityManagerBuilder().usingHosts(brokerServers);
+ if (configuration.isUseHttpsWithDmaap()){
+ managerBuilder = managerBuilder.usingHttps();
+ }
+ cambriaIdentityManager = managerBuilder.build();
+ } catch (MalformedURLException | GeneralSecurityException e) {
+ handleCambriaInitFailure(errorWrapper, e);
+ }
+ }
+ }
+
+ private void handleCambriaInitFailure(Wrapper<IDistributionClientResult> errorWrapper, Exception e) {
+ final String errorMessage = "Failed initilizing cambria component:" + e.getMessage();
+ IDistributionClientResult errorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.CAMBRIA_INIT_FAILED, errorMessage);
+ errorWrapper.setInnerElement(errorResponse);
+ log.error(errorMessage);
+ log.debug(errorMessage, e);
+ }
+
+ @Override
+ public IDistributionClientResult sendDownloadStatus(IDistributionStatusMessage statusMessage, String errorReason) {
+ log.info("DistributionClient - sendDownloadStatus with errorReason");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason));
+
+ }
+
+ @Override
+ public IDistributionClientResult sendDeploymentStatus(IDistributionStatusMessage statusMessage, String errorReason) {
+ log.info("DistributionClient - sendDeploymentStatus with errorReason");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason));
+
+ }
+
+ @Override
+ public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage) {
+ log.info("DistributionClient - sendComponentDone status");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage));
+
+ }
+
+ @Override
+ public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage,
+ String errorReason) {
+ log.info("DistributionClient - sendComponentDone status with errorReason");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason));
+ }
+
+
+ @Override
+ public List<IVfModuleMetadata> decodeVfModuleArtifact(byte[] artifactPayload) {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ String vfModuleJsonString = new String(artifactPayload, StandardCharsets.UTF_8);
+ final Type type = new TypeToken<List<VfModuleMetadata>>() {
+ }.getType();
+ List<IVfModuleMetadata> vfModules = gson.fromJson(vfModuleJsonString, type);
+ return vfModules;
+ }
+
+
+ public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage) {
+ log.info("DistributionClient - sendFinalDistributionStatus status");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getSimpleBuilder(statusMessage));
+
+ }
+
+
+ @Override
+ public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage,
+ String errorReason) {
+ log.info("DistributionClient - sendFinalDistributionStatus status with errorReason");
+ Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>();
+ validateRunReady(errorWrapper);
+ if (!errorWrapper.isEmpty()) {
+ return errorWrapper.getInnerElement();
+ }
+ return sendStatus(DistributionStatusMessageJsonBuilderFactory.getErrorReasonBuilder(statusMessage, errorReason));
+
+
+ }
+
+ public Either<List<String>,IDistributionClientResult> getUEBServerList() {
+ List<String> msgBusAddresses = configuration.getMsgBusAddress();
+ if(msgBusAddresses.isEmpty()){
+ return Either.right(new DistributionClientResultImpl(DistributionActionResultEnum.CONF_MISSING_MSG_BUS_ADDRESS, "Message bus address was not found in the config file"));
+ }
+ else{
+ return GeneralUtils.convertToValidHostName(msgBusAddresses);
+ }
+ }
+
+
+
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java
new file mode 100644
index 0000000..0df0b7b
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionClientResultImpl.java
@@ -0,0 +1,50 @@
+/*-
+ * ============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.impl;
+
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+
+public class DistributionClientResultImpl implements IDistributionClientResult {
+
+ DistributionActionResultEnum responseStatus;
+ String responseMessage;
+
+ public DistributionClientResultImpl(DistributionActionResultEnum responseStatus, String responseMessage) {
+ this.responseStatus = responseStatus;
+ this.responseMessage = responseMessage;
+ }
+
+ @Override
+ public DistributionActionResultEnum getDistributionActionResult() {
+ return responseStatus;
+ }
+
+ @Override
+ public String getDistributionMessageResult() {
+ return responseMessage;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionClientResultImpl [responseStatus=" + responseStatus + ", responseMessage=" + responseMessage + "]";
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java
new file mode 100644
index 0000000..d5bc4ce
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageImpl.java
@@ -0,0 +1,113 @@
+/*-
+ * ============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.impl;
+
+import org.onap.sdc.api.consumer.IComponentDoneStatusMessage;
+import org.onap.sdc.api.consumer.IDistributionStatusMessage;
+import org.onap.sdc.api.consumer.IFinalDistrStatusMessage;
+import org.onap.sdc.utils.DistributionStatusEnum;
+
+class DistributionStatusMessageImpl implements IDistributionStatusMessage {
+
+ String distributionID;
+ String consumerID;
+ long timestamp;
+ String artifactURL;
+ DistributionStatusEnum status;
+ String errorReason;
+ private String componentName;
+
+ public DistributionStatusMessageImpl(IDistributionStatusMessage message) {
+ super();
+ distributionID = message.getDistributionID();
+ consumerID = message.getConsumerID();
+ timestamp = message.getTimestamp();
+ artifactURL = message.getArtifactURL();
+ status = message.getStatus();
+
+ }
+
+ public DistributionStatusMessageImpl(IComponentDoneStatusMessage message) {
+ super();
+ distributionID = message.getDistributionID();
+ consumerID = message.getConsumerID();
+ timestamp = message.getTimestamp();
+ artifactURL = message.getArtifactURL();
+ status = message.getStatus();
+ componentName = message.getComponentName();
+ }
+
+ public DistributionStatusMessageImpl(IFinalDistrStatusMessage message) {
+ super();
+ distributionID = message.getDistributionID();
+ consumerID = message.getConsumerID();
+ timestamp = message.getTimestamp();
+
+ artifactURL = "";
+ status = message.getStatus();
+ componentName = message.getComponentName();
+ }
+
+ @Override
+ public String getDistributionID() {
+
+ return distributionID;
+ }
+
+ @Override
+ public String getConsumerID() {
+
+ return consumerID;
+ }
+
+ @Override
+ public long getTimestamp() {
+
+ return timestamp;
+ }
+
+ @Override
+ public String getArtifactURL() {
+
+ return artifactURL;
+ }
+
+ @Override
+ public DistributionStatusEnum getStatus() {
+
+ return status;
+ }
+
+ public String getErrorReason() {
+ return errorReason;
+ }
+
+ public void setErrorReason(String errorReason) {
+ this.errorReason = errorReason;
+ }
+
+ public String getComponentName() {
+ return componentName;
+ }
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java
new file mode 100644
index 0000000..d8c722d
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/DistributionStatusMessageJsonBuilderFactory.java
@@ -0,0 +1,148 @@
+/*-
+ * ============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.impl;
+
+import org.onap.sdc.api.IDistributionStatusMessageJsonBuilder;
+import org.onap.sdc.api.consumer.IComponentDoneStatusMessage;
+import org.onap.sdc.api.consumer.IDistributionStatusMessage;
+import org.onap.sdc.api.consumer.IFinalDistrStatusMessage;
+import org.onap.sdc.utils.DistributionStatusEnum;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class DistributionStatusMessageJsonBuilderFactory {
+ static Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IDistributionStatusMessage statusMessage){
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+
+ return prepareBuilderFromImpl(message);
+ }
+
+ public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IComponentDoneStatusMessage statusMessage){
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+
+ return prepareBuilderFromImpl(message);
+ }
+
+ public static IDistributionStatusMessageJsonBuilder getSimpleBuilder(IFinalDistrStatusMessage statusMessage){
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+
+ return prepareBuilderFromImpl(message);
+ }
+
+ public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IDistributionStatusMessage statusMessage, String errorReason){
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+ message.setErrorReason(errorReason);
+
+ return prepareBuilderFromImpl(message);
+ }
+
+ public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IComponentDoneStatusMessage statusMessage,
+ String errorReason) {
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+ message.setErrorReason(errorReason);
+ return prepareBuilderFromImpl(message);
+ }
+
+ public static IDistributionStatusMessageJsonBuilder getErrorReasonBuilder(IFinalDistrStatusMessage statusMessage,
+ String errorReason) {
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+ message.setErrorReason(errorReason);
+ return prepareBuilderFromImpl(message);
+ }
+
+ static IDistributionStatusMessageJsonBuilder prepareBuilderForNotificationStatus(final String consumerId, final long currentTimeMillis, final String distributionId,
+ final ArtifactInfoImpl artifactInfo, boolean isNotified){
+
+ final DistributionStatusEnum fakeStatusToReplace = DistributionStatusEnum.DOWNLOAD_OK;
+ final String jsonRequest = buildDistributionStatusJson(consumerId, currentTimeMillis, distributionId, artifactInfo, fakeStatusToReplace);
+
+ DistributionStatusNotificationEnum notificationStatus = isNotified ? DistributionStatusNotificationEnum.NOTIFIED : DistributionStatusNotificationEnum.NOT_NOTIFIED;
+ final String changedRequest = jsonRequest.replace(fakeStatusToReplace.name(), notificationStatus.name());
+ IDistributionStatusMessageJsonBuilder builder = new IDistributionStatusMessageJsonBuilder() {
+ @Override
+ public String build() {
+ return changedRequest;
+ }
+ };
+ return builder;
+
+ }
+
+ private static String buildDistributionStatusJson(final String consumerId,
+ final long currentTimeMillis, final String distributionId,
+ final ArtifactInfoImpl artifactInfo,
+ final DistributionStatusEnum fakeStatusToBeReplaced) {
+ IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() {
+ @Override
+ public long getTimestamp() {
+ return currentTimeMillis;
+ }
+
+ @Override
+ public DistributionStatusEnum getStatus() {
+
+ return fakeStatusToBeReplaced;
+ }
+
+ @Override
+ public String getDistributionID() {
+ return distributionId;
+ }
+
+ @Override
+ public String getConsumerID() {
+ return consumerId;
+ }
+
+ @Override
+ public String getArtifactURL() {
+ return artifactInfo.getArtifactURL();
+ }
+ };
+
+ DistributionStatusMessageImpl message = new DistributionStatusMessageImpl(statusMessage);
+ final String jsonRequest = gson.toJson(message);
+ return jsonRequest;
+ }
+
+ private static IDistributionStatusMessageJsonBuilder prepareBuilderFromImpl( DistributionStatusMessageImpl message) {
+ final String jsonRequest = gson.toJson(message);
+ IDistributionStatusMessageJsonBuilder builder = new IDistributionStatusMessageJsonBuilder() {
+ @Override
+ public String build() {
+ return jsonRequest;
+ }
+ };
+ return builder;
+ }
+
+ private enum DistributionStatusNotificationEnum {
+ NOTIFIED, NOT_NOTIFIED
+ }
+
+
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java
new file mode 100644
index 0000000..92dad7b
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/JsonContainerResourceInstance.java
@@ -0,0 +1,158 @@
+/*-
+ * ============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.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.notification.IResourceInstance;
+
+class JsonContainerResourceInstance implements IResourceInstance {
+ JsonContainerResourceInstance (){}
+ private String resourceInstanceName;
+ private String resourceCustomizationUUID;
+ private String resourceName;
+ private String resourceVersion;
+ private String resoucreType;
+ private String resourceUUID;
+ private String resourceInvariantUUID;
+ private String category;
+ private String subcategory;
+ private List<ArtifactInfoImpl> artifacts;
+
+ private JsonContainerResourceInstance(IResourceInstance resourceInstance){
+ resourceInstanceName = resourceInstance.getResourceInstanceName();
+ resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID();
+ resourceName = resourceInstance.getResourceName();
+ resourceVersion = resourceInstance.getResourceVersion();
+ resoucreType = resourceInstance.getResourceType();
+ resourceUUID = resourceInstance.getResourceUUID();
+ resourceInvariantUUID = resourceInstance.getResourceInvariantUUID();
+ category = resourceInstance.getCategory();
+ subcategory = resourceInstance.getSubcategory();
+ artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(resourceInstance.getArtifacts());
+ }
+
+ public static List<JsonContainerResourceInstance> convertToJsonContainer(List<IResourceInstance> resources){
+ List<JsonContainerResourceInstance> buildResources = new ArrayList<JsonContainerResourceInstance>();
+ if( resources != null ){
+ for( IResourceInstance resourceInstance : resources ){
+ buildResources.add(new JsonContainerResourceInstance(resourceInstance));
+ }
+ }
+ return buildResources;
+ }
+
+ @Override
+ public String getResourceInstanceName() {
+ return resourceInstanceName;
+ }
+
+ public void setResourceInstanceName(String resourceInstanceName) {
+ this.resourceInstanceName = resourceInstanceName;
+ }
+
+ @Override
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ @Override
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ @Override
+ public String getResourceType() {
+ return resoucreType;
+ }
+
+ public void setResoucreType(String resoucreType) {
+ this.resoucreType = resoucreType;
+ }
+
+ @Override
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ @Override
+ public List<IArtifactInfo> getArtifacts() {
+ List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
+ if( artifacts != null ){
+ temp.addAll(artifacts);
+ }
+ return temp;
+ }
+
+ public void setArtifacts(List<ArtifactInfoImpl> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public List<ArtifactInfoImpl> getArtifactsImpl(){
+ return artifacts;
+ }
+
+ @Override
+ public String getResourceInvariantUUID() {
+ return resourceInvariantUUID;
+ }
+
+ public void setResourceInvariantUUID(String resourceInvariantUUID) {
+ this.resourceInvariantUUID = resourceInvariantUUID;
+ }
+ public String getResourceCustomizationUUID() {
+ return resourceCustomizationUUID;
+ }
+
+ public void setResourceCustomizationUUID(String resourceCustomizationUUID) {
+ this.resourceCustomizationUUID = resourceCustomizationUUID;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getSubcategory() {
+ return subcategory;
+ }
+
+ public void setSubcategory(String subcategory) {
+ this.subcategory = subcategory;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java
new file mode 100644
index 0000000..aab1e29
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationConsumer.java
@@ -0,0 +1,181 @@
+/*-
+ * ============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.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.notification.IResourceInstance;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+import org.onap.sdc.api.consumer.INotificationCallback;
+import org.onap.sdc.api.notification.INotificationData;
+import org.onap.sdc.utils.ArtifactTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.att.nsa.cambria.client.CambriaConsumer;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+class NotificationConsumer implements Runnable {
+
+ private static Logger log = LoggerFactory.getLogger(NotificationConsumer.class.getName());
+
+ private CambriaConsumer cambriaConsumer;
+ private INotificationCallback clientCallback;
+ private List<String> artifactsTypes;
+ private DistributionClientImpl distributionClient;
+
+ public NotificationConsumer(CambriaConsumer cambriaConsumer, INotificationCallback clientCallback, List<String> artifactsTypes, DistributionClientImpl distributionClient) {
+ this.cambriaConsumer = cambriaConsumer;
+ this.clientCallback = clientCallback;
+ this.artifactsTypes = artifactsTypes;
+ this.distributionClient = distributionClient;
+ }
+
+ @Override
+ public void run() {
+
+ try {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ long currentTimeMillis = System.currentTimeMillis();
+ for (String notificationMsg : cambriaConsumer.fetch()) {
+ log.debug("received message from topic");
+ log.debug("recieved notification from broker: {}", notificationMsg);
+
+ final NotificationDataImpl notificationFromUEB = gson.fromJson(notificationMsg, NotificationDataImpl.class);
+ NotificationDataImpl notificationForCallback = buildCallbackNotificationLogic(currentTimeMillis, notificationFromUEB);
+ if (isActivateCallback(notificationForCallback)) {
+ String stringNotificationForCallback = gson.toJson(notificationForCallback);
+ log.debug("sending notification to client: {}", stringNotificationForCallback);
+ clientCallback.activateCallback(notificationForCallback);
+ }
+ }
+
+ } catch (Exception e) {
+ log.error("Error exception occured when fetching with Cambria Client:{}", e.getMessage());
+ log.debug("Error exception occured when fetching with Cambria Client:{}", e.getMessage(), e);
+ }
+ }
+
+ private boolean isActivateCallback(NotificationDataImpl notificationForCallback) {
+ boolean hasRelevantArtifactsInResourceInstance = notificationForCallback.getResources() != null && !notificationForCallback.getResources().isEmpty();
+ boolean hasRelevantArtifactsInService = notificationForCallback.getServiceArtifacts() != null && !notificationForCallback.getServiceArtifacts().isEmpty();
+
+ return hasRelevantArtifactsInResourceInstance || hasRelevantArtifactsInService;
+ }
+
+ protected NotificationDataImpl buildCallbackNotificationLogic(long currentTimeMillis, final NotificationDataImpl notificationFromUEB) {
+ List<IResourceInstance> relevantResourceInstances = buildResourceInstancesLogic(notificationFromUEB, currentTimeMillis);
+ List<ArtifactInfoImpl> relevantServiceArtifacts = handleRelevantArtifacts(notificationFromUEB, currentTimeMillis, notificationFromUEB.getServiceArtifactsImpl());
+ notificationFromUEB.setResources(relevantResourceInstances);
+ notificationFromUEB.setServiceArtifacts(relevantServiceArtifacts);
+ return notificationFromUEB;
+ }
+
+ private List<IResourceInstance> buildResourceInstancesLogic(NotificationDataImpl notificationFromUEB, long currentTimeMillis) {
+
+ List<IResourceInstance> relevantResourceInstances = new ArrayList<>();
+
+ for (JsonContainerResourceInstance resourceInstance : notificationFromUEB.getResourcesImpl()) {
+ final List<ArtifactInfoImpl> artifactsImplList = resourceInstance.getArtifactsImpl();
+ List<ArtifactInfoImpl> foundRelevantArtifacts = handleRelevantArtifacts(notificationFromUEB, currentTimeMillis, artifactsImplList);
+ if (!foundRelevantArtifacts.isEmpty() || distributionClient.getConfiguration().isFilterInEmptyResources()) {
+ resourceInstance.setArtifacts(foundRelevantArtifacts);
+ relevantResourceInstances.add(resourceInstance);
+ }
+ }
+ return relevantResourceInstances;
+
+ }
+
+ private List<ArtifactInfoImpl> handleRelevantArtifacts(NotificationDataImpl notificationFromUEB, long currentTimeMillis, final List<ArtifactInfoImpl> artifactsImplList) {
+ List<ArtifactInfoImpl> relevantArtifacts = new ArrayList<>();
+ if (artifactsImplList != null) {
+ for (ArtifactInfoImpl artifactInfo : artifactsImplList) {
+ handleRelevantArtifact(notificationFromUEB, currentTimeMillis, artifactsImplList, relevantArtifacts, artifactInfo);
+ }
+ }
+ return relevantArtifacts;
+ }
+
+ private void handleRelevantArtifact(NotificationDataImpl notificationFromUEB, long currentTimeMillis, final List<ArtifactInfoImpl> artifactsImplList, List<ArtifactInfoImpl> relevantArtifacts, ArtifactInfoImpl artifactInfo) {
+ boolean isArtifactRelevant = artifactsTypes.contains(artifactInfo.getArtifactType());
+ String artifactType = artifactInfo.getArtifactType();
+ if (artifactInfo.getGeneratedFromUUID() != null && !artifactInfo.getGeneratedFromUUID().isEmpty()) {
+ IArtifactInfo generatedFromArtInfo = findGeneratedFromArtifact(artifactInfo.getGeneratedFromUUID(), artifactsImplList);
+ if (generatedFromArtInfo != null)
+ isArtifactRelevant = isArtifactRelevant && artifactsTypes.contains(generatedFromArtInfo.getArtifactType());
+ else
+ isArtifactRelevant = false;
+ }
+ if (isArtifactRelevant) {
+ setRelatedArtifacts(artifactInfo, notificationFromUEB);
+ if (artifactType.equals(ArtifactTypeEnum.HEAT.name()) || artifactType.equals(ArtifactTypeEnum.HEAT_VOL.name()) || artifactType.equals(ArtifactTypeEnum.HEAT_NET.name())) {
+ setGeneratedArtifact(artifactsImplList, artifactInfo);
+ }
+ relevantArtifacts.add(artifactInfo);
+
+ }
+ IDistributionClientResult notificationStatus = distributionClient.sendNotificationStatus(currentTimeMillis, notificationFromUEB.getDistributionID(), artifactInfo, isArtifactRelevant);
+ if (notificationStatus.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ log.error("Error failed to send notification status to UEB failed status:{}, error message:{}", notificationStatus.getDistributionActionResult().name(), notificationStatus.getDistributionMessageResult());
+ }
+ }
+
+ private void setRelatedArtifacts(ArtifactInfoImpl artifact, INotificationData notificationData) {
+ if (artifact.getRelatedArtifactsUUID() != null) {
+ List<IArtifactInfo> relatedArtifacts = new ArrayList<>();
+ for (String relatedArtifactUUID : artifact.getRelatedArtifactsUUID()) {
+ relatedArtifacts.add(notificationData.getArtifactMetadataByUUID(relatedArtifactUUID));
+ }
+ artifact.setRelatedArtifactsInfo(relatedArtifacts);
+ }
+
+ }
+
+ private void setGeneratedArtifact(final List<ArtifactInfoImpl> artifactsImplList, ArtifactInfoImpl artifactInfo) {
+ IArtifactInfo found = null;
+ String artifactUUID = artifactInfo.getArtifactUUID();
+ for (ArtifactInfoImpl generatedArtifactInfo : artifactsImplList) {
+ if (generatedArtifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.name()) && artifactUUID.equals(generatedArtifactInfo.getGeneratedFromUUID())) {
+ found = generatedArtifactInfo;
+ break;
+ }
+ }
+
+ artifactInfo.setGeneratedArtifact(found);
+ }
+
+ private IArtifactInfo findGeneratedFromArtifact(String getGeneratedFromUUID, List<ArtifactInfoImpl> list) {
+ IArtifactInfo found = null;
+ for (ArtifactInfoImpl artifactInfo : list) {
+ if (getGeneratedFromUUID.equals(artifactInfo.getArtifactUUID())) {
+ found = artifactInfo;
+ break;
+ }
+ }
+ return found;
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java
new file mode 100644
index 0000000..7b7b532
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/NotificationDataImpl.java
@@ -0,0 +1,179 @@
+/*-
+ * ============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.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.sdc.api.notification.IResourceInstance;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.notification.INotificationData;
+
+
+class NotificationDataImpl implements INotificationData {
+
+ private String distributionID;
+ private String serviceName;
+ private String serviceVersion;
+ private String serviceUUID;
+ private String serviceDescription;
+ private String serviceInvariantUUID;
+ private List<JsonContainerResourceInstance> resources;
+ private List<ArtifactInfoImpl> serviceArtifacts;
+ private String workloadContext;
+
+ @Override
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ @Override
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ @Override
+ public String getServiceVersion() {
+ return serviceVersion;
+ }
+
+ @Override
+ public String getServiceUUID() {
+ return serviceUUID;
+ }
+
+ public void setDistributionID(String distributionID) {
+ this.distributionID = distributionID;
+ }
+
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ public void setServiceVersion(String serviceVersion) {
+ this.serviceVersion = serviceVersion;
+ }
+
+ public void setServiceUUID(String serviceUUID) {
+ this.serviceUUID = serviceUUID;
+ }
+
+
+
+ public String getServiceDescription() {
+ return serviceDescription;
+ }
+
+ public void setServiceDescription(String serviceDescription) {
+ this.serviceDescription = serviceDescription;
+ }
+
+ @Override
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ @Override
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ @Override
+ public String toString() {
+ return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName
+ + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription="
+ + serviceDescription + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources
+ + ", serviceArtifacts=" + serviceArtifacts + ", workloadContext=" + workloadContext + "]";
+ }
+
+ @Override
+ public List<IResourceInstance> getResources() {
+ List<IResourceInstance> ret = new ArrayList<IResourceInstance>();
+ if( resources != null ){
+ ret.addAll(resources);
+ }
+ return ret;
+ }
+
+ public void setResources(List<IResourceInstance> resources){
+ this.resources = JsonContainerResourceInstance.convertToJsonContainer(resources);
+ }
+
+ public List<JsonContainerResourceInstance> getResourcesImpl(){
+ return resources;
+ }
+
+ List<ArtifactInfoImpl> getServiceArtifactsImpl(){
+ return serviceArtifacts;
+ }
+
+ @Override
+ public List<IArtifactInfo> getServiceArtifacts() {
+
+ List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>();
+ if( serviceArtifacts != null ){
+ temp.addAll(serviceArtifacts);
+ }
+ return temp;
+ }
+
+ void setServiceArtifacts(List<ArtifactInfoImpl> relevantServiceArtifacts) {
+ serviceArtifacts = relevantServiceArtifacts;
+
+ }
+
+ @Override
+ public String getServiceInvariantUUID() {
+ return serviceInvariantUUID;
+ }
+
+
+ public void setServiceInvariantUUID(String serviceInvariantUUID) {
+ this.serviceInvariantUUID = serviceInvariantUUID;
+ }
+ @Override
+ public IArtifactInfo getArtifactMetadataByUUID(String artifactUUID){
+ IArtifactInfo ret = findArtifactInfoByUUID(artifactUUID, serviceArtifacts);
+ if( ret == null && resources != null ){
+ for( JsonContainerResourceInstance currResourceInstance : resources ){
+ ret = findArtifactInfoByUUID(artifactUUID, currResourceInstance.getArtifactsImpl());
+ if( ret != null ){
+ break;
+ }
+ }
+ }
+ return ret;
+
+ }
+
+ private IArtifactInfo findArtifactInfoByUUID(String artifactUUID, List<ArtifactInfoImpl> listToCheck) {
+ IArtifactInfo ret = null;
+ if( listToCheck != null ){
+ for(IArtifactInfo curr: listToCheck ){
+ if(curr.getArtifactUUID().equals(artifactUUID) ){
+ ret = curr;
+ break;
+ }
+ }
+ }
+ return ret;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java
new file mode 100644
index 0000000..49ba428
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusConsumer.java
@@ -0,0 +1,66 @@
+/*-
+ * ============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.impl;
+
+import org.onap.sdc.api.consumer.IStatusCallback;
+import org.onap.sdc.api.notification.IStatusData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.att.nsa.cambria.client.CambriaConsumer;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+class StatusConsumer implements Runnable {
+
+ private static Logger log = LoggerFactory.getLogger(StatusConsumer.class.getName());
+
+ private CambriaConsumer cambriaConsumer;
+ private IStatusCallback clientCallback;
+
+ public StatusConsumer(CambriaConsumer cambriaConsumer, IStatusCallback clientCallback) {
+ this.cambriaConsumer = cambriaConsumer;
+ this.clientCallback = clientCallback;
+ }
+
+ @Override
+ public void run() {
+
+ try {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ for (String statusMsg : cambriaConsumer.fetch()) {
+ log.debug("received message from topic");
+ log.debug("recieved notification from broker: {}", statusMsg);
+ IStatusData statusData = gson.fromJson(statusMsg, StatusDataImpl.class);
+ clientCallback.activateCallback(statusData);
+
+
+ }
+
+ } catch (Exception e) {
+ log.error("Error exception occured when fetching with Cambria Client:{}", e.getMessage());
+ log.debug("Error exception occured when fetching with Cambria Client:{}", e.getMessage(), e);
+ }
+ }
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java
new file mode 100644
index 0000000..70513fe
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.sdc.impl;
+
+import org.onap.sdc.api.notification.IStatusData;
+import org.onap.sdc.utils.DistributionStatusEnum;
+
+public class StatusDataImpl implements IStatusData {
+
+ String distributionID;
+ String consumerID;
+ long timestamp;
+ String artifactURL;
+ DistributionStatusEnum status;
+ String componentName;
+ String errorReason;
+
+ @Override
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ public void setDistributionID(String distributionId) {
+ this.distributionID = distributionId;
+ }
+ @Override
+ public String getConsumerID() {
+ return consumerID;
+ }
+
+ public void setConsumerID(String consumerId) {
+ this.consumerID = consumerId;
+ }
+ @Override
+ public Long getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
+ @Override
+ public String getArtifactURL() {
+ return artifactURL;
+ }
+
+ public void setArtifactURL(String artifactURL) {
+ this.artifactURL = artifactURL;
+ }
+ @Override
+ public DistributionStatusEnum getStatus() {
+ return status;
+ }
+
+ public void setStatus(DistributionStatusEnum status) {
+ this.status = status;
+ }
+
+
+ @Override
+ public String toString() {
+ return "StatusDataImpl [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status +", errorReason=" + errorReason+ "]";
+ }
+ @Override
+ public String getComponentName() {
+ return componentName;
+ }
+
+ @Override
+ public String getErrorReason() {
+ return errorReason;
+ }
+
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java
new file mode 100644
index 0000000..fb745f3
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/VfModuleMetadata.java
@@ -0,0 +1,61 @@
+/*-
+ * ============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.impl;
+
+import java.util.List;
+
+import org.onap.sdc.api.notification.IVfModuleMetadata;
+
+final class VfModuleMetadata implements IVfModuleMetadata {
+ private VfModuleMetadata(){
+ //This Class is only built by parsing Json
+ }
+
+ private String vfModuleModelName;
+ private String vfModuleModelInvariantUUID;
+ private String vfModuleModelVersion;
+ private String vfModuleModelUUID;
+ private String vfModuleModelDescription;
+ private boolean isBase;
+ private List<String> artifacts;
+
+ public String getVfModuleModelName() {
+ return vfModuleModelName;
+ }
+ public String getVfModuleModelInvariantUUID() {
+ return vfModuleModelInvariantUUID;
+ }
+ public String getVfModuleModelVersion() {
+ return vfModuleModelVersion;
+ }
+ public String getVfModuleModelUUID() {
+ return vfModuleModelUUID;
+ }
+ public String getVfModuleModelDescription() {
+ return vfModuleModelDescription;
+ }
+ public boolean isBase() {
+ return isBase;
+ }
+ public List<String> getArtifacts() {
+ return artifacts;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java
new file mode 100644
index 0000000..e0cd56e
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientDownloadResultStubImpl.java
@@ -0,0 +1,78 @@
+/*-
+ * ============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.impl.mock;
+
+import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+
+/** Mock Implementation */
+public class DistributionClientDownloadResultStubImpl extends DistributionClientResultStubImpl implements IDistributionClientDownloadResult {
+
+ @Override
+ public byte[] getArtifactPayload() {
+ String mockPayload = "heat_template_version: 2013-05-23\r\n" +
+ "\r\n" +
+ "description: >\r\n" +
+ " HOT template that creates one COR network (direct).\r\n" +
+ "\r\n" +
+ "parameters:\r\n" +
+ " cor_direct_net_name:\r\n" +
+ " type: string\r\n" +
+ " description: Name of COR direct network\r\n" +
+ " cor_direct_net_cidr:\r\n" +
+ " type: string\r\n" +
+ " description: Direct network address (CIDR notation)\r\n" +
+ " cor_direct_net_gateway:\r\n" +
+ " type: string\r\n" +
+ " description: Direct network gateway address\r\n" +
+ " cor_direct_net_RT:\r\n" +
+ " type: string\r\n" +
+ " description: Direct network route-target (RT)\r\n" +
+ "\r\n" +
+ "resources:\r\n" +
+ " cor_direct_net:\r\n" +
+ " type: OS::Contrail::VirtualNetwork\r\n" +
+ " properties:\r\n" +
+ " name: { get_param: cor_direct_net_name }\r\n" +
+ " route_targets: [ get_param: cor_direct_net_RT ]\r\n" +
+ "\r\n" +
+ " cor_direct_ip_subnet:\r\n" +
+ " type: OS::Neutron::Subnet\r\n" +
+ " properties:\r\n" +
+ " network_id: { get_resource: cor_direct_net }\r\n" +
+ " cidr: {get_param: cor_direct_net_cidr}\r\n" +
+ " gateway_ip: { get_param: cor_direct_net_gateway }\r\n";
+
+ return mockPayload.getBytes();
+ }
+
+ @Override
+ public String getArtifactName() {
+ // TODO Auto-generated method stub
+ return "MackArtifactName";
+ }
+
+ @Override
+ public String getArtifactFilename() {
+ // TODO Auto-generated method stub
+ return "MackArtifactName";
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java
new file mode 100644
index 0000000..cf0466b
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientResultStubImpl.java
@@ -0,0 +1,37 @@
+/*-
+ * ============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.impl.mock;
+
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.utils.DistributionActionResultEnum;
+/** Mock Implementation */
+public class DistributionClientResultStubImpl implements IDistributionClientResult {
+ @Override
+ public DistributionActionResultEnum getDistributionActionResult() {
+ return DistributionActionResultEnum.SUCCESS;
+ }
+
+ @Override
+ public String getDistributionMessageResult() {
+ return "Stub Result, method not implemented!";
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java
new file mode 100644
index 0000000..9049215
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/mock/DistributionClientStubImpl.java
@@ -0,0 +1,127 @@
+/*-
+ * ============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.impl.mock;
+
+import java.util.List;
+
+import org.onap.sdc.api.IDistributionClient;
+import org.onap.sdc.api.consumer.*;
+import org.onap.sdc.api.notification.IArtifactInfo;
+import org.onap.sdc.api.notification.IVfModuleMetadata;
+import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.api.consumer.*;
+
+/** Mock Implementation */
+public class DistributionClientStubImpl implements IDistributionClient {
+
+
+ public IDistributionClientResult updateConfiguration(IConfiguration newConf) {
+ return new DistributionClientResultStubImpl();
+ }
+
+ public IDistributionClientResult start() {
+ return new DistributionClientResultStubImpl();
+ }
+
+ public IDistributionClientResult stop() {
+ return new DistributionClientResultStubImpl();
+ }
+
+ public IDistributionClientResult sendDownloadStatus( IDistributionStatusMessage statusMessage) {
+ return new DistributionClientResultStubImpl();
+ }
+
+ public IDistributionClientResult sendDeploymentStatus( IDistributionStatusMessage statusMessage) {
+ return new DistributionClientResultStubImpl();
+ }
+
+ @Override
+ public IDistributionClientDownloadResult download(IArtifactInfo artifactInfo) {
+ return new DistributionClientDownloadResultStubImpl();
+ }
+
+ @Override
+ public IDistributionClientResult init(IConfiguration conf, INotificationCallback callback) {
+ return new DistributionClientResultStubImpl();
+ }
+
+ @Override
+ public IDistributionClientResult init(IConfiguration conf, INotificationCallback notificationCallback,
+ IStatusCallback statusCallback) {
+ return new DistributionClientResultStubImpl();
+ }
+
+ @Override
+ public IConfiguration getConfiguration() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendDownloadStatus(
+ IDistributionStatusMessage statusMessage, String errorReason) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendDeploymentStatus(
+ IDistributionStatusMessage statusMessage, String errorReason) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage) {
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage) {
+ return null;
+ }
+
+ @Override
+ public List<IVfModuleMetadata> decodeVfModuleArtifact(byte[] artifactPayload) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendComponentDoneStatus(IComponentDoneStatusMessage statusMessage,
+ String errorReason) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IDistributionClientResult sendFinalDistrStatus(IFinalDistrStatusMessage statusMessage, String errorReason) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+
+
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java
new file mode 100644
index 0000000..8df257e
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/ArtifactTypeEnum.java
@@ -0,0 +1,46 @@
+/*-
+ * ============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.utils;
+
+public enum ArtifactTypeEnum {
+ HEAT,
+ HEAT_VOL,
+ HEAT_NET,
+ MURANO_PKG,
+ HEAT_ENV,
+ YANG_XML,
+ OTHER,
+ VF_LICENSE,
+ VENDOR_LICENSE,
+ MODEL_INVENTORY_PROFILE,
+ MODEL_QUERY_SPEC,
+ APPC_CONFIG,
+ VNF_CATALOG,
+ HEAT_NESTED,
+ HEAT_ARTIFACT,
+ VF_MODULES_METADATA,
+ //DCAE Artifacts
+ DCAE_TOSCA, DCAE_JSON, DCAE_POLICY, DCAE_DOC,
+ DCAE_EVENT, DCAE_INVENTORY_TOSCA, DCAE_INVENTORY_JSON,
+ DCAE_INVENTORY_POLICY, DCAE_INVENTORY_DOC,
+ DCAE_INVENTORY_BLUEPRINT, DCAE_INVENTORY_EVENT;
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java
new file mode 100644
index 0000000..fe871f8
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionActionResultEnum.java
@@ -0,0 +1,58 @@
+/*-
+ * ============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.utils;
+
+public enum DistributionActionResultEnum {
+ SUCCESS,
+ FAIL,
+ GENERAL_ERROR,
+ BAD_REQUEST,
+ DISTRIBUTION_CLIENT_NOT_INITIALIZED,
+ DISTRIBUTION_CLIENT_IS_TERMINATED,
+ DISTRIBUTION_CLIENT_ALREADY_INITIALIZED,
+ DISTRIBUTION_CLIENT_ALREADY_STARTED,
+
+ DATA_INTEGRITY_PROBLEM,
+ ARTIFACT_NOT_FOUND,
+
+ CONFIGURATION_IS_MISSING,
+ CONF_MISSING_USERNAME,
+ CONF_MISSING_PASSWORD,
+ CONF_MISSING_ASDC_FQDN,
+ CONF_MISSING_ARTIFACT_TYPES,
+ CONF_CONTAINS_INVALID_ARTIFACT_TYPES,
+ CONF_MISSING_CONSUMER_ID,
+ CONF_MISSING_ENVIRONMENT_NAME,
+ CONF_MISSING_CONSUMER_GROUP,
+ CONF_INVALID_ASDC_FQDN,
+ CONF_INVALID_CONSUME_PRODUCE_STATUS_TOPIC_FALG,
+ CONF_MISSING_MSG_BUS_ADDRESS,
+ CONF_INVALID_MSG_BUS_ADDRESS,
+ ASDC_AUTHENTICATION_FAILED,
+ ASDC_AUTHORIZATION_FAILED,
+ ASDC_NOT_FOUND,
+ ASDC_SERVER_PROBLEM,
+ ASDC_CONNECTION_FAILED,
+ ASDC_SERVER_TIMEOUT,
+
+ CAMBRIA_INIT_FAILED,
+ UEB_KEYS_CREATION_FAILED
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java
new file mode 100644
index 0000000..1dcbca3
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionClientConstants.java
@@ -0,0 +1,44 @@
+/*-
+ * ============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.utils;
+
+import java.util.regex.Pattern;
+
+/**
+ * Constants Used By Distribution Client
+ * @author mshitrit
+ *
+ */
+public final class DistributionClientConstants {
+ public static final String CLIENT_DESCRIPTION = "ASDC Distribution Client Key for %s";
+ public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE);
+ public static final String EMAIL = "";
+ public static final int MIN_POLLING_INTERVAL_SEC = 15;
+ public static final int POOL_SIZE = 10;
+ public static final int POLLING_TIMEOUT_SEC = 15;
+
+ public static final String HEADER_INSTANCE_ID = "X-ECOMP-InstanceID";
+ public static final String HEADER_REQUEST_ID = "X-ECOMP-RequestID";
+ public static final String APPLICATION_JSON = "application/json";
+ public static final String HEADER_CONTENT_TYPE = "Content-Type";
+
+ private DistributionClientConstants(){ throw new UnsupportedOperationException();}
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java
new file mode 100644
index 0000000..e620195
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/DistributionStatusEnum.java
@@ -0,0 +1,56 @@
+/*-
+ * ============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.utils;
+
+public enum DistributionStatusEnum {
+ /**Can be sent when ONAP component successfully downloaded the specific artifact*/
+ DOWNLOAD_OK,
+
+ /**Can be sent when ONAP component failed to download the specific artifact (corrupted file)*/
+ DOWNLOAD_ERROR,
+
+ /**Can be sent only if the repeated distribution notification event is sent when the ONAP component already downloaded the artifact , but still not stored it in the local repository .*/
+ ALREADY_DOWNLOADED,
+
+ /**Can be sent when ONAP component successfully deployed the specific artifact in the local repository*/
+ DEPLOY_OK,
+
+ /**Can be sent when ONAP component failed to store the downloaded artifact in the local repository*/
+ DEPLOY_ERROR,
+
+ /**Sent when the repeated distribution notification event is sent for already stored in the local repository service artifact ( artifact's version and checksum match the one stored in the local repository)*/
+ ALREADY_DEPLOYED,
+ /**
+ * ONAP component is requested to publish this status once component successfully complete downloading and storing all the data it needs from the service.
+ */
+ COMPONENT_DONE_OK,
+
+ /**ONAP component is requested to publish this status when component failed to download or failed to store one or more of the mandatory information it requires from the service model.
+
+ It is recommended to populate the errorReason field with appropriate description of the error
+*/
+ COMPONENT_DONE_ERROR,
+ /** The DISTRIBUTION_COMPLETE_OK/ERROR status indicating the overall ONAP components status of retrieving and storing the information.
+*/
+ DISTRIBUTION_COMPLETE_OK,
+
+ DISTRIBUTION_COMPLETE_ERROR
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java
new file mode 100644
index 0000000..a69e479
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/GeneralUtils.java
@@ -0,0 +1,92 @@
+/*-
+ * ============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.utils;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.commons.codec.binary.Base64;
+import org.onap.sdc.api.results.IDistributionClientResult;
+import org.onap.sdc.impl.DistributionClientResultImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+public class GeneralUtils {
+ private static final Logger log = LoggerFactory.getLogger(GeneralUtils.class.getName());
+ public static String calculateMD5 (String data){
+ String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
+ // encode base-64 result
+ byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
+ String encodeBase64Str = new String(encodeBase64);
+ return encodeBase64Str;
+
+ }
+
+ public static String calculateMD5(byte[] decodedPayload) {
+ String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(decodedPayload);
+ byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes());
+ return new String(encodeMd5);
+ }
+
+ public static boolean isBase64Encoded(String str){
+ boolean isEncoded = false;
+ try
+ {
+ // If no exception is caught, then it is possibly a base64 encoded string
+ byte[] data = Base64.decodeBase64(str);
+ // checks if the string was properly padded to the
+ isEncoded= ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={1,2}\\z", str)));
+
+ }
+ catch (Exception e)
+ {
+ // If exception is caught, then it is not a base64 encoded string
+ isEncoded= false;
+ }
+ return isEncoded;
+ }
+
+
+ public static Either<List<String>, IDistributionClientResult> convertToValidHostName(List<String> msgBusAddresses) {
+ List<String> uebLocalHostsNames = new ArrayList<>();
+ for(String name : msgBusAddresses){
+ try {
+ uebLocalHostsNames.add(InetAddress.getByName(name).getHostName());
+ } catch (UnknownHostException e) {
+ log.debug("UnknownHost: {}", e.getMessage(), e);
+ }
+ }
+ Either<List<String>, IDistributionClientResult> response;
+ if( uebLocalHostsNames.isEmpty() ){
+ response = Either.right(new DistributionClientResultImpl(DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS, "configuration is invalid: " + DistributionActionResultEnum.CONF_INVALID_MSG_BUS_ADDRESS.name()));
+
+ }
+ else{
+ response = Either.left(uebLocalHostsNames);
+ }
+ return response;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java
new file mode 100644
index 0000000..097cafb
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Pair.java
@@ -0,0 +1,39 @@
+/*-
+ * ============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.utils;
+
+public final class Pair<F, S> {
+ private final F first;
+ private final S second;
+
+ public Pair(F first, S second){
+ this.first = first;
+ this.second = second;
+ }
+
+ public F getFirst() {
+ return first;
+ }
+
+ public S getSecond() {
+ return second;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java
new file mode 100644
index 0000000..d1d799c
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/Wrapper.java
@@ -0,0 +1,45 @@
+/*-
+ * ============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.utils;
+/**
+ * Very Basic Wrapper class.
+ * @author mshitrit
+ *
+ * @param <T>
+ */
+public class Wrapper<T>{
+ private T innerElement;
+ public Wrapper(T innerElement){
+ this.innerElement = innerElement;
+ }
+ public Wrapper(){
+ this.innerElement = null;
+ }
+ public T getInnerElement() {
+ return innerElement;
+ }
+ public void setInnerElement(T innerElement) {
+ this.innerElement = innerElement;
+ }
+ public boolean isEmpty(){
+ return innerElement == null;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java
new file mode 100644
index 0000000..9c294d2
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/YamlToObjectConverter.java
@@ -0,0 +1,155 @@
+/*-
+ * ============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.utils;
+
+import java.beans.IntrospectionException;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.HashMap;
+
+import org.onap.sdc.utils.heat.HeatConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.TypeDescription;
+import org.yaml.snakeyaml.Yaml;
+import org.yaml.snakeyaml.introspector.BeanAccess;
+import org.yaml.snakeyaml.introspector.Property;
+import org.yaml.snakeyaml.introspector.PropertyUtils;
+
+public class YamlToObjectConverter {
+
+ private static Logger log = LoggerFactory
+ .getLogger(YamlToObjectConverter.class.getName());
+
+ private static HashMap<String, Yaml> yamls = new HashMap<String, Yaml>();
+
+ private static Yaml defaultYaml = new Yaml();
+
+ static {
+
+ org.yaml.snakeyaml.constructor.Constructor heatConstructor = new org.yaml.snakeyaml.constructor.Constructor(HeatConfiguration.class);
+ TypeDescription heatDescription = new TypeDescription(HeatConfiguration.class);
+ //heatDescription.putListPropertyType("parameters", HeatParameterConfiguration.class);
+ heatConstructor.addTypeDescription(heatDescription);
+ PropertyUtils propertyUtils = new PropertyUtils() {
+ @Override
+ //This is in order to workaround "default" field in HeatParameterEntry, since default is Java keyword
+ public Property getProperty(Class<? extends Object> type, String name, BeanAccess bAccess)
+ throws IntrospectionException {
+ name = name.substring(0, 1).toLowerCase() + name.substring(1);
+ return super.getProperty(type, name, bAccess);
+ }
+
+ };
+ //Skip properties which are not found - we only are interested in "parameters"
+ propertyUtils.setSkipMissingProperties(true);
+ heatConstructor.setPropertyUtils(propertyUtils);
+
+ Yaml yaml = new Yaml(heatConstructor);
+
+ yamls.put(HeatConfiguration.class.getName(), yaml);
+
+ }
+
+ private static <T> Yaml getYamlByClassName(Class<T> className) {
+
+ Yaml yaml = yamls.get(className.getName());
+ if (yaml == null) {
+ yaml = defaultYaml;
+ }
+
+ return yaml;
+ }
+
+ public <T> T convert(String dirPath, Class<T> className,
+ String configFileName) {
+
+ T config = null;
+
+ try {
+
+ String fullFileName = dirPath + File.separator + configFileName;
+
+ config = convert(fullFileName, className);
+
+ } catch (Exception e) {
+ log.error("Failed to convert yaml file " + configFileName
+ + " to object.", e);
+ }
+
+ return config;
+ }
+
+ public <T> T convert(String fullFileName, Class<T> className) {
+
+ T config = null;
+
+ Yaml yaml = getYamlByClassName(className);
+
+ InputStream in = null;
+ try {
+
+ File f = new File(fullFileName);
+ if (false == f.exists()) {
+ log.warn("The file " + fullFileName
+ + " cannot be found. Ignore reading configuration.");
+ return null;
+ }
+ in = Files.newInputStream(Paths.get(fullFileName));
+
+ config = yaml.loadAs(in, className);
+
+ // System.out.println(config.toString());
+ } catch (Exception e) {
+ log.error("Failed to convert yaml file " + fullFileName
+ + " to object.", e);
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ return config;
+ }
+
+ public <T> T convertFromString(String yamlContents, Class<T> className) {
+
+ T config = null;
+
+ Yaml yaml = getYamlByClassName(className);
+
+ try {
+ config = yaml.loadAs(yamlContents, className);
+ } catch (Exception e){
+ log.error("Failed to convert YAML {} to object." , yamlContents, e);
+ }
+
+ return config;
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java
new file mode 100644
index 0000000..ee272f4
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatConfiguration.java
@@ -0,0 +1,42 @@
+/*-
+ * ============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.utils.heat;
+
+import java.util.Map;
+
+public class HeatConfiguration {
+
+ //All the rest of heat file is not needed for now...
+ Map<String, HeatParameter> parameters;
+
+
+ public Map<String, HeatParameter> getParameters() {
+ return parameters;
+ }
+
+
+ public void setParameters(Map<String, HeatParameter> parameters) {
+ this.parameters = parameters;
+ }
+
+
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java
new file mode 100644
index 0000000..3638bcf
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameter.java
@@ -0,0 +1,207 @@
+/*-
+ * ============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.utils.heat;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class HeatParameter{
+
+ String type;
+ String label;
+ String description;
+ //This is in order to workaround "default" field in HeatParameterEntry, since default is Java keyword
+ //YAML constructor will lowercase it during parsing
+ String Default;
+ String hidden = "false";//Default value according to OpenStack spec
+ List<HeatParameterConstraint> constraints;
+
+
+
+ public String getHidden() {
+ return hidden;
+ }
+ public void setHidden(String hidden) {
+ this.hidden = hidden;
+ }
+
+ public List<HeatParameterConstraint> getConstraints() {
+ return constraints;
+ }
+ public void setConstraints(List<HeatParameterConstraint> constraints) {
+ this.constraints = constraints;
+ }
+ public String getType() {
+ return type;
+ }
+ public void setType(String type) {
+ this.type = type;
+ }
+ public String getLabel() {
+ return label;
+ }
+ public void setLabel(String label) {
+ this.label = label;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public String getDefault() {
+ return Default;
+ }
+ public void setDefault(String default1) {
+ Default = default1;
+ }
+
+
+
+ // Getting specific constraints
+ /**
+ * Get the first "length" constraint from HEAT parameter.
+ * No additional "length" constraint is searched for.
+ *
+ * @return first "length" constraint found for this parameter,
+ * or null if no such constraint exists.
+ */
+ public HeatParameterConstraint getLengthConstraint(){
+ HeatParameterConstraint res = null;
+ if (constraints != null){
+ for (HeatParameterConstraint entry : constraints){
+ if (entry.getLength() != null){
+ res = entry;
+ break;
+ }
+ }
+ }
+ return res;
+ }
+
+
+ /**
+ * Get the first "range" constraint from HEAT parameter.
+ * No additional "range" constraint is searched for.
+ *
+ * @return first "range" constraint found for this parameter,
+ * or null if no such constraint exists.
+ */
+ public HeatParameterConstraint getRangeConstraint(){
+ HeatParameterConstraint res = null;
+ if (constraints != null){
+ for (HeatParameterConstraint entry : constraints){
+ if (entry.getRange() != null){
+ res = entry;
+ break;
+ }
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Get the first "allowed_values" constraint from HEAT parameter.
+ * No additional "allowed_values" constraint is searched for.
+ *
+ * @return first "allowed_values" constraint found for this parameter,
+ * or null if no such constraint exists.
+ */
+ public HeatParameterConstraint getAllowedValuesConstraint(){
+ HeatParameterConstraint res = null;
+ if (constraints != null){
+ for (HeatParameterConstraint entry : constraints){
+ if (entry.getAllowed_values() != null){
+ res = entry;
+ break;
+ }
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Get the "allowed_pattern" constraint list from HEAT parameter.
+ *
+ * @return "allowed_pattern" constraint list found for this parameter,
+ * or null if no such constraint exists.
+ */
+ public List<HeatParameterConstraint> getAllowedPatternConstraint(){
+ List<HeatParameterConstraint> res = null;
+ if (constraints != null){
+ for (HeatParameterConstraint entry : constraints){
+ if (entry.getAllowed_pattern() != null){
+ if (res == null){
+ res = new ArrayList<>();
+ }
+ res.add(entry);
+ }
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Get the "custom_constraint" constraint list from HEAT parameter.
+ *
+ * @return "custom_constraint" constraint list found for this parameter,
+ * or null if no such constraint exists.
+ */
+ public List<HeatParameterConstraint> getCustomConstraintConstraint(){
+ List<HeatParameterConstraint> res = null;
+ if (constraints != null){
+ for (HeatParameterConstraint entry : constraints){
+ if (entry.getCustom_constraint() != null){
+ if (res == null){
+ res = new ArrayList<>();
+ }
+ res.add(entry);
+ }
+ }
+ }
+ return res;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ if (type != null){
+ sb.append("type:"+type+", ");
+ }
+ if (label != null){
+ sb.append("label:"+label+", ");
+ }
+ if (Default != null){
+ sb.append("default:"+Default+", ");
+ }
+ if (hidden != null){
+ sb.append("hidden:"+hidden+", ");
+ }
+ if (constraints != null){
+ sb.append("constraints:"+constraints+", ");
+ }
+ if (description != null){
+ sb.append("description:"+description);
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java
new file mode 100644
index 0000000..d618caf
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParameterConstraint.java
@@ -0,0 +1,93 @@
+/*-
+ * ============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.utils.heat;
+
+import java.util.List;
+import java.util.Map;
+
+public class HeatParameterConstraint {
+
+ Map<String, String> length;
+ Map<String, String> range;
+ List<String> allowed_values;
+ String allowed_pattern;
+ String custom_constraint;
+ String description;
+
+
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public Map<String, String> getLength() {
+ return length;
+ }
+ public void setLength(Map<String, String> length) {
+ this.length = length;
+ }
+ public Map<String, String> getRange() {
+ return range;
+ }
+ public void setRange(Map<String, String> range) {
+ this.range = range;
+ }
+ public List<String> getAllowed_values() {
+ return allowed_values;
+ }
+ public void setAllowed_values(List<String> allowed_values) {
+ this.allowed_values = allowed_values;
+ }
+ public String getAllowed_pattern() {
+ return allowed_pattern;
+ }
+ public void setAllowed_pattern(String allowed_pattern) {
+ this.allowed_pattern = allowed_pattern;
+ }
+ public String getCustom_constraint() {
+ return custom_constraint;
+ }
+ public void setCustom_constraint(String custom_constraint) {
+ this.custom_constraint = custom_constraint;
+ }
+
+ @Override
+ public String toString() {
+ String constraintTypeValue = "<empty>";
+ String descriptionStr = "<empty>";
+ if (length != null){
+ constraintTypeValue = "length:"+length;
+ } else if (range != null){
+ constraintTypeValue = "range:"+range;
+ } else if (allowed_values != null){
+ constraintTypeValue = "allowed_values:"+allowed_values;
+ } else if (allowed_pattern != null){
+ constraintTypeValue = "allowed_pattern:"+allowed_pattern;
+ } else if (custom_constraint != null){
+ constraintTypeValue = "custom_constraint:"+custom_constraint;
+ }
+ if (description != null){
+ descriptionStr = "description:"+description;
+ }
+ return new StringBuilder().append(constraintTypeValue).append(", ").append(descriptionStr).toString();
+ }
+}
diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java
new file mode 100644
index 0000000..340a59d
--- /dev/null
+++ b/sdc-distribution-client/src/main/java/org/onap/sdc/utils/heat/HeatParser.java
@@ -0,0 +1,75 @@
+/*-
+ * ============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.utils.heat;
+
+import java.util.Map;
+
+import org.onap.sdc.utils.YamlToObjectConverter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HeatParser {
+
+ private static Logger log = LoggerFactory.getLogger(HeatParser.class.getName());
+
+
+ /**
+ * Parses and returns the contents of the "parameters" section of YAML-formatted HEAT template.
+ *
+ * @param heatFileContents - the string contents of HEAT template
+ * @return map of parameter name to HeatParameter object.
+ * For the following YAML snippet:
+ * <b>parameters:
+ * image_name_1:
+ * type: string
+ * label: Image Name
+ * description: SCOIMAGE Specify an image name for instance1
+ * default: cirros-0.3.1-x86_64
+ * </b>
+ * the map with one entry will be returned, the key will be "image_name_1".
+ * For a HeatParameter object, getConstraints() returns the list of all constraints,
+ * regardless of constraint type.
+ * For that reason, for each constraint type a sugaring function were added on the HeatParameter type,
+ * for example getLengthConstraint(). A correct way to fetch the "length" constraint values map would be
+ * parameter.getLengthConstraint().getLength(). Same logic was implemented for all other constraint types.
+ *
+ * In case of parse error, null will be returned.
+ *
+ */
+ public Map<String, HeatParameter> getHeatParameters(String heatFileContents){
+ log.debug("Start of extracting HEAT parameters from file, file contents: {}", heatFileContents);
+ Map<String, HeatParameter> heatParameters = null;
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+ HeatConfiguration heatConfiguration = yamlToObjectConverter.convertFromString(heatFileContents, HeatConfiguration.class);
+ if (heatConfiguration != null){
+ heatParameters = heatConfiguration.getParameters();
+ } else {
+ log.error("Couldn't parse HEAT template.");
+ }
+ if (heatParameters != null && heatParameters.size() > 0){
+ System.out.println("Found HEAT parameters: "+heatParameters.toString());
+ log.debug("Found HEAT parameters: {}", heatParameters.toString());
+ } else {
+ log.warn("HEAT template parameters section wasn't found or is empty.");
+ }
+ return heatParameters;
+ }
+}