KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > utils > xml > DB2DOM


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
//
14
// DB2DOM
15
//
16
// NK 25.07.2001
17
//
18

19 package org.jahia.utils.xml;
20
21 import java.io.FileOutputStream JavaDoc;
22 import java.sql.ResultSet JavaDoc;
23 import java.sql.ResultSetMetaData JavaDoc;
24 import java.sql.SQLException JavaDoc;
25 import java.util.Hashtable JavaDoc;
26
27 import javax.xml.parsers.DocumentBuilder JavaDoc;
28 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
29 import javax.xml.transform.OutputKeys JavaDoc;
30 import javax.xml.transform.Transformer JavaDoc;
31 import javax.xml.transform.TransformerFactory JavaDoc;
32 import javax.xml.transform.dom.DOMSource JavaDoc;
33 import javax.xml.transform.stream.StreamResult JavaDoc;
34
35 import org.jahia.exceptions.JahiaException;
36 import org.jahia.utils.DBRowDataFilter;
37 import org.jahia.utils.JahiaConsole;
38 import org.jahia.utils.JahiaTools;
39 import org.w3c.dom.Document JavaDoc;
40 import org.w3c.dom.Element JavaDoc;
41 import org.w3c.dom.Text JavaDoc;
42
43
44 /**
45  * Class used to build DOM Document from database contents.
46  *
47  * @author Khue Nguyen
48  * @version 1.0
49  */

