2 * Copyright 2005-2011 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.xmlrouter.impl;
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;
25 import java.util.concurrent.atomic.AtomicLong;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import javax.xml.transform.dom.DOMSource;
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;
46 * @author Erik Brakkee
49 public class XMLRouter implements Gateway, DestinationRegistry {
51 private static final Logger LOGGER = Logger.getLogger(XMLRouter.class
54 private AtomicLong sequenceNumbers;
55 private EventListener listener;
57 private AtomicLong nextEventId;
59 private XMLRouterConfiguration config;
61 private Map<Id<Destination>, Destination> destinations;
63 public XMLRouter(Clock aClock, XMLRouterConfiguration aConfig,
64 EventListener aListener) {
65 sequenceNumbers = new AtomicLong(1);
68 nextEventId = new AtomicLong(clock.currentTimeMillis());
70 destinations = new LinkedHashMap<Id<Destination>, Destination>();
74 public void publish(String aSource, DOMSource aEvent) {
75 config.startPublishEvent();
77 publishImpl(aSource, aEvent);
79 config.endPublishEvent();
83 private void publishImpl(String aSource, DOMSource aEvent) {
84 long time = clock.currentTimeMillis();
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);
90 boolean delivered = false;
93 List<String> filteredInputTypes = determineFilteredInputTypes(
95 if (filteredInputTypes.isEmpty()) {
96 if (LOGGER.isLoggable(Level.FINE)) {
97 String doc = new XMLDocument(aEvent).print(true);
101 "Event ''0}'' from source {1} removed because of filters.",
102 new Object[] { doc, aSource });
106 // get the reachable target types through transformations.
108 // It is possible that a given event belongs to multiple input
110 // This is however certainly not the main case.
112 for (String inputType : filteredInputTypes) {
113 boolean result = deliverEvent(info, inputType);
114 delivered = delivered || result;
118 destinationNotFound(aSource, aEvent);
119 listener.notDelivered(info);
124 private boolean deliverEvent(EventInfo aInfo, String aInputType) {
126 boolean delivered = false;
127 Set<String> possibleTargetTypes = new HashSet<String>();
128 possibleTargetTypes.addAll(config.getTransformations()
129 .getPossibleTargetTypes(aInputType));
131 // ask each destination what target types, if any they want to have.
132 for (Map.Entry<Id<Destination>, Destination> entry : destinations
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();
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);
156 if (!isAllowedByFilters(t.getToType(), transformed)) {
161 if (allowed && transformed != null) {
162 // all transformations done and all filters still
164 boolean result = destination.receive(transformed);
165 listener.delivered(aInfo, ts, destinationId.getId(),
167 delivered = delivered || result;
176 private List<String> determineFilteredInputTypes(List<String> aTypes,
179 // apply filters to the input
180 List<String> filteredTypes = new ArrayList<String>();
181 for (String type : aTypes) {
182 boolean allowed = isAllowedByFilters(type, aEvent);
184 filteredTypes.add(type);
187 return filteredTypes;
190 private boolean isAllowedByFilters(String aType, DOMSource aEvent) {
191 boolean allowed = true;
192 for (Filter filter : config.getRouterConfig().filterConfig().values()) {
193 if (!filter.isAllowed(aType, aEvent)) {
200 private List<String> determineDocumentTypes(DOMSource aEvent) {
201 List<String> res = new ArrayList<String>();
202 for (DocumentType type : config.getRouterConfig().documentTypeConfig()
204 if (type.isInstance(aEvent)) {
205 res.add(type.getName());
211 private String eventToString(String aSource, DOMSource aEvent) {
212 return "source '" + aSource + "': Event: '" +
213 new XMLDocument(aEvent).print(true) + "'";
216 private void transformationReturnedNull(String aSource, DOMSource aEvent,
217 String aInputType, Transformation aT, DOMSource aTransformed) {
218 LOGGER.log(Level.WARNING, "Transformation returned null for event " +
219 eventToString(aSource, aEvent) + " inputType '" + aInputType +
220 "', transformation '" + aT + "' document to transform " +
221 new XMLDocument(aTransformed).print(true));
224 private void destinationNotFound(String aSource, DOMSource aEvent) {
225 LOGGER.log(Level.WARNING, "No destination found for event: " +
226 eventToString(aSource, aEvent));
230 public Id<Destination> registerDestination(Destination aDestination) {
231 notNull("destination", aDestination);
232 long seqno = sequenceNumbers.getAndIncrement();
233 Id<Destination> id = new Id<Destination>(seqno + "");
234 destinations.put(id, new RobustDestination(id, aDestination));
239 public void unregisterDestination(Id<Destination> aId) {
240 destinations.remove(aId);
243 private void notNull(String aName, Object aValue) {
244 if (aValue == null) {
245 throw new IllegalArgumentException("Parameter '" + aName +
246 "' may not be null");