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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. return Path.createFastestPathFromNodes(graph, nodes);
  45. }
  46. /**
  47. * Read a node from the input stream and returns it.
  48. *
  49. * @param graph Graph containing the nodes.
  50. *
  51. * @return The next node in the input stream.
  52. *
  53. * @throws IOException if something occurs while reading the note.
  54. * @throws IndexOutOfBoundsException if the node is not in the graph.
  55. */
  56. protected Node readNode(Graph graph) throws IOException {
  57. return graph.getNodes().get(dis.readInt());
  58. }
  59. }