Change nexus values to properties
[appc.git] / appc-asdc-listener / appc-asdc-listener-bundle / src / main / java / org / openecomp / appc / sdc / listener / DownloadAndStoreOp.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.sdc.listener;
23
24 import org.openecomp.appc.adapter.dmaap.EventSender;
25 import org.openecomp.appc.adapter.dmaap.DmaapDestination;
26 import org.openecomp.appc.adapter.dmaap.event.EventHeader;
27 import org.openecomp.appc.adapter.dmaap.event.EventMessage;
28 import org.openecomp.appc.adapter.dmaap.event.EventStatus;
29 import org.openecomp.appc.exceptions.APPCException;
30 import org.openecomp.appc.licmgr.Constants;
31 import org.openecomp.appc.licmgr.LicenseManager;
32 import org.openecomp.sdc.api.IDistributionClient;
33 import org.openecomp.sdc.api.notification.IArtifactInfo;
34 import org.openecomp.sdc.api.notification.INotificationData;
35 import org.openecomp.sdc.api.notification.IResourceInstance;
36 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
37 import org.openecomp.sdc.utils.DistributionActionResultEnum;
38 import org.openecomp.sdc.utils.DistributionStatusEnum;
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import org.osgi.framework.BundleContext;
42 import org.osgi.framework.FrameworkUtil;
43 import org.osgi.framework.ServiceReference;
44
45 import static org.openecomp.appc.licmgr.Constants.ASDC_ARTIFACTS_FIELDS.*;
46
47 import java.io.UnsupportedEncodingException;
48 import java.net.MalformedURLException;
49 import java.net.URI;
50 import java.text.DateFormat;
51 import java.text.SimpleDateFormat;
52 import java.util.Date;
53 import java.util.HashMap;
54 import java.util.Map;
55
56 @SuppressWarnings("JavaDoc")
57 public class DownloadAndStoreOp implements Runnable {
58
59     public static final String PAYLOAD_CHARSET = "UTF-8";
60
61     private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss";
62
63     private final EELFLogger logger = EELFManager.getInstance().getLogger(DownloadAndStoreOp.class);
64
65     private IDistributionClient client;
66     private EventSender eventSender;
67
68     private INotificationData notification;
69     private IResourceInstance resource;
70     private IArtifactInfo artifact;
71
72     private URI storeUri;
73
74     public DownloadAndStoreOp(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource,
75                               IArtifactInfo artifact, URI storeUri) {
76         this.client = client;
77         this.eventSender = eventSender;
78         this.notification = notification;
79         this.resource = resource;
80         this.artifact = artifact;
81         this.storeUri = storeUri;
82     }
83
84     @Override
85     public void run() {
86         logger.info(String.format("Attempting to download artifact %s", artifact));
87         // Download artifact
88         IDistributionClientDownloadResult download = client.download(artifact);
89         logger.info(String.format("Download of artifact %s completed with status %s", artifact.getArtifactUUID(), download));
90
91         // Notify of download status
92         if (download.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
93             client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact,
94                             DistributionStatusEnum.DOWNLOAD_ERROR), download.getDistributionMessageResult());
95             sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), "Download is failed.");
96             return;
97         }
98
99         client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DOWNLOAD_OK));
100
101         String data = null;
102         try {
103             if (download.getArtifactPayload() != null) {
104                 data = new String(download.getArtifactPayload(), PAYLOAD_CHARSET);
105             }
106         } catch (UnsupportedEncodingException e) {
107             e.printStackTrace();
108         }
109
110         boolean providerSuccess = false;
111         String providerReason = "Unknown Error";
112         // Send data to provider
113         if (data != null && artifact != null) {
114             switch(artifact.getArtifactType()) {
115                 case "APPC_CONFIG":
116                     String postData = Util.toAsdcStoreDocumentInput(notification, resource, artifact, data);
117                     try {
118                         ProviderResponse result = ProviderOperations.post(storeUri.toURL(), postData, null);
119                         if (result.getStatus() == 200) {
120                             providerSuccess = Util.parseResponse(result.getBody());
121                             providerReason = "Success";
122                         }
123                     } catch (MalformedURLException | APPCException e) {
124                         providerReason = e.getMessage();
125                         e.printStackTrace();
126                     }
127                     break;
128
129                 case "VF_LICENSE":
130                     BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
131                     ServiceReference srefLicenseService = bctx.getServiceReference(LicenseManager.class);
132                     LicenseManager licenseService = (LicenseManager) bctx.getService(srefLicenseService);
133
134                     Map<String, String> artifactPayload = prepareArtifactPayloadParamsMap(data);
135
136                     String vnfType = artifactPayload.get(RESOURCE_NAME.name());
137                     String version = artifactPayload.get(RESOURCE_VERSION.name());
138                     String packageArtifactID = artifactPayload.get(ARTIFACT_UUID.name());
139                     String packageArtifactVersion = artifactPayload.get(INTERNAL_VERSION.name());
140
141                     try {
142                         if (null == vnfType || null == version || null == packageArtifactID || null == packageArtifactVersion || vnfType.isEmpty() || version.isEmpty() || packageArtifactID.isEmpty() || packageArtifactVersion.isEmpty()) {
143                             throw new APPCException(String.format("Missing information in ASDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s', artifactVersion='%s'", vnfType, version, packageArtifactID, packageArtifactVersion));
144                         }
145
146                         Map<String, String> existingArtifactPayload = licenseService.retrieveLicenseModelData(vnfType, version);
147
148                         if (existingArtifactPayload.isEmpty()) { // new resource
149                             licenseService.storeArtifactPayload(artifactPayload);
150                         } else { // duplicate
151                             logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version));
152                         }
153
154                         providerSuccess = true;
155
156                     } catch (Exception e) {
157                         providerSuccess = false;
158                         providerReason = e.getMessage();
159                     }
160                     break;
161
162                 default:
163                     throw new UnsupportedOperationException("Artifact type " + artifact.getArtifactType() + " is not supported");
164             }
165
166         }
167
168         // Notify of provider's response
169         if (providerSuccess) {
170             client.sendDeploymentStatus(
171                             Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DEPLOY_OK));
172         } else {
173             client.sendDeploymentStatus(Util.buildDistributionStatusMessage(client, notification, artifact,
174                             DistributionStatusEnum.DEPLOY_ERROR), providerReason);
175             sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), providerReason);
176         }
177
178     }
179
180     /**
181      * Prepares Artifact Payload params map
182      * @param data
183      * @return Map<String,String>
184      */
185     private Map<String, String> prepareArtifactPayloadParamsMap(String data) {
186         Map<String, String> paramsMap = new HashMap<>();
187
188         paramsMap.put(SERVICE_UUID.name(), this.notification.getServiceUUID());
189         paramsMap.put(DISTRIBUTION_ID.name(), this.notification.getDistributionID());
190         paramsMap.put(SERVICE_NAME.name(), this.notification.getServiceName());
191         paramsMap.put(SERVICE_DESCRIPTION.name(), this.notification.getServiceDescription());
192         paramsMap.put(RESOURCE_UUID.name(), this.resource.getResourceUUID());
193         paramsMap.put(RESOURCE_INSTANCE_NAME.name(), this.resource.getResourceInstanceName());
194         paramsMap.put(RESOURCE_NAME.name(), this.resource.getResourceName());
195         paramsMap.put(RESOURCE_VERSION.name(), this.resource.getResourceVersion());
196         paramsMap.put(RESOURCE_TYPE.name(), this.resource.getResourceType());
197         paramsMap.put(ARTIFACT_UUID.name(), this.artifact.getArtifactUUID());
198         paramsMap.put(ARTIFACT_TYPE.name(), this.artifact.getArtifactType());
199         paramsMap.put(ARTIFACT_VERSION.name(), this.artifact.getArtifactVersion());
200         paramsMap.put(ARTIFACT_DESCRIPTION.name(), this.artifact.getArtifactDescription());
201         paramsMap.put(CREATION_DATE.name(), getCurrentDateTime());
202         paramsMap.put(ARTIFACT_NAME.name(), this.artifact.getArtifactName());
203         paramsMap.put(ARTIFACT_CONTENT.name(), data);
204
205         return paramsMap;
206     }
207
208
209     private String getCurrentDateTime() {
210         DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
211         Date date = new Date();
212         return dateFormat.format(date);
213     }
214
215     private void sendDCAEEvent(String distributionID, String serviceName, String serviceVersion, String errorMessage) {
216         if (null == eventSender) return;
217         String errorDescription = String.format("ASDC distribution of service '%s', version '%s' is failed with reason: '%s'",
218                         serviceName, serviceVersion, errorMessage);
219
220         EventMessage eventMessage = new EventMessage(
221                         new EventHeader((new java.util.Date()).toString(), serviceVersion, distributionID),
222                         new EventStatus(401, errorDescription));
223
224         eventSender.sendEvent(DmaapDestination.DCAE, eventMessage);
225     }
226
227 }