1 5 package prefuse.data.io; 6 7 import java.io.OutputStream ; 8 import java.io.PrintWriter ; 9 import java.util.Date ; 10 import java.util.HashMap ; 11 12 import prefuse.data.Graph; 13 import prefuse.data.Node; 14 import prefuse.data.Schema; 15 import prefuse.util.io.XMLWriter; 16 17 33 public class TreeMLWriter extends AbstractGraphWriter { 34 35 38 public interface Tokens extends TreeMLReader.Tokens {} 39 40 43 private static final HashMap TYPES = new HashMap (); 44 static { 45 TYPES.put(int.class, Tokens.INT); 46 TYPES.put(long.class, Tokens.LONG); 47 TYPES.put(float.class, Tokens.FLOAT); 48 TYPES.put(double.class, Tokens.REAL); 49 TYPES.put(boolean.class, Tokens.BOOLEAN); 50 TYPES.put(String .class, Tokens.STRING); 51 TYPES.put(Date .class, Tokens.DATE); 52 } 53 54 57 public void writeGraph(Graph graph, OutputStream os) throws DataIOException 58 { 59 Schema ns = graph.getNodeTable().getSchema(); 61 checkTreeMLSchema(ns); 62 63 XMLWriter xml = new XMLWriter(new PrintWriter (os)); 64 xml.begin(); 65 66 xml.comment("prefuse TreeML Writer | " 67 + new Date (System.currentTimeMillis())); 68 69 xml.start(Tokens.TREE); 71 72 xml.start(Tokens.DECLS); 74 String [] attr = new String [] {Tokens.NAME, Tokens.TYPE }; 75 String [] vals = new String [2]; 76 77 for ( int i=0; i<ns.getColumnCount(); ++i ) { 78 vals[0] = ns.getColumnName(i); 79 vals[1] = (String )TYPES.get(ns.getColumnType(i)); 80 xml.tag(Tokens.DECL, attr, vals, 2); 81 } 82 xml.end(); 83 xml.println(); 84 85 86 attr[0] = Tokens.NAME; 88 attr[1] = Tokens.VALUE; 89 90 Node n = graph.getSpanningTree().getRoot(); 91 while ( n != null ) { 92 boolean leaf = (n.getChildCount() == 0); 93 94 if ( leaf ) { 95 xml.start(Tokens.LEAF); 96 } else { 97 xml.start(Tokens.BRANCH); 98 } 99 100 if ( ns.getColumnCount() > 0 ) { 101 for ( int i=0; i<ns.getColumnCount(); ++i ) { 102 vals[0] = ns.getColumnName(i); 103 vals[1] = n.getString(vals[0]); 104 xml.tag(Tokens.ATTR, attr, vals, 2); 105 } 106 } 107 n = nextNode(n, xml); 108 } 109 110 xml.end(); 112 xml.finish(); 113 } 114 115 122 private Node nextNode(Node x, XMLWriter xml) { 123 Node n, c; 124 if ( (c=x.getChild(0)) != null ) { 125 } else if ( (c=x.getNextSibling()) != null ) { 127 xml.end(); 128 } else { 129 c = x.getParent(); 130 xml.end(); 131 while ( c != null ) { 132 if ( (n=c.getNextSibling()) != null ) { 133 c = n; 134 xml.end(); 135 break; 136 } 137 c = c.getParent(); 138 xml.end(); 139 } 140 } 141 return c; 142 } 143 144 151 private void checkTreeMLSchema(Schema s) throws DataIOException { 152 for ( int i=0; i<s.getColumnCount(); ++i ) { 153 Class type = s.getColumnType(i); 154 if ( TYPES.get(type) == null ) { 155 throw new DataIOException("Data type unsupported by the " 156 + "TreeML format: " + type.getName()); 157 } 158 } 159 } 160 161 } | Popular Tags |