001/*****************************************************************************
002 * Copyright (C) PicoContainer Organization. All rights reserved.            *
003 * ------------------------------------------------------------------------- *
004 * The software in this package is published under the terms of the BSD      *
005 * style license a copy of which has been included with this distribution in *
006 * the LICENSE.txt file.                                                     *
007 *                                                                           *
008 * Original code by                                                          *
009 *****************************************************************************/
010package org.picocontainer.gems.monitors.prefuse;
011
012import java.util.Collection;
013import java.util.HashMap;
014import java.util.Map;
015
016import org.picocontainer.gems.monitors.ComponentDependencyMonitor.Dependency;
017
018import prefuse.data.Graph;
019import prefuse.data.Node;
020import prefuse.data.Schema;
021import prefuse.data.tuple.TupleSet;
022
023public final class PrefuseDependencyGraph implements ComponentDependencyListener {
024    private Graph graph;
025
026    private final Map nodes;
027
028    public PrefuseDependencyGraph() {
029        this.graph = initializeGraph();
030        this.nodes = new HashMap();
031    }
032
033    public void addDependency(final Dependency dependency) {
034        Node componentNode = addNode(dependency.getComponentType());
035        Node dependencyNode = addNode(dependency.getDependencyType());
036        if (dependencyNode != null) {
037            graph.addEdge(componentNode, dependencyNode);
038        }
039    }
040
041    Collection getTypes() {
042        return nodes.keySet();
043    }
044
045    Node[] getNodes() {
046        return (Node[]) nodes.values().toArray(new Node[nodes.size()]);
047    }
048
049    private Node addNode(final Class type) {
050        if (type != null && !nodes.containsKey(type)) {
051            Node node = graph.addNode();
052            node.set("type", type);
053            nodes.put(type, node);
054        }
055        return (Node) nodes.get(type);
056    }
057
058    private Graph initializeGraph() {
059        return getGraph(getSchema());
060    }
061
062    private Graph getGraph(final Schema schema) {
063        graph = new Graph(true);
064        graph.addColumns(schema);
065        return graph;
066    }
067
068    private Schema getSchema() {
069        Schema schema = new Schema();
070        schema.addColumn("type", Class.class, null);
071        return schema;
072    }
073
074    public TupleSet getEdges() {
075        return graph.getEdges();
076    }
077
078    public Graph getGraph() {
079        return graph;
080    }
081}