PageRenderTime 37ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/v2_0_5/generator/src/org/collazos/generator/GenerateUtil.java

#
Java | 497 lines | 444 code | 25 blank | 28 comment | 21 complexity | 6087c066b22dae9fb5ecb225255014a0 MD5 | raw file
Possible License(s): LGPL-2.1
  1. /*
  2. * generator Database Bean Generator
  3. * Copyright (C) 2005 Josep Carles Collazos
  4. *
  5. * This software is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2.1 of the License, or (at your option) any later version.
  9. *
  10. * This software is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. *
  19. * Josep Carles Collazos
  20. * mailto: jespo@users.sourceforge.net
  21. *
  22. */
  23. package org.collazos.generator;
  24. import java.io.BufferedWriter;
  25. import java.io.File;
  26. import java.io.FileWriter;
  27. import java.io.IOException;
  28. import java.sql.Connection;
  29. import java.sql.ResultSet;
  30. import java.sql.SQLException;
  31. import java.sql.Statement;
  32. import java.util.Properties;
  33. import org.collazos.generator.bdexception.BaseRuntimeException;
  34. import org.collazos.util.database.ConnectDB;
  35. import electric.xml.Element;
  36. /**
  37. * Type description
  38. *
  39. * @author Josep Carles Collazos
  40. * @created 11-mar-2005
  41. */
  42. public class GenerateUtil {
  43. private Properties props;
  44. private boolean valueAsAttribute = false;
  45. private boolean stringsAsCdata = false;
  46. private String basedir;
  47. private String packageName;
  48. private boolean tofile;
  49. private boolean toStdout;
  50. private BufferedWriter output;
  51. private String connectionOpen;
  52. private String connectionClose;
  53. private String connectionPackage;
  54. private String exceptionPackage;
  55. private String xmlImport;
  56. private boolean isEnabled;
  57. private String xmlRowName;
  58. private String xmlFieldName;
  59. private String xmlRowidName;
  60. private String xmlValueName;
  61. private boolean isOracle;
  62. private boolean hasLogs;
  63. public GenerateUtil(Properties props) {
  64. this.props = props;
  65. this.basedir = (String) props.get("generator.io.basedir");
  66. this.packageName = (String) props.get("generator.class.package");
  67. this.tofile = new Boolean((String) props.get("generator.io.file")).booleanValue();
  68. this.toStdout = new Boolean((String) props.get("generator.io.stdout")).booleanValue();
  69. this.connectionOpen = (String) props.get("generator.database.connection.open");
  70. this.connectionClose = (String) props.get("generator.database.connection.close");
  71. this.exceptionPackage = (String) props.get("generator.database.exception.package");
  72. this.connectionPackage = (String) props.get("generator.database.connection.package");
  73. this.xmlImport = (String) props.get("generator.xml.import");
  74. this.isEnabled = new Boolean((String) props.get("generator.static.enabled")).booleanValue();
  75. this.xmlRowName = (String) props.getProperty("generator.static.row.name","row");
  76. this.xmlFieldName = (String) props.getProperty("generator.static.field.name","field");
  77. this.xmlRowidName = (String) props.getProperty("generator.static.rowid.name","rowid");
  78. this.xmlValueName = (String) props.getProperty("generator.static.value.name","value");
  79. this.valueAsAttribute = new Boolean((String) props.get("generator.static.value.attribute")).booleanValue();
  80. this.stringsAsCdata = new Boolean((String) props.get("generator.static.strings.cdata")).booleanValue();
  81. this.isOracle = ((String) props.get("generator.database.driver")).indexOf("oracle")!=-1;
  82. this.hasLogs = new Boolean((String) props.get("generator.log.enabled")).booleanValue();
  83. }
  84. public void out(String text) throws IOException{
  85. if (this.toStdout)
  86. System.out.println(text);
  87. if (this.tofile)
  88. output.write(text+"\n");
  89. }
  90. public static Element executeQueryToXml(String sql) {
  91. Connection con = null;
  92. Statement stm = null;
  93. ResultSet rs = null;
  94. int k=0;
  95. try {
  96. con = ConnectDB.getSimpleConnection();
  97. stm = con.createStatement();
  98. rs = stm.executeQuery(sql);
  99. Element queryResult = new Element("query-result");
  100. int numColumns = rs.getMetaData().getColumnCount();
  101. String[] fieldName = new String[numColumns];
  102. String[] fieldType = new String[numColumns];
  103. for (int i=0;i<numColumns;i++) {
  104. fieldName[i]=rs.getMetaData().getColumnName(i+1);
  105. int numType = rs.getMetaData().getColumnType(i+1);
  106. ColumnData cd = new ColumnData(fieldName[i],numType,1);
  107. fieldType[i]=cd.getJavaType();
  108. }
  109. while (rs.next()) {
  110. Element tmpElem = new Element("row");
  111. for (int i=0;i<numColumns;i++) {
  112. String fieldValue=rs.getString(fieldName[i]);
  113. Element fieldElem = new Element("field");
  114. fieldElem.setAttribute("name",fieldName[i]);
  115. fieldElem.setAttribute("java-type",fieldType[i]);
  116. fieldElem.setText(rs.getString(fieldName[i]));
  117. tmpElem.addChild(fieldElem);
  118. }
  119. tmpElem.setAttribute("rowid",""+k);
  120. queryResult.addChild(tmpElem);
  121. k++;
  122. }
  123. return queryResult;
  124. } catch (Exception e) {
  125. throw new BaseRuntimeException(e.toString());
  126. } finally {
  127. if (rs != null) try { rs.close(); } catch (Exception ignored) {}
  128. if (stm != null) try { stm.close(); } catch (Exception ignored) {}
  129. if (con != null) ConnectDB.putConnection(con);
  130. }
  131. }
  132. public void writeHeader() throws IOException {
  133. out("//Generation Date: "+new java.util.Date());
  134. out("package "+packageName+";");
  135. out("");
  136. out("import java.sql.*;");
  137. out("import "+this.connectionPackage+";");
  138. out("import "+this.exceptionPackage+".*;");
  139. out("import "+this.xmlImport+";");
  140. out("");
  141. out("/**");
  142. out(" * BdUtils");
  143. out(" * Generator version: "+GenerateSkel.version);
  144. out(" * Class to provide some useful stuff.");
  145. out(" * Generation Date: "+new java.util.Date());
  146. out(" * ");
  147. out(" */");
  148. out("public class BdUtils {");
  149. out("");
  150. if (hasLogs)
  151. out(" private static ISimpleLogger logger = new Logger(System.out);");
  152. out("");
  153. }
  154. public void writeConstructor() throws IOException {
  155. out(" public BdUtils() {");
  156. out(" }");
  157. out("");
  158. }
  159. public void writeExecuteUpdate() throws IOException {
  160. out(" public static int executeUpdate(String sql) {");
  161. out(" Connection con = null;");
  162. out(" Statement stm = null;");
  163. out(" int result = -1;");
  164. out(" try {");
  165. if (this.hasLogs)
  166. out(" logger.log(\"[executeUpdate] SQL:\"+sql);");
  167. out(" con = "+this.connectionOpen+";");
  168. out(" stm = con.createStatement();");
  169. out(" result = stm.executeUpdate(sql);");
  170. out(" return result;");
  171. out(" } catch (Exception e) {");
  172. out(" throw new BaseRuntimeException(e.toString());");
  173. out(" } finally {");
  174. out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
  175. out(" if (con != null) "+this.connectionClose+";");
  176. out(" }");
  177. out(" }");
  178. out("");
  179. }
  180. public void writeExecuteUpdate2() throws IOException {
  181. out(" ");
  182. out(" public static int executeUpdate(Connection con, String sql) {");
  183. out(" Statement stm = null;");
  184. out(" int result = -1;");
  185. out(" try {");
  186. out(" stm = con.createStatement();");
  187. out(" result = stm.executeUpdate(sql);");
  188. out(" return result;");
  189. out(" } catch (Exception e) {");
  190. out(" throw new BaseRuntimeException(e.toString());");
  191. out(" } finally {");
  192. out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
  193. out(" }");
  194. out(" }");
  195. }
  196. public void writeExecuteQuery() throws IOException {
  197. out(" public static Element executeQueryToXml(String sql) {");
  198. out(" Connection con = null;");
  199. out(" Statement stm = null;");
  200. out(" ResultSet rs = null;");
  201. out(" int k=0;");
  202. out(" try {");
  203. out(" con = "+this.connectionOpen+";");
  204. if (this.hasLogs)
  205. out(" logger.log(\"[executeQueryToXml] SQL:\"+sql);");
  206. out(" stm = con.createStatement();");
  207. out(" rs = stm.executeQuery(sql);");
  208. out(" Element queryResult = new Element(\"query-result\");");
  209. out(" int numColumns = rs.getMetaData().getColumnCount();");
  210. out(" String[] fieldName = new String[numColumns];");
  211. out(" String[] fieldType = new String[numColumns];");
  212. out(" for (int i=0;i<numColumns;i++) {");
  213. out(" fieldName[i]=rs.getMetaData().getColumnName(i+1);");
  214. out(" int numType = rs.getMetaData().getColumnType(i+1);");
  215. out(" ColumnData cd = new ColumnData(fieldName[i],numType,1);");
  216. out(" fieldType[i]=cd.getJavaType();");
  217. out(" }");
  218. out(" while (rs.next()) {");
  219. out(" Element tmpElem = new Element(\""+this.xmlRowName+"\");");
  220. out(" for (int i=0;i<numColumns;i++) {");
  221. out(" String fieldValue=rs.getString(fieldName[i]);");
  222. out(" Element fieldElem = new Element(\""+this.xmlFieldName+"\");");
  223. out(" fieldElem.setAttribute(\"name\",fieldName[i]);");
  224. out(" fieldElem.setAttribute(\"java-type\",fieldType[i]);");
  225. if (valueAsAttribute)
  226. out(" fieldElem.setAttribute(\""+this.xmlValueName+"\",rs.getString(fieldName[i]));");
  227. else {
  228. if (stringsAsCdata) {
  229. out(" if (fieldType[i].equals(\"String\")) {");
  230. out(" CData txtCdata = new CData(rs.getString(fieldName[i]));");
  231. out(" fieldElem.setText(txtCdata);");
  232. out(" } else {");
  233. out(" fieldElem.setText(rs.getString(fieldName[i]));");
  234. out(" }");
  235. }
  236. else
  237. out(" fieldElem.setText(rs.getString(fieldName[i]));");
  238. }
  239. out(" tmpElem.addChild(fieldElem);");
  240. out(" }");
  241. out(" tmpElem.setAttribute(\""+this.xmlRowidName+"\",\"\"+k);");
  242. out(" queryResult.addChild(tmpElem);");
  243. out(" k++;");
  244. out(" }");
  245. out(" return queryResult;");
  246. out(" } catch (Exception e) {");
  247. out(" throw new BaseRuntimeException(e.toString());");
  248. out(" } finally {");
  249. out(" if (rs != null) try { rs.close(); } catch (Exception ignored) {}");
  250. out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
  251. out(" if (con != null) "+this.connectionClose+";");
  252. out(" }");
  253. out(" }");
  254. out("");
  255. }
  256. public void writeReplaceString() throws IOException {
  257. out(" public static String replaceString (String str, String find, String replace) {");
  258. out(" if (str == null) return null;");
  259. out(" if ((find == null) || (find.length() == 0)) return str;");
  260. out(" if (replace == null) replace = \"\";");
  261. out(" StringBuffer sb = new StringBuffer(str.length());");
  262. out(" int pos = 0;");
  263. out(" int lastPos = 0;");
  264. out(" while (pos >= 0) {");
  265. out(" pos = str.indexOf(find, lastPos);");
  266. out(" if (pos >= 0) {");
  267. out(" sb.append(str.substring(lastPos, pos));");
  268. out(" sb.append(replace);");
  269. out(" } else {");
  270. out(" sb.append(str.substring(lastPos));");
  271. out(" }");
  272. out(" lastPos = pos + find.length();");
  273. out(" }");
  274. out(" return sb.toString();");
  275. out(" }");
  276. }
  277. public void writeGetNextSequenceValue() throws IOException {
  278. out(" ");
  279. out(" public static int getNextSequenceValue(String sequenceName,Connection con) {");
  280. out(" String sql=\"select \"+sequenceName+\".nextval from dual\";");
  281. out(" Statement stm = null;");
  282. out(" ResultSet rs = null;");
  283. out(" int k=0;");
  284. out(" try {");
  285. if (this.hasLogs)
  286. out(" logger.log(\"[getNextSequenceValue] SQL:\"+sql);");
  287. out(" stm = con.createStatement();");
  288. out(" rs = stm.executeQuery(sql);");
  289. out(" rs.next();");
  290. out(" int id = rs.getInt(1);");
  291. out(" return id;");
  292. out(" } catch (Exception e) {");
  293. out(" throw new BaseRuntimeException(e.toString());");
  294. out(" } finally {");
  295. out(" if (rs != null) try { rs.close(); } catch (Exception ignored) {}");
  296. out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
  297. out(" }");
  298. out(" }");
  299. out("");
  300. }
  301. public void writeColumnDataClass() throws IOException {
  302. out(" ");
  303. out(" ");
  304. out(" ");
  305. out(" private static class ColumnData");
  306. out(" {");
  307. out(" String[] sqlTypes = { \"CHAR\",\"TINYINT\",\"BIGINT\",\"INT\",\"SMALLINT\",\"FLOAT\",\"REAL\",\"DOUBLE\",\"NUMERIC\",\"DECIMAL\",\"DATE\",\"VARCHAR\",\"LONGVARCHAR\",\"TIMESTAMP\",\"TIME\",\"BIT\",\"BINARY\",\"VARBINARY\",\"LONGVARBINARY\",\"NULL\",\"OTHER\",\"TEXT\" };");
  308. out(" int type;");
  309. out(" int columns;");
  310. out(" String name;");
  311. out(" public ColumnData (String name,int origType, int columns)");
  312. out(" {");
  313. out(" this.name = name;");
  314. out(" this.type = origType;");
  315. out(" this.columns = columns;");
  316. out(" switch (type)");
  317. out(" {");
  318. out(" case -1:");
  319. out(" break;");
  320. out(" case -2:");
  321. out(" type = 18;");
  322. out(" break;");
  323. out(" case -3:");
  324. out(" type = 19;");
  325. out(" break;");
  326. out(" case -4:");
  327. out(" type = 19;");
  328. out(" break;");
  329. out(" case -5:");
  330. out(" type = 3;");
  331. out(" break;");
  332. out(" case -6:");
  333. out(" type = 2;");
  334. out(" break;");
  335. out(" case -7:");
  336. out(" type = 16;");
  337. out(" break;");
  338. out(" case 1111:");
  339. out(" type = 3;");
  340. out(" break;");
  341. out(" case 91:");
  342. out(" type = 11;");
  343. out(" break;");
  344. out(" case 92:");
  345. out(" type = 14;");
  346. out(" break;");
  347. out(" case 93:");
  348. out(" type = 14;");
  349. out(" break;");
  350. out(" default:");
  351. out(" break;");
  352. out(" }");
  353. out(" }");
  354. out(" public ColumnData (String name, String coltype, int columns)");
  355. out(" {");
  356. out(" this.name = name;");
  357. out(" this.columns = columns;");
  358. out(" int i=0;");
  359. out(" boolean quit = false;");
  360. out(" this.type = -1; // invalid");
  361. out(" while (!quit)");
  362. out(" {");
  363. out(" if (coltype.toUpperCase().compareTo(sqlTypes[i]) == 0)");
  364. out(" {");
  365. out(" this.type = i+1;");
  366. out(" quit = true;");
  367. out(" }");
  368. out(" i++;");
  369. out(" if (i>=sqlTypes.length)");
  370. out(" quit = true;");
  371. out(" }");
  372. out(" }");
  373. out(" public String getName() {");
  374. out(" return name;");
  375. out(" }");
  376. out(" public String getJavaType()");
  377. out(" {");
  378. out(" String jType = null;");
  379. out(" switch (type)");
  380. out(" {");
  381. out(" case 1:");
  382. out(" case 12:");
  383. out(" case 13:");
  384. out(" case 22:");
  385. out(" jType = \"String\";");
  386. out(" break;");
  387. out(" case 2:");
  388. out(" jType = \"byte\";");
  389. out(" break;");
  390. out(" case 3:");
  391. out(" jType = \"long\";");
  392. out(" break;");
  393. out(" case 4:");
  394. out(" jType = \"int\";");
  395. out(" break;");
  396. out(" case 5:");
  397. out(" jType = \"short\";");
  398. out(" break;");
  399. out(" case 6:");
  400. out(" case 8:");
  401. out(" jType = \"double\";");
  402. out(" break;");
  403. out(" case 9:");
  404. out(" case 10:");
  405. out(" jType = \"java.math.BigDecimal\";");
  406. out(" break;");
  407. out(" case 7:");
  408. out(" jType = \"float\";");
  409. out(" break;");
  410. out(" case 11:");
  411. out(" jType = \"java.util.Date\";");
  412. out(" break;");
  413. out(" case 14:");
  414. out(" jType = \"Timestamp\";");
  415. out(" break;");
  416. out(" case 15:");
  417. out(" jType = \"Time\";");
  418. out(" break;");
  419. out(" case 16:");
  420. out(" jType = \"boolean\";");
  421. out(" break;");
  422. out(" case 17:");
  423. out(" case 18:");
  424. out(" case 19:");
  425. out(" jType = \"byte[]\";");
  426. out(" break;");
  427. out(" case 20:");
  428. out(" jType = \"null\";");
  429. out(" break;");
  430. out(" default:");
  431. out(" jType = \"unknown\";");
  432. out(" break;");
  433. out(" }");
  434. out(" return jType;");
  435. out(" }");
  436. out(" public String getType() {");
  437. out(" if ((type > sqlTypes.length) || (type < 0))");
  438. out(" return \"\"+type;");
  439. out(" else");
  440. out(" return sqlTypes[type-1];");
  441. out(" }");
  442. out(" } ");
  443. out("");
  444. }
  445. public void generate() throws IOException, SQLException {
  446. if (!isEnabled)
  447. return;
  448. String folder = basedir+File.separator+GenerateSkel.packageToFile(packageName);
  449. try {
  450. File f = new File(folder);
  451. if (!f.exists())
  452. f.mkdirs();
  453. } catch (Exception e) {
  454. e.printStackTrace();
  455. }
  456. String fileName = folder+File.separator+"BdUtils.java";
  457. output = new BufferedWriter(new FileWriter(fileName));
  458. writeHeader();
  459. writeConstructor();
  460. writeExecuteQuery();
  461. writeExecuteUpdate();
  462. writeExecuteUpdate2();
  463. writeReplaceString();
  464. writeColumnDataClass();
  465. if (isOracle)
  466. writeGetNextSequenceValue();
  467. out("}");
  468. output.close();
  469. }
  470. public static void main(String[] args) {
  471. }
  472. }