Advertisement
Guest User

Untitled

a guest
Mar 30th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.65 KB | None | 0 0
  1.  
  2. /*
  3. The MIT License (MIT)
  4.  
  5. Copyright (c) 2014 sinfonier-project
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in
  15. all copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. THE SOFTWARE.
  24. */
  25.  
  26. package com.sinfonier.bolts;
  27.  
  28. import java.sql.Connection;
  29. import java.sql.DatabaseMetaData;
  30. import java.sql.DriverManager;
  31. import java.sql.PreparedStatement;
  32. import java.sql.ResultSet;
  33. import java.sql.SQLException;
  34. import java.util.ArrayList;
  35. import java.util.Date;
  36. import java.util.List;
  37. import java.util.Map;
  38.  
  39. /**
  40. * JDBC Bolt to insert or update row
  41. *
  42. * @author jmdiez
  43. */
  44.  
  45. public class JDBCBolt extends BaseSinfonierBolt {
  46.  
  47.  
  48. private static final long serialVersionUID = 7799073747630789816L;
  49.  
  50. private static final boolean CHECKNOTNULL = true;
  51.  
  52. private boolean debug = true;
  53. private String driver; // p.e. "com.mysql.jdbc.Driver"
  54. private String url; // p.e. "jdbc:mysql://localhost:3306/mydb"
  55. private String user;
  56. private String password;
  57. private String tableName;
  58. private String[] fields;
  59. private List<String> pks;
  60. private String errorField;
  61. private transient Connection conn;
  62. private boolean error = false;
  63. private Date lastConn;
  64.  
  65. public JDBCBolt(String xmlFile) {
  66. super(xmlFile);
  67. }
  68.  
  69. @Override
  70. public void userprepare() {
  71.  
  72. conn = null;
  73. driver = getParam("driver");
  74. url = getParam("url");
  75. user = getParam("user");
  76. password = getParam("password");
  77. this.tableName = this.getParam("tablename", JDBCBolt.CHECKNOTNULL);
  78. this.errorField = this.getParam("errorField");
  79. if (errorField == null) {
  80. errorField = "error";
  81. }
  82.  
  83. List<Object> list = this.getParamList("fields");
  84. fields = new String[list.size()];
  85. list.toArray(fields);
  86.  
  87. open();
  88. pks = getPks();
  89.  
  90. }
  91.  
  92. @Override
  93. public void userexecute() {
  94. if (!existsField(errorField)) {
  95. Map<String,Object> tuple = getJson();
  96. if (existsRow(tuple))
  97. {
  98. createAndExecuteUpdate(tuple);
  99. } else
  100. {
  101. createAndExecuteInsert(tuple);
  102. }
  103.  
  104. }
  105. emit();
  106. }
  107.  
  108. public void usercleanup() {
  109. closedb();
  110. }
  111.  
  112. /**
  113. * Connect to a jdbc database
  114. *
  115. */
  116. public Connection open() {
  117. try {
  118. Class.forName(driver);
  119. } catch (ClassNotFoundException e) {
  120. debug("JDBC driver not found");
  121. e.printStackTrace();
  122. error = true;
  123. return null;
  124. }
  125.  
  126. try {
  127. conn = DriverManager.getConnection(url, user, password);
  128.  
  129. } catch (SQLException e) {
  130. debug("Connection Failed! Check output console");
  131. e.printStackTrace();
  132. error = true;
  133. return conn;
  134. }
  135.  
  136. if (conn != null) {
  137. debug("Connected To Database");
  138. } else {
  139. error = true;
  140. debug("Failed to make connection!");
  141. }
  142. lastConn = new Date();
  143. error = false;
  144. return conn;
  145. }
  146.  
  147. private boolean existsRow(Map<String, Object> tuple)
  148. {
  149. String firstPk = pks.get(0);
  150. StringBuilder query = new StringBuilder(String.format("SELECT %s FROM %s ",firstPk, tableName));
  151. query.append(buildWherePks());
  152. try {
  153. PreparedStatement preparedStatement = conn.prepareStatement(query.toString());
  154. int i=1;
  155. for ( String key: pks )
  156. {
  157. preparedStatement.setObject(i++, tuple.get(key));
  158. }
  159.  
  160. ResultSet rs = preparedStatement.executeQuery();
  161. while(rs.next())
  162. {
  163. return true;
  164. }
  165. } catch (Exception ex) {
  166. addField(errorField, ex.getMessage());
  167. addField(errorField + "Query", query.toString());
  168. }
  169.  
  170. return false;
  171. }
  172.  
  173. private String buildWherePks() {
  174.  
  175. String sep = " WHERE ";
  176. StringBuilder where = new StringBuilder(" ");
  177. for ( String key: pks )
  178. {
  179. where.append(sep);
  180. where.append(String.format("%s = ?", key));
  181. sep = " AND ";
  182. }
  183.  
  184. return where.toString();
  185.  
  186. }
  187.  
  188. /**
  189. * Create a valid query for JDBC from a Map<String, Object> and executes
  190. * it
  191. *
  192. * @param tuple
  193. * Map with the keys and values for each field.
  194. */
  195. private void createAndExecuteInsert(Map<String, Object> tuple) {
  196. StringBuilder query = new StringBuilder(String.format("INSERT INTO %s (",tableName));
  197. List<Object> fieldValues = new ArrayList<Object>();
  198. List<String> questions = new ArrayList<String>(fields.length);
  199. if (fields != null && fields.length > 0) {
  200.  
  201. query.append(String.join(",",fields));
  202. query.append(") VALUES (");
  203. for (int i = 0; i < fields.length; i++) {
  204. fieldValues.add(tuple.get(fields[i]));
  205. questions.add("?");
  206. }
  207. query.append(String.join(",",questions));
  208. query.append(") ");
  209. } else {
  210. List<String> fieldNames = new ArrayList<String>(tuple.size());
  211. for (Map.Entry<String, Object> entry : tuple.entrySet()) {
  212. fieldNames.add(entry.getKey());
  213. questions.add("?");
  214. fieldValues.add(entry.getValue());
  215. }
  216. query.append(String.join(",",fieldNames));
  217. query.append(") VALUES (");
  218. query.append(String.join(",",questions));
  219. query.append(") ");
  220. }
  221.  
  222. try {
  223. PreparedStatement preparedStatement = conn.prepareStatement(query.toString());
  224. int i=1;
  225. for (Object obj: fieldValues)
  226. {
  227. preparedStatement.setObject(i++, obj);
  228. }
  229.  
  230. preparedStatement.executeUpdate();
  231. } catch (Exception ex) {
  232. addField(errorField, ex.getMessage());
  233. addField(errorField + "Query", query.toString());
  234. }
  235. }
  236.  
  237. /**
  238. * Gets the primary keys of the table;
  239. */
  240. private List<String> getPks()
  241. {
  242. List<String> lsPks = new ArrayList<String>();
  243. try {
  244. DatabaseMetaData dmd = conn.getMetaData();
  245. ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);
  246.  
  247.  
  248. while(rs.next()){
  249. lsPks.add(rs.getString("COLUMN_NAME"));
  250. }
  251. }catch (SQLException e) {
  252. e.printStackTrace();
  253. }
  254.  
  255. return lsPks;
  256. }
  257.  
  258. /**
  259. * Create a valid query for JDBC from a Map<String, Object> and executes
  260. * it
  261. *
  262. * @param tuple
  263. * Map with the keys and values for each field.
  264. */
  265. private void createAndExecuteUpdate(Map<String, Object> tuple) {
  266. StringBuilder query = new StringBuilder(String.format("UPDATE %s SET ",tableName));
  267. List<Object> fieldValues = new ArrayList<Object>();
  268. String sep = "";
  269. if (fields != null && fields.length > 0) {
  270.  
  271. for (int i = 0; i < fields.length; i++) {
  272. if (! pks.contains(fields[i]))
  273. {
  274. query.append(String.format("%s %s = ?",sep,fields[i]));
  275. fieldValues.add(tuple.get(fields[i]));
  276. sep = ",";
  277. }
  278. }
  279. } else {
  280. for (Map.Entry<String, Object> entry : tuple.entrySet()) {
  281. if (!pks.contains(entry.getKey()))
  282. {
  283. query.append(String.format("%s %s = ?",sep, entry.getKey()));
  284. fieldValues.add(entry.getValue());
  285. sep = ",";
  286. }
  287. }
  288.  
  289. }
  290. query.append(buildWherePks());
  291. try {
  292. PreparedStatement preparedStatement = conn.prepareStatement(query.toString());
  293. int i=1;
  294. for (Object obj: fieldValues)
  295. {
  296. preparedStatement.setObject(i++, obj);
  297. }
  298. for (String pk: pks)
  299. {
  300. preparedStatement.setObject(i++, tuple.get(pk));
  301. }
  302. preparedStatement.executeUpdate();
  303. } catch (Exception ex) {
  304. addField(errorField, ex.getMessage());
  305. addField(errorField + "Query", query.toString());
  306. }
  307. }
  308.  
  309.  
  310. public void closedb()
  311. {
  312. if (conn != null)
  313. {
  314. try {
  315. conn.close();
  316. } catch (SQLException e) {
  317. error = true;
  318. e.printStackTrace();
  319. }
  320. }
  321. }
  322. public void reopen()
  323. {
  324. debug("Reconnecting to Database");
  325. closedb();
  326.  
  327. open();
  328. }
  329.  
  330. private void debug(String str)
  331. {
  332. if (debug)
  333. System.out.println(str);
  334. }
  335.  
  336.  
  337. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement