/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
- /*
- * generator Database Bean Generator
- * Copyright (C) 2005 Josep Carles Collazos
- *
- * This software is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * Josep Carles Collazos
- * mailto: jespo@users.sourceforge.net
- *
- */
- package org.collazos.generator;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Properties;
- import org.collazos.generator.bdexception.BaseRuntimeException;
- import org.collazos.util.database.ConnectDB;
- import electric.xml.Element;
- /**
- * Type description
- *
- * @author Josep Carles Collazos
- * @created 11-mar-2005
- */
- public class GenerateUtil {
- private Properties props;
- private boolean valueAsAttribute = false;
- private boolean stringsAsCdata = false;
- private String basedir;
- private String packageName;
- private boolean tofile;
- private boolean toStdout;
- private BufferedWriter output;
- private String connectionOpen;
- private String connectionClose;
- private String connectionPackage;
- private String exceptionPackage;
- private String xmlImport;
- private boolean isEnabled;
- private String xmlRowName;
- private String xmlFieldName;
- private String xmlRowidName;
- private String xmlValueName;
- private boolean isOracle;
- private boolean hasLogs;
- public GenerateUtil(Properties props) {
- this.props = props;
- this.basedir = (String) props.get("generator.io.basedir");
- this.packageName = (String) props.get("generator.class.package");
- this.tofile = new Boolean((String) props.get("generator.io.file")).booleanValue();
- this.toStdout = new Boolean((String) props.get("generator.io.stdout")).booleanValue();
- this.connectionOpen = (String) props.get("generator.database.connection.open");
- this.connectionClose = (String) props.get("generator.database.connection.close");
- this.exceptionPackage = (String) props.get("generator.database.exception.package");
- this.connectionPackage = (String) props.get("generator.database.connection.package");
- this.xmlImport = (String) props.get("generator.xml.import");
- this.isEnabled = new Boolean((String) props.get("generator.static.enabled")).booleanValue();
- this.xmlRowName = (String) props.getProperty("generator.static.row.name","row");
- this.xmlFieldName = (String) props.getProperty("generator.static.field.name","field");
- this.xmlRowidName = (String) props.getProperty("generator.static.rowid.name","rowid");
- this.xmlValueName = (String) props.getProperty("generator.static.value.name","value");
- this.valueAsAttribute = new Boolean((String) props.get("generator.static.value.attribute")).booleanValue();
- this.stringsAsCdata = new Boolean((String) props.get("generator.static.strings.cdata")).booleanValue();
- this.isOracle = ((String) props.get("generator.database.driver")).indexOf("oracle")!=-1;
- this.hasLogs = new Boolean((String) props.get("generator.log.enabled")).booleanValue();
- }
- public void out(String text) throws IOException{
- if (this.toStdout)
- System.out.println(text);
- if (this.tofile)
- output.write(text+"\n");
- }
- public static Element executeQueryToXml(String sql) {
- Connection con = null;
- Statement stm = null;
- ResultSet rs = null;
- int k=0;
- try {
- con = ConnectDB.getSimpleConnection();
- stm = con.createStatement();
- rs = stm.executeQuery(sql);
- Element queryResult = new Element("query-result");
- int numColumns = rs.getMetaData().getColumnCount();
- String[] fieldName = new String[numColumns];
- String[] fieldType = new String[numColumns];
- for (int i=0;i<numColumns;i++) {
- fieldName[i]=rs.getMetaData().getColumnName(i+1);
- int numType = rs.getMetaData().getColumnType(i+1);
- ColumnData cd = new ColumnData(fieldName[i],numType,1);
- fieldType[i]=cd.getJavaType();
- }
- while (rs.next()) {
- Element tmpElem = new Element("row");
- for (int i=0;i<numColumns;i++) {
- String fieldValue=rs.getString(fieldName[i]);
- Element fieldElem = new Element("field");
- fieldElem.setAttribute("name",fieldName[i]);
- fieldElem.setAttribute("java-type",fieldType[i]);
- fieldElem.setText(rs.getString(fieldName[i]));
- tmpElem.addChild(fieldElem);
- }
- tmpElem.setAttribute("rowid",""+k);
- queryResult.addChild(tmpElem);
- k++;
- }
- return queryResult;
- } catch (Exception e) {
- throw new BaseRuntimeException(e.toString());
- } finally {
- if (rs != null) try { rs.close(); } catch (Exception ignored) {}
- if (stm != null) try { stm.close(); } catch (Exception ignored) {}
- if (con != null) ConnectDB.putConnection(con);
- }
- }
- public void writeHeader() throws IOException {
- out("//Generation Date: "+new java.util.Date());
- out("package "+packageName+";");
- out("");
- out("import java.sql.*;");
- out("import "+this.connectionPackage+";");
- out("import "+this.exceptionPackage+".*;");
- out("import "+this.xmlImport+";");
- out("");
- out("/**");
- out(" * BdUtils");
- out(" * Generator version: "+GenerateSkel.version);
- out(" * Class to provide some useful stuff.");
- out(" * Generation Date: "+new java.util.Date());
- out(" * ");
- out(" */");
- out("public class BdUtils {");
- out("");
- if (hasLogs)
- out(" private static ISimpleLogger logger = new Logger(System.out);");
- out("");
- }
- public void writeConstructor() throws IOException {
- out(" public BdUtils() {");
- out(" }");
- out("");
- }
- public void writeExecuteUpdate() throws IOException {
- out(" public static int executeUpdate(String sql) {");
- out(" Connection con = null;");
- out(" Statement stm = null;");
- out(" int result = -1;");
- out(" try {");
- if (this.hasLogs)
- out(" logger.log(\"[executeUpdate] SQL:\"+sql);");
- out(" con = "+this.connectionOpen+";");
- out(" stm = con.createStatement();");
- out(" result = stm.executeUpdate(sql);");
- out(" return result;");
- out(" } catch (Exception e) {");
- out(" throw new BaseRuntimeException(e.toString());");
- out(" } finally {");
- out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
- out(" if (con != null) "+this.connectionClose+";");
- out(" }");
- out(" }");
- out("");
- }
- public void writeExecuteUpdate2() throws IOException {
- out(" ");
- out(" public static int executeUpdate(Connection con, String sql) {");
- out(" Statement stm = null;");
- out(" int result = -1;");
- out(" try {");
- out(" stm = con.createStatement();");
- out(" result = stm.executeUpdate(sql);");
- out(" return result;");
- out(" } catch (Exception e) {");
- out(" throw new BaseRuntimeException(e.toString());");
- out(" } finally {");
- out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
- out(" }");
- out(" }");
- }
- public void writeExecuteQuery() throws IOException {
- out(" public static Element executeQueryToXml(String sql) {");
- out(" Connection con = null;");
- out(" Statement stm = null;");
- out(" ResultSet rs = null;");
- out(" int k=0;");
- out(" try {");
- out(" con = "+this.connectionOpen+";");
- if (this.hasLogs)
- out(" logger.log(\"[executeQueryToXml] SQL:\"+sql);");
- out(" stm = con.createStatement();");
- out(" rs = stm.executeQuery(sql);");
- out(" Element queryResult = new Element(\"query-result\");");
- out(" int numColumns = rs.getMetaData().getColumnCount();");
- out(" String[] fieldName = new String[numColumns];");
- out(" String[] fieldType = new String[numColumns];");
- out(" for (int i=0;i<numColumns;i++) {");
- out(" fieldName[i]=rs.getMetaData().getColumnName(i+1);");
- out(" int numType = rs.getMetaData().getColumnType(i+1);");
- out(" ColumnData cd = new ColumnData(fieldName[i],numType,1);");
- out(" fieldType[i]=cd.getJavaType();");
- out(" }");
- out(" while (rs.next()) {");
- out(" Element tmpElem = new Element(\""+this.xmlRowName+"\");");
- out(" for (int i=0;i<numColumns;i++) {");
- out(" String fieldValue=rs.getString(fieldName[i]);");
- out(" Element fieldElem = new Element(\""+this.xmlFieldName+"\");");
- out(" fieldElem.setAttribute(\"name\",fieldName[i]);");
- out(" fieldElem.setAttribute(\"java-type\",fieldType[i]);");
- if (valueAsAttribute)
- out(" fieldElem.setAttribute(\""+this.xmlValueName+"\",rs.getString(fieldName[i]));");
- else {
- if (stringsAsCdata) {
- out(" if (fieldType[i].equals(\"String\")) {");
- out(" CData txtCdata = new CData(rs.getString(fieldName[i]));");
- out(" fieldElem.setText(txtCdata);");
- out(" } else {");
- out(" fieldElem.setText(rs.getString(fieldName[i]));");
- out(" }");
- }
- else
- out(" fieldElem.setText(rs.getString(fieldName[i]));");
- }
- out(" tmpElem.addChild(fieldElem);");
- out(" }");
- out(" tmpElem.setAttribute(\""+this.xmlRowidName+"\",\"\"+k);");
- out(" queryResult.addChild(tmpElem);");
- out(" k++;");
- out(" }");
- out(" return queryResult;");
- out(" } catch (Exception e) {");
- out(" throw new BaseRuntimeException(e.toString());");
- out(" } finally {");
- out(" if (rs != null) try { rs.close(); } catch (Exception ignored) {}");
- out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
- out(" if (con != null) "+this.connectionClose+";");
- out(" }");
- out(" }");
- out("");
- }
- public void writeReplaceString() throws IOException {
- out(" public static String replaceString (String str, String find, String replace) {");
- out(" if (str == null) return null;");
- out(" if ((find == null) || (find.length() == 0)) return str;");
- out(" if (replace == null) replace = \"\";");
- out(" StringBuffer sb = new StringBuffer(str.length());");
- out(" int pos = 0;");
- out(" int lastPos = 0;");
- out(" while (pos >= 0) {");
- out(" pos = str.indexOf(find, lastPos);");
- out(" if (pos >= 0) {");
- out(" sb.append(str.substring(lastPos, pos));");
- out(" sb.append(replace);");
- out(" } else {");
- out(" sb.append(str.substring(lastPos));");
- out(" }");
- out(" lastPos = pos + find.length();");
- out(" }");
- out(" return sb.toString();");
- out(" }");
- }
- public void writeGetNextSequenceValue() throws IOException {
- out(" ");
- out(" public static int getNextSequenceValue(String sequenceName,Connection con) {");
- out(" String sql=\"select \"+sequenceName+\".nextval from dual\";");
- out(" Statement stm = null;");
- out(" ResultSet rs = null;");
- out(" int k=0;");
- out(" try {");
- if (this.hasLogs)
- out(" logger.log(\"[getNextSequenceValue] SQL:\"+sql);");
- out(" stm = con.createStatement();");
- out(" rs = stm.executeQuery(sql);");
- out(" rs.next();");
- out(" int id = rs.getInt(1);");
- out(" return id;");
- out(" } catch (Exception e) {");
- out(" throw new BaseRuntimeException(e.toString());");
- out(" } finally {");
- out(" if (rs != null) try { rs.close(); } catch (Exception ignored) {}");
- out(" if (stm != null) try { stm.close(); } catch (Exception ignored) {}");
- out(" }");
- out(" }");
- out("");
- }
- public void writeColumnDataClass() throws IOException {
- out(" ");
- out(" ");
- out(" ");
- out(" private static class ColumnData");
- out(" {");
- 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\" };");
- out(" int type;");
- out(" int columns;");
- out(" String name;");
- out(" public ColumnData (String name,int origType, int columns)");
- out(" {");
- out(" this.name = name;");
- out(" this.type = origType;");
- out(" this.columns = columns;");
- out(" switch (type)");
- out(" {");
- out(" case -1:");
- out(" break;");
- out(" case -2:");
- out(" type = 18;");
- out(" break;");
- out(" case -3:");
- out(" type = 19;");
- out(" break;");
- out(" case -4:");
- out(" type = 19;");
- out(" break;");
- out(" case -5:");
- out(" type = 3;");
- out(" break;");
- out(" case -6:");
- out(" type = 2;");
- out(" break;");
- out(" case -7:");
- out(" type = 16;");
- out(" break;");
- out(" case 1111:");
- out(" type = 3;");
- out(" break;");
- out(" case 91:");
- out(" type = 11;");
- out(" break;");
- out(" case 92:");
- out(" type = 14;");
- out(" break;");
- out(" case 93:");
- out(" type = 14;");
- out(" break;");
- out(" default:");
- out(" break;");
- out(" }");
- out(" }");
- out(" public ColumnData (String name, String coltype, int columns)");
- out(" {");
- out(" this.name = name;");
- out(" this.columns = columns;");
- out(" int i=0;");
- out(" boolean quit = false;");
- out(" this.type = -1; // invalid");
- out(" while (!quit)");
- out(" {");
- out(" if (coltype.toUpperCase().compareTo(sqlTypes[i]) == 0)");
- out(" {");
- out(" this.type = i+1;");
- out(" quit = true;");
- out(" }");
- out(" i++;");
- out(" if (i>=sqlTypes.length)");
- out(" quit = true;");
- out(" }");
- out(" }");
- out(" public String getName() {");
- out(" return name;");
- out(" }");
- out(" public String getJavaType()");
- out(" {");
- out(" String jType = null;");
- out(" switch (type)");
- out(" {");
- out(" case 1:");
- out(" case 12:");
- out(" case 13:");
- out(" case 22:");
- out(" jType = \"String\";");
- out(" break;");
- out(" case 2:");
- out(" jType = \"byte\";");
- out(" break;");
- out(" case 3:");
- out(" jType = \"long\";");
- out(" break;");
- out(" case 4:");
- out(" jType = \"int\";");
- out(" break;");
- out(" case 5:");
- out(" jType = \"short\";");
- out(" break;");
- out(" case 6:");
- out(" case 8:");
- out(" jType = \"double\";");
- out(" break;");
- out(" case 9:");
- out(" case 10:");
- out(" jType = \"java.math.BigDecimal\";");
- out(" break;");
- out(" case 7:");
- out(" jType = \"float\";");
- out(" break;");
- out(" case 11:");
- out(" jType = \"java.util.Date\";");
- out(" break;");
- out(" case 14:");
- out(" jType = \"Timestamp\";");
- out(" break;");
- out(" case 15:");
- out(" jType = \"Time\";");
- out(" break;");
- out(" case 16:");
- out(" jType = \"boolean\";");
- out(" break;");
- out(" case 17:");
- out(" case 18:");
- out(" case 19:");
- out(" jType = \"byte[]\";");
- out(" break;");
- out(" case 20:");
- out(" jType = \"null\";");
- out(" break;");
- out(" default:");
- out(" jType = \"unknown\";");
- out(" break;");
- out(" }");
- out(" return jType;");
- out(" }");
- out(" public String getType() {");
- out(" if ((type > sqlTypes.length) || (type < 0))");
- out(" return \"\"+type;");
- out(" else");
- out(" return sqlTypes[type-1];");
- out(" }");
- out(" } ");
- out("");
- }
- public void generate() throws IOException, SQLException {
- if (!isEnabled)
- return;
- String folder = basedir+File.separator+GenerateSkel.packageToFile(packageName);
- try {
- File f = new File(folder);
- if (!f.exists())
- f.mkdirs();
- } catch (Exception e) {
- e.printStackTrace();
- }
- String fileName = folder+File.separator+"BdUtils.java";
- output = new BufferedWriter(new FileWriter(fileName));
- writeHeader();
- writeConstructor();
- writeExecuteQuery();
- writeExecuteUpdate();
- writeExecuteUpdate2();
- writeReplaceString();
- writeColumnDataClass();
- if (isOracle)
- writeGetNextSequenceValue();
- out("}");
- output.close();
- }
- public static void main(String[] args) {
- }
- }