index
int64
repo_id
string
file_path
string
content
string
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/Response.java
package com.aliyun.sdk.gateway.pop.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-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/policy/POPUserAgentPolicy.java
package com.aliyun.sdk.gateway.pop.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("pop.gateway.version"); } catch (IOException e) { e.printStackTrace(); } } public static String getDefaultUserAgentSuffix() { return "aliyun-gateway-pop: " + gatewayVersion; } }
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/sse/ResponseBodyIterator.java
package com.aliyun.sdk.gateway.pop.sse; import darabonba.core.TeaModel; import darabonba.core.sse.SSEResponseIterator; public class ResponseBodyIterator extends SSEResponseIterator<String> { ResponseBodyIterator() { } public static ResponseBodyIterator create() { return new ResponseBodyIterator(); } @Override protected String toModel(String data) { return (String) TeaModel.confirmType(String.class, data); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/BaseClientBuilder.java
package com.aliyun.sdk.gateway.sls; import com.aliyun.sdk.gateway.sls.internal.interceptor.*; import com.aliyun.sdk.gateway.sls.policy.SLSUserAgentPolicy; 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.util.Optional; import static darabonba.core.EndpointType.*; public abstract class BaseClientBuilder<BuilderT extends IClientBuilder<BuilderT, ClientT>, ClientT> extends TeaClientBuilder<BuilderT, ClientT> { @Override protected String serviceName() { return "SLS"; } 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, SLSUserAgentPolicy.getDefaultUserAgentSuffix())); } @Override protected ClientConfiguration finalizeServiceConfiguration(ClientConfiguration configuration) { //interceptor InterceptorChain chain = InterceptorChain.create(); // chain.addRequestInterceptor(new TransformRequestBodyInterceptor()); chain.addHttpRequestInterceptor(new MakeMutableHttpRequestInterceptor()); chain.addHttpRequestInterceptor(new GenerateUrlInterceptor()); chain.addHttpRequestInterceptor(new SigningInterceptor()); chain.addResponseInterceptor(new MakeMutableResponseInterceptor()); chain.addResponseInterceptor(new ResponseBodyInterceptor()); chain.addOutputInterceptor(new FinalizedOutputInterceptor()); configuration.setOption(ClientOption.INTERCEPTOR_CHAIN, chain); configuration.setOption(ClientOption.HTTP_PROTOCOL, resolveHttpProtocol(configuration)); //endpoint configuration.setOption(ClientOption.ENDPOINT, resolveEndpoint(configuration)); return configuration; } private String resolveHttpProtocol(ClientConfiguration config) { return Optional.ofNullable(config.option(ClientOption.HTTP_PROTOCOL)) .orElse("http"); } private String resolveEndpoint(ClientConfiguration config) { return Optional.ofNullable(config.option(ClientOption.ENDPOINT)) .orElseGet(() -> endpointFromRegion(config)); } private static String getShareEndpoint(String region) { if ("cn-hangzhou-corp".equals(region) || "cn-shanghai-corp".equals(region)) { return region + ".sls.aliyuncs.com"; } else if ("cn-zhangbei-corp".equals(region)) { return "zhangbei-corp-share.log.aliyuncs.com"; } else { return region + "-share.log.aliyuncs.com"; } } private String endpointFromRegion(ClientConfiguration config) { final String region = config.option(ClientOption.REGION); final String type = Optional.ofNullable(config.option(ClientOption.ENDPOINT_TYPE)).orElse(PUBLIC); String endpoint; switch (type) { case INTRANET: endpoint = region + "-intranet.log.aliyuncs.com"; break; case SHARE: endpoint = getShareEndpoint(region); break; case ACCELERATE: endpoint = "log-global.aliyuncs.com"; break; case PUBLIC: default: endpoint = region + ".log.aliyuncs.com"; break; } return endpoint; } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/Configuration.java
package com.aliyun.sdk.gateway.sls; 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-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/auth
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/auth/signer/DefaultSLSSigner.java
package com.aliyun.sdk.gateway.sls.auth.signer; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.signature.SignerParams; 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 com.aliyun.core.utils.StringUtils; import darabonba.core.TeaRequest; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; public class DefaultSLSSigner implements SLSSigner { private static final String SLS_PREFIX = "x-log-"; private static final String ACS_PREFIX = "x-acs-"; 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 = "LOG "; @Override public HttpRequest sign(TeaRequest request, HttpRequest httpRequest, SignerParams params) { final ICredential cred = params.credentials(); httpRequest.getHeaders().set("x-log-signaturemethod", "hmac-sha1"); if (cred.securityToken() != null && !cred.securityToken().isEmpty()) { httpRequest.getHeaders().set("x-acs-security-token", cred.securityToken()); } String signature = buildSignature( cred.accessKeySecret(), request.method().toString(), request.pathname(), httpRequest.getHeaders(), request.query()); httpRequest.getHeaders().set(AUTHORIZATION, composeRequestAuthorization(cred.accessKeyId(), signature)); return httpRequest; } 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) { StringBuilder canonicalString = new StringBuilder(); canonicalString.append(method).append(NEW_LINE); TreeMap<String, String> headersToSign = new TreeMap<>(); for (HttpHeader header : headers) { 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(SLS_PREFIX) || lowerKey.startsWith(ACS_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(SLS_PREFIX) || key.startsWith(ACS_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)); return canonicalString.toString(); } private static String buildCanonicalizedResource(String resourcePath, Map<String, String> parameters) { StringBuilder builder = new StringBuilder(); if (!StringUtils.isEmpty(resourcePath) && resourcePath.contains("?")) { int index = resourcePath.lastIndexOf("?"); builder.append(resourcePath.substring(0, index)); } else { builder.append(resourcePath); } if (parameters != null) { String[] parameterNames = parameters.keySet().toArray(new String[0]); Arrays.sort(parameterNames); char separator = '?'; for (String paramName : parameterNames) { builder.append(separator); builder.append(paramName); String paramValue = parameters.get(paramName); if (paramValue != null) { builder.append("=").append(paramValue); } separator = '&'; } } return builder.toString(); } private static String computeSignature(String key, String data) { try { Mac mac = SignAlgorithmHmacSHA1.HmacSHA1.getMac(); mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), SignAlgorithmHmacSHA1.HmacSHA1.toString())); byte[] signData = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64Util.encodeToString(signData); } 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) { String canonicalString = buildCanonicalString(httpMethod, resourcePath, headers, query); return computeSignature(secretAccessKey, canonicalString); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/auth
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/auth/signer/SLSSigner.java
package com.aliyun.sdk.gateway.sls.auth.signer; import com.aliyun.auth.signature.Signer; import com.aliyun.auth.signature.SignerParams; import com.aliyun.core.http.HttpRequest; import darabonba.core.TeaRequest; public interface SLSSigner extends Signer { HttpRequest sign(TeaRequest request, HttpRequest httpRequest, SignerParams params); }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/exception/SLSException.java
package com.aliyun.sdk.gateway.sls.exception; import darabonba.core.exception.ServerException; public class SLSException extends ServerException { private String errorCode; private String errorMessage; private String requestId; public SLSException(String errorCode, String errorMessage, String requestId) { this.errorCode = errorCode; this.errorMessage = errorMessage; this.requestId = requestId; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public String getMessage() { return errorMessage + "\n[Code]: " + errorCode + "\n[RequestId]: " + requestId; } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/HttpUtil.java
package com.aliyun.sdk.gateway.sls.internal; import java.io.UnsupportedEncodingException; 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); } } /** * 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(); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/AttributeKey.java
package com.aliyun.sdk.gateway.sls.internal.interceptor; import com.aliyun.core.utils.AttributeMap; 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<String> REQUEST_BODY = new AttributeKey<>(String.class); protected AttributeKey(Class<T> valueType) { super(valueType); } protected AttributeKey(UnsafeValueType unsafeValueType) { super(unsafeValueType); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/FinalizedOutputInterceptor.java
package com.aliyun.sdk.gateway.sls.internal.interceptor; 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 { @Override public TeaModel modifyOutput(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); Map<String, Object> model = CommonUtil.buildMap( new TeaPair("body", response.deserializedBody()), new TeaPair("headers", response.httpResponse().getHeaders().toMap())); try { TeaModel.toModel(model, context.output()); } catch (Exception e) { throw new TeaException(e); } return context.output(); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/GenerateUrlInterceptor.java
package com.aliyun.sdk.gateway.sls.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.sls.internal.HttpUtil; 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.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 TeaRequest request = context.teaRequest(); HttpRequest httpRequest = context.httpRequest(); //scheme String scheme = configuration.option(ClientOption.HTTP_PROTOCOL); //project name String project = Optional.ofNullable(request.hostMap().get("project")).orElse(""); //host & path String host = configuration.option(ClientOption.ENDPOINT); String path = request.pathname(); if (!StringUtils.isEmpty(project)) { host = String.format("%s.%s", project, host); } httpRequest.setHeader("Host", host); if (!StringUtils.isEmpty(path) && path.contains("?")) { int index = path.lastIndexOf("?"); String newPath = path.substring(0, index); if (index < path.length() - 1) { String[] queries = path.substring(index + 1).split("&"); for (String query : queries) { int eqIndex = query.lastIndexOf("="); String key = query; String value = null; if (eqIndex != -1) { key = query.substring(0, eqIndex); if (eqIndex < query.length() - 1) { value = query.substring(eqIndex + 1); } } request.query().put(key, value); } } path = newPath; } //qeruy String queryString = HttpUtil.paramToQueryString(request.query(), "utf-8"); StringBuilder uri = new StringBuilder(); uri.append(String.format("%s://", scheme)); uri.append(host); uri.append(HttpUtil.urlEncode(path, "utf-8").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-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/MakeMutableHttpRequestInterceptor.java
package com.aliyun.sdk.gateway.sls.internal.interceptor; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import darabonba.core.TeaConfiguration; 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 org.apache.hc.core5.http.HttpHeaders; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MakeMutableHttpRequestInterceptor implements HttpRequestInterceptor { public static String md5Crypt(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance("MD5"); String res = new BigInteger(1, md.digest(bytes)).toString(16).toUpperCase(); StringBuilder zeros = new StringBuilder(); for (int i = 0; i + res.length() < 32; i++) { zeros.append("0"); } return zeros.toString() + res; } catch (NoSuchAlgorithmException e) { // never happen throw new RuntimeException("Not Supported signature method: MD5", e); } } @Override public HttpRequest modifyHttpRequest(InterceptorContext context, AttributeMap attributes) { TeaConfiguration configuration = context.configuration(); ClientConfiguration clientConfiguration = configuration.clientConfiguration(); HttpRequest httpRequest = new HttpRequest(context.teaRequest().method()); httpRequest.setHeaders(context.teaRequest().headers()); httpRequest.setHeader("x-log-apiversion", "0.6.0"); httpRequest.setHeader("user-agent", clientConfiguration.option(ClientOption.USER_AGENT)); TeaRequest request = context.teaRequest(); Object body = request.body(); if (body != null) { String bodyStr = ParseUtil.toJSONString(request.body()); httpRequest.setBody(bodyStr); httpRequest.setHeader("x-log-bodyrawsize", String.valueOf(bodyStr.length())); httpRequest.setHeader(HttpHeaders.CONTENT_MD5, md5Crypt(bodyStr.getBytes(StandardCharsets.UTF_8))); httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); } else { httpRequest.setHeader("x-log-bodyrawsize", "0"); } return httpRequest; } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/MakeMutableResponseInterceptor.java
package com.aliyun.sdk.gateway.sls.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-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/ResponseBodyInterceptor.java
package com.aliyun.sdk.gateway.sls.internal.interceptor; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.ParseUtil; import com.aliyun.sdk.gateway.sls.exception.SLSException; import com.github.luben.zstd.Zstd; import darabonba.core.TeaResponse; import darabonba.core.exception.ClientException; import darabonba.core.interceptor.InterceptorContext; import darabonba.core.interceptor.ResponseInterceptor; import darabonba.core.utils.CommonUtil; import net.jpountz.lz4.LZ4Factory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Map; import java.util.zip.Inflater; public class ResponseBodyInterceptor implements ResponseInterceptor { @Override public TeaResponse modifyResponse(InterceptorContext context, AttributeMap attributes) { TeaResponse response = context.teaResponse(); try { handleResponseBody(context, response); } catch (Exception e) { response.setException(new ClientException("Parsing response body fail", e)); } return response; } private void handleResponseBody(InterceptorContext context, TeaResponse response) { if (!response.success()) { handleResponseError(context, response); return; } byte[] body; try { body = getDecompressedBody(context, response); } catch (Exception e) { String requestId = context.httpResponse().getHeaders().getValue("x-log-requestid"); String compressType = context.httpResponse().getHeaders().getValue("x-log-compresstype"); context.teaResponse().setException(new SLSException("DecompressResponseError", "fail to decompress response body using compressType " + compressType + ", error:" + e.getMessage(), requestId)); return; } if (body == null) { body = new byte[0]; } String respBodyType = context.teaRequest().bodyType(); if ("json".equals(respBodyType) || "array".equals(respBodyType)) { if (body.length == 0) { return; // todo: should we just throw an exception here? } response.setDeserializedBody(ParseUtil.parseJSON(new String(body))); return; } if ("byte".equals(respBodyType)) { response.setDeserializedBody(body); return; } if ("binary".equals(respBodyType)) { response.setDeserializedBody(new ByteArrayInputStream(body) ); return; } response.setDeserializedBody(new String(body)); } private void handleResponseError(InterceptorContext context, TeaResponse response) { String bodyStr = response.httpResponse().getBodyAsString(); Map<String, Object> body = CommonUtil.assertAsMap(ParseUtil.parseJSON(bodyStr)); if (body.containsKey("Error")) { Object error = body.get("Error"); Map<String, Object> errorMap = CommonUtil.assertAsMap(error); String errorCode = (String) errorMap.get("Code"); String errorMessage = (String) errorMap.get("Message"); String requestId = (String) errorMap.get("RequestId"); context.teaResponse().setException(new SLSException(errorCode, errorMessage, requestId)); return; } String requestId = context.httpResponse().getHeaders().getValue("x-log-requestid"); if (body.containsKey("errorCode")) { String errorCode = (String) body.get("errorCode"); String errorMessage = (String) body.get("errorMessage"); context.teaResponse().setException(new SLSException(errorCode, errorMessage, requestId)); return; } context.teaResponse().setException(new SLSException("InvalidResponseFormat.", bodyStr.substring(0, Math.min(128, bodyStr.length())), requestId)); } private byte[] getDecompressedBody(InterceptorContext context, TeaResponse response) throws Exception { HttpHeaders headers = context.httpResponse().getHeaders(); String bodyrawSize = headers.getValue("x-log-bodyrawsize"); String compressType = headers.getValue("x-log-compresstype"); if (CommonUtil.isUnset(bodyrawSize) || CommonUtil.isUnset(compressType)) { return response.httpResponse().getBodyAsByteArray(); } int rawSize = Integer.parseInt(bodyrawSize); if (rawSize == 0) { return new byte[0]; } return readAndDecompressBody(context, response, compressType, rawSize); } private byte[] readAndDecompressBody(InterceptorContext context, TeaResponse response, String compressType, int rawSize) throws Exception { byte[] compressed = response.httpResponse().getBodyAsByteArray(); if ("lz4".equals(compressType)) { LZ4Factory factory = LZ4Factory.fastestInstance(); byte[] decompressed = new byte[rawSize]; factory.fastDecompressor().decompress(compressed, 0, decompressed, 0, rawSize); return decompressed; } if ("zstd".equals(compressType)) { return Zstd.decompress(compressed, rawSize); } if ("gzip".equals(compressType) || "deflate".equals(compressType)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(compressed.length); Inflater decompressor = new Inflater(); try { decompressor.setInput(compressed); final byte[] buf = new byte[1024]; while (!decompressor.finished()) { int count = decompressor.inflate(buf); bos.write(buf, 0, count); } return bos.toByteArray(); } finally { decompressor.end(); } } throw new IllegalArgumentException("Unsupported compress type: " + compressType); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/internal/interceptor/SigningInterceptor.java
package com.aliyun.sdk.gateway.sls.internal.interceptor; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.provider.ICredentialProvider; import com.aliyun.auth.signature.SignerParams; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.AttributeMap; import com.aliyun.core.utils.DateUtil; import com.aliyun.sdk.gateway.sls.auth.signer.DefaultSLSSigner; import com.aliyun.sdk.gateway.sls.auth.signer.SLSSigner; 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.Date; 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 Date now = new Date(); httpRequest.setHeader("Date", DateUtil.formatRfc822Date(now)); //sign request SLSSigner signer = new DefaultSLSSigner(); ICredentialProvider provider = configuration.option(ClientOption.CREDENTIALS_PROVIDER); ICredential cred = provider.getCredentials(); SignerParams params = SignerParams.create().setCredentials(cred); return signer.sign(request, httpRequest, params); } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/models/Request.java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.gateway.sls.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 RequestModel.BuilderImpl<ProviderT, BuilderT> { protected Builder() { } protected Builder(Request request) { } } }
0
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/models/Response.java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.gateway.sls.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-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls
java-sources/com/aliyun/aliyun-gateway-sls/0.3.2-beta/com/aliyun/sdk/gateway/sls/policy/SLSUserAgentPolicy.java
package com.aliyun.sdk.gateway.sls.policy; import java.io.IOException; import java.util.Properties; public class SLSUserAgentPolicy { private static String gatewayVersion = "unknown"; static { try { Properties props = new Properties(); props.load(SLSUserAgentPolicy.class.getClassLoader().getResourceAsStream("project.properties")); gatewayVersion = props.getProperty("sls.gateway.version"); } catch (IOException e) { e.printStackTrace(); } } public static String getDefaultUserAgentSuffix() { return "aliyun-gateway-sls: " + gatewayVersion; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/ApacheAsyncHttpClient.java
package com.aliyun.httpcomponent.httpclient; import org.apache.hc.client5.http.async.methods.*; import com.aliyun.core.http.*; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.BinaryUtils; import com.aliyun.core.utils.Context; import com.aliyun.core.utils.StringUtils; import com.aliyun.httpcomponent.httpclient.implementation.ApacheAsyncHttpResponse; import com.aliyun.httpcomponent.httpclient.implementation.StreamRequestProducer; import com.aliyun.httpcomponent.httpclient.implementation.reactive.ReactiveApacheHttpResponse; import com.aliyun.httpcomponent.httpclient.implementation.reactive.ReactiveHttpResponse; import com.aliyun.httpcomponent.httpclient.implementation.reactive.ReactiveResponseConsumer; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.nio.AsyncRequestProducer; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.util.TimeValue; import org.apache.hc.core5.util.Timeout; import java.net.*; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static com.aliyun.core.http.ProxyOptions.Type.HTTP; class ApacheAsyncHttpClient implements HttpClient { private final String RESPONSE_HANDLER_KEY = "RESPONSE_HANDLER"; private final ClientLogger logger = new ClientLogger(ApacheAsyncHttpClient.class); private final CloseableHttpAsyncClient apacheHttpAsyncClient; private final Timeout connectTimeout; private final long connectionKeepAlive; ApacheAsyncHttpClient(CloseableHttpAsyncClient apacheHttpAsyncClient, Timeout connectTimeout, long connectionKeepAlive) { this.apacheHttpAsyncClient = apacheHttpAsyncClient; this.connectTimeout = connectTimeout; this.connectionKeepAlive = connectionKeepAlive; } @Override public CompletableFuture<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public CompletableFuture<HttpResponse> send(HttpRequest request, Context context) { apacheHttpAsyncClient.start(); Objects.requireNonNull(request.getHttpMethod(), "'request.getHttpMethod()' cannot be null."); Objects.requireNonNull(request.getUrl(), "'request.getUrl()' cannot be null."); Objects.requireNonNull(request.getUrl().getProtocol(), "'request.getUrl().getProtocol()' cannot be null."); if (context.getData(RESPONSE_HANDLER_KEY).isPresent() || request.getStreamBody() != null) { return sendV2(request, context); } else { return sendV1(request, context); } } @Override public void close() { if (apacheHttpAsyncClient != null) { apacheHttpAsyncClient.close(CloseMode.GRACEFUL); } } private SimpleHttpRequest toApacheAsyncRequest(HttpRequest request) throws URISyntaxException, ExecutionException, InterruptedException { final SimpleRequestBuilder apacheRequestBuilder = SimpleRequestBuilder.create(request.getHttpMethod().toString()) .setUri(request.getUrl().toURI()); final HttpHeaders headers = request.getHeaders(); for (HttpHeader httpHeader : headers) { apacheRequestBuilder.setHeader(httpHeader.getName(), httpHeader.getValue()); } switch (request.getHttpMethod()) { case GET: case HEAD: case DELETE: return apacheRequestBuilder.build(); default: if (request.getBody() != null) { ContentType type; if (StringUtils.isEmpty(headers.getValue("content-type"))) { type = ContentType.APPLICATION_FORM_URLENCODED; } else { String[] ct = headers.getValue("content-type").split(";"); if (ct.length > 1) { type = ContentType.create(ct[0].trim(), ct[1].replace("charset=", "").trim()); } else { type = ContentType.create(ct[0].trim()); } } apacheRequestBuilder.setBody(BinaryUtils.copyAllBytesFrom(request.getBody()), type); } return apacheRequestBuilder.build(); } } private AsyncRequestProducer toApacheRequestProducer(HttpRequest request) throws URISyntaxException, ExecutionException, InterruptedException { SimpleHttpRequest simpleHttpRequest = toApacheAsyncRequest(request); simpleHttpRequest.setConfig(new ApacheIndividualRequestBuilder(request, connectTimeout, connectionKeepAlive).build()); if (request.getStreamBody() != null) { return StreamRequestProducer.create(simpleHttpRequest, request.getStreamBody()); } else { return SimpleRequestProducer.create(simpleHttpRequest); } } private CompletableFuture<HttpResponse> sendV1(HttpRequest request, Context context) { SimpleHttpRequest apacheRequest; try { apacheRequest = toApacheAsyncRequest(request); } catch (URISyntaxException | ExecutionException | InterruptedException e) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must can convert to a valid URI", e)); } apacheRequest.setConfig(new ApacheIndividualRequestBuilder(request, connectTimeout, connectionKeepAlive).build()); CompletableFuture<SimpleHttpResponse> cf = new CompletableFuture<>(); final Future<SimpleHttpResponse> future = apacheHttpAsyncClient.execute( apacheRequest, new FutureCallback<SimpleHttpResponse>() { @Override public void completed(SimpleHttpResponse response) { cf.complete(response); } @Override public void failed(final Exception ex) { cf.completeExceptionally(ex); } @Override public void cancelled() { cf.cancel(true); } }); return cf.thenApply(simpleHttpResponse -> new ApacheAsyncHttpResponse(request, simpleHttpResponse)); } private CompletableFuture<HttpResponse> sendV2(HttpRequest request, Context context) { AsyncRequestProducer apacheRequestProducer; try { apacheRequestProducer = toApacheRequestProducer(request); } catch (URISyntaxException | ExecutionException | InterruptedException e) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must can convert to a valid URI", e)); } if (context.getData(RESPONSE_HANDLER_KEY).isPresent()) { CompletableFuture<ReactiveApacheHttpResponse> cf = new CompletableFuture<>(); final Future<ReactiveApacheHttpResponse> future = apacheHttpAsyncClient.execute( apacheRequestProducer, new ReactiveResponseConsumer((HttpResponseHandler) context.getData(RESPONSE_HANDLER_KEY).get()), new FutureCallback<ReactiveApacheHttpResponse>() { @Override public void completed(ReactiveApacheHttpResponse response) { cf.complete(response); } @Override public void failed(final Exception ex) { cf.completeExceptionally(ex); } @Override public void cancelled() { cf.cancel(true); } }); return cf.thenApply(reactiveHttpResponse -> new ReactiveHttpResponse(request, reactiveHttpResponse)); } else { CompletableFuture<SimpleHttpResponse> cf = new CompletableFuture<>(); final Future<SimpleHttpResponse> future = apacheHttpAsyncClient.execute( apacheRequestProducer, SimpleResponseConsumer.create(), new FutureCallback<SimpleHttpResponse>() { @Override public void completed(SimpleHttpResponse response) { cf.complete(response); } @Override public void failed(final Exception ex) { cf.completeExceptionally(ex); } @Override public void cancelled() { cf.cancel(true); } }); return cf.thenApply(simpleHttpResponse -> new ApacheAsyncHttpResponse(request, simpleHttpResponse)); } } private static final class ApacheIndividualRequestBuilder { private final ClientLogger logger = new ClientLogger(ApacheIndividualRequestBuilder.class); private final HttpRequest request; private final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); private final Timeout connectTimeout; private final long connectionKeepAlive; public ApacheIndividualRequestBuilder(HttpRequest request, Timeout connectTimeout, long connectionKeepAlive) { this.request = request; this.connectTimeout = connectTimeout; this.connectionKeepAlive = connectionKeepAlive; } ApacheIndividualRequestBuilder setConnectTimeout() { if (request.getConnectTimeout() != null) requestConfigBuilder.setConnectTimeout(duration2Timeout(request.getConnectTimeout())); else { requestConfigBuilder.setConnectTimeout(connectTimeout); } return this; } ApacheIndividualRequestBuilder setResponseTimeout() { if (request.getResponseTimeout() != null) requestConfigBuilder.setResponseTimeout(duration2Timeout(request.getResponseTimeout())); return this; } // if not set, based on setRoutePlanner config ApacheIndividualRequestBuilder setProxy() { ProxyOptions proxyOptions = request.getProxyOptions(); if (proxyOptions != null && proxyOptions.getType() == HTTP) { if (proxyOptions.getNonProxyHosts() == null || !proxyOptions.getNonProxyHosts().contains(request.getUrl().getHost())) { InetSocketAddress inetSocketAddress = proxyOptions.getAddress(); requestConfigBuilder.setProxy(new HttpHost( proxyOptions.getScheme(), inetSocketAddress.getAddress(), inetSocketAddress.getHostString(), inetSocketAddress.getPort() )); } else { requestConfigBuilder.setProxy(null); } } return this; } RequestConfig build() { this.setConnectTimeout().setResponseTimeout().setProxy(); return requestConfigBuilder.setConnectionKeepAlive(TimeValue.of(connectionKeepAlive, TimeUnit.MILLISECONDS)).build(); } private Timeout duration2Timeout(Duration duration) { return Timeout.ofMilliseconds(duration.toMillis()); } } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/ApacheAsyncHttpClientBuilder.java
package com.aliyun.httpcomponent.httpclient; import com.aliyun.core.http.HttpClient; import com.aliyun.core.http.ProxyOptions; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.Configuration; import com.aliyun.httpcomponent.httpclient.implementation.CompositeX509TrustManager; import com.aliyun.httpcomponent.httpclient.implementation.SdkConnectionKeepAliveStrategy; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.CredentialsProvider; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; import org.apache.hc.client5.http.impl.async.HttpAsyncClients; import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; import org.apache.hc.client5.http.ssl.DefaultHostnameVerifier; import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy; import org.apache.hc.core5.http.nio.ssl.TlsStrategy; import org.apache.hc.core5.reactor.IOReactorConfig; import org.apache.hc.core5.util.Timeout; import javax.net.ssl.*; import java.net.*; import java.security.KeyStore; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; public class ApacheAsyncHttpClientBuilder { private final ClientLogger logger = new ClientLogger(ApacheAsyncHttpClientBuilder.class); private HttpAsyncClientBuilder httpAsyncClientBuilder; private Duration connectionTimeout; private Duration responseTimeout; private Duration maxIdleTimeOut; private Duration keepAlive; private int maxConnections = 128; private int maxConnectionsPerRoute = 128; private Duration connectRequestTimeout; private ProxyOptions proxyOptions = null; private Configuration configuration; private static final long DEFAULT_TIMEOUT = TimeUnit.SECONDS.toMillis(20); private static final long DEFAULT_KEEP_ALIVE = TimeUnit.SECONDS.toMillis(20); private static final long DEFAULT_MAX_CONN_TIMEOUT = TimeUnit.SECONDS.toMillis(10); private static final long DEFAULT_MAX_RESPONSE_TIMEOUT = TimeUnit.SECONDS.toMillis(20); private static final long DEFAULT_MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private static final long DEFAULT_CONNECT_REQUEST_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private static final long DEFAULT_MAX_IDLE_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private X509TrustManager[] x509TrustManagers = null; private KeyManager[] keyManagers = null; private HostnameVerifier hostnameVerifier = null; private boolean ignoreSSL = false; public ApacheAsyncHttpClientBuilder() { this.httpAsyncClientBuilder = HttpAsyncClients.custom(); } public ApacheAsyncHttpClientBuilder(HttpAsyncClientBuilder httpAsyncClientBuilder) { this.httpAsyncClientBuilder = Objects.requireNonNull(httpAsyncClientBuilder, "'httpAsyncClientBuilder' cannot be null."); } public ApacheAsyncHttpClientBuilder connectionTimeout(Duration connectionTimeout) { // setConnectionTimeout can be null this.connectionTimeout = connectionTimeout; return this; } public ApacheAsyncHttpClientBuilder responseTimeout(Duration responseTimeout) { this.responseTimeout = responseTimeout; return this; } public ApacheAsyncHttpClientBuilder maxIdleTimeOut(Duration maxIdleTimeOut) { this.maxIdleTimeOut = maxIdleTimeOut; return this; } public ApacheAsyncHttpClientBuilder keepAlive(Duration keepAlive) { this.keepAlive = keepAlive; return this; } public ApacheAsyncHttpClientBuilder maxConnections(int maxConnections) { this.maxConnections = maxConnections; return this; } public ApacheAsyncHttpClientBuilder maxConnectionsPerRoute(int maxConnectionsPerRoute) { this.maxConnectionsPerRoute = maxConnectionsPerRoute; return this; } public ApacheAsyncHttpClientBuilder connectRequestTimeout(Duration connectRequestTimeout) { this.connectRequestTimeout = connectRequestTimeout; return this; } public ApacheAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public ApacheAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } public ApacheAsyncHttpClientBuilder x509TrustManagers(X509TrustManager[] x509TrustManagers) { this.x509TrustManagers = x509TrustManagers; return this; } public ApacheAsyncHttpClientBuilder keyManagers(KeyManager[] keyManagers) { this.keyManagers = keyManagers; return this; } public ApacheAsyncHttpClientBuilder hostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } public ApacheAsyncHttpClientBuilder ignoreSSL(boolean ignoreSSL) { this.ignoreSSL = ignoreSSL; return this; } public HttpClient build() { // requestConfig httpAsyncClientBuilder.setDefaultRequestConfig(defaultRequestConfig()); // connectionManager config PoolingAsyncClientConnectionManager cm = connectionPoolConfig(); httpAsyncClientBuilder.setConnectionManager(cm); // proxy Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; if (proxyOptions == null && buildConfiguration != Configuration.NONE) proxyOptions = ProxyOptions.fromConfiguration(buildConfiguration); if (proxyOptions != null) { InetSocketAddress inetSocketAddress = proxyOptions.getAddress(); ProxyOptions.Type type = proxyOptions.getType(); switch (type) { case SOCKS4: case SOCKS5: IOReactorConfig.Builder config = IOReactorConfig.custom() .setSocksProxyAddress(inetSocketAddress); if (proxyOptions.getUsername() != null) { config.setSocksProxyUsername(proxyOptions.getUsername()) .setSocksProxyPassword(proxyOptions.getPassword()); } httpAsyncClientBuilder.setIOReactorConfig(config.build()); break; default: httpAsyncClientBuilder.setProxy(new HttpHost( proxyOptions.getScheme(), inetSocketAddress.getAddress(), inetSocketAddress.getHostString(), inetSocketAddress.getPort() )); } if (proxyOptions.getUsername() != null) { CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create() .add(new AuthScope(proxyOptions.getAddress().getHostString(), proxyOptions.getAddress().getPort()), proxyOptions.getUsername(), proxyOptions.getPassword().toCharArray()) .build(); httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } // httpAsyncClientBuilder.setRoutePlanner(new SdkProxyRoutePlanner( // proxyOptions.getScheme(), // proxyOptions.getAddress(), // proxyOptions.getNonProxyHosts())); } // httpAsyncClientBuilder httpAsyncClientBuilder // Connection reuse policy, i.e. whether it can keepAlive .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE) // Set how long a connection can remain idle before it is reused, maximum idle time .setKeepAliveStrategy(buildKeepAliveStrategy()) // Set the connections in the connection pool to clear the maximum idle time using a background thread .evictIdleConnections(getTimeoutMillis(this.maxIdleTimeOut, "idle")) // Set up to use background threads to clear expired connections .evictExpiredConnections() // Disable redirects .disableRedirectHandling() // Disable reconnect policy .disableAutomaticRetries() // SDK will set the user agent header in the pipeline. Don't let Apache waste time .setUserAgent(""); return new ApacheAsyncHttpClient(httpAsyncClientBuilder.build(), getTimeoutMillis(this.connectionTimeout, "connect"), this.keepAlive == null ? DEFAULT_KEEP_ALIVE : this.keepAlive.toMillis()); } private PoolingAsyncClientConnectionManager connectionPoolConfig() { // set TrustManager PoolingAsyncClientConnectionManagerBuilder cmb = PoolingAsyncClientConnectionManagerBuilder.create(); List<TrustManager> trustManagerList = new ArrayList<TrustManager>(); X509TrustManager[] trustManagers = this.x509TrustManagers; if (null != trustManagers) { trustManagerList.addAll(Arrays.asList(trustManagers)); } TrustManagerFactory tmf = null; try { // get trustManager using default certification from jdk tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); trustManagerList.addAll(Arrays.asList(tmf.getTrustManagers())); } catch (Exception e) { throw logger.logExceptionAsError(new RuntimeException(e)); } final List<X509TrustManager> finalTrustManagerList = new ArrayList<X509TrustManager>(); for (TrustManager tm : trustManagerList) { if (tm instanceof X509TrustManager) { finalTrustManagerList.add((X509TrustManager) tm); } } CompositeX509TrustManager compositeX509TrustManager = new CompositeX509TrustManager(finalTrustManagerList); compositeX509TrustManager.setIgnoreSSLCert(this.ignoreSSL); // set KeyManager KeyManager[] keyManagers = null; if (this.keyManagers != null) { keyManagers = this.keyManagers; } // Generate SSLContext by TrustManager and KeyManager SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, new TrustManager[]{compositeX509TrustManager}, null); } catch (Exception e) { throw logger.logExceptionAsError(new RuntimeException(e)); } // set HostnameVerifier HostnameVerifier hostnameVerifier = null; if (this.ignoreSSL) { hostnameVerifier = new NoopHostnameVerifier(); } else if (this.hostnameVerifier != null) { hostnameVerifier = this.hostnameVerifier; } else { hostnameVerifier = new DefaultHostnameVerifier(); } // set connection pool TlsStrategy TlsStrategy tlsStrategy = ClientTlsStrategyBuilder .create() .setSslContext(sslContext) .setHostnameVerifier(hostnameVerifier) .build(); cmb.setTlsStrategy(tlsStrategy); // Set the number of connection pool connections and generate a connection manager PoolingAsyncClientConnectionManager cm = cmb // Specify the maximum total connection value .setMaxConnTotal(getMaxConnTotal(this.maxConnections)) // Specify the maximum connection value for each route .setMaxConnPerRoute(getMaxConnTotal(this.maxConnectionsPerRoute)) .build(); return cm; } private RequestConfig defaultRequestConfig() { RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(getTimeoutMillis(this.connectRequestTimeout, "connectionRequest")) .setConnectTimeout(getTimeoutMillis(this.connectionTimeout, "connect")) .setResponseTimeout(getTimeoutMillis(this.responseTimeout, "response")) .setDefaultKeepAlive(this.keepAlive == null ? DEFAULT_KEEP_ALIVE : this.keepAlive.toMillis(), TimeUnit.MILLISECONDS); return requestConfigBuilder.setRedirectsEnabled(false).build(); } private static Timeout getTimeoutMillis(Duration timeout, String name) { if (timeout == null) { switch (name) { case "idle": return Timeout.ofMilliseconds(DEFAULT_MAX_IDLE_TIMEOUT); case "connect": return Timeout.ofMilliseconds(DEFAULT_MAX_CONN_TIMEOUT); case "response": return Timeout.ofMilliseconds(DEFAULT_MAX_RESPONSE_TIMEOUT); case "connectionRequest": return Timeout.ofMilliseconds(DEFAULT_CONNECT_REQUEST_TIMEOUT); default: return Timeout.ofMilliseconds(DEFAULT_TIMEOUT); } } if (timeout.isZero() || timeout.isNegative()) { return Timeout.ofMilliseconds(0); } return Timeout.ofMilliseconds(Math.max(timeout.toMillis(), DEFAULT_MINIMUM_TIMEOUT)); } private static int getMaxConnTotal(int maxConnTotal) { if (maxConnTotal <= 0) { return Runtime.getRuntime().availableProcessors() * 10; } return maxConnTotal; } private ConnectionKeepAliveStrategy buildKeepAliveStrategy() { long maxIdle = getTimeoutMillis(this.maxIdleTimeOut, "idle").toMilliseconds(); return maxIdle > 0 ? new SdkConnectionKeepAliveStrategy(maxIdle) : null; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/ApacheAsyncHttpClientProvider.java
package com.aliyun.httpcomponent.httpclient; import com.aliyun.core.http.HttpClient; import com.aliyun.core.http.HttpClientProvider; import com.aliyun.core.utils.HttpClientOptions; public class ApacheAsyncHttpClientProvider implements HttpClientProvider { @Override public HttpClient createInstance() { return new ApacheAsyncHttpClientBuilder().build(); } @Override public HttpClient createInstance(HttpClientOptions clientOptions) { ApacheAsyncHttpClientBuilder builder = new ApacheAsyncHttpClientBuilder(); if(clientOptions != null) { builder.proxy(clientOptions.getProxyOptions()) .configuration(clientOptions.getConfiguration()) .responseTimeout(clientOptions.getResponseTimeout()); } return builder.build(); } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/ApacheAsyncHttpResponse.java
package com.aliyun.httpcomponent.httpclient.implementation; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.BaseUtils; import org.apache.hc.client5.http.async.methods.SimpleBody; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; import org.apache.hc.core5.http.Header; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public final class ApacheAsyncHttpResponse extends ApacheHttpResponseBase { private SimpleHttpResponse apacheResponse; public ApacheAsyncHttpResponse(HttpRequest httpRequest, SimpleHttpResponse apacheResponse) { super(httpRequest, apacheResponse.getCode(), toHeaders(apacheResponse)); this.apacheResponse = apacheResponse; } @Override public ByteBuffer getBody() { byte[] bytes = getBodyAsByteArray(); return bytes != null ? ByteBuffer.wrap(bytes) : null; } @Override public byte[] getBodyAsByteArray() { SimpleBody body = apacheResponse.getBody(); return body != null ? body.getBodyBytes() : null; } @Override public String getBodyAsString() { byte[] bytes = getBodyAsByteArray(); return bytes != null ? BaseUtils.bomAwareToString(getBodyAsByteArray(), getHeaderValue("Content-Type")) : null; } @Override public String getBodyAsString(Charset charset) { byte[] bytes = getBodyAsByteArray(); return bytes != null ? new String(getBodyAsByteArray(), charset) : null; } private static HttpHeaders toHeaders(SimpleHttpResponse response) { final HttpHeaders httpHeaders = new HttpHeaders(); Set<String> nameSet = new HashSet<>(); Header[] apacheHeaders = response.getHeaders(); for (Header header : apacheHeaders) { nameSet.add(header.getName()); } nameSet.forEach((name) -> { Header[] entityHeaders = response.getHeaders(name); List<String> values = new ArrayList<>(); for (Header entityHeader : entityHeaders) { values.add(entityHeader.getValue()); } httpHeaders.set(name, values); }); return httpHeaders; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/ApacheHttpResponseBase.java
package com.aliyun.httpcomponent.httpclient.implementation; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.http.HttpResponse; abstract class ApacheHttpResponseBase extends HttpResponse { private final int statusCode; private final HttpHeaders headers; ApacheHttpResponseBase(final HttpRequest request, int statusCode, HttpHeaders headers) { super(request); this.statusCode = statusCode; this.headers = headers; } @Override public final int getStatusCode() { return this.statusCode; } @Override public final String getHeaderValue(String name) { return this.headers.getValue(name); } @Override public final HttpHeaders getHeaders() { return this.headers; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/CompositeX509TrustManager.java
package com.aliyun.httpcomponent.httpclient.implementation; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CompositeX509TrustManager implements X509TrustManager { private final List<X509TrustManager> trustManagers; private boolean ignoreSSL = false; public boolean isIgnoreSSL() { return ignoreSSL; } public void setIgnoreSSLCert(boolean ignoreSSL) { this.ignoreSSL = ignoreSSL; } public CompositeX509TrustManager(List<X509TrustManager> trustManagers) { this.trustManagers = trustManagers; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // do nothing } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (ignoreSSL) { return; } for (X509TrustManager trustManager : trustManagers) { try { trustManager.checkServerTrusted(chain, authType); return; // someone trusts them. success! } catch (CertificateException e) { // maybe someone else will trust them } } throw new CertificateException("None of the TrustManagers trust this certificate chain"); } @Override public X509Certificate[] getAcceptedIssuers() { List<X509Certificate> certificates = new ArrayList<X509Certificate>(); for (X509TrustManager trustManager : trustManagers) { certificates.addAll(Arrays.asList(trustManager.getAcceptedIssuers())); } X509Certificate[] certificatesArray = new X509Certificate[certificates.size()]; return certificates.toArray(certificatesArray); } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/SdkConnectionKeepAliveStrategy.java
package com.aliyun.httpcomponent.httpclient.implementation; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.util.TimeValue; public class SdkConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy { private final long maxIdleTime; public SdkConnectionKeepAliveStrategy(long maxIdleTime) { this.maxIdleTime = maxIdleTime; } @Override public TimeValue getKeepAliveDuration( HttpResponse response, HttpContext context) { // If there's a Keep-Alive timeout directive in the response and it's // shorter than our configured max, honor that. Otherwise go with the // configured maximum. long duration = DefaultConnectionKeepAliveStrategy.INSTANCE .getKeepAliveDuration(response, context).getDuration(); if (0 < duration && duration < maxIdleTime) { return TimeValue.ofMilliseconds(duration); } return TimeValue.ofMilliseconds(maxIdleTime); } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/SdkProxyRoutePlanner.java
package com.aliyun.httpcomponent.httpclient.implementation; import java.net.InetSocketAddress; import java.util.regex.Pattern; import com.aliyun.core.utils.StringUtils; import org.apache.hc.client5.http.impl.DefaultSchemePortResolver; import org.apache.hc.client5.http.impl.routing.DefaultRoutePlanner; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.protocol.HttpContext; /** * SdkProxyRoutePlanner delegates a Proxy Route Planner from the settings instead of the * system properties. It will use the proxy created from proxyHost and proxyPort and * filter the hosts who matches nonProxyHosts pattern. */ public class SdkProxyRoutePlanner extends DefaultRoutePlanner { private HttpHost proxy; private final Pattern nonProxyHostsPattern; public SdkProxyRoutePlanner(String scheme, InetSocketAddress proxySocketAddress, String nonProxyHosts) { super(DefaultSchemePortResolver.INSTANCE); proxy = new HttpHost(scheme, proxySocketAddress.getAddress(), proxySocketAddress.getHostString(), proxySocketAddress.getPort()); this.nonProxyHostsPattern = StringUtils.isEmpty(nonProxyHosts) ? null : Pattern.compile(nonProxyHosts, Pattern.CASE_INSENSITIVE); } private boolean doesTargetMatchNonProxyHosts(HttpHost target) { if (nonProxyHostsPattern == null) { return false; } return nonProxyHostsPattern.matcher(target.getHostName()).matches(); } @Override protected HttpHost determineProxy( final HttpHost target, final HttpContext context) throws HttpException { return doesTargetMatchNonProxyHosts(target) ? null : proxy; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/StreamEntityProducer.java
package com.aliyun.httpcomponent.httpclient.implementation; import org.apache.hc.core5.http.nio.AsyncEntityProducer; import org.apache.hc.core5.http.nio.DataStreamChannel; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Set; public final class StreamEntityProducer implements AsyncEntityProducer { private InputStream data; private long contentLength; private ByteBuffer buffer; private boolean gotEOF; public StreamEntityProducer(InputStream inputstream) { this.data = inputstream; this.gotEOF = false; this.buffer = null; this.contentLength = -1; } @Override public boolean isRepeatable() { return false; } @Override public void failed(Exception e) { releaseResources(); } @Override public long getContentLength() { return contentLength; } @Override public String getContentType() { return null; } @Override public String getContentEncoding() { return null; } @Override public boolean isChunked() { return contentLength == -1; } @Override public Set<String> getTrailerNames() { return null; } @Override public int available() { return Integer.MAX_VALUE; } @Override public void produce(DataStreamChannel dataStreamChannel) throws IOException { fillBuffer(); while (buffer != null && buffer.remaining() > 0) { dataStreamChannel.write(buffer); if (buffer.remaining() > 0) { break; } else { fillBuffer(); } } if (gotEOF && (buffer == null || !buffer.hasRemaining())) { dataStreamChannel.endStream(); } } @Override public void releaseResources() { } private void fillBuffer() throws IOException { if (buffer == null || !buffer.hasRemaining()) { byte[] src = new byte[4096]; int ret = data.read(src); if (ret < 0) { gotEOF = true; return; } buffer = ByteBuffer.wrap(src, 0, ret); } } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/StreamRequestProducer.java
package com.aliyun.httpcomponent.httpclient.implementation; import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.nio.AsyncEntityProducer; import org.apache.hc.core5.http.nio.support.BasicRequestProducer; import org.apache.hc.core5.util.Args; import java.io.InputStream; public class StreamRequestProducer extends BasicRequestProducer { StreamRequestProducer(HttpRequest request, AsyncEntityProducer dataProducer) { super(request, dataProducer); } public static StreamRequestProducer create(SimpleHttpRequest request, InputStream inputsteam) { Args.notNull(request, "Request"); StreamEntityProducer entityProducer = new StreamEntityProducer(inputsteam); return new StreamRequestProducer(request, entityProducer); } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/reactive/ReactiveApacheHttpResponse.java
package com.aliyun.httpcomponent.httpclient.implementation.reactive; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.message.BasicHttpResponse; import org.apache.hc.core5.util.Args; import java.util.Iterator; public class ReactiveApacheHttpResponse extends BasicHttpResponse { private com.aliyun.core.http.HttpHeaders sdkHttpHeaders; public ReactiveApacheHttpResponse(int code) { super(code); } public ReactiveApacheHttpResponse(int code, String reasonPhrase) { super(code, reasonPhrase); } public static ReactiveApacheHttpResponse copy(HttpResponse original) { Args.notNull(original, "HTTP response"); ReactiveApacheHttpResponse copy = new ReactiveApacheHttpResponse(original.getCode()); copy.setVersion(original.getVersion()); Iterator it = original.headerIterator(); while(it.hasNext()) { copy.addHeader((Header)it.next()); } return copy; } public static ReactiveApacheHttpResponse copyLite(HttpResponse original, com.aliyun.core.http.HttpHeaders httpHeaders) { Args.notNull(original, "HTTP response"); Args.notNull(httpHeaders, "com.aliyun.core.http httpHeaders"); ReactiveApacheHttpResponse copy = new ReactiveApacheHttpResponse(original.getCode()); copy.setVersion(original.getVersion()); copy.setSDKHttpHeaders(httpHeaders); return copy; } public static ReactiveApacheHttpResponse create(int code) { return new ReactiveApacheHttpResponse(code); } public com.aliyun.core.http.HttpHeaders getSDKHttpHeaders() { return sdkHttpHeaders; } public void setSDKHttpHeaders(com.aliyun.core.http.HttpHeaders sdkHttpHeaders) { this.sdkHttpHeaders = sdkHttpHeaders; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/reactive/ReactiveDataConsumer.java
package com.aliyun.httpcomponent.httpclient.implementation.reactive; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpStreamResetException; import org.apache.hc.core5.http.nio.AsyncDataConsumer; import org.apache.hc.core5.http.nio.CapacityChannel; import org.apache.hc.core5.util.Args; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; final class ReactiveDataConsumer implements AsyncDataConsumer, Publisher<ByteBuffer> { private final AtomicLong requests = new AtomicLong(0); private final BlockingQueue<ByteBuffer> buffers = new LinkedBlockingQueue<>(); private final AtomicBoolean flushInProgress = new AtomicBoolean(false); private final Object flushLock = new Object(); private final AtomicInteger windowScalingIncrement = new AtomicInteger(0); private volatile boolean cancelled; private volatile boolean completed; private volatile Exception exception; private volatile CapacityChannel capacityChannel; private volatile Subscriber<? super ByteBuffer> subscriber; public void failed(final Exception cause) { if (!completed) { exception = cause; flushToSubscriber(); } } @Override public void updateCapacity(final CapacityChannel capacityChannel) throws IOException { throwIfCancelled(); this.capacityChannel = capacityChannel; signalCapacity(capacityChannel); } private void signalCapacity(final CapacityChannel channel) throws IOException { final int increment = windowScalingIncrement.getAndSet(0); if (increment > 0) { channel.update(increment); } } private void throwIfCancelled() throws IOException { if (cancelled) { throw new HttpStreamResetException("Downstream subscriber to ReactiveDataConsumer cancelled"); } } @Override public void consume(final ByteBuffer byteBuffer) throws IOException { if (completed) { throw new IllegalStateException("Received data past end of stream"); } throwIfCancelled(); final byte[] copy = new byte[byteBuffer.remaining()]; byteBuffer.get(copy); buffers.add(ByteBuffer.wrap(copy)); flushToSubscriber(); } @Override public void streamEnd(final List<? extends Header> trailers) { completed = true; flushToSubscriber(); } @Override public void releaseResources() { this.capacityChannel = null; } private void flushToSubscriber() { synchronized (flushLock) { final Subscriber<? super ByteBuffer> s = subscriber; if (flushInProgress.getAndSet(true)) { return; } try { if (s == null) { return; } if (exception != null) { s.onError(exception); subscriber = null; return; } ByteBuffer next; while (requests.get() > 0 && ((next = buffers.poll()) != null)) { final int bytesFreed = next.remaining(); s.onNext(next); requests.decrementAndGet(); windowScalingIncrement.addAndGet(bytesFreed); } final CapacityChannel localChannel = capacityChannel; if (localChannel != null) { try { signalCapacity(localChannel); } catch (final IOException e) { exception = e; s.onError(e); return; } } if (completed && buffers.isEmpty()) { s.onComplete(); subscriber = null; } } finally { flushInProgress.set(false); } } } @Override public void subscribe(final Subscriber<? super ByteBuffer> subscriber) { this.subscriber = Args.notNull(subscriber, "subscriber"); subscriber.onSubscribe(new Subscription() { @Override public void request(final long increment) { if (increment <= 0) { failed(new IllegalArgumentException("The number of elements requested must be strictly positive")); return; } requests.addAndGet(increment); flushToSubscriber(); } @Override public void cancel() { ReactiveDataConsumer.this.cancelled = true; ReactiveDataConsumer.this.subscriber = null; } }); } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/reactive/ReactiveHttpResponse.java
package com.aliyun.httpcomponent.httpclient.implementation.reactive; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.http.HttpResponse; import org.apache.hc.core5.http.Header; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public final class ReactiveHttpResponse extends HttpResponse { private final int statusCode; private final HttpHeaders headers; public ReactiveHttpResponse(HttpRequest request, ReactiveApacheHttpResponse apacheResponse) { super(request); this.statusCode = apacheResponse.getCode(); this.headers = (apacheResponse.getSDKHttpHeaders() == null) ? toHeaders(apacheResponse) : apacheResponse.getSDKHttpHeaders(); } @Override public int getStatusCode() { return this.statusCode; } @Override public String getHeaderValue(String name) { return this.headers.getValue(name); } @Override public HttpHeaders getHeaders() { return this.headers; } @Override public ByteBuffer getBody() { return null; } @Override public byte[] getBodyAsByteArray() { return null; } @Override public String getBodyAsString() { return null; } @Override public String getBodyAsString(Charset charset) { return null; } private static HttpHeaders toHeaders(ReactiveApacheHttpResponse response) { final HttpHeaders httpHeaders = new HttpHeaders(); Set<String> nameSet = new HashSet<>(); Header[] apacheHeaders = response.getHeaders(); for (Header header : apacheHeaders) { nameSet.add(header.getName()); } nameSet.forEach((name) -> { Header[] entityHeaders = response.getHeaders(name); List<String> values = new ArrayList<>(); for (Header entityHeader : entityHeaders) { values.add(entityHeader.getValue()); } httpHeaders.set(name, values); }); return httpHeaders; } }
0
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation
java-sources/com/aliyun/aliyun-http-apache/0.3.2-beta/com/aliyun/httpcomponent/httpclient/implementation/reactive/ReactiveResponseConsumer.java
package com.aliyun.httpcomponent.httpclient.implementation.reactive; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpResponseHandler; import org.apache.hc.core5.concurrent.BasicFuture; import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.nio.AsyncResponseConsumer; import org.apache.hc.core5.http.nio.CapacityChannel; import org.apache.hc.core5.http.protocol.HttpContext; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; public final class ReactiveResponseConsumer implements AsyncResponseConsumer<ReactiveApacheHttpResponse> { private final ReactiveDataConsumer reactiveDataConsumer = new ReactiveDataConsumer(); private final List<Header> trailers = Collections.synchronizedList(new ArrayList<Header>()); private volatile BasicFuture<ReactiveApacheHttpResponse> responseCompletion; private volatile HttpResponse informationResponse; private volatile EntityDetails entityDetails; private HttpResponseHandler handler; private HttpResponse response; private com.aliyun.core.http.HttpHeaders sdkHttpHeaders; /** * Creates a {@code ReactiveResponseConsumer}. */ public ReactiveResponseConsumer(HttpResponseHandler handler) { this.handler = handler; } /** * Returns the intermediate (1xx) HTTP response if one was received. * * @return the information response, or {@code null} if none. */ public HttpResponse getInformationResponse() { return informationResponse; } /** * Returns the response entity details. * * @return the entity details, or {@code null} if none. */ public EntityDetails getEntityDetails() { return entityDetails; } /** * Returns the trailers received at the end of the response. * * @return a non-null list of zero or more trailers. */ public List<Header> getTrailers() { return trailers; } @Override public void consumeResponse( final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext, final FutureCallback<ReactiveApacheHttpResponse> resultCallback ) { this.response = response; this.entityDetails = entityDetails; this.responseCompletion = new BasicFuture<>(resultCallback); this.sdkHttpHeaders = toHeaders(response); this.handler.onStream(reactiveDataConsumer, response.getCode(), sdkHttpHeaders); if (entityDetails == null) { streamEnd(null); } } @Override public void informationResponse(final HttpResponse response, final HttpContext httpContext) { this.informationResponse = response; } @Override public void failed(final Exception cause) { reactiveDataConsumer.failed(cause); if (responseCompletion != null) { responseCompletion.failed(cause); } } @Override public void updateCapacity(final CapacityChannel capacityChannel) throws IOException { reactiveDataConsumer.updateCapacity(capacityChannel); } @Override public void consume(final ByteBuffer src) throws IOException { reactiveDataConsumer.consume(src); } @Override public void streamEnd(final List<? extends Header> trailers) { if (trailers != null) { this.trailers.addAll(trailers); } reactiveDataConsumer.streamEnd(trailers); ReactiveApacheHttpResponse result = ReactiveApacheHttpResponse.copyLite(this.response, this.sdkHttpHeaders); if (responseCompletion != null) { responseCompletion.completed(result); } } @Override public void releaseResources() { reactiveDataConsumer.releaseResources(); if (responseCompletion != null) { responseCompletion.cancel(); } } private static com.aliyun.core.http.HttpHeaders toHeaders(HttpResponse response) { final HttpHeaders httpHeaders = new HttpHeaders(); Set<String> nameSet = new HashSet<>(); Header[] apacheHeaders = response.getHeaders(); for (Header header : apacheHeaders) { nameSet.add(header.getName()); } nameSet.forEach((name) -> { Header[] entityHeaders = response.getHeaders(name); List<String> values = new ArrayList<>(); for (Header entityHeader : entityHeaders) { values.add(entityHeader.getValue()); } httpHeaders.set(name, values); }); return httpHeaders; } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/NettyAsyncHttpClient.java
package com.aliyun.netty; import com.aliyun.core.http.*; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.Context; import com.aliyun.netty.implementation.response.NettyAsyncHttpBufferedResponse; import com.aliyun.netty.utils.ByteBufferCollector; import com.aliyun.netty.implementation.response.NettyAsyncHttpResponse; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelOption; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.proxy.ProxyConnectException; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.netty.ByteBufMono; import reactor.netty.NettyOutbound; import reactor.netty.http.client.HttpClientRequest; import reactor.netty.http.client.HttpClientResponse; import javax.net.ssl.SSLException; import java.nio.ByteBuffer; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; class NettyAsyncHttpClient implements HttpClient { private final ClientLogger logger = new ClientLogger(NettyAsyncHttpClient.class); private final reactor.netty.http.client.HttpClient nettyClient; NettyAsyncHttpClient(reactor.netty.http.client.HttpClient httpClient) { this.nettyClient = httpClient; } @Override public CompletableFuture<HttpResponse> send(HttpRequest httpRequest) { return send(httpRequest, Context.NONE); } @Override public CompletableFuture<HttpResponse> send(HttpRequest httpRequest, Context context) { Objects.requireNonNull(httpRequest.getHttpMethod(), "'request.getHttpMethod()' cannot be null."); Objects.requireNonNull(httpRequest.getUrl(), "'request.getUrl()' cannot be null."); Objects.requireNonNull(httpRequest.getUrl().getProtocol(), "'request.getUrl().getProtocol()' cannot be null."); boolean eagerlyReadResponse = (boolean) context.getData("eagerly-read-response").orElse(false); reactor.netty.http.client.HttpClient nettyClientInner = nettyClient; if (httpRequest.getResponseTimeout() != null) nettyClientInner = nettyClientInner.responseTimeout(httpRequest.getResponseTimeout()); if (httpRequest.getConnectTimeout() != null) nettyClientInner = nettyClientInner.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) httpRequest.getConnectTimeout().toMillis()); ProxyOptions buildProxyOptions = httpRequest.getProxyOptions(); if (buildProxyOptions != null) { nettyClientInner = nettyClientInner.noProxy().proxy(proxy -> proxy.type(NettyAsyncHttpClientBuilder.toReactorNettyProxyType(buildProxyOptions.getType(), logger)) .address(buildProxyOptions.getAddress()) .username(buildProxyOptions.getUsername()) .password(ignored -> buildProxyOptions.getPassword()) .nonProxyHosts(buildProxyOptions.getNonProxyHosts())); } return nettyClientInner .request(HttpMethod.valueOf(httpRequest.getHttpMethod().toString())) .uri(httpRequest.getUrl().toString()) .send(bodySendDelegate(httpRequest)) .responseSingle(responseDelegate(httpRequest, eagerlyReadResponse)) .onErrorMap(throwable -> { // The exception was an SSLException that was caused by a failure to connect to a proxy. // Extract the inner ProxyConnectException and propagate that instead. if (throwable instanceof SSLException) { if (throwable.getCause() instanceof ProxyConnectException) { return throwable.getCause(); } } return throwable; }) .toFuture(); } private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate( final HttpRequest restRequest) { return (reactorNettyRequest, reactorNettyOutbound) -> { for (HttpHeader hdr : restRequest.getHeaders()) { if (reactorNettyRequest.requestHeaders().contains(hdr.getName())) { final AtomicBoolean first = new AtomicBoolean(true); hdr.getValuesList().forEach(value -> { if (first.compareAndSet(true, false)) { reactorNettyRequest.header(hdr.getName(), value); } else { reactorNettyRequest.addHeader(hdr.getName(), value); } }); } else { hdr.getValuesList().forEach(value -> reactorNettyRequest.addHeader(hdr.getName(), value)); } } if (restRequest.getBody() != null) { Flux<ByteBuf> nettyByteBufFlux = Flux.just(restRequest.getBody()).map(Unpooled::wrappedBuffer); return reactorNettyOutbound.send(nettyByteBufFlux); } else { return reactorNettyOutbound; } }; } private static BiFunction<HttpClientResponse, ByteBufMono, Mono<HttpResponse>> responseDelegate( final HttpRequest restRequest, final boolean eagerlyReadResponse) { return (reactorNettyResponse, byteBufMono) -> { if (eagerlyReadResponse) { Mono<ByteBuffer> body = byteBufMono.asByteBuffer(); ByteBufferCollector collector = new ByteBufferCollector(); return body.map(buffer -> { collector.write(buffer); return collector.toByteArray(); }).map(bytes -> new NettyAsyncHttpBufferedResponse(reactorNettyResponse, restRequest, bytes)); } else { return Mono.just(new NettyAsyncHttpResponse(reactorNettyResponse, byteBufMono, restRequest)); } }; } @Override public void close() { } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/NettyAsyncHttpClientBuilder.java
package com.aliyun.netty; import com.aliyun.core.http.ProxyOptions; import com.aliyun.core.utils.Configuration; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.StringUtils; import com.aliyun.netty.implementation.ChallengeHolder; import com.aliyun.netty.implementation.CompositeX509TrustManager; import com.aliyun.netty.utils.AuthorizationChallengeHandler; import com.aliyun.netty.implementation.handler.*; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.ssl.SslHandler; import io.netty.resolver.AddressResolverGroup; import io.netty.resolver.NoopAddressResolverGroup; import reactor.netty.Connection; import reactor.netty.NettyPipeline; import reactor.netty.http.client.HttpClient; import reactor.netty.resources.ConnectionProvider; import reactor.netty.transport.AddressUtils; import reactor.netty.transport.ProxyProvider; import javax.net.ssl.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.KeyStore; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; public class NettyAsyncHttpClientBuilder { private final ClientLogger logger = new ClientLogger(NettyAsyncHttpClientBuilder.class); private static final long DEFAULT_TIMEOUT = TimeUnit.SECONDS.toMillis(20); private static final long DEFAULT_MAX_CONN_TIMEOUT = TimeUnit.SECONDS.toMillis(10); private static final long DEFAULT_MAX_RESPONSE_TIMEOUT = TimeUnit.SECONDS.toMillis(20); private static final long DEFAULT_MAX_IDLE_TIMEOUT = TimeUnit.SECONDS.toMillis(30); private static final long DEFAULT_MINIMUM_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1); private final HttpClient baseHttpClient; private boolean enableWiretap; private ProxyOptions proxyOptions; private ConnectionProvider connectionProvider; private EventLoopGroup eventLoopGroup; private Configuration configuration; private Duration connectTimeout; private Duration writeTimeout; private Duration responseTimeout; private Duration readTimeout; private int maxConnections; private Duration maxIdleTimeOut; private X509TrustManager[] x509TrustManagers = null; private KeyManager[] keyManagers = null; private HostnameVerifier hostnameVerifier = null; private boolean ignoreSSL = false; private int port = 80; public NettyAsyncHttpClientBuilder() { this.baseHttpClient = null; } public NettyAsyncHttpClientBuilder(HttpClient nettyHttpClient) { this.baseHttpClient = Objects.requireNonNull(nettyHttpClient, "'HttpClient' cannot be null."); } public com.aliyun.core.http.HttpClient build() { HttpClient nettyHttpClient; if (this.baseHttpClient != null) { nettyHttpClient = baseHttpClient; } else if (this.connectionProvider != null) { nettyHttpClient = HttpClient.create(this.connectionProvider); } else { ConnectionProvider connectionProviderDefault = ConnectionProvider.builder("custom") .maxConnections(getMaxConnTotal(this.maxConnections)) .maxIdleTime(getTimeoutMillis(this.maxIdleTimeOut, "idle")) .build(); nettyHttpClient = HttpClient.create(connectionProviderDefault); } nettyHttpClient = nettyHttpClient .port(port) .wiretap(enableWiretap) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) getTimeoutMillis(connectTimeout, "conn").toMillis()) .doOnRequest((request, connection) -> addWriteTimeoutHandler(connection, getTimeoutMillis(writeTimeout, "").toMillis())) .doAfterRequest((request, connection) -> addResponseTimeoutHandler(connection, getTimeoutMillis(responseTimeout, "response").toMillis())) .doOnResponse((response, connection) -> addReadTimeoutHandler(connection, getTimeoutMillis(readTimeout, "").toMillis())) .doAfterResponseSuccess((response, connection) -> removeReadTimeoutHandler(connection)); Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; ProxyOptions buildProxyOptions = (proxyOptions == null && buildConfiguration != Configuration.NONE) ? ProxyOptions.fromConfiguration(buildConfiguration, true) : proxyOptions; /* * Only configure the custom authorization challenge handler and challenge holder when using an authenticated * HTTP proxy. All other proxying such as SOCKS4, SOCKS5, and anonymous HTTP will use Netty's built-in handlers. */ boolean useCustomProxyHandler = shouldUseCustomProxyHandler(buildProxyOptions); AuthorizationChallengeHandler handler = useCustomProxyHandler ? new AuthorizationChallengeHandler(buildProxyOptions.getUsername(), buildProxyOptions.getPassword()) : null; AtomicReference<ChallengeHolder> proxyChallengeHolder = useCustomProxyHandler ? new AtomicReference<>() : null; if (eventLoopGroup != null) { nettyHttpClient = nettyHttpClient.runOn(eventLoopGroup); } // Proxy configurations are present, setup a proxy in Netty. if (buildProxyOptions != null) { // Determine if custom handling will be used, otherwise use Netty's built-in handlers. if (handler != null) { /* * Configure the request Channel to be initialized with a ProxyHandler. The ProxyHandler is the * first operation in the pipeline as it needs to handle sending a CONNECT request to the proxy * before any request data is sent. * * And in addition to adding the ProxyHandler update the Bootstrap resolver for proxy support. */ Pattern nonProxyHostsPattern = StringUtils.isEmpty(buildProxyOptions.getNonProxyHosts()) ? null : Pattern.compile(buildProxyOptions.getNonProxyHosts(), Pattern.CASE_INSENSITIVE); nettyHttpClient = nettyHttpClient.doOnChannelInit((connectionObserver, channel, socketAddress) -> { if (shouldApplyProxy(socketAddress, nonProxyHostsPattern)) { channel.pipeline() .addFirst(NettyPipeline.ProxyHandler, new HttpProxyHandler( AddressUtils.replaceWithResolved(buildProxyOptions.getAddress()), handler, proxyChallengeHolder)) .addLast("Ali.proxy.ExceptionHandler", new HttpProxyExceptionHandler()); } channel.pipeline().addLast("ssl", new SslHandler(sslEngineGenerate())); }); AddressResolverGroup<?> resolver = nettyHttpClient.configuration().resolver(); if (resolver == null) { nettyHttpClient.resolver(NoopAddressResolverGroup.INSTANCE); } } else { nettyHttpClient = nettyHttpClient.proxy(proxy -> proxy.type(toReactorNettyProxyType(buildProxyOptions.getType(), logger)) .address(buildProxyOptions.getAddress()) .username(buildProxyOptions.getUsername()) .password(ignored -> buildProxyOptions.getPassword()) .nonProxyHosts(buildProxyOptions.getNonProxyHosts())); } } return new NettyAsyncHttpClient(nettyHttpClient.disableRetry(true)); } private SSLEngine sslEngineGenerate() { List<TrustManager> trustManagerList = new ArrayList<TrustManager>(); X509TrustManager[] trustManagers = this.x509TrustManagers; if (null != trustManagers) { trustManagerList.addAll(Arrays.asList(trustManagers)); } TrustManagerFactory tmf = null; try { // get trustManager using default certification from jdk tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); trustManagerList.addAll(Arrays.asList(tmf.getTrustManagers())); } catch (Exception e) { throw logger.logExceptionAsError(new RuntimeException(e)); } final List<X509TrustManager> finalTrustManagerList = new ArrayList<X509TrustManager>(); for (TrustManager tm : trustManagerList) { if (tm instanceof X509TrustManager) { finalTrustManagerList.add((X509TrustManager) tm); } } CompositeX509TrustManager compositeX509TrustManager = new CompositeX509TrustManager(finalTrustManagerList); compositeX509TrustManager.setIgnoreSSLCert(this.ignoreSSL); // set KeyManager KeyManager[] keyManagers = null; if (this.keyManagers != null) { keyManagers = this.keyManagers; } // Generate SSLContext by TrustManager and KeyManager SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, new TrustManager[]{compositeX509TrustManager}, null); } catch (Exception e) { throw logger.logExceptionAsError(new RuntimeException(e)); } SSLEngine engine = sslContext.createSSLEngine(); engine.setUseClientMode(true); return engine; } public NettyAsyncHttpClientBuilder connectionProvider(ConnectionProvider connectionProvider) { this.connectionProvider = connectionProvider; return this; } public NettyAsyncHttpClientBuilder maxIdleTimeOut(Duration maxIdleTimeOut) { this.maxIdleTimeOut = maxIdleTimeOut; return this; } public NettyAsyncHttpClientBuilder maxConnections(int maxConnections) { this.maxConnections = maxConnections; return this; } public NettyAsyncHttpClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public NettyAsyncHttpClientBuilder wiretap(boolean enableWiretap) { this.enableWiretap = enableWiretap; return this; } public NettyAsyncHttpClientBuilder port(int port) { this.port = port; return this; } public NettyAsyncHttpClientBuilder eventLoopGroup(EventLoopGroup eventLoopGroup) { this.eventLoopGroup = eventLoopGroup; return this; } public NettyAsyncHttpClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } public NettyAsyncHttpClientBuilder connectionTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } public NettyAsyncHttpClientBuilder writeTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } public NettyAsyncHttpClientBuilder responseTimeout(Duration responseTimeout) { this.responseTimeout = responseTimeout; return this; } public NettyAsyncHttpClientBuilder readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } public NettyAsyncHttpClientBuilder x509TrustManagers(X509TrustManager[] x509TrustManagers) { this.x509TrustManagers = x509TrustManagers; return this; } public NettyAsyncHttpClientBuilder keyManagers(KeyManager[] keyManagers) { this.keyManagers = keyManagers; return this; } public NettyAsyncHttpClientBuilder hostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } public NettyAsyncHttpClientBuilder ignoreSSL(Boolean ignoreSSL) { this.ignoreSSL = ignoreSSL; return this; } protected static boolean shouldUseCustomProxyHandler(ProxyOptions options) { return options != null && options.getUsername() != null && options.getType() == ProxyOptions.Type.HTTP; } protected static ProxyProvider.Proxy toReactorNettyProxyType(ProxyOptions.Type aliProxyType, ClientLogger logger) { switch (aliProxyType) { case HTTP: return ProxyProvider.Proxy.HTTP; case SOCKS4: return ProxyProvider.Proxy.SOCKS4; case SOCKS5: return ProxyProvider.Proxy.SOCKS5; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown 'ProxyOptions.Type' enum value")); } } protected static boolean shouldApplyProxy(SocketAddress socketAddress, Pattern nonProxyHostsPattern) { if (nonProxyHostsPattern == null) { return true; } if (!(socketAddress instanceof InetSocketAddress)) { return true; } InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; return !nonProxyHostsPattern.matcher(inetSocketAddress.getHostString()).matches(); } private static void addWriteTimeoutHandler(Connection connection, long timeoutMillis) { connection.addHandlerLast(WriteTimeoutHandler.HANDLER_NAME, new WriteTimeoutHandler(timeoutMillis)); } private static void addResponseTimeoutHandler(Connection connection, long timeoutMillis) { connection.removeHandler(WriteTimeoutHandler.HANDLER_NAME) .addHandlerLast(ResponseTimeoutHandler.HANDLER_NAME, new ResponseTimeoutHandler(timeoutMillis)); } private static void addReadTimeoutHandler(Connection connection, long timeoutMillis) { connection.removeHandler(ResponseTimeoutHandler.HANDLER_NAME) .addHandlerLast(ReadTimeoutHandler.HANDLER_NAME, new ReadTimeoutHandler(timeoutMillis)); } private static void removeReadTimeoutHandler(Connection connection) { connection.removeHandler(ReadTimeoutHandler.HANDLER_NAME); } private static Duration getTimeoutMillis(Duration timeout, String name) { if (timeout == null) { switch (name) { case "idle": return Duration.ofMillis(DEFAULT_MAX_IDLE_TIMEOUT); case "conn": return Duration.ofMillis(DEFAULT_MAX_CONN_TIMEOUT); case "response": return Duration.ofMillis(DEFAULT_MAX_RESPONSE_TIMEOUT); default: return Duration.ofMillis(DEFAULT_TIMEOUT); } } if (timeout.isZero() || timeout.isNegative()) { return Duration.ofMillis(0); } return Duration.ofMillis(Math.max(timeout.toMillis(), DEFAULT_MINIMUM_TIMEOUT)); } private static int getMaxConnTotal(int maxConnTotal) { if (maxConnTotal <= 0) { return Runtime.getRuntime().availableProcessors() * 10; } return maxConnTotal; } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/NettyAsyncHttpClientProvider.java
package com.aliyun.netty; import com.aliyun.core.http.HttpClient; import com.aliyun.core.http.HttpClientProvider; import com.aliyun.core.utils.HttpClientOptions; public final class NettyAsyncHttpClientProvider implements HttpClientProvider { @Override public HttpClient createInstance() { return new NettyAsyncHttpClientBuilder().build(); } @Override public HttpClient createInstance(HttpClientOptions clientOptions) { NettyAsyncHttpClientBuilder builder = new NettyAsyncHttpClientBuilder(); if (clientOptions != null) { builder = builder.proxy(clientOptions.getProxyOptions()) .configuration(clientOptions.getConfiguration()) .writeTimeout(clientOptions.getWriteTimeout()) .responseTimeout(clientOptions.getResponseTimeout()) .readTimeout(clientOptions.getReadTimeout()); } return builder.build(); } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/ChallengeHolder.java
package com.aliyun.netty.implementation; import java.util.List; import java.util.Map; public final class ChallengeHolder { private final List<Map<String, String>> digestChallenges; private final boolean BasicChallenge; public ChallengeHolder(boolean hasBasicChallenge, List<Map<String, String>> digestChallenges) { this.BasicChallenge = hasBasicChallenge; this.digestChallenges = digestChallenges; } public List<Map<String, String>> getDigestChallenges() { return digestChallenges; } public boolean hasBasicChallenge() { return BasicChallenge; } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/CompositeX509TrustManager.java
package com.aliyun.netty.implementation; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CompositeX509TrustManager implements X509TrustManager { private final List<X509TrustManager> trustManagers; private boolean ignoreSSL = false; public boolean isIgnoreSSL() { return ignoreSSL; } public void setIgnoreSSLCert(boolean ignoreSSL) { this.ignoreSSL = ignoreSSL; } public CompositeX509TrustManager(List<X509TrustManager> trustManagers) { this.trustManagers = trustManagers; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // do nothing } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (ignoreSSL) { return; } for (X509TrustManager trustManager : trustManagers) { try { trustManager.checkServerTrusted(chain, authType); return; // someone trusts them. success! } catch (CertificateException e) { // maybe someone else will trust them } } throw new CertificateException("None of the TrustManagers trust this certificate chain"); } @Override public X509Certificate[] getAcceptedIssuers() { List<X509Certificate> certificates = new ArrayList<X509Certificate>(); for (X509TrustManager trustManager : trustManagers) { certificates.addAll(Arrays.asList(trustManager.getAcceptedIssuers())); } X509Certificate[] certificatesArray = new X509Certificate[certificates.size()]; return certificates.toArray(certificatesArray); } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/HttpHeadersWrapper.java
package com.aliyun.netty.implementation; import com.aliyun.core.http.HttpHeader; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import java.util.*; import java.util.stream.Stream; public class HttpHeadersWrapper extends HttpHeaders { private static final ClientLogger LOGGER = new ClientLogger(HttpHeadersWrapper.class); private final io.netty.handler.codec.http.HttpHeaders nettyHeaders; private Map<String, String> abstractMap; public HttpHeadersWrapper(io.netty.handler.codec.http.HttpHeaders httpHeaders) { this.nettyHeaders = httpHeaders; } @Override public int getSize() { return nettyHeaders.size(); } @Override public HttpHeaders set(String name, String value) { if (name == null) { return this; } if (value == null) { remove(name); } else { nettyHeaders.set(name, value); } return this; } @Override public HttpHeaders set(String name, List<String> listValues) { if (name == null) { return this; } if (listValues == null) { remove(name); } else { nettyHeaders.set(name, listValues); } return this; } HttpHeaders add(String name, String value) { if (name == null) { return this; } if (value == null) { remove(name); } else { nettyHeaders.add(name, value); } return this; } @Override public HttpHeader get(String name) { if (nettyHeaders.contains(name)) { return new NettyHttpHeader(this, name, nettyHeaders.getAll(name)); } return null; } @Override public HttpHeader remove(String name) { HttpHeader header = get(name); nettyHeaders.remove(name); return header; } @Override public String getValue(String name) { final HttpHeader header = get(name); return (header == null) ? null : header.getValue(); } @Override public String[] getValues(String name) { final HttpHeader header = get(name); return (header == null) ? null : header.getValues(); } @Override public Map<String, String> toMap() { if (abstractMap == null) { abstractMap = new AbstractMap<String, String>() { private final Map<String, String> innerJoinMap = new HashMap<>(); @Override public int size() { return nettyHeaders.size(); } @Override public boolean isEmpty() { return nettyHeaders.isEmpty(); } @Override public boolean containsKey(Object key) { return nettyHeaders.contains((String) key); } @Override public boolean containsValue(Object value) { throw LOGGER.logExceptionAsWarning(new UnsupportedOperationException()); } @Override public String get(final Object key) { return innerJoinMap.computeIfAbsent((String) key, _key -> String.join(",", nettyHeaders.getAll(_key))); } @Override public String put(String key, String value) { throw LOGGER.logExceptionAsWarning(new UnsupportedOperationException()); } @Override public String remove(Object key) { throw LOGGER.logExceptionAsWarning(new UnsupportedOperationException()); } @Override public void putAll(Map<? extends String, ? extends String> m) { throw LOGGER.logExceptionAsWarning(new UnsupportedOperationException()); } @Override public void clear() { throw LOGGER.logExceptionAsWarning(new UnsupportedOperationException()); } @Override public Set<Entry<String, String>> entrySet() { return new AbstractSet<Entry<String, String>>() { @Override public Iterator<Entry<String, String>> iterator() { return nettyHeaders.iteratorAsString(); } @Override public int size() { return nettyHeaders.size(); } }; } }; } return abstractMap; } @Override public Iterator<HttpHeader> iterator() { return stream().iterator(); } @Override public Stream<HttpHeader> stream() { return nettyHeaders.names().stream() .map(name -> new NettyHttpHeader(this, name, nettyHeaders.getAll(name))); } static class NettyHttpHeader extends HttpHeader { private final HttpHeadersWrapper allHeaders; NettyHttpHeader(HttpHeadersWrapper allHeaders, String name, String value) { super(name, value); this.allHeaders = allHeaders; } NettyHttpHeader(HttpHeadersWrapper allHeaders, String name, List<String> listValues) { super(name, listValues); this.allHeaders = allHeaders; } @Override public void addValue(String value) { super.addValue(value); allHeaders.add(getName(), value); } } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/Utility.java
package com.aliyun.netty.implementation; import io.netty.buffer.ByteBuf; import reactor.netty.Connection; import java.nio.ByteBuffer; public final class Utility { public static ByteBuffer deepCopyBuffer(ByteBuf byteBuffer) { ByteBuffer buffer = ByteBuffer.allocate(byteBuffer.readableBytes()); byteBuffer.readBytes(buffer); buffer.rewind(); return buffer; } public static void closeConnection(Connection reactorConnection) { if (!reactorConnection.isDisposed()) { reactorConnection.channel().eventLoop().execute(reactorConnection::dispose); } } private Utility() { } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/handler/HttpProxyExceptionHandler.java
package com.aliyun.netty.implementation.handler; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.proxy.ProxyConnectException; import javax.net.ssl.SSLException; public class HttpProxyExceptionHandler extends ChannelDuplexHandler { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof SSLException) { SSLException sslException = (SSLException) cause; if (sslException.getCause() instanceof ProxyConnectException) { ctx.fireExceptionCaught(sslException.getCause()); return; } ctx.fireExceptionCaught(cause); } if (cause instanceof RuntimeException) { RuntimeException runtimeException = (RuntimeException) cause; if (runtimeException.getCause() instanceof ProxyConnectException) { ctx.fireExceptionCaught(runtimeException.getCause()); return; } ctx.fireExceptionCaught(cause); } } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/handler/HttpProxyHandler.java
package com.aliyun.netty.implementation.handler; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.StringUtils; import com.aliyun.netty.implementation.ChallengeHolder; import com.aliyun.netty.utils.AuthorizationChallengeHandler; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import io.netty.handler.proxy.ProxyConnectException; import io.netty.handler.proxy.ProxyHandler; import io.netty.util.AttributeKey; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import java.util.regex.Pattern; import static com.aliyun.netty.utils.AuthorizationChallengeHandler.PROXY_AUTHENTICATION_INFO; import static com.aliyun.netty.utils.AuthorizationChallengeHandler.PROXY_AUTHORIZATION; import static com.aliyun.netty.utils.AuthorizationChallengeHandler.PROXY_AUTHENTICATE; public final class HttpProxyHandler extends ProxyHandler { private static final AttributeKey<String> PROXY_AUTHORIZATION_KEY = AttributeKey.newInstance("ProxyAuthorization"); private static final String AUTH_BASIC = "basic"; private static final String AUTH_DIGEST = "digest"; private static final String CNONCE = "cnonce"; private static final String NC = "nc"; private static final String NONE = "none"; private static final String HTTP = "http"; private static final Pattern AUTH_SCHEME_PATTERN = Pattern.compile("^" + AUTH_DIGEST, Pattern.CASE_INSENSITIVE); private static final String PROXY_METHOD = HttpMethod.CONNECT.name(); private static final String PROXY_URI_PATH = "/"; private static final Supplier<byte[]> NO_BODY = () -> new byte[0]; private final ClientLogger logger = new ClientLogger(HttpProxyHandler.class); private final AuthorizationChallengeHandler challengeHandler; private final AtomicReference<ChallengeHolder> proxyChallengeHolderReference; private final HttpClientCodec codec; private String authScheme = null; private HttpResponseStatus status; private static final String VALIDATION_ERROR_TEMPLATE = "The '%s' returned in the 'Proxy-Authentication-Info' " + "header doesn't match the value sent in the 'Proxy-Authorization' header. Sent: %s, received: %s."; public HttpProxyHandler(InetSocketAddress proxyAddress, AuthorizationChallengeHandler challengeHandler, AtomicReference<ChallengeHolder> proxyChallengeHolderReference) { super(proxyAddress); this.challengeHandler = challengeHandler; this.proxyChallengeHolderReference = proxyChallengeHolderReference; this.codec = new HttpClientCodec(); } @Override public String protocol() { return HTTP; } @Override public String authScheme() { return (authScheme == null) ? NONE : authScheme; } @Override protected void addCodec(ChannelHandlerContext ctx) { ctx.pipeline().addBefore(ctx.name(), null, this.codec); } @Override protected void removeEncoder(ChannelHandlerContext ctx) { this.codec.removeOutboundHandler(); } @Override protected void removeDecoder(ChannelHandlerContext ctx) { this.codec.removeInboundHandler(); } @Override public Object newInitialMessage(ChannelHandlerContext ctx) { InetSocketAddress destinationAddress = this.destinationAddress(); String hostString = HttpUtil.formatHostnameForHttp(destinationAddress); int port = destinationAddress.getPort(); String url = hostString + ":" + port; String hostHeader = (port == 80 || port == 443) ? url : hostString; FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, url, Unpooled.EMPTY_BUFFER, false); request.headers().set(HttpHeaderNames.HOST, hostHeader); if (challengeHandler != null) { String authorizationHeader = createAuthorizationHeader(); if (!StringUtils.isEmpty(authorizationHeader)) { authScheme = AUTH_SCHEME_PATTERN.matcher(authorizationHeader).find() ? AUTH_DIGEST : AUTH_BASIC; request.headers().set(PROXY_AUTHORIZATION, authorizationHeader); ctx.channel().attr(PROXY_AUTHORIZATION_KEY).set(authorizationHeader); } } return request; } private String createAuthorizationHeader() { String authorizationHeader = challengeHandler.attemptToPipelineAuthorization(PROXY_METHOD, PROXY_URI_PATH, NO_BODY); if (!StringUtils.isEmpty(authorizationHeader)) { return authorizationHeader; } ChallengeHolder proxyChallengeHolder = proxyChallengeHolderReference.get(); if (proxyChallengeHolder != null) { List<Map<String, String>> digestChallenges = proxyChallengeHolder.getDigestChallenges(); if (!StringUtils.isEmpty(digestChallenges)) { authorizationHeader = challengeHandler.handleDigest(PROXY_METHOD, PROXY_URI_PATH, digestChallenges, NO_BODY); } if (StringUtils.isEmpty(authorizationHeader) && proxyChallengeHolder.hasBasicChallenge()) { authorizationHeader = challengeHandler.handleBasic(); } } return authorizationHeader; } @Override public boolean handleResponse(ChannelHandlerContext ctx, Object object) throws ProxyConnectException { if (object instanceof HttpResponse) { if (status != null) { throw logger.logExceptionAsWarning(new RuntimeException("Received too many responses for a request")); } HttpResponse response = (HttpResponse) object; status = response.status(); if (response.status().code() == 407) { proxyChallengeHolderReference.set(extractChallengesFromHeaders(response.headers())); } else if (response.status().code() == 200) { validateProxyAuthenticationInfo(response.headers().get(PROXY_AUTHENTICATION_INFO), ctx.channel().attr(PROXY_AUTHORIZATION_KEY).get()); } } boolean responseComplete = object instanceof LastHttpContent; if (responseComplete) { if (status == null) { throw new ProxyConnectException("Never received response for CONNECT request."); } else if (status.code() != 200) { throw new ProxyConnectException("Failed to connect to proxy."); } } return responseComplete; } private static ChallengeHolder extractChallengesFromHeaders(HttpHeaders headers) { boolean hasBasicChallenge = false; List<Map<String, String>> digestChallenges = new ArrayList<>(); for (String proxyAuthenticationHeader : headers.getAll(PROXY_AUTHENTICATE)) { String[] typeValuePair = proxyAuthenticationHeader.split(" ", 2); String challengeType = typeValuePair[0].trim(); if (challengeType.equalsIgnoreCase(AUTH_BASIC)) { hasBasicChallenge = true; } else if (challengeType.equalsIgnoreCase(AUTH_DIGEST)) { Map<String, String> digestChallenge = new HashMap<>(); for (String challengePiece : typeValuePair[1].split(",")) { String[] kvp = challengePiece.split("=", 2); if (kvp.length != 2) { continue; } digestChallenge.put(kvp[0].trim(), kvp[1].trim().replace("\"", "")); } digestChallenges.add(digestChallenge); } } return new ChallengeHolder(hasBasicChallenge, digestChallenges); } private void validateProxyAuthenticationInfo(String infoHeader, String authorizationHeader) { if (StringUtils.isEmpty(infoHeader)) { return; } Map<String, String> authenticationInfoPieces = AuthorizationChallengeHandler .parseAuthenticationOrAuthorizationHeader(infoHeader); Map<String, String> authorizationPieces = AuthorizationChallengeHandler .parseAuthenticationOrAuthorizationHeader(authorizationHeader); validateProxyAuthenticationInfoValue(CNONCE, authenticationInfoPieces, authorizationPieces); validateProxyAuthenticationInfoValue(NC, authenticationInfoPieces, authorizationPieces); challengeHandler.consumeAuthenticationInfoHeader(authenticationInfoPieces); } private void validateProxyAuthenticationInfoValue(String name, Map<String, String> authInfoPieces, Map<String, String> authorizationPieces) { if (authInfoPieces.containsKey(name)) { String sentValue = authorizationPieces.get(name); String receivedValue = authInfoPieces.get(name); if (!receivedValue.equalsIgnoreCase(sentValue)) { throw logger.logExceptionAsError(new IllegalStateException( String.format(VALIDATION_ERROR_TEMPLATE, name, sentValue, receivedValue))); } } } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/handler/ReadTimeoutHandler.java
package com.aliyun.netty.implementation.handler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public final class ReadTimeoutHandler extends ChannelInboundHandlerAdapter { public static final String HANDLER_NAME = "AliyunReadTimeoutHandler"; private static final String READ_TIMED_OUT_MESSAGE = "Channel read time out after %d milliseconds."; private final long timeoutMillis; private boolean closeJudge; private long lastWriteMillisecond; private ScheduledFuture<?> readTimeoutWatcher; public ReadTimeoutHandler(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } @Override public void channelReadComplete(ChannelHandlerContext ctx) { this.lastWriteMillisecond = System.currentTimeMillis(); ctx.fireChannelReadComplete(); } @Override public void handlerAdded(ChannelHandlerContext ctx) { if (timeoutMillis > 0) { this.readTimeoutWatcher = ctx.executor().scheduleAtFixedRate(() -> readTimeoutRunnable(ctx), timeoutMillis, timeoutMillis, TimeUnit.MILLISECONDS); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { disposeWatcher(); } private void readTimeoutRunnable(ChannelHandlerContext ctx) { if ((timeoutMillis - (System.currentTimeMillis() - lastWriteMillisecond)) > 0) { return; } if (!closeJudge) { disposeWatcher(); ctx.fireExceptionCaught(new TimeoutException(String.format(READ_TIMED_OUT_MESSAGE, timeoutMillis))); ctx.close(); closeJudge = true; } } private void disposeWatcher() { if (readTimeoutWatcher != null && !readTimeoutWatcher.isDone()) { readTimeoutWatcher.cancel(false); readTimeoutWatcher = null; } } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/handler/ResponseTimeoutHandler.java
package com.aliyun.netty.implementation.handler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public final class ResponseTimeoutHandler extends ChannelInboundHandlerAdapter { public static final String HANDLER_NAME = "AliyunResponseTimeoutHandler"; private static final String RESPONSE_TIMED_OUT_MESSAGE = "Channel response time out after %d milliseconds."; private final long timeoutMillis; private boolean closeJudge; private ScheduledFuture<?> responseTimeoutWatcher; public ResponseTimeoutHandler(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } @Override public void handlerAdded(ChannelHandlerContext ctx) { if (timeoutMillis > 0) { this.responseTimeoutWatcher = ctx.executor().schedule(() -> responseTimedOut(ctx), timeoutMillis, TimeUnit.MILLISECONDS); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { disposeWatcher(); } private void responseTimedOut(ChannelHandlerContext ctx) { if (!closeJudge) { disposeWatcher(); ctx.fireExceptionCaught(new TimeoutException(String.format(RESPONSE_TIMED_OUT_MESSAGE, timeoutMillis))); ctx.close(); closeJudge = true; } } private void disposeWatcher() { if (responseTimeoutWatcher != null && !responseTimeoutWatcher.isDone()) { responseTimeoutWatcher.cancel(false); responseTimeoutWatcher = null; } } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/handler/WriteTimeoutHandler.java
package com.aliyun.netty.implementation.handler; import io.netty.channel.*; import io.netty.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public final class WriteTimeoutHandler extends ChannelOutboundHandlerAdapter { public static final String HANDLER_NAME = "AliyunWriteTimeoutHandler"; private static final String WRITE_TIMED_OUT_MESSAGE = "Channel write operation time out after %d milliseconds."; private final ChannelFutureListener writeListener = (future) -> this.lastWriteMillis = System.currentTimeMillis(); private final long timeoutMillis; private boolean closed; private long lastWriteMillis; private long lastWriteProgress; private ScheduledFuture<?> writeTimeoutWatcher; public WriteTimeoutHandler(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } @Override public void handlerAdded(ChannelHandlerContext ctx) { if (timeoutMillis > 0) { this.writeTimeoutWatcher = ctx.executor().scheduleAtFixedRate(() -> writeTimeoutRunnable(ctx), timeoutMillis, timeoutMillis, TimeUnit.MILLISECONDS); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { disposeWatcher(); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ctx.write(msg, promise.unvoid()).addListener(writeListener); } private void writeTimeoutRunnable(ChannelHandlerContext ctx) { if ((timeoutMillis - (System.currentTimeMillis() - lastWriteMillis)) > 0) { return; } ChannelOutboundBuffer buffer = ctx.channel().unsafe().outboundBuffer(); if (buffer != null) { long writeProgress = buffer.currentProgress(); if (writeProgress != lastWriteProgress) { this.lastWriteProgress = writeProgress; return; } } if (!closed) { disposeWatcher(); ctx.fireExceptionCaught(new TimeoutException(String.format(WRITE_TIMED_OUT_MESSAGE, timeoutMillis))); ctx.close(); closed = true; } } private void disposeWatcher() { if (writeTimeoutWatcher != null && !writeTimeoutWatcher.isDone()) { writeTimeoutWatcher.cancel(false); writeTimeoutWatcher = null; } } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/response/NettyAsyncHttpBufferedResponse.java
package com.aliyun.netty.implementation.response; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.http.HttpResponse; import com.aliyun.core.utils.BaseUtils; import reactor.netty.http.client.HttpClientResponse; import java.nio.ByteBuffer; import java.nio.charset.Charset; public final class NettyAsyncHttpBufferedResponse extends NettyAsyncHttpResponseBase { private final byte[] body; public NettyAsyncHttpBufferedResponse(HttpClientResponse ClientResponse, HttpRequest httpRequest, byte[] body) { super(ClientResponse, httpRequest); this.body = body; } @Override public ByteBuffer getBody() { return ByteBuffer.wrap(body); } @Override public byte[] getBodyAsByteArray() { return body; } @Override public String getBodyAsString() { return BaseUtils.bomAwareToString(body, getHeaderValue("Content-Type")); } @Override public String getBodyAsString(Charset charset) { return new String(body, charset); } @Override public HttpResponse buffer() { return this; } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/response/NettyAsyncHttpResponse.java
package com.aliyun.netty.implementation.response; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.utils.BaseUtils; import reactor.netty.ByteBufMono; import reactor.netty.http.client.HttpClientResponse; import java.nio.ByteBuffer; import java.nio.charset.Charset; public final class NettyAsyncHttpResponse extends NettyAsyncHttpResponseBase { private final ByteBufMono byteBufMono; public NettyAsyncHttpResponse(HttpClientResponse reactorNettyResponse, ByteBufMono byteBufMono, HttpRequest httpRequest) { super(reactorNettyResponse, httpRequest); this.byteBufMono = byteBufMono; } @Override public byte[] getBodyAsByteArray() { return bodyIntern().asByteArray().block(); } @Override public ByteBuffer getBody() { return bodyIntern().asByteBuffer().block(); } @Override public String getBodyAsString() { return BaseUtils.bomAwareToString(getBodyAsByteArray(), getHeaderValue("Content-Type")); } @Override public String getBodyAsString(Charset charset) { return bodyIntern().asString(charset).block(); } private ByteBufMono bodyIntern() { return byteBufMono; } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/implementation/response/NettyAsyncHttpResponseBase.java
package com.aliyun.netty.implementation.response; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.http.HttpRequest; import com.aliyun.core.http.HttpResponse; import com.aliyun.netty.implementation.HttpHeadersWrapper; import reactor.netty.http.client.HttpClientResponse; public abstract class NettyAsyncHttpResponseBase extends HttpResponse { private HttpHeadersWrapper headers; private final HttpClientResponse reactorNettyResponse; public NettyAsyncHttpResponseBase(HttpClientResponse reactorNettyResponse, HttpRequest httpRequest) { super(httpRequest); this.reactorNettyResponse = reactorNettyResponse; } @Override public final String getHeaderValue(String name) { return reactorNettyResponse.responseHeaders().get(name); } @Override public final int getStatusCode() { return reactorNettyResponse.status().code(); } @Override public final HttpHeaders getHeaders() { if (headers == null) { headers = new HttpHeadersWrapper(reactorNettyResponse.responseHeaders()); } return headers; } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/utils/AuthorizationChallengeHandler.java
package com.aliyun.netty.utils; import com.aliyun.core.utils.StringUtils; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * This class handles Basic and Digest authorization challenges, complying to RFC 2617 and RFC 7616. */ public class AuthorizationChallengeHandler { /* * RFC 2617 and 7616 specifies these characters to use when creating a hex string. */ private static final char[] HEX_CHARACTERS = "0123456789abcdef".toCharArray(); private static final String BASIC = "Basic "; private static final String DIGEST = "Digest "; private static final String ALGORITHM = "algorithm"; private static final String REALM = "realm"; private static final String NONCE = "nonce"; private static final String QOP = "qop"; private static final String AUTH = "auth"; private static final String AUTH_INT = "auth-int"; private static final String USERHASH = "userhash"; private static final String OPAQUE = "opaque"; private static final String NEXT_NONCE = "nextnonce"; /* * Digest proxy supports 3 unique algorithms in SHA-512/256, SHA-256, and MD5. Each algorithm is able to be used in * a <algorithm> and <algorithm>-sess variant, if the '-sess' variant is sent the response nonce and generated * cnonce (client nonce) will be used to calculate HA1. */ private static final String SESS = "-SESS"; private static final String SHA_512_256 = "SHA-512-256"; private static final String SHA_512_256_SESS = SHA_512_256 + SESS; private static final String SHA_256 = "SHA-256"; private static final String SHA_256_SESS = SHA_256 + SESS; private static final String MD5 = "MD5"; private static final String MD5_SESS = MD5 + SESS; // TODO: Prefer SESS based challenges? private static final String[] ALGORITHM_PREFERENCE_ORDER = { SHA_512_256, SHA_512_256_SESS, SHA_256, SHA_256_SESS, MD5, MD5_SESS }; /** * Header representing a server requesting authentication. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; /** * Header representing a proxy server requesting authentication. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** * Header representing the authorization the client is presenting to a server. */ public static final String AUTHORIZATION = "Authorization"; /** * Header representing the authorization the client is presenting to a proxy server. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** * Header representing additional information a server is expecting during future authentication requests. */ public static final String AUTHENTICATION_INFO = "Authentication-Info"; /** * Header representing additional information a proxy server is expecting during future authentication requests. */ public static final String PROXY_AUTHENTICATION_INFO = "Proxy-Authentication-Info"; private final String username; private final String password; private final Map<String, AtomicInteger> nonceTracker = new ConcurrentHashMap<>(); private final AtomicReference<String> authorizationPipeliningType = new AtomicReference<>(); private final AtomicReference<ConcurrentHashMap<String, String>> lastChallenge = new AtomicReference<>(); /** * Creates an {@link AuthorizationChallengeHandler} using the {@code username} and {@code password} to respond to * authentication challenges. * * @param username Username used to response to authorization challenges. * @param password Password used to respond to authorization challenges. * @throws NullPointerException If {@code username} or {@code password} are {@code null}. */ public AuthorizationChallengeHandler(String username, String password) { this.username = Objects.requireNonNull(username, "'username' cannot be null."); this.password = Objects.requireNonNull(password, "'password' cannot be null."); } /** * Handles Basic authentication challenges. * * @return Authorization header for Basic authentication challenges. */ public final String handleBasic() { authorizationPipeliningType.set(BASIC); String token = username + ":" + password; return BASIC + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)); } /** * Handles Digest authentication challenges. * * @param method HTTP method being used in the request. * @param uri Relative URI for the request. * @param challenges List of challenges that the server returned for the client to choose from and use when creating * the authorization header. * @param entityBodySupplier Supplies the request entity body, used to compute the hash of the body when using * {@code "qop=auth-int"}. * @return Authorization header for Digest authentication challenges. */ public final String handleDigest(String method, String uri, List<Map<String, String>> challenges, Supplier<byte[]> entityBodySupplier) { authorizationPipeliningType.set(DIGEST); Map<String, List<Map<String, String>>> challengesByType = partitionByChallengeType(challenges); for (String algorithm : ALGORITHM_PREFERENCE_ORDER) { // No challenges using this algorithm, skip it. if (!challengesByType.containsKey(algorithm)) { continue; } Function<byte[], byte[]> digestFunction = getDigestFunction(algorithm); // Unable to retrieve a digest for the specified algorithm, skip it. if (digestFunction == null) { continue; } ConcurrentHashMap<String, String> challenge = new ConcurrentHashMap<>(challengesByType.get(algorithm) .get(0)); lastChallenge.set(challenge); return createDigestAuthorizationHeader(method, uri, challenge, algorithm, entityBodySupplier, digestFunction); } return null; } /** * Attempts to pipeline requests by applying the most recent authorization type used to create an authorization * header. * * @param method HTTP method being used in the request. * @param uri Relative URI for the request. * @param entityBodySupplier Supplies the request entity body, used to compute the hash of the body when using * {@code "qop=auth-int"}. * @return A preemptive authorization header for a potential Digest authentication challenge. */ public final String attemptToPipelineAuthorization(String method, String uri, Supplier<byte[]> entityBodySupplier) { String pipeliningType = authorizationPipeliningType.get(); if (DIGEST.equals(pipeliningType)) { Map<String, String> challenge = new HashMap<>(lastChallenge.get()); String algorithm = challenge.get(ALGORITHM); if (algorithm == null) { algorithm = MD5; } return createDigestAuthorizationHeader(method, uri, challenge, algorithm, entityBodySupplier, getDigestFunction(algorithm)); } else if (BASIC.equals(pipeliningType)) { return handleBasic(); } return null; } /** * Consumes either the 'Authentication-Info' or 'Proxy-Authentication-Info' header returned in a response from a * server. This header is used by the server to communicate information about the successful authentication of the * client, this header may be returned at any time by the server. * * <p>See <a href="https://tools.ietf.org/html/rfc7615">RFC 7615</a> for more information about these headers.</p> * * @param authenticationInfoMap Either 'Authentication-Info' or 'Proxy-Authentication-Info' header returned from the * server split into its key-value pair pieces. */ public final void consumeAuthenticationInfoHeader(Map<String, String> authenticationInfoMap) { if (StringUtils.isEmpty(authenticationInfoMap)) { return; } /* * If the authentication info header has a nextnonce value set update the last challenge nonce value to it. * The nextnonce value indicates to the client which nonce value it should use to generate its response value. */ if (authenticationInfoMap.containsKey(NEXT_NONCE)) { lastChallenge.get().put(NONCE, authenticationInfoMap.get(NEXT_NONCE)); } } /** * Parses the {@code Authorization} or {@code Authentication} header into its key-value pairs. * <p> * This will remove quotes on quoted string values. * * @param header Authorization or Authentication header. * @return The Authorization or Authentication header split into its key-value pairs. */ public static Map<String, String> parseAuthenticationOrAuthorizationHeader(String header) { if (StringUtils.isEmpty(header)) { return Collections.emptyMap(); } if (header.startsWith(BASIC) || header.startsWith(DIGEST)) { header = header.split(" ", 2)[1]; } return Stream.of(header.split(",")) .map(String::trim) .map(kvp -> kvp.split("=", 2)) .collect(Collectors.toMap(kvpPieces -> kvpPieces[0].toLowerCase(Locale.ROOT), kvpPieces -> kvpPieces[1].replace("\"", ""))); } /* * Creates the Authorization header for the Digest authentication challenge. */ private String createDigestAuthorizationHeader(String method, String uri, Map<String, String> challenge, String algorithm, Supplier<byte[]> entityBodySupplier, Function<byte[], byte[]> digestFunction) { String realm = challenge.get(REALM); String nonce = challenge.get(NONCE); String qop = getQop(challenge.get(QOP)); String opaque = challenge.get(OPAQUE); boolean hashUsername = Boolean.parseBoolean(challenge.get(USERHASH)); /* * If the algorithm being used is <algorithm>-sess or QOP is 'auth' or 'auth-int' a client nonce will be needed * to calculate the authorization header. If the QOP is set a nonce-count will need to retrieved. */ int nc = 0; String clientNonce = null; if (AUTH.equals(qop) || AUTH_INT.equals(qop)) { clientNonce = generateNonce(); nc = getNc(challenge); } else if (algorithm.endsWith(SESS)) { clientNonce = generateNonce(); } String ha1 = algorithm.endsWith(SESS) ? calculateHa1Sess(digestFunction, realm, nonce, clientNonce) : calculateHa1NoSess(digestFunction, realm); String ha2 = AUTH_INT.equals(qop) ? calculateHa2AuthIntQop(digestFunction, method, uri, entityBodySupplier.get()) : calculateHa2AuthQopOrEmpty(digestFunction, method, uri); String response = (AUTH.equals(qop) || AUTH_INT.equals(qop)) ? calculateResponseKnownQop(digestFunction, ha1, nonce, nc, clientNonce, qop, ha2) : calculateResponseUnknownQop(digestFunction, ha1, nonce, ha2); String headerUsername = (hashUsername) ? calculateUserhash(digestFunction, realm) : username; return buildAuthorizationHeader(headerUsername, realm, uri, algorithm, nonce, nc, clientNonce, qop, response, opaque, hashUsername); } /* * Retrieves the nonce count for the given challenge. If the nonce in the challenge has already been used this will * increment and return the nonce count tracking, otherwise this will begin a new nonce tracking and return 1. */ private int getNc(Map<String, String> challenge) { String nonce = challenge.get(NONCE); if (nonceTracker.containsKey(nonce)) { return nonceTracker.get(nonce).incrementAndGet(); } else { nonceTracker.put(nonce, new AtomicInteger(1)); return 1; } } /* * Parses the qopHeader for the qop to use. If the qopHeader is null or only contains unknown qop types null will * be returned, otherwise the preference is 'auth' followed by 'auth-int'. */ private String getQop(String qopHeader) { if (StringUtils.isEmpty(qopHeader)) { return null; } else if (qopHeader.equalsIgnoreCase(AUTH)) { return AUTH; } else if (qopHeader.equalsIgnoreCase(AUTH_INT)) { return AUTH_INT; } else { return null; } } /* * Calculates the 'HA1' hex string when using an algorithm that isn't a '-sess' variant. * * This performs the following operations: * - Create the digest of (username + ":" + realm + ":" password). * - Return the resulting bytes as a hex string. */ private String calculateHa1NoSess(Function<byte[], byte[]> digestFunction, String realm) { return hexStringOf(digestFunction.apply(String.format("%s:%s:%s", username, realm, password) .getBytes(StandardCharsets.UTF_8))); } /* * Calculates the 'HA1' hex string when using a '-sess' algorithm variant. * * This performs the following operations: * - Create the digest of (username + ":" + realm + ":" password). * - Convert the resulting bytes to a hex string, aliased as userPassHex. * - Create the digest of (userPassHex + ":" nonce + ":" + cnonce). * - Return the resulting bytes as a hex string. */ private String calculateHa1Sess(Function<byte[], byte[]> digestFunction, String realm, String nonce, String cnonce) { return hexStringOf(digestFunction.apply(String.format("%s:%s:%s", calculateHa1NoSess(digestFunction, realm), nonce, cnonce).getBytes(StandardCharsets.UTF_8))); } /* * Calculates the 'HA2' hex string when using 'qop=auth' or the qop is unknown. * * This performs the following operations: * - Create the digest of (httpMethod + ":" + uri). * - Return the resulting bytes as a hex string. */ private String calculateHa2AuthQopOrEmpty(Function<byte[], byte[]> digestFunction, String httpMethod, String uri) { return hexStringOf(digestFunction.apply(String.format("%s:%s", httpMethod, uri) .getBytes(StandardCharsets.UTF_8))); } /* * Calculates the 'HA2' hex string when using 'qop=auth-int'. * * This performs the following operations: * - Create the digest of (requestEntityBody). * - Convert the resulting bytes to a hex string, aliased as bodyHex. * - Create the digest of (httpMethod + ":" + uri + ":" bodyHex). * - Return the resulting bytes as a hex string. * * The request entity body is the unmodified body of the request. Using 'qop=auth-int' requires the request body to * be replay-able, this is why 'auth' is preferred instead of auth-int as this cannot be guaranteed. In addition to * the body being replay-able this runs into risks when the body is very large and potentially consuming large * amounts of memory. */ private String calculateHa2AuthIntQop(Function<byte[], byte[]> digestFunction, String httpMethod, String uri, byte[] requestEntityBody) { return hexStringOf(digestFunction.apply(String.format("%s:%s:%s", httpMethod, uri, hexStringOf(digestFunction.apply(requestEntityBody))).getBytes(StandardCharsets.UTF_8))); } /* * Calculates the 'response' hex string when qop is unknown. * * This performs the following operations: * - Create the digest of (ha1 + ":" + nonce + ":" + ha2). * - Return the resulting bytes as a hex string. */ private String calculateResponseUnknownQop(Function<byte[], byte[]> digestFunction, String ha1, String nonce, String ha2) { return hexStringOf(digestFunction.apply(String.format("%s:%s:%s", ha1, nonce, ha2) .getBytes(StandardCharsets.UTF_8))); } /* * Calculates the 'response' hex string when 'qop=auth' or 'qop=auth-int'. * * This performs the following operations: * - Create the digest of (ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2). * - Return the resulting byes as a hex string. * * nc, nonce count, is represented in a hexadecimal format. */ private String calculateResponseKnownQop(Function<byte[], byte[]> digestFunction, String ha1, String nonce, int nc, String cnonce, String qop, String ha2) { return hexStringOf(digestFunction.apply(String.format("%s:%s:%08X:%s:%s:%s", ha1, nonce, nc, cnonce, qop, ha2) .getBytes(StandardCharsets.UTF_8))); } /* * Calculates the hashed username value if the authenticate challenge has 'userhash=true'. */ private String calculateUserhash(Function<byte[], byte[]> digestFunction, String realm) { return hexStringOf(digestFunction.apply(String.format("%s:%s", username, realm) .getBytes(StandardCharsets.UTF_8))); } /* * Attempts to retrieve the digest function for the specified algorithm. */ private static Function<byte[], byte[]> getDigestFunction(String algorithm) { if (algorithm.endsWith(SESS)) { algorithm = algorithm.substring(0, algorithm.length() - SESS.length()); } try { /* * The SHA-512-256 algorithm is the first half of SHA-512 and needs special handling compared to SHA-256 * and MD5. */ if (SHA_512_256.equals(algorithm)) { MessageDigest digest = MessageDigest.getInstance("SHA-512"); return (bytes) -> Arrays.copyOf(digest.digest(bytes), 32); } else { MessageDigest digest = MessageDigest.getInstance(algorithm); return digest::digest; } } catch (NoSuchAlgorithmException e) { return null; } } /* * Splits the Authenticate challenges by the algorithm it uses. */ private static Map<String, List<Map<String, String>>> partitionByChallengeType( List<Map<String, String>> challenges) { return challenges.stream().collect(Collectors.groupingBy(headers -> { String algorithmHeader = headers.get(ALGORITHM); // RFC7616 specifies that is the "algorithm" header is null it defaults to MD5. return (algorithmHeader == null) ? MD5 : algorithmHeader.toUpperCase(Locale.ROOT); })); } /* * Creates a unique and secure nonce. */ String generateNonce() { byte[] nonce = new byte[16]; new SecureRandom().nextBytes(nonce); return hexStringOf(nonce); } /* * Creates the Authorization/Proxy-Authorization header value based on the computed Digest authentication value. */ private static String buildAuthorizationHeader(String username, String realm, String uri, String algorithm, String nonce, int nc, String cnonce, String qop, String response, String opaque, boolean userhash) { StringBuilder authorizationBuilder = new StringBuilder(DIGEST); authorizationBuilder.append("username=\"").append(username).append("\", ") .append("realm=\"").append(realm).append("\", ") .append("nonce=\"").append(nonce).append("\", ") .append("uri=\"").append(uri).append("\", ") .append("response=\"").append(response).append("\""); if (!StringUtils.isEmpty(algorithm)) { authorizationBuilder.append(", ").append("algorithm=").append(algorithm); } if (!StringUtils.isEmpty(cnonce)) { authorizationBuilder.append(", ").append("cnonce=\"").append(cnonce).append("\""); } if (!StringUtils.isEmpty(opaque)) { authorizationBuilder.append(", ").append("opaque=\"").append(opaque).append("\""); } if (!StringUtils.isEmpty(qop)) { authorizationBuilder.append(", ").append("qop=").append(qop); authorizationBuilder.append(", ").append("nc=").append(String.format("%08X", nc)); } if (userhash) { authorizationBuilder.append(", ").append("userhash=").append(true); } return authorizationBuilder.toString(); } /* * Converts the passed byte array into a hex string. */ private static String hexStringOf(byte[] bytes) { // Hex uses 4 bits, converting a byte to hex will double its size. char[] hexCharacters = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { // Convert the byte into an integer, masking all but the last 8 bits (the byte). int b = bytes[i] & 0xFF; // Shift 4 times to the right to get the leading 4 bits and get the corresponding hex character. hexCharacters[i * 2] = HEX_CHARACTERS[b >>> 4]; // Mask all but the last 4 bits and get the corresponding hex character. hexCharacters[i * 2 + 1] = HEX_CHARACTERS[b & 0x0F]; } return new String(hexCharacters); } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/utils/ByteBufferCollector.java
package com.aliyun.netty.utils; import com.aliyun.core.logging.ClientLogger; import java.nio.ByteBuffer; import java.util.Arrays; public final class ByteBufferCollector { /* * Start with a default size of 1 KB as this is small enough to be performant while covering most small response * sizes. */ private static final int DEFAULT_INITIAL_SIZE = 1024; private static final String INVALID_INITIAL_SIZE = "'initialSize' cannot be equal to or less than 0."; private static final String REQUESTED_BUFFER_INVALID = "Required capacity is greater than Integer.MAX_VALUE."; private final ClientLogger logger = new ClientLogger(ByteBufferCollector.class); private byte[] buffer; private int position; /** * Constructs a new ByteBufferCollector instance with a default sized backing array. */ public ByteBufferCollector() { this(DEFAULT_INITIAL_SIZE); } /** * Constructs a new ByteBufferCollector instance with a specified initial size. * * @param initialSize The initial size for the backing array. * @throws IllegalArgumentException If {@code initialSize} is equal to or less than {@code 0}. */ public ByteBufferCollector(int initialSize) { if (initialSize <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_INITIAL_SIZE)); } this.buffer = new byte[initialSize]; this.position = 0; } /** * Writes a ByteBuffers content into the backing array. * * @param byteBuffer The ByteBuffer to concatenate into the collector. * @throws IllegalStateException If the size of the backing array would be larger than {@link Integer#MAX_VALUE} * when the passed buffer is written. */ public synchronized void write(ByteBuffer byteBuffer) { // Null buffer. if (byteBuffer == null) { return; } int remaining = byteBuffer.remaining(); // Nothing to write. if (remaining == 0) { return; } ensureCapacity(remaining); byteBuffer.get(buffer, position, remaining); position += remaining; } /** * Creates a copy of the backing array resized to the number of bytes written into the collector. * * @return A copy of the backing array. */ public synchronized byte[] toByteArray() { return Arrays.copyOf(buffer, position); } /* * This method ensures that the backing buffer has sufficient space to write the data from the passed ByteBuffer. */ private void ensureCapacity(int byteBufferRemaining) throws OutOfMemoryError { int currentCapacity = buffer.length; int requiredCapacity = position + byteBufferRemaining; /* * This validates that adding the current capacity and ByteBuffer remaining doesn't result in an integer * overflow response by checking that the result uses the same sign as both of the addition arguments. */ if (((position ^ requiredCapacity) & (byteBufferRemaining ^ requiredCapacity)) < 0) { throw logger.logExceptionAsError(new IllegalStateException(REQUESTED_BUFFER_INVALID)); } // Buffer is already large enough to accept the data being written. if (currentCapacity >= requiredCapacity) { return; } // Propose a new capacity that is double the size of the current capacity. int proposedNewCapacity = currentCapacity << 1; // If the proposed capacity is less than the required capacity use the required capacity. // Subtraction is used instead of a direct comparison as the bit shift could overflow into a negative int. if ((proposedNewCapacity - requiredCapacity) < 0) { proposedNewCapacity = requiredCapacity; } // If the proposed capacity doubling overflowed integer use a slightly smaller size than max value. if (proposedNewCapacity < 0) { proposedNewCapacity = Integer.MAX_VALUE - 8; } buffer = Arrays.copyOf(buffer, proposedNewCapacity); } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/utils/FluxToCompletableFuture.java
package com.aliyun.netty.utils; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.publisher.Operators; import reactor.util.context.Context; public final class FluxToCompletableFuture<T> extends CompletableFuture<T> implements Subscriber<T> { final AtomicReference<Subscription> ref = new AtomicReference(); final boolean cancelSourceOnNext; public FluxToCompletableFuture(boolean sourceCanEmitMoreThanOnce) { this.cancelSourceOnNext = sourceCanEmitMoreThanOnce; } public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = super.cancel(mayInterruptIfRunning); if (cancelled) { Subscription s = (Subscription)this.ref.getAndSet(null); if (s != null) { s.cancel(); } } return cancelled; } public void onSubscribe(Subscription s) { if (Operators.validate((Subscription)this.ref.getAndSet(s), s)) { s.request(9223372036854775807L); } else { s.cancel(); } } public void onNext(T t) { Subscription s = (Subscription)this.ref.getAndSet(null); if (s != null) { this.complete(t); if (this.cancelSourceOnNext) { s.cancel(); } } else { Operators.onNextDropped(t, this.currentContext()); } } public void onError(Throwable t) { if (this.ref.getAndSet(null) != null) { this.completeExceptionally(t); } } public void onComplete() { if (this.ref.getAndSet(null) != null) { this.complete(null); } } public Context currentContext() { return Context.empty(); } }
0
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty
java-sources/com/aliyun/aliyun-http-netty/0.3.2-beta/com/aliyun/netty/utils/FluxUtil.java
package com.aliyun.netty.utils; import com.aliyun.core.http.HttpHeaders; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.Context; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.TypeUtil; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.core.Exceptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Operators; import reactor.util.context.ContextView; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.CompletionHandler; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.function.Function; import java.util.stream.Collectors; /** * Utility type exposing methods to deal with {@link Flux}. */ public final class FluxUtil { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * Checks if a type is Flux&lt;ByteBuffer&gt;. * * @param entityType the type to check * @return whether the type represents a Flux that emits ByteBuffer */ public static boolean isFluxByteBuffer(Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Flux.class)) { final Type innerType = TypeUtil.getTypeArguments(entityType)[0]; return TypeUtil.isTypeOrSubTypeOf(innerType, ByteBuffer.class); } return false; } /** * Collects ByteBuffers emitted by a Flux into a byte array. * * @param stream A stream which emits ByteBuffer instances. * @return A Mono which emits the concatenation of all the ByteBuffer instances given by the source Flux. * @throws IllegalStateException If the combined size of the emitted ByteBuffers is greater than {@link * Integer#MAX_VALUE}. */ public static Mono<byte[]> collectBytesInByteBufferStream(Flux<ByteBuffer> stream) { return stream.collect(ByteBufferCollector::new, ByteBufferCollector::write) .map(ByteBufferCollector::toByteArray); } /** * Collects ByteBuffers emitted by a Flux into a byte array. * <p> * Unlike {@link #collectBytesInByteBufferStream(Flux)}, this method accepts a second parameter {@code sizeHint}. * This size hint allows for optimizations when creating the initial buffer to reduce the number of times it needs * to be resized while concatenating emitted ByteBuffers. * * @param stream A stream which emits ByteBuffer instances. * @param sizeHint A hint about the expected stream size. * @return A Mono which emits the concatenation of all the ByteBuffer instances given by the source Flux. * @throws IllegalArgumentException If {@code sizeHint} is equal to or less than {@code 0}. * @throws IllegalStateException If the combined size of the emitted ByteBuffers is greater than {@link * Integer#MAX_VALUE}. */ public static Mono<byte[]> collectBytesInByteBufferStream(Flux<ByteBuffer> stream, int sizeHint) { return stream.collect(() -> new ByteBufferCollector(sizeHint), ByteBufferCollector::write) .map(ByteBufferCollector::toByteArray); } /** * Collects ByteBuffers returned in a network response into a byte array. * <p> * The {@code headers} are inspected for containing an {@code Content-Length} which determines if a size hinted * collection, {@link #collectBytesInByteBufferStream(Flux, int)}, or default collection, {@link * #collectBytesInByteBufferStream(Flux)}, will be used. * * @param stream A network response ByteBuffer stream. * @param headers The HTTP headers of the response. * @return A Mono which emits the collected network response ByteBuffers. * @throws NullPointerException If {@code headers} is null. * @throws IllegalStateException If the size of the network response is greater than {@link Integer#MAX_VALUE}. */ public static Mono<byte[]> collectBytesFromNetworkResponse(Flux<ByteBuffer> stream, HttpHeaders headers) { Objects.requireNonNull(headers, "'headers' cannot be null."); String contentLengthHeader = headers.getValue("Content-Length"); if (contentLengthHeader == null) { return FluxUtil.collectBytesInByteBufferStream(stream); } else { try { int contentLength = Integer.parseInt(contentLengthHeader); if (contentLength > 0) { return FluxUtil.collectBytesInByteBufferStream(stream, contentLength); } else { return Mono.just(EMPTY_BYTE_ARRAY); } } catch (NumberFormatException ex) { return FluxUtil.collectBytesInByteBufferStream(stream); } } } /** * Gets the content of the provided ByteBuffer as a byte array. This method will create a new byte array even if the * ByteBuffer can have optionally backing array. * * @param byteBuffer the byte buffer * @return the byte array */ public static byte[] byteBufferToArray(ByteBuffer byteBuffer) { int length = byteBuffer.remaining(); byte[] byteArray = new byte[length]; byteBuffer.get(byteArray); return byteArray; } /** * Converts an {@link InputStream} into a {@link Flux} of {@link ByteBuffer} using a chunk size of 4096. * <p> * Given that {@link InputStream} is not guaranteed to be replayable the returned {@link Flux} should be considered * non-replayable as well. * <p> * If the passed {@link InputStream} is {@code null} {@link Flux#empty()} will be returned. * * @param inputStream The {@link InputStream} to convert into a {@link Flux}. * @return A {@link Flux} of {@link ByteBuffer ByteBuffers} that contains the contents of the stream. */ public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { return toFluxByteBuffer(inputStream, 4096); } /** * Converts an {@link InputStream} into a {@link Flux} of {@link ByteBuffer}. * <p> * Given that {@link InputStream} is not guaranteed to be replayable the returned {@link Flux} should be considered * non-replayable as well. * <p> * If the passed {@link InputStream} is {@code null} {@link Flux#empty()} will be returned. * * @param inputStream The {@link InputStream} to convert into a {@link Flux}. * @param chunkSize The requested size for each {@link ByteBuffer}. * @return A {@link Flux} of {@link ByteBuffer ByteBuffers} that contains the contents of the stream. * @throws IllegalArgumentException If {@code chunkSize} is less than or equal to {@code 0}. */ public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream, int chunkSize) { if (chunkSize <= 0) { return Flux.error(new IllegalArgumentException("'chunkSize' must be greater than 0.")); } if (inputStream == null) { return Flux.empty(); } return Flux.<ByteBuffer, InputStream>generate(() -> inputStream, (stream, sink) -> { byte[] buffer = new byte[chunkSize]; try { int offset = 0; while (offset < chunkSize) { int readCount = inputStream.read(buffer, offset, chunkSize - offset); // We have finished reading the stream, trigger onComplete. if (readCount == -1) { // If there were bytes read before reaching the end emit the buffer before completing. if (offset > 0) { sink.next(ByteBuffer.wrap(buffer, 0, offset)); } sink.complete(); return stream; } offset += readCount; } sink.next(ByteBuffer.wrap(buffer)); } catch (IOException ex) { sink.error(ex); } return stream; }).filter(ByteBuffer::hasRemaining); } public static <T> Mono<T> withContext(Function<Context, Mono<T>> serviceCall) { return withContext(serviceCall, Collections.emptyMap()); } public static <T> Mono<T> withContext(Function<Context, Mono<T>> serviceCall, Map<String, String> contextAttributes) { return Mono.deferContextual(context -> { final Context[] azureContext = new Context[]{Context.NONE}; if (!StringUtils.isEmpty(contextAttributes)) { contextAttributes.forEach((key, value) -> azureContext[0] = azureContext[0].addData(key, value)); } if (!context.isEmpty()) { context.stream().forEach(entry -> azureContext[0] = azureContext[0].addData(entry.getKey(), entry.getValue())); } return serviceCall.apply(azureContext[0]); }); } // public static <T> Mono<T> toMono(Response<T> response) { // return Mono.justOrEmpty(response.getValue()); // } /** * Propagates a {@link RuntimeException} through the error channel of {@link Mono}. * * @param logger The {@link ClientLogger} to log the exception. * @param ex The {@link RuntimeException}. * @param <T> The return type. * @return A {@link Mono} that terminates with error wrapping the {@link RuntimeException}. */ public static <T> Mono<T> monoError(ClientLogger logger, RuntimeException ex) { return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex))); } /** * Propagates a {@link RuntimeException} through the error channel of {@link Flux}. * * @param logger The {@link ClientLogger} to log the exception. * @param ex The {@link RuntimeException}. * @param <T> The return type. * @return A {@link Flux} that terminates with error wrapping the {@link RuntimeException}. */ public static <T> Flux<T> fluxError(ClientLogger logger, RuntimeException ex) { return Flux.error(logger.logExceptionAsError(Exceptions.propagate(ex))); } /** * This method converts the incoming {@code deferContextual} from {@link reactor.util.context.Context Reactor * Context} to {@link Context Azure Context} and calls the given lambda function with this context and returns a * collection of type {@code T} * <p> * If the reactor context is empty, {@link Context#NONE} will be used to call the lambda function * </p> * * <p><strong>Code samples</strong></p> * {@codesnippet com.azure.core.implementation.util.fluxutil.fluxcontext} * * @param serviceCall The lambda function that makes the service call into which the context will be passed * @param <T> The type of response returned from the service call * @return The response from service call */ public static <T> Flux<T> fluxContext(Function<Context, Flux<T>> serviceCall) { return Flux.deferContextual(context -> serviceCall.apply(toAzureContext(context))); } /** * Converts a reactor context to azure context. If the reactor context is {@code null} or empty, {@link * Context#NONE} will be returned. * * @param context The reactor context * @return The azure context */ private static Context toAzureContext(ContextView context) { final Context[] azureContext = new Context[]{Context.NONE}; if (!context.isEmpty()) { context.stream().forEach(entry -> azureContext[0] = azureContext[0].addData(entry.getKey(), entry.getValue())); } return azureContext[0]; } /** * Converts an Azure context to Reactor context. If the Azure context is {@code null} or empty, {@link * reactor.util.context.Context#empty()} will be returned. * * @param context The Azure context. * @return The Reactor context. */ public static reactor.util.context.Context toReactorContext(Context context) { if (context == null) { return reactor.util.context.Context.empty(); } // Filter out null value entries as Reactor's context doesn't allow null values. Map<Object, Object> contextValues = context.getValues().entrySet().stream() .filter(kvp -> kvp.getValue() != null) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); return StringUtils.isEmpty(contextValues) ? reactor.util.context.Context.empty() : reactor.util.context.Context.of(contextValues); } /** * Writes the bytes emitted by a Flux to an AsynchronousFileChannel. * * @param content the Flux content * @param outFile the file channel * @return a Mono which performs the write operation when subscribed */ public static Mono<Void> writeFile(Flux<ByteBuffer> content, AsynchronousFileChannel outFile) { return writeFile(content, outFile, 0); } /** * Writes the bytes emitted by a Flux to an AsynchronousFileChannel starting at the given position in the file. * * @param content the Flux content * @param outFile the file channel * @param position the position in the file to begin writing * @return a Mono which performs the write operation when subscribed */ public static Mono<Void> writeFile(Flux<ByteBuffer> content, AsynchronousFileChannel outFile, long position) { return Mono.create(emitter -> content.subscribe(new Subscriber<ByteBuffer>() { // volatile ensures that writes to these fields by one thread will be immediately visible to other threads. // An I/O pool thread will write to isWriting and read isCompleted, // while another thread may read isWriting and write to isCompleted. volatile boolean isWriting = false; volatile boolean isCompleted = false; volatile Subscription subscription; volatile long pos = position; @Override public void onSubscribe(Subscription s) { subscription = s; s.request(1); } @Override public void onNext(ByteBuffer bytes) { isWriting = true; outFile.write(bytes, pos, null, onWriteCompleted); } final CompletionHandler<Integer, Object> onWriteCompleted = new CompletionHandler<Integer, Object>() { @Override public void completed(Integer bytesWritten, Object attachment) { isWriting = false; if (isCompleted) { emitter.success(); } //noinspection NonAtomicOperationOnVolatileField pos += bytesWritten; subscription.request(1); } @Override public void failed(Throwable exc, Object attachment) { subscription.cancel(); emitter.error(exc); } }; @Override public void onError(Throwable throwable) { subscription.cancel(); emitter.error(throwable); } @Override public void onComplete() { isCompleted = true; if (!isWriting) { emitter.success(); } } })); } /** * Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads part of a file into chunks of the * given size. * * @param fileChannel The file channel. * @param chunkSize the size of file chunks to read. * @param offset The offset in the file to begin reading. * @param length The number of bytes to read from the file. * @return the Flux. */ public static Flux<ByteBuffer> readFile(AsynchronousFileChannel fileChannel, int chunkSize, long offset, long length) { return new FileReadFlux(fileChannel, chunkSize, offset, length); } /** * Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads part of a file. * * @param fileChannel The file channel. * @param offset The offset in the file to begin reading. * @param length The number of bytes to read from the file. * @return the Flux. */ public static Flux<ByteBuffer> readFile(AsynchronousFileChannel fileChannel, long offset, long length) { return readFile(fileChannel, DEFAULT_CHUNK_SIZE, offset, length); } /** * Creates a {@link Flux} from an {@link AsynchronousFileChannel} which reads the entire file. * * @param fileChannel The file channel. * @return The AsyncInputStream. */ public static Flux<ByteBuffer> readFile(AsynchronousFileChannel fileChannel) { try { long size = fileChannel.size(); return readFile(fileChannel, DEFAULT_CHUNK_SIZE, 0, size); } catch (IOException e) { return Flux.error(new RuntimeException("Failed to read the file.", e)); } } private static final int DEFAULT_CHUNK_SIZE = 1024 * 64; private static final class FileReadFlux extends Flux<ByteBuffer> { private final AsynchronousFileChannel fileChannel; private final int chunkSize; private final long offset; private final long length; FileReadFlux(AsynchronousFileChannel fileChannel, int chunkSize, long offset, long length) { this.fileChannel = fileChannel; this.chunkSize = chunkSize; this.offset = offset; this.length = length; } @Override public void subscribe(CoreSubscriber<? super ByteBuffer> actual) { FileReadSubscription subscription = new FileReadSubscription(actual, fileChannel, chunkSize, offset, length); actual.onSubscribe(subscription); } static final class FileReadSubscription implements Subscription, CompletionHandler<Integer, ByteBuffer> { private static final int NOT_SET = -1; private static final long serialVersionUID = -6831808726875304256L; // private final Subscriber<? super ByteBuffer> subscriber; private volatile long position; // private final AsynchronousFileChannel fileChannel; private final int chunkSize; private final long offset; private final long length; // private volatile boolean done; private Throwable error; private volatile ByteBuffer next; private volatile boolean cancelled; // volatile int wip; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<FileReadSubscription> WIP = AtomicIntegerFieldUpdater.newUpdater(FileReadSubscription.class, "wip"); volatile long requested; @SuppressWarnings("rawtypes") static final AtomicLongFieldUpdater<FileReadSubscription> REQUESTED = AtomicLongFieldUpdater.newUpdater(FileReadSubscription.class, "requested"); // FileReadSubscription(Subscriber<? super ByteBuffer> subscriber, AsynchronousFileChannel fileChannel, int chunkSize, long offset, long length) { this.subscriber = subscriber; // this.fileChannel = fileChannel; this.chunkSize = chunkSize; this.offset = offset; this.length = length; // this.position = NOT_SET; } //region Subscription implementation @Override public void request(long n) { if (Operators.validate(n)) { Operators.addCap(REQUESTED, this, n); drain(); } } @Override public void cancel() { this.cancelled = true; } //endregion //region CompletionHandler implementation @Override public void completed(Integer bytesRead, ByteBuffer buffer) { if (!cancelled) { if (bytesRead == -1) { done = true; } else { // use local variable to perform fewer volatile reads long pos = position; int bytesWanted = Math.min(bytesRead, maxRequired(pos)); long position2 = pos + bytesWanted; //noinspection NonAtomicOperationOnVolatileField position = position2; buffer.position(bytesWanted); buffer.flip(); next = buffer; if (position2 >= offset + length) { done = true; } } drain(); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { if (!cancelled) { // must set error before setting done to true // so that is visible in drain loop error = exc; done = true; drain(); } } //endregion private void drain() { if (WIP.getAndIncrement(this) != 0) { return; } // on first drain (first request) we initiate the first read if (position == NOT_SET) { position = offset; doRead(); } int missed = 1; while (true) { if (cancelled) { return; } if (REQUESTED.get(this) > 0) { boolean emitted = false; // read d before next to avoid race boolean d = done; ByteBuffer bb = next; if (bb != null) { next = null; subscriber.onNext(bb); emitted = true; } if (d) { if (error != null) { subscriber.onError(error); } else { subscriber.onComplete(); } // exit without reducing wip so that further drains will be NOOP return; } if (emitted) { // do this after checking d to avoid calling read // when done Operators.produced(REQUESTED, this, 1); // doRead(); } } missed = WIP.addAndGet(this, -missed); if (missed == 0) { return; } } } private void doRead() { // use local variable to limit volatile reads long pos = position; ByteBuffer innerBuf = ByteBuffer.allocate(Math.min(chunkSize, maxRequired(pos))); fileChannel.read(innerBuf, pos, innerBuf, this); } private int maxRequired(long pos) { long maxRequired = offset + length - pos; if (maxRequired <= 0) { return 0; } else { int m = (int) (maxRequired); // support really large files by checking for overflow if (m < 0) { return Integer.MAX_VALUE; } else { return m; } } } } } // Private Ctr private FluxUtil() { } }
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/OkHttpAsyncClient.java
package okhttp; import com.aliyun.core.http.ProxyOptions; import com.aliyun.core.utils.HttpClientOptions; import okhttp3.OkHttpClient; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; public class OkHttpAsyncClient { public static final ConcurrentHashMap<String, OkHttpClient> clients = new ConcurrentHashMap<String, OkHttpClient>(); public static CompletableFuture<OkHttpClient> getOkHttpClient(String host, int port, ProxyOptions proxyOptions) throws Exception { CompletableFuture<OkHttpClient> clientFuture = CompletableFuture.supplyAsync(new Supplier<OkHttpClient>() { @Override public OkHttpClient get() { String key; if (null != proxyOptions.getType()) { key = getClientKey(proxyOptions.getAddress().getHostString(), proxyOptions.getAddress().getPort()); } else { key = getClientKey(host, port); } OkHttpClient client = clients.get(key); if (null == client) { try { client = createClient(proxyOptions).get(); } catch (Exception e) { e.printStackTrace(); } clients.put(key, client); } return client; } }); return clientFuture; } public static CompletableFuture<OkHttpClient> createClient(HttpClientOptions clientOptions) { CompletableFuture<OkHttpClient> okHttpClientFuture = CompletableFuture.supplyAsync(new Supplier<OkHttpClient>() { @Override public OkHttpClient get() { OkHttpAsyncClientBuilder builder = new OkHttpAsyncClientBuilder(); builder = builder.proxy(clientOptions).readTimeout(clientOptions.getReadTimeout()); OkHttpClient client = builder.buildOkHttpClient(); return client; } }); return okHttpClientFuture; } public static CompletableFuture<OkHttpClient> createClient(ProxyOptions proxyOptions) { CompletableFuture<OkHttpClient> okHttpClientFuture = CompletableFuture.supplyAsync(new Supplier<OkHttpClient>() { @Override public OkHttpClient get() { OkHttpAsyncClientBuilder builder = new OkHttpAsyncClientBuilder(); builder = builder.proxy(proxyOptions); OkHttpClient client = builder.buildOkHttpClient(); return client; } }); return okHttpClientFuture; } public static String getClientKey(String host, int port) { return String.format("%s:%d", host, port); } }
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/OkHttpAsyncClientBuilder.java
package okhttp; import com.aliyun.core.exception.AliyunException; import com.aliyun.core.http.ProxyOptions; import com.aliyun.core.utils.HttpClientOptions; import okhttp.utils.TrueHostnameVerifier; import okhttp.utils.X509TrustManagerImp; import okhttp3.*; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.time.Duration; public class OkHttpAsyncClientBuilder { private OkHttpClient.Builder builder; private ProxyOptions proxyOptions; private HttpClientOptions clientOptions; private Duration connectionTimeout; private Duration readTimeout; private ConnectionPool connectionPool; public OkHttpAsyncClientBuilder() { builder = new OkHttpClient().newBuilder(); } public OkHttpAsyncClientBuilder connectTimeout(Duration connectionTimeout) { if (null == connectionTimeout) { this.connectionTimeout = Duration.ofSeconds(10); } this.connectionTimeout = connectionTimeout; return this; } public OkHttpAsyncClientBuilder readTimeout(Duration readTimeout) { if (null == readTimeout) { this.readTimeout = Duration.ofSeconds(10); } this.readTimeout = readTimeout; return this; } public OkHttpAsyncClientBuilder connectionPool(ConnectionPool connectionPool) { this.builder.connectionPool(connectionPool); return this; } public OkHttpAsyncClientBuilder certificate(Boolean bool) { try { if (bool) { X509TrustManager compositeX509TrustManager = new X509TrustManagerImp(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{compositeX509TrustManager}, new java.security.SecureRandom()); this.builder.sslSocketFactory(sslContext.getSocketFactory(), compositeX509TrustManager). hostnameVerifier(new TrueHostnameVerifier()); } return this; } catch (Exception e) { throw new AliyunException(e.getMessage(), e); } } public OkHttpAsyncClientBuilder proxy(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public OkHttpAsyncClientBuilder proxy(HttpClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } public OkHttpAsyncClientBuilder proxyAuthenticator(ProxyOptions proxyOptions) { final String credential = Credentials.basic(proxyOptions.getUsername(), proxyOptions.getPassword()); Authenticator authenticator = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { return response.request().newBuilder() .header("Proxy-Authorization", credential) .build(); } }; this.builder.proxyAuthenticator(authenticator); return this; } public OkHttpClient buildOkHttpClient() { return this.builder.build(); } }
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/OkHttpAsyncProvider.java
package okhttp; import com.aliyun.core.http.ProxyOptions; import com.aliyun.core.utils.HttpClientOptions; import okhttp3.OkHttpClient; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; public class OkHttpAsyncProvider { public OkHttpClient createInstance() { return new OkHttpAsyncClientBuilder().buildOkHttpClient(); } public CompletableFuture<OkHttpClient> createInstance(HttpClientOptions clientOptions) { CompletableFuture<OkHttpClient> clientFuture = CompletableFuture.supplyAsync(new Supplier<OkHttpClient>() { @Override public OkHttpClient get() { OkHttpAsyncClientBuilder builder = new OkHttpAsyncClientBuilder(); if (clientOptions != null) { builder = builder.proxy(clientOptions.getProxyOptions()).readTimeout(clientOptions.getReadTimeout()); } return builder.buildOkHttpClient(); } }); return clientFuture; } public CompletableFuture<OkHttpClient> createInstance(ProxyOptions proxyOptions) { CompletableFuture<OkHttpClient> clientFuture = CompletableFuture.supplyAsync(new Supplier<OkHttpClient>() { @Override public OkHttpClient get() { OkHttpAsyncClientBuilder builder = new OkHttpAsyncClientBuilder(); if (proxyOptions != null) { builder = builder.proxy(proxyOptions); } return builder.buildOkHttpClient(); } }); return clientFuture; } }
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/asynchttp/AsyncRequestBody.java
//package okhttp.asynchttp; // //import com.aliyun.core.utils.StringUtils; //import okhttp3.MediaType; //import okhttp3.RequestBody; //import okio.BufferedSink; // //import java.io.IOException; //import java.io.InputStream; //import java.util.concurrent.CompletableFuture; // //public class AsyncRequestBody extends RequestBody { // // private InputStream inputStream; // private String contentType; // // public AsyncRequestBody(TeaRequest teaRequest) { // this.inputStream = teaRequest.body; // this.contentType = teaRequest.headers.get("content-type"); // } // // @Override // public MediaType contentType() { // MediaType type; // if (StringUtils.isEmpty(contentType)) { // if (null == inputStream) { // return null; // } // type = MediaType.parse("application/json; charset=UTF-8;"); // return type; // } // return MediaType.parse(contentType); // } // // @Override // public long contentLength() throws IOException { // if (null != inputStream && inputStream.available() > 0) { // return inputStream.available(); // } // return super.contentLength(); // } // // @Override // public void writeTo(BufferedSink bufferedSink) { // CompletableFuture future = CompletableFuture.runAsync(new Runnable() { // @Override // public void run() { // if (null == inputStream) { // return; // } // byte[] buffer = new byte[4096]; // int bytesRead; // try { // while ((bytesRead = inputStream.read(buffer)) != -1) { // bufferedSink.write(buffer, 0, bytesRead); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } //}
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/asynchttp/AsyncRequestBuilder.java
//package okhttp.asynchttp; // //import darabonba.core.TeaRequest; //import okhttp.synhttp.OkRequestBody; //import okhttp3.Request; // //import java.net.URL; //import java.util.Map; //import java.util.concurrent.CompletableFuture; //import java.util.function.Supplier; // //public class AsyncRequestBuilder { // private Request.Builder builder; // // public AsyncRequestBuilder(Request.Builder builder) { // this.builder = builder; // } // // public AsyncRequestBuilder url(URL url) { // this.builder.url(url); // return this; // } // // public AsyncRequestBuilder header(Map<String, String> headers) { // headers.keySet().stream() // .map(headerName -> this.builder.header(headerName, headers.get(headerName))); // return this; // } // // public CompletableFuture<Request> buildRequest(TeaRequest request) { // Request.Builder builderRequest = builder; // CompletableFuture<Request> requestFuture = CompletableFuture.supplyAsync(new Supplier<Request>() { // @Override // public Request get() { // String method = request.method.toUpperCase(); // OkRequestBody requestBody; // switch (method) { // case "DELETE": // builderRequest.delete(); // break; // case "POST": // requestBody = new OkRequestBody(request); // builderRequest.post(requestBody); // break; // case "PUT": // requestBody = new OkRequestBody(request); // builderRequest.put(requestBody); // break; // case "PATCH": // requestBody = new OkRequestBody(request); // builderRequest.patch(requestBody); // break; // default: // builderRequest.get(); // break; // } // return builderRequest.build(); // } // }); // return requestFuture; // } //} //
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/synhttp/ClientHelper.java
//package okhttp.synhttp; // //import okhttp3.OkHttpClient; // //import java.net.URL; //import java.util.Map; //import java.util.concurrent.ConcurrentHashMap; // //public class ClientHelper { // public static final ConcurrentHashMap<String, OkHttpClient> clients = new ConcurrentHashMap<String, OkHttpClient>(); // // public static OkHttpClient getOkHttpClient(String host, int port, Map<String, Object> map) throws Exception { // String key; // if (null != map.get("httpProxy") || null != map.get("httpsProxy")) { // Object urlString = null == map.get("httpProxy") ? map.get("httpsProxy") : map.get("httpProxy"); // URL url = new URL(String.valueOf(urlString)); // key = getClientKey(url.getHost(), url.getPort()); // } else { // key = getClientKey(host, port); // } // OkHttpClient client = clients.get(key); // if (null == client) { // client = createClient(map); // clients.put(key, client); // } // return client; // } // // public static OkHttpClient createClient(Map<String, Object> map) { // OkHttpClientBuilder builder = new OkHttpClientBuilder(); // builder = builder.connectTimeout(map).readTimeout(map).connectionPool(map).certificate(map).proxy(map).proxyAuthenticator(map); // OkHttpClient client = builder.buildOkHttpClient(); // return client; // } // // public static String getClientKey(String host, int port) { // return String.format("%s:%d", host, port); // } //}
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/synhttp/OkHttpClientBuilder.java
//package okhttp.synhttp; // //import darabonba.core.exception.TeaException; //import darabonba.core.utils.TrueHostnameVerifier; //import darabonba.core.utils.X509TrustManagerImp; //import okhttp3.*; // //import javax.net.ssl.SSLContext; //import javax.net.ssl.TrustManager; //import javax.net.ssl.X509TrustManager; //import java.io.IOException; //import java.net.InetSocketAddress; //import java.net.Proxy; //import java.net.URL; //import java.util.Map; //import java.util.concurrent.TimeUnit; // //public class OkHttpClientBuilder { // private OkHttpClient.Builder builder; // // public OkHttpClientBuilder() { // builder = new OkHttpClient().newBuilder(); // } // // public OkHttpClientBuilder connectTimeout(Map<String, Object> map) { // Object object = map.get("connectTimeout"); // long timeout; // try { // timeout = Long.parseLong(String.valueOf(object)); // } catch (Exception e) { // return this; // } // this.builder.connectTimeout(timeout, TimeUnit.MILLISECONDS); // return this; // } // // public OkHttpClientBuilder readTimeout(Map<String, Object> map) { // Object object = map.get("readTimeout"); // long timeout; // try { // timeout = Long.parseLong(String.valueOf(object)); // } catch (Exception e) { // return this; // } // this.builder.readTimeout(timeout, TimeUnit.MILLISECONDS); // return this; // } // // public OkHttpClientBuilder connectionPool(Map<String, Object> map) { // Object maxIdleConns = map.get("maxIdleConns"); // int maxIdleConnections; // try { // maxIdleConnections = Integer.parseInt(String.valueOf(maxIdleConns)); // } catch (Exception e) { // maxIdleConnections = 5; // } // ConnectionPool connectionPool = new ConnectionPool(maxIdleConnections, 10000L, TimeUnit.MILLISECONDS); // this.builder.connectionPool(connectionPool); // return this; // } // // public OkHttpClientBuilder certificate(Map<String, Object> map) { // try { // if (Boolean.parseBoolean(String.valueOf(map.get("ignoreSSL")))) { // X509TrustManager compositeX509TrustManager = new X509TrustManagerImp(); // SSLContext sslContext = SSLContext.getInstance("TLS"); // sslContext.init(null, new TrustManager[]{compositeX509TrustManager}, new java.security.SecureRandom()); // this.builder.sslSocketFactory(sslContext.getSocketFactory(), compositeX509TrustManager). // hostnameVerifier(new TrueHostnameVerifier()); // } // return this; // } catch (Exception e) { // throw new TeaException(e.getMessage(), e); // } // // } // // public OkHttpClientBuilder proxy(Map<String, Object> map) { // try { // if (null != map.get("httpProxy") || null != map.get("httpsProxy")) { // Object urlString = null == map.get("httpProxy") ? map.get("httpsProxy") : map.get("httpProxy"); // URL url = new URL(String.valueOf(urlString)); // this.builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()))); // } // return this; // } catch (Exception e) { // throw new TeaException(e.getMessage(), e); // } // // } // // public OkHttpClientBuilder proxyAuthenticator(Map<String, Object> map) { // try { // Object httpsProxy = map.get("httpsProxy"); // if (httpsProxy != null) { // URL proxyUrl = new URL(String.valueOf(httpsProxy)); // String userInfo = proxyUrl.getUserInfo(); // if (null != userInfo) { // String[] userMessage = userInfo.split(":"); // final String credential = Credentials.basic(userMessage[0], userMessage[1]); // Authenticator authenticator = new Authenticator() { // @Override // public Request authenticate(Route route, Response response) throws IOException { // return response.request().newBuilder() // .header("Proxy-Authorization", credential) // .build(); // } // }; // this.builder.proxyAuthenticator(authenticator); // } // } // return this; // } catch (Exception e) { // throw new TeaException(e.getMessage(), e); // } // } // // public OkHttpClient buildOkHttpClient() { // return this.builder.build(); // } //}
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/synhttp/OkRequestBody.java
//package okhttp.synhttp; // //import darabonba.core.TeaRequest; //import darabonba.core.utils.StringUtils; //import okhttp3.MediaType; //import okhttp3.RequestBody; //import okio.BufferedSink; // //import java.io.IOException; //import java.io.InputStream; // //public class OkRequestBody extends RequestBody { // // private InputStream inputStream; // private String contentType; // // public OkRequestBody(TeaRequest teaRequest) { // this.inputStream = teaRequest.body; // this.contentType = teaRequest.headers.get("content-type"); // } // // // @Override // public MediaType contentType() { // MediaType type; // if (StringUtils.isEmpty(contentType)) { // if (null == inputStream) { // return null; // } // type = MediaType.parse("application/json; charset=UTF-8;"); // return type; // } // return MediaType.parse(contentType); // } // // @Override // public long contentLength() throws IOException { // if (null != inputStream && inputStream.available() > 0) { // return inputStream.available(); // } // return super.contentLength(); // } // // @Override // public void writeTo(BufferedSink bufferedSink) throws IOException { // if (null == inputStream) { // return; // } // byte[] buffer = new byte[4096]; // int bytesRead; // while ((bytesRead = inputStream.read(buffer)) != -1) { // bufferedSink.write(buffer, 0, bytesRead); // } // } //}
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/synhttp/OkRequestBuilder.java
//package okhttp.synhttp; // //import darabonba.core.TeaRequest; //import okhttp3.Request; // //import java.net.URL; //import java.util.Map; // //public class OkRequestBuilder { // private Request.Builder builder; // // public OkRequestBuilder(Request.Builder builder) { // this.builder = builder; // } // // public OkRequestBuilder url(URL url) { // this.builder.url(url); // return this; // } // // public OkRequestBuilder header(Map<String, String> headers) { // for (String headerName : headers.keySet()) { // this.builder.header(headerName, headers.get(headerName)); // } // return this; // } // // public Request buildRequest(TeaRequest request) { // String method = request.method.toUpperCase(); // OkRequestBody requestBody; // switch (method) { // case "DELETE": // this.builder.delete(); // break; // case "POST": // requestBody = new OkRequestBody(request); // this.builder.post(requestBody); // break; // case "PUT": // requestBody = new OkRequestBody(request); // this.builder.put(requestBody); // break; // case "PATCH": // requestBody = new OkRequestBody(request); // this.builder.patch(requestBody); // break; // default: // this.builder.get(); // break; // } // return this.builder.build(); // } //}
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/utils/TrueHostnameVerifier.java
package okhttp.utils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; public class TrueHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }
0
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp
java-sources/com/aliyun/aliyun-http-okhttp/0.3.2-beta/okhttp/utils/X509TrustManagerImp.java
package okhttp.utils; import javax.net.ssl.X509TrustManager; import java.security.cert.X509Certificate; public class X509TrustManagerImp implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/Credential.java
package com.aliyun.auth.credentials; import com.aliyun.core.utils.StringUtils; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class Credential implements ICredential { private final String accessKeyId; private final String accessKeySecret; private final String securityToken; public static final Credential ANONYMOUS_CREDENTIALS = Credential .builder() .accessKeyId(null) .accessKeyId(null) .securityToken(null) .build(); private Credential(Builder builder) { this.accessKeyId = builder.accessKeyId; this.accessKeySecret = builder.accessKeySecret; this.securityToken = builder.securityToken; } public static Builder builder() { return new Builder(); } public String accessKeyId() { return accessKeyId; } public String accessKeySecret() { return accessKeySecret; } public String securityToken() { return securityToken; } @Override public String toString() { Map<String, Object> fieldMap = new HashMap<>(); fieldMap.put("accessKeyId", accessKeyId); fieldMap.put("accessKeySecret", accessKeySecret); fieldMap.put("securityToken", securityToken); return StringUtils.toAliString("Credential", fieldMap); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Credential that = (Credential) o; return Objects.equals(accessKeyId, that.accessKeyId) && Objects.equals(accessKeySecret, that.accessKeySecret); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + Objects.hashCode(accessKeyId()); hashCode = 31 * hashCode + Objects.hashCode(accessKeySecret()); return hashCode; } public static final class Builder { private String accessKeyId; private String accessKeySecret; private String securityToken; public Builder accessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; return this; } public Builder accessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; return this; } public Builder securityToken(String securityToken) { this.securityToken = securityToken; return this; } public Credential build() { return new Credential(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/ICredential.java
package com.aliyun.auth.credentials; public interface ICredential { String accessKeyId(); String accessKeySecret(); String securityToken(); }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/exception/CredentialException.java
package com.aliyun.auth.credentials.exception; import java.io.Serializable; public class CredentialException extends RuntimeException implements Serializable { private static final long serialVersionUID = 634786425123290588L; public CredentialException(String message) { super(message); } public CredentialException(String message, Throwable cause) { super(message, cause); } @Override public String getMessage() { return super.getMessage(); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/CompatibleUrlConnClient.java
package com.aliyun.auth.credentials.http; import com.aliyun.auth.credentials.exception.*; import com.aliyun.core.utils.SdkAutoCloseable; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyStore; import java.util.*; import java.util.Map.Entry; public class CompatibleUrlConnClient implements SdkAutoCloseable { protected static final String ACCEPT_ENCODING = "Accept-Encoding"; protected static final String CONTENT_TYPE = "Content-Type"; protected static final String USER_AGENT = "User-Agent"; private static final String DEFAULT_USER_AGENT; static { Properties sysProps = System.getProperties(); String version = ""; Properties props = new Properties(); try { props.load(CompatibleUrlConnClient.class.getClassLoader().getResourceAsStream("core.properties")); version = props.getProperty("sdk.project.version"); } catch (IOException e) { e.printStackTrace(); } DEFAULT_USER_AGENT = String.format("AlibabaCloud (%s; %s) Java/%s Credentials/%s TeaDSL/1", sysProps.getProperty("os.name"), sysProps .getProperty("os.arch"), sysProps.getProperty("java.runtime.version"), version); } public CompatibleUrlConnClient() { } public HttpResponse syncInvoke(HttpRequest request) { InputStream content = null; HttpResponse response; HttpURLConnection httpConn = buildHttpConnection(request); try { httpConn.connect(); if (request.getHttpContent() != null) { DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); dos.write(request.getHttpContent()); dos.flush(); dos.close(); } content = httpConn.getInputStream(); response = new HttpResponse(httpConn.getURL().toString()); parseHttpConn(response, httpConn, content, null); return response; } catch (IOException e) { content = httpConn.getErrorStream(); response = new HttpResponse(httpConn.getURL().toString()); parseHttpConn(response, httpConn, content, e); return response; } finally { if (content != null) { try { content.close(); } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } } httpConn.disconnect(); } } private SSLSocketFactory createSSLSocketFactory(boolean ignoreSSLCert) { try { X509TrustManagerImp compositeX509TrustManager; if (ignoreSSLCert) { compositeX509TrustManager = new X509TrustManagerImp(true); } else { // get trustManager using default certification from jdk TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); List<TrustManager> trustManagerList = new ArrayList<TrustManager>(Arrays.asList(tmf.getTrustManagers())); final List<X509TrustManager> finalTrustManagerList = new ArrayList<X509TrustManager>(); for (TrustManager tm : trustManagerList) { if (tm instanceof X509TrustManager) { finalTrustManagerList.add((X509TrustManager) tm); } } compositeX509TrustManager = new X509TrustManagerImp(finalTrustManagerList); } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{compositeX509TrustManager}, new java.security.SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new CredentialException(e.getMessage(), e); } } private HostnameVerifier createHostnameVerifier(boolean ignoreSSLCert) { return DefaultAuthHostnameVerifier.getInstance(ignoreSSLCert); } public void checkHttpRequest(HttpRequest request) { String strUrl = request.getSysUrl(); if (null == strUrl) { throw new IllegalArgumentException("URL is null for HttpRequest."); } if (null == request.getSysMethod()) { throw new IllegalArgumentException("Method is not set for HttpRequest."); } } public HttpURLConnection initHttpConnection(URL url, HttpRequest request) { try { HttpURLConnection httpConn = null; if ("https".equalsIgnoreCase(url.getProtocol())) { SSLSocketFactory sslSocketFactory = createSSLSocketFactory(false); HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection(); httpsConn.setSSLSocketFactory(sslSocketFactory); HostnameVerifier hostnameVerifier = createHostnameVerifier(false); httpsConn.setHostnameVerifier(hostnameVerifier); httpConn = httpsConn; } if (httpConn == null) { httpConn = (HttpURLConnection) url.openConnection(); } httpConn.setRequestMethod(request.getSysMethod().toString()); httpConn.setInstanceFollowRedirects(false); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); setConnectionTimeout(httpConn, request); httpConn.setRequestProperty(ACCEPT_ENCODING, "identity"); httpConn.setRequestProperty(USER_AGENT, DEFAULT_USER_AGENT); Map<String, String> mappedHeaders = request.getSysHeaders(); for (Entry<String, String> entry : mappedHeaders.entrySet()) { httpConn.setRequestProperty(entry.getKey(), entry.getValue()); } if (request.getHttpContent() != null) { httpConn.setRequestProperty(CONTENT_TYPE, request.getSysHeaders().get(CONTENT_TYPE)); } return httpConn; } catch (Exception e) { throw new CredentialException(e.getMessage(), e); } } public void setConnectionTimeout(HttpURLConnection httpConn, HttpRequest request) { httpConn.setConnectTimeout(request.getSysConnectTimeout()); httpConn.setReadTimeout(request.getSysReadTimeout()); } public HttpURLConnection buildHttpConnection(HttpRequest request) { checkHttpRequest(request); String strUrl = request.getSysUrl(); try { URL url = new URL(strUrl); System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); HttpURLConnection httpConn = initHttpConnection(url, request); return httpConn; } catch (Exception e) { throw new CredentialException(e.getMessage(), e); } } public void parseHttpConn(HttpResponse response, HttpURLConnection httpConn, InputStream content, Exception e) { byte[] buff; try { if (null != content) { buff = readContent(content); } else { response.setResponseMessage(e.getMessage()); return; } response.setResponseCode(httpConn.getResponseCode()); response.setResponseMessage(httpConn.getResponseMessage()); Map<String, List<String>> headers = httpConn.getHeaderFields(); for (Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); if (null == key) { continue; } List<String> values = entry.getValue(); StringBuilder builder = new StringBuilder(values.get(0)); for (int i = 1; i < values.size(); i++) { builder.append(","); builder.append(values.get(i)); } response.putHeaderParameter(key, builder.toString()); } String type = response.getHeaderValue("Content-Type"); if (null != buff && null != type) { response.setSysEncoding("UTF-8"); String[] split = type.split(";"); response.setHttpContentType(FormatType.mapAcceptToFormat(split[0].trim())); if (split.length > 1 && split[1].contains("=")) { String[] codings = split[1].split("="); response.setSysEncoding(codings[1].trim().toUpperCase()); } } response.setHttpContent(buff, response.getSysEncoding(), response.getHttpContentType()); } catch (Exception exception) { throw new CredentialException(exception.getMessage(), exception); } } public byte[] readContent(InputStream content) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; try { while (true) { final int read = content.read(buff); if (read == -1) { break; } outputStream.write(buff, 0, read); } } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } return outputStream.toByteArray(); } @Override public void close() { // do nothing } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/DefaultAuthHostnameVerifier.java
package com.aliyun.auth.credentials.http; import org.apache.hc.client5.http.ssl.DefaultHostnameVerifier; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; public class DefaultAuthHostnameVerifier implements HostnameVerifier { private boolean ignoreSSLCert = false; private static final HostnameVerifier NOOP_INSTANCE = new DefaultAuthHostnameVerifier(true); private DefaultAuthHostnameVerifier(boolean ignoreSSLCert) { this.ignoreSSLCert = ignoreSSLCert; } public static HostnameVerifier getInstance(boolean ignoreSSLCert) { if (ignoreSSLCert) { return NOOP_INSTANCE; } else { return new DefaultHostnameVerifier(); } } @Override public boolean verify(String s, SSLSession sslSession) { return ignoreSSLCert; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/FormatType.java
package com.aliyun.auth.credentials.http; import java.util.Arrays; public enum FormatType { XML("application/xml", "text/xml"), JSON("application/json", "text/json"), RAW("application/octet-stream"), FORM("application/x-www-form-urlencoded"); private String[] formats; FormatType(String... formats) { this.formats = formats; } public static String mapFormatToAccept(FormatType format) { return format.formats[0]; } public static FormatType mapAcceptToFormat(String accept) { for (FormatType value : values()) { if (Arrays.asList(value.formats).contains(accept)) { return value; } } return RAW; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/HttpMessage.java
package com.aliyun.auth.credentials.http; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.utils.*; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.util.Collections; import java.util.HashMap; import java.util.Map; public abstract class HttpMessage { protected static final String CONTENT_TYPE = "Content-Type"; protected static final String CONTENT_MD5 = "Content-MD5"; protected static final String CONTENT_LENGTH = "Content-Length"; protected FormatType httpContentType = null; protected byte[] httpContent = null; protected String encoding = null; protected Map<String, String> headers = new HashMap<String, String>(); protected Integer connectTimeout = null; protected Integer readTimeout = null; private String url = null; private MethodType method = null; private int httpTimeout = 0; public HttpMessage(String strUrl) { this.url = strUrl; } public HttpMessage() { } public FormatType getHttpContentType() { return httpContentType; } public void putHeaderParameter(String name, String value) { if (null != name && null != value) { this.headers.put(name, value); } } public void setHttpContentType(FormatType httpContentType) { this.httpContentType = httpContentType; } public byte[] getHttpContent() { return httpContent; } public void setHttpContent(byte[] content, String encoding, FormatType format) { if (null == content) { this.headers.remove(CONTENT_MD5); this.headers.put(CONTENT_LENGTH, "0"); this.headers.remove(CONTENT_TYPE); // this.httpContentType = null; this.httpContent = null; this.encoding = null; return; } // for GET HEADER DELETE OPTION method, sdk should ignore the content if (getSysMethod() != null && !getSysMethod().hasContent()) { content = new byte[0]; } this.httpContent = content; this.encoding = encoding; String contentLen = String.valueOf(content.length); String strMd5 = md5Sum(content); this.headers.put(CONTENT_MD5, strMd5); this.headers.put(CONTENT_LENGTH, contentLen); if (null != format) { this.headers.put(CONTENT_TYPE, FormatType.mapFormatToAccept(format)); } } public static String md5Sum(byte[] buff) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(buff); return Base64Helper.encode(messageDigest); } catch (Exception e) { throw new CredentialException(e.getMessage(), e); } } public String getHeaderValue(String name) { return this.headers.get(name); } public String getHttpContentString() { String stringContent = ""; if (this.httpContent != null) { try { if (this.encoding == null) { stringContent = new String(this.httpContent); } else { stringContent = new String(this.httpContent, this.encoding); } } catch (UnsupportedEncodingException exp) { throw new CredentialException("Can not parse response due to unsupported encoding: " + exp.getMessage(), exp); } } return stringContent; } public String getSysUrl() { return url; } public void setSysUrl(String url) { this.url = url; } public MethodType getSysMethod() { return this.method; } public void setSysMethod(MethodType method) { this.method = method; //This is the pop rule and the put method accepts only json data if (MethodType.PUT == method) { setHttpContentType(FormatType.JSON); } } public String getSysEncoding() { return encoding; } public void setSysEncoding(String encoding) { this.encoding = encoding; } public Integer getSysConnectTimeout() { return connectTimeout; } public void setSysConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public Integer getSysReadTimeout() { return readTimeout; } public void setSysReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; } public void setHttpTimeout(int httpTimeout) { this.httpTimeout = httpTimeout; } public int getHttpTimeout() { return httpTimeout; } public Map<String, String> getSysHeaders() { return Collections.unmodifiableMap(headers); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/HttpRequest.java
package com.aliyun.auth.credentials.http; import com.aliyun.auth.credentials.utils.ParameterHelper; import com.aliyun.core.utils.Configuration; import java.io.IOException; import java.util.*; public class HttpRequest extends HttpMessage { private Map<String, String> immutableMap = new HashMap<String, String>(); private static final String DEFAULT_USER_AGENT; static { String javaVersion = Configuration.getGlobalConfiguration().get("java.version"); String osName = Configuration.getGlobalConfiguration().get("os.name"); String osArch = Configuration.getGlobalConfiguration().get("os.arch"); String coreVersion = "unknown"; try { Properties props = new Properties(); props.load(HttpRequest.class.getClassLoader().getResourceAsStream("core.properties")); coreVersion = props.getProperty("sdk.project.version"); } catch (IOException e) { e.printStackTrace(); } DEFAULT_USER_AGENT = String.format("AlibabaCloud (%s; %s) Java/%s AsyncCredentials/%s TeaDSL/1", "AlibabaCloud", osName, osArch, javaVersion, "AsyncCoreService", coreVersion); } public HttpRequest() { setCommonParameter(); } public HttpRequest(String url) { super(url); setCommonParameter(); } private void setCommonParameter() { this.immutableMap.put("Timestamp", ParameterHelper.getISO8601Time(new Date())); this.immutableMap.put("SignatureNonce", ParameterHelper.getUniqueNonce()); this.immutableMap.put("SignatureMethod", "HMAC-SHA1"); this.immutableMap.put("SignatureVersion", "1.0"); this.putHeaderParameter("user-agent", DEFAULT_USER_AGENT); } public void setUrlParameter(String key, String value) { this.immutableMap.put(key, value); } public String getUrlParameter(String key) { return this.immutableMap.get(key); } public Map<String, String> getUrlParameters() { return Collections.unmodifiableMap(immutableMap); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/HttpResponse.java
package com.aliyun.auth.credentials.http; public class HttpResponse extends HttpMessage { private int responseCode; private String responseMessage; public HttpResponse(String strUrl) { super(strUrl); } public int getResponseCode() { return responseCode; } public void setResponseCode(int responseCode) { this.responseCode = responseCode; } public String getResponseMessage() { return responseMessage; } public void setResponseMessage(String responseMessage) { this.responseMessage = responseMessage; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/MethodType.java
package com.aliyun.auth.credentials.http; public enum MethodType { GET(false), PUT(true), POST(true); private boolean hasContent; MethodType(boolean hasContent) { this.hasContent = hasContent; } public boolean hasContent() { return hasContent; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/TrueHostnameVerifier.java
package com.aliyun.auth.credentials.http; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; public class TrueHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/http/X509TrustManagerImp.java
package com.aliyun.auth.credentials.http; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class X509TrustManagerImp implements X509TrustManager { private List<X509TrustManager> trustManagers = new ArrayList<X509TrustManager>(); private boolean ignoreSSLCert = false; public boolean isIgnoreSSLCert() { return ignoreSSLCert; } public X509TrustManagerImp(boolean ignoreSSLCert) { this.ignoreSSLCert = ignoreSSLCert; } public X509TrustManagerImp(List<X509TrustManager> trustManagers) { this.trustManagers = trustManagers; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { // do nothing } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (this.ignoreSSLCert) { return; } for (X509TrustManager trustManager : this.trustManagers) { try { trustManager.checkServerTrusted(chain, authType); return; // someone trusts them. success! } catch (CertificateException e) { // maybe someone else will trust them } } throw new CertificateException("None of the TrustManagers trust this certificate chain"); } @Override public X509Certificate[] getAcceptedIssuers() { List<X509Certificate> certificates = new ArrayList<X509Certificate>(); for (X509TrustManager trustManager : this.trustManagers) { certificates.addAll(Arrays.asList(trustManager.getAcceptedIssuers())); } X509Certificate[] certificatesArray = new X509Certificate[certificates.size()]; return certificates.toArray(certificatesArray); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/AnonymousCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.core.utils.StringUtils; import java.util.HashMap; public class AnonymousCredentialProvider implements ICredentialProvider { private AnonymousCredentialProvider() { } public static AnonymousCredentialProvider create() { return new AnonymousCredentialProvider(); } @Override public ICredential getCredentials() throws CredentialException { return Credential.ANONYMOUS_CREDENTIALS; } @Override public void close() { } @Override public String toString() { return StringUtils.toAliString("AnonymousCredentialsProvider", new HashMap<>()); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/CLIProfileCredentialsProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.CredentialException; import com.aliyun.auth.credentials.utils.AuthUtils; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.List; public class CLIProfileCredentialsProvider implements ICredentialProvider { private final String CLI_CREDENTIALS_CONFIG_PATH = System.getProperty("user.home") + "/.aliyun/config.json"; private volatile ICredentialProvider credentialsProvider; private volatile String currentProfileName; private final Object credentialsProviderLock = new Object(); private CLIProfileCredentialsProvider(Builder builder) { this.currentProfileName = builder.profileName == null ? System.getenv("ALIBABA_CLOUD_PROFILE") : builder.profileName; } public static Builder builder() { return new Builder(); } @Override public ICredential getCredentials() { if (AuthUtils.isDisableCLIProfile()) { throw new CredentialException("CLI credentials file is disabled."); } Config config = parseProfile(CLI_CREDENTIALS_CONFIG_PATH); if (null == config) { throw new CredentialException("Unable to get profile from empty CLI credentials file."); } String refreshedProfileName = System.getenv("ALIBABA_CLOUD_PROFILE"); if (shouldReloadCredentialsProvider(refreshedProfileName)) { synchronized (credentialsProviderLock) { if (shouldReloadCredentialsProvider(refreshedProfileName)) { if (!StringUtils.isEmpty(refreshedProfileName)) { this.currentProfileName = refreshedProfileName; } this.credentialsProvider = reloadCredentialsProvider(config, this.currentProfileName); } } } return this.credentialsProvider.getCredentials(); } ICredentialProvider reloadCredentialsProvider(Config config, String profileName) { String currentProfileName = !StringUtils.isEmpty(profileName) ? profileName : config.getCurrent(); List<Profile> profiles = config.getProfiles(); if (profiles != null && !profiles.isEmpty()) { for (Profile profile : profiles) { if (!StringUtils.isEmpty(profile.getName()) && profile.getName().equals(currentProfileName)) { switch (profile.getMode()) { case "AK": return StaticCredentialProvider.create( Credential.builder() .accessKeyId(Validate.notNull( profile.getAccessKeyId(), "AccessKeyId must not be null.")) .accessKeySecret(Validate.notNull( profile.getAccessKeySecret(), "AccessKeySecret must not be null.")) .build()); case "StsToken": return StaticCredentialProvider.create( Credential.builder() .accessKeyId(Validate.notNull( profile.getAccessKeyId(), "AccessKeyId must not be null.")) .accessKeySecret(Validate.notNull( profile.getAccessKeySecret(), "AccessKeySecret must not be null.")) .securityToken(Validate.notNull(profile.securityToken, "SecurityToken must not be null.")) .build()); case "RamRoleArn": ICredentialProvider innerProvider = StaticCredentialProvider.create( Credential.builder() .accessKeyId(Validate.notNull( profile.getAccessKeyId(), "AccessKeyId must not be null.")) .accessKeySecret(Validate.notNull( profile.getAccessKeySecret(), "AccessKeySecret must not be null.")) .build()); return RamRoleArnCredentialProvider.builder() .credentialsProvider(innerProvider) .durationSeconds(profile.getDurationSeconds()) .roleArn(profile.getRoleArn()) .roleSessionName(profile.getRoleSessionName()) .stsRegionId(profile.getStsRegionId()) .enableVpc(profile.getEnableVpc()) .policy(profile.getPolicy()) .externalId(profile.getExternalId()) .build(); case "EcsRamRole": return EcsRamRoleCredentialProvider.builder() .roleName(profile.getRamRoleName()) .build(); case "OIDC": return OIDCRoleArnCredentialProvider.builder() .durationSeconds(profile.getDurationSeconds()) .roleArn(profile.getRoleArn()) .roleSessionName(profile.getRoleSessionName()) .oidcProviderArn(profile.getOidcProviderArn()) .oidcTokenFilePath(profile.getOidcTokenFile()) .stsRegionId(profile.getStsRegionId()) .enableVpc(profile.getEnableVpc()) .policy(profile.getPolicy()) .build(); case "ChainableRamRoleArn": ICredentialProvider previousProvider = reloadCredentialsProvider(config, profile.getSourceProfile()); return RamRoleArnCredentialProvider.builder() .credentialsProvider(previousProvider) .durationSeconds(profile.getDurationSeconds()) .roleArn(profile.getRoleArn()) .roleSessionName(profile.getRoleSessionName()) .stsRegionId(profile.getStsRegionId()) .enableVpc(profile.getEnableVpc()) .policy(profile.getPolicy()) .externalId(profile.getExternalId()) .build(); default: throw new CredentialException(String.format("Unsupported profile mode '%s' form CLI credentials file.", profile.getMode())); } } } } throw new CredentialException(String.format("Unable to get profile with '%s' form CLI credentials file.", currentProfileName)); } Config parseProfile(String configFilePath) { File configFile = new File(configFilePath); if (!configFile.exists() || !configFile.isFile() || !configFile.canRead()) { throw new CredentialException(String.format("Unable to open credentials file: %s.", configFile.getAbsolutePath())); } Gson gson = new Gson(); try (BufferedReader br = new BufferedReader(new FileReader(configFile))) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } String jsonContent = sb.toString(); return gson.fromJson(jsonContent, Config.class); } catch (Exception e) { throw new CredentialException(String.format("Failed to parse credential form CLI credentials file: %s.", configFile.getAbsolutePath())); } } boolean shouldReloadCredentialsProvider(String profileName) { return this.credentialsProvider == null || (!StringUtils.isEmpty(this.currentProfileName) && !StringUtils.isEmpty(profileName) && !this.currentProfileName.equals(profileName)); } @Override public void close() { } public static final class Builder { private String profileName; public Builder profileName(String profileName) { this.profileName = profileName; return this; } public CLIProfileCredentialsProvider build() { return new CLIProfileCredentialsProvider(this); } } static class Config { @SerializedName("current") private String current; @SerializedName("profiles") private List<Profile> profiles; public String getCurrent() { return current; } public List<Profile> getProfiles() { return profiles; } } static class Profile { @SerializedName("name") private String name; @SerializedName("mode") private String mode; @SerializedName("access_key_id") private String accessKeyId; @SerializedName("access_key_secret") private String accessKeySecret; @SerializedName("sts_token") private String securityToken; @SerializedName("ram_role_arn") private String roleArn; @SerializedName("ram_session_name") private String roleSessionName; @SerializedName("expired_seconds") private Integer durationSeconds; @SerializedName("sts_region") private String stsRegionId; @SerializedName("enable_vpc") private Boolean enableVpc; @SerializedName("ram_role_name") private String ramRoleName; @SerializedName("oidc_token_file") private String oidcTokenFile; @SerializedName("oidc_provider_arn") private String oidcProviderArn; @SerializedName("source_profile") private String sourceProfile; @SerializedName("policy") private String policy; @SerializedName("external_id") private String externalId; public String getName() { return name; } public String getMode() { return mode; } public String getAccessKeyId() { return accessKeyId; } public String getAccessKeySecret() { return accessKeySecret; } public String getSecurityToken() { return securityToken; } public String getRoleArn() { return roleArn; } public String getRoleSessionName() { return roleSessionName; } public Integer getDurationSeconds() { return durationSeconds; } public String getStsRegionId() { return stsRegionId; } public Boolean getEnableVpc() { return enableVpc; } public String getRamRoleName() { return ramRoleName; } public String getOidcTokenFile() { return oidcTokenFile; } public String getOidcProviderArn() { return oidcProviderArn; } public String getSourceProfile() { return sourceProfile; } public String getPolicy() { return policy; } public String getExternalId() { return externalId; } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/CredentialsProviderChain.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.IOUtils; import com.aliyun.core.utils.SdkAutoCloseable; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import java.util.*; public class CredentialsProviderChain implements ICredentialProvider, SdkAutoCloseable { private static final ClientLogger logger = new ClientLogger(CredentialsProviderChain.class); private final List<ICredentialProvider> credentialsProviders; private final boolean reuseLastProviderEnabled; private volatile ICredentialProvider lastUsedProvider; private CredentialsProviderChain(Builder builder) { this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled; this.credentialsProviders = Collections.unmodifiableList( Validate.notEmpty(builder.credentialsProviders, "No credential provider.")); } public static Builder builder() { return new Builder(); } @Override public ICredential getCredentials() throws CredentialException { if (reuseLastProviderEnabled && lastUsedProvider != null){ return lastUsedProvider.getCredentials(); } List<String> errorMessages = new ArrayList<>(); for (ICredentialProvider provider : credentialsProviders) { try { ICredential credentials = provider.getCredentials(); logger.verbose("Loading credentials from " + provider); lastUsedProvider = provider; return credentials; } catch (RuntimeException e) { String message = provider.getClass().getName() + ": " + e.getMessage(); errorMessages.add(message); logger.verbose("Unable to load credentials from " + message); } } throw new CredentialException("Unable to load credentials from any of the providers in the chain " + errorMessages); } @Override public void close() { credentialsProviders.forEach(credentials -> IOUtils.closeIfCloseable(credentials, logger)); } @Override public String toString() { Map<String, Object> fieldMap = new HashMap<>(); fieldMap.put("credentialsProviders", credentialsProviders); return StringUtils.toAliString("CredentialsProviderChain", fieldMap); } public static final class Builder { private List<ICredentialProvider> credentialsProviders = new ArrayList<>(); private boolean reuseLastProviderEnabled = true; public Builder credentialsProviders(Collection<? extends ICredentialProvider> credentialsProviders) { this.credentialsProviders = new ArrayList<>(credentialsProviders); return this; } public Builder credentialsProviders(ICredentialProvider... credentialsProviders) { return credentialsProviders(Arrays.asList(credentialsProviders)); } public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) { this.reuseLastProviderEnabled = reuseLastProviderEnabled; return this; } public Builder addCredentialsProvider(ICredentialProvider credentialsProviders) { this.credentialsProviders.add(credentialsProviders); return this; } public CredentialsProviderChain build() { return new CredentialsProviderChain(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/CredentialsProviderFactory.java
package com.aliyun.auth.credentials.provider; public class CredentialsProviderFactory { public <T extends ICredentialProvider> T createCredentialsProvider(T classInstance) { return classInstance; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/DefaultCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.utils.AuthUtils; import com.aliyun.core.utils.StringUtils; import java.util.*; public class DefaultCredentialProvider implements ICredentialProvider { // private static final DefaultCredentialProvider DEFAULT_CREDENTIALS_PROVIDER = new DefaultCredentialProvider(builder()); private List<ICredentialProvider> customizeProviders; private final CredentialsProviderChain providerChain; private DefaultCredentialProvider(Builder builder) { this.customizeProviders = builder.customizeProviders; this.providerChain = createChain(builder); } // public static DefaultCredentialProvider create() { // return DEFAULT_CREDENTIALS_PROVIDER; // } private CredentialsProviderChain createChain(Builder builder) { boolean asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled; boolean reuseLastProviderEnabled = builder.reuseLastProviderEnabled; if (customizeProviders.isEmpty()) { customizeProviders.add(SystemPropertiesCredentialProvider.create()); customizeProviders.add(EnvironmentVariableCredentialProvider.create()); if (AuthUtils.environmentEnableOIDC()) { customizeProviders.add(OIDCRoleArnCredentialProvider.builder() .roleArn(AuthUtils.getEnvironmentRoleArn()) .oidcProviderArn(AuthUtils.getEnvironmentOIDCProviderArn()) .oidcTokenFilePath(AuthUtils.getEnvironmentOIDCTokenFilePath()) .build()); } customizeProviders.add(CLIProfileCredentialsProvider.builder().build()); customizeProviders.add(ProfileCredentialProvider.builder() .profileFile(builder.profileFile) .clientType(builder.clientType) .asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled) .build()); if (!AuthUtils.isDisableECSMetaData()) { customizeProviders.add(EcsRamRoleCredentialProvider.builder().build()); } String uri = AuthUtils.getEnvironmentCredentialsURI(); if (!StringUtils.isEmpty(uri)) { customizeProviders.add(URLCredentialProvider.builder() .credentialsURI(uri) .build()); } } return CredentialsProviderChain.builder() .reuseLastProviderEnabled(reuseLastProviderEnabled) .credentialsProviders(customizeProviders) .build(); } public static Builder builder() { return new Builder(); } @Override public ICredential getCredentials() { return providerChain.getCredentials(); } public Boolean containsCredentialProvider(ICredentialProvider provider) { return customizeProviders.contains(provider); } @Override public void close() { providerChain.close(); } @Override public String toString() { Map<String, Object> fieldMap = new HashMap<>(); fieldMap.put("providerChain", providerChain); return StringUtils.toAliString("DefaultCredentialsProvider", fieldMap); } public static final class Builder { private String profileFile; private String clientType; private Boolean reuseLastProviderEnabled = true; private Boolean asyncCredentialUpdateEnabled = false; private List<ICredentialProvider> customizeProviders = new ArrayList<ICredentialProvider>(); public Builder profileFile(String profileFile) { this.profileFile = profileFile; return this; } public Builder clientType(String clientType) { this.clientType = clientType; return this; } public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) { this.reuseLastProviderEnabled = reuseLastProviderEnabled; return this; } public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) { this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled; return this; } public Builder customizeProviders(Collection<? extends ICredentialProvider> customizeProviders) { this.customizeProviders = new ArrayList<>(customizeProviders); return this; } public Builder customizeProviders(ICredentialProvider... customizeProviders) { return customizeProviders(Arrays.asList(customizeProviders)); } public Builder addCustomizeProviders(ICredentialProvider credentialsProviders) { this.customizeProviders.add(credentialsProviders); return this; } public DefaultCredentialProvider build() { return new DefaultCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/EcsRamRoleCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.http.*; import com.aliyun.auth.credentials.utils.*; import com.aliyun.core.utils.StringUtils; import com.google.gson.Gson; import java.time.Instant; import java.util.Map; public final class EcsRamRoleCredentialProvider extends HttpCredentialProvider { private static final String URL_IN_ECS_METADATA = "/latest/meta-data/ram/security-credentials/"; private static final String URL_IN_METADATA_TOKEN = "/latest/api/token"; private static final String ECS_METADAT_FETCH_ERROR_MSG = "Failed to get RAM session credentials from ECS metadata service."; private final String roleName; private final String metadataServiceHost; private final Boolean disableIMDSv1; private final int connectionTimeout; private final int readTimeout; private final CompatibleUrlConnClient client; private EcsRamRoleCredentialProvider(BuilderImpl builder) { super(builder); if (AuthUtils.isDisableECSMetaData()) { throw new CredentialException("IMDS credentials is disabled."); } this.roleName = builder.roleName == null ? AuthUtils.getEnvironmentECSMetaData() : builder.roleName; this.disableIMDSv1 = builder.disableIMDSv1 == null ? AuthUtils.getDisableECSIMDSv1() : builder.disableIMDSv1; this.metadataServiceHost = builder.metadataServiceHost == null ? "100.100.100.200" : builder.metadataServiceHost; this.connectionTimeout = builder.connectionTimeout == null ? 1000 : builder.connectionTimeout; this.readTimeout = builder.readTimeout == null ? 1000 : builder.readTimeout; this.client = new CompatibleUrlConnClient(); this.buildRefreshCache(); } public static EcsRamRoleCredentialProvider create(String roleName) { return builder().roleName(roleName).build(); } public static Builder builder() { return new BuilderImpl(); } private String getMetadata(String url) { HttpRequest request = new HttpRequest(url); request.setSysMethod(MethodType.GET); request.setSysConnectTimeout(connectionTimeout); request.setSysReadTimeout(readTimeout); HttpResponse response; String metadataToken = this.getMetadataToken(); if (metadataToken != null) { request.putHeaderParameter("X-aliyun-ecs-metadata-token", metadataToken); } try { response = client.syncInvoke(request); } catch (Exception e) { throw new CredentialException("Failed to connect ECS Metadata Service: " + e); } if (response.getResponseCode() == 404) { throw new CredentialException("The role name was not found in the instance."); } if (response.getResponseCode() != 200) { throw new CredentialException(ECS_METADAT_FETCH_ERROR_MSG + " HttpCode=" + response.getResponseCode()); } return response.getHttpContentString(); } private String getMetadataToken() { try { HttpRequest request = new HttpRequest("http://" + metadataServiceHost + URL_IN_METADATA_TOKEN); request.setSysMethod(MethodType.PUT); request.setSysConnectTimeout(connectionTimeout); request.setSysReadTimeout(readTimeout); request.putHeaderParameter("X-aliyun-ecs-metadata-token-ttl-seconds", "21600"); HttpResponse response; try { response = client.syncInvoke(request); } catch (Exception e) { throw new CredentialException("Failed to connect ECS Metadata Service: " + e); } if (response.getResponseCode() != 200) { throw new CredentialException("Failed to get token from ECS Metadata Service. HttpCode=" + response.getResponseCode() + ", ResponseMessage=" + response.getHttpContentString()); } return new String(response.getHttpContent()); } catch (Exception ex) { return throwErrorOrReturn(ex); } } private String throwErrorOrReturn(Exception e) { if (this.disableIMDSv1) { throw new CredentialException("Failed to get token from ECS Metadata Service, and fallback to IMDS v1 is disabled via the disableIMDSv1 configuration is turned on. Original error: " + e.getMessage()); } return null; } @Override public RefreshResult<ICredential> refreshCredentials() { String roleName = this.roleName; if (StringUtils.isEmpty(this.roleName)) { roleName = getMetadata("http://" + metadataServiceHost + URL_IN_ECS_METADATA); } String jsonContent = getMetadata("http://" + metadataServiceHost + URL_IN_ECS_METADATA + roleName); Map<String, String> result = new Gson().fromJson(jsonContent, Map.class); if (!"Success".equals(result.get("Code"))) { throw new CredentialException(ECS_METADAT_FETCH_ERROR_MSG); } if (!result.containsKey("AccessKeyId") || !result.containsKey("AccessKeySecret") || !result.containsKey("SecurityToken")) { throw new CredentialException(String.format("Error retrieving credentials from IMDS result: %s.", jsonContent)); } Instant expiration = ParameterHelper.getUTCDate(result.get("Expiration")).toInstant(); ICredential credential = Credential.builder() .accessKeyId(result.get("AccessKeyId")) .accessKeySecret(result.get("AccessKeySecret")) .securityToken(result.get("SecurityToken")) .build(); return RefreshResult.builder(credential) .staleTime(getStaleTime(expiration)) .prefetchTime(getPrefetchTime(expiration)) .build(); } @Override public void close() { super.close(); this.client.close(); } public interface Builder extends HttpCredentialProvider.Builder<EcsRamRoleCredentialProvider, Builder> { Builder roleName(String roleSessionName); Builder metadataServiceHost(String metadataServiceHost); Builder disableIMDSv1(Boolean disableIMDSv1); Builder connectionTimeout(Integer connectionTimeout); Builder readTimeout(Integer readTimeout); @Override EcsRamRoleCredentialProvider build(); } private static final class BuilderImpl extends HttpCredentialProvider.BuilderImpl<EcsRamRoleCredentialProvider, Builder> implements Builder { private String roleName; private String metadataServiceHost; private Boolean disableIMDSv1; private Integer connectionTimeout; private Integer readTimeout; public Builder roleName(String roleName) { this.roleName = roleName; return this; } public Builder metadataServiceHost(String metadataServiceHost) { this.metadataServiceHost = metadataServiceHost; return this; } public Builder disableIMDSv1(Boolean disableIMDSv1) { this.disableIMDSv1 = disableIMDSv1; return this; } public Builder connectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder readTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } @Override public EcsRamRoleCredentialProvider build() { return new EcsRamRoleCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/EnvironmentVariableCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.utils.*; import com.aliyun.core.utils.StringUtils; public class EnvironmentVariableCredentialProvider implements ICredentialProvider { public static EnvironmentVariableCredentialProvider create() { return new EnvironmentVariableCredentialProvider(); } @Override public ICredential getCredentials() { String accessKeyId = AuthUtils.getEnvironmentAccessKeyId(); String accessKeySecret = AuthUtils.getEnvironmentAccessKeySecret(); String securityToken = AuthUtils.getEnvironmentSecurityToken(); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { throw new CredentialException("Environment variable accessKeyId/accessKeySecret cannot be empty"); } if (!StringUtils.isEmpty(securityToken)) { return Credential.builder() .accessKeyId(accessKeyId) .accessKeySecret(accessKeySecret) .securityToken(securityToken) .build(); } return Credential.builder() .accessKeyId(accessKeyId) .accessKeySecret(accessKeySecret) .build(); } @Override public void close() { } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/HttpCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.utils.*; import java.time.Duration; import java.time.Instant; import java.util.Optional; public abstract class HttpCredentialProvider implements ICredentialProvider { private final boolean asyncCredentialUpdateEnabled; private Optional<RefreshCachedSupplier<ICredential>> credentialsCache; protected HttpCredentialProvider(BuilderImpl<?, ?> builder) { this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled; } protected void buildRefreshCache(){ RefreshCachedSupplier.Builder<ICredential> cacheBuilder = RefreshCachedSupplier.builder(this::refreshCredentials); if (this.asyncCredentialUpdateEnabled) { cacheBuilder.prefetchStrategy(new NonBlocking()); } this.credentialsCache = Optional.of(cacheBuilder.build()); } public abstract RefreshResult<ICredential> refreshCredentials(); public Instant getStaleTime(Instant expiration) { return expiration == null ? null : expiration.minus(Duration.ofMinutes(1)); } public Instant getPrefetchTime(Instant expiration) { Instant oneHourFromNow = Instant.now().plus(Duration.ofHours(1)); if (expiration == null) { return oneHourFromNow; } Instant prefetchTime = expiration.minus(Duration.ofMinutes(15)); return oneHourFromNow.isAfter(prefetchTime) ? prefetchTime : oneHourFromNow; } @Override public ICredential getCredentials() { return credentialsCache.map(RefreshCachedSupplier::get).orElseThrow(() -> new CredentialException("Unable to get credentials")); } @Override public void close() { credentialsCache.ifPresent(RefreshCachedSupplier::close); } public interface Builder<ProviderT extends HttpCredentialProvider, BuilderT extends Builder> { BuilderT asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled); ProviderT build(); } protected abstract static class BuilderImpl<ProviderT extends HttpCredentialProvider, BuilderT extends Builder> implements Builder<ProviderT, BuilderT> { private boolean asyncCredentialUpdateEnabled = false; protected BuilderImpl() { } @Override public BuilderT asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) { this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled; return (BuilderT) this; } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/ICredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.core.utils.SdkAutoCloseable; public interface ICredentialProvider extends SdkAutoCloseable { ICredential getCredentials() throws CredentialException; }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/ICredentialProviderBuilder.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.exception.CredentialException; public interface ICredentialProviderBuilder { ICredentialProvider getICredentialProvider() throws CredentialException; }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/OIDCRoleArnCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.CredentialException; import com.aliyun.auth.credentials.http.*; import com.aliyun.auth.credentials.utils.AuthUtils; import com.aliyun.auth.credentials.utils.ParameterHelper; import com.aliyun.auth.credentials.utils.RefreshResult; import com.aliyun.core.utils.StringUtils; import com.google.gson.Gson; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.time.Instant; import java.util.HashMap; import java.util.Map; public class OIDCRoleArnCredentialProvider extends HttpCredentialProvider { /** * Default duration for started sessions. Unit of Second */ private int durationSeconds; /** * The arn of the role to be assumed. */ private String roleArn; private String oidcProviderArn; private String oidcTokenFilePath; /** * An identifier for the assumed role session. */ private final String roleSessionName; private String policy; /** * Unit of millisecond */ private int connectionTimeout; private int readTimeout; /** * Endpoint of RAM OpenAPI */ private final String stsEndpoint; private final CompatibleUrlConnClient client; private String protocol = "https"; private OIDCRoleArnCredentialProvider(BuilderImpl builder) { super(builder); this.roleSessionName = builder.roleSessionName == null ? !StringUtils.isEmpty(AuthUtils.getEnvironmentRoleSessionName()) ? AuthUtils.getEnvironmentRoleSessionName() : "aliyun-java-auth-" + System.currentTimeMillis() : builder.roleSessionName; this.durationSeconds = builder.durationSeconds == null ? 3600 : builder.durationSeconds; if (this.durationSeconds < 900) { throw new IllegalArgumentException("Session duration should be in the range of 900s - max session duration."); } this.roleArn = builder.roleArn == null ? AuthUtils.getEnvironmentRoleArn() : builder.roleArn; if (StringUtils.isEmpty(this.roleArn)) { throw new IllegalArgumentException("RoleArn or environment variable ALIBABA_CLOUD_ROLE_ARN cannot be empty."); } this.oidcProviderArn = builder.oidcProviderArn == null ? AuthUtils.getEnvironmentOIDCProviderArn() : builder.oidcProviderArn; if (StringUtils.isEmpty(this.oidcProviderArn)) { throw new IllegalArgumentException("OIDCProviderArn or environment variable ALIBABA_CLOUD_OIDC_PROVIDER_ARN cannot be empty."); } this.oidcTokenFilePath = builder.oidcTokenFilePath == null ? AuthUtils.getEnvironmentOIDCTokenFilePath() : builder.oidcTokenFilePath; if (StringUtils.isEmpty(this.oidcTokenFilePath)) { throw new IllegalArgumentException("OIDCTokenFilePath or environment variable ALIBABA_CLOUD_OIDC_TOKEN_FILE cannot be empty."); } this.policy = builder.policy; this.connectionTimeout = builder.connectionTimeout == null ? 5000 : builder.connectionTimeout; this.readTimeout = builder.readTimeout == null ? 10000 : builder.readTimeout; if (!StringUtils.isEmpty(builder.stsEndpoint)) { this.stsEndpoint = builder.stsEndpoint; } else { String prefix = builder.enableVpc != null ? (builder.enableVpc ? "sts-vpc" : "sts") : AuthUtils.isEnableVpcEndpoint() ? "sts-vpc" : "sts"; if (!StringUtils.isEmpty(builder.stsRegionId)) { this.stsEndpoint = String.format("%s.%s.aliyuncs.com", prefix, builder.stsRegionId); } else if (!StringUtils.isEmpty(AuthUtils.getEnvironmentSTSRegion())) { this.stsEndpoint = String.format("%s.%s.aliyuncs.com", prefix, AuthUtils.getEnvironmentSTSRegion()); } else { this.stsEndpoint = "sts.aliyuncs.com"; } } this.client = new CompatibleUrlConnClient(); this.buildRefreshCache(); } public static Builder builder() { return new BuilderImpl(); } public String getStsEndpoint() { return this.stsEndpoint; } @Override public RefreshResult<ICredential> refreshCredentials() { String oidcToken = AuthUtils.getOIDCToken(oidcTokenFilePath); ParameterHelper parameterHelper = new ParameterHelper(); HttpRequest httpRequest = new HttpRequest(); httpRequest.setUrlParameter("Action", "AssumeRoleWithOIDC"); httpRequest.setUrlParameter("Format", "JSON"); httpRequest.setUrlParameter("Version", "2015-04-01"); Map<String, String> body = new HashMap<String, String>(); body.put("DurationSeconds", String.valueOf(durationSeconds)); body.put("RoleArn", this.roleArn); body.put("OIDCProviderArn", this.oidcProviderArn); body.put("OIDCToken", oidcToken); body.put("RoleSessionName", this.roleSessionName); body.put("Policy", this.policy); try { StringBuilder content = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : body.entrySet()) { if (StringUtils.isEmpty(entry.getValue())) { continue; } if (first) { first = false; } else { content.append("&"); } content.append(URLEncoder.encode(entry.getKey(), "UTF-8")); content.append("="); content.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } httpRequest.setHttpContent(content.toString().getBytes("UTF-8"), "UTF-8", FormatType.FORM); } catch (UnsupportedEncodingException e) { throw new CredentialException(String.format("Error refreshing credentials from OIDC: %s.", e.getMessage())); } httpRequest.setSysMethod(MethodType.POST); httpRequest.setSysConnectTimeout(this.connectionTimeout); httpRequest.setSysReadTimeout(this.readTimeout); httpRequest.setSysUrl(parameterHelper.composeUrl(this.stsEndpoint, httpRequest.getUrlParameters(), protocol)); HttpResponse httpResponse; try { httpResponse = client.syncInvoke(httpRequest); } catch (Exception e) { throw new CredentialException("Failed to connect OIDC Service: " + e); } if (httpResponse.getResponseCode() != 200) { throw new CredentialException(String.format("Error refreshing credentials from OIDC, HttpCode: %s, result: %s.", httpResponse.getResponseCode(), httpResponse.getHttpContentString())); } Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(httpResponse.getHttpContentString(), Map.class); if (null == map || !map.containsKey("Credentials")) { throw new CredentialException(String.format("Error retrieving credentials from OIDC result: %s.", httpResponse.getHttpContentString())); } Map<String, String> result = (Map<String, String>) map.get("Credentials"); if (!result.containsKey("AccessKeyId") || !result.containsKey("AccessKeySecret") || !result.containsKey("SecurityToken")) { throw new CredentialException(String.format("Error retrieving credentials from OIDC result: %s.", httpResponse.getHttpContentString())); } Instant expiration = ParameterHelper.getUTCDate(result.get("Expiration")).toInstant(); ICredential credential = Credential.builder() .accessKeyId(result.get("AccessKeyId")) .accessKeySecret(result.get("AccessKeySecret")) .securityToken(result.get("SecurityToken")) .build(); return RefreshResult.builder(credential) .staleTime(getStaleTime(expiration)) .prefetchTime(getPrefetchTime(expiration)) .build(); } @Override public void close() { super.close(); this.client.close(); } public interface Builder extends HttpCredentialProvider.Builder<OIDCRoleArnCredentialProvider, Builder> { Builder roleSessionName(String roleSessionName); Builder durationSeconds(Integer durationSeconds); Builder roleArn(String roleArn); Builder oidcProviderArn(String oidcProviderArn); Builder oidcTokenFilePath(String oidcTokenFilePath); Builder policy(String policy); Builder connectionTimeout(Integer connectionTimeout); Builder readTimeout(Integer readTimeout); Builder stsEndpoint(String stsEndpoint); Builder stsRegionId(String stsRegionId); Builder enableVpc(Boolean enableVpc); @Override OIDCRoleArnCredentialProvider build(); } private static final class BuilderImpl extends HttpCredentialProvider.BuilderImpl<OIDCRoleArnCredentialProvider, Builder> implements Builder { private String roleSessionName; private Integer durationSeconds; private String roleArn; private String oidcProviderArn; private String oidcTokenFilePath; private String policy; private Integer connectionTimeout; private Integer readTimeout; private String stsEndpoint; private String stsRegionId; private Boolean enableVpc; public Builder roleSessionName(String roleSessionName) { this.roleSessionName = roleSessionName; return this; } public Builder durationSeconds(Integer durationSeconds) { this.durationSeconds = durationSeconds; return this; } public Builder roleArn(String roleArn) { this.roleArn = roleArn; return this; } public Builder oidcProviderArn(String oidcProviderArn) { this.oidcProviderArn = oidcProviderArn; return this; } public Builder oidcTokenFilePath(String oidcTokenFilePath) { this.oidcTokenFilePath = oidcTokenFilePath; return this; } public Builder policy(String policy) { this.policy = policy; return this; } public Builder connectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder readTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } public Builder stsEndpoint(String stsEndpoint) { this.stsEndpoint = stsEndpoint; return this; } public Builder stsRegionId(String stsRegionId) { this.stsRegionId = stsRegionId; return this; } public Builder enableVpc(Boolean enableVpc) { this.enableVpc = enableVpc; return this; } @Override public OIDCRoleArnCredentialProvider build() { return new OIDCRoleArnCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/ProfileCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.utils.*; import com.aliyun.core.utils.StringUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ProfileCredentialProvider implements ICredentialProvider { private static volatile Map<String, Map<String, String>> ini; private final String profileFile; private final String clientType; private final ICredentialProvider credentialProvider; private final boolean asyncCredentialUpdateEnabled; private ProfileCredentialProvider(Builder builder) { this.profileFile = builder.profileFile == null ? AuthConstant.DEFAULT_CREDENTIALS_FILE_PATH : builder.profileFile; this.clientType = builder.clientType == null ? AuthConstant.DEFAULT_CLIENT_TYPE : builder.clientType; this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled; if (this.profileFile.length() == 0) { throw new CredentialException("The specified credentials file is empty."); } Map<String, Map<String, String>> ini; try { ini = getIni(this.profileFile); } catch (IOException e) { throw new CredentialException("The specified credentials file is not exist."); } Map<String, Map<String, String>> client = loadIni(ini); Map<String, String> clientConfig = client.get(this.clientType); if (clientConfig == null) { throw new CredentialException("Client is not open in the specified credentials file."); } this.credentialProvider = createCredentialProvider(clientConfig); } public static Builder builder() { return new Builder(); } public static ProfileCredentialProvider create() { return builder().build(); } public static ProfileCredentialProvider create(String clientType) { return builder().clientType(clientType).build(); } @Override public ICredential getCredentials() throws CredentialException { return credentialProvider.getCredentials(); } @Override public void close() { } private static Map<String, Map<String, String>> getIni(String profileFile) throws IOException { if (null == ini) { ini = ProfileUtils.parseFile(profileFile); } return ini; } private Map<String, Map<String, String>> loadIni(Map<String, Map<String, String>> ini) { Map<String, Map<String, String>> client = new HashMap<String, Map<String, String>>(16); String enable; for (Map.Entry<String, Map<String, String>> clientType : ini.entrySet()) { enable = clientType.getValue().get(AuthConstant.INI_ENABLE); if (Boolean.parseBoolean(enable)) { Map<String, String> clientConfig = new HashMap<String, String>(16); for (Map.Entry<String, String> enabledClient : clientType.getValue().entrySet()) { clientConfig.put(enabledClient.getKey(), enabledClient.getValue()); } client.put(clientType.getKey(), clientConfig); } } return client; } private ICredentialProvider createCredentialProvider(Map<String, String> clientConfig) { String configType = clientConfig.get(AuthConstant.INI_TYPE); if (StringUtils.isEmpty(configType)) { throw new CredentialException("The configured client type is empty."); } if (AuthConstant.INI_TYPE_ARN.equals(configType)) { return getSTSAssumeRoleSessionCredentialProvider(clientConfig); } if (AuthConstant.INI_TYPE_KEY_PAIR.equals(configType)) { return getSTSGetSessionAccessKeyCredentialProvider(clientConfig); } if (AuthConstant.INI_TYPE_RAM.equals(configType)) { return getInstanceProfileCredentialProvider(clientConfig); } if (AuthConstant.INI_TYPE_OIDC.equals(configType)) { return getSTSOIDCRoleSessionCredentials(clientConfig); } String accessKeyId = clientConfig.get(AuthConstant.INI_ACCESS_KEY_ID); String accessKeySecret = clientConfig.get(AuthConstant.INI_ACCESS_KEY_IDSECRET); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { throw new CredentialException("The configured access_key_id or access_key_secret is empty"); } return StaticCredentialProvider.create(Credential.builder() .accessKeyId(accessKeyId) .accessKeySecret(accessKeySecret) .build()); } private ICredentialProvider getSTSAssumeRoleSessionCredentialProvider(Map<String, String> clientConfig) { String accessKeyId = clientConfig.get(AuthConstant.INI_ACCESS_KEY_ID); String accessKeySecret = clientConfig.get(AuthConstant.INI_ACCESS_KEY_IDSECRET); String roleSessionName = clientConfig.get(AuthConstant.INI_ROLE_SESSION_NAME); String roleArn = clientConfig.get(AuthConstant.INI_ROLE_ARN); String regionId = clientConfig.get(AuthConstant.DEFAULT_REGION); String policy = clientConfig.get(AuthConstant.INI_POLICY); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { throw new CredentialException("The configured access_key_id or access_key_secret is empty."); } if (StringUtils.isEmpty(roleSessionName) || StringUtils.isEmpty(roleArn)) { throw new CredentialException("The configured role_session_name or role_arn is empty."); } return RamRoleArnCredentialProvider.builder() .roleSessionName(roleSessionName) .roleArn(roleArn) .regionId(regionId) .policy(policy) .asyncCredentialUpdateEnabled(this.asyncCredentialUpdateEnabled) .credential(Credential.builder() .accessKeyId(accessKeyId) .accessKeySecret(accessKeySecret) .build()) .build(); } private ICredentialProvider getSTSOIDCRoleSessionCredentials(Map<String, String> clientConfig) { String roleSessionName = clientConfig.get(AuthConstant.INI_ROLE_SESSION_NAME); String roleArn = clientConfig.get(AuthConstant.INI_ROLE_ARN); String OIDCProviderArn = clientConfig.get(AuthConstant.INI_OIDC_PROVIDER_ARN); String OIDCTokenFilePath = clientConfig.get(AuthConstant.INI_OIDC_TOKEN_FILE_PATH); String policy = clientConfig.get(AuthConstant.INI_POLICY); if (StringUtils.isEmpty(roleArn)) { throw new CredentialException("The configured role_arn is empty."); } if (StringUtils.isEmpty(OIDCProviderArn)) { throw new CredentialException("The configured oidc_provider_arn is empty."); } if (StringUtils.isEmpty(OIDCTokenFilePath)) { throw new CredentialException("The configured oidc_token_file_path is empty."); } return OIDCRoleArnCredentialProvider.builder() .roleArn(roleArn) .roleSessionName(roleSessionName) .oidcProviderArn(OIDCProviderArn) .oidcTokenFilePath(OIDCTokenFilePath) .policy(policy) .build(); } public ICredentialProvider getSTSGetSessionAccessKeyCredentialProvider(Map<String, String> clientConfig) { String publicKeyId = clientConfig.get(AuthConstant.INI_PUBLIC_KEY_ID); String privateKeyFile = clientConfig.get(AuthConstant.INI_PRIVATE_KEY_FILE); if (StringUtils.isEmpty(privateKeyFile)) { throw new CredentialException("The configured private_key_file is empty."); } String privateKey = AuthUtils.getPrivateKey(privateKeyFile); if (StringUtils.isEmpty(publicKeyId) || StringUtils.isEmpty(privateKey)) { throw new CredentialException("The configured public_key_id or private_key_file content is empty."); } return RsaKeyPairCredentialProvider.builder() .asyncCredentialUpdateEnabled(this.asyncCredentialUpdateEnabled) .credential(Credential.builder() .accessKeyId(publicKeyId) .accessKeySecret(privateKey) .build()) .build(); } private ICredentialProvider getInstanceProfileCredentialProvider(Map<String, String> clientConfig) { String roleName = clientConfig.get(AuthConstant.INI_ROLE_NAME); if (StringUtils.isEmpty(roleName)) { throw new CredentialException("The configured role_name is empty."); } return EcsRamRoleCredentialProvider.builder() .asyncCredentialUpdateEnabled(this.asyncCredentialUpdateEnabled) .roleName(roleName) .build(); } static final class Builder { private String profileFile = AuthConstant.CREDENTIALS_FILE_PATH; private String clientType = AuthConstant.CLIENT_TYPE; private boolean asyncCredentialUpdateEnabled = false; public Builder profileFile(String profileFile) { this.profileFile = profileFile; return this; } public Builder clientType(String clientType) { this.clientType = clientType; return this; } public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) { this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled; return this; } public ProfileCredentialProvider build() { return new ProfileCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/RamRoleArnCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.http.*; import com.aliyun.auth.credentials.utils.*; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import com.google.gson.Gson; import java.time.Instant; import java.util.Map; public final class RamRoleArnCredentialProvider extends HttpCredentialProvider { /** * Default duration for started sessions. Unit of Second */ private int durationSeconds; /** * The arn of the role to be assumed. */ private String roleArn; /** * An identifier for the assumed role session. */ private final String roleSessionName; private String policy; private String externalId; /** * Unit of millisecond */ private int connectionTimeout; private int readTimeout; private final ICredentialProvider credentialsProvider; /** * Endpoint of RAM OpenAPI */ private final String stsEndpoint; private final CompatibleUrlConnClient client; private String protocol = "https"; private RamRoleArnCredentialProvider(BuilderImpl builder) { super(builder); this.roleSessionName = builder.roleSessionName == null ? !StringUtils.isEmpty(AuthUtils.getEnvironmentRoleSessionName()) ? AuthUtils.getEnvironmentRoleSessionName() : "aliyun-java-auth-" + System.currentTimeMillis() : builder.roleSessionName; this.durationSeconds = builder.durationSeconds == null ? 3600 : builder.durationSeconds; if (this.durationSeconds < 900) { throw new IllegalArgumentException("Session duration should be in the range of 900s - max session duration."); } this.roleArn = builder.roleArn == null ? AuthUtils.getEnvironmentRoleArn() : builder.roleArn; if (StringUtils.isEmpty(this.roleArn)) { throw new IllegalArgumentException("RoleArn or environment variable ALIBABA_CLOUD_ROLE_ARN cannot be empty."); } this.policy = builder.policy; this.externalId = builder.externalId; this.connectionTimeout = builder.connectionTimeout == null ? 5000 : builder.connectionTimeout; this.readTimeout = builder.readTimeout == null ? 10000 : builder.readTimeout; if (!StringUtils.isEmpty(builder.stsEndpoint)) { this.stsEndpoint = builder.stsEndpoint; } else { String prefix = builder.enableVpc != null ? (builder.enableVpc ? "sts-vpc" : "sts") : AuthUtils.isEnableVpcEndpoint() ? "sts-vpc" : "sts"; if (!StringUtils.isEmpty(builder.stsRegionId)) { this.stsEndpoint = String.format("%s.%s.aliyuncs.com", prefix, builder.stsRegionId); } else if (!StringUtils.isEmpty(AuthUtils.getEnvironmentSTSRegion())) { this.stsEndpoint = String.format("%s.%s.aliyuncs.com", prefix, AuthUtils.getEnvironmentSTSRegion()); } else { this.stsEndpoint = "sts.aliyuncs.com"; } } if (null != builder.credentialsProvider) { this.credentialsProvider = builder.credentialsProvider; } else { Validate.notNull(builder.credential, "Credentials must not be null."); this.credentialsProvider = StaticCredentialProvider.create(builder.credential); } this.client = new CompatibleUrlConnClient(); this.buildRefreshCache(); } public static RamRoleArnCredentialProvider create(Credential credential) { return builder().credential(credential).build(); } public static Builder builder() { return new BuilderImpl(); } public String getStsEndpoint() { return this.stsEndpoint; } @Override public RefreshResult<ICredential> refreshCredentials() { ParameterHelper parameterHelper = new ParameterHelper(); HttpRequest httpRequest = new HttpRequest(); httpRequest.setUrlParameter("Action", "AssumeRole"); httpRequest.setUrlParameter("Format", "JSON"); httpRequest.setUrlParameter("Version", "2015-04-01"); httpRequest.setUrlParameter("DurationSeconds", String.valueOf(durationSeconds)); httpRequest.setUrlParameter("RoleArn", roleArn); httpRequest.setUrlParameter("RoleSessionName", roleSessionName); if (policy != null) { httpRequest.setUrlParameter("Policy", policy); } if (externalId != null) { httpRequest.setUrlParameter("ExternalId", this.externalId); } httpRequest.setSysMethod(MethodType.GET); httpRequest.setSysConnectTimeout(this.connectionTimeout); httpRequest.setSysReadTimeout(this.readTimeout); ICredential credentials = this.credentialsProvider.getCredentials(); Validate.notNull(credentials, "Unable to load original credentials from the providers in RAM role arn."); httpRequest.setUrlParameter("AccessKeyId", credentials.accessKeyId()); if (!StringUtils.isEmpty(credentials.securityToken())) { httpRequest.setUrlParameter("SecurityToken", credentials.securityToken()); } String strToSign = parameterHelper.composeStringToSign(MethodType.GET, httpRequest.getUrlParameters()); String signature = parameterHelper.signString(strToSign, credentials.accessKeySecret() + "&"); httpRequest.setUrlParameter("Signature", signature); httpRequest.setSysUrl(parameterHelper.composeUrl(this.stsEndpoint, httpRequest.getUrlParameters(), protocol)); HttpResponse httpResponse; try { httpResponse = client.syncInvoke(httpRequest); } catch (Exception e) { throw new CredentialException("Failed to connect RamRoleArn Service: " + e); } if (httpResponse.getResponseCode() != 200) { throw new CredentialException(String.format("Error refreshing credentials from RamRoleArn, HttpCode: %s, result: %s.", httpResponse.getResponseCode(), httpResponse.getHttpContentString())); } Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(httpResponse.getHttpContentString(), Map.class); if (null == map || !map.containsKey("Credentials")) { throw new CredentialException(String.format("Error retrieving credentials from RamRoleArn result: %s.", httpResponse.getHttpContentString())); } Map<String, String> result = (Map<String, String>) map.get("Credentials"); if (!result.containsKey("AccessKeyId") || !result.containsKey("AccessKeySecret") || !result.containsKey("SecurityToken")) { throw new CredentialException(String.format("Error retrieving credentials from RamRoleArn result: %s.", httpResponse.getHttpContentString())); } Instant expiration = ParameterHelper.getUTCDate(result.get("Expiration")).toInstant(); ICredential credential = Credential.builder() .accessKeyId(result.get("AccessKeyId")) .accessKeySecret(result.get("AccessKeySecret")) .securityToken(result.get("SecurityToken")) .build(); return RefreshResult.builder(credential) .staleTime(getStaleTime(expiration)) .prefetchTime(getPrefetchTime(expiration)) .build(); } @Override public void close() { super.close(); this.client.close(); } public interface Builder extends HttpCredentialProvider.Builder<RamRoleArnCredentialProvider, Builder> { Builder roleSessionName(String roleSessionName); Builder durationSeconds(Integer durationSeconds); Builder roleArn(String roleArn); Builder regionId(String regionId); Builder policy(String policy); Builder connectionTimeout(Integer connectionTimeout); Builder readTimeout(Integer readTimeout); Builder credential(Credential credential); Builder credentialsProvider(ICredentialProvider credentialsProvider); Builder stsEndpoint(String stsEndpoint); Builder stsRegionId(String stsRegionId); Builder enableVpc(Boolean enableVpc); Builder externalId(String externalId); @Override RamRoleArnCredentialProvider build(); } private static final class BuilderImpl extends HttpCredentialProvider.BuilderImpl<RamRoleArnCredentialProvider, Builder> implements Builder { private String roleSessionName; private Integer durationSeconds; private String roleArn; private String regionId; private String policy; private Integer connectionTimeout; private Integer readTimeout; private Credential credential; private String stsEndpoint; private String stsRegionId; private Boolean enableVpc; private ICredentialProvider credentialsProvider; private String externalId; public Builder roleSessionName(String roleSessionName) { this.roleSessionName = roleSessionName; return this; } public Builder durationSeconds(Integer durationSeconds) { this.durationSeconds = durationSeconds; return this; } public Builder roleArn(String roleArn) { this.roleArn = roleArn; return this; } public Builder regionId(String regionId) { this.regionId = regionId; return this; } public Builder policy(String policy) { this.policy = policy; return this; } public Builder connectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder readTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } public Builder credential(Credential credential) { this.credential = credential; return this; } public Builder credentialsProvider(ICredentialProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } public Builder stsEndpoint(String stsEndpoint) { this.stsEndpoint = stsEndpoint; return this; } public Builder stsRegionId(String stsRegionId) { this.stsRegionId = stsRegionId; return this; } public Builder enableVpc(Boolean enableVpc) { this.enableVpc = enableVpc; return this; } public Builder externalId(String externalId) { this.externalId = externalId; return this; } @Override public RamRoleArnCredentialProvider build() { return new RamRoleArnCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/RsaKeyPairCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.http.*; import com.aliyun.auth.credentials.utils.*; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import com.google.gson.Gson; import java.time.Instant; import java.util.Map; public class RsaKeyPairCredentialProvider extends HttpCredentialProvider { /** * Default duration for started sessions. Unit of Second */ private int durationSeconds; private String regionId; /** * Unit of millisecond */ private int connectionTimeout; private int readTimeout; private Credential credential; private final String stsEndpoint; private final CompatibleUrlConnClient client; private RsaKeyPairCredentialProvider(BuilderImpl builder) { super(builder); this.durationSeconds = builder.durationSeconds == null ? 3600 : builder.durationSeconds; if (this.durationSeconds < 900) { throw new IllegalArgumentException("Session duration should be in the range of 900s - max session duration."); } this.regionId = builder.regionId; this.connectionTimeout = builder.connectionTimeout == null ? 5000 : builder.connectionTimeout; this.readTimeout = builder.readTimeout == null ? 10000 : builder.readTimeout; this.credential = Validate.notNull(builder.credential, "Credentials must not be null."); if (!StringUtils.isEmpty(builder.stsEndpoint)) { this.stsEndpoint = builder.stsEndpoint; } else { String prefix = builder.enableVpc != null ? (builder.enableVpc ? "sts-vpc" : "sts") : AuthUtils.isEnableVpcEndpoint() ? "sts-vpc" : "sts"; if (!StringUtils.isEmpty(builder.stsRegionId)) { this.stsEndpoint = String.format("%s.%s.aliyuncs.com", prefix, builder.stsRegionId); } else if (!StringUtils.isEmpty(AuthUtils.getEnvironmentSTSRegion())) { this.stsEndpoint = String.format("%s.%s.aliyuncs.com", prefix, AuthUtils.getEnvironmentSTSRegion()); } else { this.stsEndpoint = "sts.ap-northeast-1.aliyuncs.com"; } } this.client = new CompatibleUrlConnClient(); this.buildRefreshCache(); } public static RsaKeyPairCredentialProvider create(Credential credential) { return builder().credential(credential).build(); } public static Builder builder() { return new BuilderImpl(); } @Override public RefreshResult<ICredential> refreshCredentials() { ParameterHelper parameterHelper = new ParameterHelper(); HttpRequest httpRequest = new HttpRequest(); httpRequest.setUrlParameter("Action", "GenerateSessionAccessKey"); httpRequest.setUrlParameter("Format", "JSON"); httpRequest.setUrlParameter("Version", "2015-04-01"); httpRequest.setUrlParameter("DurationSeconds", String.valueOf(durationSeconds)); httpRequest.setUrlParameter("AccessKeyId", credential.accessKeyId()); httpRequest.setUrlParameter("RegionId", this.regionId); String strToSign = parameterHelper.composeStringToSign(MethodType.GET, httpRequest.getUrlParameters()); String signature = parameterHelper.signString(strToSign, credential.accessKeySecret() + "&"); httpRequest.setUrlParameter("Signature", signature); httpRequest.setSysMethod(MethodType.GET); httpRequest.setSysConnectTimeout(this.connectionTimeout); httpRequest.setSysReadTimeout(this.readTimeout); httpRequest.setSysUrl(parameterHelper.composeUrl(this.stsEndpoint, httpRequest.getUrlParameters(), "https")); HttpResponse httpResponse; try { httpResponse = client.syncInvoke(httpRequest); } catch (Exception e) { throw new CredentialException("Failed to connect RsaKeyPair Service: " + e); } if (httpResponse.getResponseCode() != 200) { throw new CredentialException(String.format("Error refreshing credentials from RsaKeyPair, HttpCode: %s, result: %s.", httpResponse.getResponseCode(), httpResponse.getHttpContentString())); } Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(httpResponse.getHttpContentString(), Map.class); if (null == map || !map.containsKey("SessionAccessKey")) { throw new CredentialException(String.format("Error retrieving credentials from RsaKeyPair result: %s.", httpResponse.getHttpContentString())); } Map<String, String> credentials = (Map<String, String>) map.get("SessionAccessKey"); Instant expiration = ParameterHelper.getUTCDate(credentials.get("Expiration")).toInstant(); ICredential credential = Credential.builder() .accessKeyId(credentials.get("SessionAccessKeyId")) .accessKeySecret(credentials.get("SessionAccessKeySecret")) .build(); return RefreshResult.builder(credential) .staleTime(getStaleTime(expiration)) .prefetchTime(getPrefetchTime(expiration)) .build(); } @Override public void close() { super.close(); this.client.close(); } public interface Builder extends HttpCredentialProvider.Builder<RsaKeyPairCredentialProvider, Builder> { Builder durationSeconds(Integer durationSeconds); Builder regionId(String regionId); Builder connectionTimeout(Integer connectionTimeout); Builder readTimeout(Integer readTimeout); Builder credential(Credential credential); Builder stsEndpoint(String stsEndpoint); Builder stsRegionId(String stsRegionId); Builder enableVpc(Boolean enableVpc); @Override RsaKeyPairCredentialProvider build(); } private static final class BuilderImpl extends HttpCredentialProvider.BuilderImpl<RsaKeyPairCredentialProvider, Builder> implements Builder { private Integer durationSeconds; private String regionId = "cn-hangzhou"; /** * Unit of millisecond */ private Integer connectionTimeout; private Integer readTimeout; private Credential credential; private String stsEndpoint; private String stsRegionId; private Boolean enableVpc; public Builder durationSeconds(Integer durationSeconds) { if (!StringUtils.isEmpty(durationSeconds)) { this.durationSeconds = durationSeconds; } return this; } public Builder regionId(String regionId) { if (!StringUtils.isEmpty(regionId)) { this.regionId = regionId; } return this; } public Builder connectionTimeout(Integer connectionTimeout) { if (!StringUtils.isEmpty(connectionTimeout)) { this.connectionTimeout = connectionTimeout; } return this; } public Builder readTimeout(Integer readTimeout) { if (!StringUtils.isEmpty(readTimeout)) { this.readTimeout = readTimeout; } return this; } public Builder credential(Credential credential) { this.credential = credential; return this; } public Builder stsEndpoint(String stsEndpoint) { this.stsEndpoint = stsEndpoint; return this; } public Builder stsRegionId(String stsRegionId) { this.stsRegionId = stsRegionId; return this; } public Builder enableVpc(Boolean enableVpc) { this.enableVpc = enableVpc; return this; } @Override public RsaKeyPairCredentialProvider build() { return new RsaKeyPairCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/StaticCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.core.utils.StringUtils; import com.aliyun.core.utils.Validate; import java.util.HashMap; import java.util.Map; public class StaticCredentialProvider implements ICredentialProvider { private Credential credential; private StaticCredentialProvider(Credential credential) { this.credential = Validate.notNull(credential, "Credentials must not be null."); } public static StaticCredentialProvider create(Credential credentials) { return new StaticCredentialProvider(credentials); } public ICredential getCredentials() throws CredentialException { return credential; } @Override public void close() { } @Override public String toString() { Map<String, Object> fieldMap = new HashMap<>(); fieldMap.put("credential", credential); return StringUtils.toAliString("StaticCredentialsProvider", fieldMap); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/SystemPropertiesCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.utils.*; import com.aliyun.core.utils.StringUtils; public class SystemPropertiesCredentialProvider implements ICredentialProvider { public static SystemPropertiesCredentialProvider create() { return new SystemPropertiesCredentialProvider(); } @Override public ICredential getCredentials() throws CredentialException { String accessKeyId = System.getProperty(AuthConstant.SYSTEM_ACCESSKEYID); String accessKeySecret = System.getProperty(AuthConstant.SYSTEM_ACCESSKEY_SECRET); if (!StringUtils.isEmpty(System.getProperty(AuthConstant.SYSTEM_ACCESSKEYSECRET))) { accessKeySecret = System.getProperty(AuthConstant.SYSTEM_ACCESSKEYSECRET); } String securityToken = System.getProperty(AuthConstant.SYSTEM_SESSION_TOKEN); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { throw new CredentialException("System Properties variable accessKeyId/accessKeySecret cannot be empty"); } if (!StringUtils.isEmpty(securityToken)) { return Credential.builder() .accessKeyId(accessKeyId) .accessKeySecret(accessKeySecret) .securityToken(securityToken) .build(); } return Credential.builder() .accessKeyId(accessKeyId) .accessKeySecret(accessKeySecret) .build(); } @Override public void close() { } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/provider/URLCredentialProvider.java
package com.aliyun.auth.credentials.provider; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.ICredential; import com.aliyun.auth.credentials.exception.CredentialException; import com.aliyun.auth.credentials.http.CompatibleUrlConnClient; import com.aliyun.auth.credentials.http.HttpRequest; import com.aliyun.auth.credentials.http.HttpResponse; import com.aliyun.auth.credentials.http.MethodType; import com.aliyun.auth.credentials.utils.AuthUtils; import com.aliyun.auth.credentials.utils.ParameterHelper; import com.aliyun.auth.credentials.utils.RefreshResult; import com.aliyun.core.utils.StringUtils; import com.google.gson.Gson; import java.net.MalformedURLException; import java.net.URL; import java.time.Instant; import java.util.Map; public class URLCredentialProvider extends HttpCredentialProvider { private final URL credentialsURI; /** * Unit of millisecond */ private int connectTimeout; private int readTimeout; private final CompatibleUrlConnClient client; private URLCredentialProvider(BuilderImpl builder) { super(builder); String credentialsURI = builder.credentialsURI == null ? AuthUtils.getEnvironmentCredentialsURI() : builder.credentialsURI; if (StringUtils.isEmpty(credentialsURI)) { throw new IllegalArgumentException("Credential URI or environment variable ALIBABA_CLOUD_CREDENTIALS_URI cannot be empty."); } try { this.credentialsURI = new URL(credentialsURI); } catch (MalformedURLException e) { throw new IllegalArgumentException("Credential URI is not valid."); } this.connectTimeout = builder.connectionTimeout == null ? 5000 : builder.connectionTimeout; this.readTimeout = builder.readTimeout == null ? 10000 : builder.readTimeout; this.client = new CompatibleUrlConnClient(); this.buildRefreshCache(); } public static Builder builder() { return new BuilderImpl(); } @Override public RefreshResult<ICredential> refreshCredentials() { HttpRequest request = new HttpRequest(this.credentialsURI.toString()); request.setSysMethod(MethodType.GET); request.setSysConnectTimeout(connectTimeout); request.setSysReadTimeout(readTimeout); HttpResponse response; try { response = client.syncInvoke(request); } catch (Exception e) { throw new CredentialException("Failed to connect Server: " + e.toString(), e); } finally { client.close(); } if (response.getResponseCode() >= 300 || response.getResponseCode() < 200) { throw new CredentialException("Failed to get credentials from server: " + this.credentialsURI.toString() + "\nHttpCode=" + response.getResponseCode() + "\nHttpRAWContent=" + response.getHttpContentString()); } Gson gson = new Gson(); Map<String, String> map; try { map = gson.fromJson(response.getHttpContentString(), Map.class); } catch (Exception e) { throw new CredentialException("Failed to get credentials from server: " + this.credentialsURI.toString() + "\nHttpCode=" + response.getResponseCode() + "\nHttpRAWContent=" + response.getHttpContentString(), e); } if (map.containsKey("Code") && map.get("Code").equals("Success")) { Instant expiration = ParameterHelper.getUTCDate(map.get("Expiration")).toInstant(); ICredential credential = Credential.builder() .accessKeyId(map.get("AccessKeyId")) .accessKeySecret(map.get("AccessKeySecret")) .securityToken(map.get("SecurityToken")) .build(); return RefreshResult.builder(credential) .staleTime(getStaleTime(expiration)) .prefetchTime(getPrefetchTime(expiration)) .build(); } else { throw new CredentialException(String.format("Error retrieving credentials from credentialsURI result: %s.", response.getHttpContentString())); } } @Override public void close() { super.close(); this.client.close(); } public interface Builder extends HttpCredentialProvider.Builder<URLCredentialProvider, Builder> { Builder credentialsURI(URL credentialsURI); Builder credentialsURI(String credentialsURI); Builder connectionTimeout(Integer connectionTimeout); Builder readTimeout(Integer readTimeout); @Override URLCredentialProvider build(); } private static final class BuilderImpl extends HttpCredentialProvider.BuilderImpl<URLCredentialProvider, Builder> implements Builder { private String credentialsURI; private Integer connectionTimeout; private Integer readTimeout; public Builder credentialsURI(URL credentialsURI) { this.credentialsURI = credentialsURI.toString(); return this; } public Builder credentialsURI(String credentialsURI) { this.credentialsURI = credentialsURI; return this; } public Builder connectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder readTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } @Override public URLCredentialProvider build() { return new URLCredentialProvider(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/AcsURLEncoder.java
package com.aliyun.auth.credentials.utils; import com.aliyun.auth.credentials.exception.*; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class AcsURLEncoder { public final static String URL_ENCODING = "UTF-8"; public static String encode(String value) { try { return URLEncoder.encode(value, URL_ENCODING); } catch (UnsupportedEncodingException e) { throw new CredentialException(e.getMessage(), e); } } public static String percentEncode(String value) { try { return value != null ? URLEncoder.encode(value, URL_ENCODING).replace("+", "%20") .replace("*", "%2A").replace("%7E", "~") : null; } catch (UnsupportedEncodingException e) { throw new CredentialException(e.getMessage(), e); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/AuthConstant.java
package com.aliyun.auth.credentials.utils; public class AuthConstant { public static final String SYSTEM_ACCESSKEYID = "alibabacloud.accessKeyId"; public static final String SYSTEM_ACCESSKEYSECRET = "alibabacloud.accessKeyIdSecret"; public static final String SYSTEM_ACCESSKEY_SECRET = "alibabacloud.accessKeySecret"; public static final String SYSTEM_SESSION_TOKEN = "alibabacloud.sessionToken"; public static final String DEFAULT_CREDENTIALS_FILE_PATH = System.getProperty("user.home") + "/.alibabacloud/credentials.ini"; public static final String CREDENTIALS_FILE_PATH = System.getenv("ALIBABA_CLOUD_CREDENTIALS_FILE"); public static final String DEFAULT_CLIENT_TYPE = "default"; public static final String CLIENT_TYPE = System.getenv("ALIBABA_CLOUD_PROFILE"); public static final String ENV_ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); public static final String ENV_ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); public static final String INI_ACCESS_KEY_ID = "access_key_id"; public static final String INI_ACCESS_KEY_IDSECRET = "access_key_secret"; public static final String INI_TYPE = "type"; public static final String INI_TYPE_RAM = "ecs_ram_role"; public static final String INI_TYPE_ARN = "ram_role_arn"; public static final String INI_TYPE_OIDC = "oidc_role_arn"; public static final String INI_TYPE_KEY_PAIR = "rsa_key_pair"; public static final String INI_PUBLIC_KEY_ID = "public_key_id"; public static final String INI_PRIVATE_KEY_FILE = "private_key_file"; public static final String INI_PRIVATE_KEY = "private_key"; public static final String INI_ROLE_NAME = "role_name"; public static final String INI_ROLE_SESSION_NAME = "role_session_name"; public static final String INI_ROLE_ARN = "role_arn"; public static final String INI_POLICY = "policy"; public static final String INI_OIDC_PROVIDER_ARN = "oidc_provider_arn"; public static final String INI_OIDC_TOKEN_FILE_PATH = "oidc_token_file_path"; public static final long TSC_VALID_TIME_SECONDS = 3600L; public static final String DEFAULT_REGION = "region_id"; public static final String INI_ENABLE = "enable"; public static final String ACCESS_KEY = "access_key"; public static final String STS = "sts"; public static final String ECS_RAM_ROLE = "ecs_ram_role"; public static final String RAM_ROLE_ARN = "ram_role_arn"; public static final String OIDC_ROLE_ARN = "oidc_role_arn"; public static final String RSA_KEY_PAIR = "rsa_key_pair"; public static final String BEARER = "bearer"; public static final String CREDENTIALS_URI = "credentials_uri"; }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/AuthUtils.java
package com.aliyun.auth.credentials.utils; import com.aliyun.auth.credentials.exception.*; import com.aliyun.core.utils.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class AuthUtils { private static volatile String privateKey; private static volatile String OIDCToken; private static volatile String environmentAccessKeyId; private static volatile String environmentAccesskeySecret; private static volatile String environmentSecurityToken; private static volatile String environmentECSMetaData; private static volatile Boolean enableECSIMDSv2; private static volatile Boolean disableECSIMDSv1; private static volatile String environmentCredentialsFile; private static volatile String environmentRoleArn; private static volatile String environmentRoleSessionName; private static volatile String environmentOIDCProviderArn; private static volatile String environmentOIDCTokenFilePath; private static volatile Boolean disableCLIProfile; private static volatile Boolean disableECSMetaData; private static volatile String environmentCredentialsURI; private static volatile Boolean enableVpcEndpoint; private static volatile String environmentSTSRegion; public static String getPrivateKey(String filePath) { FileInputStream in = null; byte[] buffer; try { in = new FileInputStream(new File(filePath)); buffer = new byte[in.available()]; in.read(buffer); privateKey = new String(buffer, "UTF-8"); } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } } } return privateKey; } public static String getOIDCToken(String OIDCTokenFilePath) { FileInputStream in = null; byte[] buffer; File file = new File(OIDCTokenFilePath); if (!file.exists() || !file.isFile()) { throw new CredentialException("OIDCTokenFilePath " + OIDCTokenFilePath + " is not exists."); } if (!file.canRead()) { throw new CredentialException("OIDCTokenFilePath " + OIDCTokenFilePath + " cannot be read."); } try { in = new FileInputStream(file); buffer = new byte[in.available()]; in.read(buffer); OIDCToken = new String(buffer, "UTF-8"); } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw new CredentialException(e.getMessage(), e); } } } return OIDCToken; } public static void setPrivateKey(String key) { privateKey = key; } public static void setEnvironmentAccessKeyId(String environmentAccessKeyId) { AuthUtils.environmentAccessKeyId = environmentAccessKeyId; } public static String getEnvironmentAccessKeyId() { return null == AuthUtils.environmentAccessKeyId ? System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") : AuthUtils.environmentAccessKeyId; } public static String getEnvironmentAccessKeySecret() { return null == AuthUtils.environmentAccesskeySecret ? System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") : AuthUtils.environmentAccesskeySecret; } public static void setEnvironmentAccessKeySecret(String environmentAccesskeySecret) { AuthUtils.environmentAccesskeySecret = environmentAccesskeySecret; } public static String getEnvironmentSecurityToken() { return null == AuthUtils.environmentSecurityToken ? System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN") : AuthUtils.environmentSecurityToken; } public static void setEnvironmentSecurityToken(String environmentSecurityToken) { AuthUtils.environmentSecurityToken = environmentSecurityToken; } public static void setEnvironmentECSMetaData(String environmentECSMetaData) { AuthUtils.environmentECSMetaData = environmentECSMetaData; } public static String getEnvironmentECSMetaData() { return null == AuthUtils.environmentECSMetaData ? System.getenv("ALIBABA_CLOUD_ECS_METADATA") : AuthUtils.environmentECSMetaData; } public static void enableECSIMDSv2(boolean enableECSIMDSv2) { AuthUtils.enableECSIMDSv2 = enableECSIMDSv2; } public static boolean getEnableECSIMDSv2() { if (null != AuthUtils.enableECSIMDSv2) { return AuthUtils.enableECSIMDSv2; } else if (null != System.getenv("ALIBABA_CLOUD_ECS_IMDSV2_ENABLE")) { return Boolean.parseBoolean(System.getenv("ALIBABA_CLOUD_ECS_IMDSV2_ENABLE")); } return false; } public static void disableECSIMDSv1(boolean disableECSIMDSv1) { AuthUtils.disableECSIMDSv1 = disableECSIMDSv1; } public static boolean getDisableECSIMDSv1() { if (null != AuthUtils.disableECSIMDSv1) { return AuthUtils.disableECSIMDSv1; } else if (null != System.getenv("ALIBABA_CLOUD_IMDSV1_DISABLED")) { return Boolean.parseBoolean(System.getenv("ALIBABA_CLOUD_IMDSV1_DISABLED")); } return false; } public static void setEnvironmentRoleArn(String environmentRoleArn) { AuthUtils.environmentRoleArn = environmentRoleArn; } public static String getEnvironmentRoleArn() { return null == AuthUtils.environmentRoleArn ? System.getenv("ALIBABA_CLOUD_ROLE_ARN") : AuthUtils.environmentRoleArn; } public static void setEnvironmentRoleSessionName(String environmentRoleSessionName) { AuthUtils.environmentRoleSessionName = environmentRoleSessionName; } public static String getEnvironmentRoleSessionName() { return null == AuthUtils.environmentRoleSessionName ? System.getenv("ALIBABA_CLOUD_ROLE_SESSION_NAME") : AuthUtils.environmentRoleSessionName; } public static void setEnvironmentOIDCProviderArn(String environmentOIDCProviderArn) { AuthUtils.environmentOIDCProviderArn = environmentOIDCProviderArn; } public static String getEnvironmentOIDCProviderArn() { return null == AuthUtils.environmentOIDCProviderArn ? System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN") : AuthUtils.environmentOIDCProviderArn; } public static void setEnvironmentOIDCTokenFilePath(String environmentOIDCTokenFilePath) { AuthUtils.environmentOIDCTokenFilePath = environmentOIDCTokenFilePath; } public static String getEnvironmentOIDCTokenFilePath() { return null == AuthUtils.environmentOIDCTokenFilePath ? System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE") : AuthUtils.environmentOIDCTokenFilePath; } public static boolean environmentEnableOIDC() { return !StringUtils.isEmpty(getEnvironmentRoleArn()) && !StringUtils.isEmpty(getEnvironmentOIDCProviderArn()) && !StringUtils.isEmpty(getEnvironmentOIDCTokenFilePath()); } public static String getEnvironmentCredentialsFile() { return null == AuthUtils.environmentCredentialsFile ? System.getenv("ALIBABA_CLOUD_CREDENTIALS_FILE") : AuthUtils.environmentCredentialsFile; } public static void setEnvironmentCredentialsFile(String environmentCredentialsFile) { AuthUtils.environmentCredentialsFile = environmentCredentialsFile; } public static void disableCLIProfile(boolean disableCLIProfile) { AuthUtils.disableCLIProfile = disableCLIProfile; } public static boolean isDisableCLIProfile() { if (null != AuthUtils.disableCLIProfile) { return AuthUtils.disableCLIProfile; } else if (null != System.getenv("ALIBABA_CLOUD_CLI_PROFILE_DISABLED")) { return Boolean.parseBoolean(System.getenv("ALIBABA_CLOUD_CLI_PROFILE_DISABLED")); } return false; } public static void disableECSMetaData(boolean disableECSMetaData) { AuthUtils.disableECSMetaData = disableECSMetaData; } public static boolean isDisableECSMetaData() { if (null != AuthUtils.disableECSMetaData) { return AuthUtils.disableECSMetaData; } else if (null != System.getenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED")) { return Boolean.parseBoolean(System.getenv("ALIBABA_CLOUD_ECS_METADATA_DISABLED")); } return false; } public static void setEnvironmentCredentialsURI(String environmentCredentialsURI) { AuthUtils.environmentCredentialsURI = environmentCredentialsURI; } public static String getEnvironmentCredentialsURI() { return null == AuthUtils.environmentCredentialsURI ? System.getenv("ALIBABA_CLOUD_CREDENTIALS_URI") : AuthUtils.environmentCredentialsURI; } public static void enableVpcEndpoint(boolean enableVpcEndpoint) { AuthUtils.enableVpcEndpoint = enableVpcEndpoint; } public static boolean isEnableVpcEndpoint() { if (null != AuthUtils.enableVpcEndpoint) { return AuthUtils.enableVpcEndpoint; } else if (null != System.getenv("ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED")) { return Boolean.parseBoolean(System.getenv("ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED")); } return false; } public static void setEnvironmentSTSRegion(String environmentSTSRegion) { AuthUtils.environmentSTSRegion = environmentSTSRegion; } public static String getEnvironmentSTSRegion() { return null == AuthUtils.environmentSTSRegion ? System.getenv("ALIBABA_CLOUD_STS_REGION") : AuthUtils.environmentSTSRegion; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/Base64Helper.java
package com.aliyun.auth.credentials.utils; public class Base64Helper { private static final String BASE64_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/"; private static byte[] zeroPad(int length, byte[] bytes) { new Base64Helper(); byte[] padded = new byte[length]; System.arraycopy(bytes, 0, padded, 0, bytes.length); return padded; } public synchronized static String encode(byte[] buff) { StringBuilder strBuilder = new StringBuilder(""); int paddingCount = (3 - (buff.length % 3)) % 3; byte[] stringArray = zeroPad(buff.length + paddingCount, buff); for (int i = 0; i < stringArray.length; i += 3) { int j = ((stringArray[i] & 0xff) << 16) + ((stringArray[i + 1] & 0xff) << 8) + (stringArray[i + 2] & 0xff); strBuilder.append(BASE64_CODE.charAt((j >> 18) & 0x3f)); strBuilder.append(BASE64_CODE.charAt((j >> 12) & 0x3f)); strBuilder.append(BASE64_CODE.charAt((j >> 6) & 0x3f)); strBuilder.append(BASE64_CODE.charAt(j & 0x3f)); } int intPos = strBuilder.length(); for (int i = paddingCount; i > 0; i--) { strBuilder.setCharAt(intPos - i, '='); } return strBuilder.toString(); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/NonBlocking.java
package com.aliyun.auth.credentials.utils; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import static java.util.concurrent.TimeUnit.SECONDS; public class NonBlocking implements RefreshCachedSupplier.PrefetchStrategy { private final AtomicBoolean currentlyRefreshing = new AtomicBoolean(false); private final ExecutorService executor; public NonBlocking() { this.executor = new ThreadPoolExecutor(0, 1, 5, SECONDS, new LinkedBlockingQueue<>(1), Executors.defaultThreadFactory()); } @Override public void prefetch(Runnable valueUpdater) { if (currentlyRefreshing.compareAndSet(false, true)) { try { executor.submit(() -> { try { valueUpdater.run(); } finally { currentlyRefreshing.set(false); } }); } catch (RuntimeException e) { currentlyRefreshing.set(false); throw e; } } } @Override public void close() { executor.shutdown(); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/OneCallerBlocks.java
package com.aliyun.auth.credentials.utils; import java.util.concurrent.atomic.AtomicBoolean; public class OneCallerBlocks implements RefreshCachedSupplier.PrefetchStrategy { private final AtomicBoolean currentlyRefreshing = new AtomicBoolean(false); @Override public void prefetch(Runnable valueUpdater) { if (currentlyRefreshing.compareAndSet(false, true)) { try { valueUpdater.run(); } finally { currentlyRefreshing.set(false); } } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/ParameterHelper.java
package com.aliyun.auth.credentials.utils; import com.aliyun.auth.credentials.exception.*; import com.aliyun.auth.credentials.http.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class ParameterHelper { private final static String TIME_ZONE = "UTC"; private final static String FORMAT_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss'Z'"; private final static String SEPARATOR = "&"; public static final String ENCODING = "UTF-8"; private static final String ALGORITHM_NAME = "HmacSHA1"; public static String getUniqueNonce() { StringBuffer uniqueNonce = new StringBuffer(); UUID uuid = UUID.randomUUID(); uniqueNonce.append(uuid.toString()); uniqueNonce.append(System.currentTimeMillis()); uniqueNonce.append(Thread.currentThread().getId()); return uniqueNonce.toString(); } public static String getISO8601Time(Date date) { SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); return df.format(date); } public static Date getUTCDate(String date) { SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); try { return df.parse(date); } catch (ParseException e) { throw new CredentialException(e.getMessage(), e); } } public String composeStringToSign(MethodType method, Map<String, String> queries) { String[] sortedKeys = queries.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); StringBuilder canonicalizedQueryString = new StringBuilder(); for (String key : sortedKeys) { canonicalizedQueryString.append("&") .append(AcsURLEncoder.percentEncode(key)).append("=") .append(AcsURLEncoder.percentEncode(queries.get(key))); } StringBuilder stringToSign = new StringBuilder(); stringToSign.append(method.toString()); stringToSign.append(SEPARATOR); stringToSign.append(AcsURLEncoder.percentEncode("/")); stringToSign.append(SEPARATOR); stringToSign.append(AcsURLEncoder.percentEncode( canonicalizedQueryString.toString().substring(1))); return stringToSign.toString(); } public String signString(String stringToSign, String accessKeySecret) { try { Mac mac = Mac.getInstance(ALGORITHM_NAME); mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), ALGORITHM_NAME)); byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING)); return Base64.getEncoder().encodeToString(signData); } catch (Exception e) { throw new CredentialException(e.getMessage(), e); } } public String composeUrl(String endpoint, Map<String, String> queries, String protocol) { Map<String, String> mapQueries = queries; StringBuilder urlBuilder = new StringBuilder(""); urlBuilder.append(protocol); urlBuilder.append("://").append(endpoint); urlBuilder.append("/?"); StringBuilder builder = new StringBuilder(""); for (Map.Entry<String, String> entry : mapQueries.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); if (val == null) { continue; } builder.append(AcsURLEncoder.encode(key)); builder.append("=").append(AcsURLEncoder.encode(val)); builder.append("&"); } int strIndex = builder.length(); builder.deleteCharAt(strIndex - 1); String query = builder.toString(); return urlBuilder.append(query).toString(); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/ProfileUtils.java
package com.aliyun.auth.credentials.utils; import com.aliyun.core.logging.ClientLogger; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern; /** * Only for internal use within the package, do not use it arbitrarily, backward compatibility and sustainability cannot be guaranteed. */ public class ProfileUtils { private static final ClientLogger logger = new ClientLogger(ProfileUtils.class); private static final Pattern EMPTY_LINE = Pattern.compile("^[\t ]*$"); public static Map<String, Map<String, String>> parseFile(String profilePath) throws IOException { return parseFile(new FileReader(profilePath)); } static Map<String, Map<String, String>> parseFile(Reader input) throws IOException { ParserProgress progress = new ParserProgress(); BufferedReader profileReader = null; try { profileReader = new BufferedReader(input); String line; while ((line = profileReader.readLine()) != null) { parseLine(progress, line); } } finally { if (profileReader != null) { profileReader.close(); } } return progress.profiles; } private static void parseLine(ParserProgress progress, String line) { ++progress.currentLineNumber; if (!EMPTY_LINE.matcher(line).matches() && !(line.startsWith("#") || line.startsWith(";"))) { if (isSectionDefinitionLine(line)) { readSectionDefinitionLine(progress, line); } else if (line.startsWith("\t")) { readPropertyContinuationLine(progress, line); } else { readPropertyDefinitionLine(progress, line); } } } private static void readSectionDefinitionLine(ParserProgress progress, String line) { String lineWithoutComments = removeTrailingComments(line, "#", ";"); String lineWithoutWhitespace = lineWithoutComments.trim(); if (!lineWithoutWhitespace.endsWith("]")) { throw new IllegalArgumentException(String.format("Section definition must end with ']' on line %s: %s", progress.currentLineNumber, line)); } String lineWithoutBrackets = lineWithoutWhitespace.substring(1, lineWithoutWhitespace.length() - 1); String profileName = lineWithoutBrackets.trim(); if (profileName.isEmpty()) { progress.ignoringCurrentProfile = true; return; } progress.currentProfileBeingRead = profileName; progress.currentPropertyBeingRead = null; progress.ignoringCurrentProfile = false; if (!progress.profiles.containsKey(profileName)) { progress.profiles.put(profileName, new LinkedHashMap<String, String>()); } } private static void readPropertyDefinitionLine(ParserProgress progress, String line) { // Invalid profile, ignore its properties if (progress.ignoringCurrentProfile) { return; } if (progress.currentProfileBeingRead == null) { // throw new IllegalArgumentException(String.format("Expected a profile definition on line %s", progress.currentLineNumber)); // To be consistent with ini4j's behavior progress.currentProfileBeingRead = "?"; if (!progress.profiles.containsKey(progress.currentProfileBeingRead)) { progress.profiles.put(progress.currentProfileBeingRead, new LinkedHashMap<String, String>()); } } // Comments with property must have whitespace before them, or they will be considered part of the value String lineWithoutComments = removeTrailingComments(line, " #", " ;", "\t#", "\t;"); String lineWithoutWhitespace = lineWithoutComments.trim(); Property<String, String> property = parsePropertyDefinition(progress, lineWithoutWhitespace); if (progress.profiles.get(progress.currentProfileBeingRead).containsKey(property.key())) { logger.warning("Duplicate property '" + property.key() + "' detected on line " + progress.currentLineNumber + ". The later one in the file will be used."); } progress.currentPropertyBeingRead = property.key(); progress.profiles.get(progress.currentProfileBeingRead).put(property.key(), property.value()); } private static void readPropertyContinuationLine(ParserProgress progress, String line) { // Invalid profile, ignore its properties if (progress.ignoringCurrentProfile) { return; } if (progress.currentProfileBeingRead == null) { // throw new IllegalArgumentException(String.format("Expected a profile definition on line %s", progress.currentLineNumber)); // To be consistent with ini4j's behavior progress.currentProfileBeingRead = "?"; if (!progress.profiles.containsKey(progress.currentProfileBeingRead)) { progress.profiles.put(progress.currentProfileBeingRead, new LinkedHashMap<String, String>()); } } // Comments are not removed on property continuation lines. They're considered part of the value. line = line.trim(); Map<String, String> profileProperties = progress.profiles.get(progress.currentProfileBeingRead); String currentPropertyValue = profileProperties.get(progress.currentPropertyBeingRead); String newPropertyValue = currentPropertyValue + "\n" + line; profileProperties.put(progress.currentPropertyBeingRead, newPropertyValue); } private static Property<String, String> parsePropertyDefinition(ParserProgress progress, String line) { int firstEqualsLocation = line.indexOf('='); String propertyKey = null; String propertyValue = null; if (firstEqualsLocation == -1) { // throw new IllegalArgumentException(String.format("Expected an '=' sign defining a property on line %s", progress.currentLineNumber)); // To be consistent with ini4j's behavior propertyKey = line.trim(); } else { propertyKey = line.substring(0, firstEqualsLocation).trim(); propertyValue = line.substring(firstEqualsLocation + 1).trim(); } if (propertyKey.isEmpty()) { throw new IllegalArgumentException(String.format("Property did not have a name on line %s", progress.currentLineNumber)); } return new Property<String, String>(propertyKey, propertyValue); } private static boolean isSectionDefinitionLine(String line) { return line.trim().startsWith("["); } private static String removeTrailingComments(String line, String... commentPatterns) { int earliestMatchIndex = line.length(); for (String pattern : commentPatterns) { int index = line.indexOf(pattern); if (index >= 0 && index < earliestMatchIndex) { earliestMatchIndex = index; } } return line.substring(0, earliestMatchIndex); } private static final class ParserProgress { private int currentLineNumber; private String currentProfileBeingRead; private String currentPropertyBeingRead; private boolean ignoringCurrentProfile; private final Map<String, Map<String, String>> profiles; private ParserProgress() { this.currentLineNumber = 0; this.currentProfileBeingRead = null; this.currentPropertyBeingRead = null; this.ignoringCurrentProfile = false; this.profiles = new LinkedHashMap<String, Map<String, String>>(); } } private static final class Property<Key, Value> { private final Key key; private final Value value; private Property(Key key, Value value) { this.key = key; this.value = value; } public Key key() { return this.key; } public Value value() { return this.value; } } }