KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > nl > hippo > spring > JavaScriptFactory


1 /*
2  * Copyright 2004 Hippo Webworks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package nl.hippo.spring;
17
18 import java.util.Collections JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.Map JavaDoc;
21 import org.mozilla.javascript.Context;
22 import org.mozilla.javascript.Scriptable;
23 import org.mozilla.javascript.ScriptableObject;
24 import org.mozilla.javascript.WrappedException;
25
26 public class JavaScriptFactory
27 {
28     
29     private static final String JavaDoc SCRIPT_PREFIX = "var result = null;";
30
31     private static final String JavaDoc SCRIPT_SUFFIX = "result;";
32
33     public JavaScriptFactory()
34     {
35         super();
36     }
37
38     public static Object JavaDoc create(String JavaDoc script, Map JavaDoc parameters) throws Throwable JavaDoc
39     {
40         Object JavaDoc result;
41         
42         if (parameters == null)
43         {
44             parameters = Collections.EMPTY_MAP;
45         }
46
47         try
48         {
49             Context javaScriptContext = Context.enter();
50             Scriptable scope = javaScriptContext.initStandardObjects(null);
51             
52             for (Iterator JavaDoc parameterNamesIterator = parameters.keySet().iterator(); parameterNamesIterator.hasNext();)
53             {
54                 String JavaDoc parameterName = (String JavaDoc) parameterNamesIterator.next();
55                 Object JavaDoc parameter = Context.toObject(parameters.get(parameterName), scope);
56                 ScriptableObject.putProperty(scope, parameterName, parameter);
57             }
58             
59             StringBuffer JavaDoc wrappedScript = new StringBuffer JavaDoc(script.length() + SCRIPT_PREFIX.length() + SCRIPT_SUFFIX.length());
60             wrappedScript.append(SCRIPT_PREFIX);
61             wrappedScript.append(script);
62             wrappedScript.append(SCRIPT_SUFFIX);
63             result = javaScriptContext.evaluateString(scope, wrappedScript.toString(), "JavaScriptFactory script", 1, null);
64         }
65         catch (WrappedException e)
66         {
67             throw e.getCause();
68         }
69         finally
70         {
71             Context.exit();
72         }
73
74         return result;
75     }
76
77 }
Popular Tags