package com.zhongan.xd.bss.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.ObjectListing;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
public class OssTool {
/** 若不进行分片续传,单个上传文件最大长度 (5G) */
//private final static long SINGLE_FILE_MAX_LENGTH = 0x140000000L;
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private OSSClient client;
/**
* 构造方法,初始化OssClient
*
* @param accessKeyId
* @param accessKeySecret
*/
private OSSClient getInstance() {
if (client == null) {
client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
return client;
}
public OssTool(String endpoint, String accessKeyId, String accessKeySecret) {
super();
this.endpoint = endpoint;
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.client = getInstance();
}
/**
* 将data上传到指定bucketName
*
* @param bucketName
* @param key
* @param data
* @param length
* @throws IOException
*/
public PutObjectResult putObject(String bucketName, String key, InputStream data, int length) throws IOException {
// 创建上传Object的Metadata
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentLength(length);
// 上传Object.
PutObjectResult result = client.putObject(bucketName, key, data, meta);
return result;
}
/**
* 获取指定bucket下的所有Object信息
*
* @param bucketName
* @return
*/
public ObjectListing listObjects(String bucketName) {
return client.listObjects(bucketName);
}
/**
* 获取指定bucket下的指定Object
*
* @param bucketName
* @param key
* @throws IOException
*/
public OSSObject getObject(String bucketName, String key) {
// 获取Object,返回结果为OSSObject对象
log.info("OssTool getObject-->endpoint={},accessKeyId={},accessKeySecret={}", endpoint, accessKeyId,
accessKeySecret);
if (client == null) {
// 初始化OSSClient
client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
log.info("OssTool getObject-->bucketName,accessKeyId");
return client.getObject(bucketName, key);
}
/**
* 删除指定bucketName下指定key对应的object
*
* @param bucketName
* @param key
*/
// public void deleteObject(String bucketName, String key) {
// // 删除Object
// client.deleteObject(bucketName, key);
// }
/**
* 生成一个预签名的URL
*
* @param bucketName
* @param key
* @param expireHours 生成的URL过期天数,调用者保证大于等于0
* @return
*/
public URL generatePresignedUrl(String bucketName, String key, int expireHours) {
// 设置URL过期时间为expireDays
Date expiration = new Date(new Date().getTime() + 1000L * 3600 * expireHours);
// 生成URL
return client.generatePresignedUrl(bucketName, key, expiration);
}
/**
* 上传文件到OSS
*
* @param client OSS客户端链接
* @param file 待上传的文件对象
* @param bucketName 文件上传空间名
* @param key 文件上传文件名
*/
// public void uploadOssFile(OSSClient client, File file, String bucketName, String key) throws IOException {
//
// Preconditions.checkArgument(null != client, "param client is null");
//
// Preconditions.checkArgument(StringUtils.isNotBlank(bucketName),
// "param bucketName is null or empty,bucketName:%s", bucketName);
//
// Preconditions.checkArgument(StringUtils.isNotBlank(key), "param key is null or empty,key:%s", key);
//
// Preconditions.checkArgument((null != file && file.exists()), "param file is null or file not found,file:%s",
// file);
//
// Preconditions.checkArgument(file.length() < SINGLE_FILE_MAX_LENGTH,
// "param file length greater than SINGLE_FILE_MAX_LENGTH");
//
// Preconditions.checkArgument(this.bucketExist(client, bucketName), "param bucketName is not exist,bucketName:%s",
// bucketName);
//
// InputStream inputStream = null;
//
// try {
//
// inputStream = new FileInputStream(file);
//
// ObjectMetadata meta = new ObjectMetadata();
//
// meta.setContentLength(file.length());
//
// client.putObject(bucketName, key, inputStream, meta);
//
// } catch (Exception e) {
//
// System.out.println("OssUtil.uploadOssFile failed,OSSException:e:" + e.getMessage());
//
// throw e;
//
// } finally {
//
// if (null != inputStream) {
// try {
//
// inputStream.close();
//
// } catch (IOException e) {
//
// System.out.println("close input stream failed e:" + e.getMessage());
//
// }
// }
// }
// }
/**
* 判断bucket是否存在
*
* @param client OSS客户端链接
* @param bucketName OSS空间名
* @return boolean
*/
public boolean bucketExist(OSSClient client, String bucketName) {
return (null != client && null != bucketName && !"".equals(bucketName)) ? client.doesBucketExist(bucketName)
: false;
}
/**
* 上传文件
*
* @param accessKeyId
* @param accessKeySecret
* @param endpoint
* @param bucket
* @param bytes
* @param objectKey
* @return {@link String}
* @throws IOException
*/
public static String uploadFile(String accessKeyId, String accessKeySecret, String endpoint, String bucket,
byte[] bytes, String objectKey)
throws IOException {
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
InputStream in = new ByteArrayInputStream(bytes);
ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentLength(in.available());
PutObjectResult result = client.putObject(bucket, objectKey, in, objectMeta);
in.close();
return result.getETag();
}
/**
* @param tbucket
* @param key
* @return
*/
public URL getUrlByKey(String tbucket, String key) {
Date date = new Date();
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.add(Calendar.HOUR, 1);
return client.generatePresignedUrl(tbucket, key, ca.getTime());
}
/**
* 从OSS下载文件
*
* @param objectkey
* @param newFile
*/
public static void downloadFile(OSSObject obj, final String newFile) {
final File file = new File(newFile);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
log.error("cd directory:{} fail:{}", newFile, e);
}
}
//获取到OSS文件
try (InputStream is = obj.getObjectContent();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);) {
final int buffer = 1024; // 定义缓冲区的大小
int length = 0;
final byte[] b = new byte[buffer];
while ((length = bis.read(b)) != -1) {
bos.write(b, 0, length);
}
bos.flush();
bos.close();
// 下载后删除oss的临时文件
// client.deleteObject(bucketName, objectkey);
} catch (final IOException e) {
log.error("cd directory:{} fail:{}", newFile, e);
}
}
public static void main(String[] args) {
String endpoint = "http://oss-cn-hzjbp-b-internal.aliyuncs.com";
String accessKeyId = "LTAIJt67GZQkRJTC";
String accessKeySecret = "3RCPK6VdHP007RCbtqGndwx8sGcfNY";
OssTool oss = new OssTool(endpoint, accessKeyId, accessKeySecret);
//
OSSObject obj = oss.getObject("core-system", "za-contract-sign/BQMMT236659220181126102806_2.pdf");
oss.downloadFile(obj, "za-contract-sign/BQMMT236659220181126102806_2.pdf");
System.out.println(obj);
}
}