use of com.qcloud.cos.exception.CosClientException in project cos-java-sdk-v5 by tencentyun.
the class BlindWatermarkDemo method addBlindWatermarkToExistImage.
public static void addBlindWatermarkToExistImage(COSClient cosClient) {
// bucket名需包含appid
// api 请参考:https://cloud.tencent.com/document/product/436/46782
String bucketName = "examplebucket-1250000000";
String key = "image/dog.jpg";
ImageProcessRequest imageProcessRequest = new ImageProcessRequest(bucketName, key);
PicOperations picOperations = new PicOperations();
picOperations.setIsPicInfo(1);
List<PicOperations.Rule> ruleList = new LinkedList<>();
PicOperations.Rule rule = new PicOperations.Rule();
rule.setBucket(bucketName);
rule.setFileId("/image/result/dog.jpg");
// 使用盲水印功能,水印图的宽高不得超过原图的1/8
rule.setRule("watermark/3/type/2/image/aHR0cDovL2V4YW1wbGVidWNrZXQtMTI1MDAwMDAwMC5jb3MuYXAtZ3Vhbmd6aG91Lm15cWNsb3VkLmNvbS9zaHVpeWluLnBuZw==");
ruleList.add(rule);
picOperations.setRules(ruleList);
imageProcessRequest.setPicOperations(picOperations);
try {
CIUploadResult ciUploadResult = cosClient.processImage(imageProcessRequest);
System.out.println(ciUploadResult.getOriginalInfo().getEtag());
for (CIObject ciObject : ciUploadResult.getProcessResults().getObjectList()) {
System.out.println(ciObject.getLocation());
}
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
}
}
use of com.qcloud.cos.exception.CosClientException in project cos-java-sdk-v5 by tencentyun.
the class DefaultCosHttpClient method buildHttpRequest.
private <X extends CosServiceRequest> HttpRequestBase buildHttpRequest(CosHttpRequest<X> request) throws CosClientException {
HttpRequestBase httpRequestBase = null;
HttpMethodName httpMethodName = request.getHttpMethod();
if (httpMethodName.equals(HttpMethodName.PUT)) {
httpRequestBase = new HttpPut();
} else if (httpMethodName.equals(HttpMethodName.GET)) {
httpRequestBase = new HttpGet();
} else if (httpMethodName.equals(HttpMethodName.DELETE)) {
httpRequestBase = new HttpDelete();
} else if (httpMethodName.equals(HttpMethodName.POST)) {
httpRequestBase = new HttpPost();
} else if (httpMethodName.equals(HttpMethodName.HEAD)) {
httpRequestBase = new HttpHead();
} else {
throw new CosClientException("unsupported http method " + httpMethodName);
}
httpRequestBase.setURI(buildUri(request));
long contentLength = -1;
Map<String, String> requestHeaders = request.getHeaders();
for (Entry<String, String> headerEntry : requestHeaders.entrySet()) {
String headerKey = headerEntry.getKey();
String headerValue = headerEntry.getValue();
if (headerKey.equals(Headers.CONTENT_LENGTH)) {
contentLength = Long.parseLong(headerValue);
continue;
}
headerValue = CodecUtils.convertFromUtf8ToIso88591(headerValue);
httpRequestBase.addHeader(headerKey, headerValue);
}
Map<String, String> customRequestHeaders = request.getOriginalRequest().getCustomRequestHeaders();
if (customRequestHeaders != null) {
for (Entry<String, String> customHeaderEntry : customRequestHeaders.entrySet()) {
String headerKey = customHeaderEntry.getKey();
String headerValue = customHeaderEntry.getValue();
if (headerKey.equals(Headers.CONTENT_LENGTH)) {
contentLength = Long.parseLong(headerValue);
continue;
}
headerValue = CodecUtils.convertFromUtf8ToIso88591(headerValue);
httpRequestBase.addHeader(headerKey, headerValue);
}
}
if (log.isDebugEnabled()) {
httpRequestBase.addHeader(Headers.SDK_LOG_DEBUG, "on");
} else {
httpRequestBase.addHeader(Headers.SDK_LOG_DEBUG, "off");
}
if (request.getContent() != null) {
InputStreamEntity reqEntity = new InputStreamEntity(request.getContent(), contentLength);
if (httpMethodName.equals(HttpMethodName.PUT) || httpMethodName.equals(HttpMethodName.POST)) {
HttpEntityEnclosingRequestBase entityRequestBase = (HttpEntityEnclosingRequestBase) httpRequestBase;
entityRequestBase.setEntity(reqEntity);
}
}
httpRequestBase.setConfig(this.requestConfig);
if (clientConfig.useBasicAuth()) {
// basic auth认证
setBasicProxyAuthorization(httpRequestBase);
}
return httpRequestBase;
}
use of com.qcloud.cos.exception.CosClientException in project cos-java-sdk-v5 by tencentyun.
the class DefaultCosHttpClient method exeute.
@Override
public <X, Y extends CosServiceRequest> X exeute(CosHttpRequest<Y> request, HttpResponseHandler<CosServiceResponse<X>> responseHandler) throws CosClientException, CosServiceException {
HttpResponse httpResponse = null;
HttpRequestBase httpRequest = null;
bufferAndResetAbleContent(request);
// Always mark the input stream before execution.
ProgressListener progressListener = request.getProgressListener();
final InputStream originalContent = request.getContent();
if (originalContent != null) {
request.setContent(monitorStreamProgress(progressListener, originalContent));
}
if (originalContent != null && originalContent.markSupported() && !(originalContent instanceof BufferedInputStream)) {
final int readLimit = clientConfig.getReadLimit();
originalContent.mark(readLimit);
}
int retryIndex = 0;
while (true) {
try {
checkInterrupted();
if (originalContent instanceof BufferedInputStream && originalContent.markSupported()) {
// Mark everytime for BufferedInputStream, since the marker could have been
// invalidated
final int readLimit = clientConfig.getReadLimit();
originalContent.mark(readLimit);
}
// 如果是重试的则恢复流
if (retryIndex != 0 && originalContent != null) {
originalContent.reset();
}
if (retryIndex != 0) {
long delay = backoffStrategy.computeDelayBeforeNextRetry(retryIndex);
Thread.sleep(delay);
}
HttpContext context = HttpClientContext.create();
httpRequest = buildHttpRequest(request);
httpResponse = null;
httpResponse = executeOneRequest(context, httpRequest);
checkResponse(request, httpRequest, httpResponse);
break;
} catch (CosServiceException cse) {
if (cse.getStatusCode() >= 500) {
String errorMsg = String.format("failed to execute http request, due to service exception," + " httpRequest: %s, retryIdx:%d, maxErrorRetry:%d", request.toString(), retryIndex, maxErrorRetry);
log.error(errorMsg, cse);
}
closeHttpResponseStream(httpResponse);
if (!shouldRetry(request, httpResponse, cse, retryIndex, retryPolicy)) {
throw cse;
}
} catch (CosClientException cce) {
String errorMsg = String.format("failed to execute http request, due to client exception," + " httpRequest: %s, retryIdx:%d, maxErrorRetry:%d", request.toString(), retryIndex, maxErrorRetry);
log.info(errorMsg, cce);
closeHttpResponseStream(httpResponse);
if (!shouldRetry(request, httpResponse, cce, retryIndex, retryPolicy)) {
log.error(errorMsg, cce);
throw cce;
}
} catch (Exception exp) {
String errorMsg = String.format("httpClient execute occur a unknow exception, httpRequest: %s", request.toString());
closeHttpResponseStream(httpResponse);
log.error(errorMsg, exp);
throw new CosClientException(errorMsg, exp);
} finally {
++retryIndex;
}
}
try {
CosHttpResponse cosHttpResponse = createResponse(httpRequest, request, httpResponse);
return responseHandler.handle(cosHttpResponse).getResult();
} catch (Exception e) {
if (e.getMessage().equals("Premature end of chunk coded message body: closing chunk expected")) {
throw new ResponseNotCompleteException("response chunk not complete", e);
}
String errorMsg = "Unable to execute response handle: " + e.getMessage();
log.info(errorMsg, e);
CosClientException cce = new CosClientException(errorMsg, e);
throw cce;
} finally {
if (!responseHandler.needsConnectionLeftOpen()) {
httpRequest.releaseConnection();
}
}
}
use of com.qcloud.cos.exception.CosClientException in project cos-java-sdk-v5 by tencentyun.
the class COSCryptoModuleBase method generateCEK.
/**
* @param kekMaterials non-null encryption materials
*/
protected final SecretKey generateCEK(final EncryptionMaterials kekMaterials, final Provider providerIn) {
final String keygenAlgo = contentCryptoScheme.getKeyGeneratorAlgorithm();
KeyGenerator generator;
try {
generator = providerIn == null ? KeyGenerator.getInstance(keygenAlgo) : KeyGenerator.getInstance(keygenAlgo, providerIn);
generator.init(contentCryptoScheme.getKeyLengthInBits(), cryptoScheme.getSecureRandom());
// Set to true if the key encryption involves the use of BC's public key
boolean involvesBCPublicKey = false;
KeyPair keypair = kekMaterials.getKeyPair();
if (keypair != null) {
String keyWrapAlgo = cryptoScheme.getKeyWrapScheme().getKeyWrapAlgorithm(keypair.getPublic());
if (keyWrapAlgo == null) {
Provider provider = generator.getProvider();
String providerName = provider == null ? null : provider.getName();
involvesBCPublicKey = CryptoRuntime.BOUNCY_CASTLE_PROVIDER.equals(providerName);
}
}
SecretKey secretKey = generator.generateKey();
if (!involvesBCPublicKey || secretKey.getEncoded()[0] != 0)
return secretKey;
for (int retry = 0; retry < 10; retry++) {
secretKey = generator.generateKey();
if (secretKey.getEncoded()[0] != 0)
return secretKey;
}
// The probability of getting here is 2^80, which is impossible in practice.
throw new CosClientException("Failed to generate secret key");
} catch (NoSuchAlgorithmException e) {
throw new CosClientException("Unable to generate envelope symmetric key:" + e.getMessage(), e);
}
}
use of com.qcloud.cos.exception.CosClientException in project cos-java-sdk-v5 by tencentyun.
the class COSCryptoModuleBase method initiateMultipartUploadSecurely.
@Override
public InitiateMultipartUploadResult initiateMultipartUploadSecurely(InitiateMultipartUploadRequest req) {
// Generate a one-time use symmetric key and initialize a cipher to
// encrypt object data
ContentCryptoMaterial cekMaterial = createContentCryptoMaterial(req);
if (cryptoConfig.getStorageMode() == ObjectMetadata) {
ObjectMetadata metadata = req.getObjectMetadata();
if (metadata == null)
metadata = new ObjectMetadata();
long dataSize = req.getDataSize();
long partSize = req.getPartSize();
if (dataSize < 0 || partSize < 0) {
throw new CosClientException("initiate multipart upload with encryption client must set dataSize and partSize");
}
if (partSize % 16 != 0) {
throw new CosClientException("initiat multipart uplaod with encryption client must set part size a mutiple of 16" + "but got " + partSize);
}
metadata.addUserMetadata(Headers.ENCRYPTION_DATA_SIZE, Long.toString(dataSize));
metadata.addUserMetadata(Headers.ENCRYPTION_PART_SIZE, Long.toString(partSize));
// Store encryption info in metadata
req.setObjectMetadata(updateMetadataWithContentCryptoMaterial(metadata, null, cekMaterial));
}
InitiateMultipartUploadResult result = cos.initiateMultipartUpload(req);
MultipartUploadCryptoContext uploadContext = newUploadContext(req, cekMaterial);
if (req instanceof MaterialsDescriptionProvider) {
MaterialsDescriptionProvider p = (MaterialsDescriptionProvider) req;
uploadContext.setMaterialsDescription(p.getMaterialsDescription());
}
multipartUploadContexts.put(result.getUploadId(), uploadContext);
return result;
}
Aggregations