b2cc984fbac5d35ecbc48ffa9bb15c669526ee21
[appc.git] / appc-inbound / appc-artifact-handler / provider / src / main / java / org / onap / appc / artifact / handler / node / ArtifactHandlerNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.artifact.handler.node;
27
28 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION;
29 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL;
30 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VF_MODULE;
31 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VM;
32 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VNF;
33 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VNFC;
34 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_CONTENTS;
35 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION;
36 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_NAME;
37 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_NAME_CAPABILITY;
38 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_NAME_REFERENCE;
39 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_TYPE;
40 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_UUID;
41 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_VERSION;
42 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.CAPABILITY;
43 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG;
44 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION;
45 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL;
46 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE;
47 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_SDC_REFERENCE;
48 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DEVICE_PROTOCOL;
49 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DISTRIBUTION_ID;
50 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS;
51 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE;
52 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.FILE_CATEGORY;
53 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE;
54 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE;
55 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP;
56 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.PARAMETER_YANG;
57 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.PD;
58 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.PORT_NUMBER;
59 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REFERENCE;
60 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REQUEST_ID;
61 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REQUEST_INFORMATION;
62 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME;
63 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_TYPE;
64 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_UUID;
65 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_VERSION;
66 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.SERVICE_DESCRIPTION;
67 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.SERVICE_NAME;
68 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.SERVICE_UUID;
69 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.TEMPLATE;
70 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.TEMPLATE_ID;
71 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.TOSCA_MODEL;
72 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.USER_NAME;
73 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VM;
74 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VM_INSTANCE;
75 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC;
76 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE;
77 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE_LIST;
78 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_INSTANCE;
79 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_TYPE;
80 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_TYPE_LIST;
81 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNF_TYPE;
82 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.URL;
83 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.OPENSTACK;
84 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ANSIBLE;
85
86 import com.att.eelf.configuration.EELFLogger;
87 import com.att.eelf.configuration.EELFManager;
88 import java.io.ByteArrayOutputStream;
89 import java.io.OutputStream;
90 import java.sql.SQLException;
91 import java.util.Map;
92 import java.util.function.Function;
93 import org.apache.commons.configuration.ConfigurationException;
94 import org.apache.commons.lang.StringUtils;
95 import org.json.JSONArray;
96 import org.json.JSONObject;
97 import org.onap.appc.artifact.handler.dbservices.DBException;
98 import org.onap.appc.artifact.handler.dbservices.DBService;
99 import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtil;
100 import org.onap.appc.yang.YANGGenerator;
101 import org.onap.appc.yang.impl.YANGGeneratorFactory;
102 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
103 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
104 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
105 import org.onap.sdnc.config.params.transformer.tosca.ArtifactProcessorImpl;
106 import org.onap.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException;
107
108 import org.json.JSONException;
109 import java.util.ArrayList;
110 import java.util.HashMap;
111 import java.util.List;
112
113 public class ArtifactHandlerNode implements SvcLogicJavaPlugin {
114
115     private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerNode.class);
116     private static final String TOSCA_PARAM = "Tosca";
117     private static final String YANG_PARAM = "Yang";
118     private static final String ARTIFACT_LIST_PARAM = "artifact-list";
119     private static final String CONFIGURE_PARAM = "Configure";
120     private static final String CONFIG_SCALE_OUT_PARAM = "ConfigScaleOut";
121     private static final String CONFIG_MODIFY_PARAM = "ConfigModify";
122
123     public void processArtifact(Map<String, String> inParams, SvcLogicContext ctx) throws ArtifactProcessorException {
124
125         if (inParams == null || inParams.isEmpty()) {
126             return;
127         }
128         String postData = inParams.get("postData");
129         if ( StringUtils.isBlank(postData)) {
130             return;
131         }
132         try {
133             log.info("Received request for process Artifact with params: " + inParams.toString());
134             JSONObject input = new JSONObject(postData).getJSONObject("input");
135             storeUpdateSdcArtifacts(input);
136         } catch (Exception e) {
137             log.error("Error when processing artifact", e);
138             throw new ArtifactProcessorException("Error occurred while processing artifact, " + e.getMessage(), e);
139         }
140     }
141
142     private boolean storeUpdateSdcArtifacts(JSONObject postDataJson) throws ArtifactHandlerInternalException {
143         log.info("Starting processing of SDC Artifacs into Handler with Data : " + postDataJson.toString());
144         try {
145             JSONObject requestInfo = (JSONObject) postDataJson.get(REQUEST_INFORMATION);
146             JSONObject documentInfo = (JSONObject) postDataJson.get(DOCUMENT_PARAMETERS);
147             String artifactName = documentInfo.getString(ARTIFACT_NAME);
148
149             if (StringUtils.isBlank(artifactName))
150                 throw new ArtifactHandlerInternalException("Missing Artifact Name ");
151
152             if (artifactName.toLowerCase().startsWith(ANSIBLE)) {
153                 validateAnsibleAdminArtifact(documentInfo);
154                 log.info("validateAnsibleAdminArtifact sucessfully done");
155             }
156
157             updateStoreArtifacts(requestInfo, documentInfo);
158             if (artifactName.toLowerCase().startsWith(REFERENCE)) {
159                 return storeReferenceData(requestInfo, documentInfo);
160             } else if (artifactName.toLowerCase().startsWith(PD)) {
161                 return createDataForPD(requestInfo, documentInfo);
162             }
163
164         } catch (Exception e) {
165             log.error("Error while processing request with id: "
166                     + ((JSONObject) postDataJson.get(REQUEST_INFORMATION)).getString(REQUEST_ID), e);
167             throw new ArtifactHandlerInternalException("Error while processing request with id: "
168                     + ((JSONObject) postDataJson.get(REQUEST_INFORMATION)).getString(REQUEST_ID)
169                     + ", Exception Message : " + e.getMessage(), e);
170         }
171         return false;
172     }
173
174     public void validateAnsibleAdminArtifact(JSONObject documentInfo) throws ArtifactHandlerInternalException {
175         String fn = "ArtifactHandlerNode.validateAnsibleAdminArtifact";
176         String artifactName = documentInfo.getString(ARTIFACT_NAME);
177         log.info(fn + ": Received Admin File Name: " + artifactName + " ArtifactCotent : "
178                 + documentInfo.getString(ARTIFACT_CONTENTS));
179         try {
180             ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
181             String contentString = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_CONTENTS));
182             JSONObject artifact = new JSONObject(contentString);
183             JSONArray fqdnList = artifact.getJSONArray("fqdn-list");
184             Map<String, List<String>> artifactMap = new HashMap<>();
185             
186             
187             for (int i = 0; i < fqdnList.length(); i++) {
188                 JSONObject fqdn = fqdnList.getJSONObject(i);
189                 List<String> valuesforFQDN = populateValueForFQDN(fqdn);
190                 artifactMap.put(fqdn.getString("vnf-management-server-fqdn"), valuesforFQDN);
191             }
192
193             validateKeyValue(artifactMap);
194
195         } catch (JSONException je) {
196             log.error(
197                     fn + " ansible_admin artifact content may not be a valid JSON, error message : " + je.getMessage());
198             throw new ArtifactHandlerInternalException(
199                     "JSON Exception:ansible admin artifact content may not be a valid JSON, error message : " + je.getMessage(), je);
200         } catch (ArtifactHandlerInternalException ae) {
201          throw ae;
202         } catch (Exception e) {
203             
204             log.error(fn + "Error while creating Admin data records", e);
205             throw new ArtifactHandlerInternalException("Error while processing ansible admin artifact" + e.getMessage(), e);
206         }
207
208     }
209     private void validateKeyValue(Map<String, List<String>> artifactMap) throws ArtifactHandlerInternalException {
210         for (Map.Entry<String,List<String>> entry1:artifactMap.entrySet()) {    
211             for (String value : entry1.getValue()) {
212                 for(Map.Entry<String,List<String>> entry2:artifactMap.entrySet() ) {                                      
213                     if (!entry1.getKey().equals(entry2.getKey()) && entry2.getValue().contains(value)) {
214                         log.info("Validation Failure, error message : Ansible Admin artifact has CloudOwner-RegionId-Tenant : " + value
215                                 + " mapped to multiple FQDN :" + entry1.getKey() + " & " + entry2.getKey());
216                         throw new ArtifactHandlerInternalException(
217                                 "Validation Failure, error message : Ansible Admin artifact has CloudOwner-RegionId-Tenant : " + value
218                                 + " mapped to multiple FQDN :" + entry1.getKey() + " & " + entry2.getKey());
219                     }
220
221
222                 }
223             }
224     }
225 }
226
227     private List<String> populateValueForFQDN(JSONObject fqdn) {
228         log.info("Inside populateValueForFQDN :" + fqdn.getString("vnf-management-server-fqdn"));
229         List<String> valuesforFQDN = new ArrayList<>();
230         JSONArray cloudJsonList = fqdn.getJSONArray("cloud-owner-list");
231         for (int j = 0; j < cloudJsonList.length(); j++) {
232             String cloudOwner = cloudJsonList.getJSONObject(j).getString("cloud-owner");
233             JSONArray regionList = cloudJsonList.getJSONObject(j).getJSONArray("region-id-list");
234             for (int i = 0; i < regionList.length(); i++) {
235                 String region = regionList.getJSONObject(i).getString("region-id");
236                 JSONArray tenantList = regionList.getJSONObject(i).getJSONArray("tenant-id-list");
237
238                 for (int k = 0; k < tenantList.length(); k++) {
239                     String tenant =  tenantList.getString(k);
240                     String valueforFQDN = cloudOwner + "-" + region + "-" + tenant;
241                     log.info("valueforFQDN for i " + i + " & j " + j + " :" + valueforFQDN);
242                     valuesforFQDN.add(valueforFQDN);
243                 }
244             }
245         }
246         return valuesforFQDN;
247     }
248
249     private boolean createDataForPD(JSONObject requestInfo, JSONObject documentInfo)
250             throws ArtifactHandlerInternalException {
251
252         String fn = "ArtifactHandlerNode.createReferenceDataForPD";
253         String artifactName = documentInfo.getString(ARTIFACT_NAME);
254         log.info(fn + "Received PD File Name: " + artifactName + " and suffix length " + PD.length());
255         try {
256
257             String suffix = artifactName.substring(PD.length());
258             createArtifactRecords(requestInfo, documentInfo, suffix);
259         } catch (Exception e) {
260             log.error("Error while creating PD data records", e);
261             throw new ArtifactHandlerInternalException("Error while creating PD data records", e);
262         }
263         return true;
264     }
265
266     private void createArtifactRecords(JSONObject requestInfo, JSONObject documentInfo, String suffix)
267             throws ArtifactHandlerInternalException {
268
269         try {
270             log.info("Creating Tosca Records and storing into SDC Artifacs");
271             String[] docs = { TOSCA_PARAM, YANG_PARAM };
272             ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
273             String pdFileContents = documentInfo.getString(ARTIFACT_CONTENTS);
274
275             // Tosca generation
276             OutputStream toscaStream = new ByteArrayOutputStream();
277             String toscaContents;
278             ArtifactProcessorImpl toscaGenerator = getArtifactProcessorImpl();
279             toscaGenerator.generateArtifact(pdFileContents, toscaStream);
280             toscaContents = toscaStream.toString();
281             log.info("Generated Tosca File : " + toscaContents);
282
283             String yangContents = "YANG generation is in Progress";
284             String yangName = null;
285
286             for (String doc : docs) {
287                 documentInfo.put(ARTIFACT_TYPE, doc.concat("Type"));
288                 documentInfo.put(ARTIFACT_DESRIPTION, doc.concat("Model"));
289                 if (doc.equals(TOSCA_PARAM)) {
290                     documentInfo.put(ARTIFACT_CONTENTS, ahpUtil.escapeSql(toscaContents));
291                 } else if (doc.equals(YANG_PARAM)) {
292                     documentInfo.put(ARTIFACT_CONTENTS, ahpUtil.escapeSql(yangContents));
293                 }
294                 documentInfo.put(ARTIFACT_NAME, doc.concat(suffix));
295                 yangName = doc.concat(suffix);
296                 updateStoreArtifacts(requestInfo, documentInfo);
297             }
298
299             String artifactId = getArtifactID(yangName);
300             OutputStream yangStream = new ByteArrayOutputStream();
301             YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator();
302             yangGenerator.generateYANG(artifactId, toscaContents, yangStream);
303             yangContents = yangStream.toString();
304
305             if (yangContents != null) {
306                 updateYangContents(artifactId, ahpUtil.escapeSql(yangContents));
307             }
308         } catch (Exception e) {
309             log.error("Error while creating artifact records", e);
310             throw new ArtifactHandlerInternalException("Error while creating artifact records", e);
311         }
312
313     }
314
315     private void updateYangContents(String artifactId, String yangContents) throws SvcLogicException {
316         SvcLogicContext context = new SvcLogicContext();
317         DBService dbservice = DBService.initialise();
318         dbservice.updateYangContents(context, artifactId, yangContents);
319     }
320
321     private String getArtifactID(String yangName) throws SvcLogicException {
322         SvcLogicContext context = new SvcLogicContext();
323         DBService dbservice = DBService.initialise();
324         return dbservice.getArtifactID(context, yangName);
325     }
326
327     protected boolean updateStoreArtifacts(JSONObject requestInfo, JSONObject documentInfo) throws SvcLogicException {
328         log.info("UpdateStoreArtifactsStarted storing of SDC Artifacs ");
329         SvcLogicContext context = new SvcLogicContext();
330         DBService dbservice = DBService.initialise();
331         ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
332         int intversion = 0;
333         context.setAttribute("artifact_name", documentInfo.getString(ARTIFACT_NAME));
334         String internalVersion = dbservice.getInternalVersionNumber(context, documentInfo.getString(ARTIFACT_NAME),
335                 null);
336         log.info("Internal Version number received from Database : " + internalVersion);
337         if (internalVersion != null) {
338             intversion = Integer.parseInt(internalVersion);
339             intversion++;
340         }
341         setAttribute(context, documentInfo::getString, SERVICE_UUID);
342         setAttribute(context, documentInfo::getString, DISTRIBUTION_ID);
343         setAttribute(context, documentInfo::getString, SERVICE_NAME);
344         setAttribute(context, documentInfo::getString, SERVICE_DESCRIPTION);
345         setAttribute(context, documentInfo::getString, RESOURCE_UUID);
346         setAttribute(context, documentInfo::getString, RESOURCE_INSTANCE_NAME);
347         setAttribute(context, documentInfo::getString, RESOURCE_VERSION);
348         setAttribute(context, documentInfo::getString, RESOURCE_TYPE);
349         setAttribute(context, documentInfo::getString, ARTIFACT_UUID);
350         setAttribute(context, documentInfo::getString, ARTIFACT_TYPE);
351         setAttribute(context, documentInfo::getString, ARTIFACT_VERSION);
352         setAttribute(context, documentInfo::getString, ARTIFACT_DESRIPTION);
353         setAttribute(context, documentInfo::getString, ARTIFACT_NAME);
354         setAttribute(context, s -> ahpUtil.escapeSql(documentInfo.getString(s)), ARTIFACT_CONTENTS);
355
356         dbservice.saveArtifacts(context, intversion);
357         return true;
358     }
359
360     public boolean storeReferenceData(JSONObject requestInfo, JSONObject documentInfo)
361             throws ArtifactHandlerInternalException {
362
363         log.info("Started storing of SDC Artifacs into Handler");
364         try {
365             DBService dbservice = DBService.initialise();
366             ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
367             String contentString = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_CONTENTS));
368             String artifactName = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_NAME));
369             String capabilityArtifactName = StringUtils.replace(artifactName, ARTIFACT_NAME_REFERENCE,
370                     ARTIFACT_NAME_CAPABILITY);
371             JSONObject capabilities = new JSONObject();
372             JSONArray vnfActionList = new JSONArray();
373             JSONArray vfModuleActionList = new JSONArray();
374             JSONArray vnfcActionList = new JSONArray();
375             JSONArray vmActionVnfcFunctionCodesList = new JSONArray();
376             String vnfType = null;
377             JSONObject contentObject = new JSONObject(contentString);
378             JSONArray contentArray = contentObject.getJSONArray("reference_data");
379             boolean storeCapabilityArtifact = true;
380             for (int a = 0; a < contentArray.length(); a++) {
381                 JSONObject content = (JSONObject) contentArray.get(a);
382                 log.info("contentString =" + content.toString());
383                 JSONObject scope = content.getJSONObject("scope");
384                 log.info("scope :" + scope);
385                 SvcLogicContext context = new SvcLogicContext();
386                 vnfType = scope.getString(VNF_TYPE);
387                 setAttribute(context, scope::getString, VNF_TYPE);
388                 setAttribute(context, content::getString, ACTION);
389                 String actionLevel = content.getString(ACTION_LEVEL);
390                 setAttribute(context, content::getString, ACTION_LEVEL);
391                 setAttribute(context, documentInfo::getString, ARTIFACT_TYPE);
392                 processActionLists(content, actionLevel, vnfcActionList, vfModuleActionList, vnfActionList,
393                         vmActionVnfcFunctionCodesList);
394                 JSONArray vnfcTypeList = setVnfcTypeInformation(scope, context);
395                 storeCapabilityArtifact = isCapabilityArtifactNeeded(context);
396                 if (content.has(DEVICE_PROTOCOL)) {
397                     setAttribute(context, content::getString, DEVICE_PROTOCOL);
398                 }
399                 if (content.has(USER_NAME)) {
400                     setAttribute(context, content::getString, USER_NAME);
401                 }
402                 if (content.has(PORT_NUMBER)) {
403                     setAttribute(context, content::getString, PORT_NUMBER);
404                 }
405                 if (content.has(URL)) {
406                     setAttribute(context, content::getString, URL);
407                 }
408                 processArtifactList(content, dbservice, context, vnfcTypeList);
409                 processConfigTypeActions(content, dbservice, context);
410                 dbservice.processDeviceAuthentication(context,
411                         dbservice.isArtifactUpdateRequired(context, DB_DEVICE_AUTHENTICATION));
412
413                 String actionProtocol = tryGetProtocol(content);
414                 if (!StringUtils.equalsIgnoreCase(actionProtocol, OPENSTACK)) {
415                     populateProtocolReference(dbservice, content);
416                 }
417
418                 context.setAttribute(VNFC_TYPE, null);
419
420                 if (content.has(VM) && content.get(VM) instanceof JSONArray) {
421                     processVmList(content, context, dbservice);
422                 }
423             }
424             if (storeCapabilityArtifact) {
425                 capabilities.put("vnf", vnfActionList);
426                 capabilities.put("vf-module", vfModuleActionList);
427                 capabilities.put("vnfc", vnfcActionList);
428                 capabilities.put("vm", vmActionVnfcFunctionCodesList);
429                 processAndStoreCapabilitiesArtifact(dbservice, documentInfo, capabilities, capabilityArtifactName,
430                         vnfType);
431             }
432
433         } catch (Exception e) {
434
435             log.error("Error while storing reference data", e);
436             throw new ArtifactHandlerInternalException("Error while storing reference data", e);
437         }
438
439         return true;
440     }
441
442     public boolean isCapabilityArtifactNeeded(SvcLogicContext context) {
443         String vnfcType = context.getAttribute(VNFC_TYPE);
444         if (StringUtils.isNotBlank(vnfcType)) {
445             log.info("No capability Artifact for this reference data as it is at VNFC level!!");
446             return false;
447         } else {
448             return true;
449         }
450     }
451
452     public JSONArray setVnfcTypeInformation(JSONObject scope, SvcLogicContext context) {
453         JSONArray vnfcTypeList = null;
454         if (scope.has(VNFC_TYPE) && !scope.isNull(VNFC_TYPE)) {
455             String vnfcTypeScope = scope.getString(VNFC_TYPE);
456             if (StringUtils.isNotBlank(vnfcTypeScope)) {
457                 setAttribute(context, scope::getString, VNFC_TYPE);
458                 log.info("VNFC Type has been set for this reference artifact!!" + vnfcTypeScope);
459             } else {
460                 context.setAttribute(VNFC_TYPE, null);
461             }
462         } else {
463             context.setAttribute(VNFC_TYPE, null);
464         }
465         if (scope.has(VNFC_TYPE_LIST) && !scope.isNull(VNFC_TYPE_LIST)
466                 && scope.get(VNFC_TYPE_LIST) instanceof JSONArray) {
467             vnfcTypeList = scope.getJSONArray(VNFC_TYPE_LIST);
468             log.info("VNFC TYPE LIST found for this artifact!! " + vnfcTypeList.toString());
469         }
470         return vnfcTypeList;
471     }
472
473     public void processActionLists(JSONObject content, String actionLevel, JSONArray vnfcActionList,
474             JSONArray vfModuleActionList, JSONArray vnfActionList, JSONArray vmActionVnfcFunctionCodesList) {
475         if (validateActionLevel(actionLevel, ACTION_LEVEL_VNFC)) {
476             vnfcActionList.put(content.getString(ACTION));
477         }
478         if (validateActionLevel(actionLevel, ACTION_LEVEL_VF_MODULE)) {
479             vfModuleActionList.put(content.getString(ACTION));
480         }
481         if (validateActionLevel(actionLevel, ACTION_LEVEL_VNF)) {
482             vnfActionList.put(content.getString(ACTION));
483         }
484         if (validateActionLevel(actionLevel, ACTION_LEVEL_VM)) {
485             if (content.has(VNFC_FUNCTION_CODE_LIST) && !content.isNull(VNFC_FUNCTION_CODE_LIST)
486                     && content.get(VNFC_FUNCTION_CODE_LIST) instanceof JSONArray) {
487                 log.info("Found vnfc-function-code-list!!");
488                 JSONArray vnfcList = content.getJSONArray(VNFC_FUNCTION_CODE_LIST);
489                 JSONObject obj = new JSONObject();
490                 obj.put(content.getString(ACTION), vnfcList);
491                 vmActionVnfcFunctionCodesList.put(obj);
492             } else {
493                 log.info("Not getting JSONArray for VNFC FUNCTION CODES");
494             }
495         }
496
497     }
498
499     private boolean validateActionLevel(String actionLevel, String actionLevelVnfc) {
500         return null != actionLevel && actionLevel.equalsIgnoreCase(actionLevelVnfc);
501     }
502
503     public void processArtifactList(JSONObject content, DBService dbservice, SvcLogicContext context,
504             JSONArray vnfcTypeList) throws ArtifactHandlerInternalException {
505
506         try {
507             if (content.has(ARTIFACT_LIST_PARAM) && content.get(ARTIFACT_LIST_PARAM) instanceof JSONArray) {
508                 JSONArray artifactLists = (JSONArray) content.get(ARTIFACT_LIST_PARAM);
509                 JSONArray templateIdList = null;
510                 if (content.has("template-id-list") && null != content.get("template-id-list")
511                         && content.get("template-id-list") instanceof JSONArray) {
512                     templateIdList = content.getJSONArray("template-id-list");
513                 }
514                 doProcessArtifactList(dbservice, context, artifactLists, templateIdList, vnfcTypeList);
515
516             }
517         } catch (Exception e) {
518             log.error("An error occurred when processing artifact list", e);
519             throw new ArtifactHandlerInternalException(e);
520         }
521     }
522
523     private void doProcessArtifactList(DBService dbservice, SvcLogicContext context, JSONArray artifactLists,
524             JSONArray templateIdList, JSONArray vnfcTypeList)
525             throws SvcLogicException, SQLException, ConfigurationException, DBException {
526         boolean pdFile = false;
527         int modelInd = 0, vnfcRefInd = 0;
528         for (int i = 0; i < artifactLists.length(); i++) {
529             String suffix = null;
530             String model = null;
531             JSONObject artifact = (JSONObject) artifactLists.get(i);
532             log.info("artifact is " + artifact);
533
534             // Get Model details
535             if (null != templateIdList && i > 0 && i % 2 == 0) {// Should this be changed to 3 to account for 3
536                                                                 // artifacts
537                 modelInd++;
538             }
539             if (null != vnfcTypeList && i > 0 && i % 3 == 0) {
540                 // TDP 517180 - CD tool has made changes to send 3 artifacts instead of 2
541                 vnfcRefInd++;
542             }
543             setAttribute(context, artifact::getString, ARTIFACT_NAME);
544             context.setAttribute(FILE_CATEGORY, artifact.getString(ARTIFACT_TYPE));
545
546             if (artifact.getString(ARTIFACT_NAME) != null
547                     && artifact.getString(ARTIFACT_NAME).toLowerCase().startsWith(PD)) {
548
549                 suffix = artifact.getString(ARTIFACT_NAME).substring(PD.length());
550                 pdFile = true;
551             }
552             log.info("Artifact-type = " + context.getAttribute(FILE_CATEGORY));
553             log.info("Artifact-name = " + context.getAttribute(ARTIFACT_NAME));
554
555             if (null != templateIdList && modelInd < templateIdList.length()) {
556                 model = templateIdList.getString(modelInd);
557                 log.info("Model is ::: " + model + "  ,modelInd = " + modelInd);
558             }
559             if (null != vnfcTypeList && vnfcRefInd < vnfcTypeList.length()) {
560                 String vnfcType = vnfcTypeList.getString(vnfcRefInd);
561                 if (StringUtils.isNotBlank(vnfcType)) {
562                     context.setAttribute(VNFC_TYPE, vnfcType);
563                 }
564                 log.info("Setting vnfc type from vnfc-type-list ::" + vnfcType);
565             }
566             if (StringUtils.isNotBlank(model)) {
567                 dbservice.processSdcReferences(context,
568                         dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model), model);
569             } else {
570                 dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE));
571             }
572
573             cleanArtifactInstanceData(context);
574             // Moving this into the for loop to account for mulitple artifact sets with pds
575             if (pdFile) {
576                 log.info("Sending information related to pdfile Artifact");
577                 tryUpdateContext(dbservice, context, pdFile, suffix, model);
578                 pdFile = false;// set to false afterprocessing yang and Tosca
579             }
580         }
581
582     }
583
584     private void tryUpdateContext(DBService dbservice, SvcLogicContext context, boolean pdFile, String suffix,
585             String model) throws SvcLogicException, SQLException, ConfigurationException, DBException {
586         if (pdFile) {
587             context.setAttribute(ARTIFACT_NAME, "Tosca".concat(suffix));
588             context.setAttribute(FILE_CATEGORY, TOSCA_MODEL);
589             dbservice.processSdcReferences(context,
590                     dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model), model);
591             context.setAttribute(ARTIFACT_NAME, "Yang".concat(suffix));
592             context.setAttribute(FILE_CATEGORY, PARAMETER_YANG);
593             dbservice.processSdcReferences(context,
594                     dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model), model);
595         }
596     }
597
598     public void processConfigTypeActions(JSONObject content, DBService dbservice, SvcLogicContext context)
599             throws ArtifactHandlerInternalException {
600
601         try {
602             if (contentsActionEquals(content, CONFIGURE_PARAM) || contentsActionEquals(content, CONFIG_MODIFY_PARAM)
603                     || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)) {
604
605                 if (content.has(DOWNLOAD_DG_REFERENCE) && content.getString(DOWNLOAD_DG_REFERENCE).length() > 0) {
606
607                     setAttribute(context, content::getString, DOWNLOAD_DG_REFERENCE);
608                     dbservice.processDownloadDgReference(context,
609                             dbservice.isArtifactUpdateRequired(context, DB_DOWNLOAD_DG_REFERENCE));
610                 }
611                 if (StringUtils.isBlank(context.getAttribute(DOWNLOAD_DG_REFERENCE))) {
612                     context.setAttribute(DOWNLOAD_DG_REFERENCE, dbservice.getDownLoadDGReference(context));
613                 }
614                 dbservice.processConfigActionDg(context,
615                         dbservice.isArtifactUpdateRequired(context, DB_CONFIG_ACTION_DG));
616
617                 tryProcessInterfaceProtocol(content, dbservice, context);
618             }
619         } catch (Exception e) {
620             log.error("An error occurred when processing config type actions", e);
621             throw new ArtifactHandlerInternalException(e);
622         }
623     }
624
625     private void tryProcessInterfaceProtocol(JSONObject content, DBService dbservice, SvcLogicContext context)
626             throws SvcLogicException, SQLException, ConfigurationException, DBException {
627
628         if (contentsActionEquals(content, CONFIGURE_PARAM) || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)) {
629             boolean isUpdateRequired = dbservice.isArtifactUpdateRequired(context, DB_DEVICE_INTERFACE_PROTOCOL);
630             if (contentsActionEquals(content, CONFIGURE_PARAM)
631                     || (contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM) && !isUpdateRequired)) {
632
633                 dbservice.processDeviceInterfaceProtocol(context, isUpdateRequired);
634             }
635         }
636     }
637
638     private boolean contentsActionEquals(JSONObject content, String action) {
639         return content.getString(ACTION).equals(action);
640     }
641
642     public void processVmList(JSONObject content, SvcLogicContext context, DBService dbservice)
643             throws SvcLogicException {
644         JSONArray vmList = (JSONArray) content.get(VM);
645         dbservice.cleanUpVnfcReferencesForVnf(context);
646         for (int i = 0; i < vmList.length(); i++) {
647             JSONObject vmInstance = (JSONObject) vmList.get(i);
648             setAttribute(context, s -> String.valueOf(vmInstance.getInt(s)), VM_INSTANCE);
649             log.info("VALUE = " + context.getAttribute(VM_INSTANCE));
650             String templateId = vmInstance.optString(TEMPLATE_ID);
651             trySetContext(context, vmInstance, templateId);
652             if (vmInstance.get(VNFC) instanceof JSONArray) {
653                 JSONArray vnfcInstanceList = (JSONArray) vmInstance.get(VNFC);
654                 for (int k = 0; k < vnfcInstanceList.length(); k++) {
655                     JSONObject vnfcInstance = (JSONObject) vnfcInstanceList.get(k);
656
657                     setAttribute(context, s -> String.valueOf(vnfcInstance.getInt(s)), VNFC_INSTANCE);
658                     setAttribute(context, vnfcInstance::getString, VNFC_TYPE);
659                     setAttribute(context, vnfcInstance::getString, VNFC_FUNCTION_CODE);
660                     resolveContext(context, vnfcInstance);
661                     tryProcessVnfcReference(content, context, dbservice);
662                     cleanVnfcInstance(context);
663                 }
664                 context.setAttribute(VM_INSTANCE, null);
665                 context.setAttribute(TEMPLATE_ID, null);
666             }
667         }
668     }
669
670     private void trySetContext(SvcLogicContext context, JSONObject vmInstance, String templateId) {
671         if (StringUtils.isNotBlank(templateId)) {
672             setAttribute(context, vmInstance::optString, TEMPLATE_ID);
673         }
674     }
675
676     private void tryProcessVnfcReference(JSONObject content, SvcLogicContext context, DBService dbservice)
677             throws SvcLogicException {
678         if (content.getString(ACTION).equals(CONFIGURE_PARAM)
679                 || content.getString(ACTION).equals(CONFIG_SCALE_OUT_PARAM)) {
680
681             dbservice.processVnfcReference(context, false);
682         }
683     }
684
685     private void resolveContext(SvcLogicContext context, JSONObject vnfcInstance) {
686         if (vnfcInstance.has(IPADDRESS_V4_OAM_VIP)) {
687             setAttribute(context, vnfcInstance::getString, IPADDRESS_V4_OAM_VIP);
688         }
689         if (vnfcInstance.has(GROUP_NOTATION_TYPE)) {
690             setAttribute(context, vnfcInstance::getString, GROUP_NOTATION_TYPE);
691         }
692         if (vnfcInstance.has(GROUP_NOTATION_VALUE)) {
693             setAttribute(context, vnfcInstance::getString, GROUP_NOTATION_VALUE);
694         }
695     }
696
697     private void cleanArtifactInstanceData(SvcLogicContext context) {
698         context.setAttribute(ARTIFACT_NAME, null);
699         context.setAttribute(FILE_CATEGORY, null);
700     }
701
702     private void cleanVnfcInstance(SvcLogicContext context) {
703
704         context.setAttribute(VNFC_INSTANCE, null);
705         context.setAttribute(VNFC_TYPE, null);
706         context.setAttribute(VNFC_FUNCTION_CODE, null);
707         context.setAttribute(IPADDRESS_V4_OAM_VIP, null);
708         context.setAttribute(GROUP_NOTATION_TYPE, null);
709         context.setAttribute(GROUP_NOTATION_VALUE, null);
710
711     }
712
713     private void processAndStoreCapabilitiesArtifact(DBService dbService, JSONObject documentInfo,
714             JSONObject capabilities, String capabilityArtifactName, String vnfType)
715             throws ArtifactHandlerInternalException {
716
717         log.info("Begin-->processAndStoreCapabilitiesArtifact ");
718
719         try {
720             JSONObject newCapabilitiesObject = new JSONObject();
721             newCapabilitiesObject.put("capabilities", capabilities);
722             SvcLogicContext context = new SvcLogicContext();
723             context.setAttribute(ARTIFACT_NAME, capabilityArtifactName);
724             context.setAttribute(FILE_CATEGORY, CAPABILITY);
725             context.setAttribute(ACTION, null);
726             context.setAttribute(VNFC_TYPE, null);
727             context.setAttribute(ARTIFACT_TYPE, null);
728             context.setAttribute(VNF_TYPE, vnfType);
729             context.setAttribute(ARTIFACT_CONTENTS, newCapabilitiesObject.toString());
730             dbService.processSdcReferences(context, dbService.isArtifactUpdateRequired(context, DB_SDC_REFERENCE));
731             int intVersion = 0;
732             String internalVersion = dbService.getInternalVersionNumber(context, context.getAttribute(ARTIFACT_NAME),
733                     null);
734             log.info("Internal Version number received from Database : " + internalVersion);
735             if (internalVersion != null) {
736                 intVersion = Integer.parseInt(internalVersion) + 1;
737             }
738             setAttribute(context, documentInfo::getString, SERVICE_UUID);
739             setAttribute(context, documentInfo::getString, DISTRIBUTION_ID);
740             setAttribute(context, documentInfo::getString, SERVICE_NAME);
741             setAttribute(context, documentInfo::getString, SERVICE_DESCRIPTION);
742             setAttribute(context, documentInfo::getString, RESOURCE_UUID);
743             setAttribute(context, documentInfo::getString, RESOURCE_INSTANCE_NAME);
744             setAttribute(context, documentInfo::getString, RESOURCE_VERSION);
745             setAttribute(context, documentInfo::getString, RESOURCE_TYPE);
746             setAttribute(context, documentInfo::getString, ARTIFACT_UUID);
747             setAttribute(context, documentInfo::getString, ARTIFACT_VERSION);
748             setAttribute(context, documentInfo::getString, ARTIFACT_DESRIPTION);
749             dbService.saveArtifacts(context, intVersion);
750         } catch (Exception e) {
751             log.error("Error saving capabilities artifact to DB", e);
752             throw new ArtifactHandlerInternalException("Error saving capabilities artifact to DB", e);
753         } finally {
754             log.info("End-->processAndStoreCapabilitiesArtifact ");
755         }
756     }
757
758     private void setAttribute(SvcLogicContext context, Function<String, String> value, String key) {
759         context.setAttribute(key, value.apply(key));
760     }
761
762     private void populateProtocolReference(DBService dbservice, JSONObject content)
763             throws ArtifactHandlerInternalException {
764         log.info("Begin-->populateProtocolReference ");
765         try {
766             SvcLogicContext context = new SvcLogicContext();
767             JSONObject scope = content.getJSONObject("scope");
768             String vnfType = tryGetVnfType(scope);
769             String protocol = tryGetProtocol(content);
770             String action = tryGetAction(content);
771             String actionLevel = tryGetActionLevel(content);
772             String template = tryGetTemplate(content);
773
774             boolean isUpdateNeeded = dbservice.isProtocolReferenceUpdateRequired(context, vnfType, protocol, action,
775                     actionLevel, template);
776             if (isUpdateNeeded) {
777                 dbservice.updateProtocolReference(context, vnfType, protocol, action, actionLevel, template);
778             } else {
779                 dbservice.insertProtocolReference(context, vnfType, protocol, action, actionLevel, template);
780             }
781         } catch (Exception e) {
782             log.error("Error inserting record into protocolReference", e);
783             throw new ArtifactHandlerInternalException("Error inserting record into protocolReference", e);
784         } finally {
785             log.info("End-->populateProtocolReference ");
786         }
787     }
788
789     private String tryGetVnfType(JSONObject scope) {
790         if (scope.has(VNF_TYPE) && !scope.isNull(VNF_TYPE)) {
791             return scope.getString(VNF_TYPE);
792         }
793         return null;
794     }
795
796     private String tryGetProtocol(JSONObject content) {
797         if (content.has(DEVICE_PROTOCOL)) {
798             return content.getString(DEVICE_PROTOCOL);
799         }
800         return null;
801     }
802
803     private String tryGetAction(JSONObject content) {
804         if (content.has(ACTION)) {
805             return content.getString(ACTION);
806         }
807         return null;
808     }
809
810     private String tryGetActionLevel(JSONObject content) {
811         if (content.has(ACTION_LEVEL)) {
812             return content.getString(ACTION_LEVEL);
813         }
814         return null;
815     }
816
817     private String tryGetTemplate(JSONObject content) {
818         if (content.has(TEMPLATE) && !content.isNull(TEMPLATE)) {
819             return content.getString(TEMPLATE);
820         }
821         return null;
822     }
823
824     protected ArtifactProcessorImpl getArtifactProcessorImpl() {
825         return new ArtifactProcessorImpl();
826     }
827 }