50 public class DB2DOM {
51
52     private static final String JavaDoc CLASS_NAME = "DB2DOM";
53
54     private static final String JavaDoc DATABASE_TAG = "database";
55     private static final String JavaDoc TABLE_TAG = "table";
56     private static final String JavaDoc ROW_TAG = "row";
57     private static final String JavaDoc COLUMN_TAG = "column";
58
59     private static final String JavaDoc ID_ATTRIB = "id";
60     private static final String JavaDoc NAME_ATTRIB = "name";
61     private static final String JavaDoc TYPE_ATTRIB = "type";
62
63     private Document JavaDoc xmlDoc = null;
64
65
66     //--------------------------------------------------------------------------
67
/**
68      * Class used to build DOM Document from database contents.
69      * Holds an internal Document object with Document Element node: <database></database>
70      * @auhtor NK
71      */

72     public DB2DOM ()
73     throws JahiaException{
74
75         try {
76
77             DocumentBuilderFactory JavaDoc dfactory =
78                                 DocumentBuilderFactory.newInstance();
79             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
80             xmlDoc = docBuilder.newDocument();
81
82         } catch ( Throwable JavaDoc t ){
83             throw new JahiaException( CLASS_NAME+".getDOMFromResultSet",
84                                 "Exception " + t.getMessage(),
85                                 JahiaException.ERROR_SEVERITY,
86                                 JahiaException.ERROR_SEVERITY);
87         }
88
89         Element JavaDoc dbNode = (Element JavaDoc) xmlDoc.createElement(DATABASE_TAG);
90         dbNode.normalize();
91
92         // add the database node
93
xmlDoc.appendChild(dbNode);
94
95     }
96
97     //--------------------------------------------------------------------------
98
/**
99      * Append a table node in the document.The DOM are build with data from resultset
100      *
101      * @param String tableName used to generate the <table name="tabName"> tag.
102      * @param ResultSet rs
103      *
104      * @auhtor NK
105      */

106     public void addTable( String JavaDoc tableName, ResultSet JavaDoc rs )
107     throws JahiaException,SQLException JavaDoc {
108
109         Document JavaDoc doc = getDOMFromResultSet(tableName,rs,null);
110         Element JavaDoc tableNode = doc.getDocumentElement();
111
112         Element JavaDoc dbNode = xmlDoc.getDocumentElement();
113         dbNode.appendChild(xmlDoc.importNode(tableNode,true));
114     }
115
116     //--------------------------------------------------------------------------
117
/**
118      * Append a table node in the document.The DOM are build with data from resultset
119      *
120      * @param String tableName used to generate the <table name="tabName"> tag.
121      * @param ResultSet rs
122      *
123      * @auhtor NK
124      */

125     public void addTable( String JavaDoc tableName, ResultSet JavaDoc rs , DBRowDataFilter filter )
126     throws JahiaException,SQLException JavaDoc {
127
128         Document JavaDoc doc = getDOMFromResultSet(tableName,rs,filter);
129         Element JavaDoc tableNode = doc.getDocumentElement();
130
131         Element JavaDoc dbNode = xmlDoc.getDocumentElement();
132         dbNode.appendChild(xmlDoc.importNode(tableNode,true));
133     }
134
135     //--------------------------------------------------------------------------
136
/**
137      * Append an Element to the the document
138      *
139      * @param Element a DOM representation of a table
140      *
141      * @auhtor NK
142      */

143     public void addTable( Element JavaDoc el )
144     throws JahiaException,SQLException JavaDoc {
145
146         Element JavaDoc dbNode = xmlDoc.getDocumentElement();
147         dbNode.appendChild(xmlDoc.importNode(el,true));
148
149     }
150
151
152     //--------------------------------------------------------------------------
153
/**
154      * save the document to a file
155      *
156      * @param String destFileName
157      */

158     public void save (String JavaDoc destFileName) throws JahiaException{
159         saveFile(destFileName);
160     }
161
162     //--------------------------------------------------------------------------
163
/**
164      * return a reference to the DOM Document
165      *
166      * @return Document the DOM Document
167      */

168     public Document JavaDoc getDocument () {
169         return xmlDoc;
170     }
171
172     //--------------------------------------------------------------------------
173
/**
174      * return a DOM as string
175      *
176      * @return Document the DOM Document
177      */

178     public String JavaDoc toString () {
179         Element JavaDoc el = (Element JavaDoc)xmlDoc.getDocumentElement();
180         if ( el != null ){
181             return el.toString();
182         }
183         return null;
184     }
185
186
187     //--------------------------------------------------------------------------
188
/**
189      * Processes through all rows in a resultset and returns its DOM
190      * representation
191      *
192      * <table name="mytable">
193      * <row id="1">
194      * <column name="col1" type="1">val1</column>
195      * <column name="col2" type="3">val2</column>
196      * </row>
197      * <row id="2">
198      * <column name="col1" type="1">val3</column>
199      * <column name="col2" type="3">val4</column>
200      * </row>
201      * </table>
202      *
203      *
204      * if the ResultSet is null, returns only <table name="mytable"></table>
205      *
206      *
207      * @param String tableName used to generate the <table name="tabName"> tag.
208      * @param ResultSet rs
209      * @return Document a DOM Document of the resulset, null if resultset is null
210      *
211      * @exception throw SQLException on sql error
212      * @exception throw JahiaException on XML error
213      *
214      * @auhtor NK
215      */

216     public static Document JavaDoc getDOMFromResultSet( String JavaDoc tableName,
217                                                     ResultSet JavaDoc rs,
218                                                     DBRowDataFilter filter )
219     throws JahiaException,SQLException JavaDoc {
220
221         JahiaConsole.println(CLASS_NAME+".getDOMFromResultSet","Table " + tableName);
222
223         Document JavaDoc xmlDoc = null;
224
225
226         try {
227
228             DocumentBuilderFactory JavaDoc dfactory =
229                                 DocumentBuilderFactory.newInstance();
230             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
231             xmlDoc = docBuilder.newDocument();
232
233         } catch ( Throwable JavaDoc t ){
234             throw new JahiaException( CLASS_NAME+".getDOMFromResultSet",
235                                 "Exception " + t.getMessage(),
236                                 JahiaException.ERROR_SEVERITY,
237                                 JahiaException.ERROR_SEVERITY);
238         }
239
240         if ( rs == null ){
241             Element JavaDoc tableNode = (Element JavaDoc) xmlDoc.createElement(TABLE_TAG);
242             tableNode.setAttribute(NAME_ATTRIB,tableName);
243             tableNode.normalize();
244             // add the table node
245
xmlDoc.appendChild(tableNode);
246             return xmlDoc;
247         }
248
249
250         String JavaDoc output = "";
251         StringBuffer JavaDoc buff = null;
252
253         ResultSetMetaData JavaDoc metaData = rs.getMetaData();
254         int columnCount = metaData.getColumnCount();
255
256         Element JavaDoc tableNode = (Element JavaDoc) xmlDoc.createElement(TABLE_TAG);
257         tableNode.setAttribute(NAME_ATTRIB,tableName);
258         tableNode.normalize();
259
260         String JavaDoc columnVal = null;
261         String JavaDoc columnName = null;
262         int columnType = 0;
263
264         // add the table node
265
xmlDoc.appendChild(tableNode);
266
267         Element JavaDoc rowNode = null;
268         Element JavaDoc columnNode = null;
269
270         while ( rs.next() ){
271             // create a row node
272
rowNode = (Element JavaDoc) xmlDoc.createElement(ROW_TAG);
273             rowNode.setAttribute(ID_ATTRIB,Integer.toString(rs.getRow()));
274
275             Hashtable JavaDoc vals = new Hashtable JavaDoc();
276             for(int column=1; column<=columnCount; column++) {
277
278                 // get column value
279
columnVal = JahiaTools.text2XMLEntityRef(rs.getString(column),0);
280                 columnType = metaData.getColumnType(column);
281                 columnName = metaData.getColumnLabel(column);
282
283                 if ( columnVal == null ){
284                     columnVal = "";
285                 }
286
287                 vals.put(columnName.toLowerCase(),columnVal);
288
289                 // create a column node
290
columnNode = (Element JavaDoc) xmlDoc.createElement(COLUMN_TAG);
291                 columnNode.setAttribute(NAME_ATTRIB, columnName);
292                 columnNode.setAttribute(TYPE_ATTRIB, Integer.toString(columnType));
293
294                 // append the value as Text Node
295
Text JavaDoc textNode = xmlDoc.createTextNode(columnVal);
296                 columnNode.appendChild(textNode);
297
298                 // add the column node to the row node
299
rowNode.appendChild(columnNode);
300                 columnNode = null;
301             }
302             if ( filter == null || filter.inValue(vals) ){
303                 // add the row node to the row set node
304
tableNode.appendChild(rowNode);
305             }
306             rowNode = null;
307         }
308
309         /*
310         JahiaConsole.println(CLASS_NAME+".getDOMFromResultSet"," DOM is "
311                                 + tableNode.toString());
312         System.gc();
313         */

314
315         return xmlDoc;
316     }
317
318
319
320
321     //--------------------------------------------------------------------------
322
/**
323      * Save the document to a file
324      *
325      * @param String the dest file name full path
326      */

327     private void saveFile(String JavaDoc destinationFileName)
328     throws JahiaException {
329
330         try {
331
332             xmlDoc.normalize(); // cleanup DOM tree a little
333

334             TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
335
336             // This creates a transformer that does a simple identity transform,
337
// and thus can be used for all intents and purposes as a serializer.
338
Transformer JavaDoc serializer = tfactory.newTransformer();
339
340             serializer.setOutputProperty(OutputKeys.METHOD, "xml");
341             serializer.setOutputProperty(OutputKeys.INDENT, "yes");
342             FileOutputStream JavaDoc fileStream = new FileOutputStream JavaDoc(destinationFileName);
343             serializer.transform(new DOMSource JavaDoc(xmlDoc),
344                              new StreamResult JavaDoc(fileStream));
345
346         } catch ( Throwable JavaDoc t ){
347             throw new JahiaException( "XMLPortlets",
348                                         "Exception " + t.getMessage(),
349                                         JahiaException.ERROR_SEVERITY,
350                                         JahiaException.SERVICE_ERROR);
351         }
352
353     }
354
355
356
357 }
358
Popular Tags