0001: /*
0002: Copyright (C) 2003 Know Gate S.L. All rights reserved.
0003: C/Oña, 107 1º2 28050 Madrid (Spain)
0004:
0005: Redistribution and use in source and binary forms, with or without
0006: modification, are permitted provided that the following conditions
0007: are met:
0008:
0009: 1. Redistributions of source code must retain the above copyright
0010: notice, this list of conditions and the following disclaimer.
0011:
0012: 2. The end-user documentation included with the redistribution,
0013: if any, must include the following acknowledgment:
0014: "This product includes software parts from hipergate
0015: (http://www.hipergate.org/)."
0016: Alternately, this acknowledgment may appear in the software itself,
0017: if and wherever such third-party acknowledgments normally appear.
0018:
0019: 3. The name hipergate must not be used to endorse or promote products
0020: derived from this software without prior written permission.
0021: Products derived from this software may not be called hipergate,
0022: nor may hipergate appear in their name, without prior written
0023: permission.
0024:
0025: This library is distributed in the hope that it will be useful,
0026: but WITHOUT ANY WARRANTY; without even the implied warranty of
0027: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
0028:
0029: You should have received a copy of hipergate License with this code;
0030: if not, visit http://www.hipergate.org or mail to info@hipergate.org
0031: */
0032:
0033: package com.knowgate.dataxslt;
0034:
0035: import java.lang.ClassNotFoundException;
0036: import java.lang.IllegalAccessException;
0037: import java.lang.StringBuffer;
0038:
0039: import java.util.LinkedList;
0040: import java.util.Vector;
0041: import java.util.Properties;
0042: import java.util.HashMap;
0043:
0044: import java.sql.Statement;
0045: import java.sql.ResultSet;
0046: import java.sql.ResultSetMetaData;
0047: import java.sql.SQLException;
0048:
0049: import java.io.IOException;
0050: import java.io.FileNotFoundException;
0051: import java.io.UnsupportedEncodingException;
0052: import java.io.InputStream;
0053: import java.io.File;
0054: import java.io.FileReader;
0055: import java.io.FileWriter;
0056: import java.io.FileInputStream;
0057: import java.io.FileOutputStream;
0058: import java.io.ByteArrayOutputStream;
0059: import java.io.StringWriter;
0060: import java.io.UTFDataFormatException;
0061:
0062: import java.net.URL;
0063: import java.net.MalformedURLException;
0064:
0065: import javax.activation.DataHandler;
0066:
0067: import javax.xml.transform.Transformer;
0068: import javax.xml.transform.stream.StreamResult;
0069: import javax.xml.transform.stream.StreamSource;
0070: import javax.xml.transform.TransformerException;
0071: import javax.xml.transform.TransformerConfigurationException;
0072: import javax.xml.transform.SourceLocator;
0073: import javax.xml.transform.OutputKeys;
0074:
0075: import org.w3c.dom.Element;
0076: import org.w3c.dom.Node;
0077: import org.w3c.dom.NodeList;
0078: import org.w3c.dom.DOMException;
0079:
0080: import dom.DOMDocument;
0081:
0082: import org.apache.oro.text.regex.*;
0083:
0084: import com.knowgate.jdc.JDCConnection;
0085:
0086: import com.knowgate.dfs.FileSystem;
0087:
0088: import com.knowgate.debug.DebugFile;
0089:
0090: import com.knowgate.misc.Gadgets;
0091:
0092: import com.knowgate.dataobjs.DB;
0093: import com.knowgate.dataobjs.DBTable;
0094: import com.knowgate.dataobjs.DBSubset;
0095: import com.knowgate.dataobjs.DBPersist;
0096:
0097: /**
0098: * PageSet DOMDocument
0099: * @author Sergio Montoro Ten
0100: * @version 2.1
0101: */
0102: public class PageSet extends DOMDocument {
0103:
0104: //-----------------------------------------------------------
0105:
0106: private Microsite oMSite; // Microsite metadata definition
0107: private String sURI; // Path to XML data file.
0108: private TransformerException oLastXcpt; // Last TransformerException raised by
0109:
0110: // buildSite() or buildSiteForEdit()
0111:
0112: //***************************************************************
0113: // Constructors
0114:
0115: private void initMicrosite(String sMsiteURI, boolean bValidateXML)
0116: throws ClassNotFoundException, Exception,
0117: IllegalAccessException, FileNotFoundException {
0118:
0119: if (DebugFile.trace)
0120: DebugFile.writeln("PageSet.initMicrosite(" + sMsiteURI
0121: + ",schema-validation="
0122: + String.valueOf(bValidateXML) + ")");
0123:
0124: // Load Microsite
0125:
0126: if (sMsiteURI.startsWith("/") || sMsiteURI.startsWith("\\")) {
0127:
0128: File oMFile = new File(sMsiteURI);
0129:
0130: if (!oMFile.exists())
0131: throw new FileNotFoundException(sMsiteURI
0132: + " not found");
0133:
0134: oMFile = null;
0135:
0136: oMSite = MicrositeFactory.getInstance(
0137: "file://" + sMsiteURI, bValidateXML);
0138: } else
0139: oMSite = MicrositeFactory.getInstance(sMsiteURI,
0140: bValidateXML);
0141: }
0142:
0143: /**
0144: * Create empty PageSet from a Microsite.
0145: * XML validation is disabled.
0146: * @param sMsiteURI Microsite XML file URI
0147: * @throws ClassNotFoundException
0148: * @throws IllegalAccessException
0149: * @throws FileNotFoundException
0150: */
0151: public PageSet(String sMsiteURI) throws ClassNotFoundException,
0152: IllegalAccessException, FileNotFoundException, Exception {
0153:
0154: initMicrosite(sMsiteURI, this .getValidation());
0155:
0156: sURI = null;
0157: } // PageSet()
0158:
0159: /**
0160: * Create empty PageSet from a Microsite
0161: * @param sMsiteURI Microsite XML file URI
0162: * (for example file:///opt/knowgate/storage/xslt/templates/Comtemporary.xml)
0163: * @param bValidateXML <b>true</b> if XML validation with W3C schemas is to be done,
0164: * <b>false</b> is no validation is to be done.
0165: * @throws ClassNotFoundException
0166: * @throws IllegalAccessException
0167: * @throws FileNotFoundException
0168: */
0169: public PageSet(String sMsiteURI, boolean bValidateXML)
0170: throws ClassNotFoundException, Exception,
0171: IllegalAccessException, FileNotFoundException {
0172: super ("UTF-8", bValidateXML, false);
0173:
0174: if (DebugFile.trace)
0175: DebugFile.writeln("new PageSet(" + sMsiteURI
0176: + ",schema-validation="
0177: + String.valueOf(bValidateXML) + ")");
0178:
0179: initMicrosite(sMsiteURI, bValidateXML);
0180: sURI = null;
0181: } // PageSet()
0182:
0183: /**
0184: * Create PageSet from a Microsite and load data from an XML file.
0185: * @param sMsiteURI Microsite XML file URI
0186: * @param sPageSetURI PageSet XML file URI
0187: * (for example file:///opt/knowgate/storage/domains/1026/workareas/f7f055ca39854673b17518ec5f87de3b/apps/Mailwire/data/Newsletter01.xml)
0188: * @throws ClassNotFoundException
0189: * @throws IllegalAccessException
0190: */
0191: public PageSet(String sMsiteURI, String sPageSetURI)
0192: throws ClassNotFoundException, Exception,
0193: IllegalAccessException, FileNotFoundException {
0194:
0195: if (DebugFile.trace)
0196: DebugFile.writeln("new PageSet(" + sMsiteURI + ","
0197: + sPageSetURI + ")");
0198:
0199: File oPFile;
0200:
0201: if (sMsiteURI.startsWith("file://"))
0202: initMicrosite(sMsiteURI, this .getValidation());
0203: else
0204: initMicrosite("file://" + sMsiteURI, this .getValidation());
0205:
0206: sURI = sPageSetURI;
0207:
0208: if (sPageSetURI.startsWith("file://")) {
0209: oPFile = new File(sPageSetURI.substring(7));
0210:
0211: if (!oPFile.exists())
0212: throw new FileNotFoundException(sPageSetURI
0213: .substring(7)
0214: + " not found");
0215:
0216: if (DebugFile.trace)
0217: DebugFile.writeln("parseURI (" + sPageSetURI + ");");
0218:
0219: parseURI(sPageSetURI);
0220: } else {
0221: oPFile = new File(sPageSetURI);
0222:
0223: if (!oPFile.exists())
0224: throw new FileNotFoundException(sPageSetURI
0225: + " not found");
0226:
0227: if (DebugFile.trace)
0228: DebugFile.writeln("parseURI (file://" + sPageSetURI
0229: + ");");
0230:
0231: parseURI("file://" + sPageSetURI);
0232: }
0233: // fi (sPageSetURI.startsWith("file://"))
0234:
0235: oPFile = null;
0236:
0237: } // PageSet()
0238:
0239: /**
0240: * Create PageSet from a Microsite and load data from an XML file.
0241: * @param sMsiteURI Microsite XML file URI
0242: * @param sPageSetURI PageSet XML file URI
0243: * @param bValidateXML <b>true</b> if XML validation with W3C schemas is to be done,
0244: * <b>false</b> is no validation is to be done.
0245: * @throws ClassNotFoundException
0246: * @throws IllegalAccessException
0247: */
0248:
0249: public PageSet(String sMsiteURI, String sPageSetURI,
0250: boolean bValidateXML) throws ClassNotFoundException,
0251: Exception, IllegalAccessException, FileNotFoundException {
0252:
0253: super ("UTF-8", bValidateXML, false);
0254:
0255: if (DebugFile.trace)
0256: DebugFile.writeln("new PageSet(" + sMsiteURI + ","
0257: + sPageSetURI + ",schema-validation="
0258: + String.valueOf(bValidateXML) + ")");
0259:
0260: File oPFile;
0261:
0262: if (sMsiteURI.startsWith("file://"))
0263: initMicrosite(sMsiteURI, bValidateXML);
0264: else
0265: initMicrosite("file://" + sMsiteURI, bValidateXML);
0266:
0267: sURI = sPageSetURI;
0268:
0269: if (sPageSetURI.startsWith("file://")) {
0270: oPFile = new File(sPageSetURI.substring(7));
0271:
0272: if (!oPFile.exists())
0273: throw new FileNotFoundException(sPageSetURI
0274: .substring(7)
0275: + " not found");
0276:
0277: parseURI(sPageSetURI);
0278: } else {
0279: oPFile = new File(sPageSetURI);
0280:
0281: if (!oPFile.exists())
0282: throw new FileNotFoundException(sPageSetURI
0283: + " not found");
0284:
0285: parseURI("file://" + sPageSetURI);
0286: }
0287: } // PageSet()
0288:
0289: //-----------------------------------------------------------
0290:
0291: /**
0292: * Get PageSet <guid> value
0293: */
0294: public String guid() {
0295: Node oPageSetNode = getRootNode().getFirstChild();
0296:
0297: if (oPageSetNode.getNodeName().equals("xml-stylesheet"))
0298: oPageSetNode = oPageSetNode.getNextSibling();
0299:
0300: // Devuelve el valor del atributo guid del nodo <pageset>
0301: return getAttribute(oPageSetNode, "guid");
0302: } // guid()
0303:
0304: //-----------------------------------------------------------
0305:
0306: /**
0307: * Last TransformerException raised by buildSite() or buildSiteForEdit()
0308: */
0309: public TransformerException lastException() {
0310: return oLastXcpt;
0311: }
0312:
0313: //-----------------------------------------------------------
0314:
0315: public Microsite microsite() {
0316: return oMSite;
0317: }
0318:
0319: //-----------------------------------------------------------
0320:
0321: /**
0322: * GUID of Catalog associated to this PageSet
0323: * @return Catalog GUID or <b>null</b> if <catalog> node does not exist.
0324: * @throws DOMException
0325: */
0326:
0327: public String catalog() throws DOMException {
0328:
0329: Node oCatalogNode;
0330: String sRetVal;
0331:
0332: if (DebugFile.trace)
0333: DebugFile.writeln("Begin PageSet.catalog()");
0334:
0335: if (DebugFile.trace)
0336: DebugFile.incIdent();
0337:
0338: // Get a reference to top Node
0339: Node oPageSetNode = getRootNode().getFirstChild();
0340: if (oPageSetNode.getNodeName().equals("xml-stylesheet"))
0341: oPageSetNode = oPageSetNode.getNextSibling();
0342:
0343: // Find <pages> node
0344: oCatalogNode = seekChildByName(oPageSetNode, "catalog");
0345:
0346: if (oCatalogNode == null)
0347: sRetVal = null;
0348: else
0349: sRetVal = oCatalogNode.getFirstChild().getNodeValue();
0350:
0351: if (DebugFile.trace) {
0352: DebugFile.decIdent();
0353: DebugFile.writeln("End PageSet.catalog() : " + sRetVal);
0354: }
0355:
0356: return sRetVal;
0357: } // company()
0358:
0359: //-----------------------------------------------------------
0360:
0361: /**
0362: * GUID of Company associated to this PageSet
0363: * @return Company GUID or <b>null</b> if <company> node does not exist.
0364: * @throws DOMException
0365: */
0366:
0367: public String company() throws DOMException {
0368:
0369: Node oCompanyNode;
0370: String sRetVal;
0371:
0372: if (DebugFile.trace)
0373: DebugFile.writeln("Begin PageSet.company()");
0374:
0375: if (DebugFile.trace)
0376: DebugFile.incIdent();
0377:
0378: // Get a reference to top Node
0379: Node oPageSetNode = getRootNode().getFirstChild();
0380: if (oPageSetNode.getNodeName().equals("xml-stylesheet"))
0381: oPageSetNode = oPageSetNode.getNextSibling();
0382:
0383: // Find <pages> node
0384: oCompanyNode = seekChildByName(oPageSetNode, "company");
0385:
0386: if (oCompanyNode == null)
0387: sRetVal = null;
0388: else
0389: sRetVal = oCompanyNode.getFirstChild().getNodeValue();
0390:
0391: if (DebugFile.trace) {
0392: DebugFile.decIdent();
0393: DebugFile.writeln("End PageSet.company() : " + sRetVal);
0394: }
0395:
0396: return sRetVal;
0397: } // catalog()
0398:
0399: // ---------------------------------------------------------------------------
0400:
0401: /**
0402: * Get a Page from this PageSet
0403: * @param sPageId GUID of page to be retrieved
0404: * @return Page object or <b>null</b> if no page with such GUID was found at XML file
0405: * @throws DOMException If <pages> node is not found
0406: * @throws NullPointerException If sPageId is <b>null</b>
0407: */
0408:
0409: public Page page(String sPageId) throws DOMException,
0410: NullPointerException {
0411:
0412: Node oPagesNode;
0413: Element oContainers;
0414: NodeList oNodeList;
0415: Page oCurrent;
0416: Page oRetVal = null;
0417:
0418: if (DebugFile.trace)
0419: DebugFile.writeln("Begin PageSet.page(" + sPageId + ")");
0420:
0421: if (null == sPageId)
0422: throw new NullPointerException(
0423: "PageSet.page(), parameter sPageId may not be null");
0424:
0425: if (DebugFile.trace)
0426: DebugFile.incIdent();
0427:
0428: // Get a reference to top Node
0429: Node oPageSetNode = getRootNode().getFirstChild();
0430: if (oPageSetNode.getNodeName().equals("xml-stylesheet"))
0431: oPageSetNode = oPageSetNode.getNextSibling();
0432:
0433: // Find <pages> node
0434: oPagesNode = seekChildByName(oPageSetNode, "pages");
0435:
0436: if (oPagesNode == null)
0437: throw new DOMException(DOMException.NOT_FOUND_ERR,
0438: "<pages> node not found");
0439:
0440: oNodeList = ((Element) oPagesNode).getElementsByTagName("page");
0441:
0442: if (oNodeList.getLength() > 0) {
0443:
0444: // Cast DOM nodes to Page objects inside Vector
0445: for (int i = 0; i < oNodeList.getLength()
0446: && (null == oRetVal); i++) {
0447: oCurrent = new Page(oNodeList.item(i), this );
0448: if (sPageId.equals(oCurrent.guid()))
0449: oRetVal = oCurrent;
0450: } // next
0451: } // fi (oNodeList.getLength()>0)
0452:
0453: if (DebugFile.trace) {
0454: DebugFile.decIdent();
0455: DebugFile.writeln("End PageSet.page() : " + oRetVal);
0456: }
0457:
0458: return oRetVal;
0459: } // page()
0460:
0461: //-----------------------------------------------------------
0462:
0463: /**
0464: * Get pages for this PageSet
0465: * @return vector of Page objects
0466: * @throws DOMException If <pages> node is not found
0467: */
0468: public Vector pages() throws DOMException {
0469: Node oPagesNode;
0470: Element oContainers;
0471: NodeList oNodeList;
0472: Vector oLinkVctr;
0473:
0474: if (DebugFile.trace) {
0475: DebugFile.writeln("Begin PageSet.pages()");
0476: DebugFile.incIdent();
0477: }
0478:
0479: // get a reference to top Node
0480: Node oPageSetNode = getRootNode().getFirstChild();
0481: if (oPageSetNode.getNodeName().equals("xml-stylesheet"))
0482: oPageSetNode = oPageSetNode.getNextSibling();
0483:
0484: // Buscar el nodo <pages>
0485: oPagesNode = seekChildByName(oPageSetNode, "pages");
0486:
0487: if (oPagesNode == null)
0488: throw new DOMException(DOMException.NOT_FOUND_ERR,
0489: "<pages> node not found");
0490:
0491: oNodeList = ((Element) oPagesNode).getElementsByTagName("page");
0492:
0493: if (oNodeList.getLength() > 0) {
0494: // Create Vector
0495: oLinkVctr = new Vector(oNodeList.getLength());
0496:
0497: // Cast DOM nodes to Page objects inside Vector
0498: for (int i = 0; i < oNodeList.getLength(); i++)
0499: oLinkVctr.add(new Page(oNodeList.item(i), this ));
0500: } else
0501: oLinkVctr = new Vector();
0502:
0503: if (DebugFile.trace) {
0504: DebugFile.decIdent();
0505: DebugFile.writeln("End PageSet.pages()");
0506: }
0507:
0508: return oLinkVctr;
0509: } // pages()
0510:
0511: //-----------------------------------------------------------
0512:
0513: /**
0514: * Get Addresses for this PageSet
0515: * @return vector of Page objects
0516: * @throws DOMException If <addresses> node is not found
0517: */
0518: public Vector addresses() throws DOMException {
0519: Node oPagesNode;
0520: Element oContainers;
0521: NodeList oNodeList;
0522: Vector oLinkVctr;
0523:
0524: if (DebugFile.trace) {
0525: DebugFile.writeln("Begin PageSet.pages()");
0526: DebugFile.incIdent();
0527: }
0528:
0529: // get a reference to top Node
0530: Node oPageSetNode = getRootNode().getFirstChild();
0531: if (oPageSetNode.getNodeName().equals("xml-stylesheet"))
0532: oPageSetNode = oPageSetNode.getNextSibling();
0533:
0534: // Buscar el nodo <pages>
0535: oPagesNode = seekChildByName(oPageSetNode, "addresses");
0536:
0537: if (oPagesNode == null)
0538: throw new DOMException(DOMException.NOT_FOUND_ERR,
0539: "<addresses> node not found");
0540:
0541: oNodeList = ((Element) oPagesNode)
0542: .getElementsByTagName("address");
0543:
0544: if (oNodeList.getLength() > 0) {
0545: // Create Vector
0546: oLinkVctr = new Vector(oNodeList.getLength());
0547:
0548: // Cast DOM nodes to Page objects inside Vector
0549: for (int i = 0; i < oNodeList.getLength(); i++)
0550: oLinkVctr.add(new Page(oNodeList.item(i), this ));
0551: } else
0552: oLinkVctr = new Vector();
0553:
0554: if (DebugFile.trace) {
0555: DebugFile.decIdent();
0556: DebugFile.writeln("End PageSet.addresses()");
0557: }
0558:
0559: return oLinkVctr;
0560: } // addresses()
0561:
0562: //-----------------------------------------------------------
0563:
0564: private LinkedList matchChildsByTag(Node oParent, String sPattern) {
0565: // Get a list of pointers to nodes with child <tag>
0566: // matches a regular expression pattern.
0567: // Parameters:
0568: // oParent -> Parent Node
0569: // sPattern -> Pattern to match
0570:
0571: Node oCurrentNode = null; // Iterador de nodos hijo
0572: Node oTag = null; // Nodo nieto <tag>
0573: NodeList oChilds = oParent.getChildNodes(); // Lista total de nodos hijo
0574: int iMaxNodes = oChilds.getLength(); // Cuenta de nodos hijo
0575: LinkedList oList = new LinkedList(); // Lista resultado
0576:
0577: Pattern oPattern = null;
0578: PatternMatcher oMatcher = new Perl5Matcher();
0579: PatternCompiler oCompiler = new Perl5Compiler();
0580:
0581: try {
0582: // Compile regular expression at Pattern Matcher
0583: oPattern = oCompiler.compile(sPattern);
0584: } catch (MalformedPatternException e) {
0585: }
0586:
0587: // Iterate throught child nodes
0588: for (int iNode = 0; iNode < iMaxNodes; iNode++) {
0589: // Assign oCurrentNode as an alias for the current node.
0590: oCurrentNode = oChilds.item(iNode);
0591: if (Node.ELEMENT_NODE == oCurrentNode.getNodeType()) {
0592:
0593: // Seek grandchild by name
0594: oTag = seekChildByName(oCurrentNode, "tag");
0595: if (null != oTag)
0596: // If pattern matches add child to list
0597: if (oMatcher.matches(getTextValue((Element) oTag),
0598: oPattern))
0599: oList.addLast(oCurrentNode);
0600: } // fi(ELEMENT_NODE)
0601: } // next(iNode)
0602:
0603: return oList;
0604: } // matchChildsByTag
0605:
0606: //-----------------------------------------------------------
0607:
0608: /**
0609: * <p>Generate XSL Transformation output for PageSet.</p>
0610: * @param sBasePath Path to directory containing XSL stylesheets
0611: * @param sOutputPath Path to output directory where generated files shall be saved.
0612: * @param oEnvironmentProps Environment Properties
0613: * @param oUserProps User Properties
0614: * @return
0615: * @throws IOException
0616: * @throws TransformerException
0617: * @throws TransformerConfigurationException
0618: */
0619: public Vector buildSite(String sBasePath, String sOutputPath,
0620: Properties oEnvironmentProps, Properties oUserProps)
0621: throws IOException, DOMException, TransformerException,
0622: TransformerConfigurationException {
0623:
0624: Transformer oTransformer;
0625: StreamResult oStreamResult;
0626: StreamSource oStreamSrcXML;
0627: InputStream oXMLStream = null;
0628: String sMedia;
0629: Page oCurrentPage;
0630: long lElapsed = 0;
0631:
0632: final String sSep = System.getProperty("file.separator");
0633:
0634: if (DebugFile.trace) {
0635: lElapsed = System.currentTimeMillis();
0636:
0637: DebugFile.writeln("Begin PageSet.BuildSite(" + sBasePath
0638: + "," + sOutputPath + "...)");
0639: DebugFile.incIdent();
0640: }
0641:
0642: oLastXcpt = null;
0643:
0644: if (!sBasePath.endsWith(sSep))
0645: sBasePath += sSep;
0646:
0647: Vector vPages = pages();
0648:
0649: // Move to containers node
0650: if (DebugFile.trace)
0651: DebugFile
0652: .writeln("seekChildByName(,[Node], \"containers\")");
0653:
0654: Node oContainers = oMSite.seekChildByName(oMSite.getRootNode()
0655: .getFirstChild(), "containers");
0656:
0657: if (oContainers == null) {
0658: if (DebugFile.trace)
0659: DebugFile
0660: .writeln("ERROR: <containers> node not found.");
0661:
0662: throw new DOMException(DOMException.NOT_FOUND_ERR,
0663: "<containers> node not found");
0664: }
0665:
0666: // Load XML data stream only once for all containers
0667: if (DebugFile.trace)
0668: DebugFile.writeln("oXMLStream = new FileInputStream("
0669: + sURI + ")");
0670:
0671: // For each Page do XSL Transformation
0672: for (int c = 0; c < vPages.size(); c++) {
0673: oCurrentPage = (Page) vPages.get(c);
0674:
0675: oXMLStream = new FileInputStream(sURI);
0676: oStreamSrcXML = new StreamSource(oXMLStream);
0677:
0678: // XSL Transformation
0679: try {
0680: if (DebugFile.trace)
0681: DebugFile
0682: .writeln("oTransformer = StylesheetCache.newTransformer("
0683: + sBasePath
0684: + "xslt"
0685: + sSep
0686: + "templates"
0687: + sSep
0688: + oMSite.name()
0689: + sSep
0690: + oCurrentPage.template() + ")");
0691:
0692: // Get a copy of Stylesheet from cache
0693: oTransformer = StylesheetCache.newTransformer(sBasePath
0694: + "xslt" + sSep + "templates" + sSep
0695: + oMSite.name() + sSep
0696: + oCurrentPage.template());
0697:
0698: sMedia = oTransformer
0699: .getOutputProperty(OutputKeys.MEDIA_TYPE);
0700: if (null == sMedia)
0701: sMedia = "html";
0702: else
0703: sMedia = sMedia.substring(sMedia.indexOf('/') + 1);
0704:
0705: if (DebugFile.trace)
0706: DebugFile.writeln("Pages[" + String.valueOf(c)
0707: + "].filePath(" + sOutputPath
0708: + oCurrentPage.getTitle().replace(' ', '_')
0709: + "." + sMedia + ")");
0710:
0711: oCurrentPage.filePath(sOutputPath
0712: + oCurrentPage.getTitle().replace(' ', '_')
0713: + "." + sMedia);
0714:
0715: if (DebugFile.trace)
0716: DebugFile
0717: .writeln("oStreamResult = new StreamResult("
0718: + oCurrentPage.filePath() + ")");
0719:
0720: oStreamResult = new StreamResult(oCurrentPage
0721: .filePath());
0722:
0723: // Set environment parameters for stylesheet
0724: StylesheetCache.setParameters(oTransformer,
0725: oEnvironmentProps);
0726:
0727: // Set user defined parameters for stylesheet
0728: StylesheetCache.setParameters(oTransformer, oUserProps);
0729:
0730: // Realizar la transformación
0731: if (DebugFile.trace)
0732: DebugFile
0733: .writeln("oTransformer.transform(oStreamSrcXML, oStreamResult)");
0734:
0735: oTransformer.setParameter("param_page", ((Page) (vPages
0736: .get(c))).getTitle());
0737: oTransformer.transform(oStreamSrcXML, oStreamResult);
0738: } catch (TransformerConfigurationException e) {
0739: oLastXcpt = e;
0740: if (DebugFile.trace)
0741: DebugFile
0742: .writeln("ERROR TransformerConfigurationException "
0743: + e.getMessageAndLocation());
0744: } catch (TransformerException e) {
0745: oLastXcpt = e;
0746: if (DebugFile.trace)
0747: DebugFile.writeln("ERROR TransformerException "
0748: + e.getMessageAndLocation());
0749: }
0750:
0751: oTransformer = null;
0752: oStreamResult = null;
0753: } // next (c)
0754:
0755: oXMLStream.close();
0756:
0757: if (DebugFile.trace) {
0758: DebugFile.writeln("done in "
0759: + String.valueOf(System.currentTimeMillis()
0760: - lElapsed) + " miliseconds");
0761:
0762: DebugFile.decIdent();
0763: DebugFile.writeln("End PageSet.buildSite()");
0764: }
0765:
0766: return vPages;
0767: } // buildSite()
0768:
0769: // ---------------------------------------------------------------------------
0770:
0771: public Page buildPageForEdit(String sPageGUID, String sBasePath,
0772: String sOutputPath, String sCtrlPath, String sMenuPath,
0773: String sIntegradorPath, String sSelPageOptions,
0774: Properties oEnvironmentProps, Properties oUserProps)
0775:
0776: throws IOException, DOMException, TransformerException,
0777: TransformerConfigurationException, MalformedURLException {
0778:
0779: Transformer oTransformer;
0780: StreamResult oStreamResult;
0781: StreamSource oStreamSrcXML;
0782: StringWriter oStrWritter;
0783: InputStream oXMLStream = null;
0784: String sTransformed;
0785: StringBuffer oPostTransform;
0786: String sKey;
0787: String sMedia;
0788: Object sVal;
0789: Page oCurrentPage;
0790:
0791: int iCloseHead, iOpenBody, iCloseBody;
0792: int iReaded;
0793: char CharBuffer[] = new char[8192];
0794: String sCharBuffer;
0795: long lElapsed = 0;
0796:
0797: final String sSep = System.getProperty("file.separator");
0798:
0799: if (DebugFile.trace) {
0800: lElapsed = System.currentTimeMillis();
0801:
0802: DebugFile.writeln("Begin Pageset.buildPageForEdit("
0803: + sBasePath + "," + sOutputPath + "," + sCtrlPath
0804: + "," + sMenuPath + ")");
0805: DebugFile.incIdent();
0806: }
0807:
0808: FileSystem oFS = new FileSystem();
0809:
0810: if (!sBasePath.endsWith(sSep))
0811: sBasePath += sSep;
0812:
0813: String sWebServer = oEnvironmentProps.getProperty("webserver",
0814: "");
0815:
0816: if (DebugFile.trace && sWebServer.length() == 0)
0817: DebugFile
0818: .writeln("WARNING: webserver property not set at EnvironmentProperties");
0819:
0820: if (!sWebServer.endsWith("/"))
0821: sWebServer += "/";
0822:
0823: // Posicionarse en el nodo de contenedores
0824: Node oContainers = oMSite.seekChildByName(oMSite.getRootNode()
0825: .getFirstChild(), "containers");
0826:
0827: if (oContainers == null) {
0828: if (DebugFile.trace)
0829: DebugFile
0830: .writeln("ERROR: <containers> node not found.");
0831:
0832: throw new DOMException(DOMException.NOT_FOUND_ERR,
0833: "<containers> node not found");
0834: }
0835:
0836: // Cagar el stream de datos XML una sola vez
0837: if (DebugFile.trace)
0838: DebugFile.writeln("new FileInputStream("
0839: + (sURI.startsWith("file://") ? sURI.substring(7)
0840: : sURI) + ")");
0841:
0842: // Para cada contenedor (página) realizar la transformación XSLT
0843:
0844: oCurrentPage = this .page(sPageGUID);
0845:
0846: oXMLStream = new FileInputStream(
0847: sURI.startsWith("file://") ? sURI.substring(7) : sURI);
0848: oStreamSrcXML = new StreamSource(oXMLStream);
0849:
0850: // Asignar cada stream de salida a su stream temporal
0851: oStrWritter = new StringWriter();
0852: oStreamResult = new StreamResult(oStrWritter);
0853:
0854: // Transformacion XSLT
0855: try {
0856:
0857: // Obtener la hoja de estilo desde el cache
0858: oTransformer = StylesheetCache.newTransformer(sBasePath
0859: + "xslt" + sSep + "templates" + sSep
0860: + oMSite.name() + sSep + oCurrentPage.template());
0861:
0862: sMedia = oTransformer
0863: .getOutputProperty(OutputKeys.MEDIA_TYPE);
0864:
0865: if (DebugFile.trace)
0866: DebugFile.writeln(OutputKeys.MEDIA_TYPE + "=" + sMedia);
0867:
0868: if (null == sMedia)
0869: sMedia = "html";
0870: else
0871: sMedia = sMedia.substring(sMedia.indexOf('/') + 1);
0872:
0873: if (null == oCurrentPage.getTitle())
0874: throw new NullPointerException("Page title is null");
0875:
0876: if (DebugFile.trace)
0877: DebugFile.writeln("Page.filePath(" + sOutputPath
0878: + oCurrentPage.getTitle().replace(' ', '_')
0879: + "." + sMedia + ")");
0880:
0881: oCurrentPage.filePath(sOutputPath
0882: + oCurrentPage.getTitle().replace(' ', '_') + "."
0883: + sMedia);
0884:
0885: // Set environment parameters for stylesheet
0886: StylesheetCache.setParameters(oTransformer,
0887: oEnvironmentProps);
0888:
0889: // Set user defined parameters for stylesheet
0890: StylesheetCache.setParameters(oTransformer, oUserProps);
0891:
0892: // Paso el title de la pagina como parametro
0893: oTransformer.setParameter("param_page", oCurrentPage
0894: .getTitle());
0895:
0896: // Realizar la transformación
0897: oTransformer.transform(oStreamSrcXML, oStreamResult);
0898:
0899: } catch (TransformerConfigurationException e) {
0900: oLastXcpt = e;
0901: sMedia = null;
0902:
0903: SourceLocator sl = e.getLocator();
0904:
0905: if (DebugFile.trace) {
0906: if (sl == null) {
0907: DebugFile
0908: .writeln("ERROR TransformerConfigurationException "
0909: + e.getMessage());
0910: } else {
0911: DebugFile
0912: .writeln("ERROR TransformerConfigurationException "
0913: + e.getMessage()
0914: + " line="
0915: + String
0916: .valueOf(sl.getLineNumber())
0917: + " column="
0918: + String.valueOf(sl
0919: .getColumnNumber()));
0920: }
0921: }
0922: } catch (TransformerException e) {
0923: oLastXcpt = e;
0924: sMedia = null;
0925:
0926: if (DebugFile.trace)
0927: DebugFile.writeln("ERROR TransformerException "
0928: + e.getMessageAndLocation());
0929: }
0930:
0931: oTransformer = null;
0932: oStreamResult = null;
0933:
0934: // Asignar un String con el fuente XML transformado
0935: sTransformed = oStrWritter.toString();
0936:
0937: if (DebugFile.trace)
0938: DebugFile.writeln("transformation length="
0939: + String.valueOf(sTransformed.length()));
0940:
0941: // Buscar el fin de tag </head>
0942: if (sTransformed.length() > 0) {
0943: iCloseHead = sTransformed.indexOf("</head");
0944: if (iCloseHead < 0)
0945: iCloseHead = sTransformed.indexOf("</HEAD");
0946:
0947: // Buscar el inicio de tag <body>
0948: iOpenBody = sTransformed.indexOf("<body", iCloseHead);
0949: if (iOpenBody < 0)
0950: iOpenBody = sTransformed.indexOf("<BODY", iCloseHead);
0951:
0952: iCloseBody = sTransformed.indexOf(">", iOpenBody + 5);
0953: for (char s = sTransformed.charAt(iCloseBody + 1); s == '\r'
0954: || s == '\n' || s == ' ' || s == '\t'; s = sTransformed
0955: .charAt(++iCloseBody))
0956: ;
0957:
0958: // Crear un buffer intermedio para mayor velocidad de concatenado
0959: oPostTransform = new StringBuffer(
0960: sTransformed.length() + 4096);
0961:
0962: // Incrustar las llamadas al Integrador en el lugar apropiado del fuente
0963: oPostTransform
0964: .append(sTransformed.substring(0, iCloseHead));
0965: oPostTransform
0966: .append("\n<script language=\"JavaScript\" src=\""
0967: + sMenuPath + "\"></script>");
0968: oPostTransform
0969: .append("\n<script language=\"JavaScript\" src=\""
0970: + sIntegradorPath + "\"></script>\n");
0971: oPostTransform.append(sTransformed.substring(iCloseHead,
0972: iCloseHead + 7));
0973: oPostTransform.append(sTransformed.substring(iOpenBody,
0974: iCloseBody));
0975:
0976: // Cargar el código fuente del control de visulización del Integrador
0977: try {
0978: sCharBuffer = oFS.readfilestr(sCtrlPath, "UTF-8");
0979:
0980: if (DebugFile.trace)
0981: DebugFile.writeln(String.valueOf(sCharBuffer
0982: .length())
0983: + " characters readed");
0984: } catch (com.enterprisedt.net.ftp.FTPException ftpe) {
0985: throw new IOException(ftpe.getMessage());
0986: }
0987:
0988: try {
0989: if (DebugFile.trace)
0990: DebugFile.writeln("Gadgets.replace(" + sCtrlPath
0991: + ",http://demo.hipergate.com/,"
0992: + sWebServer + ")");
0993:
0994: Gadgets.replace(sCharBuffer,
0995: "http://demo.hipergate.com/", sWebServer);
0996:
0997: } catch (org.apache.oro.text.regex.MalformedPatternException e) {
0998: }
0999:
1000: oPostTransform.append("<!--Begin " + sCtrlPath + "-->\n");
1001:
1002: oPostTransform.append(sCharBuffer);
1003: sCharBuffer = null;
1004:
1005: oPostTransform.append("\n<!--End " + sCtrlPath + "-->\n");
1006:
1007: oPostTransform.append(sTransformed.substring(iCloseBody));
1008: } else {
1009: oPostTransform = new StringBuffer("Page "
1010: + oCurrentPage.getTitle()
1011: + " could not be rendered.");
1012: if (oLastXcpt != null)
1013: oPostTransform.append("<BR>"
1014: + oLastXcpt.getMessageAndLocation());
1015: }
1016:
1017: // Escribir el resultado con las llamadas incrustadas en el archivo de salida
1018:
1019: if (sSelPageOptions.length() == 0)
1020: oFS.writefilestr(sOutputPath
1021: + oCurrentPage.getTitle().replace(' ', '_') + "_."
1022: + sMedia, oPostTransform.toString(), "UTF-8");
1023: else
1024: try {
1025:
1026: oFS.writefilestr(sOutputPath
1027: + oCurrentPage.getTitle().replace(' ', '_')
1028: + "_." + sMedia, Gadgets
1029: .replace(oPostTransform.toString(),
1030: ":selPageOptions", sSelPageOptions),
1031: "UTF-8");
1032:
1033: } catch (Exception e) {/* Ignore MalformedPatternException, is never thrown */
1034: }
1035:
1036: // Desreferenciar los buffers intermedios para liberar memoria lo antes posible
1037: oPostTransform = null;
1038: sTransformed = null;
1039:
1040: oXMLStream.close();
1041:
1042: if (DebugFile.trace) {
1043: DebugFile.writeln("done in "
1044: + String.valueOf(System.currentTimeMillis()
1045: - lElapsed) + " miliseconds");
1046:
1047: DebugFile.decIdent();
1048: DebugFile.writeln("End Pageset.buildPageForEdit() : "
1049: + oCurrentPage.getTitle());
1050: }
1051:
1052: return oCurrentPage;
1053: } // buildPageForEdit()
1054:
1055: //-----------------------------------------------------------
1056:
1057: /**
1058: * <p>Generate XSL Transformation output with editing layers for PageSet.</p>
1059: * @param sBasePath Path to directory containing XSL stylesheets
1060: * @param sOutputPath Path to output directory where generated files shall be saved.
1061: * @param sCtrlPath Path to source code of the edition layer (tipically /includes/integrador_ctrl.inc file)
1062: * @param sMenuPath Path to dynamic page that generates the block list (tipically /webbuilder/wb_mnuintegrador.jsp)
1063: * @param sIntegradorPath Path to JavaScript functions of edition layer (tipically integrador.js)
1064: * @param sSelPageOptions If this is a single Page PageSet this parameter must be "",
1065: * else it is a list of available pages in HTML <OPTION>...</OPTION> format.
1066: * @param oEnvironmentProps Environment properties to be replaced at templated
1067: * @param oUserProps User Properties to be replaced at templated
1068: * @throws IOException
1069: * @throws DOMException
1070: * @throws TransformerException
1071: * @throws TransformerConfigurationException
1072: * @throws NullPointerException
1073: */
1074: public void buildSiteForEdit(String sBasePath, String sOutputPath,
1075: String sCtrlPath, String sMenuPath, String sIntegradorPath,
1076: String sSelPageOptions, Properties oEnvironmentProps,
1077: Properties oUserProps)
1078:
1079: throws IOException, DOMException, TransformerException,
1080: TransformerConfigurationException, MalformedURLException {
1081:
1082: Transformer oTransformer;
1083: StreamResult oStreamResult;
1084: StreamSource oStreamSrcXML;
1085: StringWriter oStrWritter;
1086: InputStream oXMLStream = null;
1087: String sTransformed;
1088: StringBuffer oPostTransform;
1089: String sKey;
1090: String sMedia;
1091: Object sVal;
1092: Page oCurrentPage;
1093:
1094: int iCloseHead, iOpenBody, iCloseBody;
1095: int iReaded;
1096: char CharBuffer[] = new char[8192];
1097: String sCharBuffer;
1098: long lElapsed = 0;
1099:
1100: final String sSep = System.getProperty("file.separator");
1101:
1102: if (DebugFile.trace) {
1103: lElapsed = System.currentTimeMillis();
1104:
1105: DebugFile.writeln("Begin Pageset.buildSiteForEdit("
1106: + sBasePath + "," + sOutputPath + "," + sCtrlPath
1107: + "," + sMenuPath + ")");
1108: DebugFile.incIdent();
1109: }
1110:
1111: FileSystem oFS = new FileSystem();
1112:
1113: Vector vPages = pages();
1114:
1115: if (!sBasePath.endsWith(sSep))
1116: sBasePath += sSep;
1117:
1118: String sWebServer = oEnvironmentProps.getProperty("webserver",
1119: "");
1120:
1121: if (DebugFile.trace && sWebServer.length() == 0)
1122: DebugFile
1123: .writeln("WARNING: webserver property not set at EnvironmentProperties");
1124:
1125: if (!sWebServer.endsWith("/"))
1126: sWebServer += "/";
1127:
1128: // Posicionarse en el nodo de contenedores
1129: Node oContainers = oMSite.seekChildByName(oMSite.getRootNode()
1130: .getFirstChild(), "containers");
1131:
1132: if (oContainers == null) {
1133: if (DebugFile.trace)
1134: DebugFile
1135: .writeln("ERROR: <containers> node not found.");
1136:
1137: throw new DOMException(DOMException.NOT_FOUND_ERR,
1138: "<containers> node not found");
1139: }
1140:
1141: // Cagar el stream de datos XML una sola vez
1142: if (DebugFile.trace)
1143: DebugFile.writeln("new FileInputStream("
1144: + (sURI.startsWith("file://") ? sURI.substring(7)
1145: : sURI) + ")");
1146:
1147: // Para cada contenedor (página) realizar la transformación XSLT
1148: for (int c = 0; c < vPages.size(); c++) {
1149:
1150: oCurrentPage = (Page) vPages.get(c);
1151:
1152: oXMLStream = new FileInputStream(
1153: sURI.startsWith("file://") ? sURI.substring(7)
1154: : sURI);
1155: oStreamSrcXML = new StreamSource(oXMLStream);
1156:
1157: // Asignar cada stream de salida a su stream temporal
1158: oStrWritter = new StringWriter();
1159: oStreamResult = new StreamResult(oStrWritter);
1160:
1161: // Transformacion XSLT
1162: try {
1163:
1164: // Obtener la hoja de estilo desde el cache
1165: oTransformer = StylesheetCache.newTransformer(sBasePath
1166: + "xslt" + sSep + "templates" + sSep
1167: + oMSite.name() + sSep
1168: + oCurrentPage.template());
1169:
1170: sMedia = oTransformer
1171: .getOutputProperty(OutputKeys.MEDIA_TYPE);
1172:
1173: if (DebugFile.trace)
1174: DebugFile.writeln(OutputKeys.MEDIA_TYPE + "="
1175: + sMedia);
1176:
1177: if (null == sMedia)
1178: sMedia = "html";
1179: else
1180: sMedia = sMedia.substring(sMedia.indexOf('/') + 1);
1181:
1182: if (null == oCurrentPage.getTitle())
1183: throw new NullPointerException("Page "
1184: + String.valueOf(c) + " title is null");
1185:
1186: if (DebugFile.trace)
1187: DebugFile.writeln("Page.filePath(" + sOutputPath
1188: + oCurrentPage.getTitle().replace(' ', '_')
1189: + "." + sMedia + ")");
1190:
1191: oCurrentPage.filePath(sOutputPath
1192: + oCurrentPage.getTitle().replace(' ', '_')
1193: + "." + sMedia);
1194:
1195: // Set environment parameters for stylesheet
1196: StylesheetCache.setParameters(oTransformer,
1197: oEnvironmentProps);
1198:
1199: // Set user defined parameters for stylesheet
1200: StylesheetCache.setParameters(oTransformer, oUserProps);
1201:
1202: // Paso el title de la pagina como parametro
1203: oTransformer.setParameter("param_page", ((Page) (vPages
1204: .get(c))).getTitle());
1205:
1206: // Realizar la transformación
1207: oTransformer.transform(oStreamSrcXML, oStreamResult);
1208:
1209: } catch (TransformerConfigurationException e) {
1210: oLastXcpt = e;
1211: sMedia = null;
1212:
1213: SourceLocator sl = e.getLocator();
1214:
1215: if (DebugFile.trace) {
1216: if (sl == null) {
1217: DebugFile
1218: .writeln("ERROR TransformerConfigurationException "
1219: + e.getMessage());
1220: } else {
1221: DebugFile
1222: .writeln("ERROR TransformerConfigurationException "
1223: + e.getMessage()
1224: + " line="
1225: + String.valueOf(sl
1226: .getLineNumber())
1227: + " column="
1228: + String.valueOf(sl
1229: .getColumnNumber()));
1230: }
1231: }
1232: } catch (TransformerException e) {
1233: oLastXcpt = e;
1234: sMedia = null;
1235:
1236: if (DebugFile.trace)
1237: DebugFile.writeln("ERROR TransformerException "
1238: + e.getMessageAndLocation());
1239: }
1240:
1241: oTransformer = null;
1242: oStreamResult = null;
1243:
1244: // Asignar un String con el fuente XML transformado
1245: sTransformed = oStrWritter.toString();
1246:
1247: if (DebugFile.trace)
1248: DebugFile.writeln("transformation length="
1249: + String.valueOf(sTransformed.length()));
1250:
1251: // Buscar el fin de tag </head>
1252: if (sTransformed.length() > 0) {
1253: iCloseHead = sTransformed.indexOf("</head");
1254: if (iCloseHead < 0)
1255: iCloseHead = sTransformed.indexOf("</HEAD");
1256:
1257: // Buscar el inicio de tag <body>
1258: iOpenBody = sTransformed.indexOf("<body", iCloseHead);
1259: if (iOpenBody < 0)
1260: iOpenBody = sTransformed.indexOf("<BODY",
1261: iCloseHead);
1262:
1263: iCloseBody = sTransformed.indexOf(">", iOpenBody + 5);
1264: for (char s = sTransformed.charAt(iCloseBody + 1); s == '\r'
1265: || s == '\n' || s == ' ' || s == '\t'; s = sTransformed
1266: .charAt(++iCloseBody))
1267: ;
1268:
1269: // Crear un buffer intermedio para mayor velocidad de concatenado
1270: oPostTransform = new StringBuffer(
1271: sTransformed.length() + 4096);
1272:
1273: // Incrustar las llamadas al Integrador en el lugar apropiado del fuente
1274: oPostTransform.append(sTransformed.substring(0,
1275: iCloseHead));
1276: oPostTransform
1277: .append("\n<script language=\"JavaScript\" src=\""
1278: + sMenuPath + "\"></script>");
1279: oPostTransform
1280: .append("\n<script language=\"JavaScript\" src=\""
1281: + sIntegradorPath + "\"></script>\n");
1282: oPostTransform.append(sTransformed.substring(
1283: iCloseHead, iCloseHead + 7));
1284: oPostTransform.append(sTransformed.substring(iOpenBody,
1285: iCloseBody));
1286:
1287: // Cargar el código fuente del control de visulización del Integrador
1288: try {
1289: sCharBuffer = oFS.readfilestr(sCtrlPath, "UTF-8");
1290:
1291: if (DebugFile.trace)
1292: DebugFile.writeln(String.valueOf(sCharBuffer
1293: .length())
1294: + " characters readed");
1295: } catch (com.enterprisedt.net.ftp.FTPException ftpe) {
1296: throw new IOException(ftpe.getMessage());
1297: }
1298:
1299: try {
1300: if (DebugFile.trace)
1301: DebugFile.writeln("Gadgets.replace("
1302: + sCtrlPath
1303: + ",http://demo.hipergate.com/,"
1304: + sWebServer + ")");
1305:
1306: Gadgets.replace(sCharBuffer,
1307: "http://demo.hipergate.com/", sWebServer);
1308: } catch (org.apache.oro.text.regex.MalformedPatternException e) {
1309: }
1310:
1311: oPostTransform.append("<!--Begin " + sCtrlPath
1312: + "-->\n");
1313:
1314: oPostTransform.append(sCharBuffer);
1315: sCharBuffer = null;
1316:
1317: oPostTransform.append("\n<!--End " + sCtrlPath
1318: + "-->\n");
1319:
1320: oPostTransform.append(sTransformed
1321: .substring(iCloseBody));
1322: } else {
1323: oPostTransform = new StringBuffer("Page "
1324: + ((Page) vPages.get(c)).getTitle()
1325: + " could not be rendered.");
1326: if (oLastXcpt != null)
1327: oPostTransform.append("<BR>"
1328: + oLastXcpt.getMessageAndLocation());
1329: }
1330:
1331: // Escribir el resultado con las llamadas incrustadas en el archivo de salida
1332: if (DebugFile.trace)
1333: DebugFile.writeln("new FileWriter(" + sOutputPath
1334: + oCurrentPage.getTitle().replace(' ', '_')
1335: + "_." + sMedia + ")");
1336:
1337: if (sSelPageOptions.length() == 0)
1338: oFS.writefilestr(sOutputPath
1339: + oCurrentPage.getTitle().replace(' ', '_')
1340: + "_." + sMedia, oPostTransform.toString(),
1341: "UTF-8");
1342: else
1343: try {
1344: oFS.writefilestr(sOutputPath
1345: + oCurrentPage.getTitle().replace(' ', '_')
1346: + "_." + sMedia, Gadgets.replace(
1347: oPostTransform.toString(),
1348: ":selPageOptions", sSelPageOptions),
1349: "UTF-8");
1350:
1351: } catch (Exception e) {/* Ignore MalformedPatternException, is never thrown */
1352: }
1353:
1354: // Desreferenciar los buffers intermedios para liberar memoria lo antes posible
1355: oPostTransform = null;
1356: sTransformed = null;
1357: } // next (c)
1358:
1359: oXMLStream.close();
1360:
1361: if (DebugFile.trace) {
1362: DebugFile.writeln("done in "
1363: + String.valueOf(System.currentTimeMillis()
1364: - lElapsed) + " miliseconds");
1365:
1366: DebugFile.decIdent();
1367: DebugFile.writeln("End Pageset.buildSiteForEdit()");
1368: }
1369: } // buildSiteForEdit()
1370:
1371: //-----------------------------------------------------------
1372:
1373: private Page findPage(String sPageGUID) {
1374: Vector oPages = this .pages();
1375: int iPages = oPages.size();
1376: Page oPage = null;
1377:
1378: for (int p = 0; p < iPages && oPage == null; p++)
1379: if (sPageGUID.equals(((Page) oPages.get(p)).guid()))
1380: oPage = (Page) oPages.get(p);
1381:
1382: return oPage;
1383: } // findPage
1384:
1385: //-----------------------------------------------------------
1386:
1387: /**
1388: * <p>Add block at the end of a Page</p>
1389: * @param sFilePath Path to PageSet XML file
1390: * @param sPageGUID <Page> GUID attribute
1391: * @param sBlockXML XML of Block to be added
1392: * @return New Block Id
1393: * @throws IllegalAccessException
1394: * @throws IOException
1395: * @throws ClassNotFoundException
1396: * @throws NumberFormatException If Identifier attribute <block id="..."> is not an integer number.
1397: */
1398: public String addBlock(String sFilePath, String sPageGUID,
1399: String sBlockXML) throws IllegalAccessException,
1400: IOException, ClassNotFoundException, NumberFormatException,
1401: UTFDataFormatException, Exception {
1402:
1403: String sBlockId;
1404: Page oPage = null;
1405: long lElapsed = 0;
1406:
1407: if (DebugFile.trace) {
1408: lElapsed = System.currentTimeMillis();
1409:
1410: DebugFile.writeln("Begin Pageset.addBlock(" + sFilePath
1411: + "," + sPageGUID + ",\n" + sBlockXML + "\n)");
1412: DebugFile.incIdent();
1413: }
1414:
1415: sURI = sFilePath;
1416:
1417: parseURI(sFilePath);
1418:
1419: oPage = findPage(sPageGUID);
1420:
1421: sBlockId = oPage.nextBlockId();
1422:
1423: try {
1424: sBlockXML = com.knowgate.misc.Gadgets.replace(sBlockXML,
1425: "<block>", "<block id=\"" + sBlockId + "\">");
1426: } catch (MalformedPatternException mpe) {
1427: }
1428:
1429: new XMLDocument(sFilePath).addNodeAndSave(
1430: "pageset/pages/page[@guid='" + oPage.guid()
1431: + "']/blocks/block/", sBlockXML);
1432:
1433: if (DebugFile.trace) {
1434: DebugFile.writeln("done in "
1435: + String.valueOf(System.currentTimeMillis()
1436: - lElapsed) + " miliseconds");
1437:
1438: DebugFile.decIdent();
1439: DebugFile.writeln("End Pageset.addBlock()");
1440: }
1441:
1442: return sBlockId;
1443: } // addBlock
1444:
1445: //-----------------------------------------------------------
1446:
1447: public void save(String sFilePath) throws IOException {
1448: FileOutputStream oOutFile = new FileOutputStream(sFilePath,
1449: false);
1450:
1451: print(oOutFile);
1452:
1453: oOutFile.close();
1454: } // save
1455:
1456: // **********************************************************
1457: // * Static Methods
1458:
1459: //-----------------------------------------------------------
1460:
1461: /**
1462: * <p>Merge Company addresses, catalog and other information into a PageSet XML file<p>
1463: * Addresses are readed from k_addresses table and appended to the XML file after the <pages> node.
1464: * @param oConn JDBC database connection
1465: * @param sFilePath Complete path to the PageSet XML data file
1466: * @param sCompanyGUID GUID of Company which addresses are to be merged into the PageSet XML file
1467: * @throws SQLException
1468: * @throws IOException
1469: */
1470: public static void mergeCompanyInfo(JDCConnection oConn,
1471: String sFilePath, String sCompanyGUID) throws SQLException,
1472: IOException {
1473:
1474: Statement oStmt;
1475: ResultSet oRSet;
1476:
1477: if (DebugFile.trace) {
1478: DebugFile
1479: .writeln("PageSet.mergeCompanyAddresses(JDCConnection,"
1480: + sFilePath + "," + sCompanyGUID + ")");
1481: DebugFile.incIdent();
1482: }
1483:
1484: XMLDocument oXMLDoc = new XMLDocument(sFilePath);
1485:
1486: String sCategoryGUID = "";
1487:
1488: if (DebugFile.trace) {
1489: DebugFile.writeln("Connection.executeQuery(SELECT "
1490: + DB.gu_category + " FROM " + DB.k_x_company_prods
1491: + " WHERE " + DB.gu_company + "='" + sCompanyGUID
1492: + "')");
1493: }
1494:
1495: oStmt = oConn.createStatement();
1496: oRSet = oStmt.executeQuery("SELECT " + DB.gu_category
1497: + " FROM " + DB.k_x_company_prods + " WHERE "
1498: + DB.gu_company + "='" + sCompanyGUID + "'");
1499: if (oRSet.next()) {
1500: sCategoryGUID = oRSet.getString(1);
1501: }
1502: oRSet.close();
1503: oStmt.close();
1504:
1505: oStmt = oConn.createStatement();
1506: oRSet = oStmt.executeQuery("SELECT * FROM " + DB.k_addresses
1507: + " WHERE 1=0");
1508: ResultSetMetaData oMDat = oRSet.getMetaData();
1509: StringBuffer oColumnList = new StringBuffer(512);
1510: int iColumnCount = oMDat.getColumnCount();
1511:
1512: for (int c = 1; c <= iColumnCount; c++) {
1513: if (c > 1)
1514: oColumnList.append(',');
1515: oColumnList.append("a."
1516: + oMDat.getColumnName(c).toLowerCase());
1517: } // next (c)
1518:
1519: oRSet.close();
1520: oStmt.close();
1521:
1522: DBSubset oAddrs = new DBSubset(DB.k_addresses + " a,"
1523: + DB.k_x_company_addr + " x", oColumnList.toString(),
1524: "a." + DB.gu_address + "=x." + DB.gu_address
1525: + " AND x." + DB.gu_company + "=? ORDER BY a."
1526: + DB.ix_address, 10);
1527:
1528: oAddrs.load(oConn, new Object[] { sCompanyGUID });
1529:
1530: String sAddresses = "\n <company>" + sCompanyGUID
1531: + "</company>\n <catalog>" + sCategoryGUID
1532: + "</catalog>\n <addresses>\n"
1533: + oAddrs.toXML(" ", "address") + "\n </addresses>";
1534:
1535: try {
1536: oXMLDoc.removeNode("pageset/company");
1537: } catch (DOMException dome) {
1538: if (dome.code != DOMException.NOT_FOUND_ERR)
1539: throw new DOMException(dome.code, dome.getMessage());
1540: }
1541: try {
1542: oXMLDoc.removeNode("pageset/catalog");
1543: } catch (DOMException dome) {
1544: if (dome.code != DOMException.NOT_FOUND_ERR)
1545: throw new DOMException(dome.code, dome.getMessage());
1546: }
1547: try {
1548: oXMLDoc.removeNode("pageset/addresses");
1549: } catch (DOMException dome) {
1550: if (dome.code != DOMException.NOT_FOUND_ERR)
1551: throw new DOMException(dome.code, dome.getMessage());
1552: }
1553:
1554: oXMLDoc.addNodeAndSave("pageset/pages", sAddresses);
1555:
1556: if (DebugFile.trace) {
1557: DebugFile.decIdent();
1558: DebugFile.writeln("PageSet.mergeCompanyAddresses()");
1559: }
1560: } // mergeCompanyAddresses
1561:
1562: //-----------------------------------------------------------
1563:
1564: /**
1565: * <p>Remove Page from PageSet</p>
1566: * Page is searched by an internal XPath expression:<br>
1567: * pageset/pages/page[@guid='<i>sPageGUID</i>']
1568: * @param sFilePath Path to PageSet XML file
1569: * @param sPageGUID <Page> GUID attribute
1570: * @throws IOException
1571: */
1572: public static void removePage(String sFilePath, String sPageGUID)
1573: throws IOException {
1574: XMLDocument oXThis = new XMLDocument(sFilePath);
1575:
1576: oXThis.removeNodeAndSave("pageset/pages/page[@guid='"
1577: + sPageGUID + "']");
1578: } // removePage
1579:
1580: //-----------------------------------------------------------
1581:
1582: /**
1583: * <p>Remove a Page searching it by title</p>
1584: * Page is searched by an internal XPath expression:<br>
1585: * pageset/pages/page[guid = '<i>sPageTitle</i>']
1586: * @param sFilePath Path to PageSet XML file
1587: * @param sPageGUIDAttr Page GUID
1588: * @throws IOException
1589: */
1590: public static void removePageByTitle(String sFilePath,
1591: String sPageGUIDAttr) throws IOException {
1592: XMLDocument oXThis = new XMLDocument(sFilePath);
1593:
1594: oXThis.removeNodeAndSave("pageset/pages/page[guid = '"
1595: + sPageGUIDAttr + "']");
1596: } // removePageByTitle
1597:
1598: //-----------------------------------------------------------
1599:
1600: /**
1601: * <p>Remove Block</p>
1602: * Block is searched by an internal XPath expression:<br>
1603: * pageset/pages/page[@guid='<i>sPageGUID</i>']/blocks/block[@id='<i>sBlockId</i>']
1604: * @param sFilePath Path to PageSet XML file
1605: * @param sPageGUID <Page> GUID attribute
1606: * @param sBlockId id attribute of Block to be removed
1607: * @throws IOException
1608: */
1609: public static void removeBlock(String sFilePath, String sPageGUID,
1610: String sBlockId) throws IOException {
1611: XMLDocument oXThis = new XMLDocument(sFilePath);
1612:
1613: oXThis
1614: .removeNodeAndSave("pageset/pages/page[@guid='"
1615: + sPageGUID + "']/blocks/block[@id='"
1616: + sBlockId + "']");
1617: } // removeBlock
1618:
1619: //-----------------------------------------------------------
1620:
1621: /**
1622: * <p>Get base Microsite GUID from a PageSet XML file.<p>
1623: * GUID is obtained directly from raw text reading without parsing the input file.
1624: * @param sPageSetURI Path to PageSet XML file
1625: * @return Microsite GUID
1626: * @throws FileNotFoundException
1627: * @throws IOException
1628: */
1629: public static String getMicrositeGUID(String sPageSetURI)
1630: throws FileNotFoundException, IOException {
1631:
1632: if (DebugFile.trace) {
1633: DebugFile.writeln("PageSet.getMicrositeGUID(" + sPageSetURI
1634: + ")");
1635: DebugFile.incIdent();
1636: }
1637:
1638: String sXML;
1639: int iMSiteOpenTag, iMSiteCloseTag;
1640: byte byXML[] = new byte[1024];
1641: FileInputStream oXMLStream = new FileInputStream(sPageSetURI);
1642: int iReaded = oXMLStream.read(byXML, 0, 1024);
1643: oXMLStream.close();
1644:
1645: sXML = new String(byXML, 0, iReaded);
1646: iMSiteOpenTag = sXML.indexOf("<microsite>") + 11;
1647: iMSiteCloseTag = sXML.indexOf("</microsite>", iMSiteOpenTag);
1648:
1649: if (DebugFile.trace) {
1650: DebugFile.decIdent();
1651: DebugFile.writeln("PageSet.getMicrositeGUID() : "
1652: + sXML.substring(iMSiteOpenTag, iMSiteCloseTag));
1653: }
1654:
1655: return sXML.substring(iMSiteOpenTag, iMSiteCloseTag);
1656: } // getMicrositeGUID();
1657:
1658: // ----------------------------------------------------------
1659:
1660: private static void printUsage() {
1661:
1662: System.out.println("");
1663: System.out.println("Usage:");
1664: System.out
1665: .println("com.knowgate.dataxslt.PageSet parse file_path");
1666: }
1667:
1668: // ---------------------------------------------------------
1669:
1670: public static void main(String[] argv)
1671: throws IllegalAccessException, ClassNotFoundException,
1672: Exception {
1673: if (argv.length != 2)
1674: printUsage();
1675: else if (!argv[0].equalsIgnoreCase("parse"))
1676: printUsage();
1677: else {
1678: PageSet oMSite = new PageSet(argv[1], true);
1679: }
1680: } // main
1681:
1682: // **********************************************************
1683: // * Variables estáticas
1684:
1685: public static final short ClassId = 71;
1686:
1687: } // PageSet
|