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