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