com.aliyun.oss.ClientException Java Examples

The following examples show how to use com.aliyun.oss.ClientException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AliyunOssClient.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * Upload string.
 *
 * @param ossClient the ossClient client
 * @param instream  the instream
 * @param fileName  the file name
 * @return the string
 */
public String upload(@NotNull OSS ossClient,
                     @NotNull InputStream instream,
                     @NotNull String fileName) {
    try {
        // 创建上传 Object 的 Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(instream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(ImageUtils.getImageType(fileName));
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
        return getUrl(ossClient, filedir, fileName);
    } catch (IOException | OSSException | ClientException e) {
        log.trace("", e);
    }
    return "";
}
 
Example #2
Source File: OSSUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 获取文件的临时地址(供文件预览使用)
 * 图片处理:https://help.aliyun.com/document_detail/47505.html
 * 异常码描:https://help.aliyun.com/document_detail/32023.html
 * @param bucket   必传:存储空间名称
 * @param endpoint 必传:存储空间所属地域的访问域名
 * @param isImg    必传:获取的文件是否为图片
 * @param process  选传:(isImg=true时必传)图片的x-oss-process参数值(传空则返回原图),举例:image/resize,p_50表示将图按比例缩略到原来的1/2
 * @param timeout  必传:有效时长,单位:分钟
 * @return 返回文件的完整地址(浏览器可直接访问)
 * Comment by 玄玉<https://jadyer.cn/> on 2018/4/9 17:23.
 */
public static String getFileURL(String endpoint, String accessKeyId, String accessKeySecret, String bucket, String key, boolean isImg, String process, int timeout) {
    LogUtil.getLogger().info("获取文件临时URL,请求ossKey=[{}],process=[{}], timeout=[{}]min", key, process, timeout);
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key, HttpMethod.GET);
        req.setExpiration(DateUtils.addMinutes(new Date(), timeout));
        if(isImg){
            req.setProcess(StringUtils.isNotBlank(process) ? process : "image/resize,p_100");
        }
        String imgURL = ossClient.generatePresignedUrl(req).toString();
        imgURL = imgURL.startsWith("http://") ? imgURL.replace("http://", "https://") : imgURL;
        LogUtil.getLogger().info("获取文件临时URL,请求ossKey=[{}],应答fileUrl=[{}]", key, imgURL);
        return imgURL;
    } catch (OSSException oe) {
        throw new SeedException("获取文件临时URL,OSS服务端异常,RequestID="+oe.getRequestId() + ",HostID="+oe.getHostId() + ",Code="+oe.getErrorCode() + ",Message="+oe.getMessage());
    } catch (ClientException ce) {
        throw new SeedException("获取文件临时URL,OSS客户端异常,RequestID="+ce.getRequestId() + ",Code="+ce.getErrorCode() + ",Message="+ce.getMessage());
    } catch (Throwable e) {
        throw new SeedException("获取文件临时URL,OSS未知异常:" + e.getMessage());
    } finally {
        if(null != ossClient){
            ossClient.shutdown();
        }
    }
}
 
Example #3
Source File: OSSUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 文件上传
 * @param bucket   存储空间名称
 * @param endpoint 存储空间所属地域的访问域名
 * @param key      文件完整名称(建议含后缀)
 * @param is       文件流
 * Comment by 玄玉<https://jadyer.cn/> on 2018/4/9 17:24.
 */
public static void upload(String bucket, String endpoint, String key, String accessKeyId, String accessKeySecret, InputStream is) {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        ossClient.putObject(bucket, key, is);
    } catch (OSSException oe) {
        throw new SeedException("文件上传,OSS服务端异常,RequestID="+oe.getRequestId() + ",HostID="+oe.getHostId() + ",Code="+oe.getErrorCode() + ",Message="+oe.getMessage());
    } catch (ClientException ce) {
        throw new SeedException("文件上传,OSS客户端异常,RequestID="+ce.getRequestId() + ",Code="+ce.getErrorCode() + ",Message="+ce.getMessage());
    } catch (Throwable e) {
        throw new SeedException("文件上传,OSS未知异常:" + e.getMessage());
    } finally {
        try {
            if(null != is){
                is.close();
            }
        } catch (final IOException ioe) {
            // ignore
        }
        if(null != ossClient){
            ossClient.shutdown();
        }
    }
}
 
