Search in sources :

Example 41 with CosClientException

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();
    }
}
Also used : CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) PicOperations(com.qcloud.cos.model.ciModel.persistence.PicOperations) CIUploadResult(com.qcloud.cos.model.ciModel.persistence.CIUploadResult) ImageProcessRequest(com.qcloud.cos.model.ciModel.common.ImageProcessRequest) LinkedList(java.util.LinkedList) CIObject(com.qcloud.cos.model.ciModel.persistence.CIObject)

Example 42 with CosClientException

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) CosClientException(com.qcloud.cos.exception.CosClientException) HttpGet(org.apache.http.client.methods.HttpGet) HttpPut(org.apache.http.client.methods.HttpPut) HttpHead(org.apache.http.client.methods.HttpHead) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 43 with CosClientException

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();
        }
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) ResponseNotCompleteException(com.qcloud.cos.exception.ResponseNotCompleteException) BufferedInputStream(java.io.BufferedInputStream) SdkBufferedInputStream(com.qcloud.cos.internal.SdkBufferedInputStream) ResettableInputStream(com.qcloud.cos.internal.ResettableInputStream) ReleasableInputStream(com.qcloud.cos.internal.ReleasableInputStream) FileInputStream(java.io.FileInputStream) ProgressInputStream(com.qcloud.cos.event.ProgressInputStream) InputStream(java.io.InputStream) CosClientException(com.qcloud.cos.exception.CosClientException) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) 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) ProgressListener(com.qcloud.cos.event.ProgressListener) CosServiceException(com.qcloud.cos.exception.CosServiceException) BufferedInputStream(java.io.BufferedInputStream) SdkBufferedInputStream(com.qcloud.cos.internal.SdkBufferedInputStream)

Example 44 with CosClientException

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);
    }
}
Also used : KeyPair(java.security.KeyPair) SecretKey(javax.crypto.SecretKey) CosClientException(com.qcloud.cos.exception.CosClientException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyGenerator(javax.crypto.KeyGenerator) Provider(java.security.Provider) COSCredentialsProvider(com.qcloud.cos.auth.COSCredentialsProvider) MaterialsDescriptionProvider(com.qcloud.cos.model.MaterialsDescriptionProvider)

Example 45 with CosClientException

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;
}
Also used : MaterialsDescriptionProvider(com.qcloud.cos.model.MaterialsDescriptionProvider) InitiateMultipartUploadResult(com.qcloud.cos.model.InitiateMultipartUploadResult) CosClientException(com.qcloud.cos.exception.CosClientException) ObjectMetadata(com.qcloud.cos.internal.crypto.CryptoStorageMode.ObjectMetadata) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata)

Aggregations

CosClientException (com.qcloud.cos.exception.CosClientException)111 CosServiceException (com.qcloud.cos.exception.CosServiceException)64 COSCredentials (com.qcloud.cos.auth.COSCredentials)41 ClientConfig (com.qcloud.cos.ClientConfig)39 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)39 Region (com.qcloud.cos.region.Region)39 COSClient (com.qcloud.cos.COSClient)37 IOException (java.io.IOException)31 File (java.io.File)28 ByteArrayInputStream (java.io.ByteArrayInputStream)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)15 TransferManager (com.qcloud.cos.transfer.TransferManager)14 ExecutorService (java.util.concurrent.ExecutorService)14 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)13 URISyntaxException (java.net.URISyntaxException)13 MultiObjectDeleteException (com.qcloud.cos.exception.MultiObjectDeleteException)12 PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)12 SecretKey (javax.crypto.SecretKey)12 MalformedURLException (java.net.MalformedURLException)11 PutObjectResult (com.qcloud.cos.model.PutObjectResult)10