Beispiel #1
0
  int[] readPlanarRGB(InputStream in) throws IOException {
    if (fi.compression > FileInfo.COMPRESSION_NONE) return readCompressedPlanarRGBImage(in);
    DataInputStream dis = new DataInputStream(in);
    int planeSize = nPixels; // 1/3 image size
    byte[] buffer = new byte[planeSize];
    int[] pixels = new int[nPixels];
    int r, g, b;

    startTime = 0L;
    showProgress(10, 100);
    dis.readFully(buffer);
    for (int i = 0; i < planeSize; i++) {
      r = buffer[i] & 0xff;
      pixels[i] = 0xff000000 | (r << 16);
    }

    showProgress(40, 100);
    dis.readFully(buffer);
    for (int i = 0; i < planeSize; i++) {
      g = buffer[i] & 0xff;
      pixels[i] |= g << 8;
    }

    showProgress(70, 100);
    dis.readFully(buffer);
    for (int i = 0; i < planeSize; i++) {
      b = buffer[i] & 0xff;
      pixels[i] |= b;
    }

    showProgress(90, 100);
    return pixels;
  }
  /**
   * Open FBS file identified by {@link #fbsURL}. The stream is positioned at the entry point
   * described by <code>entryPoint</code>.
   *
   * @param entryPoint entry point information.
   * @return a newly created FBS input stream on success, <code>null</code> if any error occured and
   *     the FBS stream is not opened.
   * @throws java.io.IOException if an I/O exception occurs.
   */
  private FbsInputStream openFbsFile(FbsEntryPoint entry) throws IOException {

    System.err.println("Entering FBS at " + entry.timestamp + " ms");

    // Make sure the protocol is HTTP.
    if (!fbkURL.getProtocol().equalsIgnoreCase("http")
        || !fbsURL.getProtocol().equalsIgnoreCase("http")) {
      System.err.println("Indexed access requires HTTP protocol in URLs");
      return null;
    }

    // Seek to the keyframe.
    InputStream is = openHttpByteRange(fbkURL, entry.key_fpos, entry.key_size);
    if (is == null) {
      return null;
    }

    // Load keyframe data from the .fbk file, prepend RFB initialization data.
    DataInputStream data = new DataInputStream(is);
    byte[] keyData = new byte[rfbInitData.length + (int) entry.key_size];
    System.arraycopy(rfbInitData, 0, keyData, 0, rfbInitData.length);
    data.readFully(keyData, rfbInitData.length, (int) entry.key_size);
    data.close();

    // Open the FBS stream.
    is = openHttpByteRange(fbsURL, entry.fbs_fpos, -1);
    if (is == null) {
      return null;
    }
    return new FbsInputStream(is, entry.timestamp, keyData, entry.fbs_skip);
  }
Beispiel #3
0
 public MessageRunnable(int msz, int mtp, DataInputStream di)
     throws IOException, SocketException {
   msgsize = msz;
   msgtype = mtp;
   msgbytes = new byte[msgsize - 2];
   di.readFully(msgbytes);
   // di.read(msgbytes);
   din = new DataInputStream(new ByteArrayInputStream(msgbytes));
 }
