Search in sources :

Example 1 with COSSigner

use of com.qcloud.cos.auth.COSSigner in project cos-java-sdk-v5 by tencentyun.

the class COSClient method buildDocPreview.

private String buildDocPreview(CosHttpRequest<DocHtmlRequest> request) throws URISyntaxException {
    String urlStr = request.getProtocol().toString() + "://" + request.getEndpoint() + request.getResourcePath();
    URIBuilder uriBuilder = new URIBuilder(urlStr);
    COSSigner cosSigner = clientConfig.getCosSigner();
    Date expiredTime = new Date(System.currentTimeMillis() + clientConfig.getSignExpired() * 1000);
    String authoriationStr = cosSigner.buildAuthorizationStr(request.getHttpMethod(), request.getResourcePath(), request.getHeaders(), request.getParameters(), fetchCredential(), expiredTime, true);
    DocHtmlRequest originalRequest = request.getOriginalRequest();
    uriBuilder.addParameter("ci-process", "doc-preview");
    uriBuilder.addParameter("dsttype", originalRequest.getType().toString());
    uriBuilder.addParameter("srcType", originalRequest.getSrcType());
    uriBuilder.addParameter("page", originalRequest.getPage());
    uriBuilder.addParameter("ImageParams", originalRequest.getImageParams());
    uriBuilder.addParameter("sheet", originalRequest.getSheet());
    uriBuilder.addParameter("password", originalRequest.getPassword());
    uriBuilder.addParameter("comment", originalRequest.getComment());
    uriBuilder.addParameter("excelPaperDirection", originalRequest.getExcelPaperDirection());
    uriBuilder.addParameter("quality", originalRequest.getQuality());
    uriBuilder.addParameter("scale", originalRequest.getScale());
    return uriBuilder.build().toString() + "&" + authoriationStr;
}
Also used : DocHtmlRequest(com.qcloud.cos.model.ciModel.job.DocHtmlRequest) COSSigner(com.qcloud.cos.auth.COSSigner) Date(java.util.Date) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 2 with COSSigner

use of com.qcloud.cos.auth.COSSigner in project cos-java-sdk-v5 by tencentyun.

the class COSClient method generatePresignedUrl.

