Search in sources :

Example 51 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project aliyun-oss-java-sdk by aliyun.

the class CallbackSample method main.

public static void main(String[] args) throws IOException {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        String content = "Hello OSS";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "key", new ByteArrayInputStream(content.getBytes()));
        Callback callback = new Callback();
        callback.setCallbackUrl(callbackUrl);
        callback.setCallbackHost("oss-cn-hangzhou.aliyuncs.com");
        callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object}," + "\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}," + "\\\"my_var1\\\":${x:var1},\\\"my_var2\\\":${x:var2}}");
        callback.setCalbackBodyType(CalbackBodyType.JSON);
        callback.addCallbackVar("x:var1", "value1");
        callback.addCallbackVar("x:var2", "value2");
        putObjectRequest.setCallback(callback);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        byte[] buffer = new byte[1024];
        putObjectResult.getResponse().getContent().read(buffer);
        putObjectResult.getResponse().getContent().close();
    } 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 {
        ossClient.shutdown();
    }
}
Also used : Callback(com.aliyun.oss.model.Callback) ByteArrayInputStream(java.io.ByteArrayInputStream) PutObjectResult(com.aliyun.oss.model.PutObjectResult) OSSException(com.aliyun.oss.OSSException) ClientException(com.aliyun.oss.ClientException) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest)

Example 52 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project druid by apache.

the class OssDataSegmentPusherTest method testPushInternal.

private void testPushInternal(boolean useUniquePath, String matcher) throws Exception {
    OSS client = EasyMock.createStrictMock(OSS.class);
    EasyMock.expect(client.putObject(EasyMock.anyObject())).andReturn(new PutObjectResult()).once();
    EasyMock.replay(client);
    OssStorageConfig config = new OssStorageConfig();
    config.setBucket("bucket");
    config.setPrefix("key");
    OssDataSegmentPusher pusher = new OssDataSegmentPusher(client, config);
    // Create a mock segment on disk
    File tmp = tempFolder.newFile("version.bin");
    final byte[] data = new byte[] { 0x0, 0x0, 0x0, 0x1 };
    Files.write(data, tmp);
    final long size = data.length;
    DataSegment segmentToPush = new DataSegment("foo", Intervals.of("2015/2016"), "0", new HashMap<>(), new ArrayList<>(), new ArrayList<>(), NoneShardSpec.instance(), 0, size);
    DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush, useUniquePath);
    Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
    Assert.assertEquals(1, (int) segment.getBinaryVersion());
    Assert.assertEquals("bucket", segment.getLoadSpec().get("bucket"));
    Assert.assertTrue(segment.getLoadSpec().get("key").toString(), Pattern.compile(matcher).matcher(segment.getLoadSpec().get("key").toString()).matches());
    Assert.assertEquals("oss_zip", segment.getLoadSpec().get("type"));
    EasyMock.verify(client);
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) File(java.io.File) DataSegment(org.apache.druid.timeline.DataSegment) OSS(com.aliyun.oss.OSS)

Example 53 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project iceberg by apache.

the class TestLocalAliyunOSS method testPutObject.

@Test
public void testPutObject() throws IOException {
    byte[] bytes = new byte[4 * 1024];
    random.nextBytes(bytes);
    String bucketNotExist = String.format("bucket-not-existing-%s", UUID.randomUUID());
    assertThrows(() -> oss.putObject(bucketNotExist, "object", wrap(bytes)), OSSErrorCode.NO_SUCH_BUCKET);
    PutObjectResult result = oss.putObject(bucketName, "object", wrap(bytes));
    Assert.assertEquals(AliyunOSSMockLocalStore.md5sum(wrap(bytes)), result.getETag());
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) Test(org.junit.Test)

Example 54 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project jeecg-boot by jeecgboot.

the class OssBootUtil method upload.

/**
 * 上传文件到oss
 * @param stream
 * @param relativePath
 * @return
 */
public static String upload(InputStream stream, String relativePath) {
    String FILE_URL = null;
    String fileUrl = relativePath;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
        FILE_URL = staticDomain + "/" + relativePath;
    } else {
        FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
    }
    PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), stream);
    // 设置权限(公开读)
    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    if (result != null) {
        log.info("------OSS文件上传成功------" + fileUrl);
    }
    return FILE_URL;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult)

Example 55 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project jeecg-boot by jeecgboot.

the class OssBootUtil method upload.

/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(MultipartFile file, String fileDir, String customBucket) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    String newBucket = bucketName;
    if (oConvertUtils.isNotEmpty(customBucket)) {
        newBucket = customBucket;
    }
    try {
        // 判断桶是否存在,不存在则创建桶
        if (!ossClient.doesBucketExist(newBucket)) {
            ossClient.createBucket(newBucket);
        }
        // 获取文件名
        String orgName = file.getOriginalFilename();
        if ("" == orgName) {
            orgName = file.getName();
        }
        // update-begin-author:liusq date:20210809 for: 过滤上传文件类型
        FileTypeFilter.fileTypeFilter(file);
        // update-end-author:liusq date:20210809 for: 过滤上传文件类型
        orgName = CommonUtils.getFileName(orgName);
        String fileName = orgName.indexOf(".") == -1 ? orgName + "_" + System.currentTimeMillis() : orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        // update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
        fileDir = StrAttackFilter.filter(fileDir);
        // update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
        fileUrl = fileUrl.append(fileDir + fileName);
        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
        // ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

PutObjectResult (com.aliyun.oss.model.PutObjectResult)56 Test (org.junit.Test)31 OSSException (com.aliyun.oss.OSSException)30 InputStream (java.io.InputStream)24 OSSObject (com.aliyun.oss.model.OSSObject)20 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)19 File (java.io.File)15 PutObjectRequest (com.aliyun.oss.model.PutObjectRequest)13 TestUtils.genFixedLengthInputStream (com.aliyun.oss.integrationtests.TestUtils.genFixedLengthInputStream)10 ByteArrayInputStream (java.io.ByteArrayInputStream)10 ArrayList (java.util.ArrayList)10 FileInputStream (java.io.FileInputStream)9 Callback (com.aliyun.oss.model.Callback)8 GetObjectRequest (com.aliyun.oss.model.GetObjectRequest)7 Date (java.util.Date)7 CopyObjectResult (com.aliyun.oss.model.CopyObjectResult)6 IOException (java.io.IOException)6 Ignore (org.junit.Ignore)6 OSS (com.aliyun.oss.OSS)5 CompleteMultipartUploadRequest (com.aliyun.oss.model.CompleteMultipartUploadRequest)5