Example #4
Source File: TestOSSService.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws OSSException, ClientException, IOException {
    OSSClient client = new OSSClient("oss-cn-hangzhou.aliyuncs.com", "", "", "");
    // BucketInfo info = client.getBucketInfo("edrmry");
    boolean exists = client.doesBucketExist("edrmry");
    System.out.println(exists);
    // System.out.println(client.listBuckets().size());
    // client.createBucket("dzh1");
    PutObjectResult r = client.putObject("edrmry", "dzh1.jpg", new FileInputStream("/Users/dzh/Pictures/8.pic.jpg"));
    System.out.println(r.getETag());
    OSSObject o = client.getObject("edrmry", "dzh1");
    InputStream is = o.getObjectContent();

    FileOutputStream fos = new FileOutputStream("/Users/dzh/Pictures/8.pic.2.jpg");
    int len = 0;
    byte[] buf = new byte[32];
    while ((len = is.read(buf)) != -1) {
        fos.write(buf, 0, len);
    }
    fos.flush();
    fos.close();
}
 
Example #5
Source File: UploadCloudTests.java    From MyShopPlus with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpload() {
    // 创建一个访问 OSS 的实例
    OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    try {
        // 文件上传
        System.out.println("Uploading a new object to OSS from an input stream\n");
        String content = "Thank you for using Aliyun Object Storage Service";
        client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        // 文件下载
        System.out.println("Downloading an object");
        OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
    } 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());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.shutdown();
    }
}
 
Example #6
Source File: OssUploadSample.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

	try {
		UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key);
		// The local file to upload---it must exist.
		uploadFileRequest.setUploadFile(uploadFile);
		// Sets the concurrent upload task number to 5.
		uploadFileRequest.setTaskNum(5);
		// Sets the part size to 1MB.
		uploadFileRequest.setPartSize(1024 * 1024 * 1);
		// Enables the checkpoint file. By default it's off.
		uploadFileRequest.setEnableCheckpoint(true);

		UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);

		CompleteMultipartUploadResult multipartUploadResult = uploadResult.getMultipartUploadResult();
		System.out.println(multipartUploadResult.getETag());

	} 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.getErrorMessage());
		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());
	} catch (Throwable e) {
		e.printStackTrace();
	} finally {
		ossClient.shutdown();
	}
}
 
Example #7
Source File: OssDownloadTests.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {

		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		try {
			DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, key);
			// Sets the local file to download to
			downloadFileRequest.setDownloadFile(downloadFile);
			// Sets the concurrent task thread count 5. By default it's 1.
			downloadFileRequest.setTaskNum(5);
			// Sets the part size, by default it's 100K.
			downloadFileRequest.setPartSize(1024 * 1024 * 1);
			// Enable checkpoint. By default it's false.
			downloadFileRequest.setEnableCheckpoint(true);

			DownloadFileResult downloadResult = ossClient.downloadFile(downloadFileRequest);

			ObjectMetadata objectMetadata = downloadResult.getObjectMetadata();
			System.out.println(objectMetadata.getETag());
			System.out.println(objectMetadata.getLastModified());
			System.out.println(objectMetadata.getUserMetadata().get("meta"));

		} 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.getErrorMessage());
			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());
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			ossClient.shutdown();
		}
	}
 
Example #8
Source File: OSSUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 文件下载
 * @param bucket   存储空间名称
 * @param endpoint 存储空间所属地域的访问域名
 * @param localURL 保存在本地的包含完整路径和后缀的完整文件名,若传空则默认放到Java临时目录中
 * @return localURL(若文件不存在则返回OSSUtil.NO_FILE)
 * Comment by 玄玉<https://jadyer.cn/> on 2018/4/9 17:24.
 */
public static String download(String bucket, String endpoint, String key, String accessKeyId, String accessKeySecret, String localURL) {
    if(StringUtils.isBlank(localURL)){
        //若未传localURL,则把下载到的文件放到Java临时目录
        localURL = System.getProperty("java.io.tmpdir") + "/ossutil-download/" + key;
        ////若文件名称不含后缀,那就主动添加后缀
        //if("".equals(FilenameUtils.getExtension(key))){
        //    localURL += ".txt";
        //}
    }
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        if(!ossClient.doesObjectExist(bucket, key)){
            return OSSUtil.NO_FILE;
        }
        //ossClient.getObject(new GetObjectRequest(bucket, key), new File(localURL));
        InputStream is = ossClient.getObject(bucket, key).getObjectContent();
        FileUtils.copyInputStreamToFile(is, new File(localURL));
        return localURL;
    } catch (OSSException oe) {
        throw new SeedException("文件下载,OSS服务端异常,RequestID="+oe.getRequestId() + ",HostID="+oe.getHostId() + ",Code="+oe.getErrorCode() + ",Message="+oe.getMessage());
    } catch (ClientException ce) {
        throw new SeedException("文件下载,OSS客户端异常,RequestID="+ce.getRequestId() + ",Code="+ce.getErrorCode() + ",Message="+ce.getMessage());
    } catch (Throwable e) {
        throw new SeedException("文件下载,OSS未知异常:" + e.getMessage());
    } finally {
        if(null != ossClient){
            ossClient.shutdown();
        }
    }
}
 
