package Dijkstra;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;
import cgl.imr.base.SerializationException;
public class Node {
private int id;
public Hashtable<Integer, Integer> edges = new Hashtable<Integer, Integer>();
public Node(String str) {
String[] line = str.split("\t");
String key = line[0];
String value = line[1];
this.id = Integer.parseInt(key);
// populating node with edges and weights
for (String s : value.split("\\|")) {
String[] s1 = s.split(",");
this.edges.put(Integer.parseInt(s1[0]), Integer.parseInt(s1[1]));
}
}
public Node(int id) {
this.id = id;
}
public Node(byte[] data) throws SerializationException {
fromBytes(data);
}
public void fromBytes(byte[] data) throws SerializationException {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bis);
try {
this.id = dis.readInt();
int count = dis.readInt();
if (count != -1) {
for (int i = 0; i < count; i++) {
int edge = dis.readInt();
int weight = dis.readInt();
this.edges.put(edge, weight);
}
}
dis.close();
bis.close();
} catch (IOException ioe) {
throw new SerializationException(ioe);
}
}
public int getID() {
return this.id;
}
public Hashtable<Integer, Integer> getEdges() {
return this.edges;
}
public void setEdgeWeight(int edge, int weight) {
this.edges.put(edge, weight);
}
public int getEdgeWeight(int edge) {
return this.edges.get(edge);
}
public String getLine() {
StringBuffer s = new StringBuffer();
for (int v : edges.keySet()) {
s.append(v).append(" ,").append(edges.get(v));
s.append(" |");
}
s.deleteCharAt(s.length() - 1);
return s.toString();
}
public byte[] getBytes() throws SerializationException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
Set<Integer> count = null;
if (this.edges != null) {
count = this.edges.keySet();
}
byte[] marshalledBytes = null;
try {
dos.writeInt(this.id);
dos.writeInt(count.size());
if (count.size() != -1) {
for (int i : count) {
dos.writeInt(i);
dos.writeInt(this.edges.get(i));
}
}
dos.flush();
marshalledBytes = bos.toByteArray();
bos = null;
dos = null;
} catch (IOException ioe) {
throw new SerializationException(ioe);
}
return marshalledBytes;
}
public void printNode(String str) {
System.out.println(str);
System.out.print(this.getID());
for (int edge : this.getEdges().keySet())
System.out.print(" " + edge + "," + this.getEdgeWeight(edge)
+ " |");
System.out.println();
}
}