1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.rblasch.convert;
17
18 import org.rblasch.convert.converters.ChainedConverter;
19 import org.rblasch.convert.dijkstra.ShortestPathEngine;
20 import org.rblasch.convert.graph.Graphs;
21 import org.rblasch.convert.graph.Path;
22 import org.rblasch.convert.graph.WeightedDirectedGraph;
23 import org.rblasch.convert.type.Type;
24
25 import java.util.Collection;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Set;
31
32 public class ShortestPathLookup implements ConverterLookup {
33 private final WeightedDirectedGraph graph;
34
35 public ShortestPathLookup(final WeightedDirectedGraph g) {
36 this.graph = g;
37 }
38
39 public void addGraph(final WeightedDirectedGraph g) {
40 Graphs.mergeInto(graph, g);
41 }
42
43 public void addType(final Type t) {
44 graph.addVertex(new TypeVertex(t));
45 }
46
47 public void addConverter(final MetaConverter mc) {
48 graph.addConnection(new TypeVertex(mc.getSourceType()),
49 new ConverterEdge(mc, mc.getWeight()),
50 new TypeVertex(mc.getDestinationType()));
51 }
52
53 public void addAllConverters(final Collection
54 for (final Iterator i = mcs.iterator(); i.hasNext();) {
55 addConverter((MetaConverter) i.next());
56 }
57 }
58
59 public int getNumberOfKnownTypes() {
60 return graph.getVertices().size();
61 }
62
63 public int getNumberOfKnownConversions() {
64 return graph.getEdges().size();
65 }
66
67 public Set
68 final Set
69 for (final Iterator i = graph.getVertices().iterator(); i.hasNext();) {
70 final TypeVertex tv = (TypeVertex) i.next();
71 types.add(tv.getType());
72 }
73 return types;
74 }
75
76 private List
77 final List
78
79 for (final Iterator i = path.getEdges().iterator(); i.hasNext();) {
80 final MetaConverter c = ((ConverterEdge) i.next()).getConverter();
81 converters.add(c);
82 }
83
84 return converters;
85 }
86
87 private Path getShortestPath(final Type sourceType, final Type destinationType) throws NoSuchConversionException {
88 final ShortestPathEngine spEngine = new ShortestPathEngine(graph);
89 final Path shortestPath = spEngine.getShortestPath(new TypeVertex(sourceType), new TypeVertex(destinationType));
90 if (shortestPath == null || shortestPath.getEdges().isEmpty()) {
91 throw new NoSuchConversionException("No conversion from " + sourceType + " to " + destinationType + " in " + graph);
92 }
93 return shortestPath;
94 }
95
96 public MetaConverter lookup(final Type sourceType, final Type destinationType) throws NoSuchConversionException {
97 return new ChainedConverter(getConvertersForPath(getShortestPath(sourceType, destinationType)));
98 }
99
100 public boolean equals(final Object obj) {
101 return graph.equals(obj);
102 }
103
104 public int hashCode() {
105 return graph.hashCode();
106 }
107
108 String dumpGraph() {
109 return graph.toString();
110 }
111 }