Fix sonar issue in SqlResource.java
[ccsdk/sli/adaptors.git] / sql-resource / provider / src / main / java / org / onap / ccsdk / sli / adaptors / resource / sql / SqlResource.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.onap.ccsdk.sli.adaptors.resource.sql;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.sql.Connection;
27 import java.sql.PreparedStatement;
28 import java.sql.ResultSet;
29 import java.sql.ResultSetMetaData;
30 import java.sql.SQLException;
31 import java.util.ArrayList;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Properties;
35
36 import javax.sql.rowset.CachedRowSet;
37
38 import org.apache.commons.lang3.StringUtils;
39 import org.onap.ccsdk.sli.core.dblib.DBResourceManager;
40 import org.onap.ccsdk.sli.core.dblib.DbLibService;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
45 import org.osgi.framework.Bundle;
46 import org.osgi.framework.BundleContext;
47 import org.osgi.framework.FrameworkUtil;
48 import org.osgi.framework.ServiceReference;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class SqlResource implements SvcLogicResource, SvcLogicJavaPlugin {
53
54     private static final Logger LOG = LoggerFactory.getLogger(SqlResource.class);
55
56     private static final String DBLIB_SERVICE = "org.onap.ccsdk.sli.core.dblib.DbLibService";
57
58     private static String CRYPT_KEY = "QtfJMKggVk";
59
60     DbLibService dblibSvc = null;
61
62     public SqlResource() {
63         this(new SqlResourcePropertiesProviderImpl(), null);
64     }
65
66     public SqlResource(SqlResourcePropertiesProvider propProvider) {
67         this(propProvider, null);
68     }
69
70     public SqlResource(SqlResourcePropertiesProvider propProvider, DbLibService dblibSvc) {
71
72         this.dblibSvc = dblibSvc;
73
74         Properties properties = propProvider.getProperties();
75
76         String cryptKey = properties.getProperty("org.onap.sdnc.resource.sql.cryptkey");
77
78         if ((cryptKey == null) || (cryptKey.length() == 0)) {
79             cryptKey = properties.getProperty("org.openecomp.sdnc.resource.sql.cryptkey");
80         }
81
82         SqlResource.setCryptKey(cryptKey);
83     }
84
85     // For sql-resource, is-available is the same as exists
86     @Override
87     public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx)
88             throws SvcLogicException {
89
90         return (exists(resource, key, prefix, ctx));
91
92     }
93
94     @Override
95     public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx)
96             throws SvcLogicException {
97
98         DbLibService dblibSvc = getDbLibService();
99         if (dblibSvc == null) {
100             return (QueryStatus.FAILURE);
101         }
102
103         String theStmt = resolveCtxVars(key, ctx);
104
105         try {
106             CachedRowSet results = dblibSvc.getData(theStmt, null, null);
107
108             if (!results.next()) {
109                 return (QueryStatus.NOT_FOUND);
110             }
111
112             int numRows = results.getInt(1);
113
114             if (numRows > 0) {
115                 return (QueryStatus.SUCCESS);
116             } else {
117                 return (QueryStatus.NOT_FOUND);
118             }
119         } catch (Exception e) {
120             LOG.error("Caught SQL exception", e);
121             return (QueryStatus.FAILURE);
122         }
123     }
124
125     // @Override
126     public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix,
127             String orderBy, SvcLogicContext ctx) throws SvcLogicException {
128
129         DbLibService dblibSvc = getDbLibService();
130
131         if (dblibSvc == null) {
132             return (QueryStatus.FAILURE);
133         }
134
135         String sqlQuery = resolveCtxVars(key, ctx);
136
137         try {
138
139             CachedRowSet results = dblibSvc.getData(sqlQuery, null, null);
140
141             QueryStatus retval = QueryStatus.SUCCESS;
142
143             if (!results.next()) {
144                 retval = QueryStatus.NOT_FOUND;
145                 LOG.debug("No data found");
146             } else {
147                 saveCachedRowSetToCtx(results, ctx, prefix, dblibSvc);
148             }
149             return (retval);
150         } catch (Exception e) {
151             LOG.error("Caught SQL exception", e);
152             return (QueryStatus.FAILURE);
153         }
154     }
155
156     public void saveCachedRowSetToCtx(CachedRowSet results, SvcLogicContext ctx, String prefix, DbLibService dblibSvc)
157             throws SQLException {
158         if (ctx != null) {
159             if ((prefix != null) && prefix.endsWith("[]")) {
160                 // Return an array.
161                 String pfx = prefix.substring(0, prefix.length() - 2);
162                 int idx = 0;
163                 do {
164                     ResultSetMetaData rsMeta = results.getMetaData();
165                     int numCols = rsMeta.getColumnCount();
166
167                     for (int i = 0; i < numCols; i++) {
168                         String colValue = null;
169                         String tableName = rsMeta.getTableName(i + 1);
170                         if (rsMeta.getColumnType(i + 1) == java.sql.Types.VARBINARY) {
171                             colValue = decryptColumn(tableName, rsMeta.getColumnName(i + 1), results.getBytes(i + 1),
172                                     dblibSvc);
173                         } else {
174                             colValue = results.getString(i + 1);
175                         }
176                         LOG.debug("Setting " + pfx + "[" + idx + "]."
177                                 + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue);
178                         ctx.setAttribute(pfx + "[" + idx + "]." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"),
179                                 colValue);
180                     }
181                     idx++;
182                 } while (results.next());
183                 LOG.debug("Setting " + pfx + "_length = " + idx);
184                 ctx.setAttribute(pfx + "_length", "" + idx);
185             } else {
186                 ResultSetMetaData rsMeta = results.getMetaData();
187                 int numCols = rsMeta.getColumnCount();
188
189                 for (int i = 0; i < numCols; i++) {
190                     String colValue = null;
191                     String tableName = rsMeta.getTableName(i + 1);
192                     if ("VARBINARY".equalsIgnoreCase(rsMeta.getColumnTypeName(i + 1))) {
193                         colValue = decryptColumn(tableName, rsMeta.getColumnName(i + 1), results.getBytes(i + 1),
194                                 dblibSvc);
195                     } else {
196                         colValue = results.getString(i + 1);
197                     }
198                     if (prefix != null) {
199                         LOG.debug("Setting " + prefix + "." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = "
200                                 + colValue);
201                         ctx.setAttribute(prefix + "." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue);
202                     } else {
203                         LOG.debug("Setting " + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue);
204                         ctx.setAttribute(rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue);
205                     }
206                 }
207             }
208         }
209     }
210
211     // reserve is no-op
212     @Override
213     public QueryStatus reserve(String resource, String select, String key, String prefix, SvcLogicContext ctx)
214             throws SvcLogicException {
215         return (QueryStatus.SUCCESS);
216     }
217
218     // release is no-op
219     @Override
220     public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
221         return (QueryStatus.SUCCESS);
222     }
223
224     private QueryStatus executeSqlWrite(String key, SvcLogicContext ctx) throws SvcLogicException {
225         QueryStatus retval = QueryStatus.SUCCESS;
226
227         DbLibService dblibSvc = getDbLibService();
228
229         if (dblibSvc == null) {
230             return (QueryStatus.FAILURE);
231         }
232
233         String sqlStmt = resolveCtxVars(key, ctx);
234
235         LOG.debug("key = [" + key + "]; sqlStmt = [" + sqlStmt + "]");
236         try {
237
238             if (!dblibSvc.writeData(sqlStmt, null, null)) {
239                 retval = QueryStatus.FAILURE;
240             }
241         } catch (Exception e) {
242             LOG.error("Caught SQL exception", e);
243             retval = QueryStatus.FAILURE;
244         }
245
246         return (retval);
247
248     }
249
250     private String resolveCtxVars(String key, SvcLogicContext ctx) {
251         if (key == null) {
252             return (null);
253         }
254
255         if (key.startsWith("'") && key.endsWith("'")) {
256             key = key.substring(1, key.length() - 1);
257             LOG.debug("Stripped outer single quotes - key is now [" + key + "]");
258         }
259
260         String[] keyTerms = key.split("\\s+");
261
262         StringBuffer sqlBuffer = new StringBuffer();
263
264         for (int i = 0; i < keyTerms.length; i++) {
265             sqlBuffer.append(resolveTerm(keyTerms[i], ctx));
266             sqlBuffer.append(" ");
267         }
268
269         return (sqlBuffer.toString());
270     }
271
272     private String resolveTerm(String term, SvcLogicContext ctx) {
273         if (term == null) {
274             return (null);
275         }
276
277         LOG.trace("resolveTerm: term is " + term);
278
279         if (term.startsWith("$") && (ctx != null)) {
280             // Resolve any index variables.
281             term = resolveCtxVariable(term.substring(1), ctx);
282             // Escape single quote
283             if (term != null) {
284                 term = term.replaceAll("'", "''");
285             }
286             return ("'" + term + "'");
287         } else {
288             return (term);
289         }
290
291     }
292
293     private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
294
295         if (ctxVarName.indexOf('[') == -1) {
296             // Ctx variable contains no arrays
297             if ("CRYPT_KEY".equals(ctxVarName)) {
298                 // Handle crypt key as special case. If it's set as a context
299                 // variable, use it. Otherwise, use
300                 // configured crypt key.
301                 String cryptKey = ctx.getAttribute(ctxVarName);
302                 if ((cryptKey != null) && (cryptKey.length() > 0)) {
303                     return (cryptKey);
304                 } else {
305                     return (CRYPT_KEY);
306                 }
307             }
308             return (ctx.getAttribute(ctxVarName));
309         }
310
311         // Resolve any array references
312         StringBuffer sbuff = new StringBuffer();
313         String[] ctxVarParts = ctxVarName.split("\\[");
314         sbuff.append(ctxVarParts[0]);
315         for (int i = 1; i < ctxVarParts.length; i++) {
316             if (ctxVarParts[i].startsWith("$")) {
317                 int endBracketLoc = ctxVarParts[i].indexOf("]");
318                 if (endBracketLoc == -1) {
319                     // Missing end bracket ... give up parsing
320                     LOG.warn("Variable reference " + ctxVarName + " seems to be missing a ']'");
321                     return (ctx.getAttribute(ctxVarName));
322                 }
323
324                 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
325                 String remainder = ctxVarParts[i].substring(endBracketLoc);
326
327                 sbuff.append("[");
328                 sbuff.append(ctx.getAttribute(idxVarName));
329                 sbuff.append(remainder);
330
331             } else {
332                 // Index is not a variable reference
333                 sbuff.append("[");
334                 sbuff.append(ctxVarParts[i]);
335             }
336         }
337
338         return (ctx.getAttribute(sbuff.toString()));
339     }
340
341     @Override
342     public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> parms,
343             String prefix, SvcLogicContext ctx) throws SvcLogicException {
344         return (executeSqlWrite(key, ctx));
345     }
346
347     private DbLibService getDbLibService() {
348
349         if (dblibSvc != null) {
350             return(dblibSvc);
351         }
352         // Try to get dblib as an OSGI service
353         BundleContext bctx = null;
354         ServiceReference sref = null;
355
356         Bundle bundle = FrameworkUtil.getBundle(SqlResource.class);
357
358         if (bundle != null) {
359             bctx = bundle.getBundleContext();
360         }
361
362         if (bctx != null) {
363             sref = bctx.getServiceReference(DBLIB_SERVICE);
364         }
365
366         if (sref == null) {
367             LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")");
368         } else {
369             dblibSvc = (DbLibService) bctx.getService(sref);
370             if (dblibSvc == null) {
371                 LOG.warn("Could not find service reference for DBLIB service (" + DBLIB_SERVICE + ")");
372             }
373         }
374
375         if (dblibSvc == null) {
376             // Must not be running in an OSGI container. See if you can load it
377             // as a
378             // a POJO then.
379
380             // If $SDNC_CONFIG_DIR/dblib.properties exists, that should
381             // be the properties passed to DBResourceManager constructor.
382             // If not, as default just use system properties.
383             Properties dblibProps = System.getProperties();
384             String cfgDir = System.getenv("SDNC_CONFIG_DIR");
385
386             if ((cfgDir == null) || (cfgDir.length() == 0)) {
387                 cfgDir = "/opt/sdnc/data/properties";
388             }
389
390             File dblibPropFile = new File(cfgDir + "/dblib.properties");
391             if (dblibPropFile.exists()) {
392                 try {
393                     dblibProps = new Properties();
394                     dblibProps.load(new FileInputStream(dblibPropFile));
395                 } catch (Exception e) {
396                     LOG.warn("Could not load properties file " + dblibPropFile.getAbsolutePath(), e);
397
398                     dblibProps = System.getProperties();
399                 }
400             }
401
402             try {
403                 dblibSvc = new DBResourceManager(dblibProps);
404             } catch (Exception e) {
405                 LOG.error("Caught exception trying to create dblib service", e);
406             }
407
408             if (dblibSvc == null) {
409                 LOG.warn("Could not create new DBResourceManager");
410             }
411         }
412
413         return (dblibSvc);
414     }
415
416     @Override
417     public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx)
418             throws SvcLogicException {
419         if (LOG.isDebugEnabled()) {
420             LOG.debug("SqlResource.notify called with resource=" + resource + ", action=" + action);
421         }
422         return QueryStatus.SUCCESS;
423     }
424
425     @Override
426     public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
427         return (executeSqlWrite(key, ctx));
428     }
429
430     public QueryStatus update(String resource, String key, Map<String, String> parms, String prefix,
431             SvcLogicContext ctx) throws SvcLogicException {
432         return (executeSqlWrite(key, ctx));
433     }
434
435     private String decryptColumn(String tableName, String colName, byte[] colValue, DbLibService dblibSvc) {
436         String strValue = new String(colValue);
437
438         if (StringUtils.isAsciiPrintable(strValue)) {
439
440             // If printable, not encrypted
441             return (strValue);
442         } else {
443             ResultSet results = null;
444             try (Connection conn =  dblibSvc.getConnection();
445                PreparedStatement stmt = conn.prepareStatement("SELECT CAST(AES_DECRYPT(?, ?) AS CHAR(50)) FROM DUAL")) {
446
447                 stmt.setBytes(1, colValue);
448                 stmt.setString(2, getCryptKey());
449                 results = stmt.executeQuery();
450
451                 if ((results != null) && results.next()) {
452                     strValue = results.getString(1);
453                     LOG.debug("Decrypted value is " + strValue);
454                 } else {
455                     LOG.warn("Cannot decrypt " + tableName + "." + colName);
456                 }
457             } catch (Exception e) {
458                 LOG.error("Caught exception trying to decrypt " + tableName + "." + colName, e);
459             }finally {
460                 if (results != null) {
461                     try {
462                         results.close();
463                     } catch (SQLException se) {
464                         LOG.error("Caught exception trying to close ResultSet",se);
465                     }
466                 }
467             }
468         }
469         return (strValue);
470     }
471
472     public static String getCryptKey() {
473         return (CRYPT_KEY);
474     }
475
476     public static String setCryptKey(String key) {
477         CRYPT_KEY = key;
478         return (CRYPT_KEY);
479     }
480
481     public String parameterizedQuery(Map<String, String> parameters, SvcLogicContext ctx) throws SvcLogicException {
482         DbLibService dblibSvc = getDbLibService();
483         String prefix = parameters.get("prefix");
484         String query = parameters.get("query");
485
486         ArrayList<String> arguments = new ArrayList<String>();
487         for (Entry<String, String> a : parameters.entrySet()) {
488             if (a.getKey().startsWith("param")) {
489                 arguments.add(a.getValue());
490             }
491         }
492
493         try {
494             if (dblibSvc == null) {
495                 return mapQueryStatus(QueryStatus.FAILURE);
496             }
497             if (query.contains("count") || query.contains("COUNT")) {
498                 CachedRowSet results = dblibSvc.getData(query, arguments, null);
499
500                 if (!results.next()) {
501                     return mapQueryStatus(QueryStatus.FAILURE);
502                 }
503
504                 int numRows = results.getInt(1);
505                 ctx.setAttribute(prefix + ".count", String.valueOf(numRows));
506                 if (numRows > 0) {
507                     return "true";
508                 } else {
509                     return "false";
510                 }
511             } else if (query.startsWith("select") || query.startsWith("SELECT")) {
512                 CachedRowSet results = dblibSvc.getData(query, arguments, null);
513                 if (!results.next()) {
514                     return mapQueryStatus(QueryStatus.NOT_FOUND);
515                 } else {
516                     saveCachedRowSetToCtx(results, ctx, prefix, dblibSvc);
517                 }
518             } else {
519                 if (!dblibSvc.writeData(query, arguments, null)) {
520                     return mapQueryStatus(QueryStatus.FAILURE);
521                 }
522             }
523             return mapQueryStatus(QueryStatus.SUCCESS);
524         } catch (SQLException e) {
525             LOG.error("Caught SQL exception", e);
526             return mapQueryStatus(QueryStatus.FAILURE);
527         }
528     }
529
530     protected String mapQueryStatus(QueryStatus status) {
531         String str = status.toString();
532         str = str.toLowerCase();
533         str = str.replaceAll("_", "-");
534         return str;
535     }
536 }