KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > webdocwf > util > loader > LoaderXIncluder


1 /*
2   Loader - tool for transfering data from one JDBC source to another and
3   doing transformations during copy.
4     Copyright (C) 2002 Together
5     This library is free software; you can redistribute it and/or
6     modify it under the terms of the GNU Lesser General Public
7     License as published by the Free Software Foundation; either
8     version 2.1 of the License, or (at your option) any later version.
9     This library is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12     Lesser General Public License for more details.
13     You should have received a copy of the GNU Lesser General Public
14     License along with this library; if not, write to the Free Software
15     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  LoaderXIncluder.java
17  Date: 22.09.2001.
18  @version 1.0
19  @author:
20  Milosevic Sinisa
21  */

22
23
24 package org.webdocwf.util.loader;
25
26 import java.io.BufferedInputStream JavaDoc;
27 import java.io.BufferedReader JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.InputStreamReader JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.io.OutputStreamWriter JavaDoc;
34 import java.io.UnsupportedEncodingException JavaDoc;
35 import java.io.Writer JavaDoc;
36 import java.net.MalformedURLException JavaDoc;
37 import java.net.URL JavaDoc;
38 import java.net.URLConnection JavaDoc;
39
40 import org.apache.xerces.parsers.SAXParser;
41 import org.webdocwf.util.loader.logging.Logger;
42 import org.xml.sax.AttributeList JavaDoc;
43 import org.xml.sax.HandlerBase JavaDoc;
44 import org.xml.sax.InputSource JavaDoc;
45 import org.xml.sax.SAXException JavaDoc;
46 import org.xml.sax.SAXParseException JavaDoc;
47
48 /**
49  * LoaderXIncluder.java
50  * This class parses a document (text or xml file) and writes the documents
51  * contents back to standard output.
52  */

