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);
}
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;
}
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);
}
}
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());
}
}
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();
}
Aggregations