6b460d1dea203495d7ef258afec33c75e86c71ab
[xmlrouter] / impl / src / main / java / org / wamblee / xmlrouter / impl / XMLRouter.java
1 /*
2  * Copyright 2005-2011 the original author or authors.
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.wamblee.xmlrouter.impl;
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashSet;
22 import java.util.LinkedHashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.concurrent.atomic.AtomicLong;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import javax.xml.transform.dom.DOMSource;
31
32 import org.wamblee.general.Clock;
33 import org.wamblee.xml.XMLDocument;
34 import org.wamblee.xmlrouter.common.Id;
35 import org.wamblee.xmlrouter.config.Config;
36 import org.wamblee.xmlrouter.config.DocumentType;
37 import org.wamblee.xmlrouter.config.Filter;
38 import org.wamblee.xmlrouter.config.Transformation;
39 import org.wamblee.xmlrouter.listener.EventInfo;
40 import org.wamblee.xmlrouter.listener.EventListener;
41 import org.wamblee.xmlrouter.publish.Gateway;
42 import org.wamblee.xmlrouter.subscribe.Destination;
43 import org.wamblee.xmlrouter.subscribe.DestinationRegistry;
44
45 // TODO concurrency.
46
47 public class XMLRouter implements Config, Gateway, DestinationRegistry {
48
49     private static final Logger LOGGER = Logger.getLogger(XMLRouter.class
50         .getName());
51
52     private EventListener listener;
53     private Clock clock;
54     private AtomicLong nextEventId;
55     private AtomicLong sequenceNumbers;
56     private Map<Long, DocumentType> documentTypes;
57     private Transformations transformations;
58     private Map<Long, Filter> filters;
59     private Map<Long, Destination> destinations;
60
61     public XMLRouter(Clock aClock, EventListener aListener) {
62         listener = aListener;
63         clock = aClock;
64         nextEventId = new AtomicLong(clock.currentTimeMillis());
65         sequenceNumbers = new AtomicLong(1);
66         documentTypes = new LinkedHashMap<Long, DocumentType>();
67         transformations = new Transformations();
68         filters = new LinkedHashMap<Long, Filter>();
69         destinations = new LinkedHashMap<Long, Destination>();
70     }
71
72     @Override
73     public Id<DocumentType> addDocumentType(DocumentType aType) {
74         long seqno = sequenceNumbers.getAndIncrement();
75         documentTypes.put(seqno, aType);
76         return new Id<DocumentType>(seqno);
77     }
78
79     @Override
80     public void removeDocumentType(Id<DocumentType> aId) {
81         documentTypes.remove(aId);
82     }
83
84     @Override
85     public Collection<DocumentType> getDocumentTypes() {
86         return Collections.unmodifiableCollection(documentTypes.values());
87     }
88
89     @Override
90     public Id<Transformation> addTransformation(Transformation aTransformation) {
91         return transformations.addTransformation(aTransformation);
92     }
93
94     @Override
95     public void removeTransformation(Id<Transformation> aId) {
96         transformations.removeTransformation(aId);
97     }
98
99     @Override
100     public Collection<Transformation> getTransformations() {
101         return transformations.getTransformations();
102     }
103
104     @Override
105     public Id<Filter> addFilter(Filter aFilter) {
106         long seqno = sequenceNumbers.getAndIncrement();
107         filters.put(seqno, aFilter);
108         return new Id<Filter>(seqno);
109     }
110
111     @Override
112     public void removeFilter(Id<Filter> aId) {
113         filters.remove(aId);
114     }
115
116     @Override
117     public Collection<Filter> getFilters() {
118         return Collections.unmodifiableCollection(filters.values());
119     }
120
121     @Override
122     public void publish(String aSource, DOMSource aEvent) {
123
124         long time = clock.currentTimeMillis();
125         Id<DOMSource> id = new Id<DOMSource>(nextEventId.getAndIncrement());
126         List<String> types = determineDocumentTypes(aEvent);
127         EventInfo info = new EventInfo(time, aSource, id, types, aEvent);
128
129         boolean delivered = false;
130         try {
131
132             List<String> filteredInputTypes = determineFilteredInputTypes(
133                 types, aEvent);
134             if (filteredInputTypes.isEmpty()) {
135                 if (LOGGER.isLoggable(Level.FINE)) {
136                     String doc = new XMLDocument(aEvent).print(true);
137                     LOGGER
138                         .log(
139                             Level.FINE,
140                             "Event ''0}'' from source {1} removed because of filters.",
141                             new Object[] { doc, aSource });
142                 }
143             }
144
145             // get the reachable target types through transformations.
146
147             // It is possible that a given event belongs to multiple input
148             // types.
149             // This is however certainly not the main case.
150
151             for (String inputType : filteredInputTypes) {
152                 boolean result = deliverEvent(info, inputType);
153                 delivered = delivered || result;
154             }
155         } finally {
156             if (!delivered) {
157                 destinationNotFound(aSource, aEvent);
158                 listener.notDelivered(info);
159             }
160         }
161     }
162
163     private boolean deliverEvent(EventInfo aInfo, String aInputType) {
164
165         boolean delivered = false;
166         Set<String> possibleTargetTypes = new HashSet<String>();
167         possibleTargetTypes.addAll(transformations
168             .getPossibleTargetTypes(aInputType));
169
170         // ask each destination what target types, if any they want to have.
171         for (Map.Entry<Long, Destination> entry : destinations.entrySet()) {
172             long destinationId = entry.getKey();
173             Destination destination = entry.getValue();
174             Collection<String> requested = destination
175                 .chooseFromTargetTypes(possibleTargetTypes);
176             if (!requested.isEmpty()) {
177                 // Deliver to the destination.
178                 for (String targetType : requested) {
179                     TransformationPath path = transformations.getPath(
180                         aInputType, targetType);
181                     List<Transformation> ts = path.getTransformations();
182                     int i = 0;
183                     boolean allowed = true;
184                     DOMSource transformed = aInfo.getEvent();
185                     while (i < ts.size() && allowed && transformed != null) {
186                         Transformation t = ts.get(i);
187                         DOMSource orig = transformed;
188                         transformed = t.transform(transformed);
189                         if (transformed == null) {
190                             transformationReturnedNull(aInfo.getSource(),
191                                 aInfo.getEvent(), aInputType, t, orig);
192                         }
193
194                         if (!isAllowedByFilters(t.getToType(), transformed)) {
195                             allowed = false;
196                         }
197                         i++;
198                     }
199                     if (allowed && transformed != null) {
200                         // all transformations done and all filters still
201                         // allow the event.
202                         boolean result = destination.receive(transformed);
203                         listener.delivered(aInfo, ts, destinationId,
204                             destination.getName(), result);
205                         delivered = delivered || result;
206
207                     }
208                 }
209             }
210         }
211         return delivered;
212     }
213
214     private List<String> determineFilteredInputTypes(List<String> aTypes,
215         DOMSource aEvent) {
216
217         // apply filters to the input
218         List<String> filteredTypes = new ArrayList<String>();
219         for (String type : aTypes) {
220             boolean allowed = isAllowedByFilters(type, aEvent);
221             if (allowed) {
222                 filteredTypes.add(type);
223             }
224         }
225         return filteredTypes;
226     }
227
228     private boolean isAllowedByFilters(String aType, DOMSource aEvent) {
229         boolean allowed = true;
230         for (Filter filter : filters.values()) {
231             if (!filter.isAllowed(aType, aEvent)) {
232                 allowed = false;
233             }
234         }
235         return allowed;
236     }
237
238     private List<String> determineDocumentTypes(DOMSource aEvent) {
239         List<String> res = new ArrayList<String>();
240         for (DocumentType type : documentTypes.values()) {
241             if (type.isInstance(aEvent)) {
242                 res.add(type.getName());
243             }
244         }
245         return res;
246     }
247
248     private void logEvent(String aMessage, String aSource, DOMSource aEvent,
249         Exception aException) {
250         LOGGER.log(Level.WARNING, aMessage + ": source '" + aSource +
251             "': Event: '" + new XMLDocument(aEvent).print(true) + "'",
252             aException);
253     }
254
255     private void logEvent(String aMessage, String aSource, DOMSource aEvent) {
256         LOGGER.log(Level.WARNING,
257             aMessage + ": " + eventToString(aSource, aEvent));
258     }
259
260     private String eventToString(String aSource, DOMSource aEvent) {
261         return "source '" + aSource + "': Event: '" +
262             new XMLDocument(aEvent).print(true) + "'";
263     }
264
265     private void transformationReturnedNull(String aSource, DOMSource aEvent,
266         String aInputType, Transformation aT, DOMSource aTransformed) {
267         LOGGER.log(Level.WARNING, "Transformation returned null for event " +
268             eventToString(aSource, aEvent) + " inputType '" + aInputType +
269             "', transformation '" + aT + "' document to transform " +
270             new XMLDocument(aTransformed).print(true));
271     }
272
273     private void destinationNotFound(String aSource, DOMSource aEvent) {
274         LOGGER.log(Level.WARNING, "No destination found for event: " +
275             eventToString(aSource, aEvent));
276     }
277
278     @Override
279     public Id<Destination> registerDestination(Destination aDestination) {
280         notNull("destination", aDestination);
281         long seqno = sequenceNumbers.getAndIncrement();
282         Id<Destination> id = new Id<Destination>(seqno);
283         destinations.put(seqno, new RobustDestination(id, aDestination));
284         return id;
285     }
286
287     @Override
288     public void unregisterDestination(Id<Destination> aId) {
289         destinations.remove(aId.getId());
290     }
291
292     private void notNull(String aName, Object aValue) {
293         if (aValue == null) {
294             throw new IllegalArgumentException("Parameter '" + aName +
295                 "' may not be null");
296         }
297     }
298 }