53 public class LoaderXIncluder
54     extends HandlerBase JavaDoc {
55   private Writer JavaDoc out;
56   private String JavaDoc encoding;
57   private int level = 0;
58   //counter for dtd file
59
private int counter1 = 1;
60
61   //counter for sql files
62
private int counter2 = 0;
63
64   //counter for xml (import definition) file
65
private int counter3 = 0;
66
67   //counter for line before dtd file
68
private int counter4 = 0;
69
70   //counter for LoaderJob.xml (part) file
71
private int counter5 = 0;
72
73   //for create and drop database
74
private int counter6 = 0;
75
76   private boolean firstPartXml = true;
77
78   private String JavaDoc loaderJobPath="";
79
80   /** Main program entry point.
81    * @param argv represents input parmeters
82    */

83   public static void main(String JavaDoc argv[]) {
84     if (argv.length == 0) {
85       System.out.println("Usage: java LoaderXIncluder uri");
86       System.out.println(" where uri is the URI of your XML document.");
87       System.out.println(" Sample: java LoaderXIncluder demo.xml");
88       System.exit(1);
89     }
90     LoaderXIncluder s1 = new LoaderXIncluder();
91     s1.parseURI(argv[0]);
92   }
93
94   /**
95    * Constructor of class without parameters.
96    */

97   public LoaderXIncluder() {
98   }
99
100   /**
101    * Construct object LoaderXIncluder with associated outputStream and encoding.
102    * @param out - OutputStream where will be written final XML.
103    * @param encoding - encoding String representation of encoding.
104    * @throws UnsupportedEncodingException
105    */

106   public LoaderXIncluder(OutputStream JavaDoc out, String JavaDoc encoding) throws UnsupportedEncodingException JavaDoc {
107     this.out = new OutputStreamWriter JavaDoc(out, encoding);
108     this.encoding = encoding;
109   }
110
111   /**
112    * Construct object LoaderXIncluder with associated outputStream.
113    * Class uses default "UTF-8" encoding.
114    * @param out - OutputStream where will be written final XML.
115    */

116   public LoaderXIncluder(OutputStream JavaDoc out) {
117     try {
118       this.out = new OutputStreamWriter JavaDoc(out, "UTF8");
119       this.encoding = "UTF-8";
120     }
121     catch (UnsupportedEncodingException JavaDoc e) {}
122   }
123
124   /**
125    * Method parseUri parses a file "uri" and writes the file
126    * contents back to standard output including contents of 'include' files .
127    * @param uri - Name of XML file.
128    */

129   public void parseURI(String JavaDoc uri) {
130     try {
131       SAXParser parser = new SAXParser();
132       parser.setDocumentHandler(this);
133       parser.setEntityResolver(this);
134       parser.setFeature("http://xml.org/sax/features/validation", false);
135       parser.setErrorHandler(this);
136 // System.out.println("Loader loads XML file : "+ uri+"\n");
137
Logger.getCentralLogger().write("normal", "Loader loads XML file : " + uri);
138
139       File JavaDoc f = new File JavaDoc(uri);
140       this.loaderJobPath=f.getCanonicalFile().getParent();
141       URL JavaDoc xml = f.toURL();
142
143       InputStreamReader JavaDoc xmlStream = new InputStreamReader JavaDoc(xml.openStream());
144       BufferedReader JavaDoc reader = new BufferedReader JavaDoc(xmlStream);
145       String JavaDoc intro = "";
146       while ( (intro = reader.readLine()) != null) {
147         if (intro.indexOf("include") == -1)
148           counter6++;
149         else
150           break;
151       }
152       counter6 = counter6 - 4;
153       LocationOfException.setJdbcNumber(counter6);
154       reader.close();
155       xmlStream.close();
156       parser.parse(uri);
157     }
158     catch (Exception JavaDoc e) {
159 // System.err.println();
160
e.printStackTrace();
161       Logger.getCentralLogger().write("normal", e.getMessage());
162     }
163   }
164
165   boolean hasDTD = false;
166   /** Processing DOCTYPE deklaration
167    * @param publicId is public ID of document
168    * @param systemId is system ID of document
169    * @return null
170    */

171   public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) {
172     hasDTD = true;
173     try {
174       if (systemId != null) {
175         out.write("<!DOCTYPE loaderJob SYSTEM \"" + systemId + "\">" + "\n");
176         counter4++;
177       } else if (publicId != null) {
178         out.write("<!DOCTYPE loaderJob PUBLIC \"" + publicId + "\">" + "\n");
179         counter4++;
180       }
181     }
182     catch (Exception JavaDoc e) {
183       System.err.println(e);
184     }
185     return null;
186   }
187
188   /** Processing instruction.
189    *@param target is target
190    *@param data is target data
191    */

192   public void processingInstruction(String JavaDoc target, String JavaDoc data) {
193     try {
194       out.write("<?");
195       out.write(target);
196       if (data != null && data.length() > 0) {
197         out.write(' ');
198         out.write(data);
199       }
200       out.write("?>");
201       counter4++;
202     }
203     catch (IOException JavaDoc e) {
204       System.err.println(e);
205     }
206   }
207
208   /** Start document. */
209   public void startDocument() {
210     if (level == 0) {
211       try {
212         out.write("<?xml version=\"1.0\"?>\r\n");
213         counter4++;
214       }
215       catch (IOException JavaDoc e) {
216         System.err.println(e);
217       }
218       LocationOfException.setIntroNumber(counter4);
219     }
220   }
221
222   /** Start element.
223    * @param name is name of the tag
224    * @param atts is attributes of the tag
225    */

