5fca4662ec26078a2cdb764ad2da876666805abc
[sdnc/core.git] / sli / common / src / main / java / org / openecomp / sdnc / sli / SvcLogicDblibStore.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                         reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.sdnc.sli;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
31 import java.sql.Blob;
32 import java.sql.Connection;
33 import java.sql.PreparedStatement;
34 import java.sql.ResultSet;
35 import java.sql.SQLException;
36 import java.util.ArrayList;
37 import java.util.Properties;
38
39 import javax.sql.rowset.CachedRowSet;
40
41 import org.openecomp.sdnc.sli.resource.dblib.DBResourceManager;
42 import org.openecomp.sdnc.sli.resource.dblib.DbLibService;
43 import org.osgi.framework.Bundle;
44 import org.osgi.framework.BundleContext;
45 import org.osgi.framework.FrameworkUtil;
46 import org.osgi.framework.ServiceReference;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public class SvcLogicDblibStore implements SvcLogicStore {
51
52         private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
53         
54         private static final Logger LOG = LoggerFactory
55                         .getLogger(SvcLogicDblibStore.class);
56
57         private static final String DBLIB_SERVICE =
58         // "org.openecomp.sdnc.sli.resource.dblib.DBLibService";
59         "org.openecomp.sdnc.sli.resource.dblib.DBResourceManager";
60         
61         Properties props = null;
62
63         public void init(Properties props) throws ConfigurationException {
64
65                 DbLibService dbSvc = getDbLibService();
66                 if(dbSvc == null) {
67                         LOG.error("SvcLogic cannot acquire DBLIB_SERVICE");
68                         return;
69                 }
70                 try {
71                         dbSvc.getData("select 1 from DUAL", new ArrayList<String>(), null);
72                         LOG.debug("SQL test was successful");
73                 } catch (SQLException e) {
74                         LOG.error("Failed SQL test", e);
75                 }
76         }
77
78         public boolean hasGraph(String module, String rpc, String version,
79                         String mode) throws SvcLogicException {
80
81                 DbLibService dbSvc = getDbLibService();
82
83                 boolean retval = false;
84                 CachedRowSet results = null;
85                 String hasVersionGraphSql = "SELECT count(*) FROM SVC_LOGIC"
86                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
87
88                 String hasActiveGraphSql = "SELECT count(*) FROM SVC_LOGIC"
89                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
90
91                 PreparedStatement hasGraphStmt = null;
92
93                 ArrayList<String> args = new ArrayList<String>();
94                 args.add(module);
95                 args.add(rpc);
96                 args.add(mode);
97
98                 try {
99
100                         if (version == null) {
101                                 results = dbSvc.getData(hasActiveGraphSql, args, null);
102                         } else {
103                                 args.add(version);
104                                 results = dbSvc.getData(hasVersionGraphSql, args, null);
105                         }
106
107                         if (results.next()) {
108                                 int cnt = results.getInt(1);
109
110                                 if (cnt > 0) {
111                                         retval = true;
112                                 }
113
114                         }
115                 } catch (Exception e) {
116                         throw new ConfigurationException("SQL query failed", e);
117                 } finally {
118                         if (results != null) {
119                                 try {
120
121                                         results.close();
122                                 } catch (SQLException x) {
123                                 }
124                         }
125
126                 }
127
128                 return (retval);
129
130         }
131
132         public SvcLogicGraph fetch(String module, String rpc, String version,
133                         String mode) throws SvcLogicException {
134
135                 DbLibService dbSvc = getDbLibService();
136
137                 Connection dbConn = null;
138                 SvcLogicGraph retval = null;
139                 ResultSet results = null;
140
141                 String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC"
142                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
143
144                 String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC"
145                                 + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
146
147
148                 try {
149                         dbConn = ((DBResourceManager) dbSvc).getConnection();
150                         PreparedStatement fetchGraphStmt;
151                         
152                         ArrayList<String> args = new ArrayList<String>();
153                         args.add(module);
154                         args.add(rpc);
155                         args.add(mode);
156
157                         if (version == null) {
158                                 fetchGraphStmt = dbConn.prepareStatement(fetchActiveGraphSql);
159                         } else {
160                                 fetchGraphStmt = dbConn.prepareStatement(fetchVersionGraphSql);
161                         }
162                         
163                         fetchGraphStmt.setString(1, module);
164                         fetchGraphStmt.setString(2,  rpc);
165                         fetchGraphStmt.setString(3, mode);
166                         if (version != null) {
167                                 fetchGraphStmt.setString(4,version);
168                         }
169
170                         results = fetchGraphStmt.executeQuery();
171                         
172                         if (results.next()) {
173                                 Blob graphBlob = results.getBlob("graph");
174
175                                 ObjectInputStream gStream = new ObjectInputStream(
176                                                 graphBlob.getBinaryStream());
177
178                                 Object graphObj = gStream.readObject();
179                                 gStream.close();
180
181                                 if (graphObj instanceof SvcLogicGraph) {
182                                         retval = (SvcLogicGraph) graphObj;
183                                 } else {
184                                         throw new ConfigurationException("invalid type for graph ("
185                                                         + graphObj.getClass().getName());
186
187                                 }
188
189                         } else {
190                                 return (null);
191                         }
192                 } catch (Exception e) {
193                         throw new ConfigurationException("SQL query 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 }