package com.miaxis.common.aliyunOSS;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.aliyun.oss.model.GetObjectRequest;

import java.io.File;

public class AliyunDown {

	/**
	 * 通过URL地址，从阿里云下载文件到指定目录，
	 * @param  url 阿里的访问地址，必须是我们自己上传的文件才能有效
	 * @param  savePath 保存在本地的地址
	 * */
	public static boolean  downAliyunFromUrlTolLocalFile(String url,String savePath){
		OSSClient ossClient = new OSSClient(AliyunConfig.ENDPOINT, AliyunConfig.ACCESSKEYID,AliyunConfig.ACCESSKEYSECRET);

		try {
			String key = url.replaceAll(AliyunConfig.VISITPATH, "");
			key = key.replace("/tms", "tms");

			ossClient.getObject(new GetObjectRequest(AliyunConfig.BUCKETNAME, key), new File(savePath));
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			ossClient.shutdown();
		}
	}
	
	/**
	 * 通过URL地址，从阿里云下载文件到指定目录，
	 * @param  url 阿里的访问地址，必须是我们自己上传的文件才能有效
	 * @param  savePath 保存在本地的地址
	 * */
	public static boolean  downBigFileAliyunFromUrlTolLocalFile(String url,String savePath){
		OSSClient ossClient = new OSSClient(AliyunConfig.ENDPOINT, AliyunConfig.ACCESSKEYID,AliyunConfig.ACCESSKEYSECRET);
		try {
			String key = url.replaceAll(AliyunConfig.VISITPATH, "");
			System.out.println(key);
			//ossClient.getObject(new GetObjectRequest(AliyunConfig.BUCKETNAME, key), new File(savePath));
			// 下载请求，10个任务并发下载，启动断点续传
			DownloadFileRequest downloadFileRequest = new DownloadFileRequest(AliyunConfig.BUCKETNAME, key);
			downloadFileRequest.setDownloadFile(savePath);
			downloadFileRequest.setTaskNum(10);
			downloadFileRequest.setEnableCheckpoint(true);
			// 下载文件
			DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);
			// 下载成功时，会返回文件的元信息
			downloadRes.getObjectMetadata();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} catch (Throwable e) {
			e.printStackTrace();
			return false;
		}finally{
			ossClient.shutdown();
		}
	}
	public static void main(String[] args) {
		String url = "http://image.lnjppt.com/tms/sld/2101000000001-1.pdf";
		downAliyunFromUrlTolLocalFile(url.replace("http://image.lnjppt.com/", ""), "E://temp.pdf");
	}
}
