KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > db > DotConnect


1 package com.dotmarketing.db;
2
3 import java.sql.Connection JavaDoc;
4 import java.sql.PreparedStatement JavaDoc;
5 import java.sql.ResultSet JavaDoc;
6 import java.sql.ResultSetMetaData JavaDoc;
7 import java.sql.Timestamp JavaDoc;
8 import java.util.ArrayList JavaDoc;
9 import java.util.HashMap JavaDoc;
10 import java.util.Iterator JavaDoc;
11
12 import com.dotmarketing.exception.DotRuntimeException;
13 import com.dotmarketing.util.Logger;
14
15 /**
16  * Description of the Class
17  *
18  * @author will
19  * @created February 25, 2002 Modified May 8, 2003 Hashtables converted to
20  * HashMaps results is now an arraylist
21  */

22 public class DotConnect {
23     ArrayList JavaDoc<Object JavaDoc> paramList;
24
25     ArrayList JavaDoc<Object JavaDoc> results;
26
27     String JavaDoc SQL;
28
29     boolean gotResult;
30
31     int cursor;
32
33     int maxRows = 10000;
34
35     int startRow = 0;
36
37     public DotConnect() {
38         Logger.debug(this, "------------ DotConnect() --------------------");
39     }
40
41     public int getInt(String JavaDoc x) {
42         x = x.toLowerCase();
43         Logger.debug(this, "getInt: " + x);
44
45         if (gotResult == false) {
46             getResult();
47         }
48
49         try {
50             return Integer.parseInt((String JavaDoc) ((HashMap JavaDoc) results.get(cursor)).get(x));
51         } catch (Exception JavaDoc e) {
52             Logger.debug(this, "getInt: " + e);
53             throw new DotRuntimeException(e.toString());
54         }
55     }
56
57     public void setMaxRows(int x) {
58         maxRows = x;
59     }
60
61     public void setMaxRows(String JavaDoc x) {
62         try {
63             setMaxRows(Integer.parseInt(x));
64         } catch (Exception JavaDoc e) {
65             throw new DotRuntimeException(e.toString());
66         }
67     }
68
69     public int getMaxRows() {
70         return maxRows;
71     }
72
73     public int getNumRows() {
74         return (results != null) ? results.size() : 0;
75     }
76
77     public Object JavaDoc getObject(String JavaDoc x) {
78         
79         Object JavaDoc obj = new Object JavaDoc();
80
81         try {
82             obj = getObject(Class.forName(x).newInstance());
83             return obj;
84         } catch (Exception JavaDoc e) {
85             Logger.error(this, "Create class Exception" + e, e);
86             throw new DotRuntimeException(e.toString());
87         }
88     }
89
90     public Object JavaDoc getObject(Object JavaDoc x) {
91         Logger.debug(this, "getObject(Object " + x.toString() + ")");
92
93         //if we don't have a result set, get one
94
if (gotResult == false) {
95             getResult();
96         }
97
98         if (getNumRows() == 0) {
99             return x;
100         }
101
102         HashMap JavaDoc o = (HashMap JavaDoc) results.get(cursor);
103
104         for (Iterator JavaDoc e = o.entrySet().iterator(); e.hasNext();) {
105             try {
106                 String JavaDoc colName = (String JavaDoc) e.next();
107                 java.lang.StringBuffer JavaDoc setter = new java.lang.StringBuffer JavaDoc();
108                 setter.append("set");
109
110                 if (colName.toString().length() > 1) {
111                     java.util.StringTokenizer JavaDoc keySpliter = new java.util.StringTokenizer JavaDoc(colName, "_");
112
113                     // Split on Underscore
114
while (keySpliter.hasMoreTokens()) {
115                         String JavaDoc partKey = keySpliter.nextToken();
116                         setter.append(partKey.substring(0, 1).toUpperCase() + partKey.substring(1));
117                     }
118                 }
119
120                 Class JavaDoc[] params = { new String JavaDoc().getClass() };
121                 Object JavaDoc[] paramsObj = new Object JavaDoc[1];
122                 paramsObj[0] = (o.get(colName) == null) ? null : o.get(colName).toString();
123
124                 x.getClass().getMethod(setter.toString(), params).invoke(x, paramsObj);
125             } catch (Exception JavaDoc ex) {
126                 Logger.error(this, "db.getObject: " + ex, ex);
127                 throw new DotRuntimeException(e.toString());
128             }
129         }
130
131         return x;
132     }
133
134     public Object JavaDoc[] getObjectArray(String JavaDoc ObjName) {
135         //if we don't have a result set, get one
136
if (gotResult == false) {
137             getResult();
138         }
139
140         ArrayList JavaDoc<Object JavaDoc> bar = new ArrayList JavaDoc<Object JavaDoc>();
141
142         for (cursor = 0; cursor < getNumRows(); cursor++) {
143             bar.add(getObject(ObjName));
144         }
145
146         return bar.toArray();
147     }
148
149     /**
150      * Executes SQL, Pulls a result set, sets the rs and rsmd variables.
151      */

152     public void getResult() {
153         Connection JavaDoc conn = DbConnectionFactory.getConnection();
154         PreparedStatement JavaDoc statement = null;
155         ResultSet JavaDoc rs = null;
156         ResultSetMetaData JavaDoc rsmd = null;
157         gotResult = true;
158
159         results = new ArrayList JavaDoc<Object JavaDoc>();
160
161         //build the SQL statement, looping through params
162
try {
163             conn.clearWarnings();
164
165             //perform some query optimizations
166
String JavaDoc starter = SQL.substring(0, 10);
167
168             statement = conn.prepareStatement(SQL);
169
170             //statement.setMaxRows(maxRows);
171

172             Logger.debug(this, "SQL = " + statement.toString());
173
174             for (int i = 0; i < paramList.size(); i++) {
175                 statement.setObject(i + 1, paramList.get(i));
176             }
177             if (!starter.toLowerCase().trim().startsWith("select")) {
178                 statement.execute();
179             } else {
180                 rs = statement.executeQuery();
181                 rsmd = rs.getMetaData();
182             }
183
184             if (rs != null) {
185                 //move to the starter row
186
for (int i = 0; i < startRow; i++) {
187                     rs.next();
188                 }
189                 ;
190
191                 int i = 0;
192
193                 while (rs.next() && (i < maxRows)) {
194                     HashMap JavaDoc<String JavaDoc,String JavaDoc> vars = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
195
196                     for (int j = 1; j <= rsmd.getColumnCount(); j++) {
197                         String JavaDoc x = rsmd.getColumnName(j) + "";
198                         
199                         if ((rs.getString(x) == null) || rs.getString(x).equals("null")) {
200                             x=x.toLowerCase();
201                             vars.put(x, "");
202                         } else {
203                             x=x.toLowerCase();
204                             vars.put(x, rs.getString(x) + "");
205                         }
206                     }
207
208                     vars.put("rownumber", Integer.toString(i));
209                     vars.put("oddoreven", Integer.toString((i % 2)));
210                     results.add(vars);
211
212                     i++;
213                 }
214             }
215         } catch (Exception JavaDoc e) {
216             Logger.error(this, "getResult(): unable to execute query. Bad SQL?:" + e, e);
217             throw new DotRuntimeException(e.toString());
218         } finally {
219             try { if (rs != null) rs.close(); } catch (Exception JavaDoc e) { }
220             try { if (statement != null) statement.close(); } catch (Exception JavaDoc e) { }
221         }
222
223         statement = null;
224         rs = null;
225         rsmd = null;
226         conn = null;
227     }
228
229     public void setSQL(String JavaDoc x) {
230         cursor = 0;
231         gotResult = false;
232         paramList = new ArrayList JavaDoc<Object JavaDoc>();
233         SQL = x;
234
235         Logger.debug(this, "setSQL: " + x);
236     }
237
238     public String JavaDoc getSQL() {
239         return SQL;
240     }
241
242     /**
243      * Returns a single result as a String.
244      *
245      * @param x
246      * Description of Parameter
247      * @return The string value
248      */

249     public String JavaDoc getString(String JavaDoc x) {
250         Logger.debug(this, "getString(String x)");
251         x = x.toLowerCase();
252         if (gotResult == false) {
253             getResult();
254         }
255
256         try {
257             return (String JavaDoc) ((HashMap JavaDoc) results.get(cursor)).get(x);
258         } catch (Exception JavaDoc e) {
259             throw new DotRuntimeException(e.toString());
260         }
261     }
262
263     //this is a specialize getUniqueID for MSSQL
264
public static synchronized int getUniqueID(String JavaDoc type) {
265         String JavaDoc SELECT_AUTONUM = "SELECT NextAutoNum as idx from webAutoNum where Code = ?";
266         String JavaDoc UPDATE_AUTONUM = "UPDATE webAutoNum set NextAutoNum = ? where Code = ?";
267
268         int x = 0;
269         DotConnect db = new DotConnect();
270         db.setSQL(SELECT_AUTONUM);
271         db.addParam(type);
272         x = db.getInt("idx");
273
274         db.setSQL(UPDATE_AUTONUM);
275         db.addParam(x + 1);
276         db.addParam(type);
277         db.getResult();
278
279         try {
280             return Integer.parseInt(Integer.toString(x) + "9");
281         } catch (Exception JavaDoc e) {
282             Logger.error("ERROR: GET NOAH/WEB AUTONUMBER FAILED:" + e, e);
283             throw new DotRuntimeException(e.toString());
284         }
285     }
286
287     /**
288      * Returns the results.
289      *
290      * @return ArrayList
291      */

292     public ArrayList JavaDoc getResults() {
293         if (gotResult == false) {
294             getResult();
295         }
296         return (results != null) ? results : new ArrayList JavaDoc();
297     }
298
299     /**
300      * Sets the startRow.
301      *
302      * @param startRow
303      * The startRow to set
304      */

305     public void setStartRow(int startRow) {
306         this.startRow = startRow;
307     }
308
309     public void setStartRow(String JavaDoc x) {
310         try {
311             setStartRow(Integer.parseInt(x));
312         } catch (Exception JavaDoc e) {
313             throw new DotRuntimeException(e.toString());
314         }
315     }
316
317     /**
318      * Returns the startRow.
319      *
320      * @return int
321      */

322     public int getStartRow() {
323         return startRow;
324     }
325
326     public void addObject(Object JavaDoc x) {
327         Logger.debug(this, "db.addParam " + paramList.size() + " (Object): " + x);
328         paramList.add(paramList.size(), x);
329     }
330
331     public void addParam(Object JavaDoc x) {
332         Logger.debug(this, "db.addParam " + paramList.size() + " (Object): " + x);
333         paramList.add(paramList.size(), x);
334     }
335
336     /**
337      * Adds a feature to the Param attribute of the dotConnect object
338      *
339      * @param x
340      * The feature to be added to the Param attribute
341      */

342     public void addParam(boolean x) {
343         Logger.debug(this, "db.addParam " + paramList.size() + " (boolean): " + x);
344         paramList.add(paramList.size(), x + "");
345     }
346
347     /**
348      * This method adds an <code>int</code> parameter to the prepared SQL
349      * statement.
350      *
351      * @param x
352      * The feature to be added to the Param attribute
353      */

354     public void addParam(int x) {
355         Logger.debug(this, "db.addParam " + paramList.size() + " (int): " + x);
356         paramList.add(paramList.size(), x + "");
357     }
358
359     /**
360      * This method adds a <code>String</code> parameter to the prepared SQL
361      * statement.
362      *
363      * @param x
364      * The feature to be added to the Param attribute
365      */

366     public void addParam(String JavaDoc x) {
367         Logger.debug(this, "db.addParam " + paramList.size() + " (String): " + x);
368         paramList.add(paramList.size(), x);
369     }
370
371     /**
372      * Adds a long parameter to the prepared SQL statement.
373      *
374      * @param x
375      * The feature to be added to the Param attribute
376      */

377     public void addParam(long x) {
378         Logger.debug(this, "db.addParam " + paramList.size() + " (long): " + x);
379         paramList.add(paramList.size(), x + "");
380     }
381
382     /**
383      * Adds a double parameter to the prepared SQL statement.
384      *
385      * @param x
386      * The feature to be added to the Param attribute
387      */

388     public void addParam(double x) {
389         Logger.debug(this, "db.addParam " + paramList.size() + " (double): " + x);
390         paramList.add(paramList.size(), x + "");
391     }
392
393     /**
394      * Adds a date parameter to the prepared SQL statement.
395      *
396      * @param x
397      * The feature to be added to the Param attribute
398      */

399     public void addParam(java.util.Date JavaDoc x) {
400         Logger.debug(this, "db.addParam " + paramList.size() + " (date): " + x);
401         paramList.add(paramList.size(), new Timestamp JavaDoc(x.getTime()));
402     }
403 }
Popular Tags