Search in sources :

Example 66 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class CosErrorResponseHandler method handle.

@Override
public CosServiceException handle(CosHttpResponse httpResponse) throws XMLStreamException {
    final InputStream is = httpResponse.getContent();
    String xmlContent = null;
    /*
         * We don't always get an error response body back from COS. When we send a HEAD request, we
         * don't receive a body, so we'll have to just return what we can.
         */
    if (is == null || httpResponse.getRequest().getHttpMethod() == HttpMethodName.HEAD) {
        return createExceptionFromHeaders(httpResponse, null);
    }
    String content = null;
    try {
        content = IOUtils.toString(is);
    } catch (IOException ioe) {
        log.debug("Failed in parsing the error response : ", ioe);
        return createExceptionFromHeaders(httpResponse, null);
    }
    XMLStreamReader reader;
    synchronized (xmlInputFactory) {
        reader = xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(content.getBytes(UTF8)));
    }
    try {
        /*
             * target depth is to determine if the XML Error response from the server has any
             * element inside <Error> tag have child tags. Parsing such tags is not supported now.
             * target depth is incremented for every start tag and decremented after every end tag
             * is encountered.
             */
        int targetDepth = 0;
        final CosServiceExceptionBuilder exceptionBuilder = new CosServiceExceptionBuilder();
        exceptionBuilder.setErrorResponseXml(content);
        exceptionBuilder.setStatusCode(httpResponse.getStatusCode());
        boolean hasErrorTagVisited = false;
        while (reader.hasNext()) {
            int event = reader.next();
            switch(event) {
                case XMLStreamConstants.START_ELEMENT:
                    targetDepth++;
                    String tagName = reader.getLocalName();
                    if (targetDepth == 1 && !COSErrorTags.Error.toString().equals(tagName))
                        return createExceptionFromHeaders(httpResponse, "Unable to parse error response. Error XML Not in proper format." + content);
                    if (COSErrorTags.Error.toString().equals(tagName)) {
                        hasErrorTagVisited = true;
                    }
                    continue;
                case XMLStreamConstants.CHARACTERS:
                    xmlContent = reader.getText();
                    if (xmlContent != null)
                        xmlContent = xmlContent.trim();
                    continue;
                case XMLStreamConstants.END_ELEMENT:
                    tagName = reader.getLocalName();
                    targetDepth--;
                    if (!(hasErrorTagVisited) || targetDepth > 1) {
                        return createExceptionFromHeaders(httpResponse, "Unable to parse error response. Error XML Not in proper format." + content);
                    }
                    if (COSErrorTags.Message.toString().equals(tagName)) {
                        exceptionBuilder.setErrorMessage(xmlContent);
                    } else if (COSErrorTags.Code.toString().equals(tagName)) {
                        exceptionBuilder.setErrorCode(xmlContent);
                    } else if (COSErrorTags.RequestId.toString().equals(tagName)) {
                        exceptionBuilder.setRequestId(xmlContent);
                    } else if (COSErrorTags.TraceId.toString().equals(tagName)) {
                        exceptionBuilder.setTraceId(xmlContent);
                    } else {
                        exceptionBuilder.addAdditionalDetail(tagName, xmlContent);
                    }
                    continue;
                case XMLStreamConstants.END_DOCUMENT:
                    return exceptionBuilder.build();
            }
        }
    } catch (Exception e) {
        log.debug("Failed in parsing the error response : " + content, e);
    }
    return createExceptionFromHeaders(httpResponse, content);
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) CosServiceExceptionBuilder(com.qcloud.cos.exception.CosServiceExceptionBuilder) CosServiceException(com.qcloud.cos.exception.CosServiceException) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 67 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class DefaultCosHttpClient method handlerErrorMessage.

private <X extends CosServiceRequest> CosServiceException handlerErrorMessage(CosHttpRequest<X> request, HttpRequestBase httpRequestBase, final org.apache.http.HttpResponse apacheHttpResponse) throws IOException {
    final StatusLine statusLine = apacheHttpResponse.getStatusLine();
    final int statusCode;
    final String reasonPhrase;
    if (statusLine == null) {
        statusCode = -1;
        reasonPhrase = null;
    } else {
        statusCode = statusLine.getStatusCode();
        reasonPhrase = statusLine.getReasonPhrase();
    }
    CosHttpResponse response = createResponse(httpRequestBase, request, apacheHttpResponse);
    CosServiceException exception = null;
    try {
        exception = errorResponseHandler.handle(response);
        log.debug("Received error response: " + exception);
    } catch (Exception e) {
        // responses that don't have any content
        if (statusCode == 413) {
            exception = new CosServiceException("Request entity too large");
            exception.setStatusCode(statusCode);
            exception.setErrorType(ErrorType.Client);
            exception.setErrorCode("Request entity too large");
        } else if (statusCode == 503 && "Service Unavailable".equalsIgnoreCase(reasonPhrase)) {
            exception = new CosServiceException("Service unavailable");
            exception.setStatusCode(statusCode);
            exception.setErrorType(ErrorType.Service);
            exception.setErrorCode("Service unavailable");
        } else {
            String errorMessage = "Unable to unmarshall error response (" + e.getMessage() + "). Response Code: " + (statusLine == null ? "None" : statusCode) + ", Response Text: " + reasonPhrase;
            throw new CosClientException(errorMessage, e);
        }
    }
    exception.setStatusCode(statusCode);
    exception.fillInStackTrace();
    return exception;
}
Also used : StatusLine(org.apache.http.StatusLine) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) URISyntaxException(java.net.URISyntaxException) ResponseNotCompleteException(com.qcloud.cos.exception.ResponseNotCompleteException) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) IOException(java.io.IOException)