Example #9
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传图片到阿里云OSS
 *
 * @param request
 * @param response
 * @param file
 * @return
 * @throws IOException
 */
@RequestMapping(value = "upload/oss/image", method = RequestMethod.POST)
@ResponseBody
public MessageResult uploadOssImage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/").toString());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    Assert.isTrue(ServletFileUpload.isMultipartContent(request), sourceService.getMessage("FORM_FORMAT_ERROR"));
    Assert.isTrue(file != null, sourceService.getMessage("NOT_FIND_FILE"));
    log.info("该文件的文件流为转为类型>>>>>>>>>>>"+UploadFileUtil.getFileHeader(file.getInputStream()));
    String fileType=UploadFileUtil.getFileType(file.getInputStream());
    System.out.println("fileType="+fileType);
    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("suffix="+suffix);
        if (!allowedFormat.contains(suffix.trim().toLowerCase())) {
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        if(fileType==null||!allowedFormat.contains(fileType.trim().toLowerCase())){
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        //压缩文件
        String path = request.getSession().getServletContext().getRealPath("/") + "upload/"+file.getOriginalFilename();
        File tempFile=new File(path);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        log.info("=================压缩前"+tempFile.length());
        UploadFileUtil.zipWidthHeightImageFile(tempFile,tempFile,425,638,0.7f);
        log.info("=================压缩后"+tempFile.length());
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        log.info(">>>>>>>>>>上传成功>>>>>>>>>>>>>");
        MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
        mr.setData(uri);
        return mr;
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage());
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("SYSTEM_ERROR"));
    } finally {
        ossClient.shutdown();
    }
}
 
Example #10
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequestMapping(value = "/oss/image", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "上传oss图片")
public String uploadOssImage(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/"));
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return MessageResult.error(500, sourceService.getMessage("FORMAT_NOT_SUPPORTED")).toString();
    }
    if (file == null) {
        return MessageResult.error(500, sourceService.getMessage("FILE_NOT_FOUND")).toString();
    }

    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());

    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        MessageResult mr = new MessageResult(0, sourceService.getMessage("SUCCESS"));
        mr.setData(uri);
        return mr.toString();
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage()).toString();
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage()).toString();
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("REQUEST_FAILED")).toString();
    } finally {
        ossClient.shutdown();
    }
}
 
Example #11
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传图片到阿里云OSS
 *
 * @param request
 * @param response
 * @param file
 * @return
 * @throws IOException
 */
@RequestMapping(value = "upload/oss/image", method = RequestMethod.POST)
@ResponseBody
public MessageResult uploadOssImage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/").toString());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    Assert.isTrue(ServletFileUpload.isMultipartContent(request), sourceService.getMessage("FORM_FORMAT_ERROR"));
    Assert.isTrue(file != null, sourceService.getMessage("NOT_FIND_FILE"));
    log.info("该文件的文件流为转为类型>>>>>>>>>>>"+UploadFileUtil.getFileHeader(file.getInputStream()));
    String fileType=UploadFileUtil.getFileType(file.getInputStream());
    System.out.println("fileType="+fileType);
    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("suffix="+suffix);
        if (!allowedFormat.contains(suffix.trim().toLowerCase())) {
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        if(fileType==null||!allowedFormat.contains(fileType.trim().toLowerCase())){
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        //压缩文件
        String path = request.getSession().getServletContext().getRealPath("/") + "upload/"+file.getOriginalFilename();
        File tempFile=new File(path);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        log.info("=================压缩前"+tempFile.length());
        UploadFileUtil.zipWidthHeightImageFile(tempFile,tempFile,425,638,0.7f);
        log.info("=================压缩后"+tempFile.length());
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        log.info(">>>>>>>>>>上传成功>>>>>>>>>>>>>");
        MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
        mr.setData(uri);
        return mr;
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage());
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("SYSTEM_ERROR"));
    } finally {
        ossClient.shutdown();
    }
}
 
