2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * ============LICENSE_END=========================================================
23 package org.onap.appc.data.services.db;
25 import java.sql.Connection;
26 import java.sql.PreparedStatement;
27 import java.sql.ResultSet;
28 import java.sql.ResultSetMetaData;
29 import java.sql.SQLException;
30 import java.util.ArrayList;
32 import javax.sql.rowset.CachedRowSet;
34 import org.apache.commons.lang3.StringUtils;
35 import org.onap.ccsdk.sli.core.dblib.DbLibService;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
41 public class CtxParameterizedResolver {
43 private static String CRYPT_KEY = "QtfJMKggVk";
44 private static final EELFLogger log = EELFManager.getInstance().getLogger(CtxParameterizedResolver.class);
46 protected static String resolveCtxVars(String key, SvcLogicContext ctx, ArrayList<String> arguments) {
51 if (key.startsWith("'") && key.endsWith("'")) {
52 key = key.substring(1, key.length() - 1);
53 log.debug("Stripped outer single quotes - key is now [" + key + "]");
56 String[] keyTerms = key.split("\\s+");
58 StringBuffer sqlBuffer = new StringBuffer();
60 for (int i = 0; i < keyTerms.length; i++) {
61 sqlBuffer.append(resolveTerm(keyTerms[i], ctx, arguments));
62 sqlBuffer.append(" ");
65 return (sqlBuffer.toString());
68 private static String resolveTerm(String term, SvcLogicContext ctx, ArrayList<String> arguments) {
73 log.trace("resolveTerm: term is " + term);
75 if (term.startsWith("$") && (ctx != null)) {
76 // Resolve any index variables.
77 term = resolveCtxVariable(term.substring(1), ctx);
78 // Escape single quote
80 term = term.replaceAll("'", "''");
82 //valueOf will store null values as a String "null"
83 arguments.add(String.valueOf(term));
91 private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
93 if (ctxVarName.indexOf('[') == -1) {
94 // Ctx variable contains no arrays
95 if ("CRYPT_KEY".equals(ctxVarName)) {
96 // Handle crypt key as special case. If it's set as a context
97 // variable, use it. Otherwise, use
98 // configured crypt key.
99 String cryptKey = ctx.getAttribute(ctxVarName);
100 if ((cryptKey != null) && (cryptKey.length() > 0)) {
106 return (ctx.getAttribute(ctxVarName));
109 // Resolve any array references
110 StringBuffer sbuff = new StringBuffer();
111 String[] ctxVarParts = ctxVarName.split("\\[");
112 sbuff.append(ctxVarParts[0]);
113 for (int i = 1; i < ctxVarParts.length; i++) {
114 if (ctxVarParts[i].startsWith("$")) {
115 int endBracketLoc = ctxVarParts[i].indexOf("]");
116 if (endBracketLoc == -1) {
117 // Missing end bracket ... give up parsing
118 log.warn("Variable reference " + ctxVarName + " seems to be missing a ']'");
119 return (ctx.getAttribute(ctxVarName));
122 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
123 String remainder = ctxVarParts[i].substring(endBracketLoc);
126 sbuff.append(ctx.getAttribute(idxVarName));
127 sbuff.append(remainder);
130 // Index is not a variable reference
132 sbuff.append(ctxVarParts[i]);
136 return (ctx.getAttribute(sbuff.toString()));
139 protected static void saveCachedRowSetToCtx(CachedRowSet results, SvcLogicContext ctx, String prefix, DbLibService dblibSvc)
140 throws SQLException {
142 if ((prefix != null) && prefix.endsWith("[]")) {
144 String pfx = prefix.substring(0, prefix.length() - 2);
147 ResultSetMetaData rsMeta = results.getMetaData();
148 int numCols = rsMeta.getColumnCount();
150 for (int i = 0; i < numCols; i++) {
151 String colValue = null;
152 String tableName = rsMeta.getTableName(i + 1);
153 if (rsMeta.getColumnType(i + 1) == java.sql.Types.VARBINARY) {
154 colValue = decryptColumn(tableName, rsMeta.getColumnName(i + 1), results.getBytes(i + 1),
157 colValue = results.getString(i + 1);
159 log.debug("Setting " + pfx + "[" + idx + "]."
160 + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue);
161 ctx.setAttribute(pfx + "[" + idx + "]." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"),
165 } while (results.next());
166 log.debug("Setting " + pfx + "_length = " + idx);
167 ctx.setAttribute(pfx + "_length", "" + idx);
169 ResultSetMetaData rsMeta = results.getMetaData();
170 int numCols = rsMeta.getColumnCount();
172 for (int i = 0; i < numCols; i++) {
173 String colValue = null;
174 String tableName = rsMeta.getTableName(i + 1);
175 if ("VARBINARY".equalsIgnoreCase(rsMeta.getColumnTypeName(i + 1))) {
176 colValue = decryptColumn(tableName, rsMeta.getColumnName(i + 1), results.getBytes(i + 1),
179 colValue = results.getString(i + 1);
181 if (prefix != null) {
182 log.debug("Setting " + prefix + "." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = "
184 ctx.setAttribute(prefix + "." + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue);
186 log.debug("Setting " + rsMeta.getColumnLabel(i + 1).replaceAll("_", "-") + " = " + colValue);
187 ctx.setAttribute(rsMeta.getColumnLabel(i + 1).replaceAll("_", "-"), colValue);
194 private static String decryptColumn(String tableName, String colName, byte[] colValue, DbLibService dblibSvc) {
195 String strValue = new String(colValue);
197 if (StringUtils.isAsciiPrintable(strValue)) {
199 // If printable, not encrypted
202 ResultSet results = null;
203 try (Connection conn = dblibSvc.getConnection();
204 PreparedStatement stmt = conn.prepareStatement("SELECT CAST(AES_DECRYPT(?, ?) AS CHAR(50)) FROM DUAL")) {
206 stmt.setBytes(1, colValue);
207 stmt.setString(2, CRYPT_KEY);
208 results = stmt.executeQuery();
210 if ((results != null) && results.next()) {
211 strValue = results.getString(1);
212 log.debug("Decrypted value is " + strValue);
214 log.warn("Cannot decrypt " + tableName + "." + colName);
216 } catch (Exception e) {
217 log.error("Caught exception trying to decrypt " + tableName + "." + colName, e);
219 if (results != null) {
222 } catch (SQLException se) {
223 log.error("Caught exception trying to close ResultSet",se);