KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > base > util > BshUtil


1 /*
2  * $Id: BshUtil.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.base.util;
26
27 import java.io.IOException JavaDoc;
28 import java.io.InputStreamReader JavaDoc;
29 import java.io.Reader JavaDoc;
30 import java.io.StringReader JavaDoc;
31 import java.net.MalformedURLException JavaDoc;
32 import java.net.URL JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Set JavaDoc;
37
38 import org.ofbiz.base.location.FlexibleLocation;
39 import org.ofbiz.base.util.cache.UtilCache;
40
41 import bsh.BshClassManager;
42 import bsh.EvalError;
43 import bsh.Interpreter;
44 import bsh.NameSpace;
45 import bsh.ParseException;
46
47 /**
48  * BshUtil - BeanShell Utilities
49  *
50  *@author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
51  *@author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
52  *@author Oswin Ondarza and Manuel Soto
53  *@created Oct 22, 2002
54  *@version $Rev: 5462 $
55  */

56 public final class BshUtil {
57
58     public static final String JavaDoc module = BshUtil.class.getName();
59
60     protected static Map JavaDoc masterClassManagers = new HashMap JavaDoc();
61     public static UtilCache parsedScripts = new UtilCache("script.BshLocationParsedCache", 0, 0, false);
62     
63     /**
64      * Evaluate a BSH condition or expression
65      * @param expression The expression to evaluate
66      * @param context The context to use in evaluation (re-written)
67      * @return Object The result of the evaluation
68      * @throws EvalError
69      */

70     public static final Object JavaDoc eval(String JavaDoc expression, Map JavaDoc context) throws EvalError {
71         Object JavaDoc o = null;
72         if (expression == null || expression.equals("")) {
73             Debug.logError("BSH Evaluation error. Empty expression", module);
74             return null;
75         }
76
77         if (Debug.verboseOn())
78             Debug.logVerbose("Evaluating -- " + expression, module);
79         if (Debug.verboseOn())
80             Debug.logVerbose("Using Context -- " + context, module);
81
82         try {
83             Interpreter bsh = makeInterpreter(context);
84             // evaluate the expression
85
o = bsh.eval(expression);
86             if (Debug.verboseOn())
87                 Debug.logVerbose("Evaluated to -- " + o, module);
88
89             // read back the context info
90
NameSpace ns = bsh.getNameSpace();
91             String JavaDoc[] varNames = ns.getVariableNames();
92             for (int x = 0; x < varNames.length; x++) {
93                 context.put(varNames[x], bsh.get(varNames[x]));
94             }
95         } catch (EvalError e) {
96             Debug.logError(e, "BSH Evaluation error.", module);
97             throw e;
98         }
99         return o;
100     }
101     
102     public static Interpreter makeInterpreter(Map JavaDoc context) throws EvalError {
103         Interpreter bsh = getMasterInterpreter(null);
104         // Set the context for the condition
105
if (context != null) {
106             Set JavaDoc keySet = context.keySet();
107             Iterator JavaDoc i = keySet.iterator();
108             while (i.hasNext()) {
109                 Object JavaDoc key = i.next();
110                 Object JavaDoc value = context.get(key);
111                 bsh.set((String JavaDoc) key, value);
112             }
113             
114             // include the context itself in for easier access in the scripts
115
bsh.set("context", context);
116         }
117         
118         return bsh;
119     }
120
121     public static Interpreter getMasterInterpreter(ClassLoader JavaDoc classLoader) {
122         if (classLoader == null) {
123             classLoader = Thread.currentThread().getContextClassLoader();
124         }
125
126         //find the "master" BshClassManager for this classpath
127
BshClassManager master = (BshClassManager) BshUtil.masterClassManagers.get(classLoader);
128         if (master == null) {
129             synchronized (OfbizBshBsfEngine.class) {
130                 master = (BshClassManager) BshUtil.masterClassManagers.get(classLoader);
131                 if (master == null) {
132                     master = BshClassManager.createClassManager();
133                     master.setClassLoader(classLoader);
134                     BshUtil.masterClassManagers.put(classLoader, master);
135                 }
136             }
137         }
138         
139         if (master != null) {
140             Interpreter interpreter = new Interpreter(new StringReader JavaDoc(""), System.out, System.err,
141                     false, new NameSpace(master, "global"), null, null);
142             return interpreter;
143         } else {
144             Interpreter interpreter = new Interpreter();
145             interpreter.setClassLoader(classLoader);
146             return interpreter;
147         }
148     }
149     
150     public static Object JavaDoc runBshAtLocation(String JavaDoc location, Map JavaDoc context) throws GeneralException {
151         try {
152             Interpreter interpreter = makeInterpreter(context);
153             
154             Interpreter.ParsedScript script = null;
155             script = (Interpreter.ParsedScript) parsedScripts.get(location);
156             if (script == null) {
157                 synchronized (OfbizBshBsfEngine.class) {
158                     script = (Interpreter.ParsedScript) parsedScripts.get(location);
159                     if (script == null) {
160                         URL JavaDoc scriptUrl = FlexibleLocation.resolveLocation(location);
161                         Reader JavaDoc scriptReader = new InputStreamReader JavaDoc(scriptUrl.openStream());
162                         script = interpreter.parseScript(location, scriptReader);
163                         if (Debug.verboseOn()) Debug.logVerbose("Caching BSH script at: " + location, module);
164                         parsedScripts.put(location, script);
165                     }
166                 }
167             }
168             
169             return interpreter.evalParsedScript(script);
170         } catch (MalformedURLException JavaDoc e) {
171             String JavaDoc errMsg = "Error loading BSH script at [" + location + "]: " + e.toString();
172             Debug.logError(e, errMsg, module);
173             throw new GeneralException(errMsg, e);
174         } catch (ParseException e) {
175             String JavaDoc errMsg = "Error parsing BSH script at [" + location + "]: " + e.toString();
176             Debug.logError(e, errMsg, module);
177             throw new GeneralException(errMsg, e);
178         } catch (IOException JavaDoc e) {
179             String JavaDoc errMsg = "Error loading BSH script at [" + location + "]: " + e.toString();
180             Debug.logError(e, errMsg, module);
181             throw new GeneralException(errMsg, e);
182         } catch (EvalError ee) {
183             Throwable JavaDoc t = ee.getCause();
184             if (t == null) {
185                 Debug.logWarning(ee, "WARNING: no cause (from getCause) found for BSH EvalError: " + ee.toString(), module);
186                 t = ee;
187             } else {
188                 Debug.logError(t, "ERROR: Got cause (from getCause) for BSH EvalError: " + ee.toString(), module);
189             }
190             
191             String JavaDoc errMsg = "Error running BSH script at [" + location + "], line [" + ee.getErrorLineNumber() + "]: " + t.toString();
192             // don't log the full exception, just the main message; more detail logged later
193
throw new GeneralException(errMsg, t);
194         }
195     }
196 }
197
Popular Tags