226   public void startElement(String JavaDoc name, AttributeList JavaDoc atts) {
227     try {
228       //if DTD or SCHEMA is not defined use default
229
if (name.equalsIgnoreCase("loaderJob")) {
230         /*
231         if (!hasDTD) {
232           String OCTOPUS_HOME = System.getProperty("OCTOPUS_HOME");
233           if (OCTOPUS_HOME != null) {
234             if (! (OCTOPUS_HOME.endsWith("\\") || OCTOPUS_HOME.endsWith("/")))
235               OCTOPUS_HOME += "/";
236             String url = "file:///" + OCTOPUS_HOME + "XmlTransform/xml/dtd/loaderJob.dtd";
237             out.write("<!DOCTYPE loaderJob SYSTEM \"" + url + "\">" + "\n");
238           } else {
239             URL dtdURL = this.getClass().getClassLoader().getResource("xml/dtd/loaderJob.dtd");
240             InputStreamReader dtdStream = new InputStreamReader(dtdURL.openStream());
241             BufferedReader reader = new BufferedReader(dtdStream);
242             StringBuffer sb = new StringBuffer();
243             String nextLine = "";
244             boolean firstLine = true;
245             while ( (nextLine = reader.readLine()) != null) {
246               if (!firstLine) {
247                 sb.append(nextLine + "\n");
248                 counter1++;
249               } else
250                 firstLine = false;
251             }
252             out.write("<!DOCTYPE loaderJob [" + sb.toString() + "\n]>");
253             counter1++;
254             LocationOfException.setDtdNumber(counter1);
255           }
256         }
257         */

258       }
259       if (name.equalsIgnoreCase("include")) {
260         String JavaDoc href = atts.getValue("href");
261         if (href == null) {
262           System.out.println("Missing href attribute in include Element");
263           System.exit(1);
264         }
265
266         File JavaDoc file=new File JavaDoc(href);
267         if(!file.isAbsolute()){
268           String JavaDoc tmp=this.loaderJobPath + System.getProperty("file.separator") + href;
269           File JavaDoc fileHref=new File JavaDoc(tmp);
270           href = fileHref.getCanonicalPath();
271         }
272
273         String JavaDoc parse = atts.getValue("parse");
274         if (parse == null)
275           parse = "xml";
276         if (parse.equals("text")) {
277           String JavaDoc encoding = atts.getValue("encoding");
278           includeTextDocument(href, encoding);
279         } else if (parse.equals("xml")) {
280           level++;
281           includeXMLDocument(href);
282           level--;
283         } else {
284           System.out.println("Illegal value for parse attribute: " + parse);
285           Logger.getCentralLogger().write("normal", "Illegal value for parse attribute: " + parse);
286           System.exit(1);
287         }
288       } else if (name.equalsIgnoreCase("definitionInclude")) {
289       } else {
290         out.write("<" + name);
291                 if (name.equals("loaderJob")) {
292                     out.write(" xmlns='http://www.objectweb.org'");
293                     out.write(" xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'");
294                     out.write(" xsi:schemaLocation='http://www.objectweb.org http://octopus.objectweb.org/doc/XmlTransform/xml/xmlschema/loaderJob.xsd'");
295                     out.write(" ");
296                 }
297 // if(name.startsWith("jdbc"))
298
// counter5++;
299
// if(!name.startsWith("jdbc") && counter5!=0 && firstPartXml==true){
300
// LocationOfException.setJdbcNumber(counter5);
301
// firstPartXml=false;
302
// counter5=0;
303
// }
304
//System.out.println("atts="+atts);
305
for (int i = 0; i < atts.getLength(); i++) {
306           out.write(" ");
307           out.write(atts.getName(i));
308           out.write("='");
309           String JavaDoc value = atts.getValue(i);
310           // + 4 allows space for one entitiy reference.
311
// If there's more than that, then the StringBuffer
312
// will automatically expand
313
// Need to use character references if the encoding
314
// can't support the character
315
StringBuffer JavaDoc encodedValue = new StringBuffer JavaDoc(value.length() + 4);
316           for (int j = 0; j < value.length(); j++) {
317             char c = value.charAt(j);
318             if (c == '&')
319               encodedValue.append("&amp;");
320             else if (c == '<')
321               encodedValue.append("&lt;");
322             else if (c == '>')
323               encodedValue.append("&gt;");
324             else if (c == '\'')
325               encodedValue.append("&apos;");
326             else
327               encodedValue.append(c);
328           }
329           out.write(encodedValue.toString());
330           out.write("'");
331         }
332         out.write(">");
333       }
334     }
335     catch (IOException JavaDoc e) {
336       System.err.println(e);
337       Logger.getCentralLogger().write("normal", e.getMessage());
338     }
339     catch (SAXException JavaDoc ex) {
340       System.err.println(ex);
341       Logger.getCentralLogger().write("normal", ex.getMessage());
342     }
343   }
344
345   /** Characters.
346    * @param ch is array of characters
347    * @param start is int
348    * @param length is length of the input parameters
349    * @throws SAXException
350    */

