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