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