351   public void characters(char ch[], int start, int length) throws SAXException JavaDoc {
352     try {
353       for (int i = 0; i < length; i++) {
354         char c = ch[start + i];
355         if (c == '&')
356           out.write("&amp;");
357         else if (c == '<')
358           out.write("&lt;");
359         else if (c == '\n') {
360           counter2++;
361           out.write(c);
362         } else
363           out.write(c);
364       }
365     }
366     catch (IOException JavaDoc e) {
367       System.err.println(e);
368       Logger.getCentralLogger().write("normal", e.getMessage());
369     }
370   }
371
372   /** Ignorable whitespace.
373    * @param ch is array of characters
374    * @param start is int
375    * @param length is length of the input parameters
376    */

377   public void ignorableWhitespace(char ch[], int start, int length) {
378     try {
379       this.characters(ch, start, length);
380     }
381     catch (SAXException JavaDoc e) {
382       System.err.println(e);
383       Logger.getCentralLogger().write("normal", e.getMessage());
384     }
385   }
386
387   /** End element.
388    * @param name is name of the tag
389    */

390   public void endElement(String JavaDoc name) {
391     if (!name.equalsIgnoreCase("include") && !name.equalsIgnoreCase("definitionInclude")) {
392 // if(name.startsWith("jdbc")&&name.endsWith("s"))
393
// counter5++;
394
try {
395         out.write("</");
396         out.write(name);
397         out.write(">");
398       }
399       catch (IOException JavaDoc e) {
400         System.err.println(e);
401         Logger.getCentralLogger().write("normal", e.getMessage());
402       }
403     }
404   }
405
406   /** End document. */
407   public void endDocument() {
408     try {
409       out.flush();
410     }
411     catch (IOException JavaDoc e) {
412       System.err.println(e);
413       Logger.getCentralLogger().write("normal", e.getMessage());
414     }
415   }
416
417   //
418
// ErrorHandler methods
419
//
420
/** Warning.
421    * @param ex is SAXParseException exception
422    */

423   public void warning(SAXParseException JavaDoc ex) {
424     System.err.println("[Warning] " + getLocationString(ex) + ": " + ex.getMessage());
425     Logger.getCentralLogger().write("normal",
426         "[Warning] " + getLocationString(ex) + ": " + ex.getMessage());
427   }
428
429   /** Error.
430    * @param ex is SAXParseException exception
431    */

432   public void error(SAXParseException JavaDoc ex) {
433     System.err.println("[Error] " + getLocationString(ex) + ": " + ex.getMessage());
434     Logger.getCentralLogger().write("normal",
435         "[Error] " + getLocationString(ex) + ": " + ex.getMessage());
436   }
437
438   /** Fatal error.
439    * @param ex is SAXParseException exception
440    * @throws SAXException
441    */

442   public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
443     System.err.println("[Fatal Error] " + getLocationString(ex) + ": " + ex.getMessage());
444     Logger.getCentralLogger().write("normal",
445         "[Fatal Error] " + getLocationString(ex) + ": " + ex.getMessage());
446     throw ex;
447   }
448
449   /** Returns a string of the location.
450    * @param ex is SAXParseException exception
451    * @return string
452    */

453   private String JavaDoc getLocationString(SAXParseException JavaDoc ex) {
454     StringBuffer JavaDoc str = new StringBuffer JavaDoc();
455     String JavaDoc systemId = ex.getSystemId();
456     if (systemId != null) {
457       int index = systemId.lastIndexOf('/');
458       if (index != -1)
459         systemId = systemId.substring(index + 1);
460       str.append(systemId);
461     }
462     str.append(':');
463     str.append(ex.getLineNumber());
464     str.append(':');
465     str.append(ex.getColumnNumber());
466     return str.toString();
467   }
468
469   /**
470    * <p>
471    * This utility method reads a document at a specified URL
472    * and fires off calls to <code>characters()</code>.
473    * It's used to include files with <code>parse="text"</code>
474    * </p>
475    *
476    * @param url URL of the document that will be read
477    * @param encoding Encoding of the document; e.g. UTF-8,
478    * ISO-8859-1, etc.
479    * @throws SAXException if the requested document cannot
480    * be downloaded from the specified URL
481    * or if the encoding is not recognized
482    */

