1 /*** $Id: Util.java,v 1.1.1.1 2004/05/18 10:50:17 mochoa Exp $*/
2 package org.j2ee.dao.gen;
3
4 import java.util.*;
5 import java.sql.*;
6 import java.io.File;
7 import java.io.FileWriter;
8
9 /***
10 * Last modified $Date: 2004/05/18 10:50:17 $
11 * @version $Revision: 1.1.1.1 $
12 * @author jvlio (jvlio@users.sourceforge.net) - 04/11/2002 - 01:51:09
13 */
14 public class Util {
15
16 public static final String DRIVER = "driver";
17 public static final String URL = "url";
18 public static final String USERID = "userid";
19 public static final String PASSWORD = "password";
20
21 public static final String SCHEMA = "schema";
22 public static final String TABLE = "table";
23 public static final String PK = "pk";
24 public static final String FIELD_PROP_MAP = "field_prop_map";
25 public static final String FIELD_JTYPE_MAP = "field_jtype_map";
26
27 public static final String ACTIONS = "actions";
28 public static final String BASE_PATH = "base_path";
29 public static final String COMMON_NAME = "common_name";
30 public static final String DAO_PACKAGE = "dao_package";
31 public static final String DTO_PACKAGE = "dto_package";
32 public static final String DTO_NAME = "dto_name";
33
34
35
36 private static Util util = null;
37
38 public final static Util getInstance() {
39 if (util==null) util=new Util();
40 return util;
41 }
42 /***
43 * Load and registed a JDBC Driver.
44 * @param driver A JDBC driver class.
45 * @throws ClassNotFoundException
46 * @throws InstantiationException
47 * @throws IllegalAccessException
48 * @throws SQLException
49 */
50 public void loadJDBCDriver(String driver) throws ClassNotFoundException,
51 InstantiationException,
52 IllegalAccessException,
53 SQLException {
54 DriverManager.registerDriver((Driver)Class.forName(driver).newInstance());
55 }
56
57
58 /***
59 *
60 * @param url JDBC URL connection string.
61 * @param usr User
62 * @param pwd Password
63 * @return a JDBC Conection to url.
64 * @throws SQLException
65 */
66 public Connection createConnection(String url, String usr, String pwd) throws SQLException {
67 return DriverManager.getConnection(url,usr,pwd);
68 }
69
70
71 public Map getPrimaryKeys(Connection con, String catalog, String schema, String table) throws SQLException {
72 Map pks = new HashMap();
73 ResultSet rset = null;
74 try {
75 DatabaseMetaData dmd = con.getMetaData();
76 rset = dmd.getPrimaryKeys(catalog,schema,table);
77 while (rset.next()) {
78 String pk = rset.getString("COLUMN_NAME").toLowerCase();
79 pks.put(pk,pk);
80 }
81 } catch(SQLException ex) {
82 ex.printStackTrace();
83 throw ex;
84 } finally {
85 try {
86 if (rset!=null) rset.close();
87 } catch(Exception ex) {}
88 }
89 return pks;
90 }
91
92
93 public TableData createTableData(Connection con, String table_name, Map pk, Map pnames, Map ptypes) throws SQLException {
94 TableData td = null;
95 Statement stmt = null;
96 ResultSet rset = null;
97 try {
98 stmt = con.createStatement();
99 rset = stmt.executeQuery("SELECT * FROM "+table_name);
100 td = createTableData(rset,pk,pnames,ptypes);
101 td.setName(table_name);
102 } catch(SQLException ex) {
103 ex.printStackTrace();
104 throw ex;
105 } finally {
106 try {
107 if (rset!=null) rset.close();
108 if (stmt!=null) stmt.close();
109 } catch(Exception ex) {}
110 }
111 return td;
112 }
113
114
115 /***
116 * Create a TableData based on a ResultSet (Table), pk (primary keys), pnames (property names) and
117 * ptypes (java property types).
118 * This method not set the tableName property.
119 * @param rset a ResultSet
120 * @param pk primary key's Map
121 * @param pnames Properties name's Map
122 * @param ptypes Properties type's Map
123 * @return a TableData based on Result set
124 * @throws SQLException
125 */
126 public TableData createTableData(ResultSet rset, Map pk, Map pnames, Map ptypes) throws SQLException {
127 ResultSetMetaData meta = rset.getMetaData();
128 int columns = meta.getColumnCount();
129
130 TableData td = new TableData();
131
132 for (int i=1;i<=columns;i++) {
133 FieldData fd = new FieldData();
134 fd.setName(meta.getColumnLabel(i).toLowerCase());
135 fd.setSize(meta.getColumnDisplaySize(i));
136 fd.setSqlType(meta.getColumnType(i));
137 if (fd.getSqlType()!=Types.BLOB) {
138 fd.setPrecision(meta.getPrecision(i));
139 }
140 fd.setScale(meta.getScale(i));
141 if (meta.isNullable(i)==ResultSetMetaData.columnNullableUnknown) throw new SQLException("The column "+fd.getName()+" is a columnNullableUnknown.");
142 fd.setNullable( (meta.isNullable(i)==ResultSetMetaData.columnNullable)? true : false );
143 //pk
144 if (pk.get(fd.getName())!=null) fd.setPk(true);
145 //java
146 Integer type = (Integer)ptypes.get(fd.getName());
147 fd.setJavaType( (type==null)? GenTypes.mapSQLTypeToJavaType(fd.getSqlType()) : type.intValue() );
148 String prop = (String)pnames.get(fd.getName());
149 fd.setJavaProp( (prop==null)? fd.getName() : prop);
150 //add field
151 td.add(fd);
152 }
153 return td;
154 }
155
156 public GenData createGeneratorData(Connection con, Map params) throws SQLException {
157 GenData aGenData = new GenData();
158
159 String pks = (String)params.get(PK);
160 if (pks!=null)
161 aGenData.setPk_map(splitPks(pks));
162 else
163 aGenData.setPk_map(getPrimaryKeys(con,null,(String)params.get(SCHEMA),(String)params.get(TABLE)));
164
165 aGenData.setField_prop_map(splitPropNames((String)params.get(FIELD_PROP_MAP)));
166 aGenData.setField_jtype_map(splitPropTypes((String)params.get(FIELD_JTYPE_MAP)));
167
168 //set gd initial parameters
169 aGenData.setCommon_name((String)params.get(COMMON_NAME));
170 aGenData.setDao_package((String)params.get(DAO_PACKAGE));
171 aGenData.setDto_package((String)params.get(DTO_PACKAGE));
172 aGenData.setDto_name((String)params.get(DTO_NAME));
173
174 aGenData.setTableData(createTableData(con,(String)params.get(TABLE),aGenData.getPk_map(),aGenData.getField_prop_map(),aGenData.getField_jtype_map()));
175
176 return aGenData;
177 }
178
179 public void createActionFiles(DAOGenerator gen, GenData gd, Collection actions, String base_path, ClassLoader loader) {
180 //generate XML
181 String xml = gen.createDAOXML(gd);
182 //create all specified actions with function DAOGenerator<GenData,action>
183 for (Iterator it=actions.iterator(); it.hasNext();) {
184 String action = (String)it.next();
185 try {
186 //get filename stuff
187 String pack = (action.equals("dto"))? gd.getDto_package() : gd.getDao_package();
188 String path = base_path+File.separator+pack.replace('.',File.separatorChar)+File.separator;
189 String filename = path+((action.equals("dto"))? gd.getDto_name() : replaceAll(gen.getFilenamePattern(action),"%COMMON_NAME%",gd.getCommon_name()))+".java";
190 //generate java implementation for this action
191 String javaAction = gen.createDAOAction(action,xml,loader);
192 System.out.print("Gen action \""+action+"\" into "+filename+" ... ");
193 // create path if this not exist
194 //String[] apack = pack.split("//x2e"); <-- this using j2sdk 1.4
195 String[] apack = split(pack,".");
196 File tmpFile = null;
197 String tmpPath = base_path;
198 for (int i=0; i<apack.length; i++) {
199 tmpPath += File.separator+apack[i];
200 tmpFile = new File(tmpPath);
201 if (!tmpFile.exists()) tmpFile.mkdir();
202 }
203 // create file or overwriting existing one
204 tmpFile = new File(filename);
205 if (!tmpFile.exists()) {
206 System.out.print("creating file ... ");
207 tmpFile.createNewFile();
208 } else
209 System.out.print("overwriting file ... ");
210 //write implementation to java file
211 FileWriter fw = new FileWriter(tmpFile);
212 fw.write(javaAction);
213 fw.flush();
214 fw.close();
215 System.out.println("done.");
216 } catch(Exception ex) {
217 System.out.println("fail.");
218 ex.printStackTrace();
219 }
220 }
221 }
222
223
224 private Map splitPks(String pks) { return splitCSV(pks); }
225
226 private Map splitPropNames(String spnames) {
227 Map pnames=new HashMap();
228 if (spnames!=null) {
229 StringTokenizer pnames_st = new StringTokenizer(spnames,",",false);
230 while(pnames_st.hasMoreTokens()) {
231 StringTokenizer pname_st = new StringTokenizer(pnames_st.nextToken(),"=",false);
232 String field = pname_st.nextToken().toLowerCase();
233 String prop = pname_st.nextToken();
234 // todo - if (fname_st.hasMoreTokens()) ERROR!!!!!!!!!
235 pnames.put(field,prop);
236 }
237 }
238 return pnames;
239 }
240
241
242 private Map splitPropTypes(String sptypes) {
243 Map ptypes=new HashMap();
244 if (sptypes!=null) {
245 StringTokenizer ptypes_st = new StringTokenizer(sptypes,",",false);
246 while(ptypes_st.hasMoreTokens()) {
247 StringTokenizer ptype_st = new StringTokenizer(ptypes_st.nextToken(),"=",false);
248 String field = ptype_st.nextToken().toLowerCase();
249 String jtype = ptype_st.nextToken();
250 // todo - if (ftype_st.hasMoreTokens()) ERROR!!!!!!!!!
251 // todo - if (GenTypes.getJavaType(jtype)==-1) ERROR!!!!!!!!!
252 ptypes.put(field,new Integer(GenTypes.getJavaType(jtype)));
253 }
254 }
255 return ptypes;
256 }
257
258
259 public Map splitCSV(String csv) {
260 Map values=new HashMap();
261 if (csv!=null) {
262 StringTokenizer csv_st = new StringTokenizer(csv,",",false);
263 while(csv_st.hasMoreTokens()) {
264 String value = csv_st.nextToken().toLowerCase();
265 values.put(value,value);
266 }
267 }
268 return values;
269 }
270
271
272 public Map splitArgs(String[] args) { return splitArgs(args,new HashMap()); }
273 public Map splitArgs(String[] args, Map params) {
274 for(int i=0; i<args.length; i++) {
275 if (args[i].startsWith("-")) {
276 String arg = args[i];
277 String value = null;
278 if(i+1<args.length || !args[i+1].startsWith("-"))
279 value = args[++i];
280 params.put(arg.substring(1),value);
281 }
282 }
283 return params;
284 }
285
286
287 public String getResourceString(ResourceBundle resources, String key) {
288 String str;
289 try {
290 str = resources.getString(key);
291 } catch (MissingResourceException mre) {
292 str = null;
293 }
294 return str;
295 }
296
297
298 /***
299 * Take the given string and chop it up into a series
300 * of strings on whitespace boundries. This is useful
301 * for trying to get an array of strings out of the
302 * resource file.
303 */
304 public String[] tokenize(String input) {
305 Vector v = new Vector();
306 StringTokenizer t = new StringTokenizer(input);
307 String cmd[];
308
309 while (t.hasMoreTokens())
310 v.addElement(t.nextToken());
311 cmd = new String[v.size()];
312 for (int i = 0; i < cmd.length; i++)
313 cmd[i] = (String) v.elementAt(i);
314
315 return cmd;
316 }
317
318
319 public String replaceAll(String src, String from, String to) {
320 StringBuffer sb = new StringBuffer();
321 int from_length = from.length();
322 int from_inx = 0;
323 int to_inx = 0;
324 for ( ; (to_inx=src.indexOf(from,from_inx))!=-1; ) {
325 if (from_inx<to_inx)
326 sb.append(src.substring(from_inx,to_inx));
327 sb.append(to);
328 from_inx = to_inx+from_length;
329 }
330 if (from_inx<src.length()) sb.append(src.substring(from_inx));
331 return sb.toString();
332 }
333
334
335 public String[] split(String src, String pattern) {
336 ArrayList splits = new ArrayList();
337 int from_length = pattern.length();
338 int from_inx = 0;
339 int to_inx = 0;
340 for ( ; (to_inx=src.indexOf(pattern,from_inx))!=-1; ) {
341 splits.add(src.substring(from_inx,to_inx));
342 from_inx = to_inx+from_length;
343 }
344 splits.add(src.substring(from_inx));
345 String[] splits_array = new String[splits.size()];
346 splits.toArray(splits_array);
347 return splits_array;
348 }
349
350 }
This page was automatically generated by Maven