Remove remaining references to openecomp
[ccsdk/sli/core.git] / sli / common / src / main / java / org / onap / ccsdk / sli / core / sli / SvcLogicDblibStore.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2017 ONAP
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.ccsdk.sli.core.sli;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.ObjectInputStream;
29 import java.io.ObjectOutputStream;
30 import java.sql.Blob;
31 import java.sql.Connection;
32 import java.sql.PreparedStatement;
33 import java.sql.ResultSet;
34 import java.sql.SQLException;
35 import java.util.ArrayList;
36 import java.util.Properties;
37
38 import javax.sql.rowset.CachedRowSet;
39
40 import org.onap.ccsdk.sli.core.dblib.DBResourceManager;
41 import org.onap.ccsdk.sli.core.dblib.DbLibService;
42 import org.osgi.framework.Bundle;
43 import org.osgi.framework.BundleContext;
44 import org.osgi.framework.FrameworkUtil;
45 import org.osgi.framework.ServiceReference;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class SvcLogicDblibStore implements SvcLogicStore {
50
51         private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
52
53         private static final Logger LOG = LoggerFactory
54                         .getLogger(SvcLogicDblibStore.class);
55
56         private static final String DBLIB_SERVICE =
57         "org.onap.ccsdk.sli.core.dblib.DBResourceManager";
58
59         Properties props = null;
60
61         public void init(Properties props) throws ConfigurationException {
62
63                 DbLibService dbSvc = getDbLibService();
64                 if(dbSvc == null) {
65                         LOG.error("SvcLogic cannot acquire DBLIB_SERVICE");
66                         return;
67                 }
68                 try {
69                         dbSvc.getData("select 1 from DUAL", new ArrayList<String>(), null);
70                         LOG.debug("SQL test was successful");
71                 } catch (SQLException e) {
72                         LOG.error("Failed SQL test", e);
73                 }
74         }
75
76         public boolean hasGraph(String module, String rpc, String version,
77                         String mode) throws SvcLogicException {
78
79                 DbLibService dbSvc = getDbLibService();
80
81                 boolean retval = false;
82                 CachedRowSet results = null;
83                 String hasVersionGraphSql = "SELECT count(*) FROM SVC_LOGIC"
84                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
85
86                 String hasActiveGraphSql = "SELECT count(*) FROM SVC_LOGIC"
87                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
88
89                 PreparedStatement hasGraphStmt = null;
90
91                 ArrayList<String> args = new ArrayList<String>();
92                 args.add(module);
93                 args.add(rpc);
94                 args.add(mode);
95
96                 try {
97
98                         if (version == null) {
99                                 results = dbSvc.getData(hasActiveGraphSql, args, null);
100                         } else {
101                                 args.add(version);
102                                 results = dbSvc.getData(hasVersionGraphSql, args, null);
103                         }
104
105                         if (results.next()) {
106                                 int cnt = results.getInt(1);
107
108                                 if (cnt > 0) {
109                                         retval = true;
110                                 }
111
112                         }
113                 } catch (Exception e) {
114                         throw new ConfigurationException("SQL query failed", e);
115                 } finally {
116                         if (results != null) {
117                                 try {
118
119                                         results.close();
120                                 } catch (SQLException x) {
121                                 }
122                         }
123
124                 }
125
126                 return (retval);
127
128         }
129
130         public SvcLogicGraph fetch(String module, String rpc, String version,
131                         String mode) throws SvcLogicException {
132
133                 DbLibService dbSvc = getDbLibService();
134
135                 Connection dbConn = null;
136                 SvcLogicGraph retval = null;
137                 ResultSet results = null;
138
139                 String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC"
140                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
141
142                 String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC"
143                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
144
145
146                 try {
147                         dbConn = ((DBResourceManager) dbSvc).getConnection();
148                         PreparedStatement fetchGraphStmt;
149
150                         ArrayList<String> args = new ArrayList<String>();
151                         args.add(module);
152                         args.add(rpc);
153                         args.add(mode);
154
155                         if (version == null) {
156                                 fetchGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql);
157                         } else {
158                                 fetchGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql);
159                         }
160
161                         fetchGraphStmt.setString(1, module);
162                         fetchGraphStmt.setString(2,  rpc);
163                         fetchGraphStmt.setString(3, mode);
164                         if (version != null) {
165                                 fetchGraphStmt.setString(4,version);
166                         }
167
168                         results = fetchGraphStmt.executeQuery();
169
170                         if (results.next()) {
171                                 Blob graphBlob = results.getBlob("graph");
172
173                                 ObjectInputStream gStream = new ObjectInputStream(
174                                                 graphBlob.getBinaryStream());
175
176                                 Object graphObj = gStream.readObject();
177                                 gStream.close();
178
179                                 if (graphObj instanceof SvcLogicGraph) {
180                                         retval = (SvcLogicGraph) graphObj;
181                                 } else {
182                                         throw new ConfigurationException("invalid type for graph ("
183                                                         + graphObj.getClass().getName());
184
185                                 }
186
187                         } else {
188                                 return (null);
189                         }
190                 } catch (SQLException e) {
191                         throw new ConfigurationException("SQL query failed", e);
192                 } catch (Exception e) {
193                         throw new ConfigurationException("Graph processing failed", e);
194                 } finally {
195                         if (results != null) {
196                                 try {
197                                         results.close();
198                                 } catch (SQLException x) {
199                                 }
200                         }
201                         try {
202                                 if (dbConn != null && !dbConn.isClosed()) {
203                                         dbConn.close();
204                                 }
205                         } catch (Throwable exc) {
206                                 // the exception not monitored
207                         } finally {
208                                 dbConn = null;
209                         }
210
211                 }
212
213                 return (retval);
214
215         }
216
217         public void store(SvcLogicGraph graph) throws SvcLogicException {
218
219                 DbLibService dbSvc = getDbLibService();
220
221                 String storeGraphSql = "INSERT INTO SVC_LOGIC (module, rpc, version, mode, active, graph)"
222                                 + " VALUES(?, ?, ?, ?, ?, ?)";
223
224                 if (graph == null) {
225                         throw new SvcLogicException("graph cannot be null");
226                 }
227
228                 byte[] graphBytes = null;
229
230                 ByteArrayOutputStream byteStr = null;
231                 ObjectOutputStream goutStr = null;
232
233                 try {
234                         byteStr = new ByteArrayOutputStream();
235                         goutStr = new ObjectOutputStream(byteStr);
236                         goutStr.writeObject(graph);
237
238                         graphBytes = byteStr.toByteArray();
239
240                 } catch (Exception e) {
241                         throw new SvcLogicException("could not serialize graph", e);
242                 } finally {
243
244                         if (goutStr != null) {
245                                 try {
246                                         goutStr.close();
247                                 } catch (IOException e) {
248
249                                 }
250                         }
251
252                         if (byteStr != null) {
253                                 try {
254                                         byteStr.close();
255                                 } catch (IOException e) {
256
257                                 }
258                         }
259                 }
260
261                 // If object already stored in database, delete it
262                 if (hasGraph(graph.getModule(), graph.getRpc(), graph.getVersion(),
263                                 graph.getMode())) {
264                         delete(graph.getModule(), graph.getRpc(), graph.getVersion(),
265                                         graph.getMode());
266                 }
267
268                 Connection dbConn = null;
269
270                 try {
271                         dbConn = ((DBResourceManager) dbSvc).getConnection();
272                         boolean oldAutoCommit = dbConn.getAutoCommit();
273                         dbConn.setAutoCommit(false);
274                         PreparedStatement storeGraphStmt = dbConn
275                                         .prepareStatement(storeGraphSql);
276                         storeGraphStmt.setString(1, graph.getModule());
277                         storeGraphStmt.setString(2, graph.getRpc());
278                         storeGraphStmt.setString(3, graph.getVersion());
279                         storeGraphStmt.setString(4, graph.getMode());
280                         storeGraphStmt.setString(5, "N");
281                         storeGraphStmt.setBlob(6, new ByteArrayInputStream(graphBytes));
282
283                         storeGraphStmt.executeUpdate();
284                         dbConn.commit();
285
286                         dbConn.setAutoCommit(oldAutoCommit);
287                 } catch (Exception e) {
288                         throw new SvcLogicException("Could not write object to database", e);
289                 } finally {
290                         try {
291                                 if (dbConn != null && !dbConn.isClosed()) {
292                                         dbConn.close();
293                                 }
294                         } catch (Throwable exc) {
295                                 // the exception not monitored
296                         } finally {
297                                 dbConn = null;
298                         }
299
300                 }
301         }
302
303         public void delete(String module, String rpc, String version, String mode)
304                         throws SvcLogicException {
305
306                 DbLibService dbSvc = getDbLibService();
307
308                 String deleteGraphSql = "DELETE FROM SVC_LOGIC WHERE module = ? AND rpc = ? AND version = ? AND mode = ?";
309
310                 ArrayList<String> args = new ArrayList<String>();
311
312                 args.add(module);
313                 args.add(rpc);
314                 args.add(version);
315                 args.add(mode);
316
317                 try {
318                         dbSvc.writeData(deleteGraphSql, args, null);
319                 } catch (Exception e) {
320                         throw new SvcLogicException(
321                                         "Could not delete object from database", e);
322                 }
323         }
324
325         public void activate(SvcLogicGraph graph) throws SvcLogicException {
326                 DbLibService dbSvc = getDbLibService();
327
328                 String deactivateSql = "UPDATE SVC_LOGIC SET active = 'N' WHERE module = ? AND rpc = ? AND mode = ?";
329
330                 String activateSql = "UPDATE SVC_LOGIC SET active = 'Y' WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
331
332                 ArrayList<String> args = new ArrayList<String>();
333
334                 args.add(graph.getModule());
335                 args.add(graph.getRpc());
336                 args.add(graph.getMode());
337
338                 try {
339
340                         dbSvc.writeData(deactivateSql, args, null);
341
342                         args.add(graph.getVersion());
343                         dbSvc.writeData(activateSql, args, null);
344
345                 } catch (Exception e) {
346                         throw new SvcLogicException("Could not activate graph", e);
347                 }
348         }
349
350         @Override
351         public void registerNodeType(String nodeType) throws SvcLogicException {
352
353                 String registerNodeSql = "INSERT INTO NODE_TYPES (nodetype) VALUES(?)";
354
355                 if (isValidNodeType(nodeType)) {
356                         return;
357                 }
358
359                 DbLibService dbSvc = getDbLibService();
360                 ArrayList<String> args = new ArrayList<String>();
361
362                 args.add(nodeType);
363
364                 try {
365                         dbSvc.writeData(registerNodeSql, args, null);
366                 } catch (Exception e) {
367                         throw new SvcLogicException("Could not add node type to database",
368                                         e);
369                 }
370
371         }
372
373         @Override
374         public void unregisterNodeType(String nodeType) throws SvcLogicException {
375
376                 if (!isValidNodeType(nodeType)) {
377                         return;
378                 }
379
380                 String unregisterNodeSql = "DELETE FROM NODE_TYPES WHERE nodetype = ?";
381
382                 DbLibService dbSvc = getDbLibService();
383                 ArrayList<String> args = new ArrayList<String>();
384
385                 args.add(nodeType);
386
387                 try {
388                         dbSvc.writeData(unregisterNodeSql, args, null);
389                 } catch (Exception e) {
390                         throw new SvcLogicException(
391                                         "Could not delete node type from database", e);
392                 }
393
394         }
395
396         @Override
397         public boolean isValidNodeType(String nodeType) throws SvcLogicException {
398
399                 String validateNodeSql = "SELECT count(*) FROM NODE_TYPES WHERE nodetype = ?";
400
401                 DbLibService dbSvc = getDbLibService();
402
403                 ArrayList<String> args = new ArrayList<String>();
404
405                 args.add(nodeType);
406
407                 boolean isValid = false;
408
409                 CachedRowSet results = null;
410                 try {
411                         results = dbSvc.getData(validateNodeSql, args, null);
412                         if (results != null) {
413                                 if (results.next()) {
414                                         int cnt = results.getInt(1);
415
416                                         if (cnt > 0) {
417                                                 isValid = true;
418                                         }
419                                 }
420                         }
421                 } catch (Exception e) {
422                         throw new SvcLogicException(
423                                         "Cannot select node type from database", e);
424                 } finally {
425                         if (results != null) {
426                                 try {
427                                         results.close();
428                                 } catch (SQLException x) {
429                                 }
430                         }
431
432                 }
433
434                 return (isValid);
435         }
436
437         private DbLibService getDbLibService() {
438
439                 // Get DbLibService interface object.
440                 DbLibService dblibSvc = null;
441                 ServiceReference sref = null;
442                 BundleContext bctx = null;
443
444                 Bundle bundle = FrameworkUtil.getBundle(SvcLogicDblibStore.class);
445
446                 if (bundle != null) {
447                         bctx = bundle.getBundleContext();
448
449                         if (bctx != null) {
450                                 sref = bctx.getServiceReference(DBLIB_SERVICE);
451                         }
452
453                         if (sref == null) {
454                                 LOG.warn("Could not find service reference for DBLIB service ("
455                                                 + DBLIB_SERVICE + ")");
456                         } else {
457                                 dblibSvc = (DbLibService) bctx.getService(sref);
458                                 if (dblibSvc == null) {
459
460                                         LOG.warn("Could not find service reference for DBLIB service ("
461                                                         + DBLIB_SERVICE + ")");
462                                 }
463                         }
464                 }
465
466                 // initialize a stand-alone instance of dblib resource
467                 else {
468                         // Try to create a DbLibService object from dblib properties
469                         if(JavaSingleton.getInstance() == null){
470                                 Properties dblibProps = new Properties();
471
472                                 String propDir = System.getenv(SDNC_CONFIG_DIR);
473                                 if (propDir == null) {
474
475                                         propDir = "/opt/sdnc/data/properties";
476                                 }
477                                 String propPath = propDir + "/dblib.properties";
478
479                                 File propFile = new File(propPath);
480
481                                 if (!propFile.exists()) {
482
483                                         LOG.warn(
484                                                         "Missing configuration properties file : "
485                                                                         + propFile);
486                                         return(null);
487                                 }
488
489                                 try {
490
491                                         dblibProps.load(new FileInputStream(propFile));
492                                 } catch (Exception e) {
493                                         LOG.warn(
494                                                         "Could not load properties file " + propPath, e);
495                                         return(null);
496
497                                 }
498
499                                 try {
500                                         dblibSvc = DBResourceManager.create(dblibProps);
501                                         JavaSingleton.setInstance(dblibSvc);
502                                 } catch (Exception e) {
503                                         LOG.warn("Caught exception trying to create DBResourceManager", e);
504                                 }
505                         } else {
506                                 dblibSvc = JavaSingleton.getInstance();
507                         }
508                 }
509                 return (dblibSvc);
510         }
511
512
513         static class JavaSingleton {
514              /* Private constructor     */
515              private JavaSingleton() {
516                 /* the body of the constructor here */
517              }
518
519              /* instance of the singleton declaration */
520              private static volatile  DbLibService INSTANCE ;
521
522              /* Access point to the unique instance of the singleton */
523              public static DbLibService getInstance() {
524                 return INSTANCE;
525              }
526
527              public static void setInstance(DbLibService dbresource) {
528                         INSTANCE = dbresource;
529                      }
530         }
531 }