@Override
public URL generatePresignedUrl(GeneratePresignedUrlRequest req, Boolean signHost) throws CosClientException {
    rejectNull(clientConfig.getRegion(), "region is null, region in clientConfig must be specified when generating a pre-signed URL");
    rejectNull(req, "The request parameter must be specified when generating a pre-signed URL");
    req.rejectIllegalArguments();
    final String bucketName = req.getBucketName();
    final String key = req.getKey();
    if (req.getExpiration() == null) {
        req.setExpiration(new Date(System.currentTimeMillis() + this.clientConfig.getSignExpired() * 1000));
    }
    HttpMethodName httpMethod = req.getMethod();
    CosHttpRequest<GeneratePresignedUrlRequest> request = createRequest(bucketName, key, req, httpMethod);
    addParameterIfNotNull(request, "versionId", req.getVersionId());
    for (Entry<String, String> entry : req.getRequestParameters().entrySet()) {
        request.addParameter(entry.getKey(), entry.getValue());
    }
    addHeaderIfNotNull(request, Headers.CONTENT_TYPE, req.getContentType());
    addHeaderIfNotNull(request, Headers.CONTENT_MD5, req.getContentMd5());
    // Custom headers that open up the possibility of supporting unexpected
    // cases.
    Map<String, String> customHeaders = req.getCustomRequestHeaders();
    if (customHeaders != null) {
        for (Map.Entry<String, String> e : customHeaders.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
    }
    addResponseHeaderParameters(request, req.getResponseHeaders());
    COSSigner cosSigner = new COSSigner();
    COSCredentials cred = fetchCredential();
    String authStr = cosSigner.buildAuthorizationStr(request.getHttpMethod(), request.getResourcePath(), request.getHeaders(), request.getParameters(), cred, req.getExpiration(), signHost);
    StringBuilder strBuilder = new StringBuilder();
    strBuilder.append(clientConfig.getHttpProtocol().toString()).append("://");
    strBuilder.append(clientConfig.getEndpointBuilder().buildGeneralApiEndpoint(formatBucket(bucketName, cred.getCOSAppId())));
    strBuilder.append(UrlEncoderUtils.encodeUrlPath(formatKey(key)));
    boolean hasAppendFirstParameter = false;
    if (authStr != null) {
        if (req.isSignPrefixMode()) {
            strBuilder.append("?sign=").append(UrlEncoderUtils.encode(authStr));
        } else {
            // urlencode auth string key & value
            String[] authParts = authStr.split("&");
            String[] encodeAuthParts = new String[authParts.length];
            for (int i = 0; i < authParts.length; i++) {
                String[] kv = authParts[i].split("=", 2);
                if (kv.length == 2) {
                    encodeAuthParts[i] = StringUtils.join("=", UrlEncoderUtils.encode(kv[0]), UrlEncoderUtils.encode(kv[1]));
                } else if (kv.length == 1) {
                    encodeAuthParts[i] = StringUtils.join("=", UrlEncoderUtils.encode(kv[0]));
                }
            }
            authStr = StringUtils.join("&", encodeAuthParts);
            strBuilder.append("?").append(authStr);
        }
        if (cred instanceof COSSessionCredentials) {
            strBuilder.append("&").append(Headers.SECURITY_TOKEN).append("=").append(UrlEncoderUtils.encode(((COSSessionCredentials) cred).getSessionToken()));
        }
        hasAppendFirstParameter = true;
    }
    for (Entry<String, String> entry : request.getParameters().entrySet()) {
        String paramKey = entry.getKey();
        String paramValue = entry.getValue();
        if (!hasAppendFirstParameter) {
            strBuilder.append("?");
            hasAppendFirstParameter = true;
        } else {
            strBuilder.append("&");
        }
        strBuilder.append(UrlEncoderUtils.encode(paramKey));
        if (paramValue != null) {
            strBuilder.append("=").append(UrlEncoderUtils.encode(paramValue));
        }
    }
    try {
        return new URL(strBuilder.toString());
    } catch (MalformedURLException e) {
        throw new CosClientException(e.toString());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) COSCredentials(com.qcloud.cos.auth.COSCredentials) CosClientException(com.qcloud.cos.exception.CosClientException) Date(java.util.Date) URL(java.net.URL) HttpMethodName(com.qcloud.cos.http.HttpMethodName) COSSessionCredentials(com.qcloud.cos.auth.COSSessionCredentials) COSSigner(com.qcloud.cos.auth.COSSigner) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with COSSigner

use of com.qcloud.cos.auth.COSSigner in project roof-im by madfroglx.

the class OCSTest method createAuthorization.

@Test
public void createAuthorization() throws UnsupportedEncodingException {
    String appid = "1255710173";
    String secret_id = "AKIDSpCPQFhNfmmcJ0Q0FKE7pNjuuiKlN73o";
    String secret_key = "kKjOsEPOCoFUlwviLm27IJ9nFWcaNyOc";
    // String sessionToken = "562af6ffcbe981dd21bd7434176dcbb2f883839030001";
    // 设置秘钥
    COSCredentials cred = new BasicCOSCredentials(appid, secret_id, secret_key);
    COSSigner cosSigner = new COSSigner();
    System.out.println(cosSigner.buildAuthorizationStr(HttpMethodName.POST, "/", cred, new Date(1520516362000L)));
}
Also used : COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) COSSigner(com.qcloud.cos.auth.COSSigner) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) Date(java.util.Date) Test(org.junit.Test)

Example 4 with COSSigner

use of com.qcloud.cos.auth.COSSigner in project cos-java-sdk-v5 by tencentyun.

the class COSClient method invoke.

private <X, Y extends CosServiceRequest> X invoke(CosHttpRequest<Y> request, HttpResponseHandler<CosServiceResponse<X>> responseHandler) throws CosClientException, CosServiceException {
    COSSigner cosSigner = clientConfig.getCosSigner();
    COSCredentials cosCredentials;
    CosServiceRequest cosServiceRequest = request.getOriginalRequest();
    if (cosServiceRequest != null && cosServiceRequest.getCosCredentials() != null) {
        cosCredentials = cosServiceRequest.getCosCredentials();
    } else {
        cosCredentials = fetchCredential();
    }
    Date expiredTime = new Date(System.currentTimeMillis() + clientConfig.getSignExpired() * 1000);
    boolean isCIWorkflowRequest = cosServiceRequest instanceof CIWorkflowServiceRequest;
    cosSigner.setCIWorkflowRequest(isCIWorkflowRequest);
    cosSigner.sign(request, cosCredentials, expiredTime);
    return this.cosHttpClient.exeute(request, responseHandler);
}
Also used : COSCredentials(com.qcloud.cos.auth.COSCredentials) COSSigner(com.qcloud.cos.auth.COSSigner) CosServiceRequest(com.qcloud.cos.internal.CosServiceRequest) CIWorkflowServiceRequest(com.qcloud.cos.internal.CIWorkflowServiceRequest) Date(java.util.Date)

