KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > dataxslt > PageSet


1 /*
2   Copyright (C) 2003 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.dataxslt;
34
35 import java.lang.ClassNotFoundException JavaDoc;
36 import java.lang.IllegalAccessException JavaDoc;
37 import java.lang.StringBuffer JavaDoc;
38
39 import java.util.LinkedList JavaDoc;
40 import java.util.Vector JavaDoc;
41 import java.util.Properties JavaDoc;
42 import java.util.HashMap JavaDoc;
43
44 import java.sql.Statement JavaDoc;
45 import java.sql.ResultSet JavaDoc;
46 import java.sql.ResultSetMetaData JavaDoc;
47 import java.sql.SQLException JavaDoc;
48
49 import java.io.IOException JavaDoc;
50 import java.io.FileNotFoundException JavaDoc;
51 import java.io.UnsupportedEncodingException JavaDoc;
52 import java.io.InputStream JavaDoc;
53 import java.io.File JavaDoc;
54 import java.io.FileReader JavaDoc;
55 import java.io.FileWriter JavaDoc;
56 import java.io.FileInputStream JavaDoc;
57 import java.io.FileOutputStream JavaDoc;
58 import java.io.ByteArrayOutputStream JavaDoc;
59 import java.io.StringWriter JavaDoc;
60 import java.io.UTFDataFormatException JavaDoc;
61
62 import java.net.URL JavaDoc;
63 import java.net.MalformedURLException JavaDoc;
64
65 import javax.activation.DataHandler JavaDoc;
66
67 import javax.xml.transform.Transformer JavaDoc;
68 import javax.xml.transform.stream.StreamResult JavaDoc;
69 import javax.xml.transform.stream.StreamSource JavaDoc;
70 import javax.xml.transform.TransformerException JavaDoc;
71 import javax.xml.transform.TransformerConfigurationException JavaDoc;
72 import javax.xml.transform.SourceLocator JavaDoc;
73 import javax.xml.transform.OutputKeys JavaDoc;
74
75 import org.w3c.dom.Element JavaDoc;
76 import org.w3c.dom.Node JavaDoc;
77 import org.w3c.dom.NodeList JavaDoc;
78 import org.w3c.dom.DOMException JavaDoc;
79
80 import dom.DOMDocument;
81
82 import org.apache.oro.text.regex.*;
83
84 import com.knowgate.jdc.JDCConnection;
85
86 import com.knowgate.dfs.FileSystem;
87
88 import com.knowgate.debug.DebugFile;
89
90 import com.knowgate.misc.Gadgets;
91
92 import com.knowgate.dataobjs.DB;
93 import com.knowgate.dataobjs.DBTable;
94 import com.knowgate.dataobjs.DBSubset;
95 import com.knowgate.dataobjs.DBPersist;
96
97 /**
98  * PageSet DOMDocument
99  * @author Sergio Montoro Ten
100  * @version 2.1
101  */

