KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > hipergate > datamodel > TableLoader


1 /*
2   Copyright (C) 2005 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.hipergate.datamodel;
34
35 import java.util.ListIterator JavaDoc;
36 import java.util.HashMap JavaDoc;
37
38 import java.sql.Connection JavaDoc;
39 import java.sql.SQLException JavaDoc;
40 import java.sql.Statement JavaDoc;
41 import java.sql.PreparedStatement JavaDoc;
42
43 import com.knowgate.dataobjs.DBColumn;
44 import com.knowgate.dataobjs.DBTable;
45 import com.knowgate.misc.Gadgets;
46
47 /**
48  * Generic text to table loader
49  * @author Sergio Montoro Ten
50  * @version 1.0
51  */

52 public class TableLoader extends DBTable implements ImportLoader {
53
54   private String JavaDoc[] aColNames;
55   private Object JavaDoc[] aValues;
56   HashMap JavaDoc oInsrColPos;
57   HashMap JavaDoc oUpdtColPos;
58   private PreparedStatement JavaDoc oInsr;
59   private PreparedStatement JavaDoc oUpdt;
60
61   // ---------------------------------------------------------------------------
62

63   public TableLoader(String JavaDoc sTableName) {
64     super(sTableName);
65     aColNames = null;
66   }
67
68   // ---------------------------------------------------------------------------
69

70   public String JavaDoc[] columnNames() throws IllegalStateException JavaDoc {
71     if (null==aColNames)
72       throw new IllegalStateException JavaDoc("TableLoader: must call prepare() before columnNames()");
73     return aColNames;
74   }
75
76   // ---------------------------------------------------------------------------
77

78   public void prepare(Connection JavaDoc oConn, ColumnList oColList) throws SQLException JavaDoc {
79     readColumns(oConn, oConn.getMetaData());
80     aColNames = Gadgets.split(getColumnsStr(),',');
81     aValues = new Object JavaDoc[columnCount()];
82     String JavaDoc sSQL;
83     String JavaDoc sCol;
84     oInsrColPos = new HashMap JavaDoc(1+oColList.size()*2);
85     oUpdtColPos = new HashMap JavaDoc(1+oColList.size()*2);
86
87     // ************************************
88
// Compose and prepare insert statement
89
sSQL = "INSERT INTO "+getName()+" ("+oColList.toString(",")+") VALUES (";
90     for (int c=0; c<oColList.size(); c++) {
91       oInsrColPos.put(oColList.getColumnName(c),new Integer JavaDoc(c+1));
92       sSQL += (c == 0 ? "" : ",") + "?";
93     }
94     sSQL += ")";
95     oInsr = oConn.prepareStatement(sSQL);
96
97     // ************************************
98
// Compose and prepare update statement
99

100     sSQL = oColList.toString("=?,");
101     ListIterator JavaDoc oIter = getPrimaryKey().listIterator();
102     while (oIter.hasNext()) {
103       sCol = (String JavaDoc) oIter.next();
104       try {
105         sSQL = Gadgets.replace(sSQL, sCol + "=?,", "");
106         sSQL = Gadgets.replace(sSQL, sCol + "=?", "");
107       } catch (Exception JavaDoc neverthrown) {}
108     }
109     String JavaDoc[] aUpdtCols = Gadgets.split(sSQL, ",");
110     for (int c=0; c<aUpdtCols.length; c++) {
111       oUpdtColPos.put(Gadgets.dechomp(aUpdtCols[c],"=?"),new Integer JavaDoc(c+1));
112     }
113     sSQL = "UPDATE "+getName()+" SET "+sSQL+ " WHERE ";
114     oIter = getPrimaryKey().listIterator();
115     int iPK=1;
116     while (oIter.hasNext()) {
117       sCol = (String JavaDoc) oIter.next();
118       oUpdtColPos.put(sCol,new Integer JavaDoc(aUpdtCols.length+iPK));
119       if (iPK>1) sSQL += " AND ";
120       sSQL += sCol+"=?";
121       iPK++;
122     }
123
124     oUpdt = oConn.prepareStatement(sSQL);
125   } // prepare
126

127   // ---------------------------------------------------------------------------
128

129   public Object JavaDoc get(int iColumnIndex) throws ArrayIndexOutOfBoundsException JavaDoc {
130     return aValues[iColumnIndex];
131   }
132
133   // ---------------------------------------------------------------------------
134

135   public Object JavaDoc get(String JavaDoc sColumnName) throws ArrayIndexOutOfBoundsException JavaDoc {
136     return aValues[getColumnIndex(sColumnName)-1];
137   }
138
139   // ---------------------------------------------------------------------------
140

141   public void put(int iColumnIndex, Object JavaDoc oValue) throws ArrayIndexOutOfBoundsException JavaDoc {
142     aValues[iColumnIndex]=oValue;
143   }
144
145   // ---------------------------------------------------------------------------
146

147   public void put(String JavaDoc sColumnName, Object JavaDoc oValue) throws ArrayIndexOutOfBoundsException JavaDoc {
148     aValues[getColumnIndex(sColumnName)-1]=oValue;
149   }
150
151   // ---------------------------------------------------------------------------
152

153   public void setAllColumnsToNull() {
154     for (int c=columnCount(); c>=0; c--) aValues[c]=null;
155   }
156
157   // ---------------------------------------------------------------------------
158

159   public void close() throws SQLException JavaDoc {
160     try { if (oUpdt!=null) oUpdt.close(); } catch (Exception JavaDoc ignore) {}
161     try { if (oInsr!=null) oUpdt.close(); } catch (Exception JavaDoc ignore) {}
162   }
163
164   // ---------------------------------------------------------------------------
165

166   private static boolean test(int iInputValue, int iBitMask) {
167     return (iInputValue&iBitMask)!=0;
168   } // test
169

170   // ---------------------------------------------------------------------------
171

172   public void store(Connection JavaDoc oConn, String JavaDoc sWorkArea, int iFlags)
173       throws SQLException JavaDoc,IllegalArgumentException JavaDoc,NullPointerException JavaDoc {
174
175     int iAffected;
176     if (oUpdt==null || oInsr==null)
177       throw new SQLException JavaDoc("Invalid command sequece. Must call ContactLoader.prepare() before TableLoader.store()");
178
179     if (!test(iFlags,MODE_APPEND) && !test(iFlags,MODE_UPDATE))
180       throw new IllegalArgumentException JavaDoc("TableLoader.store() Flags bitmask must contain either MODE_APPEND, MODE_UPDATE or both");
181
182     if (test(iFlags,MODE_UPDATE)) {
183       ListIterator JavaDoc oIter = getColumns().listIterator();
184       int iPos = 0;
185       while (oIter.hasNext()) {
186         DBColumn oCol = (DBColumn) oIter.next();
187         Integer JavaDoc iUpdtPos = (Integer JavaDoc) oUpdtColPos.get(oCol.getName());
188         if (null!=iUpdtPos) {
189           oUpdt.setObject(iUpdtPos.intValue(),aValues[iPos], oCol.getSqlType());
190         }
191         iPos++;
192       } // wend
193
iAffected = oUpdt.executeUpdate();
194     } // fi (MODE_UPDATE)
195

196     if (test(iFlags,MODE_APPEND)) {
197       ListIterator JavaDoc oIter = getColumns().listIterator();
198       int iPos = 0;
199       while (oIter.hasNext()) {
200         DBColumn oCol = (DBColumn) oIter.next();
201         Integer JavaDoc iInsrPos = (Integer JavaDoc) oUpdtColPos.get(oCol.getName());
202         if (null!=iInsrPos) {
203           oUpdt.setObject(iInsrPos.intValue(),aValues[iPos], oCol.getSqlType());
204         }
205         iPos++;
206       } // wend
207
iAffected = oInsr.executeUpdate();
208     } // fi (MODE_UPDATE)
209
}
210
211   // ---------------------------------------------------------------------------
212
}
213
Popular Tags