Example #12
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequestMapping(value = "/oss/image", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "上传oss图片")
public String uploadOssImage(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/"));
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return MessageResult.error(500, sourceService.getMessage("FORMAT_NOT_SUPPORTED")).toString();
    }
    if (file == null) {
        return MessageResult.error(500, sourceService.getMessage("FILE_NOT_FOUND")).toString();
    }

    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());

    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        MessageResult mr = new MessageResult(0, sourceService.getMessage("SUCCESS"));
        mr.setData(uri);
        return mr.toString();
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage()).toString();
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage()).toString();
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("REQUEST_FAILED")).toString();
    } finally {
        ossClient.shutdown();
    }
}
 
Example #13
Source File: OssConcurrentGetObjectTests.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	/*
	 * Constructs a client instance with your account for accessing OSS
	 */
	client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

	try {
		/*
		 * Upload an object to your bucket
		 */
		System.out.println("Uploading a new object to OSS from a file\n");
		client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

		/*
		 * Get size of the object and pre-create a random access file to
		 * hold object data
		 */
		ObjectMetadata metadata = client.getObjectMetadata(bucketName, key);
		long objectSize = metadata.getContentLength();
		RandomAccessFile raf = new RandomAccessFile(localFilePath, "rw");
		raf.setLength(objectSize);
		raf.close();

		/*
		 * Calculate how many blocks to be divided
		 */
		final long blockSize = 1 * 1024 * 1024L; // 1MB
		int blockCount = (int) (objectSize / blockSize);
		if (objectSize % blockSize != 0) {
			blockCount++;
		}
		System.out.println("Total blocks count " + blockCount + "\n");

		/*
		 * Download the object concurrently
		 */
		System.out.println("Start to download " + key + "\n");
		for (int i = 0; i < blockCount; i++) {
			long startPos = i * blockSize;
			long endPos = (i + 1 == blockCount) ? objectSize : (i + 1) * blockSize;
			executorService.execute(new BlockFetcher(startPos, endPos, i + 1));
		}

		/*
		 * Waiting for all blocks finished
		 */
		executorService.shutdown();
		while (!executorService.isTerminated()) {
			try {
				executorService.awaitTermination(5, TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		/*
		 * Verify whether all blocks are finished
		 */
		if (completedBlocks.intValue() != blockCount) {
			throw new IllegalStateException("Download fails due to some blocks are not finished yet");
		} else {
			System.out.println("Succeed to download object " + 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.getErrorMessage());
		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.
		 */
		if (client != null) {
			client.shutdown();
		}
	}
}
 
Example #14
Source File: OssSimpleGetObjectTests.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	/*
	 * Constructs a client instance with your account for accessing OSS
	 */
	OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

	try {

		/**
		 * Note that there are two ways of uploading an object to your
		 * bucket, the one by specifying an input stream as content source,
		 * the other by specifying a file.
		 */

		/*
		 * Upload an object to your bucket from an input stream
		 */
		System.out.println("Uploading a new object to OSS from an input stream\n");
		String content = "Thank you for using Aliyun Object Storage Service";
		client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

		/*
		 * Upload an object to your bucket from a file
		 */
		System.out.println("Uploading a new object to OSS from a file\n");
		client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

		/*
		 * Download an object from your bucket
		 */
		System.out.println("Downloading an object");
		OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
		System.out.println("ObjectKey: " + object.getKey());
		System.out.println("ClientCRC: " + object.getClientCRC());
		System.out.println("ServerCRC: " + object.getServerCRC());
		System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
		displayTextInputStream(object.getObjectContent());

	} 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.getErrorMessage());
		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();
	}
}
 
Example #15
Source File: SimpleGetObjectSample.java    From albert with MIT License 4 votes vote down vote up
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 {
        
        /**
         * Note that there are two ways of uploading an object to your bucket, the one 
         * by specifying an input stream as content source, the other by specifying a file.
         */
        
        /*
         * Upload an object to your bucket from an input stream
         */
        System.out.println("Uploading a new object to OSS from an input stream\n");
        String content = "Thank you for using Aliyun Object Storage Service";
        client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));
        
        /*
         * Upload an object to your bucket from a file
         */
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
        
        /*
         * Download an object from your bucket
         */
        System.out.println("Downloading an object");
        OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
        
    } 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();
    }
}