102 public class PageSet extends DOMDocument {
103
104   //-----------------------------------------------------------
105

106   private Microsite oMSite; // Microsite metadata definition
107
private String JavaDoc sURI; // Path to XML data file.
108
private TransformerException JavaDoc oLastXcpt; // Last TransformerException raised by
109
// buildSite() or buildSiteForEdit()
110

111   //***************************************************************
112
// Constructors
113

114   private void initMicrosite(String JavaDoc sMsiteURI, boolean bValidateXML)
115     throws ClassNotFoundException JavaDoc, Exception JavaDoc, IllegalAccessException JavaDoc,FileNotFoundException JavaDoc {
116
117     if (DebugFile.trace) DebugFile.writeln("PageSet.initMicrosite(" + sMsiteURI + ",schema-validation=" + String.valueOf(bValidateXML) + ")");
118
119     // Load Microsite
120

121     if (sMsiteURI.startsWith("/") || sMsiteURI.startsWith("\\")) {
122
123       File JavaDoc oMFile = new File JavaDoc(sMsiteURI);
124
125       if (!oMFile.exists())
126         throw new FileNotFoundException JavaDoc (sMsiteURI + " not found");
127
128       oMFile = null;
129
130       oMSite = MicrositeFactory.getInstance("file://" + sMsiteURI, bValidateXML);
131     }
132     else
133       oMSite = MicrositeFactory.getInstance(sMsiteURI, bValidateXML);
134   }
135
136  /**
137   * Create empty PageSet from a Microsite.
138   * XML validation is disabled.
139   * @param sMsiteURI Microsite XML file URI
140   * @throws ClassNotFoundException
141   * @throws IllegalAccessException
142   * @throws FileNotFoundException
143   */

144   public PageSet(String JavaDoc sMsiteURI)
145     throws ClassNotFoundException JavaDoc, IllegalAccessException JavaDoc, FileNotFoundException JavaDoc, Exception JavaDoc {
146
147     initMicrosite(sMsiteURI, this.getValidation());
148
149     sURI = null;
150   } // PageSet()
151

152   /**
153    * Create empty PageSet from a Microsite
154    * @param sMsiteURI Microsite XML file URI
155    * (for example file:///opt/knowgate/storage/xslt/templates/Comtemporary.xml)
156    * @param bValidateXML <b>true</b> if XML validation with W3C schemas is to be done,
157    * <b>false</b> is no validation is to be done.
158    * @throws ClassNotFoundException
159    * @throws IllegalAccessException
160    * @throws FileNotFoundException
161    */

162   public PageSet(String JavaDoc sMsiteURI, boolean bValidateXML)
163     throws ClassNotFoundException JavaDoc, Exception JavaDoc, IllegalAccessException JavaDoc, FileNotFoundException JavaDoc {
164     super("UTF-8", bValidateXML, false);
165
166     if (DebugFile.trace) DebugFile.writeln("new PageSet(" + sMsiteURI + ",schema-validation=" + String.valueOf(bValidateXML) + ")");
167
168     initMicrosite(sMsiteURI, bValidateXML);
169     sURI = null;
170   } // PageSet()
171

172   /**
173    * Create PageSet from a Microsite and load data from an XML file.
174    * @param sMsiteURI Microsite XML file URI
175    * @param sPageSetURI PageSet XML file URI
176    * (for example file:///opt/knowgate/storage/domains/1026/workareas/f7f055ca39854673b17518ec5f87de3b/apps/Mailwire/data/Newsletter01.xml)
177    * @throws ClassNotFoundException
178    * @throws IllegalAccessException
179    */

180   public PageSet(String JavaDoc sMsiteURI, String JavaDoc sPageSetURI)
181     throws ClassNotFoundException JavaDoc, Exception JavaDoc, IllegalAccessException JavaDoc, FileNotFoundException JavaDoc {
182
183     if (DebugFile.trace) DebugFile.writeln("new PageSet(" + sMsiteURI + "," + sPageSetURI + ")");
184
185     File JavaDoc oPFile;
186
187     if (sMsiteURI.startsWith("file://"))
188       initMicrosite(sMsiteURI, this.getValidation());
189     else
190       initMicrosite("file://" + sMsiteURI, this.getValidation());
191
192     sURI = sPageSetURI;
193
194     if (sPageSetURI.startsWith("file://")) {
195       oPFile = new File JavaDoc(sPageSetURI.substring(7));
196
197       if (!oPFile.exists())
198         throw new FileNotFoundException JavaDoc (sPageSetURI.substring(7) + " not found");
199
200       if (DebugFile.trace) DebugFile.writeln("parseURI (" + sPageSetURI + ");");
201
202       parseURI(sPageSetURI);
203     }
204     else {
205       oPFile = new File JavaDoc(sPageSetURI);
206
207       if (!oPFile.exists())
208         throw new FileNotFoundException JavaDoc (sPageSetURI + " not found");
209
210       if (DebugFile.trace) DebugFile.writeln("parseURI (file://" + sPageSetURI + ");");
211
212       parseURI("file://" + sPageSetURI);
213     }
214     // fi (sPageSetURI.startsWith("file://"))
215

216     oPFile = null;
217
218   } // PageSet()
219

220   /**
221    * Create PageSet from a Microsite and load data from an XML file.
222    * @param sMsiteURI Microsite XML file URI
223    * @param sPageSetURI PageSet XML file URI
224    * @param bValidateXML <b>true</b> if XML validation with W3C schemas is to be done,
225    * <b>false</b> is no validation is to be done.
226    * @throws ClassNotFoundException
227    * @throws IllegalAccessException
228    */

229
230   public PageSet(String JavaDoc sMsiteURI, String JavaDoc sPageSetURI, boolean bValidateXML)
231     throws ClassNotFoundException JavaDoc, Exception JavaDoc, IllegalAccessException JavaDoc, FileNotFoundException JavaDoc {
232
233     super("UTF-8", bValidateXML, false);
234
235     if (DebugFile.trace) DebugFile.writeln("new PageSet(" + sMsiteURI + "," + sPageSetURI + ",schema-validation=" + String.valueOf(bValidateXML) + ")");
236
237     File JavaDoc oPFile;
238
239     if (sMsiteURI.startsWith("file://"))
240       initMicrosite(sMsiteURI, bValidateXML);
241     else
242       initMicrosite("file://" + sMsiteURI, bValidateXML);
243
244     sURI = sPageSetURI;
245
246     if (sPageSetURI.startsWith("file://")) {
247       oPFile = new File JavaDoc(sPageSetURI.substring(7));
248
249       if (!oPFile.exists())
250         throw new FileNotFoundException JavaDoc (sPageSetURI.substring(7) + " not found");
251
252       parseURI(sPageSetURI);
253     }
254     else {
255       oPFile = new File JavaDoc(sPageSetURI);
256
257       if (!oPFile.exists())
258         throw new FileNotFoundException JavaDoc (sPageSetURI + " not found");
259
260       parseURI("file://" + sPageSetURI);
261     }
262   } // PageSet()
263

264   //-----------------------------------------------------------
265

266   /**
267    * Get PageSet &lt;guid&gt; value
268    */

269   public String JavaDoc guid() {
270     Node JavaDoc oPageSetNode = getRootNode().getFirstChild();
271
272     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
273
274     // Devuelve el valor del atributo guid del nodo <pageset>
275
return getAttribute(oPageSetNode, "guid");
276   } // guid()
277

278   //-----------------------------------------------------------
279

280   /**
281    * Last TransformerException raised by buildSite() or buildSiteForEdit()
282    */

283   public TransformerException JavaDoc lastException() {
284     return oLastXcpt;
285   }
286
287   //-----------------------------------------------------------
288

289   public Microsite microsite() {
290     return oMSite;
291   }
292
293   //-----------------------------------------------------------
294

295   /**
296    * GUID of Catalog associated to this PageSet
297    * @return Catalog GUID or <b>null</b> if &lt;catalog&gt; node does not exist.
298    * @throws DOMException
299    */

300
301   public String JavaDoc catalog() throws DOMException JavaDoc {
302
303     Node JavaDoc oCatalogNode;
304     String JavaDoc sRetVal;
305
306     if (DebugFile.trace)
307       DebugFile.writeln("Begin PageSet.catalog()");
308
309     if (DebugFile.trace) DebugFile.incIdent();
310
311     // Get a reference to top Node
312
Node JavaDoc oPageSetNode = getRootNode().getFirstChild();
313     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
314
315     // Find <pages> node
316
oCatalogNode = seekChildByName(oPageSetNode, "catalog");
317
318     if (oCatalogNode==null)
319       sRetVal = null;
320     else
321       sRetVal = oCatalogNode.getFirstChild().getNodeValue();
322
323     if (DebugFile.trace) {
324       DebugFile.decIdent();
325       DebugFile.writeln("End PageSet.catalog() : " + sRetVal);
326     }
327
328     return sRetVal;
329   } // company()
330

331   //-----------------------------------------------------------
332

333   /**
334    * GUID of Company associated to this PageSet
335    * @return Company GUID or <b>null</b> if &lt;company&gt; node does not exist.
336    * @throws DOMException
337    */

338
339   public String JavaDoc company() throws DOMException JavaDoc {
340
341     Node JavaDoc oCompanyNode;
342     String JavaDoc sRetVal;
343
344     if (DebugFile.trace)
345       DebugFile.writeln("Begin PageSet.company()");
346
347     if (DebugFile.trace) DebugFile.incIdent();
348
349     // Get a reference to top Node
350
Node JavaDoc oPageSetNode = getRootNode().getFirstChild();
351     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
352
353     // Find <pages> node
354
oCompanyNode = seekChildByName(oPageSetNode, "company");
355
356     if (oCompanyNode==null)
357       sRetVal = null;
358     else
359       sRetVal = oCompanyNode.getFirstChild().getNodeValue();
360
361     if (DebugFile.trace) {
362       DebugFile.decIdent();
363       DebugFile.writeln("End PageSet.company() : " + sRetVal);
364     }
365
366     return sRetVal;
367   } // catalog()
368

369   // ---------------------------------------------------------------------------
370

371   /**
372    * Get a Page from this PageSet
373    * @param sPageId GUID of page to be retrieved
374    * @return Page object or <b>null</b> if no page with such GUID was found at XML file
375    * @throws DOMException If <pages> node is not found
376    * @throws NullPointerException If sPageId is <b>null</b>
377    */

378
379   public Page page(String JavaDoc sPageId) throws DOMException JavaDoc,NullPointerException JavaDoc {
380
381     Node JavaDoc oPagesNode;
382     Element JavaDoc oContainers;
383     NodeList JavaDoc oNodeList;
384     Page oCurrent;
385     Page oRetVal = null;
386
387     if (DebugFile.trace)
388       DebugFile.writeln("Begin PageSet.page(" + sPageId + ")");
389
390     if (null==sPageId)
391       throw new NullPointerException JavaDoc("PageSet.page(), parameter sPageId may not be null");
392
393     if (DebugFile.trace) DebugFile.incIdent();
394
395     // Get a reference to top Node
396
Node JavaDoc oPageSetNode = getRootNode().getFirstChild();
397     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
398
399     // Find <pages> node
400
oPagesNode = seekChildByName(oPageSetNode, "pages");
401
402     if (oPagesNode==null)
403       throw new DOMException JavaDoc(DOMException.NOT_FOUND_ERR, "<pages> node not found");
404
405     oNodeList = ((Element JavaDoc)oPagesNode).getElementsByTagName("page");
406
407     if (oNodeList.getLength()>0) {
408
409       // Cast DOM nodes to Page objects inside Vector
410
for (int i=0; i<oNodeList.getLength() && (null==oRetVal); i++) {
411         oCurrent = new Page(oNodeList.item(i), this);
412         if (sPageId.equals(oCurrent.guid()))
413           oRetVal = oCurrent;
414       } // next
415
} // fi (oNodeList.getLength()>0)
416

417     if (DebugFile.trace) {
418       DebugFile.decIdent();
419       DebugFile.writeln("End PageSet.page() : " + oRetVal);
420     }
421
422     return oRetVal;
423   } // page()
424

425   //-----------------------------------------------------------
426

427   /**
428    * Get pages for this PageSet
429    * @return vector of Page objects
430    * @throws DOMException If <pages> node is not found
431    */

432   public Vector JavaDoc pages() throws DOMException JavaDoc {
433     Node JavaDoc oPagesNode;
434     Element JavaDoc oContainers;
435     NodeList JavaDoc oNodeList;
436     Vector JavaDoc oLinkVctr;
437
438     if (DebugFile.trace) {
439       DebugFile.writeln("Begin PageSet.pages()");
440       DebugFile.incIdent();
441     }
442
443     // get a reference to top Node
444
Node JavaDoc oPageSetNode = getRootNode().getFirstChild();
445     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
446
447     // Buscar el nodo <pages>
448
oPagesNode = seekChildByName(oPageSetNode, "pages");
449
450     if (oPagesNode==null)
451       throw new DOMException JavaDoc(DOMException.NOT_FOUND_ERR, "<pages> node not found");
452
453     oNodeList = ((Element JavaDoc)oPagesNode).getElementsByTagName("page");
454
455     if (oNodeList.getLength()>0) {
456       // Create Vector
457
oLinkVctr = new Vector JavaDoc(oNodeList.getLength());
458
459       // Cast DOM nodes to Page objects inside Vector
460
for (int i=0; i<oNodeList.getLength(); i++)
461         oLinkVctr.add(new Page (oNodeList.item(i), this));
462     }
463     else
464       oLinkVctr = new Vector JavaDoc();
465
466     if (DebugFile.trace) {
467       DebugFile.decIdent();
468       DebugFile.writeln("End PageSet.pages()");
469     }
470
471     return oLinkVctr;
472   } // pages()
473

474   //-----------------------------------------------------------
475

476   /**
477    * Get Addresses for this PageSet
478    * @return vector of Page objects
479    * @throws DOMException If <addresses> node is not found
480    */

481   public Vector JavaDoc addresses() throws DOMException JavaDoc {
482     Node JavaDoc oPagesNode;
483     Element JavaDoc oContainers;
484     NodeList JavaDoc oNodeList;
485     Vector JavaDoc oLinkVctr;
486
487     if (DebugFile.trace) {
488       DebugFile.writeln("Begin PageSet.pages()");
489       DebugFile.incIdent();
490     }
491
492     // get a reference to top Node
493
Node JavaDoc oPageSetNode = getRootNode().getFirstChild();
494     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
495
496     // Buscar el nodo <pages>
497
oPagesNode = seekChildByName(oPageSetNode, "addresses");
498
499     if (oPagesNode==null)
500       throw new DOMException JavaDoc(DOMException.NOT_FOUND_ERR, "<addresses> node not found");
501
502     oNodeList = ((Element JavaDoc)oPagesNode).getElementsByTagName("address");
503
504     if (oNodeList.getLength()>0) {
505       // Create Vector
506
oLinkVctr = new Vector JavaDoc(oNodeList.getLength());
507
508       // Cast DOM nodes to Page objects inside Vector
509
for (int i=0; i<oNodeList.getLength(); i++)
510         oLinkVctr.add(new Page (oNodeList.item(i), this));
511     }
512     else
513       oLinkVctr = new Vector JavaDoc();
514
515     if (DebugFile.trace) {
516       DebugFile.decIdent();
517       DebugFile.writeln("End PageSet.addresses()");
518     }
519
520     return oLinkVctr;
521   } // addresses()
522

523   //-----------------------------------------------------------
524

525   private LinkedList JavaDoc matchChildsByTag(Node JavaDoc oParent, String JavaDoc sPattern) {
526     // Get a list of pointers to nodes with child <tag>
527
// matches a regular expression pattern.
528
// Parameters:
529
// oParent -> Parent Node
530
// sPattern -> Pattern to match
531

532     Node JavaDoc oCurrentNode = null; // Iterador de nodos hijo
533
Node JavaDoc oTag = null; // Nodo nieto <tag>
534
NodeList JavaDoc oChilds = oParent.getChildNodes(); // Lista total de nodos hijo
535
int iMaxNodes = oChilds.getLength(); // Cuenta de nodos hijo
536
LinkedList JavaDoc oList = new LinkedList JavaDoc(); // Lista resultado
537

538     Pattern oPattern = null;
539     PatternMatcher oMatcher = new Perl5Matcher();
540     PatternCompiler oCompiler = new Perl5Compiler();
541
542     try {
543       // Compile regular expression at Pattern Matcher
544
oPattern = oCompiler.compile(sPattern);
545     } catch(MalformedPatternException e) {}
546
547     // Iterate throught child nodes
548
for (int iNode=0; iNode<iMaxNodes; iNode++) {
549       // Assign oCurrentNode as an alias for the current node.
550
oCurrentNode = oChilds.item(iNode);
551       if(Node.ELEMENT_NODE==oCurrentNode.getNodeType()) {
552
553         // Seek grandchild by name
554
oTag = seekChildByName(oCurrentNode, "tag");
555         if (null!=oTag)
556           // If pattern matches add child to list
557
if (oMatcher.matches(getTextValue((Element JavaDoc)oTag), oPattern))
558             oList.addLast(oCurrentNode);
559       } // fi(ELEMENT_NODE)
560
} // next(iNode)
561

562     return oList;
563   } // matchChildsByTag
564

565
566   //-----------------------------------------------------------
567

568   /**
569    * <p>Generate XSL Transformation output for PageSet.</p>
570    * @param sBasePath Path to directory containing XSL stylesheets
571    * @param sOutputPath Path to output directory where generated files shall be saved.
572    * @param oEnvironmentProps Environment Properties
573    * @param oUserProps User Properties
574    * @return
575    * @throws IOException
576    * @throws TransformerException
577    * @throws TransformerConfigurationException
578    */

579   public Vector JavaDoc buildSite(String JavaDoc sBasePath, String JavaDoc sOutputPath, Properties JavaDoc oEnvironmentProps, Properties JavaDoc oUserProps)
580       throws IOException JavaDoc, DOMException JavaDoc, TransformerException JavaDoc, TransformerConfigurationException JavaDoc {
581
582     Transformer JavaDoc oTransformer;
583     StreamResult JavaDoc oStreamResult;
584     StreamSource JavaDoc oStreamSrcXML;
585     InputStream JavaDoc oXMLStream = null;
586     String JavaDoc sMedia;
587     Page oCurrentPage;
588     long lElapsed = 0;
589
590     final String JavaDoc sSep = System.getProperty("file.separator");
591
592     if (DebugFile.trace) {
593       lElapsed = System.currentTimeMillis();
594
595       DebugFile.writeln("Begin PageSet.BuildSite(" + sBasePath + "," + sOutputPath + "...)");
596       DebugFile.incIdent();
597     }
598
599     oLastXcpt = null;
600
601     if (!sBasePath.endsWith(sSep)) sBasePath += sSep;
602
603     Vector JavaDoc vPages = pages();
604
605     // Move to containers node
606
if (DebugFile.trace)
607       DebugFile.writeln("seekChildByName(,[Node], \"containers\")");
608
609     Node JavaDoc oContainers = oMSite.seekChildByName(oMSite.getRootNode().getFirstChild(), "containers");
610
611     if (oContainers==null) {
612       if (DebugFile.trace)
613         DebugFile.writeln("ERROR: <containers> node not found.");
614
615       throw new DOMException JavaDoc(DOMException.NOT_FOUND_ERR, "<containers> node not found");
616     }
617
618     // Load XML data stream only once for all containers
619
if (DebugFile.trace)
620       DebugFile.writeln("oXMLStream = new FileInputStream(" + sURI + ")");
621
622     // For each Page do XSL Transformation
623
for (int c=0; c<vPages.size(); c++) {
624       oCurrentPage = (Page) vPages.get(c);
625
626       oXMLStream = new FileInputStream JavaDoc(sURI);
627       oStreamSrcXML = new StreamSource JavaDoc(oXMLStream);
628
629       // XSL Transformation
630
try {
631         if (DebugFile.trace)
632           DebugFile.writeln("oTransformer = StylesheetCache.newTransformer(" + sBasePath + "xslt" + sSep + "templates" + sSep + oMSite.name() + sSep + oCurrentPage.template() + ")");
633
634         // Get a copy of Stylesheet from cache
635
oTransformer = StylesheetCache.newTransformer(sBasePath + "xslt" + sSep + "templates" + sSep + oMSite.name() + sSep + oCurrentPage.template());
636
637         sMedia = oTransformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
638         if (null==sMedia)
639           sMedia = "html";
640         else
641           sMedia = sMedia.substring(sMedia.indexOf('/')+1);
642
643         if (DebugFile.trace)
644           DebugFile.writeln("Pages[" + String.valueOf(c) + "].filePath(" + sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "." + sMedia + ")");
645
646         oCurrentPage.filePath(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "." + sMedia);
647
648         if (DebugFile.trace)
649           DebugFile.writeln("oStreamResult = new StreamResult(" + oCurrentPage.filePath() + ")");
650
651         oStreamResult = new StreamResult JavaDoc(oCurrentPage.filePath());
652
653         // Set environment parameters for stylesheet
654
StylesheetCache.setParameters(oTransformer, oEnvironmentProps);
655
656         // Set user defined parameters for stylesheet
657
StylesheetCache.setParameters(oTransformer, oUserProps);
658
659         // Realizar la transformación
660
if (DebugFile.trace)
661           DebugFile.writeln("oTransformer.transform(oStreamSrcXML, oStreamResult)");
662
663         oTransformer.setParameter("param_page", ((Page)(vPages.get(c))).getTitle());
664         oTransformer.transform(oStreamSrcXML, oStreamResult);
665       }
666       catch (TransformerConfigurationException JavaDoc e) {
667         oLastXcpt = e;
668         if (DebugFile.trace) DebugFile.writeln("ERROR TransformerConfigurationException " + e.getMessageAndLocation());
669       }
670       catch (TransformerException JavaDoc e) {
671         oLastXcpt = e;
672         if (DebugFile.trace) DebugFile.writeln("ERROR TransformerException " + e.getMessageAndLocation());
673       }
674
675       oTransformer = null;
676       oStreamResult = null;
677     } // next (c)
678

679     oXMLStream.close();
680
681     if (DebugFile.trace) {
682       DebugFile.writeln("done in " + String.valueOf(System.currentTimeMillis()-lElapsed) + " miliseconds");
683
684       DebugFile.decIdent();
685       DebugFile.writeln("End PageSet.buildSite()");
686     }
687
688     return vPages;
689   } // buildSite()
690

691
692   // ---------------------------------------------------------------------------
693

694   public Page buildPageForEdit(String JavaDoc sPageGUID, String JavaDoc sBasePath,
695                                String JavaDoc sOutputPath, String JavaDoc sCtrlPath,
696                                String JavaDoc sMenuPath, String JavaDoc sIntegradorPath,
697                                String JavaDoc sSelPageOptions,
698                                Properties JavaDoc oEnvironmentProps, Properties JavaDoc oUserProps)
699
700     throws IOException JavaDoc, DOMException JavaDoc, TransformerException JavaDoc,
701            TransformerConfigurationException JavaDoc, MalformedURLException JavaDoc {
702
703     Transformer JavaDoc oTransformer;
704     StreamResult JavaDoc oStreamResult;
705     StreamSource JavaDoc oStreamSrcXML;
706     StringWriter JavaDoc oStrWritter;
707     InputStream JavaDoc oXMLStream = null;
708     String JavaDoc sTransformed;
709     StringBuffer JavaDoc oPostTransform;
710     String JavaDoc sKey;
711     String JavaDoc sMedia;
712     Object JavaDoc sVal;
713     Page oCurrentPage;
714
715     int iCloseHead, iOpenBody, iCloseBody;
716     int iReaded;
717     char CharBuffer[] = new char[8192];
718     String JavaDoc sCharBuffer;
719     long lElapsed = 0;
720
721     final String JavaDoc sSep = System.getProperty("file.separator");
722
723     if (DebugFile.trace) {
724       lElapsed = System.currentTimeMillis();
725
726       DebugFile.writeln("Begin Pageset.buildPageForEdit(" + sBasePath + "," + sOutputPath + "," + sCtrlPath + "," + sMenuPath + ")");
727       DebugFile.incIdent();
728     }
729
730     FileSystem oFS = new FileSystem();
731
732     if (!sBasePath.endsWith(sSep)) sBasePath += sSep;
733
734     String JavaDoc sWebServer = oEnvironmentProps.getProperty("webserver", "");
735
736     if (DebugFile.trace && sWebServer.length()==0) DebugFile.writeln("WARNING: webserver property not set at EnvironmentProperties");
737
738     if (!sWebServer.endsWith("/")) sWebServer+="/";
739
740
741     // Posicionarse en el nodo de contenedores
742
Node JavaDoc oContainers = oMSite.seekChildByName(oMSite.getRootNode().getFirstChild(), "containers");
743
744     if (oContainers==null) {
745       if (DebugFile.trace)
746         DebugFile.writeln("ERROR: <containers> node not found.");
747
748       throw new DOMException JavaDoc(DOMException.NOT_FOUND_ERR, "<containers> node not found");
749     }
750
751     // Cagar el stream de datos XML una sola vez
752
if (DebugFile.trace)
753       DebugFile.writeln("new FileInputStream(" + (sURI.startsWith("file://") ? sURI.substring(7) : sURI) + ")");
754
755
756     // Para cada contenedor (página) realizar la transformación XSLT
757

758       oCurrentPage = this.page(sPageGUID);
759
760       oXMLStream = new FileInputStream JavaDoc(sURI.startsWith("file://") ? sURI.substring(7) : sURI);
761       oStreamSrcXML = new StreamSource JavaDoc(oXMLStream);
762
763       // Asignar cada stream de salida a su stream temporal
764
oStrWritter = new StringWriter JavaDoc();
765       oStreamResult = new StreamResult JavaDoc(oStrWritter);
766
767       // Transformacion XSLT
768
try {
769
770         // Obtener la hoja de estilo desde el cache
771
oTransformer = StylesheetCache.newTransformer(sBasePath + "xslt" + sSep + "templates" + sSep + oMSite.name() + sSep + oCurrentPage.template());
772
773         sMedia = oTransformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
774
775         if (DebugFile.trace) DebugFile.writeln(OutputKeys.MEDIA_TYPE + "=" + sMedia);
776
777         if (null==sMedia)
778           sMedia = "html";
779         else
780           sMedia = sMedia.substring(sMedia.indexOf('/')+1);
781
782         if (null==oCurrentPage.getTitle())
783           throw new NullPointerException JavaDoc("Page title is null");
784
785         if (DebugFile.trace)
786           DebugFile.writeln("Page.filePath(" + sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "." + sMedia + ")");
787
788         oCurrentPage.filePath(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "." + sMedia);
789
790         // Set environment parameters for stylesheet
791
StylesheetCache.setParameters (oTransformer, oEnvironmentProps);
792
793         // Set user defined parameters for stylesheet
794
StylesheetCache.setParameters (oTransformer, oUserProps);
795
796         // Paso el title de la pagina como parametro
797
oTransformer.setParameter ("param_page", oCurrentPage.getTitle());
798
799         // Realizar la transformación
800
oTransformer.transform (oStreamSrcXML, oStreamResult);
801
802       }
803       catch (TransformerConfigurationException JavaDoc e) {
804          oLastXcpt = e;
805          sMedia = null;
806
807          SourceLocator JavaDoc sl = e.getLocator();
808
809          if (DebugFile.trace) {
810            if (sl == null) {
811              DebugFile.writeln("ERROR TransformerConfigurationException " + e.getMessage());
812            }
813            else {
814              DebugFile.writeln("ERROR TransformerConfigurationException " + e.getMessage() + " line=" + String.valueOf(sl.getLineNumber()) + " column=" + String.valueOf(sl.getColumnNumber()));
815            }
816          }
817       }
818       catch (TransformerException JavaDoc e) {
819         oLastXcpt = e;
820         sMedia = null;
821
822         if (DebugFile.trace) DebugFile.writeln("ERROR TransformerException " + e.getMessageAndLocation());
823       }
824
825       oTransformer = null;
826       oStreamResult = null;
827
828       // Asignar un String con el fuente XML transformado
829
sTransformed = oStrWritter.toString();
830
831       if (DebugFile.trace) DebugFile.writeln("transformation length=" + String.valueOf(sTransformed.length()));
832
833       // Buscar el fin de tag </head>
834
if (sTransformed.length()>0) {
835         iCloseHead = sTransformed.indexOf("</head");
836         if (iCloseHead<0) iCloseHead = sTransformed.indexOf("</HEAD");
837
838         // Buscar el inicio de tag <body>
839
iOpenBody = sTransformed.indexOf("<body", iCloseHead);
840         if (iOpenBody<0) iOpenBody = sTransformed.indexOf("<BODY", iCloseHead);
841
842         iCloseBody = sTransformed.indexOf(">", iOpenBody+5);
843         for (char s = sTransformed.charAt(iCloseBody+1); s=='\r' || s=='\n' || s==' ' || s=='\t'; s = sTransformed.charAt(++iCloseBody)) ;
844
845         // Crear un buffer intermedio para mayor velocidad de concatenado
846
oPostTransform = new StringBuffer JavaDoc(sTransformed.length()+4096);
847
848         // Incrustar las llamadas al Integrador en el lugar apropiado del fuente
849
oPostTransform.append(sTransformed.substring(0, iCloseHead));
850         oPostTransform.append("\n<script language=\"JavaScript\" SRC=\"" + sMenuPath + "\"></script>");
851         oPostTransform.append("\n<script language=\"JavaScript\" SRC=\"" + sIntegradorPath + "\"></script>\n");
852         oPostTransform.append(sTransformed.substring(iCloseHead, iCloseHead+7));
853         oPostTransform.append(sTransformed.substring(iOpenBody, iCloseBody));
854
855         // Cargar el código fuente del control de visulización del Integrador
856
try {
857           sCharBuffer = oFS.readfilestr(sCtrlPath, "UTF-8");
858
859           if (DebugFile.trace) DebugFile.writeln(String.valueOf(sCharBuffer.length()) + " characters readed");
860         }
861         catch (com.enterprisedt.net.ftp.FTPException ftpe) {
862           throw new IOException JavaDoc (ftpe.getMessage());
863         }
864
865         try {
866           if (DebugFile.trace) DebugFile.writeln("Gadgets.replace(" + sCtrlPath + ",http://demo.hipergate.com/," + sWebServer + ")");
867
868           Gadgets.replace(sCharBuffer, "http://demo.hipergate.com/", sWebServer);
869
870         } catch (org.apache.oro.text.regex.MalformedPatternException e) { }
871
872         oPostTransform.append("<!--Begin " + sCtrlPath + "-->\n");
873
874         oPostTransform.append(sCharBuffer);
875         sCharBuffer = null;
876
877         oPostTransform.append("\n<!--End " + sCtrlPath + "-->\n");
878
879         oPostTransform.append(sTransformed.substring(iCloseBody));
880       }
881       else {
882         oPostTransform = new StringBuffer JavaDoc("Page " + oCurrentPage.getTitle() + " could not be rendered.");
883         if (oLastXcpt!=null) oPostTransform.append("<BR>" + oLastXcpt.getMessageAndLocation());
884       }
885
886       // Escribir el resultado con las llamadas incrustadas en el archivo de salida
887

888       if (sSelPageOptions.length()==0)
889         oFS.writefilestr(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "_." + sMedia, oPostTransform.toString(), "UTF-8");
890       else
891         try {
892
893           oFS.writefilestr(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "_." + sMedia, Gadgets.replace(oPostTransform.toString(), ":selPageOptions", sSelPageOptions), "UTF-8");
894
895         } catch (Exception JavaDoc e) {/* Ignore MalformedPatternException, is never thrown */ }
896
897       // Desreferenciar los buffers intermedios para liberar memoria lo antes posible
898
oPostTransform = null;
899       sTransformed = null;
900
901     oXMLStream.close();
902
903     if (DebugFile.trace) {
904       DebugFile.writeln("done in " + String.valueOf(System.currentTimeMillis()-lElapsed) + " miliseconds");
905
906       DebugFile.decIdent();
907       DebugFile.writeln("End Pageset.buildPageForEdit() : " + oCurrentPage.getTitle());
908     }
909
910     return oCurrentPage;
911   } // buildPageForEdit()
912

913   //-----------------------------------------------------------
914

915   /**
916    * <p>Generate XSL Transformation output with editing layers for PageSet.</p>
917    * @param sBasePath Path to directory containing XSL stylesheets
918    * @param sOutputPath Path to output directory where generated files shall be saved.
919    * @param sCtrlPath Path to source code of the edition layer (tipically /includes/integrador_ctrl.inc file)
920    * @param sMenuPath Path to dynamic page that generates the block list (tipically /webbuilder/wb_mnuintegrador.jsp)
921    * @param sIntegradorPath Path to JavaScript functions of edition layer (tipically integrador.js)
922    * @param sSelPageOptions If this is a single Page PageSet this parameter must be "",
923    * else it is a list of available pages in HTML <OPTION>...</OPTION> format.
924    * @param oEnvironmentProps Environment properties to be replaced at templated
925    * @param oUserProps User Properties to be replaced at templated
926    * @throws IOException
927    * @throws DOMException
928    * @throws TransformerException
929    * @throws TransformerConfigurationException
930    * @throws NullPointerException
931    */

932   public void buildSiteForEdit(String JavaDoc sBasePath, String JavaDoc sOutputPath,
933                                String JavaDoc sCtrlPath, String JavaDoc sMenuPath,
934                                String JavaDoc sIntegradorPath, String JavaDoc sSelPageOptions,
935                                Properties JavaDoc oEnvironmentProps, Properties JavaDoc oUserProps)
936
937     throws IOException JavaDoc, DOMException JavaDoc, TransformerException JavaDoc,
938            TransformerConfigurationException JavaDoc, MalformedURLException JavaDoc {
939
940     Transformer JavaDoc oTransformer;
941     StreamResult JavaDoc oStreamResult;
942     StreamSource JavaDoc oStreamSrcXML;
943     StringWriter JavaDoc oStrWritter;
944     InputStream JavaDoc oXMLStream = null;
945     String JavaDoc sTransformed;
946     StringBuffer JavaDoc oPostTransform;
947     String JavaDoc sKey;
948     String JavaDoc sMedia;
949     Object JavaDoc sVal;
950     Page oCurrentPage;
951
952     int iCloseHead, iOpenBody, iCloseBody;
953     int iReaded;
954     char CharBuffer[] = new char[8192];
955     String JavaDoc sCharBuffer;
956     long lElapsed = 0;
957
958     final String JavaDoc sSep = System.getProperty("file.separator");
959
960     if (DebugFile.trace) {
961       lElapsed = System.currentTimeMillis();
962
963       DebugFile.writeln("Begin Pageset.buildSiteForEdit(" + sBasePath + "," + sOutputPath + "," + sCtrlPath + "," + sMenuPath + ")");
964       DebugFile.incIdent();
965     }
966
967     FileSystem oFS = new FileSystem();
968
969     Vector JavaDoc vPages = pages();
970
971     if (!sBasePath.endsWith(sSep)) sBasePath += sSep;
972
973     String JavaDoc sWebServer = oEnvironmentProps.getProperty("webserver", "");
974
975     if (DebugFile.trace && sWebServer.length()==0) DebugFile.writeln("WARNING: webserver property not set at EnvironmentProperties");
976
977     if (!sWebServer.endsWith("/")) sWebServer+="/";
978
979
980     // Posicionarse en el nodo de contenedores
981
Node JavaDoc oContainers = oMSite.seekChildByName(oMSite.getRootNode().getFirstChild(), "containers");
982
983     if (oContainers==null) {
984       if (DebugFile.trace)
985         DebugFile.writeln("ERROR: <containers> node not found.");
986
987       throw new DOMException JavaDoc(DOMException.NOT_FOUND_ERR, "<containers> node not found");
988     }
989
990     // Cagar el stream de datos XML una sola vez
991
if (DebugFile.trace)
992       DebugFile.writeln("new FileInputStream(" + (sURI.startsWith("file://") ? sURI.substring(7) : sURI) + ")");
993
994
995     // Para cada contenedor (página) realizar la transformación XSLT
996
for (int c=0; c<vPages.size(); c++) {
997
998       oCurrentPage = (Page) vPages.get(c);
999
1000      oXMLStream = new FileInputStream JavaDoc(sURI.startsWith("file://") ? sURI.substring(7) : sURI);
1001      oStreamSrcXML = new StreamSource JavaDoc(oXMLStream);
1002
1003      // Asignar cada stream de salida a su stream temporal
1004
oStrWritter = new StringWriter JavaDoc();
1005      oStreamResult = new StreamResult JavaDoc(oStrWritter);
1006
1007      // Transformacion XSLT
1008
try {
1009
1010        // Obtener la hoja de estilo desde el cache
1011
oTransformer = StylesheetCache.newTransformer(sBasePath + "xslt" + sSep + "templates" + sSep + oMSite.name() + sSep + oCurrentPage.template());
1012
1013        sMedia = oTransformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
1014
1015        if (DebugFile.trace) DebugFile.writeln(OutputKeys.MEDIA_TYPE + "=" + sMedia);
1016
1017        if (null==sMedia)
1018          sMedia = "html";
1019        else
1020          sMedia = sMedia.substring(sMedia.indexOf('/')+1);
1021
1022        if (null==oCurrentPage.getTitle())
1023          throw new NullPointerException JavaDoc("Page " + String.valueOf(c) + " title is null");
1024
1025        if (DebugFile.trace)
1026          DebugFile.writeln("Page.filePath(" + sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "." + sMedia + ")");
1027
1028        oCurrentPage.filePath(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "." + sMedia);
1029
1030        // Set environment parameters for stylesheet
1031
StylesheetCache.setParameters (oTransformer, oEnvironmentProps);
1032
1033        // Set user defined parameters for stylesheet
1034
StylesheetCache.setParameters (oTransformer, oUserProps);
1035
1036        // Paso el title de la pagina como parametro
1037
oTransformer.setParameter ("param_page", ((Page)(vPages.get(c))).getTitle());
1038
1039        // Realizar la transformación
1040
oTransformer.transform (oStreamSrcXML, oStreamResult);
1041
1042      }
1043      catch (TransformerConfigurationException JavaDoc e) {
1044         oLastXcpt = e;
1045         sMedia = null;
1046
1047         SourceLocator JavaDoc sl = e.getLocator();
1048
1049         if (DebugFile.trace) {
1050           if (sl == null) {
1051             DebugFile.writeln("ERROR TransformerConfigurationException " + e.getMessage());
1052           }
1053           else {
1054             DebugFile.writeln("ERROR TransformerConfigurationException " + e.getMessage() + " line=" + String.valueOf(sl.getLineNumber()) + " column=" + String.valueOf(sl.getColumnNumber()));
1055           }
1056         }
1057      }
1058      catch (TransformerException JavaDoc e) {
1059        oLastXcpt = e;
1060        sMedia = null;
1061
1062        if (DebugFile.trace) DebugFile.writeln("ERROR TransformerException " + e.getMessageAndLocation());
1063      }
1064
1065      oTransformer = null;
1066      oStreamResult = null;
1067
1068      // Asignar un String con el fuente XML transformado
1069
sTransformed = oStrWritter.toString();
1070
1071      if (DebugFile.trace) DebugFile.writeln("transformation length=" + String.valueOf(sTransformed.length()));
1072
1073      // Buscar el fin de tag </head>
1074
if (sTransformed.length()>0) {
1075        iCloseHead = sTransformed.indexOf("</head");
1076        if (iCloseHead<0) iCloseHead = sTransformed.indexOf("</HEAD");
1077
1078        // Buscar el inicio de tag <body>
1079
iOpenBody = sTransformed.indexOf("<body", iCloseHead);
1080        if (iOpenBody<0) iOpenBody = sTransformed.indexOf("<BODY", iCloseHead);
1081
1082        iCloseBody = sTransformed.indexOf(">", iOpenBody+5);
1083        for (char s = sTransformed.charAt(iCloseBody+1); s=='\r' || s=='\n' || s==' ' || s=='\t'; s = sTransformed.charAt(++iCloseBody)) ;
1084
1085        // Crear un buffer intermedio para mayor velocidad de concatenado
1086
oPostTransform = new StringBuffer JavaDoc(sTransformed.length()+4096);
1087
1088        // Incrustar las llamadas al Integrador en el lugar apropiado del fuente
1089
oPostTransform.append(sTransformed.substring(0, iCloseHead));
1090        oPostTransform.append("\n<script language=\"JavaScript\" SRC=\"" + sMenuPath + "\"></script>");
1091        oPostTransform.append("\n<script language=\"JavaScript\" SRC=\"" + sIntegradorPath + "\"></script>\n");
1092        oPostTransform.append(sTransformed.substring(iCloseHead, iCloseHead+7));
1093        oPostTransform.append(sTransformed.substring(iOpenBody, iCloseBody));
1094
1095        // Cargar el código fuente del control de visulización del Integrador
1096
try {
1097          sCharBuffer = oFS.readfilestr(sCtrlPath, "UTF-8");
1098
1099          if (DebugFile.trace) DebugFile.writeln(String.valueOf(sCharBuffer.length()) + " characters readed");
1100        }
1101        catch (com.enterprisedt.net.ftp.FTPException ftpe) {
1102          throw new IOException JavaDoc (ftpe.getMessage());
1103        }
1104
1105        try {
1106          if (DebugFile.trace) DebugFile.writeln("Gadgets.replace(" + sCtrlPath + ",http://demo.hipergate.com/," + sWebServer + ")");
1107
1108          Gadgets.replace(sCharBuffer, "http://demo.hipergate.com/", sWebServer);
1109        } catch (org.apache.oro.text.regex.MalformedPatternException e) { }
1110
1111        oPostTransform.append("<!--Begin " + sCtrlPath + "-->\n");
1112
1113        oPostTransform.append(sCharBuffer);
1114        sCharBuffer = null;
1115
1116        oPostTransform.append("\n<!--End " + sCtrlPath + "-->\n");
1117
1118        oPostTransform.append(sTransformed.substring(iCloseBody));
1119      }
1120      else {
1121        oPostTransform = new StringBuffer JavaDoc("Page " + ((Page)vPages.get(c)).getTitle() + " could not be rendered.");
1122        if (oLastXcpt!=null) oPostTransform.append("<BR>" + oLastXcpt.getMessageAndLocation());
1123      }
1124
1125      // Escribir el resultado con las llamadas incrustadas en el archivo de salida
1126
if (DebugFile.trace) DebugFile.writeln("new FileWriter(" + sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "_." + sMedia + ")");
1127
1128
1129      if (sSelPageOptions.length()==0)
1130        oFS.writefilestr(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "_." + sMedia, oPostTransform.toString(), "UTF-8");
1131      else
1132        try {
1133          oFS.writefilestr(sOutputPath + oCurrentPage.getTitle().replace(' ','_') + "_." + sMedia, Gadgets.replace(oPostTransform.toString(), ":selPageOptions", sSelPageOptions), "UTF-8");
1134
1135        } catch (Exception JavaDoc e) {/* Ignore MalformedPatternException, is never thrown */ }
1136
1137      // Desreferenciar los buffers intermedios para liberar memoria lo antes posible
1138
oPostTransform = null;
1139      sTransformed = null;
1140    } // next (c)
1141

1142    oXMLStream.close();
1143
1144    if (DebugFile.trace) {
1145      DebugFile.writeln("done in " + String.valueOf(System.currentTimeMillis()-lElapsed) + " miliseconds");
1146
1147      DebugFile.decIdent();
1148      DebugFile.writeln("End Pageset.buildSiteForEdit()");
1149    }
1150  } // buildSiteForEdit()
1151

1152  //-----------------------------------------------------------
1153

1154  private Page findPage(String JavaDoc sPageGUID) {
1155    Vector JavaDoc oPages = this.pages();
1156    int iPages = oPages.size();
1157    Page oPage = null;
1158
1159    for (int p=0; p<iPages && oPage==null; p++)
1160      if (sPageGUID.equals(((Page)oPages.get(p)).guid()))
1161        oPage = (Page)oPages.get(p);
1162
1163    return oPage;
1164  } // findPage
1165

1166  //-----------------------------------------------------------
1167

1168  /**
1169   * <p>Add block at the end of a Page</p>
1170   * @param sFilePath Path to PageSet XML file
1171   * @param sPageGUID &lt;Page&gt; GUID attribute
1172   * @param sBlockXML XML of Block to be added
1173   * @return New Block Id
1174   * @throws IllegalAccessException
1175   * @throws IOException
1176   * @throws ClassNotFoundException
1177   * @throws NumberFormatException If Identifier attribute <block id="..."> is not an integer number.
1178   */

1179  public String JavaDoc addBlock(String JavaDoc sFilePath, String JavaDoc sPageGUID, String JavaDoc sBlockXML)
1180    throws IllegalAccessException JavaDoc, IOException JavaDoc, ClassNotFoundException JavaDoc,
1181           NumberFormatException JavaDoc, UTFDataFormatException JavaDoc, Exception JavaDoc {
1182
1183    String JavaDoc sBlockId;
1184    Page oPage = null;
1185    long lElapsed = 0;
1186
1187    if (DebugFile.trace) {
1188      lElapsed = System.currentTimeMillis();
1189
1190      DebugFile.writeln("Begin Pageset.addBlock(" + sFilePath + "," + sPageGUID + ",\n" + sBlockXML + "\n)");
1191      DebugFile.incIdent();
1192    }
1193
1194    sURI = sFilePath;
1195
1196    parseURI(sFilePath);
1197
1198    oPage = findPage(sPageGUID);
1199
1200    sBlockId = oPage.nextBlockId();
1201
1202    try {
1203      sBlockXML = com.knowgate.misc.Gadgets.replace(sBlockXML, "<block>", "<block id=\"" + sBlockId + "\">");
1204    }
1205    catch (MalformedPatternException mpe) { }
1206
1207    new XMLDocument(sFilePath).addNodeAndSave("pageset/pages/page[@guid='" + oPage.guid() + "']/blocks/block/", sBlockXML);
1208
1209    if (DebugFile.trace) {
1210      DebugFile.writeln("done in " + String.valueOf(System.currentTimeMillis()-lElapsed) + " miliseconds");
1211
1212      DebugFile.decIdent();
1213      DebugFile.writeln("End Pageset.addBlock()");
1214    }
1215
1216  return sBlockId;
1217  } // addBlock
1218

1219  //-----------------------------------------------------------
1220

1221  public void save(String JavaDoc sFilePath) throws IOException JavaDoc {
1222    FileOutputStream JavaDoc oOutFile = new FileOutputStream JavaDoc(sFilePath, false);
1223
1224    print(oOutFile);
1225
1226    oOutFile.close();
1227  } // save
1228

1229  // **********************************************************
1230
// * Static Methods
1231

1232  //-----------------------------------------------------------
1233

1234  /**
1235   * <p>Merge Company addresses, catalog and other information into a PageSet XML file<p>
1236   * Addresses are readed from k_addresses table and appended to the XML file after the &lt;pages&gt; node.
1237   * @param oConn JDBC database connection
1238   * @param sFilePath Complete path to the PageSet XML data file
1239   * @param sCompanyGUID GUID of Company which addresses are to be merged into the PageSet XML file
1240   * @throws SQLException
1241   * @throws IOException
1242   */

1243  public static void mergeCompanyInfo (JDCConnection oConn, String JavaDoc sFilePath, String JavaDoc sCompanyGUID)
1244    throws SQLException JavaDoc, IOException JavaDoc {
1245
1246    Statement JavaDoc oStmt;
1247    ResultSet JavaDoc oRSet;
1248
1249    if (DebugFile.trace) {
1250      DebugFile.writeln("PageSet.mergeCompanyAddresses(JDCConnection," + sFilePath + "," + sCompanyGUID + ")");
1251      DebugFile.incIdent();
1252    }
1253
1254    XMLDocument oXMLDoc = new XMLDocument(sFilePath);
1255
1256    String JavaDoc sCategoryGUID = "";
1257
1258    if (DebugFile.trace) {
1259      DebugFile.writeln("Connection.executeQuery(SELECT " + DB.gu_category + " FROM " + DB.k_x_company_prods + " WHERE " + DB.gu_company + "='" + sCompanyGUID + "')");
1260    }
1261
1262    oStmt = oConn.createStatement();
1263    oRSet = oStmt.executeQuery("SELECT " + DB.gu_category + " FROM " + DB.k_x_company_prods + " WHERE " + DB.gu_company + "='" + sCompanyGUID + "'");
1264    if (oRSet.next()) {
1265      sCategoryGUID = oRSet.getString(1);
1266    }
1267    oRSet.close();
1268    oStmt.close();
1269
1270    oStmt = oConn.createStatement();
1271    oRSet = oStmt.executeQuery("SELECT * FROM " + DB.k_addresses + " WHERE 1=0");
1272    ResultSetMetaData JavaDoc oMDat = oRSet.getMetaData();
1273    StringBuffer JavaDoc oColumnList = new StringBuffer JavaDoc(512);
1274    int iColumnCount = oMDat.getColumnCount();
1275
1276    for (int c=1; c<=iColumnCount; c++) {
1277      if (c>1) oColumnList.append(',');
1278      oColumnList.append("a." + oMDat.getColumnName(c).toLowerCase());
1279    } // next (c)
1280

1281    oRSet.close();
1282    oStmt.close();
1283
1284    DBSubset oAddrs = new DBSubset(DB.k_addresses + " a," + DB.k_x_company_addr + " x",
1285                                   oColumnList.toString(), "a." + DB.gu_address + "=x." + DB.gu_address + " AND x." + DB.gu_company + "=? ORDER BY a." + DB.ix_address, 10);
1286
1287    oAddrs.load(oConn, new Object JavaDoc[]{sCompanyGUID});
1288
1289    String JavaDoc sAddresses = "\n <company>" + sCompanyGUID + "</company>\n <catalog>" + sCategoryGUID + "</catalog>\n <addresses>\n" + oAddrs.toXML(" ", "address") + "\n </addresses>";
1290
1291    try { oXMLDoc.removeNode("pageset/company"); }
1292    catch (DOMException JavaDoc dome) {
1293      if (dome.code!=DOMException.NOT_FOUND_ERR) throw new DOMException JavaDoc(dome.code, dome.getMessage());
1294    }
1295    try { oXMLDoc.removeNode("pageset/catalog"); }
1296    catch (DOMException JavaDoc dome) {
1297      if (dome.code!=DOMException.NOT_FOUND_ERR) throw new DOMException JavaDoc(dome.code, dome.getMessage());
1298    }
1299    try { oXMLDoc.removeNode("pageset/addresses"); }
1300    catch (DOMException JavaDoc dome) {
1301      if (dome.code!=DOMException.NOT_FOUND_ERR) throw new DOMException JavaDoc(dome.code, dome.getMessage());
1302    }
1303
1304    oXMLDoc.addNodeAndSave("pageset/pages", sAddresses);
1305
1306    if (DebugFile.trace) {
1307      DebugFile.decIdent();
1308      DebugFile.writeln("PageSet.mergeCompanyAddresses()");
1309    }
1310  } // mergeCompanyAddresses
1311

1312    //-----------------------------------------------------------
1313

1314  /**
1315   * <p>Remove Page from PageSet</p>
1316   * Page is searched by an internal XPath expression:<br>
1317   * pageset/pages/page[@guid='<i>sPageGUID</i>']
1318   * @param sFilePath Path to PageSet XML file
1319   * @param sPageGUID &lt;Page&gt; GUID attribute
1320   * @throws IOException
1321   */

1322  public static void removePage(String JavaDoc sFilePath, String JavaDoc sPageGUID) throws IOException JavaDoc {
1323    XMLDocument oXThis = new XMLDocument(sFilePath);
1324
1325    oXThis.removeNodeAndSave("pageset/pages/page[@guid='" + sPageGUID + "']");
1326  } // removePage
1327

1328  //-----------------------------------------------------------
1329

1330  /**
1331   * <p>Remove a Page searching it by title</p>
1332   * Page is searched by an internal XPath expression:<br>
1333   * pageset/pages/page[guid = '<i>sPageTitle</i>']
1334   * @param sFilePath Path to PageSet XML file
1335   * @param sPageGUIDAttr Page GUID
1336   * @throws IOException
1337   */

1338  public static void removePageByTitle(String JavaDoc sFilePath, String JavaDoc sPageGUIDAttr) throws IOException JavaDoc {
1339    XMLDocument oXThis = new XMLDocument(sFilePath);
1340
1341    oXThis.removeNodeAndSave("pageset/pages/page[guid = '" + sPageGUIDAttr + "']");
1342  } // removePageByTitle
1343

1344  //-----------------------------------------------------------
1345

1346  /**
1347   * <p>Remove Block</p>
1348   * Block is searched by an internal XPath expression:<br>
1349   * pageset/pages/page[@guid='<i>sPageGUID</i>']/blocks/block[@id='<i>sBlockId</i>']
1350   * @param sFilePath Path to PageSet XML file
1351   * @param sPageGUID &lt;Page&gt; GUID attribute
1352   * @param sBlockId id attribute of Block to be removed
1353   * @throws IOException
1354   */

1355  public static void removeBlock(String JavaDoc sFilePath, String JavaDoc sPageGUID, String JavaDoc sBlockId) throws IOException JavaDoc {
1356    XMLDocument oXThis = new XMLDocument(sFilePath);
1357
1358    oXThis.removeNodeAndSave("pageset/pages/page[@guid='" + sPageGUID + "']/blocks/block[@id='" + sBlockId + "']");
1359  } // removeBlock
1360

1361  //-----------------------------------------------------------
1362

1363  /**
1364   * <p>Get base Microsite GUID from a PageSet XML file.<p>
1365   * GUID is obtained directly from raw text reading without parsing the input file.
1366   * @param sPageSetURI Path to PageSet XML file
1367   * @return Microsite GUID
1368   * @throws FileNotFoundException
1369   * @throws IOException
1370   */

1371  public static String JavaDoc getMicrositeGUID(String JavaDoc sPageSetURI)
1372    throws FileNotFoundException JavaDoc, IOException JavaDoc {
1373
1374    if (DebugFile.trace) {
1375      DebugFile.writeln("PageSet.getMicrositeGUID(" + sPageSetURI + ")");
1376      DebugFile.incIdent();
1377    }
1378
1379    String JavaDoc sXML;
1380    int iMSiteOpenTag, iMSiteCloseTag;
1381    byte byXML[] = new byte[1024];
1382    FileInputStream JavaDoc oXMLStream = new FileInputStream JavaDoc(sPageSetURI);
1383    int iReaded = oXMLStream.read(byXML, 0, 1024);
1384    oXMLStream.close();
1385
1386    sXML = new String JavaDoc(byXML, 0, iReaded);
1387    iMSiteOpenTag = sXML.indexOf("<microsite>")+11;
1388    iMSiteCloseTag = sXML.indexOf("</microsite>", iMSiteOpenTag);
1389
1390    if (DebugFile.trace) {
1391      DebugFile.decIdent();
1392      DebugFile.writeln("PageSet.getMicrositeGUID() : " + sXML.substring(iMSiteOpenTag, iMSiteCloseTag));
1393    }
1394
1395    return sXML.substring(iMSiteOpenTag, iMSiteCloseTag);
1396  } // getMicrositeGUID();
1397

1398  // ----------------------------------------------------------
1399

1400  private static void printUsage() {
1401
1402    System.out.println("");
1403    System.out.println("Usage:");
1404    System.out.println("com.knowgate.dataxslt.PageSet parse file_path");
1405  }
1406
1407  // ---------------------------------------------------------
1408

1409  public static void main(String JavaDoc[] argv)
1410    throws IllegalAccessException JavaDoc, ClassNotFoundException JavaDoc, Exception JavaDoc {
1411    if (argv.length!=2)
1412      printUsage();
1413    else if (!argv[0].equalsIgnoreCase("parse"))
1414      printUsage();
1415    else {
1416      PageSet oMSite = new PageSet(argv[1], true);
1417    }
1418  } // main
1419

1420  // **********************************************************
1421
// * Variables estáticas
1422

1423  public static final short ClassId = 71;
1424
1425} // PageSet
1426
Popular Tags