View Javadoc

1   /*
2    *  Copyright 1999-2004 The Apache Software Foundation.
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 org.apache.struts.flow.sugar;
17  
18  import org.mozilla.javascript.*;
19  import java.util.*;
20  import java.io.Serializable;
21  
22  /***
23   *  Base class for function extensions.  A function extension is a function
24   *  is added to an existing Java object at the Rhino level.
25   */
26  public abstract class ExtensionFunction extends ScriptableObject implements Function {
27          
28      protected Object target;    
29      protected Scriptable wrapper;
30          
31      public Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) {
32          try {
33              Object o = execute(cx, scope, thisObj, args);
34              if (o instanceof Scriptable) {
35                  return o;
36              } else if (o == target) {
37                  return wrapper;
38              } else {
39                  // Need to wrap the object before we return it.
40                  scope = ScriptableObject.getTopLevelScope(scope);
41                  Class type = Object.class;
42                  if (o != null) {
43                      type = o.getClass();
44                  } 
45                  return cx.getWrapFactory().wrap(cx, scope, o, type);
46              }
47          } catch (Exception ex) {
48              throw Context.throwAsScriptRuntimeEx(ex);
49          }
50      }
51      
52      public abstract Object execute(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws Exception;
53       
54      public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) {
55          return null;
56      }
57      
58      public String getClassName() {
59          return getClass().getName();
60      }
61      
62      public void setTarget(Object target) {
63          this.target = target;   
64      }
65      
66      public void setWrapper(Scriptable wrapper) {
67          this.wrapper = wrapper;   
68      }
69  }