e1c76ecf8d090dc14b158d5cc5ee8812e4d3df06
[appc.git] / appc-inbound / appc-artifact-handler / provider / src / main / java / org / onap / appc / artifact / handler / dbservices / DBService.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  * 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.artifact.handler.dbservices;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import org.apache.commons.configuration.ConfigurationException;
29 import org.apache.commons.configuration.PropertiesConfiguration;
30 import org.apache.commons.lang.StringUtils;
31 import org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants;
32 import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource;
33 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
34 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
35 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus;
37
38 public class DBService {
39
40     private static final EELFLogger log = EELFManager.getInstance().getLogger(DBService.class);
41     private static final String FAILURE_PARAM = "FAILURE";
42     private static final String RECEIVED_AS = "Internal Version received as1 : ";
43     private static final String SET_DOWNLOAD_CONFIG_QUERY_STR = " set DOWNLOAD_CONFIG_DG = $";
44     private static final String WHERE_VNF_TYPE_QUERY_STR = " where VNF_TYPE = $";
45     private static final String ACTION_QUERY_STR = " , ACTION = $";
46     private static final String VNF_TYPE_QUERY_STR = " , VNF_TYPE = $";
47     private static final String INSERT_INTO_QUERY_STR = "insert into ";
48     private static final String AND_ACTION_QUERY_STR = " and ACTION = $";
49     private static final String AND_FILE_CAT_QUERY_STR = " and FILE_CATEGORY = $";
50     private static final String AND_VNF_TYPE_QUERY_STR = " and VNF_TYPE = $";
51     private static final String UPDATE_QUERY_STR = "update ";
52     private static final String AND_VNFC_TYPE_QUERY_STR = " and VNFC_TYPE = $";
53
54     private SvcLogicResource serviceLogic;
55     private static DBService dgGeneralDBService = null;
56
57     private DBService() {
58         if (serviceLogic == null) {
59             serviceLogic = new SqlResource();
60         }
61     }
62
63     protected DBService(SqlResource svcLogic) {
64         if (serviceLogic == null) {
65             serviceLogic = svcLogic;
66         }
67     }
68
69     public static DBService initialise() {
70         if (dgGeneralDBService == null) {
71             dgGeneralDBService = new DBService();
72         }
73         return dgGeneralDBService;
74     }
75
76     public String getInternalVersionNumber(SvcLogicContext ctx, String artifactName, String prefix)
77         throws SvcLogicException {
78         QueryStatus status;
79         String artifactInternalVersion = null;
80         if (serviceLogic != null && ctx != null) {
81             String key = "select max(internal_version) as maximum from ASDC_ARTIFACTS  WHERE ARTIFACT_NAME = '"
82                 + artifactName + "'";
83             log.info("Getting internal Versoin :" + key);
84             status = serviceLogic.query("SQL", false, null, key, prefix, null, ctx);
85             if (status.toString().equals(FAILURE_PARAM)) {
86                 throw new SvcLogicException("Error - getting internal Artifact Number");
87             }
88             artifactInternalVersion = ctx.getAttribute("maximum");
89             log.info("Internal Version received as : " + artifactInternalVersion);
90             log.info(RECEIVED_AS + ctx.getAttribute("max(internal_version)"));
91             log.info(RECEIVED_AS + ctx.getAttribute("max"));
92             log.info(RECEIVED_AS + ctx.getAttribute("internal_version"));
93             log.info(RECEIVED_AS + ctx.getAttributeKeySet().toString());
94         }
95         return artifactInternalVersion;
96     }
97
98     public String getArtifactID(SvcLogicContext ctx, String artifactName) throws SvcLogicException {
99         QueryStatus status;
100         String artifactID = null;
101         if (serviceLogic != null && ctx != null) {
102             String key = "select max(ASDC_ARTIFACTS_ID) as id from ASDC_ARTIFACTS  WHERE ARTIFACT_NAME = '"
103                 + artifactName + "'";
104             log.info("Getting Artifact ID String :" + key);
105             status = serviceLogic.query("SQL", false, null, key, null, null, ctx);
106             if (status.toString().equals(FAILURE_PARAM)) {
107                 throw new SvcLogicException("Error - getting  Artifact ID from database");
108             }
109             artifactID = ctx.getAttribute("id");
110             log.info("SDC_ARTIFACTS_ID received as : " + ctx.getAttribute("id"));
111         }
112         return artifactID;
113     }
114
115     public QueryStatus saveArtifacts(SvcLogicContext ctx, int intversion) throws SvcLogicException {
116         QueryStatus status = null;
117         if (serviceLogic != null && ctx != null) {
118             String key = "INSERT INTO ASDC_ARTIFACTS " + "SET SERVICE_UUID    =  $service-uuid , "
119                 + " DISTRIBUTION_ID    =  $distribution-id ," + " SERVICE_NAME    =  $service-name ,"
120                 + " SERVICE_DESCRIPTION    =  $service-description ," + " RESOURCE_UUID    = $resource-uuid ,"
121                 + " RESOURCE_INSTANCE_NAME    = $resource-instance-name ," + " RESOURCE_NAME    = $resource-name ,"
122                 + " RESOURCE_VERSION    = $resource-version ," + " RESOURCE_TYPE    = $resource-type ,"
123                 + " ARTIFACT_UUID    = $artifact-uuid ," + " ARTIFACT_TYPE    = $artifact-type ,"
124                 + " ARTIFACT_VERSION    = $artifact-version ,"
125                 + " ARTIFACT_DESCRIPTION    = $artifact-description ," + " INTERNAL_VERSION    = " + intversion
126                 + "," + " ARTIFACT_NAME       =  $artifact-name ," + " ARTIFACT_CONTENT    =  $artifact-contents ";
127
128             status = serviceLogic.save("SQL", false, false, key, null, null, ctx);
129             if (status.toString().equals(FAILURE_PARAM)) {
130                 throw new SvcLogicException("Error While processing storing Artifact: "
131                     + ctx.getAttribute(SdcArtifactHandlerConstants.ARTIFACT_NAME));
132             }
133         }
134         return status;
135     }
136
137     public QueryStatus logData(SvcLogicContext ctx, String prefix) throws SvcLogicException {
138         QueryStatus status = null;
139         if (serviceLogic != null && ctx != null) {
140             String key = "INSERT INTO CONFIG_TRANSACTION_LOG " + " SET request_id = $request-id , "
141                 + " message_type = $log-message-type , " + " message = $log-message ;";
142             status = serviceLogic.save("SQL", false, false, key, null, prefix, ctx);
143             if (status.toString().equals(FAILURE_PARAM)) {
144                 throw new SvcLogicException("Error while loging data");
145             }
146
147         }
148         return status;
149     }
150
151     public void processConfigureActionDg(SvcLogicContext context, boolean isUpdate) {
152         log.info("Update Parameter for SDC Reference " + isUpdate);
153         //TODO implement this method
154     }
155
156     public void processSdcReferences(SvcLogicContext context, boolean isUpdate) throws SvcLogicException {
157         processSdcReferences(context, isUpdate, null);
158     }
159
160     public void processSdcReferences(SvcLogicContext context, boolean isUpdate, String modelId) throws SvcLogicException {
161         String key;
162         QueryStatus status;
163          if (isUpdate && context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY)
164             .equals(SdcArtifactHandlerConstants.CAPABILITY)) {
165             log.info("Updating capability artifact in ASDC_REFERENCE");
166             key = UPDATE_QUERY_STR + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + "  set ARTIFACT_NAME = $"
167                 + SdcArtifactHandlerConstants.ARTIFACT_NAME + " where " + "FILE_CATEGORY = $"
168                 + SdcArtifactHandlerConstants.FILE_CATEGORY + AND_VNF_TYPE_QUERY_STR
169                 + SdcArtifactHandlerConstants.VNF_TYPE;
170         } else if (isUpdate) {
171             key = UPDATE_QUERY_STR + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + "  set ARTIFACT_NAME = $"
172                 + SdcArtifactHandlerConstants.ARTIFACT_NAME + " where VNFC_TYPE = $"
173                 + SdcArtifactHandlerConstants.VNFC_TYPE + AND_FILE_CAT_QUERY_STR
174                 + SdcArtifactHandlerConstants.FILE_CATEGORY + AND_ACTION_QUERY_STR + SdcArtifactHandlerConstants.ACTION
175                 + AND_VNF_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNF_TYPE;
176             if (StringUtils.isNotBlank(modelId)) {
177                 key += createQueryListForTemplateIds(modelId);
178             }
179         } else {
180             if (context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY)
181                 .equals(SdcArtifactHandlerConstants.CAPABILITY)) {
182                 log.info("Inserting new record for capability artifact in ASDC_REFERENCE");
183                 key = INSERT_INTO_QUERY_STR + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set VNFC_TYPE = null "
184                     + " , FILE_CATEGORY = $" + SdcArtifactHandlerConstants.FILE_CATEGORY + VNF_TYPE_QUERY_STR
185                     + SdcArtifactHandlerConstants.VNF_TYPE + " , ACTION = null " + " , ARTIFACT_TYPE = null "
186                     + " , ARTIFACT_NAME = $" + SdcArtifactHandlerConstants.ARTIFACT_NAME;
187             } else {
188                 key = INSERT_INTO_QUERY_STR + SdcArtifactHandlerConstants.DB_SDC_REFERENCE + " set VNFC_TYPE = $"
189                     + SdcArtifactHandlerConstants.VNFC_TYPE + " , FILE_CATEGORY = $"
190                     + SdcArtifactHandlerConstants.FILE_CATEGORY + VNF_TYPE_QUERY_STR
191                     + SdcArtifactHandlerConstants.VNF_TYPE + ACTION_QUERY_STR + SdcArtifactHandlerConstants.ACTION
192                     + " , ARTIFACT_TYPE = $" + SdcArtifactHandlerConstants.ARTIFACT_TYPE + " , ARTIFACT_NAME = $"
193                     + SdcArtifactHandlerConstants.ARTIFACT_NAME;
194             }
195         }
196         if (serviceLogic != null) {
197             log.info("Insert Key: " + key);
198             status = serviceLogic.save("SQL", false, false, key, null, null, context);
199             if (status.toString().equals(FAILURE_PARAM)) {
200                 throw new SvcLogicException("Error While processing sdc_reference table ");
201             }
202         }
203     }
204
205     public boolean isArtifactUpdateRequired(SvcLogicContext context, String db) throws DBException {
206         return isArtifactUpdateRequired( context,  db, null);
207     }
208
209     public boolean isArtifactUpdateRequired(SvcLogicContext context, String db, String modelId)
210         throws DBException {
211         try {
212             log.info("Checking if Update required for this data");
213             log.info("db" + db);
214             log.info("ACTION=" + context.getAttribute(SdcArtifactHandlerConstants.ACTION));
215             log.info("VNFC_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNFC_TYPE));
216             log.info("VNFC_INSTANCE=" + context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE));
217             log.info("VM_INSTANCE=" + context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE));
218             log.info("VNF_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE));
219
220             //Check for templates
221             //if templates are present - there might be multiple records, so validate
222             if( db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE) && StringUtils.isNotBlank(modelId)) {
223                 log.info("ModelId is sent!!");
224                   String queryPart = createQueryListForTemplateIds(modelId);
225                   log.info("Querypart is = "+queryPart);
226                    if (isUpdateRequiredForTemplates(queryPart, context, db)) {
227                        log.info("Update is Required!!");
228                     return true;
229                    } else {
230                        log.info("Insert is Required!!");
231                        return false;
232                    }
233             }
234
235             String whereClause;
236             QueryStatus status;
237             whereClause = WHERE_VNF_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNF_TYPE;
238             whereClause = resolveWhereClause(context, db, whereClause);
239             if (validate(db)) {
240                 if (!db.equals(SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION)) {
241                     String key = "select COUNT(*) from " + db + whereClause;
242                     log.info("SELECT String : " + key);
243                     status = serviceLogic.query("SQL", false, null, key, null, null, context);
244                     checkForFailure(db, status);
245                     String count = context.getAttribute("COUNT(*)");
246                     log.info("Number of row Returned : " + count + ": " + status + ":");
247                     return tryAddCountAttribute(context, count);
248                 } else {
249                     log.info("Check for update or insert for properties file");
250                     String protocol = context.getAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL);
251                     String action = context.getAttribute(SdcArtifactHandlerConstants.ACTION);
252                     String vnfType = context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE);
253                     PropertiesConfiguration conf = new PropertiesConfiguration(
254                         System.getenv("APPC_CONFIG_DIR") + "/appc_southbound.properties");
255                     String property = tryCreatePropertyStr(protocol, action, vnfType);
256                     return keyExists(conf, property);
257                 }
258             }
259             return false;
260         } catch (SvcLogicException | ConfigurationException e) {
261             throw new DBException("An error occurred while checking for artifact update", e);
262         }
263     }
264
265     private void checkForFailure(String db, QueryStatus status) throws SvcLogicException {
266         if (status.toString().equals(FAILURE_PARAM)) {
267             throw new SvcLogicException("Error while reading data from " + db);
268         }
269     }
270
271     private boolean validate(String db) {
272         return db != null && serviceLogic != null;
273     }
274
275     private boolean keyExists(PropertiesConfiguration conf, String property) {
276         if (conf.subset(property) != null) {
277             if (conf.containsKey(property)) {
278                 log.info("Key Exists for property" + property + "in southbound.properties file");
279                 return true;
280             }
281         } else {
282             log.info("Key Does not exists and need to add the key  for property" + property
283                 + "in southbound.properties file");
284         }
285         return false;
286     }
287
288     private boolean tryAddCountAttribute(SvcLogicContext context, String count) {
289         if (count != null && Integer.parseInt(count) > 0) {
290             context.setAttribute(count, null);
291             return true;
292         } else {
293             return false;
294         }
295     }
296
297     private String tryCreatePropertyStr(String protocol, String action, String vnfType) {
298
299         if (StringUtils.isNotBlank(vnfType) && StringUtils.isNotBlank(protocol) && StringUtils
300             .isNotBlank(action)) {
301             return vnfType + "." + protocol + "." + action;
302         }
303         return "";
304     }
305
306     private String resolveWhereClause(SvcLogicContext context, String db, String whereClause) {
307         if (db != null) {
308             if (hasValidAttributes(context, db)) {
309                 return whereClause + AND_FILE_CAT_QUERY_STR + SdcArtifactHandlerConstants.FILE_CATEGORY;
310             } else if (db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE)) {
311                 return whereClause + AND_VNFC_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNFC_TYPE
312                     + AND_FILE_CAT_QUERY_STR + SdcArtifactHandlerConstants.FILE_CATEGORY + AND_ACTION_QUERY_STR
313                     + SdcArtifactHandlerConstants.ACTION;
314             } else if (db.equals(SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE)) {
315                 return " where PROTOCOL = $" + SdcArtifactHandlerConstants.DEVICE_PROTOCOL;
316             } else if (db.equals(SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG)) {
317                 return whereClause + AND_ACTION_QUERY_STR + SdcArtifactHandlerConstants.ACTION;
318             } else if (db.equals(SdcArtifactHandlerConstants.DB_VNFC_REFERENCE)) {
319                 return whereClause + AND_ACTION_QUERY_STR + SdcArtifactHandlerConstants.ACTION
320                     + AND_VNFC_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNFC_TYPE + " and VNFC_INSTANCE = $"
321                     + SdcArtifactHandlerConstants.VNFC_INSTANCE + " and VM_INSTANCE = $"
322                     + SdcArtifactHandlerConstants.VM_INSTANCE;
323             }
324         }
325         return whereClause;
326     }
327
328     private boolean hasValidAttributes(SvcLogicContext context, String db) {
329         return db.equals(SdcArtifactHandlerConstants.DB_SDC_REFERENCE)
330             && context.getAttribute(SdcArtifactHandlerConstants.FILE_CATEGORY)
331             .equals(SdcArtifactHandlerConstants.CAPABILITY)
332             && context.getAttribute(SdcArtifactHandlerConstants.ACTION) == null;
333     }
334
335     public void processDeviceInterfaceProtocol(SvcLogicContext context, boolean isUpdate) throws SvcLogicException {
336         log.info("Starting DB operation for Device Interface Protocol " + isUpdate);
337         String key;
338         QueryStatus status;
339         if (isUpdate) {
340             key = UPDATE_QUERY_STR + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL + " set PROTOCOL = $"
341                 + SdcArtifactHandlerConstants.DEVICE_PROTOCOL + " , DG_RPC = 'getDeviceRunningConfig' "
342                 + " , MODULE = 'APPC' " + WHERE_VNF_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNF_TYPE;
343         } else {
344             key =
345                 INSERT_INTO_QUERY_STR + SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL + " set  VNF_TYPE = $"
346                     + SdcArtifactHandlerConstants.VNF_TYPE + " , PROTOCOL = $"
347                     + SdcArtifactHandlerConstants.DEVICE_PROTOCOL + " , DG_RPC = 'getDeviceRunningConfig' "
348                     + " , MODULE = 'APPC' ";
349         }
350
351         if (serviceLogic != null && context != null) {
352
353             status = serviceLogic.save("SQL", false, false, key, null, null, context);
354             if (status.toString().equals(FAILURE_PARAM)) {
355                 throw new SvcLogicException("Error While processing DEVICE_INTERFACE_PROTOCOL table ");
356             }
357         }
358     }
359
360     public void processDeviceAuthentication(SvcLogicContext context, boolean isUpdate)
361         throws DBException {
362         try {
363             String fn = "DBService.processDeviceAuthentication";
364             log.info(fn + "Starting DB operation for Device Authentication " + isUpdate);
365             String protocol = context.getAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL);
366             String action = context.getAttribute(SdcArtifactHandlerConstants.ACTION);
367             String vnfType = context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE);
368             String url = context.getAttribute(SdcArtifactHandlerConstants.URL);
369             String port = context.getAttribute(SdcArtifactHandlerConstants.PORT_NUMBER);
370             String user = context.getAttribute(SdcArtifactHandlerConstants.USER_NAME);
371             String property = vnfType + "." + protocol + "." + action;
372             log.info("property :" + property);
373             if (StringUtils.isBlank(url)) {
374                 url = "";
375             }
376             if (StringUtils.isBlank(port)) {
377                 port = "";
378             }
379             if (StringUtils.isBlank(user)) {
380                 user = "";
381             }
382             if (isInvalidInput(protocol, action, vnfType)) {
383                 throw new SvcLogicException(
384                     "Error While processing reference File as few or all of parameters VNF_TYPE,PROTOCOL,ACTION are missing ");
385             }
386             PropertiesConfiguration conf =
387                 new PropertiesConfiguration(System.getenv("APPC_CONFIG_DIR") + "/appc_southbound.properties");
388             log.info("is Updating to southbound  properties : " + isUpdate);
389
390             resolveUserAction(isUpdate, user, property, conf);
391             resolvePortAction(port, property, conf);
392             resolveUrlAction(url, property, conf);
393             tryAddPasswordProperty(property, conf);
394
395             log.info("About to save to properties file");
396             conf.save();
397             log.info("saved to properties file");
398         } catch (SvcLogicException | ConfigurationException e) {
399             throw new DBException("An error occurred when processing device authentication", e);
400         }
401     }
402
403     private void tryAddPasswordProperty(String property, PropertiesConfiguration conf) {
404         if (!conf.containsKey(property + "." + "password")) {
405             conf.addProperty(property + "." + "password", "");
406         }
407     }
408
409     private void resolveUrlAction(String url, String property, PropertiesConfiguration conf) {
410         if (conf.containsKey(property + "." + "url") ) {
411             if (url != null && !url.isEmpty()) {
412                 conf.setProperty(property + "." + "url", url);
413             }
414         } else {
415             conf.addProperty(property + "." + "url", url);
416         }
417     }
418
419     private void resolvePortAction(String port, String property, PropertiesConfiguration conf) {
420         if (conf.containsKey(property + "." + "port")) {
421             if (port != null && !port.isEmpty()) {
422                 conf.setProperty(property + "." + "port", port);
423             }
424         } else {
425             conf.addProperty(property + "." + "port", port);
426         }
427     }
428
429     private void resolveUserAction(boolean isUpdate, String user, String property, PropertiesConfiguration conf) {
430         if (conf.containsKey(property + "." + "user")) {
431             if (user != null && !user.isEmpty()) {
432                 conf.setProperty(property + "." + "user", user);
433             }
434         } else {
435             conf.addProperty(property + "." + "user", user);
436         }
437     }
438
439     private boolean isInvalidInput(String protocol, String action, String vnfType) {
440         return isInvalid(vnfType) && isInvalid(action) && isInvalid(protocol);
441     }
442
443     private boolean isInvalid(String str) {
444         return (str == null) || ("".equals(str));
445     }
446
447     public void processVnfcReference(SvcLogicContext context, boolean isUpdate) throws SvcLogicException {
448         String fn = "DBService.processVnfcReference";
449         log.info(fn + "Starting DB operation for Vnfc Reference " + isUpdate);
450         String key;
451
452         int vmInstance = -1;
453         if (context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE) != null) {
454             vmInstance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VM_INSTANCE));
455         }
456
457         int vnfcInstance = -1;
458         if (context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE) != null) {
459             vnfcInstance = Integer.parseInt(context.getAttribute(SdcArtifactHandlerConstants.VNFC_INSTANCE));
460         }
461
462         QueryStatus status;
463         if (isUpdate) {
464             key = UPDATE_QUERY_STR + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " set VM_INSTANCE = " + vmInstance
465                 + " , VNFC_INSTANCE = " + vnfcInstance + " , VNFC_TYPE = $" + SdcArtifactHandlerConstants.VNFC_TYPE
466                 + " , VNFC_FUNCTION_CODE = $" + SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE
467                 + " , GROUP_NOTATION_TYPE = $" + SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE
468                 + " , GROUP_NOTATION_VALUE = $" + SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE
469                 + " , IPADDRESS_V4_OAM_VIP = $" + SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP
470                 + WHERE_VNF_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNF_TYPE + AND_ACTION_QUERY_STR
471                 + SdcArtifactHandlerConstants.ACTION + AND_VNFC_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNFC_TYPE
472                 + " and VNFC_INSTANCE = $" + SdcArtifactHandlerConstants.VNFC_INSTANCE + " and VM_INSTANCE = $"
473                 + SdcArtifactHandlerConstants.VM_INSTANCE;
474         } else {
475             key = INSERT_INTO_QUERY_STR + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " set  VNF_TYPE = $"
476                 + SdcArtifactHandlerConstants.VNF_TYPE + ACTION_QUERY_STR + SdcArtifactHandlerConstants.ACTION
477                 + " , VM_INSTANCE = $" + SdcArtifactHandlerConstants.VM_INSTANCE + " , VNFC_INSTANCE = $"
478                 + SdcArtifactHandlerConstants.VNFC_INSTANCE + " , VNFC_TYPE = $"
479                 + SdcArtifactHandlerConstants.VNFC_TYPE + " , VNFC_FUNCTION_CODE = $"
480                 + SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE + " , TEMPLATE_ID = $"
481                 + SdcArtifactHandlerConstants.TEMPLATE_ID + " , GROUP_NOTATION_TYPE = $"
482                 + SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE + " , IPADDRESS_V4_OAM_VIP = $"
483                 + SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP + " , GROUP_NOTATION_VALUE = $"
484                 + SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE;
485         }
486
487         if (serviceLogic != null) {
488             status = serviceLogic.save("SQL", false, false, key, null, null, context);
489             if (status.toString().equals(FAILURE_PARAM)) {
490                 throw new SvcLogicException("Error While processing VNFC_REFERENCE table ");
491             }
492         }
493     }
494
495     public void processDownloadDgReference(SvcLogicContext context, boolean isUpdate)
496         throws SvcLogicException {
497         String fn = "DBService.processDownloadDgReference";
498         log.info(fn + "Starting DB operation for Download DG Reference " + isUpdate);
499         String key;
500         QueryStatus status = null;
501
502         if (isUpdate) {
503             key =
504                 UPDATE_QUERY_STR + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE + SET_DOWNLOAD_CONFIG_QUERY_STR
505                     + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " where PROTOCOL = $"
506                     + SdcArtifactHandlerConstants.DEVICE_PROTOCOL;
507         } else {
508             key = INSERT_INTO_QUERY_STR + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE
509                 + SET_DOWNLOAD_CONFIG_QUERY_STR
510                 + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " , PROTOCOL = $"
511                 + SdcArtifactHandlerConstants.DEVICE_PROTOCOL;
512         }
513
514         if (serviceLogic != null && context != null) {
515             status = serviceLogic.save("SQL", false, false, key, null, null, context);
516         }
517         if ((status == null) || status.toString().equals(FAILURE_PARAM)) {
518             throw new SvcLogicException("Error While processing DOWNLOAD_DG_REFERENCE table ");
519         }
520     }
521
522     public void processConfigActionDg(SvcLogicContext context, boolean isUpdate) throws SvcLogicException {
523         String fn = "DBService.processConfigActionDg";
524         log.info(fn + "Starting DB operation for Config DG Action " + isUpdate);
525         String key;
526         QueryStatus status = null;
527
528         if (context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE) != null
529             && context.getAttribute(SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE).length() > 0) {
530             if (isUpdate) {
531                 key = UPDATE_QUERY_STR + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG + SET_DOWNLOAD_CONFIG_QUERY_STR
532                     + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + " where ACTION = $"
533                     + SdcArtifactHandlerConstants.ACTION + AND_VNF_TYPE_QUERY_STR
534                     + SdcArtifactHandlerConstants.VNF_TYPE;
535             } else {
536                 key = INSERT_INTO_QUERY_STR + SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG
537                     + SET_DOWNLOAD_CONFIG_QUERY_STR
538                     + SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE + ACTION_QUERY_STR
539                     + SdcArtifactHandlerConstants.ACTION + VNF_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNF_TYPE;
540             }
541
542             if (serviceLogic != null) {
543                 status = serviceLogic.save("SQL", false, false, key, null, null, context);
544             }
545             if ((status == null) || status.toString().equals(FAILURE_PARAM)) {
546                 throw new SvcLogicException("Error While processing Configure DG Action table ");
547             }
548         } else {
549             log.info("No Update required for Config DG Action");
550         }
551
552     }
553
554     public String getModelDataInformationbyArtifactName(String artifactName) throws SvcLogicException {
555         String fn = "DBService.getVnfData";
556         SvcLogicContext con = new SvcLogicContext();
557         String key;
558         QueryStatus status;
559         key =
560             "select VNF_TYPE, VNFC_TYPE, ACTION, FILE_CATEGORY, ARTIFACT_TYPE from ASDC_REFERENCE where  ARTIFACT_NAME = "
561                 + artifactName;
562
563         if (serviceLogic != null) {
564             log.info(fn + "select Key: " + key);
565             status = serviceLogic.query("SQL", false, null, key, null, null, con);
566             if (status.toString().equals(FAILURE_PARAM)) {
567                 throw new SvcLogicException("Error While processing is ArtifactUpdateRequiredforPD table ");
568             }
569
570         }
571         log.info(fn + "Vnf_received :" + con.getAttribute("VNF_TYPE"));
572
573         return con.getAttribute("VNF_TYPE");
574     }
575
576     public void updateYangContents(SvcLogicContext context, String artifactId, String yangContents)
577         throws SvcLogicException {
578         String fn = "DBService.updateYangContents";
579         log.info(fn + "Starting DB operation for  updateYangContents");
580         String key;
581         QueryStatus status = null;
582
583         key = "update ASDC_ARTIFACTS " + " set ARTIFACT_CONTENT = '" + yangContents + "'"
584             + " where ASDC_ARTIFACTS_ID = " + artifactId;
585
586         if (serviceLogic != null && context != null) {
587             status = serviceLogic.save("SQL", false, false, key, null, null, context);
588         }
589         if ((status == null) || status.toString().equals(FAILURE_PARAM)) {
590             throw new SvcLogicException("Error While processing Configure DG Action table ");
591         }
592
593     }
594
595
596     public void insertProtocolReference(SvcLogicContext context, String vnfType, String protocol, String action,
597         String actionLevel, String template) throws SvcLogicException {
598         String fn = "DBService.insertProtocolReference";
599         log.info(fn + "Starting DB operation for  insertProtocolReference");
600         String key;
601         QueryStatus status = null;
602
603         key = "insert into PROTOCOL_REFERENCE (ACTION, VNF_TYPE, PROTOCOL, UPDATED_DATE, TEMPLATE, ACTION_LEVEL)"
604             + " values  (" + "'" + action + "', '" + vnfType + "', '" + protocol + "', now(),'" + template + "', '"
605             + actionLevel + "')";
606
607         if (serviceLogic != null && context != null) {
608             status = serviceLogic.save("SQL", false, false, key, null, null, context);
609         }
610         if ((status == null) || status.toString().equals(FAILURE_PARAM)) {
611             throw new SvcLogicException("Error While processing insertProtocolReference ");
612         }
613
614     }
615
616     public boolean isProtocolReferenceUpdateRequired(SvcLogicContext context, String vnfType, String protocol,
617         String action, String actionLevel, String template) throws SvcLogicException {
618         SvcLogicContext localContext = new SvcLogicContext();
619         String fn = "DBService.isProtocolReferenceUpdateRequired";
620         log.info(fn + "Starting DB operation for  isProtocolReferenceUpdateRequired");
621
622         String key = "select COUNT(*) from PROTOCOL_REFERENCE where ACTION='" + action + "' and ACTION_LEVEL='" + actionLevel
623             + "' and VNF_TYPE='" + vnfType + "'";
624         serviceLogic.query("SQL", false, null, key, null, null, localContext);
625
626         String countStr = localContext.getAttribute("COUNT(*)");
627         int count = Integer.parseInt(countStr);
628         return count > 0;
629     }
630
631     public void updateProtocolReference(SvcLogicContext context, String vnfType, String protocol, String action,
632         String actionLevel, String template) throws SvcLogicException {
633
634         String fn = "DBService.isProtocolReferenceUpdateRequired";
635         log.info(fn + "Starting DB operation for  isProtocolReferenceUpdateRequired");
636         String key;
637         QueryStatus status;
638
639         key = "update PROTOCOL_REFERENCE set UPDATED_DATE=now(), template='" + template + "', protocol ='" + protocol
640             + "' where ACTION='" + action + "' and ACTION_LEVEL='" + actionLevel + "' and VNF_TYPE='" + vnfType
641             + "'";
642         status = serviceLogic.save("SQL", false, false, key, null, null, context);
643         if (status == QueryStatus.FAILURE) {
644             log.info("updateProtocolReference:: Error updating protocol reference");
645             throw new SvcLogicException("Error - updating PROTOCOL_REFERENCE_TABLE in updateProtocolReference");
646         }
647     }
648
649     public String getDownLoadDGReference(SvcLogicContext context) throws DBException {
650         try {
651
652             String fn = "DBService.setDownLoadDGReference";
653             String downloadConfigDg;
654             log.info(fn + "Setting Download DG Reference from DB");
655             String key;
656             QueryStatus status;
657             String protocol = context.getAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL);
658             if (StringUtils.isBlank(protocol)) {
659                 log.info(fn + " :: Protocol is Blank!! Returning without querying DB");
660                 throw new ConfigurationException(fn + ":: Protocol is Blank!! Returning without querying DB");
661             }
662             key = "select download_config_dg from " + SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE
663                 + " where protocol = '" + protocol + "'";
664             SvcLogicContext localContext = new SvcLogicContext();
665             status = serviceLogic.query("SQL", false, null, key, null, null, localContext);
666             if (status == QueryStatus.FAILURE) {
667                 log.info(fn + ":: Error retrieving download_config_dg");
668                 throw new SvcLogicException("Error retrieving download_config_dg");
669             }
670             if (status == QueryStatus.NOT_FOUND) {
671                 log.info(fn + ":: NOT_FOUND! No data found for download_config_dg!!");
672                 throw new SvcLogicException(fn + ":: NOT_FOUND! No data found for download_config_dg!");
673             }
674             downloadConfigDg = localContext.getAttribute("download-config-dg");
675             log.info(fn + "download_config_dg::" + downloadConfigDg);
676             return downloadConfigDg;
677         } catch (SvcLogicException | ConfigurationException e) {
678             throw new DBException("An error occurred when getting DG reference", e);
679         }
680     }
681
682     public void cleanUpVnfcReferencesForVnf(SvcLogicContext context) throws SvcLogicException {
683         try {
684             String key1 = "delete from " + SdcArtifactHandlerConstants.DB_VNFC_REFERENCE + " where action = $"
685                 + SdcArtifactHandlerConstants.ACTION + " and vnf_type = $" + SdcArtifactHandlerConstants.VNF_TYPE;
686             log.debug("Action : " + context.getAttribute(SdcArtifactHandlerConstants.ACTION));
687             log.debug("vnfType: " + context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE));
688             QueryStatus status;
689             log.info("cleanUpVnfcReferencesForVnf()::Query:" + key1);
690             if (serviceLogic != null) {
691                 status = serviceLogic.save("SQL", false, false, key1, null, null, context);
692                 if (status.toString().equals(FAILURE_PARAM)) {
693                     log.debug("Error deleting from VNFC_REFERENCE table");
694                     throw new SvcLogicException("Error While processing VNFC_REFERENCE table ");
695                 }
696             }
697         } catch (Exception e) {
698             log.debug("Error deleting from VNFC_REFERENCE table  : "
699                 + context.getAttribute(SdcArtifactHandlerConstants.ACTION) + " and "
700                 + context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE), e);
701         }
702     }
703
704
705     public boolean isUpdateRequiredForTemplates(String queryPart, SvcLogicContext context, String db) throws DBException {
706         try {
707             log.info("Checking if Update required for this data");
708             log.info("db" + db);
709             log.info("ACTION=" + context.getAttribute(SdcArtifactHandlerConstants.ACTION));
710             log.info("VNF_TYPE=" + context.getAttribute(SdcArtifactHandlerConstants.VNF_TYPE));
711             log.info("");
712             String whereClause;
713             QueryStatus status;
714             whereClause = WHERE_VNF_TYPE_QUERY_STR + SdcArtifactHandlerConstants.VNF_TYPE ;
715             whereClause = resolveWhereClause(context, db, whereClause);
716             whereClause += queryPart;
717             if (validate(db)) {
718                 if (!db.equals(SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION)) {
719                     String key = "select COUNT(*) from " + db + whereClause;
720                     log.info("SELECT String : " + key);
721                     status = serviceLogic.query("SQL", false, null, key, null, null, context);
722                     checkForFailure(db, status);
723                     String count = context.getAttribute("COUNT(*)");
724                     log.info("Number of row Returned : " + count + ": " + status + ":");
725                     return tryAddCountAttribute(context, count);
726                 }
727             }
728             log.info("Problems validating DB and/or Context ");
729             return false;
730
731         } catch (SvcLogicException e) {
732             throw new DBException("An error occurred while checking for artifact update", e);
733         }
734     }
735
736     public String createQueryListForTemplateIds(String modelId) {
737         String queryPart = " AND ARTIFACT_NAME like '%_" + modelId+".%'";
738         return queryPart;
739     }
740 }