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.core;
17  
18  import org.mozilla.javascript.Scriptable;
19  import org.apache.struts.flow.core.javascript.fom.FOM_Flow;
20  import java.lang.reflect.Constructor;
21  
22  /***
23   *  Defines a variable registrar used to define a call-specific variable in the
24   *  global scope. Static variables are defined once per global scope, while
25   *  call-specific variables can define instances of themselves for every script
26   *  call.
27   */
28  public class DefaultFlowVariableFactory implements FlowVariableFactory {
29  
30      private Class variableClass;
31  
32      public DefaultFlowVariableFactory(Class variableClass) {
33          this.variableClass = variableClass;
34      }
35  
36      /***
37       *  Gets an instance of the variable. First tries to call constructor that
38       *  takes a single argument of the Context. If not found, it calls the empty
39       *  constructor.
40       *
41       *@param  scope  The scope the variable will be placed in
42       *@param  ctx    The commons chain context for the call, null if defining a
43       *      static variable
44       *@return        The instance value
45       */
46      public Object getInstance(Scriptable scope, FOM_Flow flow) {
47          try {
48              Constructor c = null;
49              try {
50                  c = variableClass.getConstructor(new Class[]{flow.getClass()});
51              } catch (NoSuchMethodException ex) {
52                  // ignored
53              }
54              if (c != null) {
55                  return c.newInstance(new Object[]{flow});
56              } else {
57                  return variableClass.newInstance();
58              }
59          } catch (Exception ex) {
60              Factory.getLogger().error(ex);
61              return null;
62          }
63      }
64  
65  }
66