@Override
    public PartResult call() throws Exception {
      PartResult tr = null;
      RandomAccessFile output = null;
      InputStream content = null;

      try {
        DownloadPart downloadPart = downloadCheckPoint.downloadParts.get(partIndex);
        tr = new PartResult(partIndex + 1, downloadPart.start, downloadPart.end);

        output = new RandomAccessFile(downloadFileRequest.getDownloadFile(), "rw");
        output.seek(downloadPart.start);

        GetObjectRequest getObjectRequest =
            new GetObjectRequest(downloadFileRequest.getBucketName(), downloadFileRequest.getKey());
        getObjectRequest.setMatchingETagConstraints(
            downloadFileRequest.getMatchingETagConstraints());
        getObjectRequest.setNonmatchingETagConstraints(
            downloadFileRequest.getNonmatchingETagConstraints());
        getObjectRequest.setModifiedSinceConstraint(
            downloadFileRequest.getModifiedSinceConstraint());
        getObjectRequest.setUnmodifiedSinceConstraint(
            downloadFileRequest.getUnmodifiedSinceConstraint());
        getObjectRequest.setResponseHeaders(downloadFileRequest.getResponseHeaders());
        getObjectRequest.setRange(downloadPart.start, downloadPart.end);

        OSSObject ossObj = objectOperation.getObject(getObjectRequest);
        objectMetadata = ossObj.getObjectMetadata();
        content = ossObj.getObjectContent();

        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int bytesRead = 0;
        while ((bytesRead = content.read(buffer)) != -1) {
          output.write(buffer, 0, bytesRead);
        }

        downloadCheckPoint.update(partIndex, true);
        if (downloadFileRequest.isEnableCheckpoint()) {
          downloadCheckPoint.dump(downloadFileRequest.getCheckpointFile());
        }
      } catch (Exception e) {
        tr.setFailed(true);
        tr.setException(e);
        logException(String.format("Task %d:%s upload part %d failed: ", id, name, partIndex), e);
      } finally {
        if (output != null) {
          output.close();
        }

        if (content != null) {
          content.close();
        }
      }

      return tr;
    }
Example #2
0
 public static void readContent(String bucketName, String key, OSSClient client)
     throws IOException {
   BufferedReader br = null;
   try {
     OSSObject objec = client.getObject(bucketName, key);
     br = new BufferedReader(new InputStreamReader(objec.getObjectContent()));
     String line = br.readLine();
     while (line != null) {
       System.out.println(line);
       line = br.readLine();
     }
     System.out.println("读完啦!");
   } catch (Exception e) {
     System.err.println(e);
   } finally {
     br.close();
   }
 }
  /**
   * 下载文件
   *
   * @author [email protected]
   * @param fileId
   * @return
   * @throws IOException
   */
  public FileInfo download(String fileId) throws IOException {
    logger.debug("download file from OSS--start");
    if (fileId == null || fileId.equals("")) {
      throw new IllegalArgumentException("fileId不能为null或者空字符串");
    }
    OSSClient client = this.getOSSClient();
    OSSObject ossObject = client.getObject(bucketName, fileId);
    FileInfo fileInfo = new FileInfo();
    InputStream is = ossObject.getObjectContent();
    byte[] content = IOUtils.readStreamAsByteArray(is);
    checkContent(content);
    ObjectMetadata objectMetadata = ossObject.getObjectMetadata();
    String fileName = objectMetadata.getUserMetadata().get("filename");
    fileInfo.setFileContent(content);
    fileInfo.setFileName(fileName);

    logger.debug("download file from OSS--end");
    return fileInfo;
  }
  public static void main(String[] args) throws IOException {
    /*
     * Constructs a client instance with your account for accessing OSS
     */
    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    try {
      /*
       * Append an object from specfied input stream, keep in mind that
       * position should be set to zero at first time.
       */
      String content = "Thank you for using Aliyun Object Storage Service";
      InputStream instream = new ByteArrayInputStream(content.getBytes());
      Long firstPosition = 0L;
      System.out.println("Begin to append object at position(" + firstPosition + ")");
      AppendObjectResult appendObjectResult =
          client.appendObject(new AppendObjectRequest(bucketName, key, instream).withPosition(0L));
      System.out.println(
          "\tNext position="
              + appendObjectResult.getNextPosition()
              + ", CRC64="
              + appendObjectResult.getObjectCRC()
              + "\n");

      /*
       * Continue to append the object from specfied file descriptor at last position
       */
      Long nextPosition = appendObjectResult.getNextPosition();
      System.out.println("Continue to append object at last position(" + nextPosition + "):");
      appendObjectResult =
          client.appendObject(
              new AppendObjectRequest(bucketName, key, createTempFile())
                  .withPosition(nextPosition));
      System.out.println(
          "\tNext position="
              + appendObjectResult.getNextPosition()
              + ", CRC64="
              + appendObjectResult.getObjectCRC());

      /*
       * View object type of the appendable object
       */
      OSSObject object = client.getObject(bucketName, key);
      System.out.println("\tObject type=" + object.getObjectMetadata().getObjectType() + "\n");
      // Do not forget to close object input stream if not use it any more
      object.getObjectContent().close();

      /*
       * Delete the appendable object
       */
      System.out.println("Deleting an appendable object");
      client.deleteObject(bucketName, key);

    } catch (OSSException oe) {
      System.out.println(
          "Caught an OSSException, which means your request made it to OSS, "
              + "but was rejected with an error response for some reason.");
      System.out.println("Error Message: " + oe.getErrorCode());
      System.out.println("Error Code:       " + oe.getErrorCode());
      System.out.println("Request ID:      " + oe.getRequestId());
      System.out.println("Host ID:           " + oe.getHostId());
    } catch (ClientException ce) {
      System.out.println(
          "Caught an ClientException, which means the client encountered "
              + "a serious internal problem while trying to communicate with OSS, "
              + "such as not being able to access the network.");
      System.out.println("Error Message: " + ce.getMessage());
    } finally {
      /*
       * Do not forget to shut down the client finally to release all allocated resources.
       */
      client.shutdown();
    }
  }