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