01: /*
02: * @(#)AddMapAction.java 1.2 04/12/06
03: *
04: * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.xml.action;
10:
11: import pnuts.beans.BeanUtil;
12: import java.util.Map;
13: import java.util.HashMap;
14: import java.util.List;
15:
16: /**
17: * This action constructs a Map object from values that two child-elements
18: * produce. This action is created with a <em>keyword</em> and the <em>value</em>.
19: *
20: * e.g.
21: * <pre>
22: * <map>
23: * <key><em>age</em></key>
24: * <value><em>0</em></value>
25: * </map>
26: * </pre>
27: * <pre>
28: * new AddMapAction("key", "value");
29: * </pre>
30: */
31: public class AddMapAction extends CallAction {
32:
33: private String keyName;
34: private String valueName;
35:
36: /**
37: * Constructor
38: *
39: * @param keyName a <em>Keyword</em> name in the rule that specifies which element is a key-part of the resulting Map entries.
40: * @param valueName a <em>Keyword</em> anem in the rule that specifies which element is a value-part of the resulting Map entries.
41: */
42: public AddMapAction(String keyName, String valueName) {
43: super (new String[] { keyName, valueName });
44: }
45:
46: public void start(String path, String key, Map attributeMap,
47: Object top) throws Exception {
48: if (!path.equals(getStackTopPath())) {
49: Map map = new HashMap();
50: if (top instanceof Map) {
51: ((Map) top).put(key, map);
52: } else if (top instanceof List) {
53: ((List) top).add(map);
54: } else {
55: BeanUtil.setProperty(top, key, map);
56: }
57: push(path, map);
58: }
59: }
60:
61: protected void call(Object[] args) {
62: if (args.length != 2) {
63: throw new IllegalArgumentException();
64: }
65: Object top = getStackTopValue();
66: if (top instanceof Map) {
67: Map map = (Map) top;
68: map.put(args[0], args[1]);
69: push(getStackTopPath(), map);
70: } else {
71: throw new IllegalArgumentException(String.valueOf(top));
72: }
73: }
74: }
|