1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.module.observation.commands;
35
36 import info.magnolia.context.Context;
37 import info.magnolia.context.MgnlContext;
38 import info.magnolia.context.SimpleContext;
39
40 import java.util.ArrayList;
41 import java.util.List;
42 import java.util.Map;
43
44 import javax.jcr.RepositoryException;
45 import javax.jcr.observation.Event;
46 import javax.jcr.observation.EventIterator;
47 import javax.jcr.observation.EventListener;
48
49 import org.apache.commons.chain.Command;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53
54
55
56
57
58
59 public class CommandEventListener implements EventListener {
60 private static final Logger log = LoggerFactory.getLogger(CommandEventListener.class);
61
62
63 private Command command;
64
65
66 private Map params;
67
68
69
70
71 public void onEvent(EventIterator events) {
72
73 log.debug("Checking event for command {} invocation", this.command.getClass().getName());
74
75 Event event;
76 List paths = new ArrayList();
77 String path = null;
78
79
80 Context ctx;
81 if (MgnlContext.hasInstance()) {
82 ctx = MgnlContext.getInstance();
83 } else {
84
85 ctx = new SimpleContext(MgnlContext.getSystemContext()) {
86 @Override
87 public void release() {
88
89 }
90 };
91 }
92
93 MgnlContext.setInstance(ctx);
94 try {
95 while (events.hasNext()) {
96 try {
97 event = events.nextEvent();
98 if (checkIfEventIsProcessed(event)) {
99
100
101 path = getPath(event);
102 if (path == null || paths.contains(path)) {
103 continue;
104 } else {
105 paths.add(path);
106 }
107
108 Context executionCtx = new SimpleContext();
109
110 try {
111 if (params != null) {
112 executionCtx.putAll(params);
113 }
114 executionCtx.put(Context.ATTRIBUTE_PATH, path);
115
116 try {
117 command.execute(executionCtx);
118 log.debug("Successfully executed command {}", command.getClass().getName());
119 } catch (Exception e) {
120 log.error("can't execute command ", e);
121 }
122 } finally {
123
124
125
126
127 }
128 }
129 } catch (Exception e) {
130 log.error("can't deliver event", e);
131 }
132 }
133 } finally {
134
135 }
136 }
137
138 protected boolean checkIfEventIsProcessed(Event event)
139 throws RepositoryException {
140 return !event.getPath().startsWith("/jcr:system");
141 }
142
143 protected String getPath(Event event) throws RepositoryException {
144 return event.getPath();
145 }
146
147 public Command getCommand() {
148 return command;
149 }
150
151 public void setCommand(Command command) {
152 this.command = command;
153 }
154
155 public Map getParams() {
156 return params;
157 }
158
159 public void setParams(Map params) {
160 this.params = params;
161 }
162
163 }