index
int64
repo_id
string
file_path
string
content
string
0
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/interceptor
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/interceptor/request/V3ReqInterceptor.java
package com.aliyun.sdk.gateway.eiam.dev.interceptor.request; import com.aliyun.sdk.gateway.eiam.dev.auth.SignatureVersion; import com.aliyun.sdk.gateway.eiam.dev.auth.signer.PopSigner; import com.aliyun.core.http.FormatType; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class V3ReqInterceptor implements RequestInterceptor { private final ClientLogger logger = new ClientLogger(V3ReqInterceptor.class); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { logger.verbose("Request pre-process begin."); TeaRequest request = context.teaRequest(); TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V3) { return request; } Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("host", configuration.endpoint()), new TeaPair("accept", FormatType.JSON), new TeaPair("x-acs-version", request.version()), new TeaPair("x-acs-action", request.action()), new TeaPair("user-agent", clientConfiguration.option(ClientOption.USER_AGENT)) ), request.headers().toMap() ); request.setHeaders(new HttpHeaders(headers)); return request; } }
0
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/interceptor
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/interceptor/response/PopResInterceptor.java
package com.aliyun.sdk.gateway.eiam.dev.interceptor.response; import com.aliyun.core.http.BodyType; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import darabonba.core.TeaResponse; import darabonba.core.exception.TeaException; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; public class PopResInterceptor implements ResponseInterceptor { private final ClientLogger logger = new ClientLogger(PopResInterceptor.class); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { logger.verbose("TeaResponse process begin."); TeaResponse teaResponse = context.teaResponse(); if (teaResponse.success()) { HttpResponse httpResponse = teaResponse.httpResponse(); Object response; try { switch (context.teaRequest().bodyType()) { case BodyType.BYTE: //response = CommonUtil.buildMap( // new TeaPair("body", httpResponse.getBodyAsByteArray()), // new TeaPair("headers", headers) //); response = httpResponse.getBodyAsByteArray(); break; case BodyType.BIN: case BodyType.STRING: //response = CommonUtil.buildMap( // new TeaPair("body", httpResponse.getBodyAsString()), // new TeaPair("headers", headers) //); response = httpResponse.getBodyAsString(); break; case BodyType.JSON: //response = CommonUtil.buildMap( // new TeaPair("body", CommonUtil.assertAsMap(ParseUtil.readAsJSON(httpResponse.getBodyAsString()))), // new TeaPair("headers", headers) //); response = CommonUtil.assertAsMap(ParseUtil.readAsJSON(httpResponse.getBodyAsString())); break; case BodyType.ARRAY: //response = CommonUtil.buildMap( // new TeaPair("body", CommonUtil.assertAsArray(ParseUtil.readAsJSON(httpResponse.getBodyAsString()))), /// new TeaPair("headers", headers) //); response = CommonUtil.assertAsArray(ParseUtil.readAsJSON(httpResponse.getBodyAsString())); break; default: //response = CommonUtil.buildMap( // new TeaPair("body", httpResponse.getBodyAsString()), // new TeaPair("headers", headers) //); response = httpResponse.getBodyAsString(); } teaResponse.setDeserializedBody(response); } catch (Exception e) { teaResponse.setException(new TeaException("Process response body error!", e)); } finally { httpResponse.close(); } } return teaResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/interceptor
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/interceptor/response/TeaResponseInterceptor.java
package com.aliyun.sdk.gateway.eiam.dev.interceptor.response; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.sdk.gateway.eiam.dev.exception.PopClientException; import com.aliyun.sdk.gateway.eiam.dev.exception.PopServerException; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; import java.util.HashMap; import java.util.Map; public class TeaResponseInterceptor implements ResponseInterceptor { private final ClientLogger logger = new ClientLogger(PopResInterceptor.class); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { logger.verbose("HttpResponse process begin."); HttpResponse httpResponse = context.httpResponse(); TeaResponse teaResponse = new TeaResponse(); teaResponse.setHttpResponse(httpResponse); teaResponse.setSuccess(CommonUtil.is2xx(httpResponse.getStatusCode())); if (CommonUtil.isNot2xx(httpResponse.getStatusCode())) { Object _body = ParseUtil.readAsJSON(httpResponse.getBodyAsString()); Map<String, Object> err = CommonUtil.assertAsMap(_body); Object requestId = CommonUtil.defaultAny(err.get("request_id"), err.get("RequestId")); Map<String, Object> errMsg = new HashMap<>(); errMsg.put("code", "" + CommonUtil.defaultAny(err.get("error"), err.get("Code")) + ""); errMsg.put("message", "code: " + httpResponse.getStatusCode() + ", " + CommonUtil.defaultAny(err.get("error_description"), err.get("Message")) + " request id: " + requestId + ""); errMsg.put("data", err); teaResponse.setException(CommonUtil.is5xx(httpResponse.getStatusCode()) ? new PopServerException(errMsg) : new PopClientException(errMsg)); } return teaResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/models/Request.java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.gateway.eiam.dev.models; import darabonba.core.RequestModel; public abstract class Request extends RequestModel { protected Request(Builder<?, ?> builder) { super(builder); } public abstract Builder toBuilder(); protected abstract static class Builder<ProviderT extends Request, BuilderT extends Builder> extends BuilderImpl<ProviderT, BuilderT> { protected Builder() { } protected Builder(Request request) { } } }
0
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/models/Response.java
package com.aliyun.sdk.gateway.eiam.dev.models; import darabonba.core.TeaModel; public abstract class Response extends TeaModel { protected Response(BuilderImpl<?, ?> builder) { } public abstract Builder toBuilder(); public interface Builder<ProviderT extends Response, BuilderT extends Builder> { ProviderT build(); } protected abstract static class BuilderImpl<ProviderT extends Response, BuilderT extends Builder> implements Builder<ProviderT, BuilderT> { protected BuilderImpl() { } protected BuilderImpl(Response response) { } } }
0
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev
java-sources/com/aliyun/aliyun-gateway-eiam-dev/0.3.2-beta/com/aliyun/sdk/gateway/eiam/dev/policy/POPUserAgentPolicy.java
package com.aliyun.sdk.gateway.eiam.dev.policy; import java.io.IOException; import java.util.Properties; public class POPUserAgentPolicy { private static String gatewayVersion = "unknown"; static { try { Properties props = new Properties(); props.load(POPUserAgentPolicy.class.getClassLoader().getResourceAsStream("project.properties")); gatewayVersion = props.getProperty("eiam.gateway.version"); } catch (IOException e) { e.printStackTrace(); } } public static String getDefaultUserAgentSuffix() { return "aliyun-gateway-eiam-dev: " + gatewayVersion; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/BaseClientBuilder.java
package com.aliyun.sdk.gateway.eventbridge; import com.aliyun.auth.signature.Signer; import com.aliyun.sdk.gateway.eventbridge.auth.signer.EventBridgeV1Signer; import com.aliyun.sdk.gateway.eventbridge.interceptor.configuration.EndpointInterceptor; import com.aliyun.sdk.gateway.eventbridge.interceptor.httpRequest.HttpReqInterceptor; import com.aliyun.sdk.gateway.eventbridge.interceptor.output.FinalizedOutputInterceptor; import com.aliyun.sdk.gateway.eventbridge.interceptor.request.ProcPathRegexInterceptor; import com.aliyun.sdk.gateway.eventbridge.interceptor.request.ReqInterceptor; import com.aliyun.sdk.gateway.eventbridge.interceptor.response.EventBridgeResInterceptor; import com.aliyun.sdk.gateway.eventbridge.interceptor.response.TeaResponseInterceptor; import com.aliyun.sdk.gateway.eventbridge.policy.EventBridgeUserAgentPolicy; import darabonba.core.TeaClientBuilder; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.client.IClientBuilder; import darabonba.core.interceptor.InterceptorChain; public abstract class BaseClientBuilder<BuilderT extends IClientBuilder<BuilderT, ClientT>, ClientT> extends TeaClientBuilder<BuilderT, ClientT> { @Override protected String serviceName() { return "EventBridge"; } public BuilderT serviceConfiguration(Configuration serviceConfiguration) { clientConfiguration.setOption(ClientOption.SERVICE_CONFIGURATION, serviceConfiguration); return (BuilderT) this; } @Override protected ClientConfiguration mergeServiceDefaults(ClientConfiguration configuration) { return configuration.merge(ClientConfiguration.create() .setOption(ClientOption.SERVICE_CONFIGURATION, Configuration.create()) .setOption(ClientOption.USER_AGENT_SERVICE_SUFFIX, EventBridgeUserAgentPolicy.getDefaultUserAgentSuffix())); } @Override protected ClientConfiguration finalizeServiceConfiguration(ClientConfiguration configuration) { InterceptorChain chain = InterceptorChain.create(); chain.addConfigurationInterceptor(new EndpointInterceptor()); chain.addRequestInterceptor(new ProcPathRegexInterceptor()); chain.addRequestInterceptor(new ReqInterceptor()); chain.addHttpRequestInterceptor(new HttpReqInterceptor()); chain.addResponseInterceptor(new TeaResponseInterceptor()); chain.addResponseInterceptor(new EventBridgeResInterceptor()); chain.addOutputInterceptor(new FinalizedOutputInterceptor()); configuration.setOption(ClientOption.INTERCEPTOR_CHAIN, chain); Signer signer = new EventBridgeV1Signer(); configuration.setOption(ClientOption.SIGNER, signer); return configuration; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/Configuration.java
package com.aliyun.sdk.gateway.eventbridge; import darabonba.core.ServiceConfiguration; public final class Configuration implements ServiceConfiguration { private Configuration() { } public static Configuration create() { return new Configuration(); } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/auth/RpcSignatureComposer.java
package com.aliyun.sdk.gateway.eventbridge.auth; import com.aliyun.auth.signature.exception.SignatureException; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Map; import static com.aliyun.core.utils.EncodeUtil.percentEncode; public class RpcSignatureComposer { private final static String SEPARATOR = "&"; public static String composeStringToSign(HttpMethod method, Map<String, String> params, Map<String, String> headers, String pathname) { StringBuilder stringToSign = new StringBuilder(); try { stringToSign.append(method); stringToSign.append(SEPARATOR); stringToSign.append(percentEncode(pathname)); stringToSign.append(SEPARATOR); stringToSign.append(percentEncode( buildCanonicalizedResource(params))); } catch (UnsupportedEncodingException e) { throw new SignatureException(e.toString()); } return stringToSign.toString(); } private static String buildCanonicalizedResource(Map<String, String> params) { String[] sortedKeys = params.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); StringBuilder queryString = new StringBuilder(); try { for (String key : sortedKeys) { if (StringUtils.isEmpty(params.get(key))) { continue; } queryString.append(SEPARATOR) .append(percentEncode(key)).append("=") .append(percentEncode(params.get(key))); } } catch (UnsupportedEncodingException e) { throw new SignatureException(e.toString()); } return queryString.length() > 0 ? queryString.substring(1) : StringUtils.EMPTY; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/auth/SignatureComposer.java
package com.aliyun.sdk.gateway.eventbridge.auth; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.utils.StringUtils; import java.util.*; public class SignatureComposer { private final static String SEPARATOR = "&"; private final static String ACCEPT = "accept"; private final static String CONTENT_MD5 = "content-md5"; private final static String CONTENT_TYPE = "content-type"; private final static String DATE = "date"; private final static String prefix = "x-acs-"; public static String composeStringToSign(HttpMethod method, Map<String, String> params, Map<String, String> headers, String pathname) { String accept = headers.get(ACCEPT) == null ? StringUtils.EMPTY : headers.get(ACCEPT); String contentMD5 = headers.get(CONTENT_MD5) == null ? StringUtils.EMPTY : headers.get(CONTENT_MD5); String contentType = headers.get(CONTENT_TYPE) == null ? StringUtils.EMPTY : headers.get(CONTENT_TYPE); String date = headers.get(DATE) == null ? StringUtils.EMPTY : headers.get(DATE); String header = method + "\n" + accept + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n"; String canonicalizedHeaders = buildCanonicalizedHeaders(headers); String canonicalizedResource = buildCanonicalizedResource(pathname, params); return header + canonicalizedHeaders + canonicalizedResource; } private static String buildCanonicalizedHeaders(Map<String, String> headers) { Set<String> keys = headers.keySet(); List<String> canonicalizedKeys = new ArrayList<>(); for (String key : keys) { if (key.startsWith(prefix)) { canonicalizedKeys.add(key); } } Collections.sort(canonicalizedKeys); StringBuilder canonicalizedHeaders = new StringBuilder(); for (String key : canonicalizedKeys) { canonicalizedHeaders.append(key); canonicalizedHeaders.append(":"); canonicalizedHeaders.append(headers.get(key).trim()); canonicalizedHeaders.append("\n"); } return canonicalizedHeaders.toString(); } private static String buildCanonicalizedResource(String pathname, Map<String, String> params) { if (params.size() <= 0) { return pathname; } String[] keys = params.keySet().toArray(new String[params.size()]); StringBuilder queryString = new StringBuilder(pathname); queryString.append("?"); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { queryString.append(keys[i]); if (!StringUtils.isEmpty(params.get(keys[i])) && !StringUtils.isEmpty(params.get(keys[i]).trim())) { queryString.append("="); queryString.append(params.get(keys[i])); } queryString.append(SEPARATOR); } return queryString.length() > 0 ? queryString.deleteCharAt(queryString.length() - 1).toString() : StringUtils.EMPTY; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/auth
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/auth/signer/EventBridgeSigner.java
package com.aliyun.sdk.gateway.eventbridge.auth.signer; import com.aliyun.auth.signature.Signer; import com.aliyun.auth.signature.SignerParams; public interface EventBridgeSigner extends Signer { String signString(String stringToSign, SignerParams params); byte[] hash(byte[] raw); String getContent(); }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/auth
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/auth/signer/EventBridgeV1Signer.java
package com.aliyun.sdk.gateway.eventbridge.auth.signer; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.signature.SignerParams; import com.aliyun.auth.signature.exception.SignatureException; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSHA1; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.util.Base64; public class EventBridgeV1Signer implements EventBridgeSigner { private final String ENCODING = "UTF-8"; private final String DEFAULT_ALGORITHM = "HMAC_SHA1"; @Override public String signString(String stringToSign, SignerParams params) { try { Mac mac = SignAlgorithmHmacSHA1.HmacSHA1.getMac(); ICredential credential = params.credentials(); mac.init(new SecretKeySpec(credential.accessKeySecret().getBytes(ENCODING), SignAlgorithmHmacSHA1.HmacSHA1.toString())); return Base64.getEncoder().encodeToString(mac.doFinal(stringToSign.getBytes(ENCODING))); } catch (UnsupportedEncodingException | InvalidKeyException e) { throw new SignatureException(e.toString()); } } @Override public byte[] hash(byte[] raw) { return null; } @Override public String getContent() { return null; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/exception/EventBridgeClientException.java
package com.aliyun.sdk.gateway.eventbridge.exception; import com.aliyun.core.utils.StringUtils; import darabonba.core.exception.ClientException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class EventBridgeClientException extends ClientException { private String code; private String message; private String requestId; private Map<String, Object> data; public EventBridgeClientException() { super(); } public EventBridgeClientException(final String message) { super(message); } public EventBridgeClientException(final Throwable cause) { super(cause); } public EventBridgeClientException(final String message, final Throwable cause) { super(message, cause); } public EventBridgeClientException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public EventBridgeClientException(Map<String, Object> map) { setData(map); } public EventBridgeClientException(Map<String, Object> map, String message, Throwable cause) { super(message, cause); setData(map); } @Override public String getMessage() { if (!StringUtils.isEmpty(message)) { return "\n(Code: " + getErrCode() + "\nMessage: " + getErrMessage() + "\nRequest ID: " + getRequestId() + ")"; } return super.getMessage(); } public String getErrMessage() { return message; } public void setErrMessage(String message) { this.message = message; } public String getErrCode() { return code; } public void setErrCode(String code) { this.code = code; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public void setData(Map<String, Object> map) { this.setErrCode(String.valueOf(map.get("code"))); this.setErrMessage(String.valueOf(map.get("message"))); Object obj = map.get("data"); if (obj == null) { return; } if (obj instanceof Map) { data = (Map<String, Object>) obj; this.setRequestId(data.get("requestId").toString()); return; } Map<String, Object> hashMap = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); try { hashMap.put(field.getName(), field.get(obj)); } catch (Exception e) { continue; } } this.data = hashMap; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/exception/EventBridgeServerException.java
package com.aliyun.sdk.gateway.eventbridge.exception; import com.aliyun.core.utils.StringUtils; import darabonba.core.exception.ServerException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class EventBridgeServerException extends ServerException { private String code; private String message; private String requestId; private Map<String, Object> data; public EventBridgeServerException() { super(); } public EventBridgeServerException(final String message) { super(message); } public EventBridgeServerException(final Throwable cause) { super(cause); } public EventBridgeServerException(final String message, final Throwable cause) { super(message, cause); } public EventBridgeServerException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public EventBridgeServerException(Map<String, Object> map) { setData(map); } public EventBridgeServerException(Map<String, Object> map, String message, Throwable cause) { super(message, cause); setData(map); } @Override public String getMessage() { if (!StringUtils.isEmpty(message)) { return "\n(Code: " + getErrCode() + "\nMessage: " + getErrMessage() + "\nRequest ID: " + getRequestId() + ")"; } return super.getMessage(); } public String getErrMessage() { return message; } public void setErrMessage(String message) { this.message = message; } public String getErrCode() { return code; } public void setErrCode(String code) { this.code = code; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public void setData(Map<String, Object> map) { this.setErrCode(String.valueOf(map.get("code"))); this.setErrMessage(String.valueOf(map.get("message"))); Object obj = map.get("data"); if (obj == null) { return; } if (obj instanceof Map) { data = (Map<String, Object>) obj; this.setRequestId(data.get("requestId").toString()); return; } Map<String, Object> hashMap = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); try { hashMap.put(field.getName(), field.get(obj)); } catch (Exception e) { continue; } } this.data = hashMap; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/AttributeKey.java
package com.aliyun.sdk.gateway.eventbridge.interceptor; import com.aliyun.core.utils.AttributeMap; public final class AttributeKey<T> extends AttributeMap.Key<T> { public static final AttributeKey<Boolean> USE_SELF_GATEWAY = new AttributeKey<>(Boolean.class); protected AttributeKey(Class<T> valueType) { super(valueType); } protected AttributeKey(UnsafeValueType unsafeValueType) { super(unsafeValueType); } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/configuration/EndpointInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.configuration; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.eventbridge.exception.EventBridgeClientException; import com.aliyun.sdk.gateway.eventbridge.interceptor.AttributeKey; import darabonba.core.TeaConfiguration; import darabonba.core.interceptor.ConfigurationInterceptor; import darabonba.core.interceptor.InterceptorContext; public class EndpointInterceptor implements ConfigurationInterceptor { private final ClientLogger logger = new ClientLogger(EndpointInterceptor.class); @Override public TeaConfiguration modifyConfiguration(InterceptorContext context, AttributeMap attributes) { logger.info("Endpoint pre-process begin."); TeaConfiguration configuration = context.configuration(); if (StringUtils.isEmpty(configuration.endpoint())) { throw new EventBridgeClientException("Endpoint is empty, please set a valid endpoint"); } if (configuration.endpoint().contains(".eventbridge.")) { attributes.put(AttributeKey.USE_SELF_GATEWAY, true); } else { attributes.put(AttributeKey.USE_SELF_GATEWAY, false); } return configuration; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/httpRequest/HttpReqInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.httpRequest; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.provider.AnonymousCredentialProvider; import com.aliyun.auth.signature.SignerParams; import com.aliyun.core.http.*; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.MapUtils; import com.aliyun.core.utils.ParseUtil; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.eventbridge.auth.RpcSignatureComposer; import com.aliyun.sdk.gateway.eventbridge.auth.SignatureComposer; import com.aliyun.sdk.gateway.eventbridge.auth.signer.EventBridgeSigner; import com.aliyun.sdk.gateway.eventbridge.interceptor.AttributeKey; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.utils.CommonUtil; import darabonba.core.utils.ModelUtil; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; public class HttpReqInterceptor implements HttpRequestInterceptor { private final ClientLogger logger = new ClientLogger(HttpReqInterceptor.class); @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { Boolean useSelfGateway = attributes.get(AttributeKey.USE_SELF_GATEWAY); TeaRequest request = context.teaRequest(); HttpRequest httpRequest; TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); EventBridgeSigner signer = (EventBridgeSigner) clientConfiguration.option(ClientOption.SIGNER); HttpMethod method = Optional.ofNullable(configuration.method()).orElseGet(request::method); Map<String, String> headers = new HashMap<>(request.headers().toMap()); Map<String, String> query = request.query(); String body = null; if (useSelfGateway) { headers.put("date", CommonUtil.getDateUTCString()); headers.put("x-acs-signature-nonce", CommonUtil.getNonce()); if (!CommonUtil.isUnset(request.body())) { body = ParseUtil.toJSONString(request.body()); headers.put("content-type", FormatType.JSON); } if (request.action().equals("PutEvents")) { headers.put("content-type", "application/cloudevents-batch+json; charset=utf-8"); } if (request.action().equals("PutEventsToAccount")) { headers.put("content-type", "application/cloudevents-batch+json; charset=utf-8"); headers.put("x-eventbridge-sourcetype", "acs.*"); } if (!(configuration.credentialProvider() instanceof AnonymousCredentialProvider)) { ICredential credential = configuration.credentialProvider().getCredentials(); String accessKeyId = credential.accessKeyId(); String securityToken = credential.securityToken(); if (!StringUtils.isEmpty(securityToken)) { headers.put("x-acs-accesskey-id", accessKeyId); headers.put("x-acs-security-token", securityToken); } headers.putAll(CommonUtil.buildMap( new TeaPair("x-acs-signature-method", "HMAC-SHA1"), new TeaPair("x-acs-signature-version", "1.0"))); String strToSign = SignatureComposer.composeStringToSign(method, query, headers, request.pathname()); SignerParams params = SignerParams.create(); params.setCredentials(credential); headers.put("authorization", "acs " + accessKeyId + ":" + signer.signString(strToSign, params)); } } else { query.put("Timestamp", CommonUtil.getTimestamp()); query.put("SignatureNonce", CommonUtil.getNonce()); Map<String, String> bodyMap = new HashMap<>(); if (!CommonUtil.isUnset(request.body())) { bodyMap = ModelUtil.query(CommonUtil.assertAsMap(request.body())); headers.put("content-type", FormatType.FORM); } Map<String, String> paramsToSign = MapUtils.concat(query, bodyMap); if (!(configuration.credentialProvider() instanceof AnonymousCredentialProvider)) { ICredential credential = configuration.credentialProvider().getCredentials(); String securityToken = credential.securityToken(); if (!StringUtils.isEmpty(securityToken)) { query.put("SecurityToken", securityToken); } query.putAll(CommonUtil.buildMap( new TeaPair("SignatureMethod", "HMAC-SHA1"), new TeaPair("SignatureVersion", "1.0"), new TeaPair("AccessKeyId", credential.accessKeyId()) )); paramsToSign.putAll(query); String strToSign = RpcSignatureComposer.composeStringToSign(method, paramsToSign, headers, request.pathname()); SignerParams params = SignerParams.create(); Credential newCredential = Credential.builder() .accessKeyId(credential.accessKeyId()) .securityToken(securityToken) .accessKeySecret(credential.accessKeySecret() + "&") .build(); params.setCredentials(newCredential); query.put("Signature", signer.signString(strToSign, params)); } body = ModelUtil.toFormString(bodyMap); } HttpHeaders httpHeaders = new HttpHeaders(headers); httpRequest = new HttpRequest(method, ModelUtil.composeUrl(configuration.endpoint(), query, configuration.protocol(), request.pathname())); httpRequest.setHeaders(httpHeaders); if (!StringUtils.isEmpty(body)) { httpRequest.setBody(body); } return httpRequest; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/output/FinalizedOutputInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.output; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import darabonba.core.TeaModel; import darabonba.core.TeaPair; import darabonba.core.TeaResponse; import darabonba.core.exception.TeaException; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.OutputInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class FinalizedOutputInterceptor implements OutputInterceptor { private final ClientLogger logger = new ClientLogger(FinalizedOutputInterceptor.class); @Override public TeaModel modifyOutput(InterceptorContext context, AttributeMap attributes) { logger.info("OutputModel process begin."); TeaResponse response = context.teaResponse(); try { Map<String, ?> headers = response.httpResponse().getHeaders().toMap(); Map<String, Object> model = CommonUtil.buildMap( new TeaPair("body", response.deserializedBody()), new TeaPair("headers", headers)); TeaModel.toModel(model, context.output()); } catch (Exception e) { throw new TeaException(e); } return context.output(); } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/request/ProcPathRegexInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.request; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.eventbridge.interceptor.AttributeKey; import darabonba.core.TeaRequest; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import java.util.*; public class ProcPathRegexInterceptor implements RequestInterceptor { private static final Map<String, String> pathResources = new HashMap<>(); static { pathResources.put("CreateEventBus", "/openapi/createEventBus"); pathResources.put("CreateEventSource", "/openapi/v2/createEventSource"); pathResources.put("CreateRule", "/openapi/createRule"); pathResources.put("DeleteEventBus", "/openapi/deleteEventBus"); pathResources.put("DeleteEventSource", "/openapi/v2/deleteEventSource"); pathResources.put("DeleteEventStreaming", "/openapi/v2/deleteEventStreaming"); pathResources.put("DeleteRule", "/openapi/deleteRule"); pathResources.put("DeleteTargets", "/openapi/deleteTargets"); pathResources.put("DisableRule", "/openapi/disableRule"); pathResources.put("EnableRule", "/openapi/enableRule"); pathResources.put("GetEventBus", "/openapi/getEventBus"); pathResources.put("GetEventStreaming", "/openapi/v2/getEventStreaming"); pathResources.put("GetRule", "/openapi/getRule"); pathResources.put("ListAliyunOfficialEventSources", "/openapi/v2/listAliyunOfficialEventSources"); pathResources.put("ListEventBuses", "/openapi/listEventBuses"); pathResources.put("ListEventStreaming", "/openapi/v2/listEventStreamings"); pathResources.put("ListEventStreamingMetrics", "/openapi/v2/listEventStreamingMetrics"); pathResources.put("ListRules", "/openapi/listRules"); pathResources.put("ListTargets", "/openapi/listTargets"); pathResources.put("ListUserDefinedEventSources", "/openapi/v2/listUserDefinedEventSources"); pathResources.put("PauseEventStreaming", "/openapi/v2/pauseEventStreaming"); pathResources.put("PutEvents", "/openapi/putEvents"); pathResources.put("QueryEvent", "/openapi/queryEventByEventId"); pathResources.put("QueryEventTraces", "/openapi/queryEventTraces"); pathResources.put("StartEventStreaming", "/openapi/v2/pauseEventStreaming"); pathResources.put("UpdateEventSource", "/openapi/v2/updateEventSource"); pathResources.put("UpdateRule", "/openapi/updateRule"); } @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); Boolean useSelfGateway = attributes.get(AttributeKey.USE_SELF_GATEWAY); if(useSelfGateway && pathResources.get(request.action()) != null){ String pathName = pathResources.get(request.action()); request.setPathname(pathName); } return request; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/request/ReqInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.request; import com.aliyun.core.http.FormatType; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.eventbridge.interceptor.AttributeKey; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class ReqInterceptor implements RequestInterceptor { private final ClientLogger logger = new ClientLogger(ReqInterceptor.class); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { logger.info("Restful request pre-process begin."); Boolean useSelfGateway = attributes.get(AttributeKey.USE_SELF_GATEWAY); TeaRequest request = context.teaRequest(); TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("host", configuration.endpoint()), new TeaPair("accept", FormatType.JSON), new TeaPair("user-agent", clientConfiguration.option(ClientOption.USER_AGENT)) ), request.headers().toMap() ); if (useSelfGateway) { headers.put("x-eventbridge-version", request.version()); if (!StringUtils.isEmpty(configuration.region())) { headers.put("x-eventbridge-regionId", configuration.region()); } request.setHeaders(new HttpHeaders(headers)); } else { Map<String, String> query = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("Action", request.action()), new TeaPair("Format", "JSON"), new TeaPair("Version", request.version()) ), request.query() ); headers.put("x-acs-version", request.version()); headers.put("x-acs-action", request.action()); request.setQuery(query); } request.setHeaders(new HttpHeaders(headers)); return request; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/response/EventBridgeResInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.response; import com.aliyun.core.http.BodyType; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.sdk.gateway.eventbridge.exception.EventBridgeServerException; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; public class EventBridgeResInterceptor implements ResponseInterceptor { private final ClientLogger logger = new ClientLogger(EventBridgeResInterceptor.class); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { logger.info("TeaResponse process begin."); TeaResponse teaResponse = context.teaResponse(); if (teaResponse.success()) { HttpResponse httpResponse = teaResponse.httpResponse(); Object response; try { switch (context.teaRequest().bodyType()) { case BodyType.BYTE: response = httpResponse.getBodyAsByteArray(); break; case BodyType.JSON: response = CommonUtil.assertAsMap(ParseUtil.readAsJSON(httpResponse.getBodyAsString())); break; case BodyType.ARRAY: response = CommonUtil.assertAsArray(ParseUtil.readAsJSON(httpResponse.getBodyAsString())); break; default: response = httpResponse.getBodyAsString(); } teaResponse.setDeserializedBody(response); } catch (Exception e) { teaResponse.setException(new EventBridgeServerException("Process response body error!", e)); } finally { httpResponse.close(); } } return teaResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/interceptor/response/TeaResponseInterceptor.java
package com.aliyun.sdk.gateway.eventbridge.interceptor.response; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.sdk.gateway.eventbridge.exception.EventBridgeClientException; import com.aliyun.sdk.gateway.eventbridge.exception.EventBridgeServerException; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; import java.util.HashMap; import java.util.Map; public class TeaResponseInterceptor implements ResponseInterceptor { private final ClientLogger logger = new ClientLogger(TeaResponseInterceptor.class); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { logger.info("HttpResponse process begin."); HttpResponse httpResponse = context.httpResponse(); TeaResponse teaResponse = new TeaResponse(); teaResponse.setHttpResponse(httpResponse); teaResponse.setSuccess(CommonUtil.is2xx(httpResponse.getStatusCode())); if (CommonUtil.isNot2xx(httpResponse.getStatusCode())) { String bodyString = httpResponse.getBodyAsString(); Object _body = ParseUtil.readAsJSON(bodyString); Map<String, Object> err = CommonUtil.assertAsMap(_body); Object requestId = CommonUtil.defaultAny(err.get("RequestId"), err.get("requestId")); Map<String, Object> errMsg = new HashMap<>(); errMsg.put("code", "" + CommonUtil.defaultAny(err.get("Code"), err.get("code")) + ""); errMsg.put("message", "[EventBridgeError-" + requestId + "] " + CommonUtil.defaultAny(err.get("Message"), err.get("message"))); errMsg.put("data", err); teaResponse.setException(CommonUtil.is5xx(httpResponse.getStatusCode()) ? new EventBridgeServerException(errMsg) : new EventBridgeClientException(errMsg)); } return teaResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/models/Request.java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.gateway.eventbridge.models; import darabonba.core.RequestModel; public abstract class Request extends RequestModel { protected Request(Builder<?, ?> builder) { super(builder); } public abstract Builder toBuilder(); protected abstract static class Builder<ProviderT extends Request, BuilderT extends Builder> extends BuilderImpl<ProviderT, BuilderT> { protected Builder() { } protected Builder(Request request) { } } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/models/Response.java
package com.aliyun.sdk.gateway.eventbridge.models; import darabonba.core.TeaModel; public abstract class Response extends TeaModel { protected Response(BuilderImpl<?, ?> builder) { } public abstract Builder toBuilder(); public interface Builder<ProviderT extends Response, BuilderT extends Response.Builder> { ProviderT build(); } protected abstract static class BuilderImpl<ProviderT extends Response, BuilderT extends Response.Builder> implements Builder<ProviderT, BuilderT> { protected BuilderImpl() { } protected BuilderImpl(Response response) { } } }
0
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge
java-sources/com/aliyun/aliyun-gateway-eventbridge/0.3.2-beta/com/aliyun/sdk/gateway/eventbridge/policy/EventBridgeUserAgentPolicy.java
package com.aliyun.sdk.gateway.eventbridge.policy; import java.io.IOException; import java.util.Properties; public class EventBridgeUserAgentPolicy { private static String gatewayVersion = "unknown"; static { try { Properties props = new Properties(); props.load(EventBridgeUserAgentPolicy.class.getClassLoader().getResourceAsStream("project.properties")); gatewayVersion = props.getProperty("eventbridge.gateway.version"); } catch (IOException e) { e.printStackTrace(); } } public static String getDefaultUserAgentSuffix() { return "aliyun-gateway-eventbridge: " + gatewayVersion; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/BaseClientBuilder.java
package com.aliyun.sdk.gateway.oss; import com.aliyun.sdk.gateway.oss.auth.signer.OSSV1Signer; import com.aliyun.sdk.gateway.oss.internal.OSSEndpointType; import com.aliyun.sdk.gateway.oss.internal.interceptor.*; import com.aliyun.sdk.gateway.oss.policy.OSSUserAgentPolicy; import com.aliyun.sdk.gateway.oss.policy.retry.OSSRetryPolicy; import darabonba.core.TeaClientBuilder; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.client.IClientBuilder; import darabonba.core.interceptor.InterceptorChain; import java.net.URI; import java.net.URL; import java.util.Optional; public abstract class BaseClientBuilder<BuilderT extends IClientBuilder<BuilderT, ClientT>, ClientT> extends TeaClientBuilder<BuilderT, ClientT> { private String default_proto = "https"; private String default_region = "cn-hangzhou"; private Integer http_port = -1; @Override protected String serviceName() { return "OSS"; } public BuilderT serviceConfiguration(Configuration serviceConfiguration) { clientConfiguration.setOption(ClientOption.SERVICE_CONFIGURATION, serviceConfiguration); return (BuilderT) this; } @Override protected ClientConfiguration mergeServiceDefaults(ClientConfiguration configuration) { return configuration.merge(ClientConfiguration.create() .setOption(ClientOption.SERVICE_CONFIGURATION, Configuration.create()) .setOption(ClientOption.RETRY_POLICY, OSSRetryPolicy.defaultRetryPolicy()) .setOption(ClientOption.CLOCK_SKEW_DIFF, 0L) .setOption(ClientOption.USER_AGENT_SERVICE_SUFFIX, OSSUserAgentPolicy.getDefaultUserAgentSuffix()) ); } @Override protected ClientConfiguration finalizeServiceConfiguration(ClientConfiguration configuration) { Configuration config = (Configuration) configuration.option(ClientOption.SERVICE_CONFIGURATION); //interceptor InterceptorChain chain = InterceptorChain.create(); //request stage chain.addRequestInterceptor(new ProcPathRegexInterceptor()); SelectObjectInterceptor selectObjectInterceptor = new SelectObjectInterceptor(); chain.addRequestInterceptor(selectObjectInterceptor); chain.addRequestInterceptor(new TransformRequestBodyInterceptor()); chain.addRequestInterceptor(new AddCommonHeadersInterceptor()); ChecksumValidationInterceptor checksumInterceptor = new ChecksumValidationInterceptor(); chain.addRequestInterceptor(checksumInterceptor); UrlDecodeEncodeInterceptor urlInterceptor = new UrlDecodeEncodeInterceptor(); chain.addRequestInterceptor(urlInterceptor); //http request stage chain.addHttpRequestInterceptor(new MakeMutableHttpRequestInterceptor()); chain.addHttpRequestInterceptor(new AddMetricInterceptor()); chain.addHttpRequestInterceptor(new SigningInterceptor()); chain.addHttpRequestInterceptor(new GenerateUrlInterceptor()); //response stage chain.addResponseInterceptor(new MakeMutableResponseInterceptor()); chain.addResponseInterceptor(new ProcResponseBodyInterceptor()); chain.addResponseInterceptor(new AdjustClockSkew()); chain.addResponseInterceptor(urlInterceptor); chain.addResponseInterceptor(checksumInterceptor); chain.addResponseInterceptor(selectObjectInterceptor); //output stage chain.addOutputInterceptor(new FinalizedOutputInterceptor()); configuration.setOption(ClientOption.INTERCEPTOR_CHAIN, chain); //signer //config.signatureVersion() == SignVersion.V1 //Signer signer; configuration.setOption(ClientOption.SIGNER, new OSSV1Signer()); //region configuration.setOption(ClientOption.REGION, resolveRegion(configuration)); //http port configuration.setOption(ClientOption.HTTP_PORT, resolveHttpPort(configuration)); //http protocol configuration.setOption(ClientOption.HTTP_PROTOCOL, resolveHttpProtocol(configuration)); //endpoint uri configuration.setOption(ClientOption.ENDPOINT_URI, resolveEndpointURI(configuration)); return configuration; } private String resolveRegion(ClientConfiguration config) { return Optional.ofNullable(config.option(ClientOption.REGION)).orElse(default_region); } private Integer resolveHttpPort(ClientConfiguration config) { return Optional.ofNullable(config.option(ClientOption.HTTP_PORT)).orElse(http_port); } private String resolveHttpProtocol(ClientConfiguration config) { return Optional.ofNullable(config.option(ClientOption.HTTP_PROTOCOL)).orElse(default_proto); } private URI resolveEndpointURI(ClientConfiguration config) { return Optional.ofNullable(endpointURIFromEndpoint(config)).orElse(endpointURIFromRegion(config)); } private URI toURI(String value) { URI uri = null; try { uri = new URI(value); } catch (Exception ignored) { } return uri; } private URI endpointURIFromEndpoint(ClientConfiguration config) { String value = config.option(ClientOption.ENDPOINT); String defaultProto = config.option(ClientOption.HTTP_PROTOCOL); if (value != null && !value.contains("://")) { value = defaultProto + "://" + value; } return toURI(value); } private URI endpointURIFromRegion(ClientConfiguration config) { final String region = config.option(ClientOption.REGION); final String type = Optional.ofNullable(config.option(ClientOption.ENDPOINT_TYPE)).orElse(OSSEndpointType.PUBLIC); final String proto = config.option(ClientOption.HTTP_PROTOCOL); String endpoint; switch (type.toLowerCase()) { case OSSEndpointType.INTERNAL: case OSSEndpointType.INTRANET: endpoint = "oss-" + region + "-internal.aliyuncs.com"; break; case OSSEndpointType.ACCELERATE: endpoint = "oss-accelerate.aliyuncs.com"; break; case OSSEndpointType.ACCELERATE_OVERSEAS: endpoint = "oss-accelerate-overseas.aliyuncs.com"; break; case OSSEndpointType.DUAL_STACK: endpoint = region + ".oss.aliyuncs.com"; break; case OSSEndpointType.PUBLIC: case OSSEndpointType.EXTRANET: default: endpoint = "oss-" + region + ".aliyuncs.com"; break; } return toURI(proto + "://" + endpoint); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/BasePresignerClientBuilder.java
package com.aliyun.sdk.gateway.oss; import com.aliyun.sdk.gateway.oss.internal.interceptor.GenerateUrlInterceptor; import com.aliyun.sdk.gateway.oss.internal.interceptor.MakeMutableHttpRequestInterceptor; import com.aliyun.sdk.gateway.oss.internal.interceptor.PreSigningInterceptor; import com.aliyun.sdk.gateway.oss.internal.interceptor.ProcPathRegexInterceptor; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.client.IClientBuilder; import darabonba.core.interceptor.InterceptorChain; public abstract class BasePresignerClientBuilder<BuilderT extends IClientBuilder<BuilderT, ClientT>, ClientT> extends BaseClientBuilder<BuilderT, ClientT> { @Override protected ClientConfiguration finalizeServiceConfiguration(ClientConfiguration configuration) { ClientConfiguration config = super.finalizeServiceConfiguration(configuration); //interceptor InterceptorChain chain = InterceptorChain.create(); chain.addRequestInterceptor(new ProcPathRegexInterceptor()); chain.addRequestInterceptor(new PreSigningInterceptor()); chain.addHttpRequestInterceptor(new MakeMutableHttpRequestInterceptor()); chain.addHttpRequestInterceptor(new GenerateUrlInterceptor()); config.setOption(ClientOption.INTERCEPTOR_CHAIN, chain); return config; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/Configuration.java
package com.aliyun.sdk.gateway.oss; import com.aliyun.sdk.gateway.oss.auth.SignVersion; import darabonba.core.ServiceConfiguration; public final class Configuration implements ServiceConfiguration { public static final SignVersion DEFAULT_SIGNATURE_VERSION = SignVersion.V1; private SignVersion signatureVersion = DEFAULT_SIGNATURE_VERSION; private boolean cnameEnabled = false; private boolean crcEnabled = true; private boolean pathStyleEnabled = false; private Configuration() { } public static Configuration create() { return new Configuration(); } public SignVersion signatureVersion() { return signatureVersion; } public Configuration setSignatureVersion(SignVersion signatureVersion) { this.signatureVersion = signatureVersion; return this; } public boolean cnameEnabled() { return cnameEnabled; } public Configuration setCnameEnabled(boolean cnameEnabled) { this.cnameEnabled = cnameEnabled; return this; } public boolean crcEnabled() { return crcEnabled; } public Configuration setCrcEnabled(boolean crcEnabled) { this.crcEnabled = crcEnabled; return this; } public boolean pathStyleEnabled() { return pathStyleEnabled; } public Configuration setPathStyleEnabled(boolean pathStyleEnabled) { this.pathStyleEnabled = pathStyleEnabled; return this; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth/SignVersion.java
package com.aliyun.sdk.gateway.oss.auth; public enum SignVersion { V1 }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth/signer/OSSSigner.java
package com.aliyun.sdk.gateway.oss.auth.signer; import com.aliyun.auth.signature.Signer; import com.aliyun.core.http.HttpRequest; import darabonba.core.TeaRequest; public interface OSSSigner extends Signer { public HttpRequest sign(TeaRequest request, HttpRequest httpRequest, OSSSignerParams params); public TeaRequest presign(TeaRequest request, OSSSignerParams params); }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth/signer/OSSSignerParams.java
package com.aliyun.sdk.gateway.oss.auth.signer; import com.aliyun.auth.signature.SignerParams; import java.time.Instant; import java.util.List; public class OSSSignerParams extends SignerParams { private List<String> subResources; private Instant signatureExpiration; protected OSSSignerParams() { super(); } public static OSSSignerParams create() { return new OSSSignerParams(); } public OSSSignerParams setSubResources(List<String> subResources) { this.subResources = subResources; return this; } public List<String> subResources() { return this.subResources; } public OSSSignerParams setSignatureExpiration(Instant signatureExpiration) { this.signatureExpiration = signatureExpiration; return this; } public Instant SignatureExpiration() { return this.signatureExpiration; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/auth/signer/OSSV1Signer.java
package com.aliyun.sdk.gateway.oss.auth.signer; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSHA1; import com.aliyun.core.http.HttpHeader; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.Base64Util; import darabonba.core.TeaRequest; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.time.Instant; import java.util.*; public class OSSV1Signer implements OSSSigner { private static final String OSS_PREFIX = "x-oss-"; private static final String AUTHORIZATION = "Authorization"; private static final String CONTENT_MD5 = "Content-MD5"; private static final String CONTENT_TYPE = "Content-Type"; private static final String DATE = "Date"; private static final String NEW_LINE = "\n"; private static final String AUTHORIZATION_PREFIX = "OSS "; private static final List<String> DEFAULT_SIGNED_PARAMETERS = Arrays.asList( /*stander http key in query*/ "response-cache-control", "response-content-disposition", "response-content-encoding", "response-content-language", "response-content-type", "response-expires", "continuation-token", /*oss key in query*/ "security-token", "callback", "callback-var", "versionId", "uploadId", "partNumber", "position", "sequential", "inventoryId", "wormId", /*live channel*/ "startTime", "endTime", "status"); @Override public HttpRequest sign(TeaRequest request, HttpRequest httpRequest, OSSSignerParams params) { final ICredential cred = params.credentials(); String signature = buildSignature( cred.accessKeySecret(), request.method().toString(), request.pathname(), httpRequest.getHeaders(), request.query(), params.subResources()); httpRequest.getHeaders().set(AUTHORIZATION, composeRequestAuthorization(cred.accessKeyId(), signature)); return httpRequest; } @Override public TeaRequest presign(TeaRequest request, OSSSignerParams params) { Instant instant = params.SignatureExpiration(); final ICredential cred = params.credentials(); String expires = String.valueOf(instant.toEpochMilli()/1000); HttpRequest httpRequest = new HttpRequest(request.method()); httpRequest.getHeaders().putAll(request.headers()); httpRequest.setHeader(DATE, expires); String signature = buildSignature( cred.accessKeySecret(), request.method().toString(), request.pathname(), httpRequest.getHeaders(), request.query(), params.subResources()); request.query().put("Expires", expires); request.query().put("OSSAccessKeyId", cred.accessKeyId()); request.query().put("Signature", signature); return request; } private static String composeRequestAuthorization(String accessKeyId, String signature) { return AUTHORIZATION_PREFIX + accessKeyId + ":" + signature; } private static String buildCanonicalString(String method, String resourcePath, HttpHeaders headers, Map<String, String> query, List<String> subResources) { StringBuilder canonicalString = new StringBuilder(); canonicalString.append(method).append(NEW_LINE); //HttpHeaders headers = request.headers(); TreeMap<String, String> headersToSign = new TreeMap<String, String>(); for (Iterator<HttpHeader> it = headers.iterator(); it.hasNext(); ) { HttpHeader header = it.next(); if (header == null) { continue; } String lowerKey = header.getName().toLowerCase(); if (lowerKey.equals(CONTENT_TYPE.toLowerCase()) || lowerKey.equals(CONTENT_MD5.toLowerCase()) || lowerKey.equals(DATE.toLowerCase()) || lowerKey.startsWith(OSS_PREFIX)) { headersToSign.put(lowerKey, header.getValue().trim()); } } if (!headersToSign.containsKey(CONTENT_TYPE.toLowerCase())) { headersToSign.put(CONTENT_TYPE.toLowerCase(), ""); } if (!headersToSign.containsKey(CONTENT_MD5.toLowerCase())) { headersToSign.put(CONTENT_MD5.toLowerCase(), ""); } // Append all headers to sign to canonical string for (Map.Entry<String, String> entry : headersToSign.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith(OSS_PREFIX)) { canonicalString.append(key).append(':').append(value); } else { canonicalString.append(value); } canonicalString.append(NEW_LINE); } // Append canonical resource to canonical string canonicalString.append(buildCanonicalizedResource(resourcePath, query, subResources)); return canonicalString.toString(); } private static boolean hasSubResource(String name, List<String> subResources) { if (subResources.contains(name)) { return true; } if (DEFAULT_SIGNED_PARAMETERS.contains(name)) { return true; } if (name.startsWith(OSS_PREFIX)) { return true; } return false; } private static String buildCanonicalizedResource(String resourcePath, Map<String, String> parameters, List<String> subResources) { StringBuilder builder = new StringBuilder(); builder.append(resourcePath); if (parameters != null) { String[] parameterNames = parameters.keySet().toArray(new String[parameters.size()]); Arrays.sort(parameterNames); char separator = '?'; for (String paramName : parameterNames) { if (!hasSubResource(paramName, subResources)) { continue; } builder.append(separator); builder.append(paramName); String paramValue = parameters.get(paramName); if (paramValue != null && !paramValue.isEmpty()) { builder.append("=").append(paramValue); } separator = '&'; } } return builder.toString(); } private static String computeSignature(String key, String data) { byte[] signData = sign(key.getBytes(StandardCharsets.UTF_8), data.getBytes(StandardCharsets.UTF_8)); return Base64Util.encodeToString(signData); } private static byte[] sign(byte[] key, byte[] data) { try { Mac mac = SignAlgorithmHmacSHA1.HmacSHA1.getMac(); mac.init(new SecretKeySpec(key, SignAlgorithmHmacSHA1.HmacSHA1.toString())); return mac.doFinal(data); } catch (InvalidKeyException ex) { throw new RuntimeException("Invalid key: " + key, ex); } } private static String buildSignature(String secretAccessKey, String httpMethod, String resourcePath, HttpHeaders headers, Map<String, String> query, List<String> subResources) { String canonicalString = buildCanonicalString(httpMethod, resourcePath, headers, query, subResources); return computeSignature(secretAccessKey, canonicalString); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/exception/InconsistentException.java
package com.aliyun.sdk.gateway.oss.exception; import darabonba.core.exception.ClientException; public class InconsistentException extends ClientException { private static final long serialVersionUID = 2140587868503948665L; private Long clientChecksum; private Long serverChecksum; private String requestId; public InconsistentException(Long clientChecksum, Long serverChecksum, String requestId) { super(); this.clientChecksum = clientChecksum; this.serverChecksum = serverChecksum; this.requestId = requestId; } public Long getClientChecksum() { return clientChecksum; } public void setClientChecksum(Long clientChecksum) { this.clientChecksum = clientChecksum; } public Long getServerChecksum() { return serverChecksum; } public void setServerChecksum(Long serverChecksum) { this.serverChecksum = serverChecksum; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public String getMessage() { return "InconsistentException " + "\n[RequestId]: " + getRequestId() + "\n[ClientChecksum]: " + getClientChecksum() + "\n[ServerChecksum]: " + getServerChecksum(); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/exception/OSSClientException.java
package com.aliyun.sdk.gateway.oss.exception; import darabonba.core.exception.ClientException; public class OSSClientException extends ClientException { public OSSClientException(final String message, final Throwable cause) { super(message, cause); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/exception/OSSErrorDetails.java
package com.aliyun.sdk.gateway.oss.exception; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class OSSErrorDetails { private Map<String, String> errorMap; private String rawResponse; public String errorMessage() { return getErrorField("Message"); } public String errorCode() { return getErrorField("Code"); } public String hostId() { return getErrorField("HostId"); } public String requestId() { return getErrorField("RequestId"); } public String getErrorField(String key) { return errorMap.getOrDefault(key, ""); } public String rawResponse() { return rawResponse; } public OSSErrorDetails() { this(new HashMap<>(), ""); } public OSSErrorDetails(Map<String, String> errorMap, String rawResponse) { this.errorMap = Optional.ofNullable(errorMap).orElse(new HashMap<>()); this.rawResponse = rawResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/exception/OSSServerException.java
package com.aliyun.sdk.gateway.oss.exception; import darabonba.core.exception.ServerException; /* public class OSSServerException extends ServerException { private String requestId; private int statusCode; private Error error; private Map<String, String> values; private void init(Map<String, String> map) { error = Error.builder() .code(map.getOrDefault("Code", "")) .message(map.getOrDefault("Message", "")) .hostId(map.getOrDefault("HostId", "")) .requestId(map.getOrDefault("RequestId", "")) .build(); values = map; } public OSSServerException() { super(); init(new HashMap<>()); } public OSSServerException(Map<String, String> map) { super(); init(Optional.ofNullable(map).orElse(new HashMap<>())); } public OSSServerException(String code, String message, String requestId, String hostId, Throwable cause) { super(null, cause); error = Error.builder() .code(code) .message(message) .hostId(requestId) .requestId(hostId) .build(); values = new HashMap<>(); } public OSSServerException(String message, Throwable cause) { super(message, cause); init(new HashMap<>()); } public Error getError() { return error; } public String getErrorValue(String key) { return values.getOrDefault(key, ""); } @Override public String getMessage() { return error.message() + "\n[Code]: " + error.code() + "\n[RequestId]: " + error.requestId() + "\n[HostId]: " + error.hostId(); } } */ public class OSSServerException extends ServerException { private String requestId; private int statusCode; private OSSErrorDetails errorDetails; public OSSServerException(OSSErrorDetails error) { super(); } public OSSServerException(int statusCode, OSSErrorDetails errorDetails) { super(); this.statusCode = statusCode; this.errorDetails = errorDetails; this.requestId = errorDetails.requestId(); } public OSSErrorDetails errorDetails() { return errorDetails; } public String requestId() { return requestId; } public int statusCode() { return statusCode; } @Override public String getMessage() { if (errorDetails != null) { return errorDetails().errorMessage() + " (Status Code: " + statusCode() + ", Code: " + errorDetails().errorCode() + ", Request ID: " + requestId() + ")"; } return super.getMessage(); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/CRC64.java
package com.aliyun.sdk.gateway.oss.internal; import java.util.zip.Checksum; public class CRC64 implements Checksum { private final static long POLY = (long) 0xc96c5795d7870f42L; // ECMA-182 /* CRC64 calculation table. */ private final static long[] table; private static final int GF2_DIM = 64; /* * dimension of GF(2) vectors (length * of CRC) */ static { table = new long[256]; for (int n = 0; n < 256; n++) { long crc = n; for (int k = 0; k < 8; k++) { if ((crc & 1) == 1) { crc = (crc >>> 1) ^ POLY; } else { crc = (crc >>> 1); } } table[n] = crc; } } /* Current CRC value. */ private long value; public CRC64() { this.value = 0; } public CRC64(long value) { this.value = value; } public CRC64(byte[] b, int len) { this.value = 0; update(b, len); } /** * Construct new CRC64 instance from byte array. **/ public static CRC64 fromBytes(byte[] b) { long l = 0; for (int i = 0; i < 4; i++) { l <<= 8; l ^= (long) b[i] & 0xFF; } return new CRC64(l); } private static long gf2MatrixTimes(long[] mat, long vec) { long sum = 0; int idx = 0; while (vec != 0) { if ((vec & 1) == 1) sum ^= mat[idx]; vec >>>= 1; idx++; } return sum; } private static void gf2MatrixSquare(long[] square, long[] mat) { for (int n = 0; n < GF2_DIM; n++) square[n] = gf2MatrixTimes(mat, mat[n]); } /* * Return the CRC-64 of two sequential blocks, where summ1 is the CRC-64 of * the first block, summ2 is the CRC-64 of the second block, and len2 is the * length of the second block. */ static public CRC64 combine(CRC64 summ1, CRC64 summ2, long len2) { // degenerate case. if (len2 == 0) return new CRC64(summ1.getValue()); int n; long row; long[] even = new long[GF2_DIM]; // even-power-of-two zeros operator long[] odd = new long[GF2_DIM]; // odd-power-of-two zeros operator // put operator for one zero bit in odd odd[0] = POLY; // CRC-64 polynomial row = 1; for (n = 1; n < GF2_DIM; n++) { odd[n] = row; row <<= 1; } // put operator for two zero bits in even gf2MatrixSquare(even, odd); // put operator for four zero bits in odd gf2MatrixSquare(odd, even); // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) long crc1 = summ1.getValue(); long crc2 = summ2.getValue(); do { // apply zeros operator for this bit of len2 gf2MatrixSquare(even, odd); if ((len2 & 1) == 1) crc1 = gf2MatrixTimes(even, crc1); len2 >>>= 1; // if no more bits set, then done if (len2 == 0) break; // another iteration of the loop with odd and even swapped gf2MatrixSquare(odd, even); if ((len2 & 1) == 1) crc1 = gf2MatrixTimes(odd, crc1); len2 >>>= 1; // if no more bits set, then done } while (len2 != 0); // return combined crc. crc1 ^= crc2; return new CRC64(crc1); } /* * Return the CRC-64 of two sequential blocks, where summ1 is the CRC-64 of * the first block, summ2 is the CRC-64 of the second block, and len2 is the * length of the second block. */ static public long combine(long crc1, long crc2, long len2) { // degenerate case. if (len2 == 0) return crc1; int n; long row; long[] even = new long[GF2_DIM]; // even-power-of-two zeros operator long[] odd = new long[GF2_DIM]; // odd-power-of-two zeros operator // put operator for one zero bit in odd odd[0] = POLY; // CRC-64 polynomial row = 1; for (n = 1; n < GF2_DIM; n++) { odd[n] = row; row <<= 1; } // put operator for two zero bits in even gf2MatrixSquare(even, odd); // put operator for four zero bits in odd gf2MatrixSquare(odd, even); // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) do { // apply zeros operator for this bit of len2 gf2MatrixSquare(even, odd); if ((len2 & 1) == 1) crc1 = gf2MatrixTimes(even, crc1); len2 >>>= 1; // if no more bits set, then done if (len2 == 0) break; // another iteration of the loop with odd and even swapped gf2MatrixSquare(odd, even); if ((len2 & 1) == 1) crc1 = gf2MatrixTimes(odd, crc1); len2 >>>= 1; // if no more bits set, then done } while (len2 != 0); // return combined crc. crc1 ^= crc2; return crc1; } /** * Get 8 byte representation of current CRC64 value. **/ public byte[] getBytes() { byte[] b = new byte[8]; for (int i = 0; i < 8; i++) { b[7 - i] = (byte) (this.value >>> (i * 8)); } return b; } /** * Get long representation of current CRC64 value. **/ @Override public long getValue() { return this.value; } /** * Update CRC64 with new byte block. **/ public void update(byte[] b, int len) { int idx = 0; this.value = ~this.value; while (len > 0) { this.value = table[((int) (this.value ^ b[idx])) & 0xff] ^ (this.value >>> 8); idx++; len--; } this.value = ~this.value; } /** * Update CRC64 with new byte. **/ public void update(byte b) { this.value = ~this.value; this.value = table[((int) (this.value ^ b)) & 0xff] ^ (this.value >>> 8); this.value = ~this.value; } @Override public void update(int b) { update((byte) (b & 0xFF)); } @Override public void update(byte[] b, int off, int len) { for (int i = off; len > 0; len--) { update(b[i++]); } } @Override public void reset() { this.value = 0; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/HttpUtil.java
package com.aliyun.sdk.gateway.oss.internal; import com.aliyun.core.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Map; public class HttpUtil { /** * Encode a URL segment with special chars replaced. */ public static String urlEncode(String value, String encoding) { if (value == null) { return ""; } try { String encoded = URLEncoder.encode(value, encoding); return encoded.replace("+", "%20").replace("*", "%2A").replace("~", "%7E").replace("/", "%2F"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("FailedToEncodeUri", e); } } public static String urlDecode(String value, String encoding) { if (StringUtils.isEmpty(value)) { return value; } try { return URLDecoder.decode(value, encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("FailedToDecodeUrl", e); } } /** * Encode request parameters to URL segment. */ public static String paramToQueryString(Map<String, String> params, String charset) { if (params == null || params.isEmpty()) { return ""; } StringBuilder paramString = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> p : params.entrySet()) { String key = p.getKey(); String value = p.getValue(); if (!first) { paramString.append("&"); } // Urlencode each request parameter paramString.append(urlEncode(key, charset)); if (value != null) { paramString.append("=").append(urlEncode(value, charset)); } first = false; } return paramString.toString(); } private static final String ISO_8859_1_CHARSET = "iso-8859-1"; private static final String UTF8_CHARSET = "utf-8"; // To fix the bug that the header value could not be unicode chars. // Because HTTP headers are encoded in iso-8859-1, // we need to convert the utf-8(java encoding) strings to iso-8859-1 ones. public static void convertHeaderCharsetFromIso88591(Map<String, String> headers) { convertHeaderCharset(headers, ISO_8859_1_CHARSET, UTF8_CHARSET); } // For response, convert from iso-8859-1 to utf-8. public static void convertHeaderCharsetToIso88591(Map<String, String> headers) { convertHeaderCharset(headers, UTF8_CHARSET, ISO_8859_1_CHARSET); } private static void convertHeaderCharset(Map<String, String> headers, String fromCharset, String toCharset) { for (Map.Entry<String, String> header : headers.entrySet()) { if (header.getValue() == null) { continue; } try { header.setValue(new String(header.getValue().getBytes(fromCharset), toCharset)); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Invalid charset name: " + e.getMessage(), e); } } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/OSSConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyun.sdk.gateway.oss.internal; /** * Miscellaneous constants used for oss client service. */ public final class OSSConstants { public static final String DEFAULT_CHARSET_NAME = "utf-8"; public static final String DEFAULT_XML_ENCODING = "utf-8"; public static final String DEFAULT_OBJECT_CONTENT_TYPE = "application/octet-stream"; public static final int KB = 1024; public static final int DEFAULT_BUFFER_SIZE = 8 * KB; public static final int DEFAULT_STREAM_BUFFER_SIZE = 512 * KB; public static final long DEFAULT_FILE_SIZE_LIMIT = 5 * 1024 * 1024 * 1024L; public static final int OBJECT_NAME_MAX_LENGTH = 1024; public static final String PROTOCOL_HTTP = "http://"; public static final String PROTOCOL_HTTPS = "https://"; public static final String PROTOCOL_RTMP = "rtmp://"; /** Represents a null OSS version ID */ public static final String NULL_VERSION_ID = "null"; /** URL encoding for OSS object keys */ public static final String URL_ENCODING = "url"; public static final String BUCKET_NAMING_REGEX = "^[a-z0-9][a-z0-9-_]{1,61}[a-z0-9]$"; }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/OSSEndpointType.java
package com.aliyun.sdk.gateway.oss.internal; public final class OSSEndpointType { public static final String PUBLIC = "public"; public static final String EXTRANET = "extranet"; public static final String INTERNAL = "internal"; public static final String INTRANET = "intranet"; public static final String ACCELERATE = "accelerate"; public static final String ACCELERATE_OVERSEAS = "accelerate-overseas"; public static final String DUAL_STACK = "dualstack"; private OSSEndpointType(){} }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/OSSEndpointUtil.java
package com.aliyun.sdk.gateway.oss.internal; import java.net.URI; import java.net.URISyntaxException; public class OSSEndpointUtil { private static URI internetEndpoint(String protocol, String region) { return toUri(protocol, "oss-" + region + ".aliyuncs.com"); } private static URI internalEndpoint(String protocol, String region) { return toUri(protocol, "oss-" + region + "-internal.aliyuncs.com"); } private static URI ipv6Endpoint(String protocol, String region) { return toUri(protocol, region + "oss.aliyuncs.com"); } private static URI accelerateEndpoint(String protocol, String region, String regionType) { if (OSSEndpointType.ACCELERATE_OVERSEAS.equalsIgnoreCase(regionType) && !region.startsWith("cn-")) { return toUri(protocol, "oss-accelerate-overseas.aliyuncs.com"); } else { return toUri(protocol, "oss-accelerate.aliyuncs.com"); } } private static URI toUri(String protocol, String endpoint) { try { return new URI(String.format("%s://%s", protocol, endpoint)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/OSSHeaders.java
package com.aliyun.sdk.gateway.oss.internal; public interface OSSHeaders { static final String OSS_PREFIX = "x-oss-"; static final String REQUEST_ID = "x-oss-request-id"; static final String SERVER_TIME = "x-oss-server-time"; static final String HASH_CRC64_ECMA = "x-oss-hash-crc64ecma"; static final String SECURITY_TOKEN = "x-oss-security-token"; static final String STORAGE_CLASS = "x-oss-storage-class"; static final String CANNED_ACL = "x-oss-acl"; static final String TAGGING = "x-oss-tagging"; static final String USER_METADATA_PREFIX = "x-oss-meta-"; static final String OBJECT_TYPE = "x-oss-object-type"; static final String OBJECT_ACL = "x-oss-object-acl"; static final String VERSION_ID = "x-oss-version-id"; static final String CALLBACK = "x-oss-callback"; static final String CALLBACK_VAR = "x-oss-callback-var"; static final String SERVER_SIDE_ENCRYPTION = "x-oss-server-side-encryption"; static final String SERVER_SIDE_ENCRYPTION_KEY_ID = "x-oss-server-side-encryption-key-id"; static final String SERVER_SIDE_DATA_ENCRYPTION = "x-oss-server-side-data-encryption"; static final String COPY_OBJECT_SOURCE = "x-oss-copy-source"; static final String COPY_SOURCE_RANGE = "x-oss-copy-source-range"; static final String COPY_OBJECT_SOURCE_IF_MATCH = "x-oss-copy-source-if-match"; static final String COPY_OBJECT_SOURCE_IF_NONE_MATCH = "x-oss-copy-source-if-none-match"; static final String COPY_OBJECT_SOURCE_IF_UNMODIFIED_SINCE = "x-oss-copy-source-if-unmodified-since"; static final String COPY_OBJECT_SOURCE_IF_MODIFIED_SINCE = "x-oss-copy-source-if-modified-since"; static final String COPY_OBJECT_METADATA_DIRECTIVE = "x-oss-metadata-directive"; static final String COPY_OBJECT_TAGGING_DIRECTIVE = "x-oss-tagging-directive"; static final String NEXT_APPEND_POSITION = "x-oss-next-append-position"; static final String SYMLINK_TARGET = "x-oss-symlink-target"; static final String RESTORE = "x-oss-restore"; static final String ONGOING_RESTORE = "ongoing-request=\"true\""; static final String SELECT_PREFIX = "x-oss-select"; static final String SELECT_CSV_ROWS = "x-oss-select-csv-rows"; static final String SELECT_OUTPUT_RAW = "x-oss-select-output-raw"; static final String SELECT_CSV_SPLITS = "x-oss-select-csv-splits"; static final String SELECT_INPUT_LINE_RANGE = "x-oss-select-line-range"; static final String SELECT_INPUT_SPLIT_RANGE = "x-oss-select-split-range"; static final String REQUEST_PAYER = "x-oss-request-payer"; static final String TRAFFIC_LIMIT = "x-oss-traffic-limit"; static final String WORM_ID = "x-oss-worm-id"; static final String PROCESS = "x-oss-process"; }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/ResourceManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyun.sdk.gateway.oss.internal; import java.text.MessageFormat; import java.util.Locale; import java.util.ResourceBundle; /** * Manager class to get localized resources. */ public class ResourceManager { private ResourceBundle bundle; ResourceManager(String baseName, Locale locale) { this.bundle = ResourceBundle.getBundle(baseName, locale); } public static ResourceManager getInstance(String baseName) { return new ResourceManager(baseName, Locale.getDefault()); } public static ResourceManager getInstance(String baseName, Locale locale) { return new ResourceManager(baseName, locale); } public String getString(String key) { return bundle.getString(key); } public String getFormattedString(String key, Object... args) { return MessageFormat.format(getString(key), args); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/async/CheckedAsyncResponseHandler.java
package com.aliyun.sdk.gateway.oss.internal.async; import darabonba.core.TeaResponseHandler; import darabonba.core.async.AsyncResponseHandler; import org.reactivestreams.Processor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.nio.ByteBuffer; import java.util.zip.Checksum; public class CheckedAsyncResponseHandler implements AsyncResponseHandler<Object, Object> { protected volatile AsyncResponseHandler<?, ?> handler; private Checksum cksum; public CheckedAsyncResponseHandler(TeaResponseHandler handler, Checksum cksum) { this.handler = (AsyncResponseHandler<?, ?>) handler; this.cksum = cksum; } @Override public void onStream(Publisher<ByteBuffer> publisher) { this.cksum.reset(); CheckSumProcessor proc = new CheckSumProcessor(cksum); this.handler.onStream(proc); publisher.subscribe(proc); } @Override public void onError(Throwable throwable) { if (this.handler != null) { this.handler.onError(throwable); } } @Override public Object transform(Object response) { return null; } public Checksum getChecksum() { return cksum; } static class CheckSumProcessor implements Processor<ByteBuffer, ByteBuffer> { protected volatile Subscriber<? super ByteBuffer> subscriber; protected Checksum cksum; CheckSumProcessor(Checksum cksum) { this.cksum = cksum; } @Override public void subscribe(final Subscriber<? super ByteBuffer> subscriber) { this.subscriber = subscriber; } @Override public void onSubscribe(Subscription subscription) { this.cksum.reset(); this.subscriber.onSubscribe(subscription); } @Override public void onNext(ByteBuffer byteBuffer) { if (byteBuffer.hasRemaining()) { cksum.update(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining()); } this.subscriber.onNext(byteBuffer); } @Override public void onError(Throwable throwable) { this.subscriber.onError(throwable); } @Override public void onComplete() { this.subscriber.onComplete(); } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/async/StoredSeparatelyHttpResponseHandler.java
package com.aliyun.sdk.gateway.oss.internal.async; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpResponseHandler; import darabonba.core.ResponseBytes; import darabonba.core.async.AsyncResponseHandler; import org.reactivestreams.Publisher; import java.nio.ByteBuffer; /* if the http status code >= 300, the result is save into AsyncResponseHandler.toBytes() otherwise the result is saved into the response handler provided by user. */ public class StoredSeparatelyHttpResponseHandler implements HttpResponseHandler { protected volatile AsyncResponseHandler<?, ?> asyncResponseHandler; protected volatile HttpResponseHandler httpResponseHandler; protected volatile AsyncResponseHandler<String, ResponseBytes<String>> errorAsyncResponseHandler; public StoredSeparatelyHttpResponseHandler(AsyncResponseHandler<?, ?> asyncResponseHandler) { this.asyncResponseHandler = asyncResponseHandler; this.httpResponseHandler = null; } public StoredSeparatelyHttpResponseHandler(HttpResponseHandler httpResponseHandler) { this.asyncResponseHandler = null; this.httpResponseHandler = httpResponseHandler; } @Override public void onStream(Publisher<ByteBuffer> publisher, int httpStatusCode, HttpHeaders headers) { if (httpStatusCode / 100 != 2) { errorAsyncResponseHandler = AsyncResponseHandler.toBytes(); errorAsyncResponseHandler.onStream(publisher); } else { if (asyncResponseHandler != null) { asyncResponseHandler.onStream(publisher); } else if (httpResponseHandler != null) { httpResponseHandler.onStream(publisher, httpStatusCode, headers); } } } @Override public void onError(Throwable throwable) { if (asyncResponseHandler != null) { asyncResponseHandler.onError(throwable); } else if (httpResponseHandler != null) { httpResponseHandler.onError(throwable); } } public byte[] getErrorBodyByteArrayUnsafe() { if (errorAsyncResponseHandler == null) { return null; } ResponseBytes<String> result = errorAsyncResponseHandler.transform(""); return result.asByteArrayUnsafe(); } public byte[] getErrorBodyByteArray() { if (errorAsyncResponseHandler == null) { return null; } ResponseBytes<String> result = errorAsyncResponseHandler.transform(""); return result.asByteArray(); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/AddCommonHeadersInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.Header; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.util.Mimetypes; import darabonba.core.TeaRequest; import darabonba.core.TeaRequestBody; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import java.util.Arrays; import java.util.List; public class AddCommonHeadersInterceptor implements RequestInterceptor { public static final List<String> DETECTED_BY_OBJECT_NAME_ACTIONS = Arrays.asList( "PutObject", "AppendObject", "CopyObject", "InitiateMultipartUpload" ); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); addContentMD5IfNeeded(request, attributes); addContentTypeIfNeeded(request, attributes); addUserAgentIfNeeded(request, context); return request; } //Content-MD5 private static void addContentMD5IfNeeded(TeaRequest request, AttributeMap attributes) { Header header = request.headers().get("Content-MD5"); if (header == null && attributes.containsKey(AttributeKey.OSS_XML_BODY_CONTENT_MD5)) { String MD5 = attributes.get(AttributeKey.OSS_XML_BODY_CONTENT_MD5); request.headers().set("Content-MD5", MD5); } } //Content-Type private static void addContentTypeIfNeeded(TeaRequest request, AttributeMap attributes) { final String MIMETYPE_DEFAULT = "application/octet-stream"; Header header = request.headers().get("Content-Type"); if (header == null) { String contentType; TeaRequestBody requestBody = attributes.get(AttributeKey.REQUEST_BODY); if (requestBody.contentType().isPresent()) { contentType = requestBody.contentType().get(); } else if (!DETECTED_BY_OBJECT_NAME_ACTIONS.contains(request.action())) { contentType = MIMETYPE_DEFAULT; } else { contentType = Mimetypes.getInstance().getMimetype(request.pathname()); } request.headers().set("Content-Type", contentType); } } //User-Agent private static void addUserAgentIfNeeded(TeaRequest request, InterceptorContext context) { Header header = request.headers().get("User-Agent"); if (header == null) { String ua = context.configuration().clientConfiguration().option(ClientOption.USER_AGENT); request.headers().set("User-Agent", ua); } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/AddContentMd5HeaderInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.Header; import com.aliyun.core.utils.AttributeMap; import darabonba.core.TeaRequest; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; public class AddContentMd5HeaderInterceptor implements RequestInterceptor { @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); Header header = request.headers().get("Content-MD5"); if (header == null && attributes.containsKey(AttributeKey.OSS_XML_BODY_CONTENT_MD5)) { String MD5 = attributes.get(AttributeKey.OSS_XML_BODY_CONTENT_MD5); request.headers().set("Content-MD5", MD5); } return request; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/AddContentTypeHeaderInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.Header; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.util.Mimetypes; import darabonba.core.TeaRequest; import darabonba.core.TeaRequestBody; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import java.util.Arrays; import java.util.List; public class AddContentTypeHeaderInterceptor implements RequestInterceptor { private static final String MIMETYPE_DEFAULT = "application/octet-stream"; private static final List<String> ALLOW_ACTIONS = Arrays.asList( "PutObject", "AppendObject", "CopyObject", "InitiateMultipartUpload" ); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); Header header = request.headers().get("Content-Type"); if (header == null) { TeaRequestBody requestBody = attributes.get(AttributeKey.REQUEST_BODY); if (requestBody.contentType().isPresent()) { request.headers().set("Content-Type", requestBody.contentType().get()); } else { request.headers().set("Content-Type", lookupMimeType(request)); } } return request; } private String lookupMimeType(TeaRequest request) { if (!ALLOW_ACTIONS.contains(request.action())) { return MIMETYPE_DEFAULT; } return Mimetypes.getInstance().getMimetype(request.pathname()); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/AddMetricInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import darabonba.core.interceptor.HttpRequestInterceptor; public class AddMetricInterceptor implements HttpRequestInterceptor { }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/AdjustClockSkew.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.DateUtil; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.oss.exception.OSSServerException; import darabonba.core.TeaResponse; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import java.util.Date; public class AdjustClockSkew implements ResponseInterceptor { @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); if (!response.success() && response.httpResponse().getStatusCode() == 403 && response.exception() instanceof OSSServerException) { OSSServerException exception = (OSSServerException) response.exception(); if ("RequestTimeTooSkewed".equals(exception.errorDetails().errorCode())) { try { Date requestTime = DateUtil.parseIso8601Date(exception.errorDetails().getErrorField("RequestTime")); Date serverTime = DateUtil.parseIso8601Date(exception.errorDetails().getErrorField("ServerTime")); Long timeOffset = serverTime.getTime() - requestTime.getTime(); context.configuration().clientConfiguration().setOption(ClientOption.CLOCK_SKEW_DIFF, timeOffset); } catch (Exception e) { } } } return response; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/AttributeKey.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.HttpResponseHandler; import com.aliyun.core.utils.AttributeMap; import darabonba.core.TeaRequestBody; import darabonba.core.async.AsyncResponseHandler; import java.time.Duration; import java.time.Instant; import java.util.List; public final class AttributeKey<T> extends AttributeMap.Key<T> { public static final AttributeKey<List<String>> EXTRA_SUBRESOURCE = new AttributeKey<>(new UnsafeValueType(List.class)); public static final AttributeKey<TeaRequestBody> REQUEST_BODY = new AttributeKey<>(TeaRequestBody.class); public static final AttributeKey<Long> REQUEST_BODY_LENGTH = new AttributeKey<>(Long.class); public static final AttributeKey<Boolean> ENABLE_CHECKSUM_CRC64 = new AttributeKey<>(Boolean.class); public static final AttributeKey<AsyncResponseHandler> OSS_ASYNC_RESPONSE_HANDLER = new AttributeKey<>(AsyncResponseHandler.class); public static final AttributeKey<HttpResponseHandler> OSS_HTTP_RESPONSE_HANDLER = new AttributeKey<>(HttpResponseHandler.class); public static final AttributeKey<String> OSS_XML_BODY_CONTENT_MD5 = new AttributeKey<>(String.class); public static final AttributeKey<Duration> OSS_SIGNATURE_DURATION = new AttributeKey<>(Duration.class); public static final AttributeKey<Instant> OSS_SIGNATURE_EXPIRATION = new AttributeKey<>(Instant.class); public static final AttributeKey<Instant> OSS_SIGNATURE_SIGNED_HEADERS = new AttributeKey<>(Instant.class); protected AttributeKey(Class<T> valueType) { super(valueType); } protected AttributeKey(UnsafeValueType unsafeValueType) { super(unsafeValueType); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/ChecksumValidationInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.Configuration; import com.aliyun.sdk.gateway.oss.exception.InconsistentException; import com.aliyun.sdk.gateway.oss.internal.CRC64; import com.aliyun.sdk.gateway.oss.internal.OSSHeaders; import com.aliyun.sdk.gateway.oss.internal.async.CheckedAsyncResponseHandler; import darabonba.core.TeaRequest; import darabonba.core.TeaResponse; import darabonba.core.async.AsyncResponseHandler; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.interceptor.ResponseInterceptor; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.zip.CheckedInputStream; public class ChecksumValidationInterceptor implements RequestInterceptor, ResponseInterceptor { private static final List<String> ALLOW_UPLOAD_ACTIONS = Arrays.asList( "PutObject", "UploadPart" ); private static final List<String> ALLOW_DOWNLOAD_ACTIONS = Arrays.asList( "GetObject" ); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); final Configuration config = (Configuration) context.configuration().serviceConfiguration(); if (config.crcEnabled()) { if (ALLOW_UPLOAD_ACTIONS.contains(request.action())) { attributes.put(AttributeKey.ENABLE_CHECKSUM_CRC64, Boolean.TRUE); } else if (ALLOW_DOWNLOAD_ACTIONS.contains(request.action())) { //GetObject needs to add crc handler into AsyncResponseHandler attributes.put(AttributeKey.ENABLE_CHECKSUM_CRC64, Boolean.TRUE); if (context.teaResponseHandler() instanceof AsyncResponseHandler) { attributes.put(AttributeKey.OSS_ASYNC_RESPONSE_HANDLER, new CheckedAsyncResponseHandler(context.teaResponseHandler(), new CRC64())); } } } return request; } @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); TeaRequest request = context.teaRequest(); if (!response.success() || response.exception() != null) { return response; } boolean enableCRC64 = Boolean.TRUE.equals(attributes.get(AttributeKey.ENABLE_CHECKSUM_CRC64)); if (enableCRC64) { Long clientCRC = null; String strServerCRC = response.httpResponse().getHeaders().getValue(OSSHeaders.HASH_CRC64_ECMA); if (ALLOW_UPLOAD_ACTIONS.contains(request.action())) { if (context.httpRequest().getStreamBody() instanceof CheckedInputStream) { CheckedInputStream is = (CheckedInputStream) context.httpRequest().getStreamBody(); clientCRC = is.getChecksum().getValue(); } } else if (ALLOW_DOWNLOAD_ACTIONS.contains(request.action())) { if (attributes.get(AttributeKey.OSS_ASYNC_RESPONSE_HANDLER) instanceof CheckedAsyncResponseHandler) { CheckedAsyncResponseHandler handler = (CheckedAsyncResponseHandler) attributes.get(AttributeKey.OSS_ASYNC_RESPONSE_HANDLER); clientCRC = handler.getChecksum().getValue(); } } if (clientCRC != null && strServerCRC != null && !bypassCRCCheck(request)) { BigInteger bi = new BigInteger(strServerCRC); Long serverCRC = bi.longValue(); if (!clientCRC.equals(serverCRC)) { String requestId = response.httpResponse().getHeaders().getValue(OSSHeaders.REQUEST_ID); response.setException(new InconsistentException(clientCRC, serverCRC, requestId)); } } } return response; } private boolean bypassCRCCheck(TeaRequest request) { String value = request.headers().getValue("Range"); if (value != null) { return true; } return false; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/FinalizedOutputInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.models.Response; import com.aliyun.sdk.gateway.oss.models.ResponseMetadata; import darabonba.core.TeaModel; import darabonba.core.TeaPair; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.OutputInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class FinalizedOutputInterceptor implements OutputInterceptor { @Override public TeaModel modifyOutput(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); Map<String, String> headers = response.httpResponse().getHeaders().toCaseInsensitiveMap(); Map<String, Object> model = CommonUtil.buildMap( new TeaPair("body", response.deserializedBody()), new TeaPair("headers", headers)); TeaModel.adjustToModel(model, context.output()); updateResponseMembersIfNeed(context, headers); return context.output(); } private void updateResponseMembersIfNeed(InterceptorContext context, Map<String, String> headers) { if (context.output() instanceof Response) { Response res = (Response)context.output(); context.setOutput(res.toBuilder() .responseMetadata(new ResponseMetadata(headers)) .httpStatusCode(context.teaResponse().httpResponse().getStatusCode()) .build()); } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/GenerateUrlInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.oss.Configuration; import com.aliyun.sdk.gateway.oss.internal.HttpUtil; import com.aliyun.sdk.gateway.oss.internal.OSSConstants; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import java.net.URI; import java.net.URL; import java.util.Optional; public class GenerateUrlInterceptor implements HttpRequestInterceptor { @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { final ClientConfiguration configuration = context.configuration().clientConfiguration(); final Configuration ossConfiguration = (Configuration)configuration.option(ClientOption.SERVICE_CONFIGURATION); final TeaRequest request = context.teaRequest(); HttpRequest httpRequest = context.httpRequest(); final URI endpointURI = configuration.option(ClientOption.ENDPOINT_URI); //scheme String scheme = endpointURI.getScheme(); //port int port = endpointURI.getPort(); //bucket name String bucket = Optional.ofNullable(request.hostMap().get("bucket")).orElse(""); //host & path String host = endpointURI.getHost(); String path = request.pathname(); if (!StringUtils.isEmpty(bucket)) { if (ossConfiguration.cnameEnabled()) { path = path.substring(bucket.length() + 1); } else if (ossConfiguration.pathStyleEnabled()){ } else { // dns domain, bucket.endpoint path = path.substring(bucket.length() + 1); host = String.format("%s.%s", bucket, host); } } if (port != -1) { host = host + ":" + port; } //query String queryString = HttpUtil.paramToQueryString(request.query(), OSSConstants.DEFAULT_CHARSET_NAME); StringBuilder uri = new StringBuilder(); uri.append(String.format("%s://", scheme)); uri.append(host); uri.append(HttpUtil.urlEncode(path, OSSConstants.DEFAULT_CHARSET_NAME).replace("%2F", "/")); uri.append(queryString.isEmpty()? "": ("?" + queryString)); //update url URL url = null; try { url = new URL(uri.toString()); } catch (Exception e){ url = httpRequest.getUrl(); } httpRequest.setUrl(url); return httpRequest; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/MakeMutableHttpRequestInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.http.HttpResponseHandler; import com.aliyun.core.io.BoundedInputStream; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.internal.CRC64; import com.aliyun.sdk.gateway.oss.internal.async.StoredSeparatelyHttpResponseHandler; import darabonba.core.TeaRequestBody; import darabonba.core.async.AsyncRequestBody; import darabonba.core.async.AsyncResponseHandler; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.sync.RequestBody; import java.io.InputStream; import java.util.zip.CheckedInputStream; import static darabonba.core.internal.AttributeKey.HTTP_RESPONSE_HANDLER; public class MakeMutableHttpRequestInterceptor implements HttpRequestInterceptor { @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { HttpRequest httpRequest = new HttpRequest(context.teaRequest().method(), "http://default"); httpRequest.getHeaders().putAll(context.teaRequest().headers()); TeaRequestBody body = attributes.get(AttributeKey.REQUEST_BODY); Long bodyLen = attributes.get(AttributeKey.REQUEST_BODY_LENGTH); boolean enableCRC64 = Boolean.TRUE.equals(attributes.get(AttributeKey.ENABLE_CHECKSUM_CRC64)); if (body instanceof RequestBody) { RequestBody rBody = (RequestBody) body; InputStream stream = rBody.newStream(); if (bodyLen != null) { stream = new BoundedInputStream(stream, bodyLen.longValue()); } if (enableCRC64) { stream = new CheckedInputStream(stream, new CRC64()); } httpRequest.setStreamBody(stream); } else if (body instanceof AsyncRequestBody) { } if (context.teaResponseHandler() instanceof AsyncResponseHandler) { attributes.put(HTTP_RESPONSE_HANDLER, getHttpResponseHandler(context, attributes)); } return httpRequest; } private HttpResponseHandler getHttpResponseHandler(InterceptorContext context, AttributeMap attributes) { if (attributes.containsKey(AttributeKey.OSS_HTTP_RESPONSE_HANDLER)) { return new StoredSeparatelyHttpResponseHandler(attributes.get(AttributeKey.OSS_HTTP_RESPONSE_HANDLER)); } else if (attributes.containsKey(AttributeKey.OSS_ASYNC_RESPONSE_HANDLER)) { return new StoredSeparatelyHttpResponseHandler(attributes.get(AttributeKey.OSS_ASYNC_RESPONSE_HANDLER)); } else { return new StoredSeparatelyHttpResponseHandler((AsyncResponseHandler) context.teaResponseHandler()); } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/MakeMutableResponseInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.utils.AttributeMap; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; public class MakeMutableResponseInterceptor implements ResponseInterceptor { @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { final HttpResponse httpResponse = context.httpResponse(); TeaResponse response = new TeaResponse(); response.setHttpResponse(httpResponse); response.setSuccess(CommonUtil.is2xx(httpResponse.getStatusCode())); return response; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/PreSigningInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.provider.ICredentialProvider; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import com.aliyun.sdk.gateway.oss.auth.signer.OSSSigner; import com.aliyun.sdk.gateway.oss.auth.signer.OSSSignerParams; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class PreSigningInterceptor implements RequestInterceptor { @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { final ClientConfiguration configuration = context.configuration().clientConfiguration(); TeaRequest request = context.teaRequest(); //Process query in path regex. List<String> extraSubresource = Optional.ofNullable(attributes.get(AttributeKey.EXTRA_SUBRESOURCE)) .orElse(new ArrayList<>()); //sign request OSSSigner signer = (OSSSigner) configuration.option(ClientOption.SIGNER); ICredentialProvider provider = configuration.option(ClientOption.CREDENTIALS_PROVIDER); ICredential cred = provider.getCredentials(); Validate.notNull(cred, "ICredential is null"); if (isAnonymous(cred)) { return request; } //EXPIRATION Instant instant; if (attributes.containsKey(AttributeKey.OSS_SIGNATURE_EXPIRATION)) { instant = attributes.get(AttributeKey.OSS_SIGNATURE_EXPIRATION); } else { instant = Instant.now().plusMillis(attributes.get(AttributeKey.OSS_SIGNATURE_DURATION).toMillis()); attributes.put(AttributeKey.OSS_SIGNATURE_EXPIRATION, instant); } //add x-oss-security-token if (!StringUtils.isEmpty(cred.securityToken())) { request.query().put("security-token", cred.securityToken()); } OSSSignerParams params = OSSSignerParams.create(); params.setSubResources(extraSubresource); params.setCredentials(cred); params.setSignatureExpiration(instant); return signer.presign(request, params); } private boolean isAnonymous(ICredential cred) { if (cred == null || StringUtils.isEmpty(cred.accessKeyId()) || StringUtils.isEmpty(cred.accessKeySecret())) { return true; } return false; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/ProcPathRegexInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.internal.OSSConstants; import darabonba.core.TeaRequest; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; public class ProcPathRegexInterceptor implements RequestInterceptor { private static final List<String> NON_SUBRESOUCES = Arrays.asList(new String[] { "list-type", "regions", }); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); //query Map<String, String> query = extractQueryFromPathRegex(request.pathRegex()); //save subresource into attributes first List<String> subResource = new ArrayList<>(query.keySet()); subResource.removeIf(key -> NON_SUBRESOUCES.contains(key)); attributes.put(AttributeKey.EXTRA_SUBRESOURCE, subResource); query.putAll(request.query()); request.setQuery(query); //append bucket name in the front of pathName String pathName = extractPathName(request.pathname(), request.pathRegex()); if (request.hostMap().containsKey("bucket")) { pathName = "/" + request.hostMap().get("bucket") + pathName; } request.setPathname(pathName); return request; } private static String extractPathName(String pathName, String pathRegex) { int index = pathRegex.indexOf("?"); if (index != -1) { pathName = pathName.substring(0, pathName.length() - (pathRegex.length() - index)); } //darabonab encodes the path by default try { pathName = URLDecoder.decode(pathName, OSSConstants.DEFAULT_CHARSET_NAME); } catch (UnsupportedEncodingException e) { } return pathName; } private static Map<String, String> extractQueryFromPathRegex(String pathRegex) { Map<String, String> query = new HashMap<>(); int index = pathRegex.indexOf("?"); if (index != -1) { String queryStr = pathRegex.substring(index + 1); String[] params = queryStr.split("&"); for (int i = 0; i < params.length; i++) { String[] p = params[i].split("="); if (p.length == 2) { query.put(p[0], p[1]); } else { query.put(p[0], null); } } } return query; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/ProcResponseBodyInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.BodyType; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.http.HttpResponseHandler; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.BaseUtils; import com.aliyun.core.utils.XmlUtil; import com.aliyun.sdk.gateway.oss.exception.OSSClientException; import com.aliyun.sdk.gateway.oss.exception.OSSErrorDetails; import com.aliyun.sdk.gateway.oss.exception.OSSServerException; import com.aliyun.sdk.gateway.oss.internal.OSSHeaders; import com.aliyun.sdk.gateway.oss.internal.async.StoredSeparatelyHttpResponseHandler; import darabonba.core.ResponseBytes; import darabonba.core.TeaRequest; import darabonba.core.TeaResponse; import darabonba.core.async.AsyncResponseHandler; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; import org.dom4j.DocumentException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.*; import static darabonba.core.internal.AttributeKey.HTTP_RESPONSE_HANDLER; public class ProcResponseBodyInterceptor implements ResponseInterceptor { private static final List<String> HEAD_OBJECT_ACTIONS = Arrays.asList( "HeadObject", "GetObjectMeta" ); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); if (response.success()) { response = procSuccessResponse(context, attributes); } else { if (hasNotResponseBody(context)) { response = procFailResponseWithoutBody(context, attributes); } else { response = procFailResponse(context, attributes); } } return response; } private Object toDeserializedBodyForNoneType(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); Class<?> type = null; try { type = context.output().getClass().getDeclaredField("body").getType(); } catch (Throwable e) { } if (type == String.class) { return response.httpResponse().getBodyAsString(); } else if (type == InputStream.class) { return new ByteArrayInputStream(response.httpResponse().getBodyAsByteArray()); } return response.httpResponse().getBodyAsByteArray(); } private TeaResponse procSuccessResponse(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); TeaResponse response = context.teaResponse(); if (skipDeserializeBody(context)) { //TODO don't parse body return response; } Exception exception = null; String bodyStr = ""; try { switch (request.bodyType()) { case BodyType.XML: bodyStr = response.httpResponse().getBodyAsString(); response.setDeserializedBody(deserializeXMLBody(bodyStr)); break; case BodyType.BIN: response.setDeserializedBody(new ByteArrayInputStream(response.httpResponse().getBodyAsByteArray())); break; case BodyType.NONE: response.setDeserializedBody(toDeserializedBodyForNoneType(context, attributes)); break; default: bodyStr = response.httpResponse().getBodyAsString(); response.setDeserializedBody(bodyStr); break; } } catch (Exception e) { exception = new OSSClientException("Parsing response body fail, the partial text is " + partialString(bodyStr), e); } response.setException(exception); return response; } private TeaResponse procFailResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); Exception exception = null; String bodyStr = ""; String requestId = null; try { requestId = response.httpResponse().getHeaders().getValue(OSSHeaders.REQUEST_ID); bodyStr = readResponseErrorBody(response, attributes); Map<String, Object> body = deserializeXMLBody(bodyStr); OSSErrorDetails errorDetail; if (body.containsKey("Error")) { errorDetail = new OSSErrorDetails((HashMap) body.get("Error"), bodyStr); } else { errorDetail = buildFakeErrorDetails("InvalidResponseFormat", requestId, bodyStr); } exception = new OSSServerException(response.httpResponse().getStatusCode(), errorDetail); } catch (Exception e) { exception = new OSSServerException(response.httpResponse().getStatusCode(), buildFakeErrorDetails("InvalidResponseFormat", requestId, bodyStr)); } response.setException(exception); return response; } private TeaResponse procFailResponseWithoutBody(InterceptorContext context, AttributeMap attributes) { String action = context.teaRequest().action(); TeaResponse response = context.teaResponse(); String requestId = response.httpResponse().getHeaders().getValue(OSSHeaders.REQUEST_ID); int code = response.httpResponse().getStatusCode(); String strCode; if (HEAD_OBJECT_ACTIONS.contains(action) && code == 404) { //change 404 to NoSuchKey strCode = "NoSuchKey"; } else { strCode = "Server:" + code; } HashMap map = new HashMap(); map.put("Code", strCode); map.put("Message", ""); map.put("RequestId", Optional.ofNullable(requestId).orElse("")); Exception exception = new OSSServerException(response.httpResponse().getStatusCode(), new OSSErrorDetails(map, "")); response.setException(exception); return response; } private boolean hasNotResponseBody(InterceptorContext context) { return (context.teaRequest().method() == HttpMethod.HEAD); } private String readResponseErrorBody(TeaResponse response, AttributeMap attributes) { if (attributes.containsKey(darabonba.core.internal.AttributeKey.HTTP_RESPONSE_HANDLER)) { HttpResponseHandler handler = attributes.get(darabonba.core.internal.AttributeKey.HTTP_RESPONSE_HANDLER); return BaseUtils.bomAwareToString(((StoredSeparatelyHttpResponseHandler) handler).getErrorBodyByteArrayUnsafe(), null); } return response.httpResponse().getBodyAsString(); } private boolean skipDeserializeBody(InterceptorContext context) { return (context.teaResponseHandler() != null); } private Map<String, Object> deserializeXMLBody(String data) throws DocumentException { Object body = XmlUtil.deserializeXml(data); return CommonUtil.assertAsMap(Optional.ofNullable(body).orElse(new HashMap<>())); } private String partialString(String value) { int len = value.length() > 128 ? 128 : value.length(); return value.substring(0, len); } private OSSErrorDetails buildFakeErrorDetails(String code, String requestId, String body) { if (body == null) { body = ""; } HashMap map = new HashMap(); String msg = "The response body is not well formed, the partial text is " + partialString(body); map.put("Code", code); map.put("Message", msg); map.put("RequestId", requestId); return new OSSErrorDetails(map, body); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/SelectObjectInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpResponseHandler; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.Base64Util; import com.aliyun.sdk.gateway.oss.exception.OSSClientException; import com.aliyun.sdk.gateway.oss.exception.OSSErrorDetails; import com.aliyun.sdk.gateway.oss.exception.OSSServerException; import com.aliyun.sdk.gateway.oss.internal.OSSHeaders; import darabonba.core.TeaRequest; import darabonba.core.TeaResponse; import darabonba.core.TeaResponseHandler; import darabonba.core.async.AsyncResponseHandler; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.interceptor.ResponseInterceptor; import org.reactivestreams.Processor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.zip.CRC32; public class SelectObjectInterceptor implements RequestInterceptor, ResponseInterceptor { private static final List<String> REQUEST_ALLOW_ACTIONS = Arrays.asList( "SelectObject", "CreateSelectObjectMeta" ); private static final AttributeKey<Boolean> SELECT_OBJECT_MEET_JSON = new AttributeKey<>(Boolean.class); private static final AttributeKey<Boolean> SELECT_OBJECT_HAS_ACTION = new AttributeKey<>(Boolean.class); public static final AttributeKey<HttpResponseHandler> SELECT_OBJECT_HTTP_RESPONSE_HANDLER = new AttributeKey<>(HttpResponseHandler.class); private static Object base64EncodeInputSerialization(HashMap root, AttributeMap attributes) { HashMap node = (HashMap) root.get("InputSerialization"); if (node != null) { HashMap csv = (HashMap) node.get("CSV"); HashMap json = (HashMap) node.get("JSON"); if (csv != null) { base64EncodeIfPresent(csv, "RecordDelimiter"); base64EncodeIfPresent(csv, "FieldDelimiter"); base64EncodeIfPresent(csv, "QuoteCharacter"); base64EncodeIfPresent(csv, "CommentCharacter"); node.replace("CSV", csv); } if (json != null) { attributes.put(SELECT_OBJECT_MEET_JSON, Boolean.TRUE); } } return node; } private static Object base64EncodeOutputSerialization(HashMap root) { HashMap node = (HashMap) root.get("OutputSerialization"); if (node != null) { HashMap csv = (HashMap) node.get("CSV"); HashMap json = (HashMap) node.get("JSON"); if (csv != null) { base64EncodeIfPresent(csv, "RecordDelimiter"); base64EncodeIfPresent(csv, "FieldDelimiter"); node.replace("CSV", csv); } if (json != null) { base64EncodeIfPresent(json, "RecordDelimiter"); node.replace("JSON", json); } } return node; } private static void base64EncodeIfPresent(HashMap node, String key) { if (node.containsKey(key) && node.get(key) != null) { node.replace(key, Base64Util.encodeToString(((String) node.get(key)).getBytes())); } } @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); String action = request.action(); if (REQUEST_ALLOW_ACTIONS.contains(action)) { // modify body HashMap body = (HashMap) request.body(); if (body.containsKey("SelectRequest")) { HashMap root = (HashMap) body.get("SelectRequest"); base64EncodeIfPresent(root, "Expression"); root.replace("InputSerialization", base64EncodeInputSerialization(root, attributes)); root.replace("OutputSerialization", base64EncodeOutputSerialization(root)); body.replace("SelectRequest", root); } else if (body.containsKey("body")) { HashMap root = (HashMap) body.get("body"); root.replace("InputSerialization", base64EncodeInputSerialization(root, attributes)); String rootKey = attributes.containsKey(SELECT_OBJECT_MEET_JSON) ? "JsonMetaRequest" : "CsvMetaRequest"; body.remove("body"); body.put(rootKey, root); } request.setBody(body); //add x-oss-process parameter String op = attributes.containsKey(SELECT_OBJECT_MEET_JSON) ? "json/" : "csv/"; op = op + (body.containsKey("SelectRequest") ? "select" : "meta"); request.query().put(OSSHeaders.PROCESS, op); // attributes.put(SELECT_OBJECT_HAS_ACTION, Boolean.TRUE); // Add http handler to decode frame if (context.teaResponseHandler() instanceof AsyncResponseHandler) { HttpResponseHandler handler = new DecodeFrameHttpResponseHandler((AsyncResponseHandler<?, ?>) context.teaResponseHandler()); attributes.put(AttributeKey.OSS_HTTP_RESPONSE_HANDLER, handler); attributes.put(SELECT_OBJECT_HTTP_RESPONSE_HANDLER, handler); } } return request; } private boolean shouldHandleResponse(TeaResponse response, AttributeMap attributes) { if (!response.success() || response.exception() != null) { return false; } return attributes.containsKey(SELECT_OBJECT_HAS_ACTION); } private static boolean hasSelectOutputRaw(HttpHeaders httpHeaders) { if (httpHeaders != null) { String value = httpHeaders.getValue(OSSHeaders.SELECT_OUTPUT_RAW); if ("true".equals(value)) { return true; } } return false; } private OSSClientException buildClientException(String msg) { return new OSSClientException(msg, null); } private OSSErrorDetails buildErrorDetails(String error, String requestId, int httpStatusCode) { HashMap map = new HashMap(); int index = error.indexOf("."); if (index != -1) { map.put("Code", error.substring(0, index)); map.put("Message", error.substring(index + 1)); } else { map.put("Code", ""); map.put("Message", error); } map.put("RequestId", requestId); map.put("HttpStatusCode", httpStatusCode + ""); return new OSSErrorDetails(map, ""); } private OSSServerException buildServerException(TeaResponse response, EndFrame frame) { String requestId = Optional.ofNullable(response.httpResponse().getHeaders().getValue(OSSHeaders.REQUEST_ID)).orElse(""); return new OSSServerException(response.httpResponse().getStatusCode(), buildErrorDetails(frame.getErrorMessage(), requestId, frame.httpStatusCode)); } private Exception changeDecodeFrameStatusToExceptionIfNeed(TeaResponse response, DecodeFrameStatus status) { Exception exception = null; if (status != null) { //check parsing status first if (status.getParsingError() != null) { //build client error exception = buildClientException(status.getParsingError()); } else { // check endFrame http status code EndFrame endFrame = status.getEndFrame(); if (endFrame != null) { int httpStatusCode = endFrame.httpStatusCode; if (httpStatusCode / 100 != 2) { exception = buildServerException(response, endFrame); } } } } return exception; } private TeaResponse modifySelectObjectResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); Exception exception = null; if (context.teaResponseHandler() instanceof AsyncResponseHandler) { DecodeFrameHttpResponseHandler handler = (DecodeFrameHttpResponseHandler) attributes.get(SELECT_OBJECT_HTTP_RESPONSE_HANDLER); DecodeFrameStatus status = handler.getDecodeFrameStatus(); exception = changeDecodeFrameStatusToExceptionIfNeed(response, status); } else if (response.deserializedBody() != null && !hasSelectOutputRaw(response.httpResponse().getHeaders())) { Object body = response.deserializedBody(); if (body instanceof InputStream) { response.setDeserializedBody(new SelectInputStream((InputStream) body)); } } response.setException(exception); return response; } private TeaResponse modifyCreateSelectObjectMetaResponse(TeaResponse response) { Exception exception = null; if (response.deserializedBody() instanceof byte[]) { CreateSelectMetaParser parser = new CreateSelectMetaParser(); DecodeFrameStatus status = parser.parse((byte[]) response.deserializedBody()); response.setDeserializedBody(parser.toEndFrameMap()); exception = changeDecodeFrameStatusToExceptionIfNeed(response, status); } response.setException(exception); return response; } @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); if (shouldHandleResponse(response, attributes)) { switch (context.teaRequest().action()) { case "SelectObject": response = modifySelectObjectResponse(context, attributes); break; case "CreateSelectObjectMeta": response = modifyCreateSelectObjectMetaResponse(response); break; default: break; } } return response; } private class SelectInputStream extends FilterInputStream { /** * Format of data frame * |--frame type(4 bytes)--|--payload length(4 bytes)--|--header checksum(4 bytes)--| * |--scanned data bytes(8 bytes)--|--payload--|--payload checksum(4 bytes)--| */ private static final int DATA_FRAME_MAGIC = 8388609; /** * Format of continuous frame * |--frame type(4 bytes)--|--payload length(4 bytes)--|--header checksum(4 bytes)--| * |--scanned data bytes(8 bytes)--|--payload checksum(4 bytes)--| */ private static final int CONTINUOUS_FRAME_MAGIC = 8388612; /** * Format of end frame * |--frame type(4 bytes)--|--payload length(4 bytes)--|--header checksum(4 bytes)--| * |--scanned data bytes(8 bytes)--|--total scan size(8 bytes)--| * |--status code(4 bytes)--|--error message--|--payload checksum(4 bytes)--| */ private static final int END_FRAME_MAGIC = 8388613; private static final int SELECT_VERSION = 1; private static final long DEFAULT_NOTIFICATION_THRESHOLD = 50 * 1024 * 1024;//notify every scanned 50MB private long currentFrameOffset; private long currentFramePayloadLength; private byte[] currentFrameTypeBytes; private byte[] currentFramePayloadLengthBytes; private byte[] currentFrameHeaderChecksumBytes; private byte[] scannedDataBytes; private byte[] currentFramePayloadChecksumBytes; private boolean finished; private long nextNotificationScannedSize; private boolean payloadCrcEnabled; private CRC32 crc32; private String requestId; /** * payload checksum is the last 4 bytes in one frame, we use this flag to indicate whether we * need read the 4 bytes before we advance to next frame. */ private boolean firstReadFrame; /** * Creates a <code>FilterInputStream</code> * by assigning the argument <code>in</code> * to the field <code>this.in</code> so as * to remember it for later use. * * @param in the underlying input stream, or <code>null</code> if * this instance is to be created without an underlying stream. */ public SelectInputStream(InputStream in) { super(in); currentFrameOffset = 0; currentFramePayloadLength = 0; currentFrameTypeBytes = new byte[4]; currentFramePayloadLengthBytes = new byte[4]; currentFrameHeaderChecksumBytes = new byte[4]; scannedDataBytes = new byte[8]; currentFramePayloadChecksumBytes = new byte[4]; finished = false; firstReadFrame = true; this.nextNotificationScannedSize = DEFAULT_NOTIFICATION_THRESHOLD; this.payloadCrcEnabled = true; if (this.payloadCrcEnabled) { this.crc32 = new CRC32(); this.crc32.reset(); } } private void internalRead(byte[] buf, int off, int len) throws IOException { int bytesRead = 0; while (bytesRead < len) { int bytes = in.read(buf, off + bytesRead, len - bytesRead); if (bytes < 0) { throw new IOException("Invalid input stream end found, need another " + (len - bytesRead) + " bytes"); } bytesRead += bytes; } } private void validateCheckSum(byte[] checksumBytes, CRC32 crc32) throws IOException { if (payloadCrcEnabled) { int currentChecksum = ByteBuffer.wrap(checksumBytes).getInt(); if (currentChecksum != 0 && crc32.getValue() != ((long) currentChecksum & 0xffffffffL)) { throw new IOException("Frame crc check failed, actual " + crc32.getValue() + ", expect: " + currentChecksum); } crc32.reset(); } } private void readFrame() throws IOException { while (currentFrameOffset >= currentFramePayloadLength && !finished) { if (!firstReadFrame) { internalRead(currentFramePayloadChecksumBytes, 0, 4); validateCheckSum(currentFramePayloadChecksumBytes, crc32); } firstReadFrame = false; //advance to next frame internalRead(currentFrameTypeBytes, 0, 4); //first byte is version byte if (currentFrameTypeBytes[0] != SELECT_VERSION) { throw new IOException("Invalid select version found " + currentFrameTypeBytes[0] + ", expect: " + SELECT_VERSION); } internalRead(currentFramePayloadLengthBytes, 0, 4); internalRead(currentFrameHeaderChecksumBytes, 0, 4); internalRead(scannedDataBytes, 0, 8); if (payloadCrcEnabled) { crc32.update(scannedDataBytes, 0, scannedDataBytes.length); } currentFrameTypeBytes[0] = 0; int type = ByteBuffer.wrap(currentFrameTypeBytes).getInt(); switch (type) { case DATA_FRAME_MAGIC: currentFramePayloadLength = ByteBuffer.wrap(currentFramePayloadLengthBytes).getInt() - 8; currentFrameOffset = 0; break; case CONTINUOUS_FRAME_MAGIC: //just break, continue break; case END_FRAME_MAGIC: currentFramePayloadLength = ByteBuffer.wrap(currentFramePayloadLengthBytes).getInt() - 8; byte[] totalScannedDataSizeBytes = new byte[8]; internalRead(totalScannedDataSizeBytes, 0, 8); byte[] statusBytes = new byte[4]; internalRead(statusBytes, 0, 4); if (payloadCrcEnabled) { crc32.update(totalScannedDataSizeBytes, 0, totalScannedDataSizeBytes.length); crc32.update(statusBytes, 0, statusBytes.length); } int status = ByteBuffer.wrap(statusBytes).getInt(); int errorMessageSize = (int) (currentFramePayloadLength - 12); String error = ""; if (errorMessageSize > 0) { byte[] errorMessageBytes = new byte[errorMessageSize]; internalRead(errorMessageBytes, 0, errorMessageSize); error = new String(errorMessageBytes); if (payloadCrcEnabled) { crc32.update(errorMessageBytes, 0, errorMessageBytes.length); } } finished = true; currentFramePayloadLength = currentFrameOffset; internalRead(currentFramePayloadChecksumBytes, 0, 4); validateCheckSum(currentFramePayloadChecksumBytes, crc32); if (status / 100 != 2) { if (error.contains(".")) { throw new IOException(error.substring(error.indexOf(".") + 1)); } else { // forward compatbility consideration throw new IOException(error); } } break; default: throw new IOException("Unsupported frame type " + type + " found"); } long scannedDataSize = ByteBuffer.wrap(scannedDataBytes).getLong(); if (scannedDataSize >= nextNotificationScannedSize || finished) { nextNotificationScannedSize += DEFAULT_NOTIFICATION_THRESHOLD; } } } @Override public int read() throws IOException { readFrame(); int byteRead = in.read(); if (byteRead >= 0) { currentFrameOffset++; if (payloadCrcEnabled) { crc32.update(byteRead); } } return byteRead; } @Override public int read(byte b[]) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] buf, int off, int len) throws IOException { readFrame(); int bytesToRead = (int) Math.min(len, currentFramePayloadLength - currentFrameOffset); if (bytesToRead != 0) { int bytes = in.read(buf, off, bytesToRead); if (bytes > 0) { currentFrameOffset += bytes; if (payloadCrcEnabled) { crc32.update(buf, off, bytes); } } return bytes; } return -1; } @Override public int available() throws IOException { throw new IOException("Select object input stream does not support available() operation"); } } private class EndFrame { protected Long offset; protected Long totalScannedBytes; protected Integer httpStatusCode = 0; protected String errorMessage = ""; public Long getOffset() { return offset; } public void setOffset(Long offset) { this.offset = offset; } public Long getTotalScannedBytes() { return totalScannedBytes; } public void setTotalScannedBytes(Long totalScannedBytes) { this.totalScannedBytes = totalScannedBytes; } public Integer getHttpStatusCode() { return httpStatusCode; } public void setHttpStatusCode(Integer httpStatusCode) { this.httpStatusCode = httpStatusCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } } private class MetaEndFrame extends EndFrame { protected Integer splitsCount; protected Long rowsCount; protected Integer colsCount; public Integer getSplitsCount() { return splitsCount; } public void setSplitsCount(Integer splitsCount) { this.splitsCount = splitsCount; } public Long getRowsCount() { return rowsCount; } public void setRowsCount(Long rowsCount) { this.rowsCount = rowsCount; } public Integer getColsCount() { return colsCount; } public void setColsCount(Integer colsCount) { this.colsCount = colsCount; } } private class DecodeFrameStatus { private String parsingError; private EndFrame endFrame; public String getParsingError() { return parsingError; } public void setParsingError(String parsingError) { this.parsingError = parsingError; } public EndFrame getEndFrame() { return endFrame; } public void setEndFrame(EndFrame endFrame) { this.endFrame = endFrame; } } private class DecodeFrameParser { //Version | Frame - Type | Payload Length | Header Checksum | Payload | Payload Checksum //<1 byte> <--3 bytes--> <-- 4 bytes --> <------4 bytes--> <variable><----4bytes------> //Payload //<offset | data> //<8 types><variable> protected static final int SELECT_VERSION = 1; protected static final int DATA_FRAME_MAGIC = 8388609; protected static final int CONTINUOUS_FRAME_MAGIC = 8388612; protected static final int END_FRAME_MAGIC = 8388613; protected static final int CSV_END_FRAME_MAGIC = 8388614; protected static final int JSON_END_FRAME_MAGIC = 8388615; protected static final int FRAME_HEADER_LEN = 12 + 8; // header + offset protected byte[] headerBuf = new byte[FRAME_HEADER_LEN]; protected byte[] tailBuf = new byte[4]; protected byte[] endFramelBuf; protected int frameType; protected int headerLen; protected int tailLen; protected int payloadRemains; protected int payloadOff; protected int payloadLen; protected CRC32 crc32 = new CRC32(); protected long payloadCRC; protected long calcPayloadCRC; protected String lastErrorMsg; DecodeFrameParser() { } protected void resetState() { headerLen = 0; tailLen = 0; payloadRemains = 0; lastErrorMsg = null; endFramelBuf = null; } protected int splitOneFrame(byte[] b, int off, int len) { int remians = len; int boff = off; // header if (headerLen < FRAME_HEADER_LEN) { int copy = Math.min(FRAME_HEADER_LEN - headerLen, remians); System.arraycopy(b, boff, headerBuf, headerLen, copy); headerLen += copy; boff += copy; remians -= copy; if (headerLen == FRAME_HEADER_LEN) { int value = ByteBuffer.wrap(headerBuf, 4, 4).getInt(); payloadRemains = value - 8; crc32.reset(); crc32.update(headerBuf, 12, 8); //first byte is version byte if (headerBuf[0] != SELECT_VERSION) { lastErrorMsg = "Invalid select version found " + headerBuf[0] + ", expect: " + SELECT_VERSION; return -1; } } } //payload if (payloadRemains > 0) { int copy = Math.min(payloadRemains, remians); frameType = ByteBuffer.wrap(headerBuf, 0, 4).getInt(); frameType &= 0x00FFFFFF; payloadOff = boff; payloadLen = copy; payloadRemains -= copy; boff += copy; remians -= copy; crc32.update(b, payloadOff, copy); return len - remians; } //tail if (tailLen < 4) { int copy = Math.min(4 - tailLen, remians); System.arraycopy(b, boff, tailBuf, tailLen, copy); tailLen += copy; remians -= copy; boff += copy; if (tailLen == 4) { payloadCRC = ((long) ByteBuffer.wrap(tailBuf).getInt()) & 0xffffffffL; calcPayloadCRC = crc32.getValue(); } } return len - remians; } } private class DecodeFrameAsyncResponseHandler implements AsyncResponseHandler<String, DecodeFrameStatus> { protected volatile AsyncResponseHandler<?, ?> handler; protected volatile DecodeFrameProcessor processor; public DecodeFrameAsyncResponseHandler(TeaResponseHandler handler) { this.handler = (AsyncResponseHandler<?, ?>) handler; } @Override public void onStream(Publisher<ByteBuffer> publisher) { DecodeFrameProcessor proc = new DecodeFrameProcessor(); this.processor = proc; this.handler.onStream(proc); publisher.subscribe(proc); } @Override public void onError(Throwable throwable) { if (this.handler != null) { this.handler.onError(throwable); } } @Override public DecodeFrameStatus transform(String response) { return this.processor.getDecodeFrameStatus(); } class DecodeFrameProcessor extends DecodeFrameParser implements Processor<ByteBuffer, ByteBuffer> { protected volatile Subscriber<? super ByteBuffer> subscriber; private Subscription subscription; protected DecodeFrameStatus decodeFrameStatus; @Override protected void resetState() { super.resetState(); decodeFrameStatus = null; } private boolean flushToSubscriber(ByteBuffer byteBuffer) { byte[] b = byteBuffer.array(); int off = byteBuffer.arrayOffset() + byteBuffer.position(); int remians = byteBuffer.remaining(); int ret; while (remians > 0) { frameType = 0; payloadLen = 0; payloadOff = 0; if ((ret = splitOneFrame(b, off, remians)) < 0) { return false; } switch (frameType) { //DATA FRAME case DATA_FRAME_MAGIC: this.subscriber.onNext(ByteBuffer.wrap(b, payloadOff, payloadLen)); break; // Select object End Frame case END_FRAME_MAGIC: endFramelBuf = new byte[payloadLen + 8]; System.arraycopy(headerBuf, 12, endFramelBuf, 0, 8); System.arraycopy(b, payloadOff, endFramelBuf, 8, payloadLen); break; case 0: // get payload checksum if (tailLen == 4) { if (payloadCRC != 0 && payloadCRC != calcPayloadCRC) { lastErrorMsg = "Frame crc check failed, actual " + calcPayloadCRC + ", expect: " + payloadCRC; return false; } //reset to next frame headerLen = 0; tailLen = 0; payloadRemains = 0; } break; default: break; } remians -= ret; off += ret; } return true; } private EndFrame toEndFrame(byte[] data) { if (data == null) { return null; } EndFrame endFrame = new EndFrame(); endFrame.setOffset(ByteBuffer.wrap(data, 0, 8).getLong()); endFrame.setTotalScannedBytes(ByteBuffer.wrap(data, 8, 8).getLong()); endFrame.setHttpStatusCode(ByteBuffer.wrap(data, 16, 4).getInt()); endFrame.setErrorMessage(new String(data, 20, data.length - 20)); return endFrame; } @Override public void subscribe(final Subscriber<? super ByteBuffer> subscriber) { this.subscriber = subscriber; } @Override public void onSubscribe(Subscription subscription) { resetState(); this.subscription = subscription; this.subscriber.onSubscribe(subscription); } @Override public void onNext(ByteBuffer byteBuffer) { if (!flushToSubscriber(byteBuffer)) { //this.subscription.cancel(); } } @Override public void onError(Throwable throwable) { this.subscriber.onError(throwable); } @Override public void onComplete() { this.subscriber.onComplete(); this.decodeFrameStatus = new DecodeFrameStatus(); if (lastErrorMsg != null) { this.decodeFrameStatus.setParsingError(lastErrorMsg); } if (endFramelBuf != null) { this.decodeFrameStatus.setEndFrame(toEndFrame(endFramelBuf)); } } public DecodeFrameStatus getDecodeFrameStatus() { return this.decodeFrameStatus; } } } private class DecodeFrameHttpResponseHandler implements HttpResponseHandler { private AsyncResponseHandler<?, ?> handler; private DecodeFrameAsyncResponseHandler decodeFrameHandler; DecodeFrameHttpResponseHandler(AsyncResponseHandler<?, ?> handler) { this.handler = handler; this.decodeFrameHandler = null; } @Override public void onStream(Publisher<ByteBuffer> publisher, int httpStatusCode, HttpHeaders headers) { if (hasSelectOutputRaw(headers)) { this.handler.onStream(publisher); } else { this.decodeFrameHandler = new DecodeFrameAsyncResponseHandler(this.handler); this.decodeFrameHandler.onStream(publisher); } } @Override public void onError(Throwable throwable) { if (this.decodeFrameHandler != null) { this.decodeFrameHandler.onError(throwable); } else if (this.handler != null) { this.handler.onError(throwable); } } public DecodeFrameStatus getDecodeFrameStatus() { if (this.decodeFrameHandler != null) { return this.decodeFrameHandler.transform(""); } else { return null; } } } private class CreateSelectMetaParser extends DecodeFrameParser { private int metaEndframeType = 0; private MetaEndFrame metaEndFrame; @Override protected void resetState() { super.resetState(); metaEndFrame = null; } private boolean parseInternal(byte[] b) { int off = 0; int remians = b.length; int ret; while (remians > 0) { frameType = 0; payloadLen = 0; payloadOff = 0; if ((ret = splitOneFrame(b, off, remians)) < 0) { return false; } switch (frameType) { case CSV_END_FRAME_MAGIC: case JSON_END_FRAME_MAGIC: metaEndframeType = frameType; endFramelBuf = new byte[payloadLen + 8]; System.arraycopy(headerBuf, 12, endFramelBuf, 0, 8); System.arraycopy(b, payloadOff, endFramelBuf, 8, payloadLen); break; case 0: // get payload checksum if (tailLen == 4) { if (payloadCRC != 0 && payloadCRC != calcPayloadCRC) { lastErrorMsg = "Frame crc check failed, actual " + calcPayloadCRC + ", expect: " + payloadCRC; return false; } //reset to next frame headerLen = 0; tailLen = 0; payloadRemains = 0; } break; default: break; } remians -= ret; off += ret; } return true; } private MetaEndFrame toMetaEndFrame(byte[] data) { if (data == null) { return null; } MetaEndFrame endFrame = new MetaEndFrame(); endFrame.setOffset(ByteBuffer.wrap(data, 0, 8).getLong()); endFrame.setTotalScannedBytes(ByteBuffer.wrap(data, 8, 8).getLong()); endFrame.setHttpStatusCode(ByteBuffer.wrap(data, 16, 4).getInt()); endFrame.setSplitsCount(ByteBuffer.wrap(data, 20, 4).getInt()); endFrame.setRowsCount(ByteBuffer.wrap(data, 24, 8).getLong()); if (metaEndframeType == CSV_END_FRAME_MAGIC) { endFrame.setColsCount(ByteBuffer.wrap(data, 32, 4).getInt()); endFrame.setErrorMessage(new String(data, 36, data.length - 36)); } else { endFrame.setErrorMessage(new String(data, 32, data.length - 32)); } return endFrame; } public DecodeFrameStatus parse(byte[] data) { resetState(); parseInternal(data); DecodeFrameStatus decodeFrameStatus = new DecodeFrameStatus(); if (lastErrorMsg != null) { decodeFrameStatus.setParsingError(lastErrorMsg); } if (endFramelBuf != null) { this.metaEndFrame = toMetaEndFrame(endFramelBuf); decodeFrameStatus.setEndFrame(this.metaEndFrame); } return decodeFrameStatus; } public HashMap toEndFrameMap() { HashMap result = new HashMap(); if (this.metaEndFrame != null) { result.put("Offset", this.metaEndFrame.getOffset()); result.put("TotalScannedBytes", this.metaEndFrame.getTotalScannedBytes()); result.put("Status", this.metaEndFrame.httpStatusCode); result.put("SplitsCount", this.metaEndFrame.splitsCount); result.put("RowsCount", this.metaEndFrame.getRowsCount()); result.put("ColsCount", this.metaEndFrame.getColsCount()); result.put("ErrorMessage", this.metaEndFrame.getErrorMessage()); } return result; } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/SigningInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.provider.ICredentialProvider; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.DateUtil; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import com.aliyun.sdk.gateway.oss.auth.signer.OSSSigner; import com.aliyun.sdk.gateway.oss.auth.signer.OSSSignerParams; import com.aliyun.sdk.gateway.oss.internal.OSSHeaders; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; public class SigningInterceptor implements HttpRequestInterceptor { @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { final ClientConfiguration configuration = context.configuration().clientConfiguration(); TeaRequest request = context.teaRequest(); HttpRequest httpRequest = context.httpRequest(); //Add Date if (httpRequest.getHeaders().getValue("Date") == null) { Date now = new Date(); now.setTime(now.getTime() + configuration.option(ClientOption.CLOCK_SKEW_DIFF)); httpRequest.getHeaders().set("Date", DateUtil.formatRfc822Date(now)); } //Process query in path regex. List<String> extraSubresource = Optional.ofNullable(attributes.get(AttributeKey.EXTRA_SUBRESOURCE)) .orElse(new ArrayList<>()); //sign request OSSSigner signer = (OSSSigner) configuration.option(ClientOption.SIGNER); ICredentialProvider provider = configuration.option(ClientOption.CREDENTIALS_PROVIDER); ICredential cred = provider.getCredentials(); Validate.notNull(cred, "ICredential is null"); if (isAnonymous(cred)) { return httpRequest; } OSSSignerParams params = OSSSignerParams.create(); params.setSubResources(extraSubresource); params.setCredentials(cred); //add x-oss-security-token if (!StringUtils.isEmpty(cred.securityToken())) { httpRequest.getHeaders().set(OSSHeaders.SECURITY_TOKEN, cred.securityToken()); } return signer.sign(request, httpRequest, params); } private boolean isAnonymous(ICredential cred) { if (cred == null || StringUtils.isEmpty(cred.accessKeyId()) || StringUtils.isEmpty(cred.accessKeySecret())) { return true; } return false; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/TransformRequestBodyInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.BodyType; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.BinaryUtils; import com.aliyun.core.utils.XmlUtil; import darabonba.core.TeaRequest; import darabonba.core.TeaRequestBody; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.sync.RequestBody; import darabonba.core.utils.CommonUtil; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; import static com.aliyun.sdk.gateway.oss.internal.interceptor.AddCommonHeadersInterceptor.DETECTED_BY_OBJECT_NAME_ACTIONS; public class TransformRequestBodyInterceptor implements RequestInterceptor { private final static RequestBody EmptyBody = RequestBody.empty(); private static String convertXMLRootName(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); if (request.body() != null) { return fromBody(context, attributes); } else if (context.teaRequestBody() != null) { return fromRequestBody(context, attributes); } else if (request.stream() != null) { return fromStream(context, attributes); } else { //request.headers().set("Content-Type", toContentType(request.reqBodyType())); setContentTypeIfNeeded(request, toContentType(request.reqBodyType())); attributes.put(AttributeKey.REQUEST_BODY, EmptyBody); return request; } } private TeaRequest fromBody(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); String bodyStr = null; switch (request.reqBodyType()) { case BodyType.XML: { Map<String, Object> body = CommonUtil.assertAsMap(request.body()); if (!body.isEmpty()) { String root = body.keySet().iterator().next(); bodyStr = XmlUtil.serializeXml(CommonUtil.assertAsMap(body.get(root)), convertXMLRootName(root)); } calcContentMd5IfNeed(bodyStr, attributes); } break; default: { Map<String, Object> body = CommonUtil.assertAsMap(request.body()); bodyStr = (String) body.get("body"); } break; } if (bodyStr == null) { bodyStr = ""; } attributes.put(AttributeKey.REQUEST_BODY, RequestBody.fromString(bodyStr, StandardCharsets.UTF_8, toContentType(request.reqBodyType()))); //request.headers().set("Content-Type", toContentType(request.reqBodyType())); setContentTypeIfNeeded(request, toContentType(request.reqBodyType())); return request; } private TeaRequest fromStream(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); TeaRequestBody requestBody = RequestBody.fromInputStream(request.stream()); attributes.put(AttributeKey.REQUEST_BODY, Optional.ofNullable(requestBody).orElse(EmptyBody)); return request; } private TeaRequest fromRequestBody(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); TeaRequestBody requestBody = context.teaRequestBody(); if (requestBody.contentLength().isPresent()) { attributes.put(AttributeKey.REQUEST_BODY_LENGTH, requestBody.contentLength().get()); } attributes.put(AttributeKey.REQUEST_BODY, requestBody); return request; } private String toContentType(String type) { switch (type) { case BodyType.XML: return "application/xml"; case BodyType.JSON: return "application/json"; default: return "application/octet-stream"; } } private void calcContentMd5IfNeed(String body, AttributeMap attributes) { if (body == null) { return; } byte[] md5 = BinaryUtils.calculateMd5(body.getBytes(StandardCharsets.UTF_8)); String md5Base64 = BinaryUtils.toBase64(md5); attributes.put(AttributeKey.OSS_XML_BODY_CONTENT_MD5, md5Base64); } private void setContentTypeIfNeeded(TeaRequest request, String contentType) { if (DETECTED_BY_OBJECT_NAME_ACTIONS.contains(request.action())) { return; } request.headers().set("Content-Type", contentType); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/internal/interceptor/UrlDecodeEncodeInterceptor.java
package com.aliyun.sdk.gateway.oss.internal.interceptor; import com.aliyun.core.http.HttpHeader; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.utils.AttributeMap; import com.aliyun.sdk.gateway.oss.internal.HttpUtil; import com.aliyun.sdk.gateway.oss.internal.OSSHeaders; import darabonba.core.TeaRequest; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.interceptor.ResponseInterceptor; import java.util.*; import java.util.stream.Collectors; public class UrlDecodeEncodeInterceptor implements RequestInterceptor, ResponseInterceptor { private static final List<String> REQUEST_ALLOW_ACTIONS = Arrays.asList( "PutSymlink" ); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); final String action = context.teaRequest().action(); if (shouldHandleRequest(request, action)) { switch (action) { case "PutSymlink": request = modifyPutSymlinkRequest(request); break; default: break; }; } return request; } private static String urlEncode(String v) { return HttpUtil.urlEncode(v, "utf-8"); } private boolean shouldHandleRequest(TeaRequest request, String action) { return REQUEST_ALLOW_ACTIONS.contains(action); } private TeaRequest modifyPutSymlinkRequest(TeaRequest request) { HttpHeader header = request.headers().get(OSSHeaders.SYMLINK_TARGET); if (header != null) { request.headers().set(OSSHeaders.SYMLINK_TARGET, urlEncode(header.getValue())); } return request; } ///////////////////////////////////////////////////////////////////////////////////////////////// private static final List<String> RESPONSE_ALLOW_ACTIONS = Arrays.asList( "ListObjects", "ListObjectsV2", "ListObjectVersions", "DeleteMultipleObjects", "ListMultipartUploads", "ListParts", "GetSymlink", "InitiateMultipartUpload", "CompleteMultipartUpload" ); private static Object urlDecode(String v) { return HttpUtil.urlDecode(v, "utf-8"); } private static ArrayList<?> urlDecodeInList(HashMap root, String node, String key) { Object obj = root.get(node); ArrayList<Object> list = null; if (List.class.isAssignableFrom(obj.getClass())) { list = (ArrayList<Object>) obj; } else { list = new ArrayList<Object>(); list.add(obj); } return (ArrayList<Object>) list.stream().map(o -> { HashMap m = (HashMap) o; m.replace(key, urlDecode((String) m.get(key))); return o; }).collect(Collectors.toList()); } @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); String action = context.teaRequest().action(); if (shouldHandleResponse(response, action)) { switch (action) { case "ListObjects": response = modifyListObjectsResponse(response); break; case "ListObjectsV2": response = modifyListObjectsV2Response(response); break; case "ListObjectVersions": response = modifyListObjectVersionsResponse(response); break; case "DeleteMultipleObjects": response = modifyDeleteMultipleObjectsResponse(response); break; case "ListMultipartUploads": response = modifyListMultipartUploadsResponse(response); break; case "ListParts": response = modifyListPartsResponse(response); break; case "GetSymlink": response = modifyGetSymlinkResponse(response); break; case "InitiateMultipartUpload": response = modifyInitiateMultipartUploadResponse(response); break; case "CompleteMultipartUpload": response = modifyCompleteMultipartUploadResponse(response); break; default: break; } } return response; } private boolean shouldHandleResponse(TeaResponse response, String action) { if (!response.success() || response.exception() != null) { return false; } return RESPONSE_ALLOW_ACTIONS.contains(action); } // Delimiter, Marker, Prefix, NextMarker, Key private TeaResponse modifyListObjectsResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("ListBucketResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Delimiter", "Marker", "Prefix", "NextMarker"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } //Contents if (root.containsKey("Contents")) { root.replace("Contents", urlDecodeInList(root, "Contents", "Key")); } //CommonPrefixes if (root.containsKey("CommonPrefixes")) { root.replace("CommonPrefixes", urlDecodeInList(root, "CommonPrefixes", "Prefix")); } body.replace("ListBucketResult", root); response.setDeserializedBody(body); } return response; } // Delimiter, StartAfter, Prefix, Key private TeaResponse modifyListObjectsV2Response(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("ListBucketResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Delimiter", "StartAfter", "Prefix"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } //Contents if (root.containsKey("Contents")) { root.replace("Contents", urlDecodeInList(root, "Contents", "Key")); } //CommonPrefixes if (root.containsKey("CommonPrefixes")) { root.replace("CommonPrefixes", urlDecodeInList(root, "CommonPrefixes", "Prefix")); } body.replace("ListBucketResult", root); response.setDeserializedBody(body); } return response; } // Delimiter, KeyMarker, NextKeyMarker, Prefix, Key private TeaResponse modifyListObjectVersionsResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("ListVersionsResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Delimiter", "KeyMarker", "NextKeyMarker", "Prefix"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } //Version if (root.containsKey("Version")) { root.replace("Version", urlDecodeInList(root, "Version", "Key")); } //DeleteMarker if (root.containsKey("DeleteMarker")) { root.replace("DeleteMarker", urlDecodeInList(root, "DeleteMarker", "Key")); } //CommonPrefixes if (root.containsKey("CommonPrefixes")) { root.replace("CommonPrefixes", urlDecodeInList(root, "CommonPrefixes", "Prefix")); } body.replace("ListVersionsResult", root); response.setDeserializedBody(body); } return response; } // Key private TeaResponse modifyDeleteMultipleObjectsResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("DeleteResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { //Deleted if (root.containsKey("Deleted")) { root.replace("Deleted", urlDecodeInList(root, "Deleted", "Key")); } body.replace("DeleteResult", root); response.setDeserializedBody(body); } return response; } // Delimiter, Prefix, KeyMarker, NextKeyMarker, Key private TeaResponse modifyListMultipartUploadsResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("ListMultipartUploadsResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Delimiter", "KeyMarker", "NextKeyMarker", "Prefix"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } //Upload if (root.containsKey("Upload")) { root.replace("Upload", urlDecodeInList(root, "Upload", "Key")); } //CommonPrefixes if (root.containsKey("CommonPrefixes")) { root.replace("CommonPrefixes", urlDecodeInList(root, "CommonPrefixes", "Prefix")); } body.replace("ListMultipartUploadsResult", root); response.setDeserializedBody(body); } return response; } // Key private TeaResponse modifyListPartsResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("ListPartsResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Key"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } body.replace("ListPartsResult", root); response.setDeserializedBody(body); } return response; } //x-oss-symlink-target private TeaResponse modifyGetSymlinkResponse(TeaResponse response) { HttpResponse httpResponse = response.httpResponse(); HttpHeader header = httpResponse.getHeaders().get(OSSHeaders.SYMLINK_TARGET); if (header != null) { httpResponse.getHeaders().set(OSSHeaders.SYMLINK_TARGET, (String)urlDecode(header.getValue())); } return response; } private TeaResponse modifyInitiateMultipartUploadResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("InitiateMultipartUploadResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Key"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } body.replace("InitiateMultipartUploadResult", root); response.setDeserializedBody(body); } return response; } private TeaResponse modifyCompleteMultipartUploadResponse(TeaResponse response) { HashMap body = (HashMap) response.deserializedBody(); HashMap root = (HashMap) body.get("CompleteMultipartUploadResult"); if (root != null && ((String) root.getOrDefault("EncodingType", "")).equals("url")) { final List<String> Keys = Arrays.asList("Key"); for (String key : Keys) { if (root.containsKey(key)) { root.replace(key, urlDecode((String) root.get(key))); } } body.replace("CompleteMultipartUploadResult", root); response.setDeserializedBody(body); } return response; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/models/Request.java
package com.aliyun.sdk.gateway.oss.models; import com.aliyun.sdk.gateway.oss.internal.OSSConstants; import darabonba.core.RequestModel; import darabonba.core.exception.ValidateException; import java.io.UnsupportedEncodingException; public abstract class Request extends RequestModel { protected Request(Builder<?, ?> builder) { super(builder); } @Override public void validate() { super.validate(); ensureBucketNameValidIfNotNull(getHostParameters().get("bucket")); ensureObjectKeyValidIfNotNull(getPathParameters().get("key")); } private static boolean validateBucketName(String bucketName) { if (bucketName == null) { return false; } return bucketName.matches(OSSConstants.BUCKET_NAMING_REGEX); } private static void ensureBucketNameValidIfNotNull(String bucketName) { if (bucketName == null) { return; } if (!validateBucketName(bucketName)) { throw new ValidateException("The bucket name " + bucketName + " is invalid."); } } private static boolean validateObjectKey(String key) { if (key == null || key.length() == 0) { return true; } byte[] bytes; try { bytes = key.getBytes(OSSConstants.DEFAULT_CHARSET_NAME); } catch (UnsupportedEncodingException e) { return true; } // Validate exclude xml unsupported chars char[] keyChars = key.toCharArray(); char firstChar = keyChars[0]; if (firstChar == '\\') { return true; } return (bytes.length <= 0 || bytes.length >= OSSConstants.OBJECT_NAME_MAX_LENGTH); } private static void ensureObjectKeyValidIfNotNull(String key) { if (key == null) { return; } if (validateObjectKey(key)) { throw new ValidateException("The object name " + key + " is invalid."); } } public abstract Builder toBuilder(); protected abstract static class Builder<ProviderT extends Request, BuilderT extends Builder> extends RequestModel.BuilderImpl<ProviderT, BuilderT> { protected Builder() { } protected Builder(Request request) { } public BuilderT headerParam(String name, Object value) { putHeaderParameter(name, value); return (BuilderT) this; } public BuilderT queryParam(String name, Object value) { putQueryParameter(name, value); return (BuilderT) this; } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/models/Response.java
package com.aliyun.sdk.gateway.oss.models; import darabonba.core.TeaModel; public abstract class Response extends TeaModel { private ResponseMetadata responseMetadata; private int httpStatusCode; protected Response(BuilderImpl<?, ?> builder) { this.responseMetadata = builder.responseMetadata; this.httpStatusCode = builder.httpStatusCode; } public ResponseMetadata getResponseMetadata() { return this.responseMetadata; } public int getHttpStatusCode() { return this.httpStatusCode; } public abstract Builder toBuilder(); public interface Builder<ProviderT extends Response, BuilderT extends Response.Builder> { BuilderT responseMetadata(ResponseMetadata responseMetadata); BuilderT httpStatusCode(int httpStatusCode); ProviderT build(); } protected abstract static class BuilderImpl<ProviderT extends Response, BuilderT extends Response.Builder> implements Builder<ProviderT, BuilderT> { private ResponseMetadata responseMetadata; private int httpStatusCode; protected BuilderImpl() { } protected BuilderImpl(Response response) { this.responseMetadata = response.responseMetadata; this.httpStatusCode = response.httpStatusCode; } /** * ResponseMetadata. */ @Override public BuilderT responseMetadata(ResponseMetadata responseMetadata) { this.responseMetadata = responseMetadata; return (BuilderT)this; } /** * httpStatusCode. */ @Override public BuilderT httpStatusCode(int httpStatusCode) { this.httpStatusCode = httpStatusCode; return (BuilderT)this; } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/models/ResponseMetadata.java
package com.aliyun.sdk.gateway.oss.models; import com.aliyun.sdk.gateway.oss.internal.OSSHeaders; import java.util.Map; import java.util.Optional; public class ResponseMetadata { private static final String UNKNOWN = "UNKNOWN"; private static final String NEGATIVE_ONE = "-1"; private final Map<String, String> metadata; public ResponseMetadata(Map<String, String> metadata) { this.metadata = metadata; } public String getRequestId() { return getValueAsString(OSSHeaders.REQUEST_ID); } public long getServerTime() { return getValueAsLong(OSSHeaders.SERVER_TIME); } private final String getValueAsString(String key) { try { return Optional.ofNullable(metadata.get(key)).orElse(UNKNOWN); } catch (Exception e) { return UNKNOWN; } } private long getValueAsLong(String key) { try { return Long.parseLong(Optional.ofNullable(metadata.get(key)).orElse(NEGATIVE_ONE)); } catch (Exception e) { return -1; } } private long getValueAsInt(String key) { try { return Integer.parseInt(Optional.ofNullable(metadata.get(key)).orElse(NEGATIVE_ONE)); } catch (Exception e) { return -1; } } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/policy/OSSUserAgentPolicy.java
package com.aliyun.sdk.gateway.oss.policy; import java.io.IOException; import java.util.Properties; public class OSSUserAgentPolicy { private static String gatewayVersion = "unknown"; static { try { Properties props = new Properties(); props.load(OSSUserAgentPolicy.class.getClassLoader().getResourceAsStream("project.properties")); gatewayVersion = props.getProperty("oss.gateway.version"); } catch (IOException e) { e.printStackTrace(); } } public static String getDefaultUserAgentSuffix() { return "aliyun-gateway-oss:" + gatewayVersion; } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/policy
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/policy/retry/OSSRetryPolicy.java
package com.aliyun.sdk.gateway.oss.policy.retry; import com.aliyun.sdk.gateway.oss.exception.InconsistentException; import com.aliyun.sdk.gateway.oss.policy.retry.conditions.RetryOnErrorCodeCondition; import darabonba.core.policy.retry.RetryPolicy; import darabonba.core.policy.retry.conditions.ExceptionsCondition; import darabonba.core.policy.retry.conditions.OrRetryCondition; import darabonba.core.policy.retry.conditions.RetryCondition; import darabonba.core.policy.retry.conditions.StatusCodeCondition; import javax.net.ssl.SSLException; import java.io.IOException; import java.net.SocketException; import java.net.SocketTimeoutException; public final class OSSRetryPolicy { private static int SC_INTERNAL_SERVER_ERROR = 500; private static int SC_BAD_GATEWAY = 502; private static int SC_SERVICE_UNAVAILABLE = 503; private static int SC_GATEWAY_TIMEOUT = 504; public static RetryPolicy defaultRetryPolicy() { return RetryPolicy.defaultRetryPolicy().toBuilder() .retryCondition(OSSRetryPolicy.defaultRetryCondition()) .build(); } private static RetryCondition defaultRetryCondition() { return OrRetryCondition.create( /*Http Status Code*/ StatusCodeCondition.create( SC_INTERNAL_SERVER_ERROR, SC_BAD_GATEWAY, SC_SERVICE_UNAVAILABLE, SC_GATEWAY_TIMEOUT ), /*Common Client Exception*/ ExceptionsCondition.create( SocketTimeoutException.class, SocketException.class, SSLException.class, IOException.class ), /*OSS Server Error Code*/ RetryOnErrorCodeCondition.create( "RequestTimeTooSkewed" ), /*OSS Client Exception*/ ExceptionsCondition.create( InconsistentException.class ) ); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/policy/retry
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/policy/retry/conditions/RetryOnErrorCodeCondition.java
package com.aliyun.sdk.gateway.oss.policy.retry.conditions; import com.aliyun.sdk.gateway.oss.exception.OSSServerException; import darabonba.core.policy.retry.RetryPolicyContext; import darabonba.core.policy.retry.conditions.RetryCondition; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; public final class RetryOnErrorCodeCondition implements RetryCondition { private final Set<String> errorCodes; private RetryOnErrorCodeCondition(Set<String> retryableErrorCodes) { this.errorCodes = retryableErrorCodes; } @Override public boolean shouldRetry(RetryPolicyContext context) { if (context.exception() instanceof OSSServerException) { OSSServerException exception = (OSSServerException) context.exception(); return errorCodes.contains(exception.errorDetails().errorCode()); } return false; } public static RetryOnErrorCodeCondition create(String... errorCodes) { return new RetryOnErrorCodeCondition(Arrays.stream(errorCodes).collect(Collectors.toSet())); } public static RetryOnErrorCodeCondition create(Set<String> errorCodes) { return new RetryOnErrorCodeCondition(errorCodes); } }
0
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss
java-sources/com/aliyun/aliyun-gateway-oss/0.3.2-beta/com/aliyun/sdk/gateway/oss/util/Mimetypes.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyun.sdk.gateway.oss.util; import java.io.*; import java.util.HashMap; import java.util.StringTokenizer; /** * Utility class used to determine the mimetype of files based on file * extensions. */ public class Mimetypes { /* The default MIME type */ public static final String DEFAULT_MIMETYPE = "application/octet-stream"; private static Mimetypes mimetypes = null; private HashMap<String, String> extensionToMimetypeMap = new HashMap<String, String>(); private Mimetypes() { } public synchronized static Mimetypes getInstance() { if (mimetypes != null) return mimetypes; mimetypes = new Mimetypes(); InputStream is = mimetypes.getClass().getResourceAsStream("/oss.mime.types"); if (is != null) { //getLog().debug("Loading mime types from file in the classpath: oss.mime.types"); try { mimetypes.loadMimetypes(is); } catch (IOException e) { //getLog().error("Failed to load mime types from file in the classpath: oss.mime.types", e); } finally { try { is.close(); } catch (IOException ex) { } } } else { //getLog().warn("Unable to find 'oss.mime.types' file in classpath"); } return mimetypes; } public void loadMimetypes(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.length() == 0) { // Ignore comments and empty lines. } else { StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { String extension = st.nextToken(); if (st.hasMoreTokens()) { String mimetype = st.nextToken(); extensionToMimetypeMap.put(extension.toLowerCase(), mimetype); } } } } } public String getMimetype(String fileName) { String mimeType = getMimetypeByExt(fileName); if (mimeType != null) { return mimeType; } return DEFAULT_MIMETYPE; } public String getMimetype(File file) { return getMimetype(file.getName()); } public String getMimetype(File file, String key) { return getMimetype(file.getName(), key); } public String getMimetype(String primaryObject, String secondaryObject) { String mimeType = getMimetypeByExt(primaryObject); if (mimeType != null) { return mimeType; } mimeType = getMimetypeByExt(secondaryObject); if (mimeType != null) { return mimeType; } return DEFAULT_MIMETYPE; } private String getMimetypeByExt(String fileName) { int lastPeriodIndex = fileName.lastIndexOf("."); if (lastPeriodIndex > 0 && lastPeriodIndex + 1 < fileName.length()) { String ext = fileName.substring(lastPeriodIndex + 1).toLowerCase(); if (extensionToMimetypeMap.keySet().contains(ext)) { String mimetype = (String) extensionToMimetypeMap.get(ext); return mimetype; } } return null; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/BaseClientBuilder.java
package com.aliyun.sdk.gateway.pop; import com.aliyun.auth.signature.Signer; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.auth.signer.PopV1Signer; import com.aliyun.sdk.gateway.pop.auth.signer.PopV3Signer; import com.aliyun.sdk.gateway.pop.auth.signer.PopV4Signer; import com.aliyun.sdk.gateway.pop.interceptor.configuration.EndpointInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.httpRequest.RoaHttpReqInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.httpRequest.RpcHttpReqInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.httpRequest.HttpReqInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.output.FinalizedOutputInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.request.RoaReqInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.request.RpcReqInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.request.ReqInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.response.PopResInterceptor; import com.aliyun.sdk.gateway.pop.interceptor.response.TeaResponseInterceptor; import com.aliyun.sdk.gateway.pop.policy.POPUserAgentPolicy; import darabonba.core.TeaClientBuilder; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.client.IClientBuilder; import darabonba.core.interceptor.InterceptorChain; import darabonba.core.utils.CommonUtil; public abstract class BaseClientBuilder<BuilderT extends IClientBuilder<BuilderT, ClientT>, ClientT> extends TeaClientBuilder<BuilderT, ClientT> { @Override protected String serviceName() { return "POP"; } public BuilderT serviceConfiguration(Configuration serviceConfiguration) { clientConfiguration.setOption(ClientOption.SERVICE_CONFIGURATION, serviceConfiguration); return (BuilderT) this; } @Override protected ClientConfiguration mergeServiceDefaults(ClientConfiguration configuration) { return configuration.merge(ClientConfiguration.create() .setOption(ClientOption.SERVICE_CONFIGURATION, Configuration.create()) .setOption(ClientOption.USER_AGENT_SERVICE_SUFFIX, POPUserAgentPolicy.getDefaultUserAgentSuffix())); } @Override protected ClientConfiguration finalizeServiceConfiguration(ClientConfiguration configuration) { InterceptorChain chain = InterceptorChain.create(); chain.addConfigurationInterceptor(new EndpointInterceptor()); chain.addRequestInterceptor(new RpcReqInterceptor()); chain.addRequestInterceptor(new RoaReqInterceptor()); chain.addRequestInterceptor(new ReqInterceptor()); chain.addHttpRequestInterceptor(new RpcHttpReqInterceptor()); chain.addHttpRequestInterceptor(new RoaHttpReqInterceptor()); chain.addHttpRequestInterceptor(new HttpReqInterceptor()); chain.addResponseInterceptor(new TeaResponseInterceptor()); chain.addResponseInterceptor(new PopResInterceptor()); chain.addOutputInterceptor(new FinalizedOutputInterceptor()); configuration.setOption(ClientOption.INTERCEPTOR_CHAIN, chain); Configuration config = (Configuration) configuration.option(ClientOption.SERVICE_CONFIGURATION); Signer signer; if (CommonUtil.isUnset(config)) { signer = new PopV1Signer(Configuration.DEFAULT_SIGNATURE_ALGORRITHM_V1); config = Configuration.create(); configuration.setOption(ClientOption.SERVICE_CONFIGURATION, config); } else if (config.signatureVersion() == SignatureVersion.V3) { signer = new PopV3Signer(config.signatureAlgorithmV3()); } else if (config.signatureVersion() == SignatureVersion.V4) { signer = new PopV4Signer(config.realSignatureAlgorithmV4()); } else { signer = new PopV1Signer(config.signatureAlgorithmV1()); } configuration.setOption(ClientOption.SIGNER, signer); return configuration; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/Configuration.java
package com.aliyun.sdk.gateway.pop; import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import darabonba.core.ServiceConfiguration; public final class Configuration implements ServiceConfiguration { public static final SignatureVersion DEFAULT_SIGNATURE_VERSION = SignatureVersion.V1; public static final SignatureAlgorithm DEFAULT_SIGNATURE_ALGORRITHM_V1 = SignatureAlgorithm.HMAC_SHA1; public static final SignatureAlgorithm DEFAULT_SIGNATURE_ALGORRITHM_V3 = SignatureAlgorithm.ACS3_HMAC_SHA256; public static final SignatureAlgorithm DEFAULT_SIGNATURE_ALGORRITHM_V4 = SignatureAlgorithm.ACS4_HMAC_SHA256; private SignatureVersion signatureVersion = DEFAULT_SIGNATURE_VERSION; private SignatureAlgorithm signatureAlgorithmV1 = DEFAULT_SIGNATURE_ALGORRITHM_V1; private SignatureAlgorithm signatureAlgorithmV3 = DEFAULT_SIGNATURE_ALGORRITHM_V3; private SignatureAlgorithm signatureAlgorithmV4 = DEFAULT_SIGNATURE_ALGORRITHM_V4; private String signatureTypePrefix = "ACS4-"; private String signPrefix = "aliyun_v4"; private String endpointSuffix = "aliyuncs.com"; private String realSignatureAlgorithmV4 = null; private Configuration() { } public static Configuration create() { return new Configuration(); } public SignatureVersion signatureVersion() { return signatureVersion; } public Configuration setSignatureVersion(SignatureVersion signatureVersion) { this.signatureVersion = signatureVersion; return this; } public SignatureAlgorithm signatureAlgorithmV1() { return signatureAlgorithmV1; } public Configuration setSignatureAlgorithmV1(SignatureAlgorithm signatureAlgorithmV1) { this.signatureAlgorithmV1 = signatureAlgorithmV1; return this; } public SignatureAlgorithm signatureAlgorithmV3() { return signatureAlgorithmV3; } public Configuration setSignatureAlgorithmV3(SignatureAlgorithm signatureAlgorithmV3) { this.signatureAlgorithmV3 = signatureAlgorithmV3; return this; } public SignatureAlgorithm signatureAlgorithmV4() { return signatureAlgorithmV4; } public Configuration setSignatureAlgorithmV4(SignatureAlgorithm signatureAlgorithmV4) { this.signatureAlgorithmV4 = signatureAlgorithmV4; this.realSignatureAlgorithmV4 = signatureAlgorithmV4.algorithmName(); return this; } public String signatureTypePrefix() { return signatureTypePrefix; } public Configuration setSignatureTypePrefix(String signatureTypePrefix) { this.signatureTypePrefix = signatureTypePrefix; this.realSignatureAlgorithmV4 = signatureAlgorithmV4.algorithmName().replace("ACS4-", signatureTypePrefix); return this; } public String realSignatureAlgorithmV4() { return realSignatureAlgorithmV4; } public String signPrefix() { return signPrefix; } public Configuration setSignPrefix(String signPrefix) { this.signPrefix = signPrefix; return this; } public String endpointSuffix() { return endpointSuffix; } public Configuration setEndpointSuffix(String endpointSuffix) { this.endpointSuffix = endpointSuffix; return this; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/RoaSignatureComposer.java
package com.aliyun.sdk.gateway.pop.auth; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.utils.StringUtils; import java.util.*; public class RoaSignatureComposer { private final static String SEPARATOR = "&"; private final static String ACCEPT = "accept"; private final static String CONTENT_MD5 = "content-md5"; private final static String CONTENT_TYPE = "content-type"; private final static String DATE = "date"; private final static String prefix = "x-acs-"; public static String composeStringToSign(HttpMethod method, Map<String, String> params, Map<String, String> headers, String pathname) { String accept = headers.get(ACCEPT) == null ? StringUtils.EMPTY : headers.get(ACCEPT); String contentMD5 = headers.get(CONTENT_MD5) == null ? StringUtils.EMPTY : headers.get(CONTENT_MD5); String contentType = headers.get(CONTENT_TYPE) == null ? StringUtils.EMPTY : headers.get(CONTENT_TYPE); String date = headers.get(DATE) == null ? StringUtils.EMPTY : headers.get(DATE); String header = method + "\n" + accept + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n"; String canonicalizedHeaders = buildCanonicalizedHeaders(headers); String canonicalizedResource = buildCanonicalizedResource(pathname, params); return header + canonicalizedHeaders + canonicalizedResource; } private static String buildCanonicalizedHeaders(Map<String, String> headers) { Set<String> keys = headers.keySet(); List<String> canonicalizedKeys = new ArrayList<>(); for (String key : keys) { if (key.startsWith(prefix)) { canonicalizedKeys.add(key); } } Collections.sort(canonicalizedKeys); StringBuilder canonicalizedHeaders = new StringBuilder(); for (String key : canonicalizedKeys) { canonicalizedHeaders.append(key); canonicalizedHeaders.append(":"); canonicalizedHeaders.append(headers.get(key).trim()); canonicalizedHeaders.append("\n"); } return canonicalizedHeaders.toString(); } private static String buildCanonicalizedResource(String pathname, Map<String, String> params) { if (params.size() <= 0) { return pathname; } String[] keys = params.keySet().toArray(new String[params.size()]); StringBuilder queryString = new StringBuilder(pathname); queryString.append("?"); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { queryString.append(keys[i]); if (!StringUtils.isEmpty(params.get(keys[i]))) { queryString.append("="); queryString.append(params.get(keys[i])); } queryString.append(SEPARATOR); } return queryString.length() > 0 ? queryString.deleteCharAt(queryString.length() - 1).toString() : StringUtils.EMPTY; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/RpcSignatureComposer.java
package com.aliyun.sdk.gateway.pop.auth; import com.aliyun.auth.signature.exception.SignatureException; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Map; import static com.aliyun.core.utils.EncodeUtil.percentEncode; public class RpcSignatureComposer { private final static String SEPARATOR = "&"; public static String composeStringToSign(HttpMethod method, Map<String, String> params, Map<String, String> headers, String pathname) { StringBuilder stringToSign = new StringBuilder(); try { stringToSign.append(method); stringToSign.append(SEPARATOR); stringToSign.append(percentEncode(pathname)); stringToSign.append(SEPARATOR); stringToSign.append(percentEncode( buildCanonicalizedResource(params))); } catch (UnsupportedEncodingException e) { throw new SignatureException(e.toString()); } return stringToSign.toString(); } private static String buildCanonicalizedResource(Map<String, String> params) { String[] sortedKeys = params.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); StringBuilder queryString = new StringBuilder(); try { for (String key : sortedKeys) { if (null != params.get(key)) { queryString.append(SEPARATOR) .append(percentEncode(key)).append("=") .append(percentEncode(params.get(key))); } } } catch (UnsupportedEncodingException e) { throw new SignatureException(e.toString()); } return queryString.length() > 0 ? queryString.substring(1) : StringUtils.EMPTY; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/SignatureAlgorithm.java
package com.aliyun.sdk.gateway.pop.auth; public enum SignatureAlgorithm { HMAC_SHA1("HMAC-SHA1"), ACS3_HMAC_SHA256("ACS3-HMAC-SHA256"), ACS3_HMAC_SM3("ACS3-HMAC-SM3"), ACS3_RSA_SHA256("ACS3-RSA-SHA256"), ACS4_HMAC_SHA256("ACS4-HMAC-SHA256"), ACS4_HMAC_SM3("ACS4-HMAC-SM3"), UNKNOWN("UNKNOWN"); private final String algorithmName; SignatureAlgorithm(String algorithmName) { this.algorithmName = algorithmName; } public String algorithmName() { return algorithmName; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/SignatureComposer.java
package com.aliyun.sdk.gateway.pop.auth; import com.aliyun.auth.signature.exception.SignatureException; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.utils.EncodeUtil; import com.aliyun.core.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.util.*; public class SignatureComposer { private final static String UTF8 = "UTF-8"; private final static String SEPARATOR = "&"; private final static String DELIMITER = ";"; private final static String prefix = "x-acs-"; private final static String CONTENT_TYPE = "content-type"; private final static String HOST = "host"; public static String composeStringToSign(HttpMethod method, Map<String, String> params, Map<String, String> headers, String pathname, String payload) { String canonicalURI = pathname; if (StringUtils.isBlank(canonicalURI)) { canonicalURI = "/"; } String queryString = getCanonicalizedResource(params); StringBuilder sb = new StringBuilder(method.toString()); sb.append("\n").append(canonicalURI) .append("\n").append(queryString) .append("\n").append(buildCanonicalizedHeaders(headers)) .append("\n").append(buildSignedHeaders(headers)) .append("\n").append(payload); return sb.toString(); } private static String buildCanonicalizedHeaders(Map<String, String> headers) { Set<String> keys = headers.keySet(); List<String> canonicalizedKeys = new ArrayList<>(); Map<String, String> valueMap = new HashMap<>(); for (String key : keys) { String lowerKey = key.toLowerCase(); if (lowerKey.startsWith(prefix) || lowerKey.equals(HOST) || lowerKey.equals(CONTENT_TYPE)) { if (!canonicalizedKeys.contains(lowerKey)) { canonicalizedKeys.add(lowerKey); } valueMap.put(lowerKey, headers.get(key).trim()); } } String[] canonicalizedKeysArray = canonicalizedKeys.toArray(new String[canonicalizedKeys.size()]); Arrays.sort(canonicalizedKeysArray); StringBuilder sb = new StringBuilder(); for (int i = 0; i < canonicalizedKeysArray.length; i++) { String key = canonicalizedKeysArray[i]; sb.append(key); sb.append(":"); sb.append(valueMap.get(key)); sb.append("\n"); } return sb.toString(); } public static String buildSignedHeaders(Map<String, String> headers) { String[] keys = headers.keySet().toArray(new String[headers.size()]); Arrays.sort(keys); List<String> canonicalizedKeys = new ArrayList<String>(); for (String key : keys) { String lowerKey = key.toLowerCase(); if (lowerKey.startsWith(prefix) || lowerKey.equals(HOST) || lowerKey.equals(CONTENT_TYPE)) { if (!canonicalizedKeys.contains(lowerKey)) { canonicalizedKeys.add(lowerKey); } } } String[] canonicalizedKeysArray = canonicalizedKeys.toArray(new String[canonicalizedKeys.size()]); return StringUtils.join(DELIMITER, Arrays.asList(canonicalizedKeysArray)); } private static String getCanonicalizedResource(Map<String, String> query) { if (query == null || query.size() == 0) { return StringUtils.EMPTY; } String[] keys = query.keySet().toArray(new String[query.size()]); Arrays.sort(keys); StringBuilder queryString = new StringBuilder(); try { for (int i = 0; i < keys.length; i++) { queryString.append(EncodeUtil.percentEncode(keys[i])); queryString.append("="); if (!StringUtils.isEmpty(query.get(keys[i]))) { queryString.append(EncodeUtil.percentEncode(query.get(keys[i]))); } queryString.append(SEPARATOR); } } catch (UnsupportedEncodingException e) { throw new SignatureException(e.toString()); } return queryString.length() > 0 ? queryString.deleteCharAt(queryString.length() - 1).toString() : StringUtils.EMPTY; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/SignatureVersion.java
package com.aliyun.sdk.gateway.pop.auth; public enum SignatureVersion { V1, V3, V4 }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/signer/PopSigner.java
package com.aliyun.sdk.gateway.pop.auth.signer; import com.aliyun.auth.signature.Signer; import com.aliyun.auth.signature.SignerParams; import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; public interface PopSigner extends Signer { default String signString(String stringToSign, SignerParams params) { return null; } default byte[] signString(String stringToSign, byte[] signingKey) { return null; } default byte[] signString(String stringToSign, String signingKey) { return null; } byte[] hash(byte[] raw); String getContent(); String getSignerName(); SignatureVersion getSignerVersion(); }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/signer/PopV1Signer.java
package com.aliyun.sdk.gateway.pop.auth.signer; import com.aliyun.auth.signature.SignerParams; import com.aliyun.auth.signature.exception.SignatureException; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSHA1; import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.auth.credentials.ICredential; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.util.Base64; public class PopV1Signer implements PopSigner { private final String ENCODING = "UTF-8"; private final SignatureAlgorithm DEFAULT_ALGORITHM = SignatureAlgorithm.HMAC_SHA1; private final SignatureAlgorithm algorithm; public PopV1Signer() { this.algorithm = DEFAULT_ALGORITHM; } public PopV1Signer(SignatureAlgorithm algorithm) { if (algorithm != null) { this.algorithm = algorithm; } else { this.algorithm = DEFAULT_ALGORITHM; } } @Override public String signString(String stringToSign, SignerParams params) { switch (algorithm) { case HMAC_SHA1: default: try { Mac mac = SignAlgorithmHmacSHA1.HmacSHA1.getMac(); ICredential credential = params.credentials(); mac.init(new SecretKeySpec(credential.accessKeySecret().getBytes(ENCODING), SignAlgorithmHmacSHA1.HmacSHA1.toString())); return Base64.getEncoder().encodeToString(mac.doFinal(stringToSign.getBytes(ENCODING))); } catch (UnsupportedEncodingException | InvalidKeyException e) { throw new SignatureException(e.toString()); } } } @Override public byte[] hash(byte[] raw) { return null; } @Override public String getContent() { return null; } @Override public String getSignerName() { return algorithm.algorithmName(); } @Override public SignatureVersion getSignerVersion() { return SignatureVersion.V1; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/signer/PopV3Signer.java
package com.aliyun.sdk.gateway.pop.auth.signer; import com.aliyun.auth.signature.SignerParams; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSHA256; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSM3; import com.aliyun.auth.signature.signer.SignAlgorithmSHA256withRSA; import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.auth.credentials.ICredential; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; import static com.aliyun.core.utils.EncodeUtil.hexEncode; public class PopV3Signer implements PopSigner { private final String ENCODING = "UTF-8"; private final String HASH_SHA256 = "SHA-256"; private final String HASH_SM3 = "SM3"; private final String PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"; private final String PEM_END = "\n-----END RSA PRIVATE KEY-----"; private final SignatureAlgorithm DEFAULT_ALGORITHM = SignatureAlgorithm.ACS3_HMAC_SHA256; private final SignatureAlgorithm algorithm; public PopV3Signer() { this.algorithm = DEFAULT_ALGORITHM; } public PopV3Signer(SignatureAlgorithm algorithm) { if (algorithm != null) { this.algorithm = algorithm; } else { this.algorithm = DEFAULT_ALGORITHM; } } @Override public String signString(String stringToSign, SignerParams params) { ICredential credential = params.credentials(); String accessKeySecret = credential.accessKeySecret(); try { switch (algorithm) { case ACS3_HMAC_SM3: HMac sm3HMAC = SignAlgorithmHmacSM3.HMAC_SM3.getMac(); SecretKey key = new SecretKeySpec(accessKeySecret.getBytes(ENCODING), SignAlgorithmHmacSM3.HMAC_SM3.toString()); byte[] sm3Sign = new byte[sm3HMAC.getMacSize()]; byte[] inputBytes = stringToSign.getBytes(ENCODING); sm3HMAC.init(new KeyParameter(key.getEncoded())); sm3HMAC.update(inputBytes, 0, inputBytes.length); sm3HMAC.doFinal(sm3Sign, 0); return hexEncode(sm3Sign); case ACS3_RSA_SHA256: Signature rsaSign = SignAlgorithmSHA256withRSA.SHA256withRSA.getSignature(); KeyFactory kf = KeyFactory.getInstance(SignAlgorithmSHA256withRSA.SHA256withRSA.toString()); byte[] keySpec = Base64.getDecoder().decode(checkRSASecret(accessKeySecret)); PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(keySpec)); rsaSign.initSign(privateKey); rsaSign.update(stringToSign.getBytes(ENCODING)); byte[] sign = rsaSign.sign(); return hexEncode(sign); case ACS3_HMAC_SHA256: default: Mac sha256HMAC = SignAlgorithmHmacSHA256.HmacSHA256.getMac(); sha256HMAC.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), SignAlgorithmHmacSHA256.HmacSHA256.toString())); return hexEncode(sha256HMAC.doFinal(stringToSign.getBytes(ENCODING))); } } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException e) { throw new com.aliyun.auth.signature.exception.SignatureException(e.toString()); } } private String checkRSASecret(String accessKeySecret) { if (accessKeySecret != null) { if (accessKeySecret.startsWith(PEM_BEGIN)) { accessKeySecret = accessKeySecret.replace(PEM_BEGIN, ""); } while (accessKeySecret.endsWith("\n") || accessKeySecret.endsWith("\r")) { accessKeySecret = accessKeySecret.substring(0, accessKeySecret.length() - 1); } if (accessKeySecret.endsWith(PEM_END)) { accessKeySecret = accessKeySecret.replace(PEM_END, ""); } } return accessKeySecret; } @Override public byte[] hash(byte[] raw) { if (null == raw) { return null; } try { MessageDigest digest; switch (algorithm) { case ACS3_HMAC_SM3: BouncyCastleProvider provider = new BouncyCastleProvider(); digest = MessageDigest.getInstance(HASH_SM3, provider); break; case ACS3_HMAC_SHA256: case ACS3_RSA_SHA256: default: digest = MessageDigest.getInstance(HASH_SHA256); } return digest.digest(raw); } catch (NoSuchAlgorithmException e) { throw new com.aliyun.auth.signature.exception.SignatureException(e.toString()); } } @Override public String getContent() { switch (algorithm) { case ACS3_HMAC_SM3: return "x-acs-content-sm3"; case ACS3_HMAC_SHA256: case ACS3_RSA_SHA256: default: return "x-acs-content-sha256"; } } @Override public String getSignerName() { return algorithm.algorithmName(); } @Override public SignatureVersion getSignerVersion() { return SignatureVersion.V3; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/auth/signer/PopV4Signer.java
package com.aliyun.sdk.gateway.pop.auth.signer; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSHA256; import com.aliyun.auth.signature.signer.SignAlgorithmHmacSM3; import com.aliyun.sdk.gateway.pop.auth.SignatureAlgorithm; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.*; public class PopV4Signer implements PopSigner { private final String ENCODING = "UTF-8"; private final String HASH_SHA256 = "SHA-256"; private final String HASH_SM3 = "SM3"; private final SignatureAlgorithm DEFAULT_ALGORITHM = SignatureAlgorithm.ACS4_HMAC_SHA256; private final String algorithm; public PopV4Signer() { this.algorithm = DEFAULT_ALGORITHM.algorithmName(); } public PopV4Signer(SignatureAlgorithm algorithm) { if (algorithm != null) { this.algorithm = algorithm.algorithmName(); } else { this.algorithm = DEFAULT_ALGORITHM.algorithmName(); } } public PopV4Signer(String algorithm) { if (algorithm != null) { this.algorithm = algorithm; } else { this.algorithm = DEFAULT_ALGORITHM.algorithmName(); } } @Override public byte[] signString(String stringToSign, byte[] signingKey) { try { if (algorithm.endsWith("HMAC-SHA256")) { Mac sha256HMAC = SignAlgorithmHmacSHA256.HmacSHA256.getMac(); sha256HMAC.init(new SecretKeySpec(signingKey, SignAlgorithmHmacSHA256.HmacSHA256.toString())); return sha256HMAC.doFinal(stringToSign.getBytes(ENCODING)); } else if (algorithm.endsWith("HMAC-SM3")) { HMac sm3HMAC = SignAlgorithmHmacSM3.HMAC_SM3.getMac(); SecretKey key = new SecretKeySpec(signingKey, SignAlgorithmHmacSM3.HMAC_SM3.toString()); byte[] sm3Sign = new byte[sm3HMAC.getMacSize()]; byte[] inputBytes = stringToSign.getBytes(ENCODING); sm3HMAC.init(new KeyParameter(key.getEncoded())); sm3HMAC.update(inputBytes, 0, inputBytes.length); sm3HMAC.doFinal(sm3Sign, 0); return sm3Sign; } throw new com.aliyun.auth.signature.exception.SignatureException("Unsupported algorithm: " + algorithm); } catch (UnsupportedEncodingException | InvalidKeyException e) { throw new com.aliyun.auth.signature.exception.SignatureException(e.toString()); } } @Override public byte[] signString(String stringToSign, String signingKey) { try { return signString(stringToSign, signingKey.getBytes(ENCODING)); } catch (UnsupportedEncodingException e) { throw new com.aliyun.auth.signature.exception.SignatureException(e.toString()); } } @Override public byte[] hash(byte[] raw) { if (null == raw) { return null; } try { MessageDigest digest; if (algorithm.endsWith("HMAC-SHA256")) { digest = MessageDigest.getInstance(HASH_SHA256); } else if (algorithm.endsWith("HMAC-SM3")) { BouncyCastleProvider provider = new BouncyCastleProvider(); digest = MessageDigest.getInstance(HASH_SM3, provider); } else { throw new com.aliyun.auth.signature.exception.SignatureException("Unsupported algorithm: " + algorithm); } return digest.digest(raw); } catch (NoSuchAlgorithmException e) { throw new com.aliyun.auth.signature.exception.SignatureException(e.toString()); } } @Override public String getContent() { if (algorithm.endsWith("HMAC-SHA256")) { return "x-acs-content-sha256"; } else if (algorithm.endsWith("HMAC-SM3")) { return "x-acs-content-sm3"; } throw new com.aliyun.auth.signature.exception.SignatureException("Unsupported algorithm: " + algorithm); } @Override public String getSignerName() { return algorithm; } @Override public SignatureVersion getSignerVersion() { return SignatureVersion.V4; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/clients/CommonAsyncClient.java
package com.aliyun.sdk.gateway.pop.clients; import com.aliyun.core.utils.SdkAutoCloseable; import com.aliyun.sdk.gateway.pop.Configuration; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.models.CommonRequest; import com.aliyun.sdk.gateway.pop.models.CommonResponse; import com.aliyun.sdk.gateway.pop.sse.ResponseBodyIterator; import darabonba.core.*; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientExecutionParams; import darabonba.core.sse.SSEHttpResponseHandler; import java.util.concurrent.CompletableFuture; public final class CommonAsyncClient implements SdkAutoCloseable { private final TeaAsyncHandler handler; CommonAsyncClient(ClientConfiguration configuration) { this.handler = new TeaAsyncHandler(configuration); } public static CommonAsyncClientBuilder builder() { return new CommonAsyncClientBuilder().serviceConfiguration(Configuration.create().setSignatureVersion(SignatureVersion.V3)); } static CommonAsyncClient create() { return builder().build(); } @Override public void close() { this.handler.close(); } public ResponseIterable<String> callSseApi(CommonRequest request) { this.handler.validateRequestModel(request); TeaRequest teaRequest = TeaRequest.create() .setProduct(request.getProduct()) .setVersion(request.getVersion()) .setStyle(RequestStyle.SSE) .setAction(request.getAction()) .setMethod(request.getHttpMethod()) .setPathRegex(request.getPath()) .setReqBodyType(request.getRequestBodyType()) .setBodyType(request.getResponseBodyType()) .setBodyIsForm(request.isFormData()) .formModel(request); ResponseBodyIterator iterator = ResponseBodyIterator.create(); ClientExecutionParams<RequestModel, TeaModel> params = new ClientExecutionParams<>() .withInput(request) .withRequest(teaRequest) .withHttpResponseHandler(new SSEHttpResponseHandler(iterator)); this.handler.execute(params); return new ResponseIterable<>(iterator); } public CompletableFuture<CommonResponse> callApi(CommonRequest request) { try { this.handler.validateRequestModel(request); TeaRequest teaRequest = TeaRequest.create() .setProduct(request.getProduct()) .setVersion(request.getVersion()) .setStyle(request.getPath().equals("/") ? RequestStyle.RPC : RequestStyle.RESTFUL) .setAction(request.getAction()) .setMethod(request.getHttpMethod()) .setPathRegex(request.getPath()) .setReqBodyType(request.getRequestBodyType()) .setBodyType(request.getResponseBodyType()) .setBodyIsForm(request.isFormData()) .formModel(request); ClientExecutionParams<CommonRequest, CommonResponse> params = new ClientExecutionParams<CommonRequest, CommonResponse>() .withInput(request) .withRequest(teaRequest) .withOutput(CommonResponse.create()); return this.handler.execute(params); } catch (Exception e) { CompletableFuture<CommonResponse> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/clients/CommonAsyncClientBuilder.java
package com.aliyun.sdk.gateway.pop.clients; import com.aliyun.sdk.gateway.pop.BaseClientBuilder; public final class CommonAsyncClientBuilder extends BaseClientBuilder<CommonAsyncClientBuilder, CommonAsyncClient> { @Override protected CommonAsyncClient buildClient() { return new CommonAsyncClient(super.applyClientConfiguration()); } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/clients/CommonClient.java
package com.aliyun.sdk.gateway.pop.clients; import com.aliyun.core.utils.SdkAutoCloseable; import com.aliyun.sdk.gateway.pop.Configuration; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.models.CommonRequest; import com.aliyun.sdk.gateway.pop.models.CommonResponse; import darabonba.core.*; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientExecutionParams; public final class CommonClient implements SdkAutoCloseable { private final TeaAsyncHandler handler; CommonClient(ClientConfiguration configuration) { this.handler = new TeaAsyncHandler(configuration); } public static CommonClientBuilder builder() { return new CommonClientBuilder().serviceConfiguration(Configuration.create().setSignatureVersion(SignatureVersion.V3)); } static CommonClient create() { return builder().build(); } @Override public void close() { this.handler.close(); } public CommonResponse callApi(CommonRequest request) { this.handler.validateRequestModel(request); TeaRequest teaRequest = TeaRequest.create() .setProduct(request.getProduct()) .setVersion(request.getVersion()) .setStyle(request.getPath().equals("/") ? RequestStyle.RPC : RequestStyle.RESTFUL) .setAction(request.getAction()) .setMethod(request.getHttpMethod()) .setPathRegex(request.getPath()) .setReqBodyType(request.getRequestBodyType()) .setBodyType(request.getResponseBodyType()) .setBodyIsForm(request.isFormData()) .formModel(request); ClientExecutionParams<CommonRequest, CommonResponse> params = new ClientExecutionParams<CommonRequest, CommonResponse>() .withInput(request) .withRequest(teaRequest) .withOutput(CommonResponse.create()); return this.handler.execute(params).join(); } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/clients/CommonClientBuilder.java
package com.aliyun.sdk.gateway.pop.clients; import com.aliyun.sdk.gateway.pop.BaseClientBuilder; public final class CommonClientBuilder extends BaseClientBuilder<CommonClientBuilder, CommonClient> { @Override protected CommonClient buildClient() { return new CommonClient(super.applyClientConfiguration()); } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/exception/PopClientException.java
package com.aliyun.sdk.gateway.pop.exception; import com.aliyun.core.utils.StringUtils; import darabonba.core.exception.ClientException; import darabonba.core.utils.CommonUtil; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class PopClientException extends ClientException { private String code; private String message; private String requestId; private String description; private Map<String, Object> accessDeniedDetail; private Map<String, Object> data; public PopClientException() { super(); } public PopClientException(final String message) { super(message); } public PopClientException(final Throwable cause) { super(cause); } public PopClientException(final String message, final Throwable cause) { super(message, cause); } public PopClientException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public PopClientException(Map<String, Object> map) { setData(map); } public PopClientException(Map<String, Object> map, String message, Throwable cause) { super(message, cause); setData(map); } @Override public String getMessage() { if (!StringUtils.isEmpty(message)) { return "\n(Code: " + getErrCode() + "\nMessage: " + getErrMessage() + "\nRequest ID: " + getRequestId() + "\nDescription: " + getDescription() + ")"; } return super.getMessage(); } public String getErrMessage() { return message; } public void setErrMessage(String message) { this.message = message; } public String getErrCode() { return code; } public void setErrCode(String code) { this.code = code; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Map<String, Object> getAccessDeniedDetail() { return accessDeniedDetail; } public void setAccessDeniedDetail(Map<String, Object> accessDeniedDetail) { this.accessDeniedDetail = accessDeniedDetail; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> map) { this.setErrCode(String.valueOf(map.get("code"))); this.setErrMessage(String.valueOf(map.get("message"))); this.setDescription(String.valueOf(map.get("description"))); if (map.containsKey("statusCode")) { this.setStatusCode(Integer.parseInt(String.valueOf(map.get("statusCode")))); } if (map.get("accessDeniedDetail") instanceof Map) { this.setAccessDeniedDetail((Map<String, Object>) map.get("accessDeniedDetail")); } Object obj = map.get("data"); if (obj == null) { return; } if (obj instanceof Map) { data = (Map<String, Object>) obj; if (!CommonUtil.isUnset(data.get("RequestId"))) { this.setRequestId(data.get("RequestId").toString()); } else if (!CommonUtil.isUnset(data.get("requestId"))) { this.setRequestId(data.get("requestId").toString()); } return; } Map<String, Object> hashMap = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); try { hashMap.put(field.getName(), field.get(obj)); } catch (Exception e) { continue; } } this.data = hashMap; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/exception/PopServerException.java
package com.aliyun.sdk.gateway.pop.exception; import com.aliyun.core.utils.StringUtils; import darabonba.core.exception.ServerException; import darabonba.core.utils.CommonUtil; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class PopServerException extends ServerException { private String code; private String message; private String requestId; private String description; private Map<String, Object> data; public PopServerException() { super(); } public PopServerException(final String message) { super(message); } public PopServerException(final Throwable cause) { super(cause); } public PopServerException(final String message, final Throwable cause) { super(message, cause); } public PopServerException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public PopServerException(Map<String, Object> map) { setData(map); } public PopServerException(Map<String, Object> map, String message, Throwable cause) { super(message, cause); setData(map); } @Override public String getMessage() { if (!StringUtils.isEmpty(message)) { return "\n(Code: " + getErrCode() + "\nMessage: " + getErrMessage() + "\nRequest ID: " + getRequestId() + "\nDescription: " + getDescription() + ")"; } return super.getMessage(); } public String getErrMessage() { return message; } public void setErrMessage(String message) { this.message = message; } public String getErrCode() { return code; } public void setErrCode(String code) { this.code = code; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> map) { this.setErrCode(String.valueOf(map.get("code"))); this.setErrMessage(String.valueOf(map.get("message"))); this.setDescription(String.valueOf(map.get("description"))); if (map.containsKey("statusCode")) { this.setStatusCode(Integer.parseInt(String.valueOf(map.get("statusCode")))); } Object obj = map.get("data"); if (obj == null) { return; } if (obj instanceof Map) { data = (Map<String, Object>) obj; if (!CommonUtil.isUnset(data.get("RequestId"))) { this.setRequestId(data.get("RequestId").toString()); } else if (!CommonUtil.isUnset(data.get("requestId"))) { this.setRequestId(data.get("requestId").toString()); } return; } Map<String, Object> hashMap = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); try { hashMap.put(field.getName(), field.get(obj)); } catch (Exception e) { continue; } } this.data = hashMap; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/configuration/EndpointInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.configuration; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.pop.exception.PopClientException; import darabonba.core.EndpointType; import darabonba.core.TeaConfiguration; import darabonba.core.TeaRequest; import darabonba.core.exception.TeaException; import darabonba.core.interceptor.ConfigurationInterceptor; import darabonba.core.interceptor.InterceptorContext; public class EndpointInterceptor implements ConfigurationInterceptor { private final ClientLogger logger = new ClientLogger(EndpointInterceptor.class); protected final static class EndpointRule { public final static String Regional = "regional"; public final static String SEPARATOR = "-"; } @Override public TeaConfiguration modifyConfiguration(InterceptorContext context, AttributeMap attributes) { logger.verbose("Endpoint pre-process begin."); TeaRequest request = context.teaRequest(); TeaConfiguration configuration = context.configuration(); if (!StringUtils.isEmpty(configuration.endpoint())) { return configuration; } if (!StringUtils.isEmpty(configuration.region()) && !request.endpointMap().isEmpty() && request.endpointMap().containsKey(configuration.region())) { configuration.setEndpoint(request.endpointMap().get(configuration.region())); return configuration; } String endpointType = StringUtils.EMPTY; if (!StringUtils.isEmpty(configuration.endpointType()) && !configuration.endpointType().equals(EndpointType.PUBLIC)) { endpointType = EndpointRule.SEPARATOR + configuration.endpointType(); } if (request.endpointRule().equals(EndpointRule.Regional)) { if (StringUtils.isEmpty(configuration.region())) { throw new PopClientException("RegionId is empty, please set a valid RegionId", new RuntimeException("RegionId is empty, please set a valid RegionId")); } configuration.setEndpoint(String.format("%s%s.%s.aliyuncs.com", request.product(), endpointType, configuration.region())); } else { configuration.setEndpoint(String.format("%s%s.aliyuncs.com", request.product(), endpointType)); } return configuration; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/httpRequest/HttpReqInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.httpRequest; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.signature.SignerParams; import com.aliyun.core.http.*; import com.aliyun.sdk.gateway.pop.Configuration; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.auth.SignatureComposer; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.provider.AnonymousCredentialProvider; import com.aliyun.sdk.gateway.pop.auth.signer.PopSigner; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.core.utils.StringUtils; import darabonba.core.RequestStyle; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.exception.TeaException; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.utils.CommonUtil; import darabonba.core.utils.ModelUtil; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import static com.aliyun.core.utils.EncodeUtil.hexEncode; public class HttpReqInterceptor implements HttpRequestInterceptor { private final ClientLogger logger = new ClientLogger(HttpReqInterceptor.class); @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); HttpRequest httpRequest = context.httpRequest(); TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V3 && signer.getSignerVersion() != SignatureVersion.V4 && !request.style().equals(RequestStyle.SSE)) { return httpRequest; } String date = CommonUtil.getTimestamp(); HttpMethod method = Optional.ofNullable(configuration.method()).orElseGet(request::method); Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("x-acs-signature-nonce", CommonUtil.getNonce()), new TeaPair("x-acs-date", date) ), request.headers().toMap() ); Map<String, String> query = request.query(); InputStream bodyStream = null; byte[] body = null; String hashedRequestPayload = hexEncode(signer.hash(StringUtils.toBytes(""))); if (!CommonUtil.isUnset(request.stream())) { body = ParseUtil.readAsBytes(request.stream()); hashedRequestPayload = hexEncode(signer.hash(body)); headers.put("content-type", FormatType.RAW); bodyStream = request.stream(); if (bodyStream.markSupported()) { try { bodyStream.reset(); } catch (IOException e) { throw new TeaException(e); } } else { bodyStream = new ByteArrayInputStream(body); } } else if (!CommonUtil.isUnset(request.body())) { if (request.reqBodyType().equals(BodyType.JSON)) { if (request.body() instanceof byte[]) { body = (byte[]) request.body(); } else { body = StringUtils.toBytes(ParseUtil.toJSONString(request.body())); } hashedRequestPayload = hexEncode(signer.hash(body)); headers.put("content-type", FormatType.JSON); } else { if (request.body() instanceof byte[]) { body = (byte[]) request.body(); } else { body = StringUtils.toBytes(Objects.requireNonNull(ModelUtil.toFormString(ModelUtil.query(CommonUtil.assertAsMap(request.body()))))); } hashedRequestPayload = hexEncode(signer.hash(body)); headers.put("content-type", FormatType.FORM); } } headers.put(signer.getContent(), hashedRequestPayload); if (!(configuration.credentialProvider() instanceof AnonymousCredentialProvider)) { ICredential credential = configuration.credentialProvider().getCredentials(); String accessKeyId = credential.accessKeyId(); String securityToken = credential.securityToken(); if (!StringUtils.isEmpty(securityToken)) { headers.put("x-acs-accesskey-id", accessKeyId); headers.put("x-acs-security-token", securityToken); } String strToSign = SignatureComposer.composeStringToSign(method, query, headers, request.pathname(), hashedRequestPayload); logger.verbose("The string to sign is: {}", strToSign); strToSign = signer.getSignerName() + "\n" + hexEncode(signer.hash(StringUtils.toBytes(strToSign))); String authorization = ""; if (signer.getSignerVersion() == SignatureVersion.V4) { Configuration config = (Configuration) clientConfiguration.option(ClientOption.SERVICE_CONFIGURATION); String region = this.getRegion(request.product(), configuration.endpoint(), configuration.region(), config.endpointSuffix()); String dateNew = date.substring(0, 10); dateNew = dateNew.replaceAll("-", ""); byte[] signingKey = this.getV4SigningKey(signer, config.signPrefix(), Optional.ofNullable(credential.accessKeySecret()).orElse(""), request.product(), region, dateNew); authorization = signer.getSignerName() + " Credential=" + Optional.ofNullable(accessKeyId).orElse("") + "/" + dateNew + "/" + region + "/" + request.product() + "/" + config.signPrefix() + "_request,SignedHeaders=" + SignatureComposer.buildSignedHeaders(headers) + ",Signature=" + hexEncode(signer.signString(strToSign, signingKey)); } else { SignerParams params = SignerParams.create(); Credential newCredential = Credential.builder() .accessKeyId(credential.accessKeyId()) .securityToken(securityToken) .accessKeySecret(Optional.ofNullable(credential.accessKeySecret()).orElse("")) .build(); params.setCredentials(newCredential); authorization = signer.getSignerName() + " Credential=" + Optional.ofNullable(accessKeyId).orElse("") + ",SignedHeaders=" + SignatureComposer.buildSignedHeaders(headers) + ",Signature=" + signer.signString(strToSign, params); } headers.put("Authorization", authorization); logger.verbose("Authorization value is: {}", authorization); } HttpHeaders httpHeaders = new HttpHeaders(headers); httpRequest = new HttpRequest(method, ModelUtil.composeUrl(configuration.endpoint(), query, configuration.protocol(), request.pathname())); httpRequest.setHeaders(httpHeaders); if (!CommonUtil.isUnset(bodyStream)) { httpRequest.setStreamBody(bodyStream); } else if (!CommonUtil.isUnset(body)) { httpRequest.setBody(body); } return httpRequest; } private byte[] getV4SigningKey(PopSigner signer, String signPrefix, String secret, String product, String region, String date) { byte[] sc2 = signer.signString(date, signPrefix + secret); byte[] sc3 = signer.signString(region, sc2); byte[] sc4 = signer.signString(product, sc3); return signer.signString(signPrefix + "_request", sc4); } private String getRegion(String product, String endpoint, String regionId, String endpointSuffix) { if (!StringUtils.isEmpty(regionId)) { return regionId; } String region = "center"; if (StringUtils.isEmpty(product) || StringUtils.isEmpty(endpoint)) { return region; } String[] strs = endpoint.split(":"); String withoutPort = strs[0]; String preRegion = withoutPort.replace("." + endpointSuffix, ""); String[] nodes = preRegion.split("\\."); if (nodes.length == 2) { return nodes[1]; } return region; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/httpRequest/RoaHttpReqInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.httpRequest; import com.aliyun.auth.credentials.Credential; import com.aliyun.core.http.*; import com.aliyun.sdk.gateway.pop.auth.RoaSignatureComposer; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.signature.SignerParams; import com.aliyun.auth.credentials.provider.AnonymousCredentialProvider; import com.aliyun.sdk.gateway.pop.auth.signer.PopSigner; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.pop.exception.PopClientException; import darabonba.core.RequestStyle; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.utils.CommonUtil; import darabonba.core.utils.ModelUtil; import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.Optional; public class RoaHttpReqInterceptor implements HttpRequestInterceptor { private final ClientLogger logger = new ClientLogger(RoaHttpReqInterceptor.class); @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); HttpRequest httpRequest = context.httpRequest(); if (!request.style().equals(RequestStyle.ROA) && !request.style().equals(RequestStyle.RESTFUL)) { return httpRequest; } TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V1) { return httpRequest; } HttpMethod method = Optional.ofNullable(configuration.method()).orElseGet(request::method); Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("date", CommonUtil.getDateUTCString()), new TeaPair("x-acs-signature-nonce", CommonUtil.getNonce()) ), request.headers().toMap() ); String body = null; if (!CommonUtil.isUnset(request.body())) { if (request.reqBodyType().equals(BodyType.JSON)) { if (request.body() instanceof byte[]) { try { body = new String((byte[]) request.body(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new PopClientException(e); } } else { body = ParseUtil.toJSONString(request.body()); } headers.put("content-type", FormatType.JSON); } else { if (request.body() instanceof byte[]) { try { body = new String((byte[]) request.body(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new PopClientException(e); } } else { body = ModelUtil.toFormString(ModelUtil.query(CommonUtil.assertAsMap(request.body()))); } headers.put("content-type", FormatType.FORM); } } Map<String, String> query = request.query(); if (!(configuration.credentialProvider() instanceof AnonymousCredentialProvider)) { ICredential credential = configuration.credentialProvider().getCredentials(); String accessKeyId = credential.accessKeyId(); String securityToken = credential.securityToken(); if (!StringUtils.isEmpty(securityToken)) { headers.put("x-acs-accesskey-id", accessKeyId); headers.put("x-acs-security-token", securityToken); } headers.putAll(CommonUtil.buildMap( new TeaPair("x-acs-signature-method", signer.getSignerName()), new TeaPair("x-acs-signature-version", "1.0"))); String strToSign = RoaSignatureComposer.composeStringToSign(method, query, headers, request.pathname()); logger.verbose("The string to sign is: {}", strToSign); SignerParams params = SignerParams.create(); Credential newCredential = Credential.builder() .accessKeyId(credential.accessKeyId()) .securityToken(securityToken) .accessKeySecret(Optional.ofNullable(credential.accessKeySecret()).orElse("")) .build(); params.setCredentials(newCredential); String authorization = "acs " + accessKeyId + ":" + signer.signString(strToSign, params); headers.put("authorization", authorization); logger.verbose("Authorization value is: {}", authorization); } HttpHeaders httpHeaders = new HttpHeaders(headers); httpRequest = new HttpRequest(method, ModelUtil.composeUrl(configuration.endpoint(), query, configuration.protocol(), request.pathname())); httpRequest.setHeaders(httpHeaders); if (!CommonUtil.isUnset(request.body())) { httpRequest.setBody(body); } return httpRequest; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/httpRequest/RpcHttpReqInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.httpRequest; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.signature.SignerParams; import com.aliyun.sdk.gateway.pop.auth.RpcSignatureComposer; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.provider.AnonymousCredentialProvider; import com.aliyun.sdk.gateway.pop.auth.signer.PopSigner; import com.aliyun.core.http.FormatType; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.MapUtils; import com.aliyun.core.utils.StringUtils; import darabonba.core.RequestStyle; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.HttpRequestInterceptor; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.utils.CommonUtil; import darabonba.core.utils.ModelUtil; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; public class RpcHttpReqInterceptor implements HttpRequestInterceptor { private final ClientLogger logger = new ClientLogger(RpcHttpReqInterceptor.class); @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { TeaRequest request = context.teaRequest(); HttpRequest httpRequest = context.httpRequest(); if (!request.style().equals(RequestStyle.RPC)) { return httpRequest; } TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V1) { return httpRequest; } HttpMethod method = Optional.ofNullable(configuration.method()).orElseGet(request::method); Map<String, String> query = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("Timestamp", CommonUtil.getTimestamp()), new TeaPair("SignatureNonce", CommonUtil.getNonce()) ), request.query() ); Map<String, String> headers = new HashMap<>(request.headers().toMap()); Map<String, String> body = new HashMap<>(); if (!CommonUtil.isUnset(request.body())) { body = ModelUtil.query(CommonUtil.assertAsMap(request.body())); headers.put("content-type", FormatType.FORM); } Map<String, String> paramsToSign = MapUtils.concat(query, body); if (!(configuration.credentialProvider() instanceof AnonymousCredentialProvider)) { ICredential credential = configuration.credentialProvider().getCredentials(); String securityToken = credential.securityToken(); if (!StringUtils.isEmpty(securityToken)) { query.put("SecurityToken", securityToken); } query.putAll(CommonUtil.buildMap( new TeaPair("SignatureMethod", signer.getSignerName()), new TeaPair("SignatureVersion", "1.0"), new TeaPair("AccessKeyId", credential.accessKeyId()) )); paramsToSign.putAll(query); String strToSign = RpcSignatureComposer.composeStringToSign(method, paramsToSign, headers, request.pathname()); logger.verbose("The string to sign is: {}", strToSign); SignerParams params = SignerParams.create(); Credential newCredential = Credential.builder() .accessKeyId(credential.accessKeyId()) .securityToken(securityToken) .accessKeySecret(Optional.ofNullable(credential.accessKeySecret()).orElse("") + "&") .build(); params.setCredentials(newCredential); String signature = signer.signString(strToSign, params); query.put("Signature", signature); logger.verbose("Signature value is: {}", signature); } HttpHeaders httpHeaders = new HttpHeaders(headers); httpRequest = new HttpRequest(method, ModelUtil.composeUrl(configuration.endpoint(), query, configuration.protocol(), request.pathname())); httpRequest.setHeaders(httpHeaders); if (!body.isEmpty()) { httpRequest.setBody(StringUtils.toBytes(Objects.requireNonNull(ModelUtil.toFormString(body)))); } return httpRequest; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/output/FinalizedOutputInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.output; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import darabonba.core.*; import darabonba.core.exception.TeaException; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.OutputInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class FinalizedOutputInterceptor implements OutputInterceptor { private final ClientLogger logger = new ClientLogger(FinalizedOutputInterceptor.class); @Override public TeaModel modifyOutput(InterceptorContext context, AttributeMap attributes) { logger.verbose("OutputModel process begin."); TeaResponse response = context.teaResponse(); TeaRequest request = context.teaRequest(); if (context.httpResponseHandler() == null && !request.style().equals(RequestStyle.SSE)) { try { Map<String, ?> headers = response.httpResponse().getHeaders().toMap(); Map<String, Object> model = CommonUtil.buildMap( new TeaPair("body", response.deserializedBody()), new TeaPair("headers", headers), new TeaPair("statusCode", response.httpResponse().getStatusCode())); TeaModel.toModel(model, context.output()); } catch (Exception e) { throw new TeaException(e); } } return context.output(); } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/request/ReqInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.request; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.auth.signer.PopSigner; import com.aliyun.core.http.FormatType; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import darabonba.core.RequestStyle; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class ReqInterceptor implements RequestInterceptor { private final ClientLogger logger = new ClientLogger(ReqInterceptor.class); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { logger.verbose("Request pre-process begin."); TeaRequest request = context.teaRequest(); TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V3 && signer.getSignerVersion() != SignatureVersion.V4 && !request.style().equals(RequestStyle.SSE)) { return request; } Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("accept", FormatType.JSON), new TeaPair("x-acs-version", request.version()), new TeaPair("x-acs-action", request.action()), new TeaPair("user-agent", clientConfiguration.option(ClientOption.USER_AGENT)) ), request.headers().toMap() ); if (request.style().equals(RequestStyle.SSE)) { headers.put("X-DashScope-SSE", "enable"); } request.setHeaders(new HttpHeaders(headers)); return request; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/request/RoaReqInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.request; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.auth.signer.PopSigner; import com.aliyun.core.http.FormatType; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import darabonba.core.RequestStyle; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class RoaReqInterceptor implements RequestInterceptor { private final ClientLogger logger = new ClientLogger(RoaReqInterceptor.class); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { logger.verbose("Restful request pre-process begin."); TeaRequest request = context.teaRequest(); if (!request.style().equals(RequestStyle.ROA) && !request.style().equals(RequestStyle.RESTFUL)) { return request; } TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V1) { return request; } Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("accept", FormatType.JSON), new TeaPair("x-acs-version", request.version()), new TeaPair("x-acs-action", request.action()), new TeaPair("user-agent", clientConfiguration.option(ClientOption.USER_AGENT)) ), request.headers().toMap() ); if (request.style().equals(RequestStyle.SSE)) { headers.put("X-DashScope-SSE", "enable"); } request.setHeaders(new HttpHeaders(headers)); return request; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/request/RpcReqInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.request; import com.aliyun.sdk.gateway.pop.auth.SignatureVersion; import com.aliyun.sdk.gateway.pop.auth.signer.PopSigner; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import darabonba.core.RequestStyle; import darabonba.core.TeaConfiguration; import darabonba.core.TeaPair; import darabonba.core.TeaRequest; import darabonba.core.client.ClientConfiguration; import darabonba.core.client.ClientOption; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.RequestInterceptor; import darabonba.core.utils.CommonUtil; import java.util.Map; public class RpcReqInterceptor implements RequestInterceptor { private final ClientLogger logger = new ClientLogger(RpcReqInterceptor.class); @Override public TeaRequest modifyRequest(InterceptorContext context, AttributeMap attributes) { logger.verbose("RPC request pre-process begin."); TeaRequest request = context.teaRequest(); if (!request.style().equals(RequestStyle.RPC)) { return request; } TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); PopSigner signer = (PopSigner) clientConfiguration.option(ClientOption.SIGNER); if (signer.getSignerVersion() != SignatureVersion.V1) { return request; } Map<String, String> query = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("Action", request.action()), new TeaPair("Format", "JSON"), new TeaPair("Version", request.version()) ), request.query() ); Map<String, String> headers = CommonUtil.merge(String.class, CommonUtil.buildMap( new TeaPair("x-acs-version", request.version()), new TeaPair("x-acs-action", request.action()), new TeaPair("user-agent", clientConfiguration.option(ClientOption.USER_AGENT)) ), request.headers().toMap() ); if (request.style().equals(RequestStyle.SSE)) { headers.put("X-DashScope-SSE", "enable"); } request.setQuery(query).setHeaders(new HttpHeaders(headers)); return request; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/response/PopResInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.response; import com.aliyun.core.http.BodyType; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.core.utils.StringUtils; import darabonba.core.TeaResponse; import darabonba.core.exception.TeaException; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; import java.io.ByteArrayInputStream; public class PopResInterceptor implements ResponseInterceptor { private final ClientLogger logger = new ClientLogger(PopResInterceptor.class); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { logger.verbose("PopResponse process begin."); TeaResponse teaResponse = context.teaResponse(); if (teaResponse.success()) { HttpResponse httpResponse = teaResponse.httpResponse(); Object response = null; String bodyStr; try { switch (context.teaRequest().bodyType()) { case BodyType.BYTE: response = httpResponse.getBodyAsByteArray(); break; case BodyType.BINARY: byte[] bytes = httpResponse.getBodyAsByteArray(); response = new ByteArrayInputStream(bytes); break; case BodyType.JSON: bodyStr = httpResponse.getBodyAsString(); if (!StringUtils.isEmpty(bodyStr)) { response = CommonUtil.assertAsMap(ParseUtil.readAsJSON(bodyStr)); } break; case BodyType.ARRAY: bodyStr = httpResponse.getBodyAsString(); if (!StringUtils.isEmpty(bodyStr)) { response = CommonUtil.assertAsArray(ParseUtil.readAsJSON(httpResponse.getBodyAsString())); } break; default: bodyStr = httpResponse.getBodyAsString(); response = bodyStr; } teaResponse.setDeserializedBody(response); } catch (Exception e) { teaResponse.setException(new TeaException("Process response body error!", e)); } finally { httpResponse.close(); } } return teaResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/interceptor/response/TeaResponseInterceptor.java
package com.aliyun.sdk.gateway.pop.interceptor.response; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.BaseUtils; import com.aliyun.core.utils.ParseUtil; import com.aliyun.core.utils.StringUtils; import com.aliyun.sdk.gateway.pop.exception.PopClientException; import com.aliyun.sdk.gateway.pop.exception.PopServerException; import darabonba.core.RequestStyle; import darabonba.core.TeaRequest; import darabonba.core.TeaResponse; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.sse.Event; import darabonba.core.sse.SSEHttpResponseHandler; import darabonba.core.utils.CommonUtil; import java.util.HashMap; import java.util.Map; public class TeaResponseInterceptor implements ResponseInterceptor { private final ClientLogger logger = new ClientLogger(PopResInterceptor.class); @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { logger.verbose("HttpResponse process begin."); HttpResponse httpResponse = context.httpResponse(); TeaRequest request = context.teaRequest(); TeaResponse teaResponse = new TeaResponse(); teaResponse.setHttpResponse(httpResponse); teaResponse.setSuccess(CommonUtil.is2xx(httpResponse.getStatusCode())); if (CommonUtil.isNot2xx(httpResponse.getStatusCode())) { Map<String, Object> errMsg = new HashMap<>(); errMsg.put("statusCode", httpResponse.getStatusCode()); if (context.httpResponseHandler() != null && request.style().equals(RequestStyle.SSE)) { String bodyStr = BaseUtils.bomAwareToString(((SSEHttpResponseHandler) context.httpResponseHandler()).getErrorBodyByteArrayUnsafe(), null); if ("text/event-stream".equals(httpResponse.getHeaderValue("content-type"))) { Event errorEvent = Event.parse(bodyStr); if ("error".equals(errorEvent.getEvent()) && !StringUtils.isEmpty(errorEvent.getData())) { Object _body = ParseUtil.readAsJSON(errorEvent.getData()); Map<String, Object> err = CommonUtil.assertAsMap(_body); errMsg.put("code", err.get("errorName")); errMsg.put("message", "code: " + err.get("errorCode") + ", " + err.get("errorMessage") + " request id: " + err.get("requestId")); errMsg.put("description", err.get("errorMessage")); errMsg.put("data", err); } else { Object requestId = httpResponse.getHeaderValue("x-acs-request-id"); Map<String, Object> err = new HashMap<>(); err.put("RequestId", requestId); errMsg.put("code", httpResponse.getStatusCode()); errMsg.put("message", bodyStr); errMsg.put("description", "Not SSE style."); errMsg.put("data", err); } } else { Object _body = ParseUtil.readAsJSON(bodyStr); Map<String, Object> err = CommonUtil.assertAsMap(_body); Object requestId = CommonUtil.defaultAny(err.get("RequestId"), err.get("requestId")); errMsg.put("code", CommonUtil.defaultAny(err.get("Code"), err.get("code"))); errMsg.put("message", "code: " + httpResponse.getStatusCode() + ", " + CommonUtil.defaultAny(err.get("Message"), err.get("message")) + " request id: " + requestId); errMsg.put("description", CommonUtil.defaultAny(err.get("Description"), err.get("description"))); errMsg.put("accessDeniedDetail", CommonUtil.defaultAny(err.get("AccessDeniedDetail"), err.get("accessDeniedDetail"))); errMsg.put("data", err); } } else if (!StringUtils.isEmpty(httpResponse.getBodyAsString())) { Object _body = ParseUtil.readAsJSON(httpResponse.getBodyAsString()); Map<String, Object> err = CommonUtil.assertAsMap(_body); Object requestId = CommonUtil.defaultAny(err.get("RequestId"), err.get("requestId")); errMsg.put("code", CommonUtil.defaultAny(err.get("Code"), err.get("code"))); errMsg.put("message", "code: " + httpResponse.getStatusCode() + ", " + CommonUtil.defaultAny(err.get("Message"), err.get("message")) + " request id: " + requestId); errMsg.put("description", CommonUtil.defaultAny(err.get("Description"), err.get("description"))); errMsg.put("accessDeniedDetail", CommonUtil.defaultAny(err.get("AccessDeniedDetail"), err.get("accessDeniedDetail"))); errMsg.put("data", err); } else { Object requestId = httpResponse.getHeaderValue("x-acs-request-id"); errMsg.put("code", httpResponse.getStatusCode()); errMsg.put("message", "code: " + httpResponse.getStatusCode() + ", request id: " + requestId); errMsg.put("description", ""); } teaResponse.setException(CommonUtil.is5xx(httpResponse.getStatusCode()) ? new PopServerException(errMsg) : new PopClientException(errMsg)); } return teaResponse; } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/models/CommonRequest.java
package com.aliyun.sdk.gateway.pop.models; import com.aliyun.core.annotation.Validation; import com.aliyun.core.http.BodyType; import com.aliyun.core.http.HttpMethod; import darabonba.core.utils.CommonUtil; import java.io.InputStream; import java.util.Objects; public class CommonRequest extends Request { @Validation(required = true) private String product; @Validation(required = true) private String version; @Validation(required = true) private String action; @Validation(required = true) private String path; @Validation(required = true) private HttpMethod httpMethod; @Validation(required = true) private String requestBodyType; @Validation(required = true) private String responseBodyType; @Validation(required = true) private Boolean isFormData; private CommonRequest(Builder builder) { super(builder); this.product = builder.product; this.version = builder.version; this.action = builder.action; this.path = builder.path; this.httpMethod = builder.httpMethod; this.requestBodyType = builder.requestBodyType; this.responseBodyType = builder.responseBodyType; this.isFormData = builder.isFormData; } public static Builder builder() { return new Builder(); } public static CommonRequest create() { return builder().build(); } public String getProduct() { return product; } public String getVersion() { return version; } public String getAction() { return this.action; } public String getPath() { return this.path; } public HttpMethod getHttpMethod() { return this.httpMethod; } public String getRequestBodyType() { return requestBodyType; } public String getResponseBodyType() { return responseBodyType; } public Boolean isFormData() { return isFormData; } @Override public Builder toBuilder() { return new Builder(this); } public static final class Builder extends Request.Builder<CommonRequest, Builder> { private String product; private String version; private String action; private String path = "/"; private HttpMethod httpMethod = HttpMethod.GET; private String requestBodyType = BodyType.JSON; private String responseBodyType = BodyType.JSON; private Boolean isFormData = false; private Builder() { super(); } private Builder(CommonRequest request) { super(request); } public Builder putQueryParameters(String name, Object value) { if (!CommonUtil.isUnset(name)) { this.putQueryParameter(name, value); } return this; } public Builder putBodyParameters(String name, Object value) { if (!CommonUtil.isUnset(name)) { this.putBodyParameter(name, value); } return this; } public Builder putBodyStream(InputStream value) { if (Objects.nonNull(value)) { this.putBodyParameter("body", value); } return this; } public Builder putHeaderParameters(String name, Object value) { if (!CommonUtil.isUnset(name)) { this.putHeaderParameter(name, value); } return this; } public Builder product(String product) { this.product = product; return this; } public Builder version(String version) { this.version = version; return this; } public Builder action(String action) { this.action = action; return this; } public Builder path(String path) { this.path = path; return this; } public Builder httpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } public Builder requestBodyType(String requestBodyType) { this.requestBodyType = requestBodyType; return this; } public Builder responseBodyType(String responseBodyType) { this.responseBodyType = responseBodyType; return this; } public Builder isFormData(boolean isFormData) { this.isFormData = isFormData; return this; } @Override public CommonRequest build() { return new CommonRequest(this); } } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/models/CommonResponse.java
package com.aliyun.sdk.gateway.pop.models; import com.aliyun.core.annotation.NameInMap; public class CommonResponse extends Response { @NameInMap("headers") private java.util.Map<String, String> headers; @NameInMap("body") private Object body; private CommonResponse(BuilderImpl builder) { super(builder); this.headers = builder.headers; this.body = builder.body; } public static CommonResponse create() { return new BuilderImpl().build(); } @Override public Builder toBuilder() { return new BuilderImpl(this); } /** * @return headers */ public java.util.Map<String, String> getHeaders() { return this.headers; } /** * @return body */ public Object getBody() { return this.body; } public interface Builder extends Response.Builder<CommonResponse, Builder> { Builder headers(java.util.Map<String, String> headers); Builder body(Object body); @Override CommonResponse build(); } private static final class BuilderImpl extends Response.BuilderImpl<CommonResponse, Builder> implements Builder { private java.util.Map<String, String> headers; private Object body; private BuilderImpl() { super(); } private BuilderImpl(CommonResponse response) { super(response); this.headers = response.headers; this.body = response.body; } /** * headers. */ @Override public Builder headers(java.util.Map<String, String> headers) { this.headers = headers; return this; } /** * body. */ @Override public Builder body(Object body) { this.body = body; return this; } @Override public CommonResponse build() { return new CommonResponse(this); } } }
0
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop
java-sources/com/aliyun/aliyun-gateway-pop/0.3.2-beta/com/aliyun/sdk/gateway/pop/models/Request.java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.gateway.pop.models; import darabonba.core.RequestModel; public abstract class Request extends RequestModel { protected Request(Builder<?, ?> builder) { super(builder); } public abstract Builder toBuilder(); protected abstract static class Builder<ProviderT extends Request, BuilderT extends Builder> extends BuilderImpl<ProviderT, BuilderT> { protected Builder() { } protected Builder(Request request) { } } }