model.DrawTopologyDiagram.java Source code

Java tutorial

Introduction

Here is the source code for model.DrawTopologyDiagram.java

Source

/*
 * Copyright (c) 2003, the JUNG Project and the Regents of the University of
 * California All rights reserved.
 *
 * This software is open-source under the BSD license; see either "license.txt"
 * or http://jung.sourceforge.net/license.txt for a description.
 *
 * Created on May 10, 2004
 */

package model;

import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
import edu.uci.ics.jung.algorithms.layout.FRLayout;
import edu.uci.ics.jung.algorithms.layout.FRLayout2;
import edu.uci.ics.jung.algorithms.layout.ISOMLayout;
import edu.uci.ics.jung.algorithms.layout.KKLayout;
import edu.uci.ics.jung.algorithms.layout.SpringLayout;
import edu.uci.ics.jung.algorithms.layout.util.Relaxer;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.ObservableGraph;
import edu.uci.ics.jung.graph.event.GraphEvent;
import edu.uci.ics.jung.graph.event.GraphEventListener;
import edu.uci.ics.jung.graph.util.Graphs;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.picking.PickedState;
import edu.uci.ics.jung.visualization.renderers.Renderer;
import model.VertexTopology;
import model.TestCase;

import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import org.apache.commons.collections15.functors.ConstantTransformer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JSplitPane;

/**
 * Demonstrates visualization of a graph being actively updated.
 *
 * @author danyelf
 */
public class DrawTopologyDiagram extends javax.swing.JApplet {
    private Map<VertexTopology, List<VertexTopology>> vertexForDiagram = new HashMap<VertexTopology, List<VertexTopology>>();
    /**
    *
    */
    //   private static final long serialVersionUID = -5345319851341875800L;

    private Graph<VertexTopology, Number> g = null;

    private VisualizationViewer<VertexTopology, Number> vv = null;

    private AbstractLayout<VertexTopology, Number> layout = null;

    Timer timer;

    boolean done;

    protected JButton switchLayout;

    //    public static final LengthFunction<Number> UNITLENGTHFUNCTION = new SpringLayout.UnitLengthFunction<Number>(
    //            100);
    public static final int EDGE_LENGTH = 100;

    @Override
    public void init() {

        //create a graph
        Graph<VertexTopology, Number> ig = Graphs.<VertexTopology, Number>synchronizedDirectedGraph(
                new DirectedSparseMultigraph<VertexTopology, Number>());

        ObservableGraph<VertexTopology, Number> og = new ObservableGraph<VertexTopology, Number>(ig);
        og.addGraphEventListener(new GraphEventListener<VertexTopology, Number>() {

            public void handleGraphEvent(GraphEvent<VertexTopology, Number> evt) {
                System.err.println("got " + evt);

            }
        });
        this.g = og;
        //layouts
        //create a graphdraw
        //        layout = new FRLayout2<String,Number>(g);
        //        layout = new SpringLayout<String,Number>(g);
        //        ((FRLayout)layout).setMaxIterations(200);
        layout = new KKLayout<VertexTopology, Number>(g);

        vv = new VisualizationViewer<VertexTopology, Number>(layout, new Dimension(600, 600));

        createGraph();

        Container content = getContentPane();
        JPanel totalCasesPanel = new JPanel();

        final JPanel scaleGrids = new JPanel(new GridLayout(0, 2));
        scaleGrids.add(new JLabel("   Test Cases      "));
        scaleGrids.add(new JLabel("       "));
        totalCasesPanel.add(scaleGrids);

        JPanel filteredCasesPanel = new JPanel();

        final JPanel filteredGrids = new JPanel(new GridLayout(0, 2));
        filteredGrids.add(new JLabel("   Filtered Cases      "));
        filteredGrids.add(new JLabel("       "));
        filteredCasesPanel.add(filteredGrids);

        JRootPane rp = this.getRootPane();
        rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

        content.setLayout(new BorderLayout());
        content.setBackground(java.awt.Color.lightGray);
        content.setFont(new Font("Serif", Font.PLAIN, 12));

        vv.getModel().getRelaxer().setSleepTime(500);
        vv.setGraphMouse(new DefaultModalGraphMouse<VertexTopology, Number>());

        vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);

        vv.setForeground(Color.white);

        FontMetrics fm = vv.getFontMetrics(vv.getFont());
        int width = fm.stringWidth(g.toString());

