View Javadoc

1   /* 
2    * Copyright (c) 2007, Fraunhofer-Gesellschaft
3    * All rights reserved.
4    * 
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions are
7    * met:
8    * 
9    * (1) Redistributions of source code must retain the above copyright
10   *     notice, this list of conditions and the disclaimer at the end.
11   *     Redistributions in binary form must reproduce the above copyright
12   *     notice, this list of conditions and the following disclaimer in
13   *     the documentation and/or other materials provided with the
14   *     distribution.
15   * 
16   * (2) Neither the name of Fraunhofer nor the names of its
17   *     contributors may be used to endorse or promote products derived
18   *     from this software without specific prior written permission.
19   * 
20   * DISCLAIMER
21   * 
22   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24   * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25   * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26   * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29   * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30   * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33   *  
34   */
35  package org.ogf.graap.wsag.server.actions.impl;
36  
37  import java.io.BufferedWriter;
38  import java.io.InputStream;
39  import java.io.OutputStream;
40  import java.io.OutputStreamWriter;
41  import java.text.MessageFormat;
42  import java.util.Date;
43  import java.util.Properties;
44  
45  import org.apache.log4j.Logger;
46  import org.apache.velocity.Template;
47  import org.apache.velocity.VelocityContext;
48  import org.apache.velocity.app.Velocity;
49  import org.apache.velocity.exception.ResourceNotFoundException;
50  import org.apache.xmlbeans.XmlDateTime;
51  import org.ogf.graap.wsag.api.logging.LogMessage;
52  
53  /**
54   * Default implementation to load files from the classpath an process these files as Velocity templates.
55   * Additional parameters can be specified, which can be used in the Velocity macros defined in the file.
56   * 
57   * @author owaeld
58   * 
59   */
60  public class FileTemplate
61  {
62  
63      private static final Logger LOG = Logger.getLogger( FileTemplate.class );
64  
65      /**
66       * Default velocity properties filename
67       */
68      public static final String VELOCITY_PROPERTIES_FILE = "/wsag4j-velocity.properties";
69  
70      private VelocityContext context;
71  
72      private Template template;
73  
74      static
75      {
76          Properties properties = new Properties();
77  
78          try
79          {
80              InputStream in = FileTemplate.class.getResourceAsStream( VELOCITY_PROPERTIES_FILE );
81              properties.load( in );
82  
83              //
84              // set Velocity log4j logger name
85              //
86              properties.setProperty( "runtime.log.logsystem.log4j.logger", FileTemplate.class.getName() );
87  
88          }
89          catch ( Exception e )
90          {
91              String message = "Failed to load velocity properties file [{0}]. Reason: {1}";
92              LOG.error( LogMessage.getMessage( message, VELOCITY_PROPERTIES_FILE, e.getMessage() ) );
93              LOG.error( "Resource loockup in WSAG4J classpath disabled." );
94              LOG.debug( e );
95          }
96  
97          try
98          {
99              Velocity.init( properties );
100         }
101         catch ( Exception e )
102         {
103             LOG.error( "Failed to initialize velocity template engine.", e );
104             LOG.error( "Resource loockup in WSAG4J classpath disabled." );
105         }
106 
107     }
108 
109     /**
110      * Creates a new file template for the given file name. The file with the specified name is resolved from
111      * the classpath.
112      * 
113      * @param filename
114      *            the file name
115      */
116     public FileTemplate( String filename )
117     {
118         try
119         {
120             this.context = new VelocityContext();
121 
122             String currDate = XmlDateTime.Factory.newValue( new Date() ).getStringValue();
123             addParameter( "currentTime", currDate );
124 
125             //
126             // avoid escaping all the XPath expression
127             //
128             addParameter( "this", "$this" );
129 
130             template = Velocity.getTemplate( filename );
131         }
132         catch ( ResourceNotFoundException e )
133         {
134             LOG.error( MessageFormat.format( "error loading template file [{0}]", filename ) );
135             LOG.error( e.getMessage() );
136         }
137         catch ( Exception e )
138         {
139             LOG.error( MessageFormat.format( "error processing template file [{0}]", filename ) );
140             LOG.error( e.getMessage() );
141         }
142     }
143 
144     /**
145      * Adds a new parameter to the Velocity context. Parameters can be accessed in the template by its key.
146      * 
147      * @param key
148      *            the parameter name
149      * 
150      * @param value
151      *            the parameter value
152      */
153     public void addParameter( String key, Object value )
154     {
155         context.put( key, value );
156     }
157 
158     /**
159      * Processes the file template as Velocity template.
160      * 
161      * @param out
162      *            the {@link OutputStream} where the result is written to
163      */
164     public void processTemplate( OutputStream out )
165     {
166         try
167         {
168             BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( out ) );
169 
170             if ( template != null )
171             {
172                 template.merge( context, writer );
173             }
174 
175             writer.flush();
176             writer.close();
177         }
178         catch ( Exception ex )
179         {
180             LOG.error( "error processing output for template:" );
181             LOG.error( ex.getMessage() );
182         }
183     }
184 }