Example 68 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class CORSTest method putAndGetNotExistBucketCORSTest.

@Test
public void putAndGetNotExistBucketCORSTest() {
    if (!judgeUserInfoValid()) {
        return;
    }
    String bucketName = "not-exist-" + bucket;
    BucketCrossOriginConfiguration bucketCORS = new BucketCrossOriginConfiguration();
    List<CORSRule> corsRules = new ArrayList<>();
    bucketCORS.setRules(corsRules);
    try {
        cosclient.setBucketCrossOriginConfiguration(bucketName, bucketCORS);
    } catch (CosServiceException cse) {
        assertEquals(4, cse.getStatusCode() / 100);
    }
    try {
        cosclient.getBucketCrossOriginConfiguration(bucketName);
    } catch (CosServiceException cse) {
        assertEquals(404, cse.getStatusCode() / 100);
    }
}
Also used : BucketCrossOriginConfiguration(com.qcloud.cos.model.BucketCrossOriginConfiguration) CosServiceException(com.qcloud.cos.exception.CosServiceException) CORSRule(com.qcloud.cos.model.CORSRule) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 69 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class CreateDeleteHeadBucketTest method testCreateDeleteBucketPrivate.

@Test
public void testCreateDeleteBucketPrivate() throws Exception {
    if (!judgeUserInfoValid()) {
        return;
    }
    try {
        String bucketName = String.format("java-pri-%s", appid);
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        createBucketRequest.setCannedAcl(CannedAccessControlList.Private);
        Bucket bucket = cosclient.createBucket(createBucketRequest);
        assertEquals(bucketName, bucket.getName());
        assertTrue(cosclient.doesBucketExist(bucketName));
        BucketVersioningConfiguration bucketVersioningConfiguration = cosclient.getBucketVersioningConfiguration(bucketName);
        assertEquals(BucketVersioningConfiguration.OFF, bucketVersioningConfiguration.getStatus());
        cosclient.deleteBucket(bucketName);
        // 删除bucket后, 由于server端有缓存 需要稍后查询, 这里sleep 5 秒
        Thread.sleep(5000L);
        assertFalse(cosclient.doesBucketExist(bucketName));
    } catch (CosServiceException cse) {
        fail(cse.toString());
    }
}
Also used : CosServiceException(com.qcloud.cos.exception.CosServiceException) Bucket(com.qcloud.cos.model.Bucket) CreateBucketRequest(com.qcloud.cos.model.CreateBucketRequest) BucketVersioningConfiguration(com.qcloud.cos.model.BucketVersioningConfiguration) Test(org.junit.Test)

Example 70 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class TransferManagerDemo method pauseDownloadFileAndResume.

// 将文件下载到本地(中途暂停并继续开始)
public static void pauseDownloadFileAndResume() {
    // 1 初始化用户身份信息(secretId, secretKey)
    COSCredentials cred = new BasicCOSCredentials("AKIDXXXXXXXX", "1A2Z3YYYYYYYYYY");
    // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
    ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1"));
    // 3 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket名需包含appid
    String bucketName = "mybucket-1251668577";
    ExecutorService threadPool = Executors.newFixedThreadPool(32);
    // 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
    TransferManager transferManager = new TransferManager(cosclient, threadPool);
    String key = "aaa/bbb.txt";
    File downloadFile = new File("src/test/resources/download.txt");
    GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
    try {
        // 返回一个异步结果copy, 可同步的调用waitForCompletion等待download结束, 成功返回void, 失败抛出异常.
        Download download = transferManager.download(getObjectRequest, downloadFile);
        Thread.sleep(5000L);
        PersistableDownload persistableDownload = download.pause();
        download = transferManager.resumeDownload(persistableDownload);
        showTransferProgress(download);
        download.waitForCompletion();
    } catch (CosServiceException e) {
        e.printStackTrace();
    } catch (CosClientException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    transferManager.shutdownNow();
    cosclient.shutdown();
}
Also used : TransferManager(com.qcloud.cos.transfer.TransferManager) COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) CosClientException(com.qcloud.cos.exception.CosClientException) COSClient(com.qcloud.cos.COSClient) PersistableDownload(com.qcloud.cos.transfer.PersistableDownload) CosServiceException(com.qcloud.cos.exception.CosServiceException) ExecutorService(java.util.concurrent.ExecutorService) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig) File(java.io.File) GetObjectRequest(com.qcloud.cos.model.GetObjectRequest) PersistableDownload(com.qcloud.cos.transfer.PersistableDownload) MultipleFileDownload(com.qcloud.cos.transfer.MultipleFileDownload) Download(com.qcloud.cos.transfer.Download)

Aggregations

CosServiceException (com.qcloud.cos.exception.CosServiceException)82 CosClientException (com.qcloud.cos.exception.CosClientException)64 COSClient (com.qcloud.cos.COSClient)37 ClientConfig (com.qcloud.cos.ClientConfig)37 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)37 COSCredentials (com.qcloud.cos.auth.COSCredentials)37 Region (com.qcloud.cos.region.Region)37 File (java.io.File)28 IOException (java.io.IOException)20 PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)15 TransferManager (com.qcloud.cos.transfer.TransferManager)14 ExecutorService (java.util.concurrent.ExecutorService)14 GetObjectRequest (com.qcloud.cos.model.GetObjectRequest)13 ByteArrayInputStream (java.io.ByteArrayInputStream)13 PutObjectResult (com.qcloud.cos.model.PutObjectResult)12 MultiObjectDeleteException (com.qcloud.cos.exception.MultiObjectDeleteException)11 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)11 ArrayList (java.util.ArrayList)10 LinkedList (java.util.LinkedList)10 Test (org.junit.Test)10