001: /*
002: * Copyright 2005 Joe Walker
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016: package org.directwebremoting.create;
017:
018: import java.io.File;
019: import java.io.RandomAccessFile;
020:
021: import javax.servlet.ServletContext;
022:
023: import org.apache.bsf.BSFException;
024: import org.apache.bsf.BSFManager;
025: import org.apache.commons.logging.LogFactory;
026: import org.apache.commons.logging.Log;
027: import org.directwebremoting.WebContext;
028: import org.directwebremoting.WebContextFactory;
029: import org.directwebremoting.extend.Creator;
030: import org.directwebremoting.util.LocalUtil;
031: import org.directwebremoting.util.Messages;
032:
033: /**
034: * A creator that uses BeanShell to evaluate some script to create an object.
035: * @author Joe Walker [joe at getahead dot ltd dot uk]
036: * @author Dennis [devel at muhlesteins dot com]
037: */
038: public class ScriptedCreator extends AbstractCreator implements Creator {
039: /**
040: * Set up some defaults
041: */
042: public ScriptedCreator() {
043: // The default is <b>true</b>. This parameter is only used if scriptPath is
044: // used instead of script. When reloadable is true, ScriptedCreator will
045: // check to see if the script has been modified before returning the
046: // existing created class.
047: setCacheable(false);
048: }
049:
050: /**
051: * The language that we are scripting in. Passed to BSF.
052: * @return Returns the language.
053: */
054: public String getLanguage() {
055: return language;
056: }
057:
058: /**
059: * @param language The language to set.
060: */
061: public void setLanguage(String language) {
062: // It would be good to be ablt to check this, but this seems to fail
063: // almost all the time
064: // if (BSFManager.isLanguageRegistered(language))
065: // {
066: // throw new IllegalArgumentException(Messages.getString("ScriptedCreator.IllegalLanguage", language));
067: // }
068: this .language = language;
069: }
070:
071: /**
072: * Are we caching the script (default: false)
073: * @return Returns the reloadable variable
074: */
075: public boolean isReloadable() {
076: return reloadable;
077: }
078:
079: /**
080: * @param reloadable Whether or not to reload the script.
081: * The default is <b>true</b>. This parameter is only used if scriptPath is
082: * used instead of script. When reloadable is true, ScriptedCreator will
083: * check to see if the script has been modified before returning the
084: * existing created class.
085: */
086: public void setReloadable(boolean reloadable) {
087: this .reloadable = reloadable;
088:
089: if (reloadable) {
090: setCacheable(false);
091: }
092: }
093:
094: /**
095: * Are we using dynamic classes (i.e. classes generated by BeanShell or
096: * similar) in which case we want to reuse class defs.
097: * @return Returns the useDynamicClasses flag state.
098: */
099: public boolean isUseDynamicClasses() {
100: return useDynamicClasses;
101: }
102:
103: /**
104: * Are we using dynamic classes (i.e. classes generated by BeanShell or
105: * similar) in which case we want to reuse class defs.
106: * @param useDynamicClasses The useDynamicClasses flag state.
107: */
108: public void setUseDynamicClasses(boolean useDynamicClasses) {
109: this .useDynamicClasses = useDynamicClasses;
110: }
111:
112: /**
113: * @return Returns the path of the script.
114: */
115: public String getScriptPath() {
116: return scriptPath;
117: }
118:
119: /**
120: * @param scriptPath Context reletive path to script.
121: */
122: public void setScriptPath(String scriptPath) {
123: if (scriptSrc != null) {
124: throw new IllegalArgumentException(Messages
125: .getString("ScriptCreator.MultipleScript"));
126: }
127:
128: this .scriptPath = scriptPath;
129: }
130:
131: /**
132: * @return Whether or not the script (located at scriptPath) has been modified.
133: */
134: private boolean scriptUpdated() {
135: if (null == scriptPath) {
136: return false;
137: }
138:
139: ServletContext sc = WebContextFactory.get().getServletContext();
140: File scriptFile = new File(sc.getRealPath(scriptPath));
141: if (scriptModified < scriptFile.lastModified()) {
142: log.debug("Script has been updated.");
143: clazz = null; // make sure that this gets re-compiled.
144: return true;
145: }
146:
147: return false;
148: }
149:
150: /**
151: * @return Returns the script.
152: * @throws InstantiationException If we can't read from the requested script
153: */
154: public String getScript() throws InstantiationException {
155: if (scriptSrc != null) {
156: return scriptSrc;
157: }
158:
159: if (scriptPath == null) {
160: throw new InstantiationException(Messages
161: .getString("ScriptedCreator.MissingScript"));
162: }
163:
164: if (cachedScript != null && (!reloadable || !scriptUpdated())) {
165: return cachedScript;
166: }
167:
168: // load the script from the path
169: log.debug("Loading Script from Path: " + scriptPath);
170: RandomAccessFile in = null;
171:
172: try {
173: ServletContext sc = WebContextFactory.get()
174: .getServletContext();
175: File scriptFile = new File(sc.getRealPath(scriptPath));
176:
177: // This uses the platform default encoding. If there are complaints
178: // from people wanting to read script files that are not in the
179: // default platform encoding then we will need a new param that is
180: // used here.
181: scriptModified = scriptFile.lastModified();
182: in = new RandomAccessFile(scriptFile, "r");
183: byte[] bytes = new byte[(int) in.length()];
184: in.readFully(bytes);
185: cachedScript = new String(bytes);
186:
187: return cachedScript;
188: } catch (Exception ex) {
189: log.error(ex.getMessage(), ex);
190: throw new InstantiationException(Messages
191: .getString("ScriptCreator.MissingScript"));
192: } finally {
193: LocalUtil.close(in);
194: }
195: }
196:
197: /**
198: * @param scriptSrc The script to set.
199: */
200: public void setScript(String scriptSrc) {
201: if (scriptPath != null) {
202: throw new IllegalArgumentException(Messages
203: .getString("ScriptCreator.MultipleScript"));
204: }
205:
206: if (scriptSrc == null || scriptSrc.trim().length() == 0) {
207: throw new IllegalArgumentException(Messages
208: .getString("ScriptedCreator.MissingScript"));
209: }
210:
211: this .scriptSrc = scriptSrc;
212: }
213:
214: /**
215: * What sort of class do we create?
216: * @param classname The name of the class
217: */
218: public void setClass(String classname) {
219: try {
220: this .clazz = LocalUtil.classForName(classname);
221: } catch (ClassNotFoundException ex) {
222: throw new IllegalArgumentException(Messages.getString(
223: "Creator.ClassNotFound", classname));
224: }
225: }
226:
227: /* (non-Javadoc)
228: * @see org.directwebremoting.Creator#getType()
229: */
230: public Class<?> getType() {
231: if (clazz == null || (reloadable && scriptUpdated())) {
232: try {
233: clazz = getInstance().getClass();
234: } catch (InstantiationException ex) {
235: log.error(
236: "Failed to instansiate object to detect type.",
237: ex);
238: return Object.class;
239: }
240: }
241:
242: return clazz;
243: }
244:
245: /* (non-Javadoc)
246: * @see org.directwebremoting.Creator#getInstance()
247: */
248: public Object getInstance() throws InstantiationException {
249: try {
250: if (useDynamicClasses && clazz != null) {
251: return clazz.newInstance();
252: }
253:
254: BSFManager bsfman = new BSFManager();
255:
256: try {
257: WebContext context = WebContextFactory.get();
258: bsfman.declareBean("context", context, context
259: .getClass());
260: } catch (BSFException ex) {
261: log
262: .warn("Failed to register WebContext with scripting engine: "
263: + ex.getMessage());
264: }
265:
266: return bsfman.eval(language,
267: (null == scriptPath ? "dwr.xml" : scriptPath), 0,
268: 0, getScript());
269: } catch (Exception ex) {
270: throw new InstantiationException(Messages.getString(
271: "ScriptedCreator.IllegalAccess", ex.getMessage()));
272: }
273: }
274:
275: /**
276: * The log stream
277: */
278: private static final Log log = LogFactory
279: .getLog(ScriptedCreator.class);
280:
281: /**
282: * The cached type of object that we are creating.
283: */
284: private Class<?> clazz = null;
285:
286: /**
287: * The language that we are scripting in. Passed to BSF.
288: */
289: private String language = null;
290:
291: /**
292: * The script that we are asking BSF to execute in order to get an object.
293: */
294: private String scriptSrc = null;
295:
296: /**
297: * The path of the script we are asking BSF to execute.
298: */
299: private String scriptPath = null;
300:
301: /**
302: * Whether or not to reload the script. Only used if scriptPath is used.
303: * ie: An inline script is not reloadable
304: */
305: private boolean reloadable = true;
306:
307: /**
308: * By default we assume that our scripts do not create classes dynamically.
309: * If they do then we need to take some special care of them.
310: */
311: private boolean useDynamicClasses = false;
312:
313: /**
314: * Script modified time. Only used when scriptPath is used.
315: */
316: private long scriptModified = -1;
317:
318: /**
319: * Contents of script loaded from scriptPath
320: */
321: private String cachedScript;
322: }
|