com.aliyun.oss.model.GetObjectRequest Java Examples

The following examples show how to use com.aliyun.oss.model.GetObjectRequest. 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: AliOSSBlobStore.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
private GetObjectRequest toGetObjectRequest(String container, String name, GetOptions options) {
    GetObjectRequest request = new GetObjectRequest(container, name);
    if (options.getIfModifiedSince() != null) {
        request.setModifiedSinceConstraint(options.getIfModifiedSince());
    }
    if (!options.getRanges()
                .isEmpty()) {
        String[] ranges = options.getRanges()
                                 .get(0)
                                 .split("-");
        long start = Integer.parseInt(ranges[0]);
        long end = Integer.parseInt(ranges[1]);
        request.setRange(start, end);
    }
    return request;
}
 
Example #2
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 #3
Source File: OSSUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 下载prefix目录下的所有文件到本地dir目录 
 * @param dir  dir
 * @param prefix  prefix
 * @return return
 */ 
public boolean download(File dir, String prefix){ 
	if(null == prefix){ 
		prefix = ""; 
	} 
	if(prefix.startsWith("/")){ 
		prefix = prefix.substring(1); 
	} 
	final int maxKeys = 200; 
	String nextMarker = null; 
	ObjectListing objectListing; 
	do { 
	    objectListing = client.listObjects(new ListObjectsRequest(config.BUCKET) 
	    .withPrefix(prefix).withMarker(nextMarker).withMaxKeys(maxKeys)); 
	    List<OSSObjectSummary> sums = objectListing.getObjectSummaries(); 
	    for (OSSObjectSummary s : sums) { 
	    	String key = s.getKey(); 
	    	if(key.endsWith("/")){ 
	    		continue; 
	    	} 
	        File file = new File(dir, key); 
	        File parent = file.getParentFile(); 
	        if(null != parent && !parent.exists()){ 
	        	parent.mkdirs(); 
	        } 
	        try{ 
	        	client.getObject(new GetObjectRequest(config.BUCKET, key), file); 
	        }catch(Exception e){ 
	        	e.printStackTrace(); 
	        } 
	        if(ConfigTable.isDebug() && log.isWarnEnabled()){ 
	        	log.warn("[oss download file][local:{}][remote:{}]",file.getAbsolutePath(),key); 
	        } 
	    } 
	    nextMarker = objectListing.getNextMarker(); 
	     
	} while (objectListing.isTruncated()); 

	return true; 
}
 
Example #4
Source File: OssDownload.java    From tools with MIT License 5 votes vote down vote up
/**
 * Download the file to the local file
 *
 * @param dir      Local dir
 * @param fileName Oss file name
 */
public void downByLocal(String dir, String fileName) {
    File f = new File(dir);
    if (!f.exists()) {
        f.mkdir();
    }
    Predicate<String> predicate = e -> e.indexOf("/", e.length() - 1) != -1;
    this.ossClient.getObject(new GetObjectRequest(this.ossMeta.getBucket(), fileName), new File(predicate.test(dir) ? dir + fileName : dir + "/" + fileName));
}
 
Example #5
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 #6
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 #7
Source File: AliyunOssUtils.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 同步 阿里云OSS 到本地
 *
 * @param path
 * @param toFile
 * @return
 */
public static boolean download(String path, File toFile) {
    boolean enable = JPressOptions.getAsBool(KEY_ENABLE);

    if (!enable || StrUtil.isBlank(path)) {
        return false;
    }

    path = removeFileSeparator(path);
    String ossBucketName = JPressOptions.get(KEY_BUCKETNAME);
    OSSClient ossClient = createOSSClient();
    try {

        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }

        if (!toFile.exists()) {
            toFile.createNewFile();
        }
        ossClient.getObject(new GetObjectRequest(ossBucketName, path), toFile);
        return true;
    } catch (Throwable e) {
        log.error("aliyun oss download error!!!  path:" + path + "   toFile:" + toFile, e);
        if (toFile.exists()) {
            toFile.delete();
        }
        return false;
    } finally {
        ossClient.shutdown();
    }
}
 
Example #8
Source File: AliyunUtil.java    From roncoo-education with MIT License 4 votes vote down vote up
private static void downloadObject(String endpoint, String keyId, String keySecret, String bucketName, String key, File file) throws IOException {
	getOssClient(endpoint, keyId, keySecret).getObject(new GetObjectRequest(bucketName, key), file);
}
 
Example #9
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 #10
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();
    }
}