No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BinaryPathReader.java 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package org.insa.graph.io;
  2. import java.io.DataInputStream;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import org.insa.graph.Graph;
  6. import org.insa.graph.Node;
  7. import org.insa.graph.Path;
  8. /**
  9. * Implementation of {@link PathReader} to read paths in binary format.
  10. *
  11. */
  12. public class BinaryPathReader extends BinaryReader implements PathReader {
  13. // Map version and magic number targeted for this reader.
  14. protected static final int VERSION = 1;
  15. protected static final int MAGIC_NUMBER = 0xdecafe;
  16. /**
  17. * Create a new BinaryPathReader that read from the given input stream.
  18. *
  19. * @param dis Input stream to read from.
  20. */
  21. public BinaryPathReader(DataInputStream dis) {
  22. super(MAGIC_NUMBER, VERSION, dis);
  23. }
  24. @Override
  25. public Path readPath(Graph graph) throws IOException {
  26. // Read and check magic number and version.
  27. checkMagicNumberOrThrow(dis.readInt());
  28. checkVersionOrThrow(dis.readInt());
  29. // Read map ID and check against graph.
  30. String mapId = readFixedLengthString(BinaryGraphReader.MAP_ID_FIELD_LENGTH, "UTF-8");
  31. if (!mapId.equals(graph.getMapId())) {
  32. throw new MapMismatchException(mapId, graph.getMapId());
  33. }
  34. // Number of nodes in the path (without first and last).
  35. int nbNodes = dis.readInt();
  36. // Skip (duplicate) first and last node
  37. readNode(graph);
  38. readNode(graph);
  39. // Read intermediate nodes:
  40. ArrayList<Node> nodes = new ArrayList<Node>();
  41. for (int i = 0; i < nbNodes; ++i) {
  42. nodes.add(readNode(graph));
  43. }
  44. this.dis.close();
  45. return Path.createFastestPathFromNodes(graph, nodes);
  46. }
  47. /**
  48. * Read a node from the input stream and returns it.
  49. *
  50. * @param graph Graph containing the nodes.
  51. *
  52. * @return The next node in the input stream.
  53. *
  54. * @throws IOException if something occurs while reading the note.
  55. * @throws IndexOutOfBoundsException if the node is not in the graph.
  56. */
  57. protected Node readNode(Graph graph) throws IOException {
  58. return graph.get(dis.readInt());
  59. }
  60. }