• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.apache.velocity.script;
2 
3 /*
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements.  See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership.  The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License.  You may obtain a copy of the License at
11  *
12  *   http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied.  See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21 
22 import org.apache.velocity.Template;
23 import org.apache.velocity.VelocityContext;
24 
25 import javax.script.CompiledScript;
26 import javax.script.ScriptContext;
27 import javax.script.ScriptEngine;
28 import javax.script.ScriptException;
29 import java.io.StringWriter;
30 import java.io.Writer;
31 
32 public class VelocityCompiledScript extends CompiledScript
33 {
34     protected VelocityScriptEngine engine;
35     protected Template template;
36 
VelocityCompiledScript(VelocityScriptEngine e, Template t)37     public VelocityCompiledScript(VelocityScriptEngine e, Template t)
38     {
39         engine = e;
40         template = t;
41     }
42 
43     @Override
eval(ScriptContext scriptContext)44     public Object eval(ScriptContext scriptContext) throws ScriptException
45     {
46         VelocityContext velocityContext = VelocityScriptEngine.getVelocityContext(scriptContext);
47         Writer out = scriptContext.getWriter();
48         if (out == null)
49         {
50             out = new StringWriter();
51             scriptContext.setWriter(out);
52         }
53         try
54         {
55             template.merge(velocityContext, out);
56             out.flush();
57         }
58         catch (Exception exp)
59         {
60             throw new ScriptException(exp);
61         }
62         return out;
63     }
64 
65     @Override
getEngine()66     public ScriptEngine getEngine()
67     {
68         return engine;
69     }
70 }
71