View Javadoc

1   /*
2    * Copyright 2005 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.javascript;
17  
18  import java.util.ArrayList;
19  import java.util.*;
20  
21  import org.mozilla.javascript.Wrapper;
22  import org.mozilla.javascript.Undefined;
23  import org.mozilla.javascript.ScriptableObject;
24  import org.mozilla.javascript.Scriptable;
25  import org.mozilla.javascript.ScriptRuntime;
26  import org.mozilla.javascript.NativeArray;
27  import org.mozilla.javascript.Script;
28  import org.mozilla.javascript.JavaScriptException;
29  
30  /***
31   * Aids in converting from Javascript objects to Java objects and vice versa.
32   * @version $Id: LocationTrackingDebugger.java 280811 2005-09-14 09:53:32Z sylvain $
33   */
34  public class ConversionHelper {
35  
36      /***
37       *  Converts a JavaScript object to a HashMap
38       *
39       *@param  jsobject  The object to convert
40       *@return           The Map
41       */
42      public static Map jsobjectToMap(Scriptable jsobject) {
43          HashMap hash = new HashMap();
44          Object[] ids = jsobject.getIds();
45          for (int i = 0; i < ids.length; i++) {
46              String key = ScriptRuntime.toString(ids[i]);
47              Object value = jsobject.get(key, jsobject);
48              if (value == Undefined.instance) {
49                  value = null;
50              } else {
51                  value = jsobjectToObject(value);
52              }
53              hash.put(key, value);
54          }
55          return hash;
56      }
57      
58      /***
59       *  Converts a JavaScript object to a Java Object
60       *
61       *@param  obj  The JavaScript object
62       *@return      The Java Object
63       */
64      public static Object jsobjectToObject(Object obj) {
65          // unwrap Scriptable wrappers of real Java objects
66          if (obj instanceof Wrapper) {
67              obj = ((Wrapper) obj).unwrap();
68          } else if (obj == Undefined.instance) {
69              obj = null;
70          }
71          return obj;
72      }
73  }
74