        Transformer<VertexTopology, Shape> vertexSize = new Transformer<VertexTopology, Shape>() {
            public Shape transform(VertexTopology i) {

                Ellipse2D circle = new Ellipse2D.Double(-20, -20, 40, 40);
                // in this case, the vertex is twice as large                
                return circle;
            }

        };

        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
            @Override
            public String transform(Object v) {

                return ((VertexTopology) v).getScreenName();
            }
        });

        vv.getRenderContext().setVertexShapeTransformer(vertexSize);

        //Get picked states
        final PickedState<VertexTopology> pickedState = vv.getPickedVertexState();
        pickedState.addItemListener(new ItemListener() {
            ArrayList<TestCase> outputTestCase = new ArrayList<TestCase>();
            final Map<String, JButton> createdBtns = new HashMap<String, JButton>();

            Map<String, Integer> deviceSelected = new HashMap<String, Integer>(); // not useful

            ArrayList<String> endPointList = new ArrayList<String>();

            @Override
            public void itemStateChanged(ItemEvent e) {
                // TODO Auto-generated method stub
                Object subject = e.getItem();
                if (e.getStateChange() != 1) {
                    scaleGrids.removeAll();
                    filteredGrids.removeAll();
                    endPointList.remove(getScreenName(subject));

                    outputTestCase.clear();

                    filteredGrids.repaint();
                    filteredGrids.add(new JLabel("   Filtered Cases      "));
                    filteredGrids.add(new JLabel("       "));

                    scaleGrids.repaint();
                    scaleGrids.add(new JLabel("   Test Cases      "));
                    scaleGrids.add(new JLabel("       "));

                    deviceSelected.clear();

                }
                if (e.getStateChange() == 1) {

                    for (TestCase testCase : outputTestCase) {
                        scaleGrids.removeAll();
                        scaleGrids.add(new JLabel("   Test Cases      "));
                        scaleGrids.add(new JLabel("       "));

                        filteredGrids.removeAll();
                        filteredGrids.add(new JLabel("   Filtered Cases      "));
                        filteredGrids.add(new JLabel("       "));

                    }

                    if (subject instanceof VertexTopology) {
                        final VertexTopology edgePicked = (VertexTopology) subject;
                        if (pickedState.isPicked(edgePicked)) {

                            for (TestCase testCase : edgePicked.getTestCaseList()) {
                                if (!outputTestCase.contains(testCase))
                                    outputTestCase.add(testCase);
                                System.out.println("The size for reference is " + testCase.inputReferenceMap.size()
                                        + testCase.getName());
                                System.out.println("The size for target is " + testCase.inputTargetMap.size()
                                        + testCase.getName());
                            }

                            if (deviceSelected.get(edgePicked.getScreenName()) != null)
                                deviceSelected.put(edgePicked.getScreenName(),
                                        deviceSelected.get(edgePicked.getScreenName()) + 1);
                            else
                                deviceSelected.put(edgePicked.getScreenName(), 1);

                            endPointList.add(edgePicked.getScreenName());

                        }
                    }
                }

                for (TestCase testCase : outputTestCase) {
                    JButton btnCase = new JButton(testCase.getName());
                    scaleGrids.add(btnCase);

                    if (testCase.getInputDeviceList().size() <= endPointList.size())
                        if (testCaseSelected(testCase, endPointList)) {
                            JButton btnCaseFiltered = new JButton(testCase.getName());
                            filteredGrids.add(btnCaseFiltered);
                        }
                    ;

                }

                scaleGrids.revalidate();
                scaleGrids.setVisible(true);
            }

        });

        final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
        vv.setGraphMouse(graphMouse);
        graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

        content.setPreferredSize(new Dimension(1400, 900));
        content.add(vv);
        switchLayout = new JButton("Switch to SpringLayout");
        //        switchLayout.addActionListener(new ActionListener() {
        //
        //            @SuppressWarnings("unchecked")
        //            public void actionPerformed(ActionEvent ae) {
        //               Dimension d = new Dimension(600,600);
        //                if (switchLayout.getText().indexOf("Spring") > 0) {
        //                    switchLayout.setText("Switch to FRLayout");
        //                    layout = new SpringLayout<String,Number>(g,
        //                        new ConstantTransformer(EDGE_LENGTH));
        //                    layout.setSize(d);
        //                    vv.getModel().setGraphLayout(layout, d);
        //                } else {
        //                    switchLayout.setText("Switch to SpringLayout");
        //                    layout = new FRLayout<String,Number>(g, d);
        //                    vv.getModel().setGraphLayout(layout, d);
        //                }
        //            }
        //        });

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, totalCasesPanel, filteredCasesPanel);
        jSplitPane.setResizeWeight(.5d);

        content.add(switchLayout, BorderLayout.SOUTH);
        content.add(jSplitPane, BorderLayout.EAST);
    }

    private String getScreenName(Object subject) {
        VertexTopology edgePicked = (VertexTopology) subject;
        return edgePicked.getScreenName();
    }

    public boolean testCaseSelected(TestCase testCase, ArrayList<String> endPointList) {
        //Make a clone to make changes    
        List<ArrayList<String>> inputDeviceList = new ArrayList<ArrayList<String>>(
                testCase.getInputDeviceList().size());
        for (ArrayList<String> p : testCase.getInputDeviceList()) {
            ArrayList<String> tempList = new ArrayList<String>(p.size());
            for (String endPointTemp : tempList)
                p.add(endPointTemp);
            inputDeviceList.add(p);
        }

        List<String> endPointListTemp = new ArrayList<String>(endPointList.size());
        for (String temp : endPointList)
            endPointListTemp.add(temp);

        //first filter out relevant endpoints
        for (ArrayList<String> inputDeviceListTemp : inputDeviceList) {
            inputDeviceListTemp.retainAll(endPointListTemp);

        }
        //sort with lowest first
        Collections.sort(inputDeviceList, new Comparator<ArrayList>() {
            public int compare(ArrayList a1, ArrayList a2) {
                return a1.size() - a2.size(); // assumes you want biggest to smallest
            }
        });
        // remove similar
        int similarCount = 0;
        for (int i = 0; i < inputDeviceList.size(); i++) {
            if (endPointListTemp.size() < 1)
                break;
            for (String temp : inputDeviceList.get(i)) {
                if (endPointListTemp.size() > 0) {
                    if (endPointListTemp.contains(temp)) {
                        endPointListTemp.remove(temp);
                        similarCount++;
                        break;
                    }
                }
            }
        }
        if (similarCount == testCase.getInputDeviceList().size())
            return true;
        else
            return false;
    }

    Integer v_prev = null;

    class RemindTask extends TimerTask {

        @Override
        public void run() {
            //            process();
            if (done)
                cancel();

        }
    }

    //    public static void main(String[] args) {
    //       DrawTopologyDiagram and = new DrawTopologyDiagram();
    //       JFrame frame = new JFrame();
    //       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //       frame.getContentPane().add(and);
    //
    //       and.init();
    //       and.draw();
    //       frame.pack();
    //       frame.setVisible(true);
    //    }

    //    private  void createTree() {
    //       g.addEdge(edgeFactory.create(), "Carbon", "Calypso");
    //       g.addEdge(edgeFactory.create(), "Carbon2", "Calypso");
    //       g.addEdge(edgeFactory.create(), "Carbon3", "Calypso");
    //       g.addEdge(edgeFactory.create(), "mx300g2", "asterix-ref");
    //       g.addEdge(edgeFactory.create(), "sx20", "asterix-ref");
    //       g.addEdge(edgeFactory.create(), "drishti", "asterix-ref");
    //       g.addEdge(edgeFactory.create(), "dx70", "asterix-ref");
    //       g.addEdge(edgeFactory.create(), "dx80", "asterix-ref");    
    //    }

    public Map<VertexTopology, List<VertexTopology>> getVertexForDiagram() {
        return vertexForDiagram;
    }

    public void setVertexForDiagram(Map<VertexTopology, List<VertexTopology>> vertexForDiagram) {
        this.vertexForDiagram = vertexForDiagram;
    }

    Factory<Integer> edgeFactory = new Factory<Integer>() {
        int i = 0;

        public Integer create() {
            return i++;
        }
    };

    private void createGraph() {
        for (Entry<VertexTopology, List<VertexTopology>> vertex : vertexForDiagram.entrySet()) {
            for (VertexTopology vertexRef : vertex.getValue()) {
                g.addEdge(edgeFactory.create(), vertex.getKey(), vertexRef);
            }

        }

    }
}