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.ByteArrayInputStream;
38  import java.io.ByteArrayOutputStream;
39  import java.text.MessageFormat;
40  import java.util.HashMap;
41  import java.util.Iterator;
42  import java.util.Map;
43  
44  import org.apache.log4j.Logger;
45  import org.apache.xmlbeans.XmlObject;
46  import org.apache.xmlbeans.XmlOptions;
47  import org.ogf.graap.wsag.server.actions.AbstractGetTemplateAction;
48  import org.ogf.graap.wsag.server.actions.ActionInitializationException;
49  import org.ogf.graap.wsag4j.types.configuration.FileTemplateConfigurationDocument;
50  import org.ogf.graap.wsag4j.types.configuration.FileTemplateConfigurationType;
51  import org.ogf.graap.wsag4j.types.configuration.ImplementationConfigurationType;
52  import org.ogf.schemas.graap.wsAgreement.AgreementTemplateType;
53  
54  /**
55   * Implementation of an {@link org.ogf.graap.wsag.server.actions.IGetTemplateAction} that dynamically creates
56   * an agreement template using Velocity Template engine. Agreement templates are generated based on the
57   * specified template file when the action is initialized ({@link #initialize()}). Subsequent calls to the
58   * {@link #getTemplate()} method return the agreement template that was created during the action
59   * initialization process.
60   * 
61   * @author Oliver Waeldrich
62   * 
63   */
64  public class VelocityAgreementTemplateAction extends AbstractGetTemplateAction
65  {
66  
67      private static final Logger LOG = Logger.getLogger( VelocityAgreementTemplateAction.class );
68  
69      private String templateFilename = "";
70  
71      private Map<String, Object> templateParameter = new HashMap<String, Object>();
72  
73      private AgreementTemplateType template;
74  
75      /**
76       * <!-- begin-UML-doc --> Initializes this action. During the action initialization process the specified
77       * template file is loaded via the application {@link ClassLoader} and processed as Velocity template. The
78       * resulting agreement template is stored and retrieved via the {@link #getTemplate()} method. <!--
79       * end-UML-doc -->
80       * 
81       * {@inheritDoc}
82       * 
83       * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
84       */
85      public void initialize() throws ActionInitializationException
86      {
87          // begin-user-code
88          try
89          {
90              ImplementationConfigurationType handlerConfig = getHandlerContext().getHandlerConfiguration();
91              XmlObject[] children =
92                  handlerConfig.selectChildren( FileTemplateConfigurationDocument.type.getDocumentElementName() );
93              if ( children.length != 1 )
94              {
95                  Object[] filler =
96                      new Object[] { getClass().getName(),
97                          FileTemplateConfigurationDocument.type.getDocumentElementName().toString(),
98                          Integer.toString( children.length ) };
99  
100                 String msgInvalidConfig =
101                     "Invalid configuration for action {0}. Expected one configuration section of type {1}, "
102                         + "but found {2}";
103                 String message = MessageFormat.format( msgInvalidConfig, filler );
104                 throw new ActionInitializationException( message );
105             }
106 
107             FileTemplateConfigurationType config = (FileTemplateConfigurationType) children[0];
108             setTemplateFilename( config.getFilename() );
109 
110             FileTemplate fileTemplate = new FileTemplate( getTemplateFilename() );
111 
112             Map<String, ?> parameter = getTemplateParameter();
113             Iterator<String> keys = parameter.keySet().iterator();
114             while ( keys.hasNext() )
115             {
116                 try
117                 {
118                     String key = (String) keys.next();
119                     fileTemplate.addParameter( key, parameter.get( key ) );
120                 }
121                 catch ( ClassCastException e )
122                 {
123                     LOG.error( "Invalid template parameter. Key value must be of type String." );
124                 }
125             }
126 
127             ByteArrayOutputStream out = new ByteArrayOutputStream();
128             fileTemplate.processTemplate( out );
129             ByteArrayInputStream in = new ByteArrayInputStream( out.toByteArray() );
130 
131             template =
132                 AgreementTemplateType.Factory.parse( in,
133                                                      new XmlOptions().setLoadReplaceDocumentElement( null ) );
134         }
135         catch ( Exception e )
136         {
137             Object[] filler = new Object[] { e.getMessage() };
138             String message = MessageFormat.format( "Error creating template. Reason: {0}", filler );
139             LOG.error( message );
140             throw new ActionInitializationException( message );
141         }
142         // end-user-code
143     }
144 
145     /**
146      * Hook for custom implementations for providing a set of parameters that are can be accessed by the
147      * Velocity template. Implementations return a map with parameters in order to dynamically include them in
148      * the template.
149      * 
150      * @return the template parameters used for creating the template
151      * 
152      * @see AbstractGetTemplateAction#getHandlerContext()
153      * @see org.ogf.graap.wsag.server.actions.IActionHandlerContext#getFactoryContext()
154      */
155     protected Map<String, ?> getTemplateParameter()
156     {
157         return templateParameter;
158     }
159 
160     /**
161      * Returns the processed template.
162      * 
163      * {@inheritDoc}
164      */
165     public AgreementTemplateType getTemplate()
166     {
167         return template;
168     }
169 
170     /**
171      * Returns the file name of the template to process.
172      * 
173      * @return the templateFilename
174      */
175     public String getTemplateFilename()
176     {
177         // begin-user-code
178         return templateFilename;
179         // end-user-code
180     }
181 
182     /**
183      * Sets the file name of the template to process.
184      * 
185      * @param templateFilename
186      *            the templateFilename to set
187      */
188     public void setTemplateFilename( String templateFilename )
189     {
190         // begin-user-code
191         this.templateFilename = templateFilename;
192         // end-user-code
193     }
194 
195 }