Beispiel #4
0
 Object readRGB48(InputStream in) throws IOException {
   if (fi.compression > FileInfo.COMPRESSION_NONE) return readCompressedRGB48(in);
   int channels = fi.samplesPerPixel;
   short[][] stack = new short[channels][nPixels];
   DataInputStream dis = new DataInputStream(in);
   int pixel = 0;
   int min = 65535, max = 0;
   if (fi.stripLengths == null) {
     fi.stripLengths = new int[fi.stripOffsets.length];
     fi.stripLengths[0] = width * height * bytesPerPixel;
   }
   for (int i = 0; i < fi.stripOffsets.length; i++) {
     if (i > 0) {
       long skip =
           (fi.stripOffsets[i] & 0xffffffffL)
               - (fi.stripOffsets[i - 1] & 0xffffffffL)
               - fi.stripLengths[i - 1];
       if (skip > 0L) dis.skip(skip);
     }
     int len = fi.stripLengths[i];
     int bytesToGo = (nPixels - pixel) * channels * 2;
     if (len > bytesToGo) len = bytesToGo;
     byte[] buffer = new byte[len];
     dis.readFully(buffer);
     int value;
     int channel = 0;
     boolean intel = fi.intelByteOrder;
     for (int base = 0; base < len; base += 2) {
       if (intel) value = ((buffer[base + 1] & 0xff) << 8) | (buffer[base] & 0xff);
       else value = ((buffer[base] & 0xff) << 8) | (buffer[base + 1] & 0xff);
       if (value < min) min = value;
       if (value > max) max = value;
       stack[channel][pixel] = (short) (value);
       channel++;
       if (channel == channels) {
         channel = 0;
         pixel++;
       }
     }
     showProgress(i + 1, fi.stripOffsets.length);
   }
   this.min = min;
   this.max = max;
   return stack;
 }
 /**
  * Send a plugin JAR file to the client
  *
  * @param data the plugin name
  */
 private void sendPlugin(ObjectConnection oc, String data) {
   DataInputStream dis = null;
   try {
     dis = new DataInputStream(new FileInputStream(APPLICATIONS_DIRECTORY + data + ".jar"));
     byte[] buf = new byte[dis.available()];
     dis.readFully(buf);
     oc.write(buf);
   } catch (Exception e) {
     Logging.getLogger().warning("Unable to send the file: " + data + ".jar");
   } finally {
     if (dis != null) {
       try {
         dis.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
Beispiel #6
0
 float[] read24bitImage(InputStream in) throws IOException {
   byte[] buffer = new byte[width * 3];
   float[] pixels = new float[nPixels];
   int b1, b2, b3;
   DataInputStream dis = new DataInputStream(in);
   for (int y = 0; y < height; y++) {
     // IJ.log("read24bitImage: ");
     dis.readFully(buffer);
     int b = 0;
     for (int x = 0; x < width; x++) {
       b1 = buffer[b++] & 0xff;
       b2 = buffer[b++] & 0xff;
       b3 = buffer[b++] & 0xff;
       pixels[x + y * width] = (b3 << 16) | (b2 << 8) | b1;
     }
   }
   return pixels;
 }
Beispiel #7
0
 Object readCompressedRGB48(InputStream in) throws IOException {
   if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING)
     throw new IOException("ImageJ cannot open 48-bit LZW compressed TIFFs with predictor");
   int channels = 3;
   short[][] stack = new short[channels][nPixels];
   DataInputStream dis = new DataInputStream(in);
   int pixel = 0;
   int min = 65535, max = 0;
   for (int i = 0; i < fi.stripOffsets.length; i++) {
     if (i > 0) {
       long skip =
           (fi.stripOffsets[i] & 0xffffffffL)
               - (fi.stripOffsets[i - 1] & 0xffffffffL)
               - fi.stripLengths[i - 1];
       if (skip > 0L) dis.skip(skip);
     }
     int len = fi.stripLengths[i];
     byte[] buffer = new byte[len];
     dis.readFully(buffer);
     buffer = uncompress(buffer);
     len = buffer.length;
     if (len % 2 != 0) len--;
     int value;
     int channel = 0;
     boolean intel = fi.intelByteOrder;
     for (int base = 0; base < len && pixel < nPixels; base += 2) {
       if (intel) value = ((buffer[base + 1] & 0xff) << 8) | (buffer[base] & 0xff);
       else value = ((buffer[base] & 0xff) << 8) | (buffer[base + 1] & 0xff);
       if (value < min) min = value;
       if (value > max) max = value;
       stack[channel][pixel] = (short) (value);
       channel++;
       if (channel == channels) {
         channel = 0;
         pixel++;
       }
     }
     showProgress(i + 1, fi.stripOffsets.length);
   }
   this.min = min;
   this.max = max;
   return stack;
 }
  private final byte[] loadfile(String s, byte abyte0[]) {
    try {
      File file = new File(s);
      System.out.println("trying to load:" + file);
      int i = (int) file.length();
      DataInputStream datainputstream = new DataInputStream(new FileInputStream(s));
      byte abyte1[] = new byte[i];
      datainputstream.readFully(abyte1, 0, i);
      datainputstream.close();
      m.reset();
      m.update(abyte1);
      byte abyte2[] = m.digest();
      for (int j = 0; j < 20; j++) if (abyte2[j] != abyte0[j]) return null;

      return abyte1;
    } catch (Exception _ex) {
      return null;
    }
  }
 byte[] download(File f) {
   if (!f.exists()) {
     IJ.error("Plugin Installer", "File not found: " + f);
     return null;
   }
   byte[] data = null;
   try {
     int len = (int) f.length();
     InputStream in = new BufferedInputStream(new FileInputStream(f));
     DataInputStream dis = new DataInputStream(in);
     data = new byte[len];
     dis.readFully(data);
     dis.close();
   } catch (Exception e) {
     IJ.error("Plugin Installer", "" + e);
     data = null;
   }
   return data;
 }
    /**
     * Reads the peer's address. First a cookie has to be sent which has to match my own cookie,
     * otherwise the connection will be refused
     */
    private Address readPeerAddress(Socket client_sock) throws Exception {
      int timeout = client_sock.getSoTimeout();
      client_sock.setSoTimeout(peer_addr_read_timeout);

      try {
        // read the cookie first
        byte[] input_cookie = new byte[cookie.length];
        in.readFully(input_cookie, 0, input_cookie.length);
        if (!matchCookie(input_cookie))
          throw new SocketException(
              "ConnectionMap.Connection.readPeerAddress(): cookie read by "
                  + getLocalAddress()
                  + " does not match own cookie; terminating connection");
        // then read the version
        short version = in.readShort();

        if (!Version.isBinaryCompatible(version)) {
          if (log.isWarnEnabled())
            log.warn(
                new StringBuilder("packet from ")
                    .append(client_sock.getInetAddress())
                    .append(':')
                    .append(client_sock.getPort())
                    .append(" has different version (")
                    .append(Version.print(version))
                    .append(") from ours (")
                    .append(Version.printVersion())
                    .append("). This may cause problems")
                    .toString());
        }
        Address client_peer_addr = new IpAddress();
        client_peer_addr.readFrom(in);

        updateLastAccessed();
        return client_peer_addr;
      } finally {
        client_sock.setSoTimeout(timeout);
      }
    }
Beispiel #11
0
 byte[] read1bitImage(InputStream in) throws IOException {
   if (fi.compression == FileInfo.LZW)
     throw new IOException("ImageJ cannot open 1-bit LZW compressed TIFFs");
   int scan = (int) Math.ceil(width / 8.0);
   int len = scan * height;
   byte[] buffer = new byte[len];
   byte[] pixels = new byte[nPixels];
   DataInputStream dis = new DataInputStream(in);
   dis.readFully(buffer);
   int value1, value2, offset, index;
   for (int y = 0; y < height; y++) {
     offset = y * scan;
     index = y * width;
     for (int x = 0; x < scan; x++) {
       value1 = buffer[offset + x] & 0xff;
       for (int i = 7; i >= 0; i--) {
         value2 = (value1 & (1 << i)) != 0 ? 255 : 0;
         if (index < pixels.length) pixels[index++] = (byte) value2;
       }
     }
   }
   return pixels;
 }
Beispiel #12
0
 short[] read12bitImage(InputStream in) throws IOException {
   int bytesPerLine = (int) (width * 1.5);
   if ((width & 1) == 1) bytesPerLine++; // add 1 if odd
   byte[] buffer = new byte[bytesPerLine * height];
   short[] pixels = new short[nPixels];
   DataInputStream dis = new DataInputStream(in);
   dis.readFully(buffer);
   for (int y = 0; y < height; y++) {
     int index1 = y * bytesPerLine;
     int index2 = y * width;
     int count = 0;
     while (count < width) {
       pixels[index2 + count] =
           (short) (((buffer[index1] & 0xff) * 16) + ((buffer[index1 + 1] >> 4) & 0xf));
       count++;
       if (count == width) break;
       pixels[index2 + count] =
           (short) (((buffer[index1 + 1] & 0xf) * 256) + (buffer[index1 + 2] & 0xff));
       count++;
       index1 += 3;
     }
   }
   return pixels;
 }
Beispiel #13
0
  /**
   * Reads the peer's address. First a cookie has to be sent which has to match my own cookie,
   * otherwise the connection will be refused
   */
  protected Address readPeerAddress(Socket client_sock) throws Exception {
    int timeout = client_sock.getSoTimeout();
    client_sock.setSoTimeout(server.peerAddressReadTimeout());

    try {
      // read the cookie first
      byte[] input_cookie = new byte[cookie.length];
      in.readFully(input_cookie, 0, input_cookie.length);
      if (!Arrays.equals(cookie, input_cookie))
        throw new SocketException(
            "BaseServer.TcpConnection.readPeerAddress(): cookie read by "
                + server.localAddress()
                + " does not match own cookie; terminating connection");
      // then read the version
      short version = in.readShort();
      if (!Version.isBinaryCompatible(version))
        throw new IOException(
            "packet from "
                + client_sock.getInetAddress()
                + ":"
                + client_sock.getPort()
                + " has different version ("
                + Version.print(version)
                + ") from ours ("
                + Version.printVersion()
                + "); discarding it");
      short addr_len = in.readShort(); // only needed by NioConnection

      Address client_peer_addr = new IpAddress();
      client_peer_addr.readFrom(in);
      updateLastAccessed();
      return client_peer_addr;
    } finally {
      client_sock.setSoTimeout(timeout);
    }
  }
  public final void run() {
    if (socketthread) {
      socketrun();
      return;
    }
    socketthread = true;
    try {
      boolean flag = false;
      try {
        String s = getParameter("member");
        int i = Integer.parseInt(s);
        if (i == 1) flag = true;
      } catch (Exception _ex) {
      }
      loading = getImage(new URL(getCodeBase(), "loading.jpg"));
      mt = new MediaTracker(this);
      mt.addImage(loading, 0);
      m = MessageDigest.getInstance("SHA");
      System.out.println(link.class);
      String s1 = ".file_store_32/";
      if (s1 == null) return;
      link.uid = getuid(s1);
      link.mainapp = this;
      link.numfile = 0;
      for (int j = 0; j < 14; j++)
        if (flag || !internetname[j].endsWith(".mem")) {
          for (int k = 0; k < 4; k++) {
            if (k == 3) return;
            byte abyte0[] = loadfile(s1 + localname[j], sha[j]);
            if (abyte0 != null) {
              if (j > 0) link.putjag(internetname[j], abyte0);
              break;
            }
            try {
              URL url = new URL(getCodeBase(), internetname[j]);
              DataInputStream datainputstream = new DataInputStream(url.openStream());
              int l = size[j];
              byte abyte1[] = new byte[l];
              for (int i1 = 0; i1 < l; i1 += 1000) {
                int j1 = l - i1;
                if (j1 > 1000) j1 = 1000;
                datainputstream.readFully(abyte1, i1, j1);
                showpercent(nicename[j], (i1 * 100) / l, barpos[j]);
              }

              datainputstream.close();
              FileOutputStream fileoutputstream = new FileOutputStream(s1 + localname[j]);
              fileoutputstream.write(abyte1);
              fileoutputstream.close();
            } catch (Exception _ex) {
            }
          }
        }
      System.out.println(cloader.class);
      cloader cloader1 = new cloader();
      cloader1.zip = new ZipFile(s1 + localname[0]);
      cloader1.link = Class.forName("link");
      inner = new mudclient_Debug();
      loadMacros();
      // inner = (Applet)cloader1.loadClass("mudclient").newInstance();
      inner.init();
      inner.start();
      return;
    } catch (Exception exception) {
      System.out.println(exception + " " + exception.getMessage());
      exception.printStackTrace();
      return;
    }
  }
Beispiel #15
0
  /** Internal method. Get and check response packet from searchd. */
  private byte[] _GetResponse(Socket sock) {
    /* connect */
    DataInputStream sIn = null;
    InputStream SockInput = null;
    try {
      SockInput = sock.getInputStream();
      sIn = new DataInputStream(SockInput);

    } catch (IOException e) {
      _error = "getInputStream() failed: " + e;
      return null;
    }

    /* read response */
    byte[] response = null;
    short status = 0, ver = 0;
    int len = 0;
    try {
      /* read status fields */
      status = sIn.readShort();
      ver = sIn.readShort();
      len = sIn.readInt();

      /* read response if non-empty */
      if (len <= 0) {
        _error = "invalid response packet size (len=" + len + ")";
        return null;
      }

      response = new byte[len];
      sIn.readFully(response, 0, len);

      /* check status */
      if (status == SEARCHD_WARNING) {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(response));

        int iWarnLen = in.readInt();
        _warning = new String(response, 4, iWarnLen);

        System.arraycopy(response, 4 + iWarnLen, response, 0, response.length - 4 - iWarnLen);

      } else if (status == SEARCHD_ERROR) {
        _error = "searchd error: " + new String(response, 4, response.length - 4);
        return null;

      } else if (status == SEARCHD_RETRY) {
        _error = "temporary searchd error: " + new String(response, 4, response.length - 4);
        return null;

      } else if (status != SEARCHD_OK) {
        _error = "searched returned unknown status, code=" + status;
        return null;
      }

    } catch (IOException e) {
      if (len != 0) {
        /* get trace, to provide even more failure details */
        PrintWriter ew = new PrintWriter(new StringWriter());
        e.printStackTrace(ew);
        ew.flush();
        ew.close();
        String sTrace = ew.toString();

        /* build error message */
        _error =
            "failed to read searchd response (status="
                + status
                + ", ver="
                + ver
                + ", len="
                + len
                + ", trace="
                + sTrace
                + ")";
      } else {
        _error = "received zero-sized searchd response (searchd crashed?): " + e.getMessage();
      }
      return null;

    } finally {
      if (_socket == null) {
        try {
          if (sIn != null) sIn.close();
          if (sock != null && !sock.isConnected()) sock.close();
        } catch (IOException e) {
          /* silently ignore close failures; nothing could be done anyway */
        }
      }
    }

    return response;
  }
Beispiel #16
0
 /** Internal method. String IO helper. */
 private static String readNetUTF8(DataInputStream istream) throws IOException {
   int iLen = istream.readInt();
   byte[] sBytes = new byte[iLen];
   istream.readFully(sBytes);
   return new String(sBytes, "UTF-8");
 }
  public static void main(String[] args) throws Exception {
    // prompt user to enter a port number

    System.out.print("Enter the port number: ");
    Scanner scan = new Scanner(System.in);
    int port = scan.nextInt();
    scan.nextLine();
    System.out.print("Enter the host name: ");
    String hostName = scan.nextLine();

    // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair
    // This will take a while: 5...15 seconrds

    System.out.println("Generating a Diffie-Hellman keypair: ");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
    kpg.initialize(PARAMETER_SPEC);
    KeyPair keyPair = kpg.genKeyPair();
    System.out.println("key pair has been made...");

    // one the key pair has been generated, we want to listen on
    // a given port for a connection to come in
    // once we get a connection, we will get two streams, One for input
    // and one for output
    // open a port and wait for a connection

    ServerSocket ss = new ServerSocket(port);
    System.out.println("Listeining on port " + port + " ...");
    Socket socket = ss.accept();

    // use to output and input primitive data type

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // next thing to do is send our public key and receive client's
    // this corresponds to server step 3 and step 4 in the diagram

    System.out.println("Sending my public key...");
    byte[] keyBytes = keyPair.getPublic().getEncoded();
    out.writeInt(keyBytes.length);
    out.write(keyBytes);
    System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes));

    // receive the client's public key

    System.out.println("Receiving client's public key...");
    DataInputStream in = new DataInputStream(socket.getInputStream());
    keyBytes = new byte[in.readInt()];
    in.readFully(keyBytes);

    // create client's public key

    KeyFactory kf = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
    PublicKey clientPublicKey = kf.generatePublic(x509Spec);

    // print out client's public key bytes

    System.out.println(
        "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded()));

    // we can now use the client's public key and
    // our own private key to perform the key agreement

    System.out.println("Performing the key agreement ... ");
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(clientPublicKey, true);

    // in a chat application, each character is sendt over the wire, separetly encrypted,
    // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte)
    // to send each character. We will encrypt the same character in a different way
    // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create
    // that IV randomly and and send it to the client. It doesn't matter if somoene
    // eavesdrops on the IV when it is sent over the wire. it's not sensitive info

    // creating the IV and sending it corresponds to step 6 and 7

    byte[] iv = new byte[8];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(iv);
    out.write(iv);

    // we generate the secret byte array we share with the client and use it
    // to create the session key (Step 8)

    byte[] sessionKeyBytes = ka.generateSecret();

    // create the session key

    SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes);
    SecretKey sessionKey = skf.generateSecret(DESedeSpec);

    // printout session key bytes

    System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded()));

    // now use tha that session key and IV to create a CipherInputStream. We will use them to read
    // all character
    // that are sent to us by the client

    System.out.println("Creating the cipher stream ...");
    Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec);
    CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter);

    // we just keep reading the input and print int to the screen, until -1 sent over

    int theCharacter = 0;
    theCharacter = cipherIn.read();
    while (theCharacter != -1) {
      System.out.print((char) theCharacter);
      theCharacter = cipherIn.read();
    }
    // once -1 is received we want to close up our stream and exit

    cipherIn.close();
    in.close();
    out.close();
    socket.close();
  }
