PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

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

#
Java | 453 lines | 400 code | 25 blank | 28 comment | 20 complexity | 4798fbbd89c4d81cb61ab793bfb35137 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. }
  158. public void writeExecuteQuery() throws IOException {
  159. out(" public static Element executeQueryToXml(String sql) {");
  160. out(" Connection con = null;");
  161. out(" Statement stm = null;");
  162. out(" ResultSet rs = null;");
  163. out(" int k=0;");
  164. out(" try {");
  165. out(" con = "+this.connectionOpen+";");
  166. if (this.hasLogs)
  167. out(" logger.log(\"[executeQueryToXml] SQL:\"+sql);");
  168. out(" stm = con.createStatement();");
  169. out(" rs = stm.executeQuery(sql);");
  170. out(" Element queryResult = new Element(\"query-result\");");
  171. out(" int numColumns = rs.getMetaData().getColumnCount();");
  172. out(" String[] fieldName = new String[numColumns];");
  173. out(" String[] fieldType = new String[numColumns];");
  174. out(" for (int i=0;i<numColumns;i++) {");
  175. out(" fieldName[i]=rs.getMetaData().getColumnName(i+1);");
  176. out(" int numType = rs.getMetaData().getColumnType(i+1);");
  177. out(" ColumnData cd = new ColumnData(fieldName[i],numType,1);");
  178. out(" fieldType[i]=cd.getJavaType();");
  179. out(" }");
  180. out(" while (rs.next()) {");
  181. out(" Element tmpElem = new Element(\""+this.xmlRowName+"\");");
  182. out(" for (int i=0;i<numColumns;i++) {");
  183. out(" String fieldValue=rs.getString(fieldName[i]);");
  184. out(" Element fieldElem = new Element(\""+this.xmlFieldName+"\");");
  185. out(" fieldElem.setAttribute(\"name\",fieldName[i]);");
  186. out(" fieldElem.setAttribute(\"java-type\",fieldType[i]);");
  187. if (valueAsAttribute)
  188. out(" fieldElem.setAttribute(\""+this.xmlValueName+"\",rs.getString(fieldName[i]));");
  189. else {
  190. if (stringsAsCdata) {
  191. out(" if (fieldType[i].equals(\"String\")) {");
  192. out(" CData txtCdata = new CData(rs.getString(fieldName[i]));");
  193. out(" fieldElem.setText(txtCdata);");
  194. out(" } else {");
  195. out(" fieldElem.setText(rs.getString(fieldName[i]));");
  196. out(" }");
  197. }
  198. else
  199. out(" fieldElem.setText(rs.getString(fieldName[i]));");
  200. }
  201. out(" tmpElem.addChild(fieldElem);");
  202. out(" }");
  203. out(" tmpElem.setAttribute(\""+this.xmlRowidName+"\",\"\"+k);");
  204. out(" queryResult.addChild(tmpElem);");
  205. out(" k++;");
  206. out(" }");
  207. out(" return queryResult;");
  208. out(" } catch (Exception e) {");
  209. out(" throw new BaseRuntimeException(e.toString());");
  210. out(" } finally {");
  211. out(" if (rs != null) try { rs.close(); } catch (Exception ignored) {}");
  212. out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
  213. out(" if (con != null) "+this.connectionClose+";");
  214. out(" }");
  215. out(" }");
  216. }
  217. public void writeReplaceString() throws IOException {
  218. out(" public static String replaceString (String str, String find, String replace) {");
  219. out(" if (str == null) return null;");
  220. out(" if ((find == null) || (find.length() == 0)) return str;");
  221. out(" if (replace == null) replace = \"\";");
  222. out(" StringBuffer sb = new StringBuffer(str.length());");
  223. out(" int pos = 0;");
  224. out(" int lastPos = 0;");
  225. out(" while (pos >= 0) {");
  226. out(" pos = str.indexOf(find, lastPos);");
  227. out(" if (pos >= 0) {");
  228. out(" sb.append(str.substring(lastPos, pos));");
  229. out(" sb.append(replace);");
  230. out(" } else {");
  231. out(" sb.append(str.substring(lastPos));");
  232. out(" }");
  233. out(" lastPos = pos + find.length();");
  234. out(" }");
  235. out(" return sb.toString();");
  236. out(" }");
  237. }
  238. public void writeGetNextSequenceValue() throws IOException {
  239. out(" public static int getNextSequenceValue(String sequenceName,Connection con) {");
  240. out(" String sql=\"select \"+sequenceName+\".nextval from dual\";");
  241. out(" Statement stm = null;");
  242. out(" ResultSet rs = null;");
  243. out(" int k=0;");
  244. out(" try {");
  245. if (this.hasLogs)
  246. out(" logger.log(\"[getNextSequenceValue] SQL:\"+sql);");
  247. out(" stm = con.createStatement();");
  248. out(" rs = stm.executeQuery(sql);");
  249. out(" rs.next();");
  250. out(" int id = rs.getInt(1);");
  251. out(" return id;");
  252. out(" } catch (Exception e) {");
  253. out(" throw new BaseRuntimeException(e.toString());");
  254. out(" } finally {");
  255. out(" if (rs != null) try { rs.close(); } catch (Exception ignored) {}");
  256. out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
  257. out(" }");
  258. out(" }");
  259. }
  260. public void writeColumnDataClass() throws IOException {
  261. out(" ");
  262. out(" ");
  263. out(" ");
  264. out(" private static class ColumnData");
  265. out(" {");
  266. 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\" };");
  267. out(" int type;");
  268. out(" int columns;");
  269. out(" String name;");
  270. out(" public ColumnData (String name,int origType, int columns)");
  271. out(" {");
  272. out(" this.name = name;");
  273. out(" this.type = origType;");
  274. out(" this.columns = columns;");
  275. out(" switch (type)");
  276. out(" {");
  277. out(" case -1:");
  278. out(" break;");
  279. out(" case -2:");
  280. out(" type = 18;");
  281. out(" break;");
  282. out(" case -3:");
  283. out(" type = 19;");
  284. out(" break;");
  285. out(" case -4:");
  286. out(" type = 19;");
  287. out(" break;");
  288. out(" case -5:");
  289. out(" type = 3;");
  290. out(" break;");
  291. out(" case -6:");
  292. out(" type = 2;");
  293. out(" break;");
  294. out(" case -7:");
  295. out(" type = 16;");
  296. out(" break;");
  297. out(" case 1111:");
  298. out(" type = 3;");
  299. out(" break;");
  300. out(" case 91:");
  301. out(" type = 11;");
  302. out(" break;");
  303. out(" case 92:");
  304. out(" type = 14;");
  305. out(" break;");
  306. out(" case 93:");
  307. out(" type = 14;");
  308. out(" break;");
  309. out(" default:");
  310. out(" break;");
  311. out(" }");
  312. out(" }");
  313. out(" public ColumnData (String name, String coltype, int columns)");
  314. out(" {");
  315. out(" this.name = name;");
  316. out(" this.columns = columns;");
  317. out(" int i=0;");
  318. out(" boolean quit = false;");
  319. out(" this.type = -1; // invalid");
  320. out(" while (!quit)");
  321. out(" {");
  322. out(" if (coltype.toUpperCase().compareTo(sqlTypes[i]) == 0)");
  323. out(" {");
  324. out(" this.type = i+1;");
  325. out(" quit = true;");
  326. out(" }");
  327. out(" i++;");
  328. out(" if (i>=sqlTypes.length)");
  329. out(" quit = true;");
  330. out(" }");
  331. out(" }");
  332. out(" public String getName() {");
  333. out(" return name;");
  334. out(" }");
  335. out(" public String getJavaType()");
  336. out(" {");
  337. out(" String jType = null;");
  338. out(" switch (type)");
  339. out(" {");
  340. out(" case 1:");
  341. out(" case 12:");
  342. out(" case 13:");
  343. out(" case 22:");
  344. out(" jType = \"String\";");
  345. out(" break;");
  346. out(" case 2:");
  347. out(" jType = \"byte\";");
  348. out(" break;");
  349. out(" case 3:");
  350. out(" jType = \"long\";");
  351. out(" break;");
  352. out(" case 4:");
  353. out(" jType = \"int\";");
  354. out(" break;");
  355. out(" case 5:");
  356. out(" jType = \"short\";");
  357. out(" break;");
  358. out(" case 6:");
  359. out(" case 8:");
  360. out(" jType = \"double\";");
  361. out(" break;");
  362. out(" case 9:");
  363. out(" case 10:");
  364. out(" jType = \"java.math.BigDecimal\";");
  365. out(" break;");
  366. out(" case 7:");
  367. out(" jType = \"float\";");
  368. out(" break;");
  369. out(" case 11:");
  370. out(" jType = \"java.util.Date\";");
  371. out(" break;");
  372. out(" case 14:");
  373. out(" jType = \"Timestamp\";");
  374. out(" break;");
  375. out(" case 15:");
  376. out(" jType = \"Time\";");
  377. out(" break;");
  378. out(" case 16:");
  379. out(" jType = \"boolean\";");
  380. out(" break;");
  381. out(" case 17:");
  382. out(" case 18:");
  383. out(" case 19:");
  384. out(" jType = \"byte[]\";");
  385. out(" break;");
  386. out(" case 20:");
  387. out(" jType = \"null\";");
  388. out(" break;");
  389. out(" default:");
  390. out(" jType = \"unknown\";");
  391. out(" break;");
  392. out(" }");
  393. out(" return jType;");
  394. out(" }");
  395. out(" public String getType() {");
  396. out(" if ((type > sqlTypes.length) || (type < 0))");
  397. out(" return \"\"+type;");
  398. out(" else");
  399. out(" return sqlTypes[type-1];");
  400. out(" }");
  401. out(" } ");
  402. }
  403. public void generate() throws IOException, SQLException {
  404. if (!isEnabled)
  405. return;
  406. String folder = basedir+File.separator+GenerateSkel.packageToFile(packageName);
  407. try {
  408. File f = new File(folder);
  409. if (!f.exists())
  410. f.mkdirs();
  411. } catch (Exception e) {
  412. e.printStackTrace();
  413. }
  414. String fileName = folder+File.separator+"BdUtils.java";
  415. output = new BufferedWriter(new FileWriter(fileName));
  416. writeHeader();
  417. writeConstructor();
  418. writeExecuteQuery();
  419. writeReplaceString();
  420. writeColumnDataClass();
  421. if (isOracle)
  422. writeGetNextSequenceValue();
  423. out("}");
  424. output.close();
  425. }
  426. public static void main(String[] args) {
  427. }
  428. }