Exemplo n.º 1
0
  /** The real "store file" method. */
  private CmdResult putFile(
      String url,
      // Only one of these two should be given:
      int nBytes,
      ReadableByteChannel contents,
      boolean calcHash,
      NVPair[] extraHeaders)
      throws HoneycombTestException, IOException, ModuleException {

    NVPair[] headers = null;

    MessageDigest sha = null;
    if (calcHash)
      try {
        sha = MessageDigest.getInstance(HC_HASH);
      } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
      }

    CmdResult cr = new CmdResult();
    cr.filename = url;

    byte[] byte_buffer = new byte[BUFSIZE];
    ByteBuffer buff = ByteBuffer.wrap(byte_buffer);

    int toWrite, written = 0;
    long startTime = System.currentTimeMillis();

    if (contents != null)
      // If we're not writing from our buffer, don't set Content-type
      headers = extraHeaders;
    else if (extraHeaders == null) headers = putHeaders;
    else {
      // Need to combine the two arrays
      NVPair[] newHeaders = new NVPair[putHeaders.length + extraHeaders.length];

      int i = 0;
      for (int j = 0; j < putHeaders.length; j++) newHeaders[i++] = putHeaders[j];
      for (int j = 0; j < extraHeaders.length; j++) newHeaders[i++] = extraHeaders[j];

      headers = newHeaders;
    }

    HttpOutputStream out = new HttpOutputStream();
    HTTPResponse response = conn.Put(url, out, headers);

    // Write into the HTTP stream
    for (; ; ) {
      if (contents != null) {
        // Read from the "contents" channel and write it out
        if ((toWrite = contents.read(buff)) < 0) break;

        byte[] data = buff.array();
        if (sha != null) sha.update(data);

        out.write(data, 0, toWrite);
        buff.clear();
      } else {
        // Write from the buffer writeBuf
        if (written >= nBytes) break;

        toWrite = nBytes - written;
        if (toWrite > BUFSIZE) {
          out.write(writeBuf);
          written += BUFSIZE;
          if (sha != null) sha.update(writeBuf);
        } else {
          out.write(writeBuf, 0, toWrite);
          if (sha != null) sha.update(writeBuf, 0, toWrite);
          break;
        }
      }
    }
    out.close();

    if (response.getStatusCode() >= 300) throw makeTestException("putFile", url, response);

    cr.mdoid = response.getHeader("ETag");
    cr.time = System.currentTimeMillis() - startTime;
    cr.pass = true;

    if (sha != null) cr.datasha1 = HCUtil.convertHashBytesToString(sha.digest());

    return cr;
  }