1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package com.enspire.gemini.commands;
25
26 import java.util.List;
27
28 import com.enspire.gemini.BidirectionalProperty;
29
30 /***
31 * Executes the <code>add()</code> operation on a <code>BidirectionalList</code>.
32 * @author Dragan Djuric <dragand@dev.java.net>
33 * @since 1.0
34 */
35 public class BidirectionalListAddByIndex extends BidirectionalListCommand {
36
37 Object oldOwner;
38 Object addValue;
39 int addIndex;
40 boolean hasChanged = false;
41
42 /***
43 * Creates a command and sets its dependencies.
44 * @param bidirectional the bidirectional list that this command is tied to
45 * @param list the unidirectional list that this command is tied to
46 * @param addIndex an index of an object that should be added to the collection
47 * @param addValue an object that should be added to the collection
48 */
49 public BidirectionalListAddByIndex(BidirectionalProperty bidirectional,
50 List list, int addIndex, Object addValue) {
51 super(bidirectional, list);
52 this.addValue = addValue;
53 this.addIndex = addIndex;
54 }
55
56 /***
57 * @see com.enspire.gemini.commands.Command#execute()
58 */
59 public void execute() {
60 int size = getList().size();
61 getList().add(addIndex, addValue);
62 hasChanged = size != getList().size();
63 if (hasChanged) {
64 try {
65 oldOwner = getBidirectionalProperty().getRelationshipUpdater().
66 set(addValue,
67 getBidirectionalProperty().getOppositeName(),
68 getBidirectionalProperty().getOwner());
69 } catch(RuntimeException e) {
70 getList().remove(addIndex);
71 throw e;
72 }
73 }
74 }
75
76 /***
77 * @see com.enspire.gemini.commands.Command#undo()
78 */
79 public void undo() {
80 if (!hasChanged) {
81 return;
82 }
83 getList().remove(addIndex);
84 getBidirectionalProperty().getRelationshipUpdater().unset(addValue,
85 getBidirectionalProperty().getOppositeName(),
86 getBidirectionalProperty().getOwner());
87 if(oldOwner != null) {
88 getBidirectionalProperty().getRelationshipUpdater().set(addValue,
89 getBidirectionalProperty().getOppositeName(), oldOwner);
90 }
91 }
92
93 }