jeremy 02/02/28 11:03:05 Added: src/scratchpad/src/org/apache/cocoon/transformation WriteableSourceTransformer.java Log: adding a replacement for FileWritingTransformer that uses the new WritableSource interface Revision Changes Path 1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/transformation/WriteableSourceTransformer.java Index: WriteableSourceTransformer.java =================================================================== /* ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modifica- tion, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "Apache Cocoon" and "Apache Software Foundation" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact [EMAIL PROTECTED] 5. Products derived from this software may not be called "Apache", nor may "Apache" appear in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.cocoon.transformation; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.component.Component; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentSelector; import org.apache.avalon.framework.component.Composable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.serialization.Serializer; import org.apache.cocoon.caching.CacheValidity; import org.apache.cocoon.caching.Cacheable; import org.apache.cocoon.environment.Source; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.environment.WriteableSource; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.ResourceNotFoundException; import org.apache.cocoon.xml.XMLConsumer; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import java.lang.SecurityException; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import java.util.Properties; /** * This transformer allows you to output to a WritableSource. * * <p>Definition:</p> * <pre> * <map:transformer name="tofile" src="org.apache.cocoon.transformation.WritableSourceTransformer"> * <map:parameter name="serializer" value="xml"/> <!-- this is the default Serializer (if your Source needs one, like for instance FileSource) --> * </map:transformer/> * </pre> * * <p>Invocation:</p> * <pre> * <map:transform type="tofile"> * <map:parameter name="serializer" value="xml"/> * </map:transform> * </pre> * * <p>Input XML document example:</p> * <pre> * <page xmlns:source="http://apache.org/cocoon/source/1.0"> * ... * <source:write src="context://doc/editable/my.xml"> * <page> * XML Object body * </page> * </source:write> * ... * </page> * </pre> * * <p>Output XML document example:</p> * <pre> * <page xmlns:source="http://apache.org/cocoon/source/1.0"> * ... * <source:write src="/source/specific/path/to/context/doc/editable/my.xml" result="success|failure" action="new"> * source specific error message * </source:write> * ... * </page> * </pre> * * @author <a href="mailto:[EMAIL PROTECTED]">Jeremy Quinn</a> * */ public class WriteableSourceTransformer extends AbstractTransformer implements Disposable, Configurable, Composable { private static String WST_URI = "http://apache.org/cocoon/source/1.0"; private static String WST_ELEMENT = "write"; private static String WST_RESULT_ATTRIBUTE= "result"; private static String WST_SRC_ATTRIBUTE = "src"; private static String WST_ACTION_ATTRIBUTE = "action"; private static String WST_SERIALIZER_ATTRIBUTE = "serializer"; /** The <code>SourceResolver</code> */ protected SourceResolver sourceResolver; /** The current <code>ComponentManager</code>. */ protected ComponentManager manager = null; /** The ContentHandler instance */ protected XMLConsumer ch; // is XMLConsumer suitable for this purpose? /** Are we using a Serializer? */ private boolean isSerializer = false; /** Current Serializer name. */ private String serializer_name = null; /** Current target name. */ private String target = null; /** Current OutputStream. */ private OutputStream os = null; /** Current status of outputting the file. */ private boolean failed = true; /** Current error message. */ private String message = null; /** Does the file exist, before we try to make it? */ private boolean exists = false; /** True when inside <write> element. */ private boolean processing; public void WriteableSourceTransformer() { } /** * Set the current <code>ComponentManager</code> instance used by this * <code>Composable</code>. */ public void compose(ComponentManager manager) throws ComponentException { this.manager=manager; // We need this later to get the Serializer, if it is required } /** * Get the current <code>Configuration</code> instance used by this * <code>Configurable</code>. */ public void configure(Configuration configuration) throws ConfigurationException { try { this.serializer_name = configuration.getChild(WST_SERIALIZER_ATTRIBUTE).getValue(); } catch (Exception e) { getLogger().debug("WritableSourceTransformer: Configuration - no serializer yet"); } } /** * Get the <code>Parameter</code> called "serializer" from the * <code>Transformer</code> invocation. */ public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException { this.sourceResolver = resolver; // save it for later, when we know the filepath to save to this.serializer_name = par.getParameter(WST_SERIALIZER_ATTRIBUTE, this.serializer_name); if (this.serializer_name != null) getLogger().debug("WritableSourceTransformer: Setup, using serializer: " + this.serializer_name); } /** * Begin the scope of a prefix-URI Namespace mapping. * * @param prefix The Namespace prefix being declared. * @param uri The Namespace URI the prefix is mapped to. */ public void startPrefixMapping(String prefix, String uri) throws SAXException { if (!this.processing) { super.startPrefixMapping(prefix,uri); } else if (this.ch != null){ this.ch.startPrefixMapping(prefix, uri); } } /** * End the scope of a prefix-URI mapping. * * @param prefix The prefix that was being mapping. */ public void endPrefixMapping(String prefix) throws SAXException { if (!this.processing) { super.endPrefixMapping(prefix); } else if (this.ch != null){ this.ch.endPrefixMapping(prefix); } } /** * Receive notification of the beginning of an element. * * @param uri The Namespace URI, or the empty string if the element has no * Namespace URI or if Namespace * processing is not being performed. * @param loc The local name (without prefix), or the empty string if * Namespace processing is not being performed. * @param raw The raw XML 1.0 name (with prefix), or the empty string if * raw names are not available. * @param a The attributes attached to the element. If there are no * attributes, it shall be an empty Attributes object. */ public void startElement(String uri, String loc, String raw, Attributes a) throws SAXException { if (!this.processing) { if (WST_URI.equals(uri) && WST_ELEMENT.equals(loc)) { getLogger().debug("WritableSourceTransformer: start processing xmlns:source"); this.failed = false; this.message = null; this.target = ""; // look for the Source String src = a.getValue("",WST_SRC_ATTRIBUTE); Source source = null; try { this.message = "The src attribute could not be resolved"; source = this.sourceResolver.resolve(src); this.target = source.getSystemId(); this.message = "The src attribute doesn't resolve to a writeable source"; WriteableSource wsource = (WriteableSource)source; //this.exists = wsource.exists(); this.message = "Could not open the source for writing"; this.os = wsource.getOutputStream(); // has a Serializer been specified? String local_serializer = a.getValue("",WST_SERIALIZER_ATTRIBUTE); if (local_serializer != null) this.serializer_name = local_serializer; if (this.serializer_name != null) { // Lookup the Serializer this.message = "that Serializer does not exist"; ComponentSelector selector = (ComponentSelector)manager.lookup(Serializer.ROLE + "Selector"); this.ch = (Serializer)selector.select(this.serializer_name); this.message = "could not write the file"; ((Serializer)this.ch).setOutputStream(this.os); // Is there a way to avoid this casting? this.isSerializer = true; } else { this.message = "could not get a ContentHandler"; this.ch = (XMLConsumer)wsource.getContentHandler(); // Is there a way to avoid this casting? } // start the document if (!this.failed) { this.ch.startDocument(); } } catch (Exception e) { getLogger().warn("WritableSourceTransformer failed, " + this.message, e); this.failed = true; //throw new SAXException("FileWritingTransformer: " + this.message, e); } finally { if (source != null) { source.recycle(); } } this.processing = true; getLogger().debug("WritableSourceTransformer: Processing Started"); } else { super.startElement(uri,loc,raw,a); } } else if (this.ch != null){ this.ch.startElement(uri,loc,raw,a); } } /** * Receive notification of the end of an element. * * @param uri The Namespace URI, or the empty string if the element has no * Namespace URI or if Namespace * processing is not being performed. * @param loc The local name (without prefix), or the empty string if * Namespace processing is not being performed. * @param raw The raw XML 1.0 name (with prefix), or the empty string if * raw names are not available. */ public void endElement(String uri, String loc, String raw) throws SAXException { if (!this.processing) { super.endElement(uri,loc,raw); } else { if (WST_URI.equals(uri) && WST_ELEMENT.equals(loc)){ if (!this.failed) { this.ch.endDocument(); } this.processing = false; getLogger().debug("WritableSourceTransformer: Processing Ended"); if (isSerializer) this.manager.release((Component)this.ch); // Is there a way to avoid this casting? // close the OutputStream try { if (this.os != null) { this.os.close(); this.os = null; } } catch(Exception e) { getLogger().warn("WritableSourceTransformer: Failed to close source", e); this.message = "Failed to close source"; this.failed = true; } // Report result String result = (this.failed) ? "failed" : "success"; String action = "none"; /*if (!this.failed){ if (this.exists) { action = "overwritten"; } else { action = "new"; } } */ AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute(null, WST_SRC_ATTRIBUTE, WST_SRC_ATTRIBUTE, "CDATA", this.target); //attrs.addAttribute(null, WST_ACTION_ATTRIBUTE, WST_ACTION_ATTRIBUTE, "CDATA", action); attrs.addAttribute(null, WST_RESULT_ATTRIBUTE, WST_RESULT_ATTRIBUTE, "CDATA", result); if (this.serializer_name != null) attrs.addAttribute(null, WST_SERIALIZER_ATTRIBUTE, WST_SERIALIZER_ATTRIBUTE, "CDATA", this.serializer_name); super.startElement(uri, loc, raw, attrs); if (this.message != null && this.failed == true) super.characters(this.message.toCharArray(), 0, this.message.length()); super.endElement(uri, loc, raw); getLogger().debug("WritableSourceTransformer: Source Written"); } else if (this.ch != null){ this.ch.endElement(uri, loc, raw); } } } /** * Receive notification of character data. * * @param c The characters from the XML document. * @param start The start position in the array. * @param len The number of characters to read from the array. */ public void characters(char c[], int start, int len) throws SAXException { if (!this.processing) { super.characters(c,start,len); } else if (this.ch != null){ this.ch.characters(c,start,len); } } /** * Receive notification of ignorable whitespace in element content. * * @param c The characters from the XML document. * @param start The start position in the array. * @param len The number of characters to read from the array. */ public void ignorableWhitespace(char c[], int start, int len) throws SAXException { if (!this.processing) { super.ignorableWhitespace(c,start,len); } else if (this.ch != null){ this.ch.ignorableWhitespace(c,start,len); } } /** * Receive notification of a processing instruction. * * @param target The processing instruction target. * @param data The processing instruction data, or null if none was * supplied. */ public void processingInstruction(String target, String data) throws SAXException { if (!this.processing) { super.processingInstruction(target,data); } else if (this.ch != null){ this.ch.processingInstruction(target,data); } } /** * Receive notification of a skipped entity. * * @param name The name of the skipped entity. If it is a parameter * entity, the name will begin with '%'. */ public void skippedEntity(String name) throws SAXException { if (!this.processing) { super.skippedEntity(name); } else if (this.ch != null){ this.ch.skippedEntity(name); } } /** * Report the start of DTD declarations, if any. * * @param name The document type name. * @param publicId The declared public identifier for the external DTD * subset, or null if none was declared. * @param systemId The declared system identifier for the external DTD * subset, or null if none was declared. */ public void startDTD(String name, String publicId, String systemId) throws SAXException { if (!this.processing) super.startDTD(name,publicId,systemId); } /** * Report the end of DTD declarations. */ public void endDTD() throws SAXException { if (!this.processing) super.endDTD(); } /** * Report the beginning of an entity. * * @param name The name of the entity. If it is a parameter entity, the * name will begin with '%'. */ public void startEntity(String name) throws SAXException { if (!this.processing) { super.startEntity(name); } else if (this.ch != null){ this.ch.startEntity(name); } } /** * Report the end of an entity. * * @param name The name of the entity that is ending. */ public void endEntity(String name) throws SAXException { if (!this.processing) { super.endEntity(name); } else if (this.ch != null){ this.ch.endEntity(name); } } /** * Report the start of a CDATA section. */ public void startCDATA() throws SAXException { if (!this.processing) { super.startCDATA(); } else if (this.ch != null){ this.ch.startCDATA(); } } /** * Report the end of a CDATA section. */ public void endCDATA() throws SAXException { if (!this.processing) { super.endCDATA(); } else if (this.ch != null){ this.ch.endCDATA(); } } /** * Report an XML comment anywhere in the document. * * @param ch An array holding the characters in the comment. * @param start The starting position in the array. * @param len The number of characters to use from the array. */ public void comment(char ch[], int start, int len) throws SAXException { if (!this.processing) { super.comment(ch,start,len); } else if (this.ch != null){ this.ch.comment(ch,start,len); } } public void recycle() { this.sourceResolver = null; } /** * dispose */ public void dispose() { } }
---------------------------------------------------------------------- In case of troubles, e-mail: [EMAIL PROTECTED] To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]