aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-examples/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'velocity-engine-examples/src/main')
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContext.java190
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContextTest.java76
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/EventExample.java564
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/Example.java126
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/Example2.java116
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/TreeMapContext.java84
-rw-r--r--velocity-engine-examples/src/main/java/org/apache/velocity/example/XMLTest.java121
-rw-r--r--velocity-engine-examples/src/main/resources/dbtest.vm18
-rw-r--r--velocity-engine-examples/src/main/resources/example1.vm32
-rw-r--r--velocity-engine-examples/src/main/resources/example2.vm17
-rw-r--r--velocity-engine-examples/src/main/resources/test.xml44
-rw-r--r--velocity-engine-examples/src/main/resources/velocity.properties20
-rw-r--r--velocity-engine-examples/src/main/resources/xml.vm42
13 files changed, 1450 insertions, 0 deletions
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContext.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContext.java
new file mode 100644
index 00000000..c6e64ea6
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContext.java
@@ -0,0 +1,190 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.context.AbstractContext;
+import org.apache.velocity.context.Context;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.Statement;
+
+/**
+ * Example context impl that uses a database to store stuff :)
+ *
+ * yes, this is silly
+ *
+ * expects a mysql db test with table
+ *
+ * CREATE TABLE contextstore (
+ * k varchar(100),
+ * val blob
+ * );
+ *
+ * very fragile, crappy code.... just a demo!
+ *
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+
+public class DBContext extends AbstractContext
+{
+ Connection conn = null;
+
+ public DBContext()
+ {
+ super();
+ setup();
+ }
+
+ public DBContext( Context inner )
+ {
+ super( inner );
+ setup();
+ }
+
+ /**
+ * retrieves a serialized object from the db
+ * and returns the living instance to the
+ * caller.
+ */
+ @Override
+ public Object internalGet(String key )
+ {
+ try
+ {
+ String sql = "SELECT val FROM contextstore WHERE k ='"+key+"'";
+ Statement s = conn.createStatement();
+ ResultSet rs = s.executeQuery( sql );
+
+ Object o = null;
+ ObjectInputStream in = null;
+
+ if(rs.next())
+ {
+ in = new ObjectInputStream( rs.getBinaryStream(1) );
+ o = in.readObject();
+ in.close();
+ }
+
+ rs.close();
+ s.close();
+
+ return o;
+ }
+ catch(Exception e)
+ {
+ System.out.println("internalGet() : " + e );
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ /**
+ * Serializes and stores an object in the database.
+ * This is really a hokey way to do it, and will
+ * cause problems. The right way is to use a
+ * prepared statement...
+ */
+ @Override
+ public Object internalPut(String key, Object value )
+ {
+ try
+ {
+ Statement s = conn.createStatement();
+ s.executeUpdate( "DELETE FROM contextstore WHERE k = '" + key + "'" );
+ s.close();
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream out = new ObjectOutputStream( baos );
+ out.writeObject( value );
+ byte buf[] = baos.toByteArray();
+ out.close();
+ baos.close();
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(buf);
+ PreparedStatement ps = conn.prepareStatement( "INSERT INTO contextstore (k,val) values ('"+key+"', ?)");
+ ps.setBinaryStream(1, bais, buf.length);
+ ps.executeUpdate();
+ ps.close();
+
+ }
+ catch(Exception e)
+ {
+ System.out.println("internalGet() : " + e );
+ }
+
+ return null;
+ }
+
+ /**
+ * Not implementing. Not required for Velocity core
+ * operation, so not bothering. As we say above :
+ * "very fragile, crappy code..."
+ */
+ @Override
+ public boolean internalContainsKey(String key)
+ {
+ return false;
+ }
+
+ /**
+ * Not implementing. Not required for Velocity core
+ * operation, so not bothering. As we say above :
+ * "very fragile, crappy code..."
+ */
+ @Override
+ public String[] internalGetKeys()
+ {
+ return null;
+ }
+
+ /**
+ * Not implementing. Not required for Velocity core
+ * operation, so not bothering. As we say above :
+ * "very fragile, crappy code..."
+ */
+ @Override
+ public Object internalRemove(String key)
+ {
+ return null;
+ }
+
+
+ private void setup()
+ {
+ try
+ {
+ Class.forName("com.mysql.cj.jdbc.Driver");
+ conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=YOUR_DB_USER&password=YOUR_DB_PASSWORD");
+ }
+ catch (Exception e)
+ {
+ System. out.println(e);
+ }
+ }
+}
+
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContextTest.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContextTest.java
new file mode 100644
index 00000000..4c123204
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/DBContextTest.java
@@ -0,0 +1,76 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.Template;
+import org.apache.velocity.runtime.RuntimeSingleton;
+
+import java.io.BufferedWriter;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.Hashtable;
+import java.util.Properties;
+
+/**
+ * the ultimate in silliness...
+ *
+ * tests the DBContext example by putting a string and a hashtable
+ * into the context and then rendering a simple template with it.
+ *
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+
+public class DBContextTest
+{
+ public DBContextTest(String templateFile)
+ {
+ try
+ {
+ RuntimeSingleton.init( new Properties() );
+
+ Template template = RuntimeSingleton.getTemplate(templateFile);
+
+ DBContext dbc = new DBContext();
+
+ Hashtable h = new Hashtable();
+ h.put("Bar", "this is from a hashtable!");
+
+ dbc.put( "string", "Hello!");
+ dbc.put( "hashtable", h );
+
+ Writer writer = new BufferedWriter(new OutputStreamWriter(System.out));
+
+ template.merge(dbc, writer);
+
+ writer.flush();
+ writer.close();
+ }
+ catch( Exception e )
+ {
+ RuntimeSingleton.getLog().error("Something funny happened", e);
+ }
+ }
+
+ public static void main(String[] args)
+ {
+ DBContextTest t;
+ t = new DBContextTest(args[0]);
+ }
+}
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/EventExample.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/EventExample.java
new file mode 100644
index 00000000..610039b1
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/EventExample.java
@@ -0,0 +1,564 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.app.event.EventCartridge;
+import org.apache.velocity.app.event.InvalidReferenceEventHandler;
+import org.apache.velocity.app.event.MethodExceptionEventHandler;
+import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
+import org.apache.velocity.context.Context;
+import org.apache.velocity.exception.MethodInvocationException;
+import org.apache.velocity.exception.ParseErrorException;
+import org.apache.velocity.util.introspection.Info;
+
+import org.slf4j.helpers.FormattingTuple;
+import org.slf4j.helpers.MarkerIgnoringBase;
+import org.slf4j.helpers.MessageFormatter;
+
+import java.io.StringWriter;
+
+/**
+ * This class is a simple demonstration of how the event handling
+ * features of the Velocity Servlet Engine are used. It uses a
+ * custom logger as well to check the log message stream
+ * when testing the InvalidReferenceEventHandler.
+ *
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+
+public class EventExample extends MarkerIgnoringBase
+ implements ReferenceInsertionEventHandler, MethodExceptionEventHandler, InvalidReferenceEventHandler
+{
+ private boolean logOutput = false;
+ private boolean exceptionSwitch = false;
+
+ public static void main( String args[] )
+ {
+ EventExample ee = new EventExample();
+ }
+
+ public EventExample()
+ {
+ try
+ {
+ /*
+ * this class implements the Logger interface, so we
+ * can use it as a logger for Velocity
+ */
+
+ Velocity.setProperty(Velocity.RUNTIME_LOG_INSTANCE, this );
+ Velocity.init();
+ }
+ catch(Exception e)
+ {
+ System.out.println("Problem initializing Velocity : " + e );
+ return;
+ }
+
+ /*
+ * lets make a Context and add some data
+ */
+
+ VelocityContext context = new VelocityContext();
+
+ context.put("name", "Velocity");
+
+ /*
+ * Now make an event cartridge, register all the
+ * event handlers (at once) and attach it to the
+ * Context
+ */
+
+ EventCartridge ec = new EventCartridge();
+ ec.addEventHandler(this);
+ ec.attachToContext( context );
+
+ try
+ {
+ /*
+ * lets test each type of event handler individually
+ * using 'dynamic' templates
+ *
+ * First, the reference insertion handler
+ */
+
+ System.out.println("");
+ System.out.println("Velocity Event Handling Demo");
+ System.out.println("============================");
+ System.out.println("");
+
+ String s = "The word 'Velocity' should be bounded by emoticons : $name.";
+
+ StringWriter w = new StringWriter();
+ Velocity.evaluate( context, w, "mystring", s );
+
+ System.out.println("Reference Insertion Test : ");
+ System.out.println(" " + w.toString());
+ System.out.println("");
+
+ /*
+ * using the same handler, we can deal with
+ * null references as well
+ */
+
+ s = "There is no reference $floobie, $nullvalue or anything in the brackets : >$!silentnull<";
+
+ w = new StringWriter();
+ Velocity.evaluate( context, w, "mystring", s );
+
+ System.out.println("Reference Insertion Test with null references : ");
+ System.out.println(" " + w.toString());
+ System.out.println("");
+
+ /*
+ * now lets test setting a null value - this test
+ * should result in *no* log output.
+ * Turn on the logger output.
+ */
+
+ logOutput = true;
+
+ s = "#set($settest = $NotAReference)";
+ w = new StringWriter();
+
+ System.out.println("invalidSetMethod test : " );
+ System.out.print(" There should be nothing between >");
+ Velocity.evaluate( context, w, "mystring", s );
+ System.out.println("< the brackets.");
+ System.out.println("");
+
+ /*
+ * now lets test setting a null value - this test
+ * should result in log output.
+ */
+
+ s = "#set($logthis = $NotAReference)";
+ w = new StringWriter();
+
+ System.out.println("invalidSetMethod test : " );
+ System.out.print(" There should be a log message between >");
+ Velocity.evaluate( context, w, "mystring", s );
+ System.out.println("< the brackets.");
+ System.out.println("");
+
+ logOutput = false;
+
+ /*
+ * finally, we test a method exception event - we do this
+ * by putting this class in the context, and calling
+ * a method that does nothing but throw an exception.
+ * we use a little switch to turn the event handling
+ * on and off
+ *
+ * Note also how the reference insertion process
+ * happens as well
+ */
+
+ exceptionSwitch = true;
+
+ context.put("this", this );
+
+ s = " $this.throwException()";
+ w = new StringWriter();
+
+ System.out.println("MethodExceptionEventHandler test : " );
+ System.out.print(" This exception will be controlled and converted into a string : ");
+ Velocity.evaluate( context, w, "mystring", s );
+ System.out.println(" " + w.toString());
+ System.out.println("");
+
+ /*
+ * now, we turn the switch off, and we can see that the
+ * exception will propgate all the way up here, and
+ * wil be caught by the catch() block below
+ */
+
+ exceptionSwitch = false;
+
+ s = " $this.throwException()";
+ w = new StringWriter();
+
+ System.out.println("MethodExceptionEventHandler test : " );
+ System.out.println(" This exception will NOT be controlled. "
+ + " The next thing you should see is the catch() output ");
+ Velocity.evaluate( context, w, "mystring", s );
+ System.out.println("If you see this, it didn't work!");
+
+ }
+ catch( ParseErrorException pee )
+ {
+ /*
+ * thrown if something is wrong with the
+ * syntax of our template string
+ */
+ System.out.println("ParseErrorException : " + pee );
+ }
+ catch( MethodInvocationException mee )
+ {
+ /*
+ * thrown if a method of a reference
+ * called by the template
+ * throws an exception. That won't happen here
+ * as we aren't calling any methods in this
+ * example, but we have to catch them anyway
+ */
+ System.out.println(" Catch Block : MethodInvocationException : " + mee );
+ }
+ catch( Exception e )
+ {
+ System.out.println("Exception : " + e );
+ }
+ }
+
+ /**
+ * silly method to throw an exception to demonstrate
+ * the method invocation exception event handling
+ */
+ public void throwException()
+ throws Exception
+ {
+ throw new Exception("Hello from throwException()");
+ }
+
+ /**
+ * Event handler for when a reference is inserted into the output stream.
+ */
+ @Override
+ public Object referenceInsert(Context context, String reference, Object value )
+ {
+ /*
+ * if we have a value
+ * lets decorate the reference with emoticons
+ */
+
+ String s = null;
+
+ if( value != null )
+ {
+ s = " ;) " + value.toString() + " :-)";
+ }
+ else
+ {
+ /*
+ * we only want to deal with $floobie - anything
+ * else we let go
+ */
+ if ( reference.equals("floobie") )
+ {
+ s = "<no floobie value>";
+ }
+ }
+ return s;
+ }
+
+ /**
+ */
+
+ @Override
+ public Object invalidGetMethod(Context context, String reference, Object object, String property, Info info)
+ {
+ /* NOP */
+ return null;
+ }
+
+ @Override
+ public Object invalidMethod(Context context, String reference, Object object, String method, Info info)
+ {
+ /* NOP */
+ return null;
+ }
+
+ /**
+ * Event handler for when the right hand side of
+ * a #set() directive is null, which results in
+ * a log message. This method gives the application
+ * a chance to 'vote' on msg generation
+ */
+ @Override
+ public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
+ {
+ if (leftreference.equals("logthis"))
+ {
+ System.out.print("Setting reference " + leftreference + " to null");
+ }
+ return false;
+ }
+
+ @Override
+ public Object methodException(Context context, Class claz, String method, Exception e, Info info ) {
+ /*
+ * only do processing if the switch is on
+ */
+
+ if( exceptionSwitch && method.equals("throwException"))
+ {
+ return "Hello from the methodException() event handler method.";
+ }
+
+ throw new RuntimeException(e);
+ }
+
+ /*
+ * Our own logging towards System.out
+ */
+
+ /**
+ * This just prints the message and level to System.out.
+ */
+ public void log(int level, String message)
+ {
+ if (logOutput)
+ {
+ System.out.println("level : " + level + " msg : " + message);
+ }
+ }
+
+
+ /**
+ * This prints the level, message, and the Throwable's message to
+ * System.out.
+ */
+ public void log(int level, String message, Throwable t)
+ {
+ if (logOutput)
+ {
+ System.out.println("level : " + level + " msg : " + message + " t : "
+ + t.getMessage());
+ }
+ }
+
+ /**
+ * This prints the level and formatted message to
+ * System.out.
+ */
+ public void formatAndLog(int level, String format, Object... arguments)
+ {
+ if (logOutput)
+ {
+ FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments);
+ log(level, tp.getMessage());
+ }
+ }
+
+ /**
+ * This always returns true because logging levels can't be disabled in
+ * this impl.
+ */
+ public boolean isLevelEnabled(int level)
+ {
+ return true;
+ }
+
+ public static final int LOG_LEVEL_TRACE = 1;
+ public static final int LOG_LEVEL_DEBUG = 2;
+ public static final int LOG_LEVEL_INFO = 3;
+ public static final int LOG_LEVEL_WARN = 4;
+ public static final int LOG_LEVEL_ERROR = 5;
+
+ /**
+ * Required init methods for Logger interface
+ */
+
+ @Override
+ public String getName()
+ {
+ return "EventExample";
+ }
+
+ @Override
+ public boolean isTraceEnabled() {
+ return isLevelEnabled(LOG_LEVEL_TRACE);
+ }
+
+ @Override
+ public void trace(String msg) {
+ log(LOG_LEVEL_TRACE, msg);
+ }
+
+ @Override
+ public void trace(String format, Object param1)
+ {
+ formatAndLog(LOG_LEVEL_TRACE, format, param1);
+ }
+
+ @Override
+ public void trace(String format, Object param1, Object param2)
+ {
+ formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
+ }
+
+ @Override
+ public void trace(String format, Object... argArray)
+ {
+ formatAndLog(LOG_LEVEL_TRACE, format, argArray);
+ }
+
+ @Override
+ public void trace(String msg, Throwable t)
+ {
+ log(LOG_LEVEL_TRACE, msg, t);
+ }
+
+ @Override
+ public boolean isDebugEnabled()
+ {
+ return isLevelEnabled(LOG_LEVEL_DEBUG);
+ }
+
+ @Override
+ public void debug(String msg)
+ {
+ log(LOG_LEVEL_DEBUG, msg);
+ }
+
+ @Override
+ public void debug(String format, Object param1)
+ {
+ formatAndLog(LOG_LEVEL_DEBUG, format, param1);
+ }
+
+ @Override
+ public void debug(String format, Object param1, Object param2)
+ {
+ formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
+ }
+
+ @Override
+ public void debug(String format, Object... argArray)
+ {
+ formatAndLog(LOG_LEVEL_DEBUG, format, argArray);
+ }
+
+ @Override
+ public void debug(String msg, Throwable t)
+ {
+ log(LOG_LEVEL_DEBUG, msg, t);
+ }
+
+ @Override
+ public boolean isInfoEnabled()
+ {
+ return isLevelEnabled(LOG_LEVEL_INFO);
+ }
+
+ @Override
+ public void info(String msg)
+ {
+ log(LOG_LEVEL_INFO, msg);
+ }
+
+ @Override
+ public void info(String format, Object arg)
+ {
+ formatAndLog(LOG_LEVEL_INFO, format, arg);
+ }
+
+ @Override
+ public void info(String format, Object arg1, Object arg2)
+ {
+ formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
+ }
+
+ @Override
+ public void info(String format, Object... argArray)
+ {
+ formatAndLog(LOG_LEVEL_INFO, format, argArray);
+ }
+
+ @Override
+ public void info(String msg, Throwable t)
+ {
+ log(LOG_LEVEL_INFO, msg, t);
+ }
+
+ @Override
+ public boolean isWarnEnabled()
+ {
+ return isLevelEnabled(LOG_LEVEL_WARN);
+ }
+
+ @Override
+ public void warn(String msg)
+ {
+ log(LOG_LEVEL_WARN, msg);
+ }
+
+ @Override
+ public void warn(String format, Object arg)
+ {
+ formatAndLog(LOG_LEVEL_WARN, format, arg);
+ }
+
+ @Override
+ public void warn(String format, Object arg1, Object arg2)
+ {
+ formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
+ }
+
+ @Override
+ public void warn(String format, Object... argArray)
+ {
+ formatAndLog(LOG_LEVEL_WARN, format, argArray);
+ }
+
+ @Override
+ public void warn(String msg, Throwable t)
+ {
+ log(LOG_LEVEL_WARN, msg, t);
+ }
+
+ @Override
+ public boolean isErrorEnabled()
+ {
+ return isLevelEnabled(LOG_LEVEL_ERROR);
+ }
+
+ @Override
+ public void error(String msg)
+ {
+ log(LOG_LEVEL_ERROR, msg);
+ }
+
+ @Override
+ public void error(String format, Object arg)
+ {
+ formatAndLog(LOG_LEVEL_ERROR, format, arg);
+ }
+
+ @Override
+ public void error(String format, Object arg1, Object arg2)
+ {
+ formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
+ }
+
+ @Override
+ public void error(String format, Object... argArray)
+ {
+ formatAndLog(LOG_LEVEL_ERROR, format, argArray);
+ }
+
+ @Override
+ public void error(String msg, Throwable t)
+ {
+ log(LOG_LEVEL_ERROR, msg, t);
+ }
+}
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/Example.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/Example.java
new file mode 100644
index 00000000..7717f382
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/Example.java
@@ -0,0 +1,126 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.exception.ParseErrorException;
+import org.apache.velocity.exception.ResourceNotFoundException;
+
+import java.io.BufferedWriter;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+
+/**
+ * This class is a simple demonstration of how the Velocity Template Engine
+ * can be used in a standalone application.
+ *
+ * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+
+public class Example
+{
+ public Example(String templateFile)
+ {
+ try
+ {
+ /*
+ * setup
+ */
+
+ Velocity.init("velocity.properties");
+
+ /*
+ * Make a context object and populate with the data. This
+ * is where the Velocity engine gets the data to resolve the
+ * references (ex. $list) in the template
+ */
+
+ VelocityContext context = new VelocityContext();
+ context.put("list", getNames());
+
+ /*
+ * get the Template object. This is the parsed version of your
+ * template input file. Note that getTemplate() can throw
+ * ResourceNotFoundException : if it doesn't find the template
+ * ParseErrorException : if there is something wrong with the VTL
+ * Exception : if something else goes wrong (this is generally
+ * indicative of as serious problem...)
+ */
+
+ Template template = null;
+
+ try
+ {
+ template = Velocity.getTemplate(templateFile);
+ }
+ catch( ResourceNotFoundException rnfe )
+ {
+ System.out.println("Example : error : cannot find template " + templateFile );
+ }
+ catch( ParseErrorException pee )
+ {
+ System.out.println("Example : Syntax error in template " + templateFile + ":" + pee );
+ }
+
+ /*
+ * Now have the template engine process your template using the
+ * data placed into the context. Think of it as a 'merge'
+ * of the template and the data to produce the output stream.
+ */
+
+ BufferedWriter writer = new BufferedWriter(
+ new OutputStreamWriter(System.out));
+
+ if ( template != null)
+ template.merge(context, writer);
+
+ /*
+ * flush and cleanup
+ */
+
+ writer.flush();
+ writer.close();
+ }
+ catch( Exception e )
+ {
+ System.out.println(e);
+ }
+ }
+
+ public ArrayList getNames()
+ {
+ ArrayList list = new ArrayList();
+
+ list.add("ArrayList element 1");
+ list.add("ArrayList element 2");
+ list.add("ArrayList element 3");
+ list.add("ArrayList element 4");
+
+ return list;
+ }
+
+ public static void main(String[] args)
+ {
+ Example t = new Example(args[0]);
+ }
+}
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/Example2.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/Example2.java
new file mode 100644
index 00000000..bf3546a6
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/Example2.java
@@ -0,0 +1,116 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.exception.MethodInvocationException;
+import org.apache.velocity.exception.ParseErrorException;
+
+import java.io.StringWriter;
+
+/**
+ * This class is a simple demonstration of how the Velocity Template Engine
+ * can be used in a standalone application using the Velocity utility class.
+ *
+ * It demonstrates two of the 'helper' methods found in the org.apache.velocity.util.Velocity
+ * class, mergeTemplate() and evaluate().
+ *
+ *
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+
+public class Example2
+{
+ public static void main( String args[] )
+ {
+ /* first, we init the runtime engine. Defaults are fine. */
+
+ try
+ {
+ Velocity.init();
+ }
+ catch(Exception e)
+ {
+ System.out.println("Problem initializing Velocity : " + e );
+ return;
+ }
+
+ /* lets make a Context and put data into it */
+
+ VelocityContext context = new VelocityContext();
+
+ context.put("name", "Velocity");
+ context.put("project", "Engine");
+
+ /* lets render a template */
+
+ StringWriter w = new StringWriter();
+
+ try
+ {
+ Velocity.mergeTemplate("example2.vm", "ISO-8859-1", context, w );
+ }
+ catch (Exception e )
+ {
+ System.out.println("Problem merging template : " + e );
+ }
+
+ System.out.println(" template : " + w );
+
+ /*
+ * lets dynamically 'create' our template
+ * and use the evaluate() method to render it
+ */
+
+ String s = "We are using $project $name to render this.";
+ w = new StringWriter();
+
+ try
+ {
+ Velocity.evaluate( context, w, "mystring", s );
+ }
+ catch( ParseErrorException pee )
+ {
+ /*
+ * thrown if something is wrong with the
+ * syntax of our template string
+ */
+ System.out.println("ParseErrorException : " + pee );
+ }
+ catch( MethodInvocationException mee )
+ {
+ /*
+ * thrown if a method of a reference
+ * called by the template
+ * throws an exception. That won't happen here
+ * as we aren't calling any methods in this
+ * example, but we have to catch them anyway
+ */
+ System.out.println("MethodInvocationException : " + mee );
+ }
+ catch( Exception e )
+ {
+ System.out.println("Exception : " + e );
+ }
+
+ System.out.println(" string : " + w );
+ }
+}
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/TreeMapContext.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/TreeMapContext.java
new file mode 100644
index 00000000..40a6dce5
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/TreeMapContext.java
@@ -0,0 +1,84 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.context.AbstractContext;
+import org.apache.velocity.context.Context;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * Example context impl that uses a TreeMap
+ *
+ * Not much point other than to show how easy it is.
+ *
+ * This is unsupported, example code.
+ *
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+
+public class TreeMapContext extends AbstractContext
+{
+ private Map<String, Object> context = new TreeMap<>();
+
+ public TreeMapContext()
+ {
+ super();
+ }
+
+ public TreeMapContext( Context inner )
+ {
+ super( inner );
+ }
+
+ @Override
+ public Object internalGet(String key )
+ {
+ return context.get( key );
+ }
+
+ @Override
+ public Object internalPut(String key, Object value )
+ {
+ return context.put( key, value );
+ }
+
+ @Override
+ public boolean internalContainsKey(String key)
+ {
+ return context.containsKey( key );
+ }
+
+ @Override
+ public String[] internalGetKeys()
+ {
+ Set<String> keys = context.keySet();
+ return keys.toArray(new String[keys.size()]);
+ }
+
+ @Override
+ public Object internalRemove(String key)
+ {
+ return context.remove( key );
+ }
+}
+
diff --git a/velocity-engine-examples/src/main/java/org/apache/velocity/example/XMLTest.java b/velocity-engine-examples/src/main/java/org/apache/velocity/example/XMLTest.java
new file mode 100644
index 00000000..78cba681
--- /dev/null
+++ b/velocity-engine-examples/src/main/java/org/apache/velocity/example/XMLTest.java
@@ -0,0 +1,121 @@
+package org.apache.velocity.example;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.Velocity;
+
+import org.jdom.Document;
+import org.jdom.input.SAXBuilder;
+
+import java.io.BufferedWriter;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+
+/**
+ * Example to show basic XML handling in a template.
+ *
+ * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
+ * @version $Id$
+ */
+public class XMLTest
+{
+ public XMLTest( String templateFile)
+ {
+ Writer writer = null;
+
+ try
+ {
+ /*
+ * and now call init
+ */
+
+ Velocity.init();
+
+
+ /*
+ * build a Document from our xml
+ */
+
+ SAXBuilder builder;
+ Document root = null;
+
+ try
+ {
+ builder = new SAXBuilder();
+ root = builder.build("test.xml");
+ }
+ catch( Exception ee)
+ {
+ System.out.println("Exception building Document : " + ee);
+ return;
+ }
+
+ /*
+ * now, make a Context object and populate it.
+ */
+
+ VelocityContext context = new VelocityContext();
+ context.put("root", root);
+
+ /*
+ * make a writer, and merge the template 'against' the context
+ */
+
+ Template template = Velocity.getTemplate(templateFile);
+
+ writer = new BufferedWriter(new OutputStreamWriter(System.out));
+ template.merge( context , writer);
+ }
+ catch( Exception e )
+ {
+ System.out.println("Exception : " + e);
+ }
+ finally
+ {
+ if ( writer != null)
+ {
+ try
+ {
+ writer.flush();
+ writer.close();
+ }
+ catch( Exception ee )
+ {
+ System.out.println("Exception : " + ee );
+ }
+ }
+ }
+ }
+
+ public static void main(String[] args)
+ {
+ XMLTest t;
+
+ if( args.length < 1 )
+ {
+ System.out.println("Usage : java XMLTest <templatename>");
+ return;
+ }
+
+ t = new XMLTest(args[0]);
+ }
+}
diff --git a/velocity-engine-examples/src/main/resources/dbtest.vm b/velocity-engine-examples/src/main/resources/dbtest.vm
new file mode 100644
index 00000000..1ee3979e
--- /dev/null
+++ b/velocity-engine-examples/src/main/resources/dbtest.vm
@@ -0,0 +1,18 @@
+## Licensed to the Apache Software Foundation (ASF) under one
+## or more contributor license agreements. See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership. The ASF licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing,
+## software distributed under the License is distributed on an
+## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+## KIND, either express or implied. See the License for the
+## specific language governing permissions and limitations
+## under the License.
+$string
+$hashtable.Bar
diff --git a/velocity-engine-examples/src/main/resources/example1.vm b/velocity-engine-examples/src/main/resources/example1.vm
new file mode 100644
index 00000000..7b17de21
--- /dev/null
+++ b/velocity-engine-examples/src/main/resources/example1.vm
@@ -0,0 +1,32 @@
+## Licensed to the Apache Software Foundation (ASF) under one
+## or more contributor license agreements. See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership. The ASF licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing,
+## software distributed under the License is distributed on an
+## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+## KIND, either express or implied. See the License for the
+## specific language governing permissions and limitations
+## under the License.
+
+#set( $this = "Velocity")
+
+$this is great!
+
+#foreach( $name in $list )
+ $name is great!
+#end
+
+#set( $condition = true)
+
+#if ($condition)
+ The condition is true!
+#else
+ The condition is false!
+#end
diff --git a/velocity-engine-examples/src/main/resources/example2.vm b/velocity-engine-examples/src/main/resources/example2.vm
new file mode 100644
index 00000000..27738c13
--- /dev/null
+++ b/velocity-engine-examples/src/main/resources/example2.vm
@@ -0,0 +1,17 @@
+## Licensed to the Apache Software Foundation (ASF) under one
+## or more contributor license agreements. See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership. The ASF licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing,
+## software distributed under the License is distributed on an
+## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+## KIND, either express or implied. See the License for the
+## specific language governing permissions and limitations
+## under the License.
+Hello from $name in the $project project.
diff --git a/velocity-engine-examples/src/main/resources/test.xml b/velocity-engine-examples/src/main/resources/test.xml
new file mode 100644
index 00000000..a76ce44a
--- /dev/null
+++ b/velocity-engine-examples/src/main/resources/test.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+<document>
+ <properties>
+ <author>
+ <email>user@velocity.apache.org</email>
+ <name>
+ <last>
+ <full>Team</full>
+ <firstinitial>T</firstinitial>
+ </last>
+ <first>
+ Velocity
+ </first>
+ </name>
+ </author>
+ <title>
+ The Velocity Project
+ </title>
+ </properties>
+
+ <body>
+ I am the body
+ </body>
+</document>
diff --git a/velocity-engine-examples/src/main/resources/velocity.properties b/velocity-engine-examples/src/main/resources/velocity.properties
new file mode 100644
index 00000000..00a7ec66
--- /dev/null
+++ b/velocity-engine-examples/src/main/resources/velocity.properties
@@ -0,0 +1,20 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Here you can configure Velocity behavior,
+# see http://velocity.apache.org/engine/${project.version}/configuration.html#configuring-velocity
+runtime.log.name = velocity
diff --git a/velocity-engine-examples/src/main/resources/xml.vm b/velocity-engine-examples/src/main/resources/xml.vm
new file mode 100644
index 00000000..366b79b1
--- /dev/null
+++ b/velocity-engine-examples/src/main/resources/xml.vm
@@ -0,0 +1,42 @@
+## Licensed to the Apache Software Foundation (ASF) under one
+## or more contributor license agreements. See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership. The ASF licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing,
+## software distributed under the License is distributed on an
+## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+## KIND, either express or implied. See the License for the
+## specific language governing permissions and limitations
+## under the License.
+#macro ( recursive $e $indent )
+#if( $e.getChildren().size() > 0 )
+$indent <$e.getName()>
+#foreach ($child in $e.getChildren() )
+#recursive( $child "$indent " )
+#end
+$indent </$e.getName()>
+#else
+$indent <$e.getName()>
+$indent $e.getTextTrim()
+$indent </$e.getName()>
+#end
+#end
+
+#set($i = " ")
+
+First, we print out the document tree with a
+recursive Velocimacro :
+
+#recursive( $root.getRootElement() $i )
+
+
+Next, we access pieces of data directly :
+
+email : $root.getRootElement().getChild("properties").getChild("author").getChild("email").getText()
+last name : $root.getRootElement().getChild("properties").getChild("author").getChild("name").getChild("last").getChild("full").getText()