velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Todd Marshall <Todd.Marsh...@Parago.Com>
Subject RE: Loading dynamically generated velocity templates
Date Wed, 21 May 2003 17:14:09 GMT
Yup, this will do the trick :)

Thank you very much.

BTW: I looked around for a searchable list archive, but couldn't find it....
Where does it live?

-----Original Message-----
From: Matthew Pomar [mailto:matthewpomar@hotmail.com] 
Sent: Wednesday, May 21, 2003 11:44 AM
To: Velocity Users List
Subject: Re: Loading dynamically generated velocity templates


Moshe,

Your 5/15 post work perfectly for me. Thanks for that effort.

Todd, I'll paste that code at the end of this message for your convenience.
You may have to fix wrapped lines as I did before the code will run, as well
as adjust the package path for the class that is being specified in the
properties of the class:
"org.apache.velocity.runtime.resource.loader.StringResourceLoader");

Regards,
Matthew Pomar


...

The last message which I sent recommended using StringBufferInputStream.
That class is deprecated and should not be used.

As pennance, here's an implementation of a proper StringResourceLoader.


----------

package org.apache.velocity.runtime.resource.loader;

import java.io.InputStream;
import java.io.ByteArrayInputStream;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

import java.util.HashMap;

// this section of imports is here just for the main() test method and it
// can be removed if main() is removed
import org.apache.velocity.app.Velocity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

/**
 * This resource loader can be used to create templates out of Strings.
 * Strings should be added to it at runtime via its setTemplate method.
 *
 * Created on May 15, 2003
 * @author Moshe Sambol
 */
public class StringResourceLoader extends ResourceLoader {

public static final String EMPTY_TEMPLATE_NAME =
"StringResourceLoader EMPTY TEMPLATE";

class TemplateDetails {
byte[] bodyBytes;
long lastModified;
}

private HashMap templates;

/**
* Initialize the template loader with a a resources class.
*/
public void init(ExtendedProperties arg0) {
templates = new HashMap();

// this is a hack so that later, the Velocity client code
will be able
// to retrieve a handle to this loader in order to add
templates to it
//  See main() test method below.
setTemplate(EMPTY_TEMPLATE_NAME, "");
}

/**
* Use this method to add a template String to this loader.
* If a template is already known with the given name then it will
be
* overwritten.
*/
public void setTemplate(String name, String body) {
TemplateDetails td = new TemplateDetails();
td.bodyBytes = body.getBytes();
td.lastModified = System.currentTimeMillis();
templates.put(name, td);
}

public void removeTemplate(String name) {
templates.remove(name);
}

public boolean hasTemplate(String name) {
return templates.containsKey(name);
}

/**
* Get the InputStream that the Runtime will parse to create a
template.
*/
public InputStream getResourceStream(String name)
throws ResourceNotFoundException {

if (templates.containsKey(name)) {
TemplateDetails td = (TemplateDetails)
templates.get(name);

return new ByteArrayInputStream(td.bodyBytes);
} else {
throw new ResourceNotFoundException("Template " +
name +

" not found.");
}
}

/**
* Given a template, check to see if the source of InputStream has
been
* modified.
*/
public boolean isSourceModified(Resource resource) {
TemplateDetails td = (TemplateDetails)
templates.get(resource.getName());
if (td == null) {
return false;
}
return (td.lastModified > resource.getLastModified());
}

/**
      * Get the last modified time of the InputStream source that was used
to
      * create the template. We need the template here because we have to
extract
      * the name of the template in order to locate the InputStream source.
*/
public long getLastModified(Resource resource) {
TemplateDetails td = (TemplateDetails)
templates.get(resource.getName());
if (td == null) {
return -1;
}
return td.lastModified;
}

public static void main(String args[]) {

java.util.Properties props = new java.util.Properties();

props.put("resource.loader","srs");

props.put("srs.resource.loader.public.name","StringResourceLoader");
props.put("srs.resource.loader.class",

"org.apache.velocity.runtime.resource.loader.StringResourceLoader");

try {
Velocity.init(props);
} catch (Exception e) {
System.out.println("Error Initializing
TemplateEngine: " +
e.getMessage());
return;
}

try {
// is there a cleaner way to get a reference to the
loader?
// I couldn't find one.
StringResourceLoader srs = (StringResourceLoader)

Velocity.getTemplate(StringResourceLoader.EMPTY_TEMPLATE_NAME).getResourceLo
ader();

srs.setTemplate("testEmail",
"dear $user, thanks for buying a $item!
Come back soon.");
srs.setTemplate("testSubject",
"thanks for shopping at $storeName");
} catch (Exception e) {
System.out.println("Error populating
StringResourceLoader: " +
e.getMessage());
return;
}

Template subject = null, message = null;

try {
subject = Velocity.getTemplate("testSubject");
message = Velocity.getTemplate("testEmail");
if ((subject == null) || (message == null)) {
System.out.println("template is null!");
return;
}

VelocityContext context = new VelocityContext();

context.put("user", "Peter Piper");
context.put("item", "pack of pickled peppers");
context.put("storeName", "Veggies R Us");

java.io.StringWriter sw = new
java.io.StringWriter();
sw.write("Subject: ");
subject.merge(context, sw);
sw.write("\nMessage: ");
message.merge(context, sw);

System.out.println(sw.toString());

} catch (Exception e) {
System.out.println("Exception merging template and
context:" +
e.getMessage());
e.printStackTrace();
}
}

}

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org



----- Original Message -----
From: "Moshe Sambol" <moshes@businesslayers.co.il>
To: "'Velocity Users List'" <velocity-user@jakarta.apache.org>
Sent: Wednesday, May 21, 2003 11:42 AM
Subject: RE: Loading dynamically generated velocity templates


> Todd,
>
> On 5/15 I posted code for a resource loader which would do this.  Check
the
> archive, the subject of the message was "RE: Template from String"
>
> Beware that my code hasn't been tested or verified by anyone else, but
it's
> pretty simple.  If nothing else it can serve as a starting point for you.
>
> -Moshe
>
>
>
> > -----Original Message-----
> > From: Todd Marshall [mailto:Todd.Marshall@Parago.Com]
> > Sent: Wednesday, May 21, 2003 7:26 PM
> > To: 'Velocity Users List'
> > Subject: Loading dynamically generated velocity templates
> >
> >
> > I'm working on a project that requires me to dynamically
> > generate velocity
> > templates that are then stored in a String object.   I'm now
> > trying to get
> > these strings into the velocity engine so they can be parsed
> > and rendered.
> >
> > Is there an existing resource loader that will allow me to do
> > this (I don't
> > want to store these in the database, so the data source
> > resource loader is
> > out), or some other way to get my templates loaded?
> >
> > -Todd
> >
> > ----------------------------------
> > Todd C. Marshall
> > Rapid Response Team Lead Developer
> > Parago, Inc
> > 1405 S. Beltline Rd., Ste 190
> > Coppell, Texas 75019
> > desk: 972-538-3911
> > fax:  972-745-3387
> > cell: 214-395-4502 (emergencies only)
> >
> > ---------------------------------------------------------------------
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: velocity-user-help@jakarta.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Mime
View raw message