Beispiel #18
0
  /*========================================================================*/
  public void run() {
    /*========================================================================*/
    Thread me = Thread.currentThread();
    RUNNING_LOOP:
    while (thread == me) {
      try {
        // Thread.currentThread().sleep(100);
        int command = dis.readInt();
        switch (command) {
          case -1:
            System.out.println("Got a request to exit");
            /*--------------------------------*/
            /* Command: exit this application */
            /*--------------------------------*/
            break RUNNING_LOOP;
          case 0:
            System.out.println("Got a command #0");
            break;
          case 1:
            /*-------------------------------------------------*/
            /* Command: receiving admin threads status         */
            /* Proto: [NbAdmins:int]                           */
            /*        [Adm1Id:int]                             */
            /*        [Adm1UsernameSize]                       */
            /*        [Adm1User:str50]                         */
            /*        [Adm1Status:int]                         */
            /*        ... until all admins are reported...     */
            /*-------------------------------------------------*/
            System.out.println("Got data on admin connections");
            int nbAdmins = dis.readInt();
            System.out.println("We have " + nbAdmins + "admin connections alike");
            // javax.swing.JButton btnKill[] = new javax.swing.JButton[nbAdmins];
            for (i = 0; i < 10; i++) {
              tblAdmins.setValueAt("", i, 0);
              tblAdmins.setValueAt("", i, 1);
              tblAdmins.setValueAt("", i, 2);
              tblAdmins.setValueAt("", i, 3);
            }
            // tblAdmins.selectAll();
            // tblAdmins.clearSelection();
            for (int i = 0; i < nbAdmins; i++) {
              int id = dis.readInt();
              int usernameSize = dis.readInt();
              byte strData[] = new byte[usernameSize];
              dis.readFully(strData);
              String user = new String(strData);
              int status = dis.readInt();
              tblAdmins.setValueAt(new Integer(id), i, 0);
              tblAdmins.setValueAt(user, i, 1);
              tblAdmins.setValueAt(new Integer(status), i, 2);
              // btnKill[i] = new javax.swing.JButton();
              // tblAdmins.setValueAt(btnKill[i],id,3);

            }
            break;
          default:
            System.out.println("Got unrecognized message");
            break;
        }
      } catch (IOException ioe) {
      }
    } // end of RUNNING_LOOP
    try {
      dis.close();
      dos.close();
    } catch (IOException ioe) {
    }
    System.exit(0);
  }
  /** Load index data from .fbi file to {@link #indexData}. */
  private void loadIndex() {
    // Loading .fbi makes sense only if both .fbi and .fbk files are available.
    if (fbiURL != null && fbkURL != null) {
      FbsEntryPoint[] newIndex;
      int numRecordsRead = 0;
      byte[] newInitData;
      try {
        // Connect.
        URLConnection connection = fbiURL.openConnection();
        connection.connect();
        DataInputStream is = new DataInputStream(connection.getInputStream());

        // Check file signature.
        byte[] b = new byte[12];
        is.readFully(b);
        if (b[0] != 'F'
            || b[1] != 'B'
            || b[2] != 'I'
            || b[3] != ' '
            || b[4] != '0'
            || b[5] != '0'
            || b[6] != '1'
            || b[7] != '.'
            || b[8] < '0'
            || b[8] > '9'
            || b[9] < '0'
            || b[9] > '9'
            || b[10] < '0'
            || b[10] > '9'
            || b[11] != '\n') {
          System.err.println("Could not load index: bad .fbi file signature");
          return;
        }

        // Read the record counter and allocate index array.
        int numRecords = is.readInt();
        if (numRecords <= 0) {
          System.err.println("Could not load index: bad .fbi record counter");
          return;
        }
        newIndex = new FbsEntryPoint[numRecords];

        // Read byte counter and allocate byte array for RFB initialization.
        int initSize = is.readInt();
        if (initSize <= 0) {
          System.err.println("Could not load index: bad RFB init data size");
          return;
        }
        newInitData = new byte[initSize];

        // Load index from the .fbi file.
        try {
          for (int i = 0; i < numRecords; i++) {
            FbsEntryPoint record = new FbsEntryPoint();
            record.timestamp = (long) is.readInt() & 0xFFFFFFFFL;
            record.key_fpos = (long) is.readInt() & 0xFFFFFFFFL;
            record.key_size = (long) is.readInt() & 0xFFFFFFFFL;
            record.fbs_fpos = (long) is.readInt() & 0xFFFFFFFFL;
            record.fbs_skip = (long) is.readInt() & 0xFFFFFFFFL;
            newIndex[i] = record;
            numRecordsRead++;
          }
        } catch (EOFException e) {
          System.err.println("Preliminary end of .fbi file");
        } catch (IOException e) {
          System.err.println("Ignored exception: " + e);
        }
        if (numRecordsRead == 0) {
          System.err.println("Could not load index: failed to read .fbi data");
          return;
        } else if (numRecordsRead != numRecords) {
          System.err.println("Warning: read not as much .fbi data as expected");
        }
        is.readFully(newInitData);
      } catch (FileNotFoundException e) {
        System.err.println("Could not load index: .fbi file not found: " + e.getMessage());
        return;
      } catch (IOException e) {
        System.err.println(e);
        System.err.println("Could not load index: failed to load .fbi file");
        return;
      }
      // Check correctness of the data read.
      for (int i = 1; i < numRecordsRead; i++) {
        if (newIndex[i].timestamp <= newIndex[i - 1].timestamp) {
          System.err.println("Could not load index: wrong .fbi file contents");
          return;
        }
      }
      // Loaded successfully.
      indexData = newIndex;
      numIndexRecords = numRecordsRead;
      rfbInitData = newInitData;
      System.err.println("Loaded index data, " + numRecordsRead + " records");
    }
  }