Ejemplo n.º 1
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;
  }