483   private void includeTextDocument(String JavaDoc url, String JavaDoc encoding) throws SAXException JavaDoc {
484     if (encoding == null || encoding.trim().equals(""))
485       encoding = "UTF-8";
486     File JavaDoc sourceXml = new File JavaDoc(url);
487     URL JavaDoc source;
488     counter2 = 1;
489     try {
490       source = sourceXml.toURL();
491     }
492     catch (MalformedURLException JavaDoc e) {
493       Logger.getCentralLogger().write("normal", "Unresolvable URL :" + e.getMessage());
494       throw new SAXException JavaDoc("Unresolvable URL :", e);
495     }
496     try {
497       URLConnection JavaDoc uc = source.openConnection();
498       String JavaDoc encodingFromHeader = uc.getContentEncoding();
499       if (encodingFromHeader != null)
500         encoding = encodingFromHeader;
501       InputStream JavaDoc in = new BufferedInputStream JavaDoc(uc.getInputStream());
502       InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(in, encoding);
503       char[] c = new char[1024];
504       while (true) {
505         int charsRead = reader.read(c, 0, 1024);
506         if (charsRead == -1)
507           break;
508         if (charsRead > 0)
509           this.characters(c, 0, charsRead);
510       }
511       counter2 = counter2 + 4;
512       LocationOfException.setFileLineNumber(counter2, url);
513 // System.out.println("Sql file "+url+"ima broj linija :"+counter2);
514
counter2 = 0;
515     }
516     catch (UnsupportedEncodingException JavaDoc e) {
517       Logger.getCentralLogger().write("normal", "Unsupported encoding: " + encoding);
518       throw new SAXException JavaDoc("Unsupported encoding: " + encoding, e);
519     }
520     catch (IOException JavaDoc e) {
521       Logger.getCentralLogger().write("normal", "Document not found: " + source.toExternalForm());
522       throw new SAXException JavaDoc("Document not found: " + source.toExternalForm(), e);
523     }
524   }
525
526   /**
527    * <p>
528    * This utility method reads a document at a specified URL
529    * and fires off calls to various <code>DocumentHandler</code> methods.
530    * It's used to include files with <code>parse="xml"</code>
531    * </p>
532    *
533    * @param url URL of the document that will be read
534    * @throws SAXException if the requested document cannot
535    be downloaded from the specified URL.
536    */

537   private void includeXMLDocument(String JavaDoc url) throws SAXException JavaDoc {
538     File JavaDoc sourceXml = new File JavaDoc(url);
539     URL JavaDoc source;
540     InputStream JavaDoc includeXML = null;
541 // int counter3=0;
542
try {
543       source = sourceXml.toURL();
544       includeXML = source.openStream();
545       InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(includeXML);
546       BufferedReader JavaDoc br = new BufferedReader JavaDoc(isr);
547       while (br.readLine() != null)
548         counter3++;
549       counter3 = counter3 + 2;
550       LocationOfException.setFileLineNumber(counter3, url);
551 // System.out.println("xml file " + url+" ima broj linija :"+counter3);
552
counter3 = 0;
553 // LocationOfException.setJdbcNumber(counter2);
554

555     }
556     catch (MalformedURLException JavaDoc e) {
557       Logger.getCentralLogger().write("normal", "Unresolvable URL :" + e.getMessage());
558       throw new SAXException JavaDoc("Unresolvable URL :", e);
559     }
560     catch (IOException JavaDoc e) {
561       Logger.getCentralLogger().write("normal", "Error in opening input stream :" + e.getMessage());
562       throw new SAXException JavaDoc("Error in opening input stream :", e);
563     }
564
565     SAXParser includeParser = new SAXParser();
566     includeParser.setDocumentHandler(this);
567     includeParser.setEntityResolver(this);
568     includeParser.setErrorHandler(this);
569     try {
570       includeParser.parse(url);
571     }
572     catch (Exception JavaDoc e) {
573       System.err.println(e);
574       Logger.getCentralLogger().write("normal", e.getMessage());
575     }
576   }
577
578
579 }
580
Popular Tags