aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/att/research/mdbc/mixins/Utils.java
blob: 22df08f9e5f08fafd89bcb51a8662f21e10a3227 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package com.att.research.mdbc.mixins;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.json.JSONObject;

import com.att.research.logging.EELFLoggerDelegate;
import com.att.research.mdbc.TableInfo;
import com.datastax.driver.core.utils.Bytes;

/**
 * Utility functions used by several of the mixins should go here.
 *
 * @author Robert P. Eby
 */
public class Utils {
	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Utils.class);
	
	/**
	 * Transforms and JsonObject into an array of objects
	 * @param ti information related to the table
	 * @param tbl table that jo belong to
	 * @param jo object that represents a row in the table
	 * @param musicDefaultPrimaryKeyName contains the name of key associated with the default primary key used by MUSIC, it can be null, if not requird 
	 * @return array with the objects in the row
	 */
	public static Object[] jsonToRow(TableInfo ti, String tbl, JSONObject jo, String musicDefaultPrimaryKeyName) {
		int columnSize = ti.columns.size();
		ArrayList<Object> rv = new ArrayList<Object>();
		if (musicDefaultPrimaryKeyName!=null && jo.has(musicDefaultPrimaryKeyName)) { 
			rv.add(jo.getString(musicDefaultPrimaryKeyName)); 
		}
		for (int i = 0; i < columnSize; i++) {
			String colname = ti.columns.get(i);
			switch (ti.coltype.get(i)) {
			case Types.BIGINT:
				rv.add(jo.optLong(colname, 0));
				break;
			case Types.BOOLEAN:
				rv.add(jo.optBoolean(colname, false));
				break;
			case Types.BLOB:
				rv.add(jo.optString(colname, ""));
				break;
			case Types.DECIMAL:
				rv.add(jo.optBigDecimal(colname, BigDecimal.ZERO));
				break;
			case Types.DOUBLE:
				rv.add(jo.optDouble(colname, 0));
				break;
			case Types.INTEGER:
				rv.add(jo.optInt(colname, 0));
				break;
			case Types.TIMESTAMP:
				//rv[i] = new Date(jo.optString(colname, ""));
				rv.add(jo.optString(colname, ""));
				break;
			case Types.DATE:
			case Types.VARCHAR:
				//Fall through
			default:
				rv.add(jo.optString(colname, ""));
				break;
			}
		}
		return rv.toArray();
	}
	
	/**
	 * Return a String equivalent of an Object.  Useful for writing SQL.
	 * @param val the object to String-ify
	 * @return the String value
	 */
	public static String getStringValue(Object val) {
		if (val == null)
			return "NULL";
		if (val instanceof String)
			return "'" + val.toString().replaceAll("'", "''") + "'";	// double any quotes
		if (val instanceof Number)
			return ""+val;
		if (val instanceof ByteBuffer)
			return "'" + Bytes.toHexString((ByteBuffer)val).substring(2) + "'";	// substring(2) is to remove the "0x" at front
		if (val instanceof Date)
			return "'" + (new Timestamp(((Date)val).getTime())).toString() + "'";
		// Boolean, and anything else
		return val.toString();
	}
	
	/**
	 * Parse result set and put into object array
	 * @param tbl
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	public static ArrayList<Object[]> parseResults(TableInfo ti, ResultSet rs) throws SQLException {
		ArrayList<Object[]> results = new ArrayList<Object[]>(); 
		while (rs.next()) {
			Object[] row = new Object[ti.columns.size()];
			for (int i = 0; i < ti.columns.size(); i++) {
				String colname = ti.columns.get(i);
				switch (ti.coltype.get(i)) {
				case Types.BIGINT:
					row[i] = rs.getLong(colname);
					break;
				case Types.BOOLEAN:
					row[i] = rs.getBoolean(colname);
					break;
				case Types.BLOB:
					System.err.println("WE DO NOT SUPPORT BLOBS IN H2!! COLUMN NAME="+colname);
					//logger.error("WE DO NOT SUPPORT BLOBS IN H2!! COLUMN NAME="+colname);
					// throw an exception here???
					break;
				case Types.DOUBLE:
					row[i] = rs.getDouble(colname);
					break;
				case Types.INTEGER:
					row[i] = rs.getInt(colname);
					break;
				case Types.TIMESTAMP:
					//rv[i] = new Date(jo.optString(colname, ""));
					row[i] = rs.getString(colname);
					break;
				case Types.VARCHAR:
					//Fall through
				default:
					row[i] = rs.getString(colname);
					break;
				}
			}
			results.add(row);
		}
		return results;
	}

	@SuppressWarnings("unused")
	static List<Class<?>> getClassesImplementing(Class<?> implx) {
		Properties pr = null;
		try {
			pr = new Properties();
			pr.load(Utils.class.getResourceAsStream("/mdbc_driver.properties"));
		}
		catch (IOException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "Could not load property file > " + e.getMessage());
		}
		
		List<Class<?>> list = new ArrayList<Class<?>>();
		if (pr==null) {
			return list;
		}
		String mixins = pr.getProperty("MIXINS");
		for (String className: mixins.split("[ ,]")) {
			try {
				Class<?> cl = Class.forName(className.trim());
				if (MixinFactory.impl(cl, implx)) {
					list.add(cl);
				}
			} catch (ClassNotFoundException e) {
				logger.error(EELFLoggerDelegate.errorLogger,"Mixin class "+className+" not found.");
			}
		}
		return list;
	}
	
	public static void registerDefaultDrivers() {
		Properties pr = null;
		try {
			pr = new Properties();
			pr.load(Utils.class.getResourceAsStream("/mdbc_driver.properties"));
		}
		catch (IOException e) {
			logger.error("Could not load property file > " + e.getMessage());
		}
		
		@SuppressWarnings("unused")
		List<Class<?>> list = new ArrayList<Class<?>>();
		String drivers = pr.getProperty("DEFAULT_DRIVERS");
		for (String driver: drivers.split("[ ,]")) {
			logger.info(EELFLoggerDelegate.applicationLogger, "Registering jdbc driver '" + driver + "'");
			try {
				@SuppressWarnings("unused")
				Class<?> cl = Class.forName(driver.trim());
			} catch (ClassNotFoundException e) {
				logger.error(EELFLoggerDelegate.errorLogger,"Driver class "+driver+" not found.");
			}
		}		
	}

	public static Properties getMdbcProperties() {
		Properties prop = new Properties();
		InputStream input = null;
		try {
			input = Utils.class.getClassLoader().getResourceAsStream("/mdbc.properties");
			prop.load(input);
		} catch (Exception e) {
			logger.warn(EELFLoggerDelegate.applicationLogger, "Could load mdbc.properties."
					+ "Proceeding with defaults " + e.getMessage());
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
				}
			}
		}
		return prop;
	}
}