geirm 01/12/18 13:23:15
Added: src/java/org/apache/tools/dvsl DVSL.java DVSLContext.java
DVSLNode.java DVSLNodeContext.java DVSLTask.java
TemplateHandler.java TransformTool.java
Transformer.java
Log:
initial check in
Revision Changes Path
1.1 jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/DVSL.java
Index: DVSL.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.List;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.io.Writer;
import java.io.StringWriter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.io.Reader;
import org.apache.velocity.context.Context;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
/**
* Main DVSL class - use this as the helper class for apps
*
* @author <a href="mailto:[EMAIL PROTECTED]">Geir Magnusson Jr.</a>
*/
public class DVSL
{
private static String TOOL_PROP_PREFIX = "toolbox.tool.";
private static String STRING_PROP_PREFIX = "toolbox.string.";
private static String INTEGER_PROP_PREFIX = "toolbox.integer.";
private static String TOOLBOX_NAME = "toolbox.contextname.";
private VelocityEngine ve = null;
private Document currentDocument = null;
private Writer currentWriter = null;
private Context toolContext;
private Context userContext;
private Context styleContext;
private DVSLContext baseContext = new DVSLContext();
private Transformer transformer;
private boolean ready = false;
private TemplateHandler templateHandler = new TemplateHandler();
public DVSL()
{
}
/**
* <p>
* Sets the user context. The user context is
* a Velocity Context containing user-supplied
* objects and data that are to be made available
* in the template
* </p>
*
* @param ctx User context of data
*/
public void setUserContext( Context ctx )
{
ready = false;
userContext = ctx;
}
/**
* <p>
* Loads the toolbox from the input Properties.
* </p>
*
* <p>
* Currently supports specification of the Toolbox
* name in the context, creating classes, and string
* and integer values. Ex :
* </p>
*
* <pre>
* toolbox.contextname = floyd
* toolbox.tool.footool = Footool
* toolbox.string.mystring = Hello there!
* toolbox.integer.myint = 7
* toolbox.string.sourcebase = ./xdocs/
* </pre>
*
* <p>
* So in template, this toolbox and it's values would
* be accessed as :
* </p>
* <pre>
* $context.floyd.footool.getFoo()
* $context.floyd.mystring
* $context.floyd.myint
* </pre>
*/
public void setToolbox( Properties p )
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
ready = false;
/*
* for each key that looks like
* toolbox.tool.<token> = class
*/
Map toolbox = new HashMap();
String toolboxname = "toolbox";
for( Enumeration e = p.propertyNames(); e.hasMoreElements(); )
{
String key = (String) e.nextElement();
String value = p.getProperty(key);
if ( key.startsWith( TOOL_PROP_PREFIX ))
{
String toolname = key.substring( TOOL_PROP_PREFIX.length());
Object o = Class.forName( value ).newInstance();
toolbox.put( toolname, o );
}
else if ( key.startsWith( INTEGER_PROP_PREFIX ) )
{
String toolname = key.substring( INTEGER_PROP_PREFIX.length());
int i = 0;
try
{
i = Integer.parseInt( value );
}
catch( Exception ee )
{
}
toolbox.put( toolname, new Integer(i) );
}
else if ( key.startsWith( STRING_PROP_PREFIX ) )
{
String toolname = key.substring( STRING_PROP_PREFIX.length());
toolbox.put( toolname, value );
}
else if ( key.startsWith( TOOLBOX_NAME ) )
{
toolboxname = value;
}
}
toolContext = new VelocityContext();
toolContext.put( toolboxname, toolbox );
}
/**
* Convenience function. See...
*/
public void setStylesheet( String stylesheet )
throws Exception
{
FileReader fr = null;
try
{
fr = new FileReader( stylesheet );
setStylesheet( fr );
}
catch( Exception e )
{
throw e;
}
finally
{
if (fr != null)
fr.close();
}
}
/**
* <p>
* Sets the stylesheet for this transformation set
* </p>
*
* <p>
* Note that don't need this for each document you want
* to transform. Just do it once, and transform away...
* </p>
*
* @param stylesheet Reader with stylesheet char stream
*/
public void setStylesheet( Reader styleReader )
throws Exception
{
ready = false;
/*
* now initialize Velocity - we need to do that
* on change of stylesheet
*/
ve = new VelocityEngine();
/*
* register our template() directive
*/
ve.setProperty("userdirective",
"org.apache.tools.dvsl.directive.MatchDirective");
ve.init();
/*
* add our template accumulator
*/
ve.setApplicationContext( templateHandler );
/*
* load and render the stylesheet
*
* this sets stylesheet specific context
* values
*/
StringWriter junkWriter = new StringWriter();
styleContext = new VelocityContext();
ve.evaluate( styleContext, junkWriter, "DVSL:stylesheet", styleReader );
/*
* now run the base template through for the rules
*/
InputStream is = this.getClass().getClassLoader().getResourceAsStream(
"org/apache/tools/dvsl/resource/defaultroot.dvsl");
if (is == null)
{
System.out.println("DEFAULT TRANSFORM RULES NOT FOUND ");
}
else
{
ve.evaluate( new VelocityContext(), junkWriter, "defaultroot.dvsl", new
InputStreamReader(is) );
is.close();
}
/*
* need a new transformer, as it depends on the
* velocity engine
*/
transformer = new Transformer( ve, templateHandler, baseContext );
}
/**
* sets up all the context goodies
*/
protected void makeReady()
{
/*
* put all the contexts together
*/
baseContext.clearContexts();
baseContext.addContext( userContext );
baseContext.addContext( toolContext );
baseContext.setStyleContext( styleContext );
}
/**
* does the transformation of the inputstream into
* the output writer
*/
protected long xform( Reader reader, Writer writer )
throws Exception
{
if (!ready)
makeReady();
return transformer.transform( reader, writer );
}
public long transform( File f, Writer writer )
throws Exception
{
Reader reader = null;
try
{
reader = new FileReader( f );
return xform( reader, writer );
}
catch( Exception e )
{
throw e;
}
finally
{
if ( reader != null)
{
reader.close();
}
}
}
public long transform( Reader reader, Writer writer )
throws Exception
{
return xform( reader, writer );
}
public long transform( InputStream is, Writer writer )
throws Exception
{
return xform( new InputStreamReader(is), writer );
}
public long transform( String infile, Writer writer )
throws Exception
{
Reader reader = null;
try
{
reader = new FileReader( infile );
return xform( reader, writer );
}
catch( Exception e )
{
throw e;
}
finally
{
if ( reader != null)
{
reader.close();
}
}
}
/**
* <p>
* Allows command-line access.
* </p>
* <p>
* Usage : java -jar dvsl.jar -STYLE stylesheeet [-IN infile] [-OUT outfile]
[-TOOL toolboxname]
* </p>
*/
public static void main(String[] args)
throws Exception
{
DVSL dvsl = new DVSL();
Reader in = new InputStreamReader(System.in);
String infile = null;
String style = null;
String outfile = null;
Writer out = new OutputStreamWriter( System.out );
String toolfile = null;
for( int i = 0; i < args.length; i++)
{
if ( args[i].equals("-IN"))
infile = args[++i];
else if (args[i].equals("-OUT" ) )
outfile = args[++i];
else if (args[i].equals("-STYLE" ) )
style = args[++i];
else if (args[i].equals("-TOOL" ) )
toolfile = args[++i];
}
if ( style == null)
{
System.out.println("usage :need to specify a stylesheet. ");
System.out.println("java -jar dvsl.jar -STYLE stylesheeet [-IN infile]
[-OUT outfile] [-TOOL toolboxname]");
return;
}
if ( style != null)
dvsl.setStylesheet( style );
if ( toolfile != null)
{
Properties p = new Properties();
InputStream fis = new FileInputStream( toolfile );
p.load( fis );
dvsl.setToolbox( p );
}
if ( infile != null)
in = new FileReader( infile );
if ( outfile != null)
out = new FileWriter( outfile );
long time = dvsl.transform( in, out );
}
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/DVSLContext.java
Index: DVSLContext.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Stack;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
/**
* Context implementation that handles wrapping several
* contexts simultaneously. The style context gets
* special treatment, getting checked first.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Geir Magnusson Jr.</a>
*/
class DVSLContext extends VelocityContext
{
protected Context styleContext = null;
protected List contextList = new ArrayList();
/**
* Used to hold the nodes as we get invoked from
* within the document for applyTemplates() duties
*/
private Stack nodeStack = new Stack();
protected Map ctx = new HashMap();
public DVSLNode pushNode( DVSLNode n )
{
nodeStack.push( n );
return n;
}
public DVSLNode peekNode()
{
return (DVSLNode) nodeStack.peek();
}
public DVSLNode popNode()
{
return (DVSLNode) nodeStack.pop();
}
public void clearNode()
{
nodeStack.clear();
return;
}
public void clearContexts()
{
styleContext = null;
contextList.clear();
}
public void addContext( Context c )
{
if (c != null)
contextList.add( c );
}
public void setStyleContext( Context c )
{
styleContext = c;
}
/**
* retrieves value for key from internal
* storage
*
* @param key name of value to get
* @return value as object
*/
public Object internalGet( String key )
{
Object o = null;
/*
* special tokens
*/
if ( key.equals("node"))
{
return peekNode();
}
/*
* start with local storage
*/
o = ctx.get( key );
if ( o != null)
return o;
/*
* if that doesn't work, try style first
* then others
*/
if ( styleContext != null)
{
o = styleContext.get( key );
if ( o != null )
return o;
}
for( int i = 0; i < contextList.size(); i++)
{
Context c = (Context) contextList.get( i );
o = c.get( key );
if ( o != null )
return o;
}
return null;
}
/**
* stores the value for key to internal
* storage
*
* @param key name of value to store
* @param value value to store
* @return previous value of key as Object
*/
public Object internalPut( String key, Object value )
{
if ( key.equals("node"))
return null;
return ctx.put( key, value );
}
/**
* determines if there is a value for the
* given key
*
* @param key name of value to check
* @return true if non-null value in store
*/
public boolean internalContainsKey(Object key)
{
/*
* start with local storage
*/
if ( ctx.containsKey( key ))
return true;
/*
* if that doesn't work, try style first
* then others
*/
if ( styleContext != null && styleContext.containsKey( key ) )
return true;
for( int i = 0; i < contextList.size(); i++)
{
Context c = (Context) contextList.get( i );
if ( c.containsKey( key ))
return true;
}
return false;
}
/**
* returns array of keys
*
* $$$ GMJ todo
*
* @return keys as []
*/
public Object[] internalGetKeys()
{
return null;
}
/**
* remove a key/value pair from the
* internal storage
*
* @param key name of value to remove
* @return value removed
*/
public Object internalRemove(Object key)
{
return ctx.remove( key );
}
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/DVSLNode.java
Index: DVSLNode.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.List;
import java.util.Map;
/**
* wrapper interface for nodes exposed in the
* template. Isolates the in-VSL DOM from that
* of the underlying implementation
*
* @author <a href="mailto:[EMAIL PROTECTED]">Geir Magnusson Jr.</a>
*/
public interface DVSLNode
{
/**
* returns the name of the node
*/
public String name();
/**
* returns the 'value' of the node
*/
public String value();
/**
* returns attribute
*/
public String attrib( String attribute );
/**
* returns a list of nodes that satisfy
* the xpath
*/
public List selectNodes( String xpath );
/**
* returns a single node that satisfies
* the xpath
*/
public DVSLNode selectSingleNode( String xpath );
public DVSLNode get( String xpath );
/**
* renders a deep copy of the XML tree
* below the current node to the output
*/
public String copy();
/**
* renders a deep copy of the nodes in
* the list ot the output
*/
public String copy( List nodeList );
/**
* returns a list of all children of the current
* node
*/
public List children();
/**
* returns the 'value' of the node
*/
public String toString();
/* ====================== */
/**
* returns the object corresponding to the node
* in the implementaion that we are using.
* use only with the greatest of care
*/
Object getNodeImpl();
Map getAttribMap();
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/DVSLNodeContext.java
Index: DVSLNodeContext.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Stack;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
/**
* <p>
* Context implementation that is the outer context
* during the transformation. Holds the node stack
* and also protects the 'special' context elements
* like 'node'
* </p>
* <p>
* There are special elements like 'node', which is
* readonly and corresponds to the current node, and
* 'attrib', which corresponds to a map of attributes
* for the current node.
* </p>
*
* @author <a href="mailto:[EMAIL PROTECTED]">Geir Magnusson Jr.</a>
*/
class DVSLNodeContext extends VelocityContext
{
/**
* Magic context entity that corresponds
* to the current node
*/
private final static String NODE = "node";
/**
* Magic context entity that corresponds to
* a Map of attributes for the current node
*/
private final static String ATTRIB = "attrib";
/**
* Used to hold the nodes as we get invoked from
* within the document for applyTemplates() duties
*/
private Stack nodeStack = new Stack();
protected Map ctx = new HashMap();
public DVSLNodeContext( Context context )
{
super(context );
}
private DVSLNodeContext()
{
}
/**
* retrieves value for key from internal
* storage
*
* @param key name of value to get
* @return value as object
*/
public Object internalGet( String key )
{
Object o = null;
/*
* special token : NODE
*
* returns current node
*/
if ( key.equals( NODE ))
{
return peekNode();
}
/*
* ATTRIB - returns attribute map
*/
if( key.equals( ATTRIB ) )
{
DVSLNode n = peekNode();
return n.getAttribMap();
}
/*
* start with local storage
*/
return ctx.get( key );
}
/**
* stores the value for key to internal
* storage
*
* @param key name of value to store
* @param value value to store
* @return previous value of key as Object
*/
public Object internalPut( String key, Object value )
{
/*
* protect both NODE and ATTRIB for now. We
* might want to let people set ATTRIB, but
* I suspect not
*/
if ( key.equals( NODE ))
return null;
if ( key.equals( ATTRIB ) )
return null;
return ctx.put( key, value );
}
/**
* determines if there is a value for the
* given key
*
* @param key name of value to check
* @return true if non-null value in store
*/
public boolean internalContainsKey(Object key)
{
return ctx.containsKey( key );
}
/**
* returns array of keys
*
* $$$ GMJ todo
*
* @return keys as []
*/
public Object[] internalGetKeys()
{
return null;
}
/**
* remove a key/value pair from the
* internal storage
*
* @param key name of value to remove
* @return value removed
*/
public Object internalRemove(Object key)
{
return ctx.remove( key );
}
/* === routines to manage current node stack === */
DVSLNode pushNode( DVSLNode n )
{
nodeStack.push( n );
return n;
}
DVSLNode peekNode()
{
return (DVSLNode) nodeStack.peek();
}
DVSLNode popNode()
{
return (DVSLNode) nodeStack.pop();
}
void clearNode()
{
nodeStack.clear();
return;
}
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/DVSLTask.java
Index: DVSLTask.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.Properties;
import java.io.Writer;
import java.io.FileWriter;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.velocity.VelocityContext;
/**
* Simple Ant task to mimic the behavior of the
* included Ant Style XSL task.
*
* Still needs :
* <style> only-on-change (also like Anakia)
* auto-output directory creation
*
* @author <a href="mailto:[EMAIL PROTECTED]">Geir Magnusson Jr.</a>
*/
public class DVSLTask extends MatchingTask
{
protected File basedir;
protected File destdir;
protected String stylesheet;
protected String toolboxProps;
protected String extension = ".html";
/*
* I wish they called this sourcedir in Style. grrr...
*/
public void setBasedir( File bd )
{
basedir = bd;
}
public void setDestdir( File dd )
{
destdir = dd;
}
public void setStyle( String style )
{
stylesheet = style;
}
public void setExtension( String ext )
{
extension = ext;
}
public void setToolbox( String toolbox )
{
toolboxProps = toolbox;
}
public void execute () throws BuildException
{
/*
* use the current project directory if no source dir set
*/
if (basedir == null)
{
basedir = project.resolveFile(".");
}
/*
* use the current directory as well. Will check to prevent that we don't
* overwrite the source
*/
if (destdir == null )
{
destdir = project.resolveFile(".");
}
/*
* must have a stylesheet
*/
if (stylesheet == null)
{
throw new BuildException("You must specify a stylesheet (.vsl file) with
the style parameter");
}
/*
* now just do it
*/
process();
}
/**
* does the real work. Gets the list of files to work on,
* and transforms each one
*/
protected void process()
throws BuildException
{
/*
* make a DVSL and set the stylesheet
*/
DVSL dvsl = new DVSL();
try
{
dvsl.setStylesheet( stylesheet );
}
catch( Exception e )
{
throw new BuildException("Problem setting stylesheet : " + e );
}
/*
* now, if we were given a toolbox, set that up too
*/
if ( toolboxProps != null)
{
try
{
Properties p = new Properties();
p.load( new FileInputStream( project.resolveFile( toolboxProps ) ) );
dvsl.setToolbox( p );
}
catch( Exception ee )
{
throw new BuildException( "Error loading the toolbox : " + ee );
}
}
/*
* get a list of the input files and process each one
*/
String[] infiles = getDirectoryScanner( basedir ).getIncludedFiles();
for (int i = 0;i < infiles.length; ++i)
{
/*
* get the infile and create the outfilename
*/
String infilename = infiles[i];
String root = infilename.substring( 0, infilename.lastIndexOf('.'));
String outfilename = root + extension;
Writer writer = null;
try
{
File infile = new File( basedir, infilename);
File outfile = new File( destdir, outfilename);
writer = new BufferedWriter( new FileWriter( outfile ) );
/*
* do the transformation
*/
long time = dvsl.transform( infile, writer );
log("Processed " + infilename + " to " + outfilename + " in " + time
+ " msec.");
}
catch( Exception e )
{
throw new BuildException( "Exception while procesing " + infilename
+ " : " + e );
}
finally
{
if (writer != null)
{
try
{
writer.flush();
writer.close();
}
catch( Exception ee )
{
}
}
}
}
log("Processing complete.");
}
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/TemplateHandler.java
Index: TemplateHandler.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.Writer;
import org.apache.velocity.context.InternalContextAdapterImpl;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.apache.velocity.context.Context;
import org.dom4j.DocumentHelper;
import org.dom4j.Document;
import org.dom4j.XPath;
import org.dom4j.Node;
import org.dom4j.rule.Pattern;
import org.dom4j.rule.Rule;
/**
* Currently provides the match rule accumulation
* as well as the AST storage and rendering
*
* Rule stuff might be replaced with the dom4j RuleManager
*
* @author <a href="mailto:[EMAIL PROTECTED]?">Geir Magnusson Jr.</a>
*/
public class TemplateHandler
{
private Map astmap = new HashMap();
private List xpathList = new ArrayList();
public void registerMatch( String xpath, SimpleNode node )
{
//System.out.println("registering : " + xpath );
Pattern pattern = DocumentHelper.createPattern( xpath );
Rule rule = new Rule( pattern );
Map foo = new HashMap();
foo.put("rule", rule );
foo.put("xpath", xpath );
foo.put("ast", node );
xpathList.add( foo );
}
boolean render( DVSLNode node, Context context, Writer writer )
throws Exception
{
/*
* find if we have an AST where the xpath expression mathes
* for this node
*/
Node dom4jnode = (Node) node.getNodeImpl();
SimpleNode sn = null;
for( int i = 0; i < xpathList.size(); i++ )
{
Map m = (Map) xpathList.get(i);
Rule xpathrule = (Rule) m.get("rule");
if( xpathrule.matches( dom4jnode ) )
{
sn = (SimpleNode) m.get( "ast" );
//System.out.println("using : " + (String) m.get("xpath") );
break;
}
}
if( sn == null)
; //System.out.println("Yikes : failed to find ast for '" +
node.getName() );
/*
* if we found something, render
*/
if( sn != null)
{
InternalContextAdapterImpl ica =
new InternalContextAdapterImpl( context );
ica.pushCurrentTemplateName( node.name() );
try
{
sn.render( ica, writer );
}
finally
{
ica.popCurrentTemplateName();
}
return true;
}
return false;
}
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/TransformTool.java
Index: TransformTool.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity","DVSL" 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
/**
* This is the tool interface exposed to the stylesheet.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Geir Magnusson Jr.</a>
*/
public interface TransformTool
{
/**
* <p>
* Applies templates in the current stylesheet
* to the nodeset returned by the XPath expression
* </p>
*
* <p>
* If the XPath expression is relative, then it is
* relative to the current node
* </p>
*
* @param xpath XPath expression to select nodes
* @return The rendered result
*/
public String applyTemplates( String xpath ) throws Exception;
public String applyTemplates( DVSLNode node ) throws Exception;
public String applyTemplates( DVSLNode node, String xpath ) throws Exception;
public String applyTemplates() throws Exception;
public String copy() throws Exception;
public Object get( String key );
}
1.1
jakarta-velocity-dvsl/src/java/org/apache/tools/dvsl/Transformer.java
Index: Transformer.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", 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 names without prior written
* permission of the Apache Group.
*
* 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 (INCLUDING, 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.dvsl;
import java.util.List;
import java.util.Stack;
import java.io.Writer;
import java.io.StringWriter;
import java.io.Reader;
import org.apache.velocity.context.Context;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.apache.tools.dvsl.dom4j.Dom4jNodeImpl;
/**
* <p>
* Class responsible for actual transformation
* of documents.
* </p>
*
* <p>
* Note that this class is <em>not</em> threadsafe.
* </p>
*
* @author <a href="mailto:[EMAIL PROTECTED]>Geir Magnusson Jr.</a>
*/
class Transformer implements TransformTool
{
/**
* Instance of VelocityEngine we are currently using.
* This must be reset with a stylesheeet change
*/
private VelocityEngine ve = null;
/**
* SAXReader that we reuse for every document. Much faster.
*/
private SAXReader saxReader = null;
/**
* basic context passed to us - can contain tools
* and such for use. Is protected from change via
* wrapping
*/
private Context baseContext;
/**
* context used during processing. Wraps the baseContext
*/
private DVSLNodeContext currentContext;
private TemplateHandler templateHandler = null;
/**
* Sole public CTOR. We rely on the caller to give us a
* VelocityEngine ready with all macros registered.
* The context is the callers context with all tools and
* style drek.
*/
public Transformer( VelocityEngine ve, TemplateHandler th, Context context )
{
this.ve = ve;
this.baseContext = context;
this.templateHandler = th;
saxReader = new SAXReader();
}
/**
* "Sealed for your protection."
*/
private Transformer()
{
}
/**
* Routine that performs the transformation on
* a document
*
* @param reader XML document char stream
* @param writer Writer to output transformation to
*/
long transform( Reader reader, Writer writer )
throws Exception
{
/*
* wrap in a context to keep subsequent documents from
* interacting with each other
*/
currentContext = new DVSLNodeContext( baseContext );
long start = System.currentTimeMillis();
/*
* parse the document
*/
Document document = saxReader.read( reader );
/*
* wrap the document. We do this as we let the dom4j package
* decide if we have a match against "/", so we need document
* to do that
*/
DVSLNode root = new Dom4jNodeImpl( document);
/*
* push 'this' into the context as our TransformTool
* and invoke the transformation
*/
currentContext.put( "context", this );
invoke( root, writer );
long end = System.currentTimeMillis();
return end-start;
}
private void invoke( DVSLNode element, Writer writer )
throws Exception
{
String[] arr = { };
currentContext.pushNode( element );
templateHandler.render( element, currentContext, writer );
currentContext.popNode();
}
public Object get( String key )
{
return currentContext.get( key );
}
public String applyTemplates( DVSLNode node, String xpath )
throws Exception
{
/*
* get the nodes that was asked for
*/
List nodeset = node.selectNodes( xpath );
StringWriter sw = new StringWriter();
for( int i = 0; i < nodeset.size(); i++)
{
// System.out.println("Apply (" + xpath + " : " + i + " : " +
( (DVSLNode) nodeset.get(i)).getNodeImpl() );
DVSLNode n = (DVSLNode) nodeset.get( i );
invoke( n, sw );
}
return sw.toString();
}
public String applyTemplates( DVSLNode node )
throws Exception
{
StringWriter sw = new StringWriter();
invoke( node, sw );
return sw.toString();
}
public String applyTemplates()
throws Exception
{
return applyTemplates( currentContext.peekNode(),
"*|@*|text()|comment()|processing-instruction()" );
}
public String applyTemplates( String path )
throws Exception
{
DVSLNode node = currentContext.peekNode();
return applyTemplates( node, path );
}
public String copy()
{
/*
* fakie, for now
*/
DVSLNode node = currentContext.peekNode();
return node.copy();
}
}
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>