com.aliyun.oss.model.OSSObject Java Examples

The following examples show how to use com.aliyun.oss.model.OSSObject. 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: 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 #2
Source File: OSSUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
/** 
 * 最后修改时间 
 * @param path  path
 * @return return
 */ 
public Date getLastModified(String path){ 
	if(null == path){ 
		path = ""; 
	} 
	if(path.startsWith("/")){ 
		path = path.substring(1); 
	} 
	try{ 
		path = path.replace("http://"+config.BUCKET+"."+config.ENDPOINT+"/", ""); 
		OSSObject obj = client.getObject(config.BUCKET, path); 
		if(null == obj){ 
			return null; 
		}else{ 
			return obj.getObjectMetadata().getLastModified(); 
		} 
	}catch(Exception e){ 
		return null; 
	} 
}
 
Example #3
Source File: DemoController.java    From zheng with MIT License 6 votes vote down vote up
@GetMapping("/aliyun/download1")
public String download1() throws IOException {
    StringBuffer result = new StringBuffer();
    OSSObject ossObject = aliyunOssClient.getObject(OssConstant.ALIYUN_OSS_BUCKET_NAME, "text.txt");
    InputStream content = ossObject.getObjectContent();
    if (content != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            result.append("\n" + line);
        }
        content.close();
    }
    return result.toString();
}
 
Example #4
Source File: AliOSSBlobStore.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public Blob getBlob(String container, String name, GetOptions options) {
    return doOssOperation(oss -> {
        GetObjectRequest req = toGetObjectRequest(container, name, options);
        OSSObject object = oss.getObject(req);
        return convertToBlob(object);
    }, false);

}
 
Example #5
Source File: OSSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public Note get(String noteId, String notePath, AuthenticationInfo subject) throws IOException {
  OSSObject ossObject = ossClient.getObject(bucketName,
          rootFolder + "/" + buildNoteFileName(noteId, notePath));
  InputStream in = null;
  try {
    in = ossObject.getObjectContent();
    return Note.fromJson(IOUtils.toString(in));
  } finally {
    if (in != null) {
      in.close();
    }
  }
}
 
Example #6
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public ObjectOperation override(File file){
	Optional<OSSObject> opt = getOSSObject();
	if(!opt.isPresent()){
		throw new BaseException("key["+key+"] is not exists in bucket["+bucketName+"]");
	}
	return store(file);
}
 
Example #7
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public Optional<OSSObject> getOSSObject(){
	if(ossObject!=null){
		return ossObject;
	}
	if(!ossClient.doesObjectExist(bucketName, key)){
		ossObject = Optional.empty();
	}else{
		ossObject = Optional.ofNullable(ossClient.getObject(bucketName, key));
	}
	return ossObject;
}
 
Example #8
Source File: AliyunOSSMode.java    From wangmarket with Apache License 2.0 5 votes vote down vote up
@Override
public String getTextByPath(String path) {
	OSSObject ossObject = OSSUtil.getOSSClient().getObject(OSSUtil.bucketName, path);
	
	if(ossObject == null){
		return null;
	}else{
		try {
			return IOUtils.toString(ossObject.getObjectContent(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
 
Example #9
Source File: AliOSSBlobStoreTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBlob() throws Exception {
    OSSObject ossObject = new OSSObject();
    ossObject.setKey(FILENAME);
    ossObject.setObjectContent(new ByteArrayInputStream(PAYLOAD.getBytes()));
    Mockito.when(blobUtils.blobBuilder())
           .thenReturn(new BlobBuilderImpl());
    Mockito.when(ossClient.getObject(any(GetObjectRequest.class)))
           .thenReturn(ossObject);
    Blob blob = aliOSSBlobStore.getBlob(CONTAINER, FILENAME);
    String actualPayload = IOUtils.toString(blob.getPayload()
                                                .openStream(), StandardCharsets.UTF_8);
    assertEquals(PAYLOAD, actualPayload);
}
 
Example #10
Source File: AliOSSBlobStore.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private Blob convertToBlob(OSSObject object) {
    BlobBuilder builder = blobBuilder(object.getKey()).payload(object.getObjectContent());
    Map<String, String> userMetadata = object.getObjectMetadata()
                                             .getUserMetadata();
    if (userMetadata != null) {
        builder.userMetadata(userMetadata);
    }
    return builder.build();
}
 
Example #11
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 #12
Source File: OSSUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
public OSSObject get(String path){ 
	if(null == path){ 
		path = ""; 
	} 
	if(path.startsWith("/")){ 
		path = path.substring(1); 
	} 
	try{ 
		path = path.replace("http://"+config.BUCKET+"."+config.ENDPOINT+"/", ""); 
		return client.getObject(config.BUCKET, path); 
	}catch(Exception e){ 
		return null; 
	} 
}
 
Example #13
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();
    }
}
 
Example #14
Source File: OssKeyLoader.java    From daming with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public byte[] getBytes() {
    OSSObject ossObject = ossClient.getObject(bucketName, objectName);
    return StreamUtils.copyToByteArray(ossObject.getObjectContent());
}
 
Example #15
Source File: AliFileFileHandler.java    From seezoon-framework-all with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream download(String relativePath) throws FileNotFoundException {
	OSSObject object = ossClient.getObject(bucketName, handleRelativePath(relativePath));
	return object.getObjectContent();
}
 
Example #16
Source File: OssUtil.java    From feeyo-hlsserver with Apache License 2.0 4 votes vote down vote up
/**
 * 获取OSS Object输入流
 */
public InputStream readObject(String fileName, long streamId) {
	OSSObject ossObject = ossClient.getObject(bucketName, String.valueOf(streamId) + "/" + fileName);
	InputStream inputStream = ossObject.getObjectContent();
	return inputStream;
}
 
Example #17
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();
	}
}