Example 5 with COSSigner

use of com.qcloud.cos.auth.COSSigner in project cos-java-sdk-v5 by tencentyun.

the class PostObjectDemo method PostObjectUploadDemo.

private static void PostObjectUploadDemo() throws Exception {
    String bucketName = "mybucket-1251668577";
    String endpoint = "cos.ap-guangzhou.myqcloud.com";
    String key = "images/test.jpg";
    String filename = "test.jpg";
    String inputFilePath = "test.jpg";
    String contentType = "image/jpeg";
    String secretId = "AKIDXXXXXXXX";
    String seretKey = "1A2Z3YYYYYYYYYY";
    long startTimestamp = System.currentTimeMillis() / 1000;
    long endTimestamp = startTimestamp + 30 * 60;
    String endTimestampStr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(endTimestamp * 1000);
    String keyTime = startTimestamp + ";" + endTimestamp;
    String boundary = "----WebKitFormBoundaryZBPbaoYE2gqeB21N";
    // 设置表单的body字段值
    Map<String, String> formFields = new HashMap<>();
    formFields.put("q-sign-algorithm", "sha1");
    formFields.put("key", key);
    formFields.put("q-ak", secretId);
    formFields.put("q-key-time", keyTime);
    // 构造policy,参考文档: https://cloud.tencent.com/document/product/436/14690
    String policy = "{\n" + "    \"expiration\": \"" + endTimestampStr + "\",\n" + "    \"conditions\": [\n" + "        { \"bucket\": \"" + bucketName + "\" },\n" + "        { \"q-sign-algorithm\": \"sha1\" },\n" + "        { \"q-ak\": \"" + secretId + "\" },\n" + "        { \"q-sign-time\":\"" + keyTime + "\" }\n" + "    ]\n" + "}";
    // policy需要base64后算放入表单中
    String encodedPolicy = new String(Base64.encodeBase64(policy.getBytes()));
    // 设置policy
    formFields.put("policy", encodedPolicy);
    // 根据编码后的policy和secretKey计算签名
    COSSigner cosSigner = new COSSigner();
    String signature = cosSigner.buildPostObjectSignature(seretKey, keyTime, policy);
    // 设置签名
    formFields.put("q-signature", signature);
    // 根据以上表单参数,构造最开始的body部分
    String formBody = buildPostObjectBody(boundary, formFields, filename, contentType);
    HttpURLConnection conn = null;
    try {
        String urlStr = "http://" + bucketName + "." + endpoint;
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", VersionInfoUtils.getUserAgent());
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        // 写入表单的最开始部分
        out.write(formBody.getBytes());
        // 将文件内容写入到输出流中
        File file = new File(inputFilePath);
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int readBytes;
        byte[] bytes = new byte[4096];
        while ((readBytes = in.read(bytes)) != -1) {
            out.write(bytes, 0, readBytes);
        }
        in.close();
        // 添加最后一个分割符,行首和行尾都是--
        byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
        out.write(endData);
        out.flush();
        out.close();
        // 读取响应头部
        for (Map.Entry<String, List<String>> entries : conn.getHeaderFields().entrySet()) {
            String values = "";
            for (String value : entries.getValue()) {
                values += value + ",";
            }
            if (entries.getKey() == null) {
                System.out.println("reponse line:" + values);
            } else {
                System.out.println(entries.getKey() + ":" + values);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
Also used : HashMap(java.util.HashMap) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) COSSigner(com.qcloud.cos.auth.COSSigner) List(java.util.List) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

COSSigner (com.qcloud.cos.auth.COSSigner)5 Date (java.util.Date)4 COSCredentials (com.qcloud.cos.auth.COSCredentials)3 URL (java.net.URL)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)1 COSSessionCredentials (com.qcloud.cos.auth.COSSessionCredentials)1 CosClientException (com.qcloud.cos.exception.CosClientException)1 HttpMethodName (com.qcloud.cos.http.HttpMethodName)1 CIWorkflowServiceRequest (com.qcloud.cos.internal.CIWorkflowServiceRequest)1 CosServiceRequest (com.qcloud.cos.internal.CosServiceRequest)1 DocHtmlRequest (com.qcloud.cos.model.ciModel.job.DocHtmlRequest)1 HttpURLConnection (java.net.HttpURLConnection)1 MalformedURLException (java.net.MalformedURLException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 List (java.util.List)1 URIBuilder (org.apache.http.client.utils.URIBuilder)1 Test (org.junit.Test)1