index
int64
repo_id
string
file_path
string
content
string
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/EndpointResolverBase.java
package com.aliyuncs.endpoint; import java.util.HashMap; import java.util.Map; import java.util.Set; public abstract class EndpointResolverBase implements EndpointResolver { Map<String, String> endpointsData; public EndpointResolverBase() { endpointsData = new HashMap<String, String>(); } public String fetchEndpointEntry(ResolveEndpointRequest request) { String key = makeEndpointKey(request); if (endpointsData.containsKey(key)) { return endpointsData.get(key); } else { return null; } } public void putEndpointEntry(String key, String endpoint) { endpointsData.put(key, endpoint); } public boolean isProductCodeValid(ResolveEndpointRequest request) { for (String key : endpointsData.keySet()) { if (key.startsWith(request.productCodeLower)) { return true; } } return false; } abstract public boolean isRegionIdValid(ResolveEndpointRequest request); abstract String makeEndpointKey(ResolveEndpointRequest request); public Set<String> getValidRegionIdsByProduct(String productCode) { // Only local config can tell return null; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/EndpointResolverRules.java
package com.aliyuncs.endpoint; import com.aliyuncs.utils.ParameterHelper; import com.aliyuncs.utils.StringUtils; import java.util.HashMap; public class EndpointResolverRules extends EndpointResolverBase { private Boolean validRegionId = false; private Boolean validProductId = false; private HashMap<String, String> productEndpointMap = null; private String productEndpointRegional = null; private String productNetwork = "public"; private String productSuffix = ""; @Override public String resolve(ResolveEndpointRequest request) { ParameterHelper.validateParameter(request.productNetwork, "productNetwork"); if (!StringUtils.isEmpty(productSuffix)) { ParameterHelper.validateParameter(request.productSuffix, "productSuffix"); } this.productEndpointMap = request.productEndpointMap; this.productEndpointRegional = request.productEndpointRegional; this.productNetwork = request.productNetwork; this.productSuffix = request.productSuffix; if (this.productEndpointMap == null || this.productEndpointRegional == null) { return null; } return getEndpoint(request.productCode, request.regionId); } @Override public String makeEndpointKey(ResolveEndpointRequest request) { return makeEndpointKey(request.productCode, request.regionId); } public String makeEndpointKey(String productCode, String regionId) { return productCode.toLowerCase() + "." + regionId.toLowerCase(); } private String getEndpoint(String productCode, String regionId) { if (this.productEndpointRegional != null && this.productEndpointMap != null) { if ("".equals(this.productNetwork) || this.productNetwork == null) { this.productNetwork = "public"; } if ("public".equals(this.productNetwork)) { if (this.productEndpointMap.containsKey(regionId)) { return this.productEndpointMap.get(regionId); } } String endpoint; if ("regional".equals(this.productEndpointRegional)) { endpoint = "<product_id><suffix><network>.<region_id>.aliyuncs.com"; endpoint = endpoint.replace("<region_id>", regionId.toLowerCase()); } else { endpoint = "<product_id><suffix><network>.aliyuncs.com"; } if (StringUtils.isEmpty(this.productSuffix)) { endpoint = endpoint.replace("<suffix>", ""); } else { endpoint = endpoint.replace("<suffix>", "-" + this.productSuffix.toLowerCase()); } if ("public".equals(this.productNetwork)) { endpoint = endpoint.replace("<network>", ""); } else { endpoint = endpoint.replace("<network>", "-" + this.productNetwork.toLowerCase()); } endpoint = endpoint.replace("<product_id>", productCode.toLowerCase()); this.validRegionId = true; this.validProductId = true; return endpoint; } return null; } @Override public boolean isProductCodeValid(ResolveEndpointRequest request) { return this.validProductId; } @Override public boolean isRegionIdValid(ResolveEndpointRequest request) { return this.validRegionId; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/InternalLocationServiceEndpointResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.endpoint; import com.aliyuncs.IAcsClient; @Deprecated public class InternalLocationServiceEndpointResolver extends LocationServiceEndpointResolver { private final static String INNER_LOCATION_SERVICE_ENDPOINT = "location-inner.aliyuncs.com"; private final static String INNER_LOCATION_SERVICE_API_VERSION = "2015-12-25"; public InternalLocationServiceEndpointResolver(IAcsClient client) { super(client); this.locationServiceEndpoint = INNER_LOCATION_SERVICE_ENDPOINT; this.locationServiceApiVersion = INNER_LOCATION_SERVICE_API_VERSION; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/LocalConfigGlobalEndpointResolver.java
package com.aliyuncs.endpoint; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.HashSet; import java.util.Map; import java.util.Set; public class LocalConfigGlobalEndpointResolver extends LocalConfigRegionalEndpointResolver { public LocalConfigGlobalEndpointResolver() { initLocalConfig(LocalConfigRegionalEndpointResolver.ENDPOINTS_JSON); } public LocalConfigGlobalEndpointResolver(String configJsonStr) { // For testability JsonObject obj = JsonParser.parseString(configJsonStr).getAsJsonObject(); initLocalConfig(obj); } protected void initLocalConfig(JsonObject obj) { initGlobalEndpointData(obj); initRegionIds(obj); initLocationCodeMapping(obj); } private void initGlobalEndpointData(JsonObject obj) { if (!obj.has("global_endpoints")) { return; } JsonObject globalEndpoints = obj.get("global_endpoints").getAsJsonObject(); Set<String> globalEndpointsKeySet = new HashSet<String>(); for (Map.Entry<String, JsonElement> entry : globalEndpoints.entrySet()) { globalEndpointsKeySet.add(entry.getKey()); } for (String locationServiceCode : globalEndpointsKeySet) { String endpoint = globalEndpoints.get(locationServiceCode).getAsString(); putEndpointEntry(makeEndpointKey(locationServiceCode), endpoint); } } @Override public String resolve(ResolveEndpointRequest request) { if (request.isOpenApiEndpoint() && isRegionIdValid(request)) { return fetchEndpointEntry(request); } else { return null; } } @Override public String makeEndpointKey(ResolveEndpointRequest request) { return makeEndpointKey(request.productCodeLower); } public String makeEndpointKey(String productCodeLower) { return getNormalizedProductCode(productCodeLower); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/LocalConfigRegionalEndpointResolver.java
package com.aliyuncs.endpoint; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.InputStream; import java.util.*; public class LocalConfigRegionalEndpointResolver extends EndpointResolverBase { protected static final String ENDPOINT_JSON = "endpoints.json"; private Set<String> validRegionIds = new HashSet<String>(); private Map<String, String> locationCodeMapping = new HashMap<String, String>(); private JsonObject regionalEndpointData; protected static final JsonObject ENDPOINTS_JSON; static { Scanner scanner = null; try { ClassLoader classLoader = LocalConfigRegionalEndpointResolver.class.getClassLoader(); InputStream is = classLoader.getResourceAsStream(ENDPOINT_JSON); scanner = new Scanner(is, "UTF-8"); scanner.useDelimiter("\0"); String jsonStr = scanner.hasNext() ? scanner.next() : ""; ENDPOINTS_JSON = JsonParser.parseString(jsonStr).getAsJsonObject(); } finally { if (null != scanner) { scanner.close(); } } } public LocalConfigRegionalEndpointResolver() { initLocalConfig(ENDPOINTS_JSON); } public LocalConfigRegionalEndpointResolver(String configJsonStr) { // For testability JsonObject obj = JsonParser.parseString(configJsonStr).getAsJsonObject(); initLocalConfig(obj); } private void initLocalConfig(JsonObject obj) { initRegionalEndpointData(obj); initRegionIds(obj); initLocationCodeMapping(obj); } private void initRegionalEndpointData(JsonObject obj) { if (!obj.has("regional_endpoints")) { return; } regionalEndpointData = obj.get("regional_endpoints").getAsJsonObject(); JsonObject regionalEndpoints = obj.get("regional_endpoints").getAsJsonObject(); Set<String> regionalEndpointsKeySet = new HashSet<String>(); for (Map.Entry<String, JsonElement> entry : regionalEndpoints.entrySet()) { regionalEndpointsKeySet.add(entry.getKey()); } for (String normalizedProductCode : regionalEndpointsKeySet) { JsonObject productData = regionalEndpoints.get(normalizedProductCode).getAsJsonObject(); Set<String> productDataKeySet = new HashSet<String>(); for (Map.Entry<String, JsonElement> entry : productData.entrySet()) { productDataKeySet.add(entry.getKey()); } for (String regionId : productDataKeySet) { String endpoint = productData.get(regionId).getAsString(); putEndpointEntry(makeEndpointKey(normalizedProductCode, regionId), endpoint); } } } protected void initRegionIds(JsonObject obj) { if (!obj.has("regions")) { return; } JsonArray regions = obj.get("regions").getAsJsonArray(); for (JsonElement regionData : regions) { validRegionIds.add(regionData.getAsString()); } } protected void initLocationCodeMapping(JsonObject obj) { if (!obj.has("location_code_mapping")) { return; } JsonObject mappingData = obj.get("location_code_mapping").getAsJsonObject(); Set<String> keySet = new HashSet<String>(); for (Map.Entry<String, JsonElement> entry : mappingData.entrySet()) { keySet.add(entry.getKey()); } for (String productCode : keySet) { String locationServiceCode = mappingData.get(productCode).getAsString(); locationCodeMapping.put(productCode, locationServiceCode); } } protected String getNormalizedProductCode(String productCode) { String productCodeLower = productCode.toLowerCase(); if (locationCodeMapping.containsKey(productCodeLower)) { return locationCodeMapping.get(productCodeLower); } return productCodeLower; } @Override public String resolve(ResolveEndpointRequest request) { if (request.isOpenApiEndpoint()) { return fetchEndpointEntry(request); } else { return null; } } @Override public String makeEndpointKey(ResolveEndpointRequest request) { return makeEndpointKey(request.productCodeLower, request.regionId); } public String makeEndpointKey(String productCodeLower, String regionId) { return getNormalizedProductCode(productCodeLower) + "." + regionId.toLowerCase(); } @Override public boolean isRegionIdValid(ResolveEndpointRequest request) { return validRegionIds.contains(request.regionId); } @Override public Set<String> getValidRegionIdsByProduct(String productCodeLower) { String code = getNormalizedProductCode(productCodeLower); if (regionalEndpointData != null && regionalEndpointData.has(code)) { JsonObject regionalEndpoints = regionalEndpointData.get(code).getAsJsonObject(); Set<String> validRegionIdsByProduct = new HashSet<String>(); for (Map.Entry<String, JsonElement> entry : regionalEndpoints.entrySet()) { validRegionIdsByProduct.add(entry.getKey()); } return validRegionIdsByProduct; } return null; } @Override public boolean isProductCodeValid(ResolveEndpointRequest request) { ResolveEndpointRequest request2 = new ResolveEndpointRequest( request.regionId, getNormalizedProductCode(request.productCode), null, null ); return super.isProductCodeValid(request2); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/LocationServiceEndpointResolver.java
package com.aliyuncs.endpoint; import com.aliyuncs.IAcsClient; import com.aliyuncs.endpoint.location.model.v20150612.DescribeEndpointsRequest; import com.aliyuncs.endpoint.location.model.v20150612.DescribeEndpointsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.ProtocolType; import java.util.HashSet; import java.util.Set; public class LocationServiceEndpointResolver extends EndpointResolverBase { private final static String DEFAULT_LOCATION_SERVICE_ENDPOINT = "location-readonly.aliyuncs.com"; private final static String DEFAULT_LOCATION_SERVICE_API_VERSION = "2015-06-12"; /** * For test use */ public int locationServiceCallCounter = 0; protected static String locationServiceEndpoint = DEFAULT_LOCATION_SERVICE_ENDPOINT; protected static String locationServiceApiVersion = DEFAULT_LOCATION_SERVICE_API_VERSION; private IAcsClient client; private Set<String> invalidProductCodes; private Set<String> validProductCodes; private Set<String> validRegionIds; public LocationServiceEndpointResolver(IAcsClient client) { this.client = client; invalidProductCodes = new HashSet<String>(); validProductCodes = new HashSet<String>(); validRegionIds = new HashSet<String>(); } public LocationServiceEndpointResolver(IAcsClient client, String locationServiceEndpoint, String locationServiceApiVersion) { this(client); this.locationServiceEndpoint = locationServiceEndpoint; this.locationServiceApiVersion = locationServiceApiVersion; } public static void setLocationServiceEndpoint(String endpoint) { locationServiceEndpoint = endpoint; } @Override public String resolve(ResolveEndpointRequest request) throws ClientException { if (request.locationServiceCode == null || request.locationServiceCode.length() == 0) { return null; } if (invalidProductCodes.contains(request.productCodeLower)) { return null; } String key = makeEndpointKey(request); if (endpointsData.containsKey(key)) { // The endpoint can be null when last fetch is failed return endpointsData.get(key); } return getEndpointFromLocationService(key, request); } synchronized private String getEndpointFromLocationService(String key, ResolveEndpointRequest request) throws ClientException { if (endpointsData.containsKey(key)) { return endpointsData.get(key); } callLocationService(key, request); locationServiceCallCounter += 1; if (endpointsData.containsKey(key)) { return endpointsData.get(key); } return null; } private void callLocationService(String key, ResolveEndpointRequest request) throws ClientException { DescribeEndpointsRequest describeEndpointsRequest = new DescribeEndpointsRequest(); describeEndpointsRequest.setSysProtocol(ProtocolType.HTTPS); describeEndpointsRequest.setAcceptFormat(FormatType.JSON); describeEndpointsRequest.setId(request.regionId); describeEndpointsRequest.setServiceCode(request.locationServiceCode); describeEndpointsRequest.setType(request.endpointType); describeEndpointsRequest.setSysEndpoint(locationServiceEndpoint); describeEndpointsRequest.setVersion(locationServiceApiVersion); DescribeEndpointsResponse response; try { response = client.getAcsResponse(describeEndpointsRequest); } catch (ClientException e) { if ("InvalidRegionId".equals(e.getErrCode()) && "The specified region does not exist.".equals(e.getErrMsg())) { // No such region putEndpointEntry(key, null); return; } else if ("Illegal Parameter".equals(e.getErrCode()) && "Please check the parameters".equals(e.getErrMsg())) { // No such product invalidProductCodes.add(request.productCodeLower); putEndpointEntry(key, null); return; } else { throw e; } } // As long as code gets here // the product code and the region id is valid // the endpoint can be still not found validProductCodes.add(request.productCodeLower); validRegionIds.add(request.regionId); boolean foundFlag = false; for (DescribeEndpointsResponse.Endpoint endpoint : response.getEndpoints()) { if (endpoint.getSerivceCode().equals(request.locationServiceCode) && endpoint.getType().equals(request.endpointType)) { foundFlag = true; putEndpointEntry(key, endpoint.getEndpoint()); break; } } if (!foundFlag) { putEndpointEntry(key, null); } } @Override public boolean isProductCodeValid(ResolveEndpointRequest request) { if (request.locationServiceCode != null) { return !invalidProductCodes.contains(request.productCodeLower); } return false; } @Override public boolean isRegionIdValid(ResolveEndpointRequest request) { return true; } @Override public String makeEndpointKey(ResolveEndpointRequest request) { return makeEndpointKey( request.productCode, request.locationServiceCode, request.regionId, request.endpointType ); } @Deprecated public String makeRegionIdKey(ResolveEndpointRequest request) { return request.locationServiceCode + "." + request.regionId + "." + request.endpointType; } public String makeEndpointKey(String productCode, String locationServiceCode, String regionId, String endpointType) { return productCode.toLowerCase() + "." + locationServiceCode + "." + regionId.toLowerCase() + "." + endpointType; } public static String getLocationServiceEndpoint() { return locationServiceEndpoint; } public static String getLocationServiceApiVersion() { return locationServiceApiVersion; } public static void setLocationServiceApiVersion(String locationServiceApiVersion) { LocationServiceEndpointResolver.locationServiceApiVersion = locationServiceApiVersion; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/ResolveEndpointRequest.java
package com.aliyuncs.endpoint; import com.aliyuncs.utils.StringUtils; import java.util.HashMap; public class ResolveEndpointRequest { public static final String ENDPOINT_TYPE_INNER = "innerAPI"; public static final String ENDPOINT_TYPE_OPEN = "openAPI"; public String productCode; public String regionId; public String endpointType; public String locationServiceCode; public String productCodeLower; public HashMap<String, String> productEndpointMap = null; public String productEndpointRegional = null; public String productNetwork = "public"; public String productSuffix = ""; public ResolveEndpointRequest(String regionId, String productCode, String locationServiceCode, String endpointType) { this.regionId = regionId; this.productCode = productCode; this.productCodeLower = productCode.toLowerCase(); if (StringUtils.isEmpty(endpointType)) { endpointType = ENDPOINT_TYPE_OPEN; } this.endpointType = endpointType; this.locationServiceCode = locationServiceCode; } public boolean isOpenApiEndpoint() { return ENDPOINT_TYPE_OPEN.equals(endpointType); } public void setProductEndpointMap(HashMap<String, String> productEndpointMap) { this.productEndpointMap = productEndpointMap; } public void setProductEndpointRegional(String productEndpointRegional) { this.productEndpointRegional = productEndpointRegional; } public void setProductNetwork(String productNetwork) { this.productNetwork = productNetwork; } public void setProductSuffix(String suffix) { this.productSuffix = suffix; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/UserCustomizedEndpointResolver.java
package com.aliyuncs.endpoint; import java.util.HashSet; import java.util.Set; public class UserCustomizedEndpointResolver extends EndpointResolverBase { private Set<String> validRegionIds; public UserCustomizedEndpointResolver() { validRegionIds = new HashSet<String>(); } public void putEndpointEntry(String regionId, String productCode, String endpoint) { putEndpointEntry(makeEndpointKey(productCode, regionId), endpoint); validRegionIds.add(regionId); } @Override public String resolve(ResolveEndpointRequest request) { return fetchEndpointEntry(request); } @Override public String makeEndpointKey(ResolveEndpointRequest request) { return makeEndpointKey(request.productCode, request.regionId); } public String makeEndpointKey(String productCode, String regionId) { return productCode.toLowerCase() + "." + regionId.toLowerCase(); } @Override public boolean isRegionIdValid(ResolveEndpointRequest request) { return validRegionIds.contains(request.regionId); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/UserVpcEndpointResolver.java
package com.aliyuncs.endpoint; import com.aliyuncs.exceptions.ClientException; public class UserVpcEndpointResolver extends EndpointResolverBase { @Override public boolean isRegionIdValid(ResolveEndpointRequest request) { return request.regionId != null; } @Override public boolean isProductCodeValid(ResolveEndpointRequest request) { return request.productCode != null; } @Override String makeEndpointKey(ResolveEndpointRequest request) { return null; } @Override public String resolve(ResolveEndpointRequest request) throws ClientException { String productCode = request.productCode.toLowerCase(); String regionId = request.regionId.toLowerCase(); return String.format("%s-vpc.%s.aliyuncs.com", productCode, regionId); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/location/model
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/location/model/v20150612/DescribeEndpointsRequest.java
package com.aliyuncs.endpoint.location.model.v20150612; import com.aliyuncs.RpcAcsRequest; public class DescribeEndpointsRequest extends RpcAcsRequest<DescribeEndpointsResponse> { private String id; private String serviceCode; private String type; public DescribeEndpointsRequest() { super("Location", "2015-06-12", "DescribeEndpoints"); } public String getId() { return this.id; } public void setId(String id) { this.id = id; putQueryParameter("Id", id); } public String getServiceCode() { return this.serviceCode; } public void setServiceCode(String serviceCode) { this.serviceCode = serviceCode; putQueryParameter("ServiceCode", serviceCode); } public String getType() { return this.type; } public void setType(String type) { this.type = type; putQueryParameter("Type", type); } @Override public Class<DescribeEndpointsResponse> getResponseClass() { return DescribeEndpointsResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/location/model
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/location/model/v20150612/DescribeEndpointsResponse.java
package com.aliyuncs.endpoint.location.model.v20150612; import com.aliyuncs.AcsResponse; import com.aliyuncs.endpoint.location.transform.v20150612.DescribeEndpointsResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; import java.util.List; public class DescribeEndpointsResponse extends AcsResponse { private String requestId; private Boolean success; private List<Endpoint> endpoints; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public List<Endpoint> getEndpoints() { return this.endpoints; } public void setEndpoints(List<Endpoint> endpoints) { this.endpoints = endpoints; } @Override public DescribeEndpointsResponse getInstance(UnmarshallerContext context) { return DescribeEndpointsResponseUnmarshaller.unmarshall(this, context); } public static class Endpoint { private String endpoint; private String id; private String namespace; private String serivceCode; private String type; private List<String> protocols; public String getEndpoint() { return this.endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getNamespace() { return this.namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getSerivceCode() { return this.serivceCode; } public void setSerivceCode(String serivceCode) { this.serivceCode = serivceCode; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public List<String> getProtocols() { return this.protocols; } public void setProtocols(List<String> protocols) { this.protocols = protocols; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/location/transform
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/endpoint/location/transform/v20150612/DescribeEndpointsResponseUnmarshaller.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.endpoint.location.transform.v20150612; import com.aliyuncs.endpoint.location.model.v20150612.DescribeEndpointsResponse; import com.aliyuncs.endpoint.location.model.v20150612.DescribeEndpointsResponse.Endpoint; import com.aliyuncs.transform.UnmarshallerContext; import java.util.ArrayList; import java.util.List; public class DescribeEndpointsResponseUnmarshaller { public static DescribeEndpointsResponse unmarshall(DescribeEndpointsResponse describeEndpointsResponse, UnmarshallerContext context) { describeEndpointsResponse.setRequestId(context.stringValue("DescribeEndpointsResponse.RequestId")); describeEndpointsResponse.setSuccess(context.booleanValue("DescribeEndpointsResponse.Success")); List<Endpoint> endpoints = new ArrayList<Endpoint>(); for (int i = 0; i < context.lengthValue("DescribeEndpointsResponse.Endpoints.Length"); i++) { Endpoint endpoint = new Endpoint(); endpoint.setEndpoint(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Endpoint")); endpoint.setId(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Id")); endpoint.setNamespace(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Namespace")); endpoint.setSerivceCode(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].SerivceCode")); endpoint.setType(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Type")); List<String> protocols = new ArrayList<String>(); for (int j = 0; j < context .lengthValue("DescribeEndpointsResponse.Endpoints[" + i + "].Protocols.Length"); j++) { protocols.add( context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Protocols[" + j + "]")); } endpoint.setProtocols(protocols); endpoints.add(endpoint); } describeEndpointsResponse.setEndpoints(endpoints); return describeEndpointsResponse; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/exceptions/ClientException.java
package com.aliyuncs.exceptions; import java.util.Map; public class ClientException extends Exception { private static final long serialVersionUID = 534996425110290578L; private String requestId; private String errCode; private String errMsg; private ErrorType errorType; private String errorDescription; private Map<String, Object> accessDeniedDetail; public ClientException(String errorCode, String errorMessage, String requestId, String errorDescription, Map<String, Object> accessDeniedDetail) { this(errorCode, errorMessage); this.setErrorDescription(errorDescription); this.setRequestId(requestId); this.setAccessDeniedDetail(accessDeniedDetail); } public ClientException(String errorCode, String errorMessage, String requestId, String errorDescription) { this(errorCode, errorMessage); this.setErrorDescription(errorDescription); this.setRequestId(requestId); } public ClientException(String errCode, String errMsg, String requestId) { this(errCode, errMsg); this.requestId = requestId; this.setErrorType(ErrorType.Client); } public ClientException(String errCode, String errMsg, Throwable cause) { super(errCode + " : " + errMsg, cause); this.errCode = errCode; this.errMsg = errMsg; this.setErrorType(ErrorType.Client); } public ClientException(String errCode, String errMsg) { super(errCode + " : " + errMsg); this.errCode = errCode; this.errMsg = errMsg; this.setErrorType(ErrorType.Client); } public ClientException(String message) { super(message); this.setErrorType(ErrorType.Client); } public ClientException(Throwable cause) { super(cause); this.setErrorType(ErrorType.Client); } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getErrCode() { return errCode; } public void setErrCode(String errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public ErrorType getErrorType() { return errorType; } public void setErrorType(ErrorType errorType) { this.errorType = errorType; } public String getErrorDescription() { return errorDescription; } public void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } public Map<String, Object> getAccessDeniedDetail() { return accessDeniedDetail; } public void setAccessDeniedDetail(Map<String, Object> accessDeniedDetail) { this.accessDeniedDetail = accessDeniedDetail; } @Override public String getMessage() { return super.getMessage() + (null == getRequestId() ? "" : "\r\nRequestId : " + getRequestId()) + (null == getErrorDescription() ? "" : "\r\nDescription : " + getErrorDescription()); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/exceptions/ErrorCodeConstant.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public class ErrorCodeConstant { public static final String SDK_ENDPOINT_RESOLVING_ERROR = "SDK.EndpointResolvingError"; public static final String SDK_ENDPOINT_TESTABILITY = "SDK.EndpointTestability"; public static final String SDK_INVALID_SERVER_RESPONSE = "SDK.InvalidServerResponse"; }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/exceptions/ErrorMessageConstant.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public class ErrorMessageConstant { public static final String INVALID_REGION_ID = "No such region '%s'. Please check your region ID."; public static final String SERVER_RESPONSE_HTTP_BODY_EMPTY = "Failed to parse the response. The request was succeeded, but the server returned an empty HTTP body."; }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/exceptions/ErrorType.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public enum ErrorType { // 客户端异常 Client, // 服务端异常 Server, // 限流 Throttling, // default Unknown, }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/exceptions/ServerException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public class ServerException extends ClientException { private static final long serialVersionUID = -7345371390798165336L; public ServerException(String errorCode, String errorMessage) { super(errorCode, errorMessage); this.setErrorType(ErrorType.Server); } public ServerException(String errCode, String errMsg, String requestId) { this(errCode, errMsg); this.setRequestId(requestId); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/exceptions/ThrottlingException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public class ThrottlingException extends ClientException { private static final long serialVersionUID = 7345371390798165333L; public ThrottlingException(String errorCode, String errorMessage) { super(errorCode, errorMessage); this.setErrorType(ErrorType.Throttling); } public ThrottlingException(String errCode, String errMsg, String requestId) { this(errCode, errMsg); this.setRequestId(requestId); } public ThrottlingException(String errCode, String errMsg, Throwable exception) { super(errCode, errMsg, exception); this.setErrorType(ErrorType.Throttling); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/CallBack.java
package com.aliyuncs.http; /** * 用于异步调用时的回调逻辑 */ public interface CallBack { /** * 请求失败 * * @param request 封装后的请求对象,包含部分http相关信息 * @param e 导致失败的异常 */ void onFailure(HttpRequest request, Exception e); /** * 收到应答 * * @param request 封装后的请求对象,包含部分http相关信息 * @param response 封装后的应答对象,包含部分http相关信息,可以调用.getBody()获取content */ void onResponse(HttpRequest request, HttpResponse response); }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/CompositeX509TrustManager.java
package com.aliyuncs.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 CompositeX509TrustManager implements X509TrustManager { private final List<X509TrustManager> trustManagers; private boolean ignoreSSLCert = false; public boolean isIgnoreSSLCert() { return ignoreSSLCert; } public void setIgnoreSSLCert(boolean ignoreSSLCert) { this.ignoreSSLCert = ignoreSSLCert; } public CompositeX509TrustManager(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 (ignoreSSLCert) { 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-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/FormatType.java
package com.aliyuncs.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") */ 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 FormatType.RAW; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpClientConfig.java
package com.aliyuncs.http; import org.apache.http.client.CredentialsProvider; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; public class HttpClientConfig { public static final long DEFAULT_CONNECTION_TIMEOUT = 5000; public static final long DEFAULT_READ_TIMEOUT = 10000; public static final String IGNORE_SSL_ENV = "ALIBABACLOUD_JAVA_CORE_INGNORE_SSL"; /** * client type */ private HttpClientType clientType = null; private String customClientClassName = null; /** * connectionPool **/ private int maxIdleConnections = 128; private long maxIdleTimeMillis = 60 * 1000L; private long keepAliveDurationMillis = 5000L; /** * timeout **/ private long connectionTimeoutMillis = DEFAULT_CONNECTION_TIMEOUT; private long readTimeoutMillis = DEFAULT_READ_TIMEOUT; private long writeTimeoutMillis = 60 * 1000L; /** * global protocolType **/ private ProtocolType protocolType = ProtocolType.HTTP; /** * https **/ private boolean ignoreSSLCerts = false; private SSLSocketFactory sslSocketFactory = null; private KeyManager[] keyManagers = null; private X509TrustManager[] x509TrustManagers = null; private SecureRandom secureRandom = null; private HostnameVerifier hostnameVerifier = null; @Deprecated private String certPath = null; /** * dispatcher **/ private int maxRequests = 128; private int maxRequestsPerHost = 128; private Runnable idleCallback = null; private ExecutorService executorService = null; /** * proxy configurations */ private String httpProxy = null; private String httpsProxy = null; private String noProxy = null; private CredentialsProvider credentialsProvider; /** * extra params */ private Map<String, Object> extParams = new HashMap<String, Object>(); private boolean compatibleMode = false; public static HttpClientConfig getDefault() { HttpClientConfig config = new HttpClientConfig(); config.setClientType(HttpClientType.ApacheHttpClient); return config; } public HttpClientType getClientType() { return clientType; } public void setClientType(HttpClientType clientType) { this.clientType = clientType; } @Deprecated public String getCertPath() { return certPath; } /** * use HttpClientConfig.setX509TrustManagers() and HttpClientConfig.setKeyManagers() instead */ @Deprecated public void setCertPath(String certPath) { this.certPath = certPath; } public int getMaxIdleConnections() { return maxIdleConnections; } public void setMaxIdleConnections(int maxIdleConnections) { this.maxIdleConnections = maxIdleConnections; } public long getMaxIdleTimeMillis() { return maxIdleTimeMillis; } public void setMaxIdleTimeMillis(long maxIdleTimeMillis) { this.maxIdleTimeMillis = maxIdleTimeMillis; } public long getKeepAliveDurationMillis() { return keepAliveDurationMillis; } public void setKeepAliveDurationMillis(long keepAliveDurationMillis) { this.keepAliveDurationMillis = keepAliveDurationMillis; } public long getConnectionTimeoutMillis() { return connectionTimeoutMillis; } public void setConnectionTimeoutMillis(long connectionTimeoutMillis) { this.connectionTimeoutMillis = connectionTimeoutMillis; } public long getReadTimeoutMillis() { return readTimeoutMillis; } public void setReadTimeoutMillis(long readTimeoutMillis) { this.readTimeoutMillis = readTimeoutMillis; } public long getWriteTimeoutMillis() { return writeTimeoutMillis; } public void setWriteTimeoutMillis(long writeTimeoutMillis) { this.writeTimeoutMillis = writeTimeoutMillis; } public SSLSocketFactory getSslSocketFactory() { return this.sslSocketFactory; } public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; } public KeyManager[] getKeyManagers() { return keyManagers; } public void setKeyManagers(KeyManager[] keyManagers) { this.keyManagers = keyManagers; } public X509TrustManager[] getX509TrustManagers() { return x509TrustManagers; } public void setX509TrustManagers(X509TrustManager[] x509TrustManagers) { this.x509TrustManagers = x509TrustManagers; } public SecureRandom getSecureRandom() { return secureRandom; } public void setSecureRandom(SecureRandom secureRandom) { this.secureRandom = secureRandom; } public HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; } public int getMaxRequests() { return maxRequests; } public void setMaxRequests(int maxRequests) { this.maxRequests = maxRequests; } public int getMaxRequestsPerHost() { return maxRequestsPerHost; } public void setMaxRequestsPerHost(int maxRequestsPerHost) { this.maxRequestsPerHost = maxRequestsPerHost; } public Runnable getIdleCallback() { return idleCallback; } public void setIdleCallback(Runnable idleCallback) { this.idleCallback = idleCallback; } public ExecutorService getExecutorService() { return executorService; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public Map<String, Object> getExtParams() { return extParams; } public void setExtParams(Map<String, Object> extParams) { this.extParams = extParams; } public String getCustomClientClassName() { return customClientClassName; } public void setCustomClientClassName(String customClientClassName) { this.customClientClassName = customClientClassName; } public Object getExtParam(Object key) { return extParams.get(key); } public Object setExtParam(String key, Object value) { return extParams.put(key, value); } public boolean containsExtParam(Object key) { return extParams.containsKey(key); } public boolean isIgnoreSSLCerts() { return "YES".equals(System.getProperty(IGNORE_SSL_ENV)) || "YES".equals(System.getenv(IGNORE_SSL_ENV)) || this.ignoreSSLCerts; } public void setIgnoreSSLCerts(boolean ignoreSSLCerts) { this.ignoreSSLCerts = ignoreSSLCerts; } public boolean isCompatibleMode() { return compatibleMode; } public void setCompatibleMode(boolean compatibleMode) { this.compatibleMode = compatibleMode; } public ProtocolType getProtocolType() { return protocolType; } public void setProtocolType(ProtocolType protocolType) { this.protocolType = protocolType; } public String getHttpProxy() { return httpProxy; } public void setHttpProxy(String httpProxy) { this.httpProxy = httpProxy; } public String getHttpsProxy() { return httpsProxy; } public void setHttpsProxy(String httpsProxy) { this.httpsProxy = httpsProxy; } public String getNoProxy() { return noProxy; } public void setNoProxy(String noProxy) { this.noProxy = noProxy; } public CredentialsProvider getCredentialsProvider() { return credentialsProvider; } public void setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpClientFactory.java
package com.aliyuncs.http; import com.aliyuncs.http.clients.ApacheHttpClient; import com.aliyuncs.http.clients.CompatibleUrlConnClient; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.utils.StringUtils; import java.lang.reflect.Constructor; public class HttpClientFactory { public static String HTTP_CLIENT_IMPL_KEY = "aliyuncs.sdk.httpclient"; public static String COMPATIBLE_HTTP_CLIENT_CLASS_NAME = CompatibleUrlConnClient.class.getName(); public static IHttpClient buildClient(IClientProfile profile) { try { HttpClientConfig clientConfig = profile.getHttpClientConfig(); if (clientConfig == null) { clientConfig = HttpClientConfig.getDefault(); profile.setHttpClientConfig(clientConfig); } String customClientClassName; if (clientConfig.isCompatibleMode()) { customClientClassName = COMPATIBLE_HTTP_CLIENT_CLASS_NAME; } else if (clientConfig.getClientType() == HttpClientType.Custom && !StringUtils.isEmpty(clientConfig.getCustomClientClassName())) { customClientClassName = clientConfig.getCustomClientClassName(); } else { customClientClassName = System.getProperty(HTTP_CLIENT_IMPL_KEY); } if (StringUtils.isEmpty(customClientClassName)) { customClientClassName = clientConfig.getClientType().getImplClass().getName(); } Class httpClientClass = Class.forName(customClientClassName); if (!IHttpClient.class.isAssignableFrom(httpClientClass)) { throw new IllegalStateException(String.format("%s is not assignable from com.aliyuncs.http.IHttpClient", customClientClassName)); } if (ApacheHttpClient.class.equals(httpClientClass)) { IHttpClient client = ApacheHttpClient.getInstance(); client.init(clientConfig); return client; } Constructor<? extends IHttpClient> constructor = httpClientClass.getConstructor(HttpClientConfig.class); return constructor.newInstance(clientConfig); } catch (Exception e) { // keep compatibility throw new IllegalStateException("HttpClientFactory buildClient failed", e); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpClientType.java
package com.aliyuncs.http; import com.aliyuncs.http.clients.CompatibleUrlConnClient; public enum HttpClientType { /** * define Compatiblen,HttpClient,okHttp,Custom */ Compatible(CompatibleUrlConnClient.class), ApacheHttpClient(com.aliyuncs.http.clients.ApacheHttpClient.class), OkHttp(null), Custom(null),; private Class<? extends IHttpClient> implClass; HttpClientType(Class<? extends IHttpClient> implClass) { this.implClass = implClass; } public Class<? extends IHttpClient> getImplClass() { return implClass; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpMessage.java
package com.aliyuncs.http; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.policy.retry.RetryPolicy; import com.aliyuncs.utils.ParameterHelper; import javax.net.ssl.KeyManager; import javax.net.ssl.X509TrustManager; import java.io.UnsupportedEncodingException; 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; protected boolean ignoreSSLCerts = false; private KeyManager[] keyManagers = null; private X509TrustManager[] x509TrustManagers = null; private RetryPolicy retryPolicy = null; public KeyManager[] getKeyManagers() { return keyManagers; } public void setKeyManagers(KeyManager[] keyManagers) { this.keyManagers = keyManagers; } public X509TrustManager[] getX509TrustManagers() { return x509TrustManagers; } public void setX509TrustManagers(X509TrustManager[] x509TrustManagers) { this.x509TrustManagers = x509TrustManagers; } public boolean isIgnoreSSLCerts() { return ignoreSSLCerts; } public void setIgnoreSSLCerts(boolean ignoreSSLCerts) { this.ignoreSSLCerts = ignoreSSLCerts; } public HttpMessage(String strUrl) { this.url = strUrl; } public HttpMessage() { } /** * @Deprecated : Use getSysUrl instead of this */ @Deprecated public String getUrl() { return url; } /** * @Deprecated : Use setSysUrl instead of this */ @Deprecated protected void setUrl(String url) { this.url = url; } /** * @Deprecated : Use getSysMethod instead of this */ @Deprecated public MethodType getMethod() { return method; } /** * @Deprecated : Use setSysMethod instead of this */ @Deprecated public void setMethod(MethodType method) { this.method = method; } public FormatType getHttpContentType() { return httpContentType; } public void setHttpContentType(FormatType httpContentType) { this.httpContentType = httpContentType; if (null != this.httpContent || null != httpContentType) { this.headers.put(CONTENT_TYPE, getContentTypeValue(this.httpContentType, this.encoding)); } else { this.headers.remove(CONTENT_TYPE); } } 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 = ParameterHelper.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)); } } /** * @Deprecated : Use getSysEncoding instead of this */ @Deprecated public String getEncoding() { return encoding; } /** * @Deprecated : Use setSysEncoding instead of this */ @Deprecated public void setEncoding(String encoding) { this.encoding = encoding; } public void putHeaderParameter(String name, String value) { if (null != name && null != value) { this.headers.put(name, value); } } public String getHeaderValue(String name) { return this.headers.get(name); } /** * @Deprecated : Use getSysConnectTimeout instead of this */ @Deprecated public Integer getConnectTimeout() { return connectTimeout; } /** * @Deprecated : Use setSysConnectTimeout instead of this */ @Deprecated public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } /** * @Deprecated : Use getSysReadTimeout instead of this */ @Deprecated public Integer getReadTimeout() { return readTimeout; } /** * @Deprecated : Use setSysReadTimeout instead of this */ @Deprecated public void setReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; } /** * @Deprecated : Use getSysHeaders instead of this */ @Deprecated public Map<String, String> getHeaders() { return Collections.unmodifiableMap(headers); } public String getContentTypeValue(FormatType contentType, String encoding) { if (null != contentType && null != encoding) { return FormatType.mapFormatToAccept(contentType) + ";charset=" + encoding.toLowerCase(); } else if (null != contentType) { return FormatType.mapFormatToAccept(contentType); } return null; } public String getHttpContentString() throws ClientException { 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 ClientException("SDK.UnsupportedEncoding", "Can not parse response due to unsupported encoding."); } } return stringContent; } public String getSysUrl() { return url; } protected void setSysUrl(String url) { this.url = url; } public MethodType getSysMethod() { return method; } public void setSysMethod(MethodType method) { this.method = method; } 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 Map<String, String> getSysHeaders() { return Collections.unmodifiableMap(headers); } public String getSysStrToSign(){ return null; } public RetryPolicy getSysRetryPolicy() { return this.retryPolicy; } public void setSysRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpRequest.java
package com.aliyuncs.http; import java.util.Map; public class HttpRequest extends HttpMessage { public HttpRequest(String strUrl) { super(strUrl); } public HttpRequest(String strUrl, Map<String, String> tmpHeaders) { super(strUrl); if (null != tmpHeaders) { this.headers = tmpHeaders; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpResponse.java
package com.aliyuncs.http; public class HttpResponse extends HttpMessage { private int status; private String reasonPhrase; public HttpResponse(String strUrl) { super(strUrl); } public HttpResponse() { } @Override public void setHttpContent(byte[] content, String encoding, FormatType format) { this.httpContent = content; this.encoding = encoding; this.httpContentType = format; } @Override public String getHeaderValue(String name) { String value = this.headers.get(name); if (null == value) { value = this.headers.get(name.toLowerCase()); } return value; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public boolean isSuccess() { return 200 <= this.status && this.status < 300; } public String getReasonPhrase() { return reasonPhrase; } public void setReasonPhrase(String reasonPhrase) { this.reasonPhrase = reasonPhrase; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/HttpUtil.java
package com.aliyuncs.http; import java.io.IOException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.SocketAddress; import java.net.URL; import java.util.Map; import java.util.Map.Entry; import javax.xml.bind.DatatypeConverter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHost; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.utils.StringUtils; public class HttpUtil { private final static Log log = LogFactory.getLog(HttpUtil.class); private static Boolean isHttpDebug; private static Boolean isHttpContentDebug; static { Boolean flag = "sdk".equalsIgnoreCase(System.getenv("DEBUG")); isHttpDebug = flag; isHttpContentDebug = flag; } public static Boolean getIsHttpDebug() { return isHttpDebug; } public static void setIsHttpDebug(Boolean isHttpDebug) { HttpUtil.isHttpDebug = isHttpDebug; } public static Boolean getIsHttpContentDebug() { return isHttpContentDebug; } public static void setIsHttpContentDebug(Boolean isHttpContentDebug) { HttpUtil.isHttpContentDebug = isHttpContentDebug; } public static String debugHttpRequest(HttpRequest request) { if (isHttpDebug) { StringBuilder debugString = new StringBuilder(); String sysUrl = request.getSysUrl(); URL url; try { url = new URL(sysUrl); debugString.append("> " + request.getSysMethod() + " " + url.getProtocol().toUpperCase() + "/1.1\n> "); debugString.append("Host : " + url.getHost() + "\n> "); } catch (MalformedURLException e) { debugString.append("> " + request.getSysMethod() + " " + sysUrl + "\n> "); debugString.append("Host : " + sysUrl + "\n> "); } Map<String, String> requestHeaders = request.getSysHeaders(); for (Entry<String, String> entry : requestHeaders.entrySet()) { debugString.append(entry.getKey() + " : " + entry.getValue() + "\n> "); } debugString.append("Request URL : " + sysUrl + "\n> "); debugString.append("Request string to sign: [" + request.getSysStrToSign() + "]\n> "); debugString.append("Request isIgnoreSSLCerts : " + request.isIgnoreSSLCerts() + "\n> "); debugString.append("Request connect timeout : " + request.getSysConnectTimeout() + "\n> "); debugString.append("Request read timeout : " + request.getSysReadTimeout() + "\n> "); debugString.append("Encoding : " + request.getSysEncoding() + "\n> "); if (isHttpContentDebug) { try { debugString.append("\n" + request.getHttpContentString()); } catch (ClientException e) { debugString.append("\n" + "Can not parse request content due to unsupported encoding : " + request .getSysEncoding()); } } log.info("\n" + debugString); return debugString.toString(); } else { return null; } } public static String debugHttpResponse(HttpResponse response) { if (isHttpDebug) { StringBuilder debugString = new StringBuilder(); String protocol = "HTTP/1.1"; debugString.append("< " + protocol + " " + response.getStatus() + "\n< "); Map<String, String> responseHeaders = response.getSysHeaders(); for (Entry<String, String> entry : responseHeaders.entrySet()) { debugString.append(entry.getKey() + " : " + entry.getValue() + "\n< "); } if (isHttpContentDebug) { try { debugString.append("\n" + response.getHttpContentString()); } catch (ClientException e) { debugString.append("\n" + "Can not parse response due to unsupported encoding : " + response .getSysEncoding()); } } log.info("\n" + debugString); return debugString.toString(); } else { return null; } } public static Proxy getJDKProxy(String clientProxy, String envProxy, HttpRequest request) throws ClientException { Proxy proxy = Proxy.NO_PROXY; try { String proxyStr = (!StringUtils.isEmpty(clientProxy) ? clientProxy : envProxy); if (StringUtils.isEmpty(proxyStr)) { return proxy; } URL proxyUrl = new URL(proxyStr); String userInfo = proxyUrl.getUserInfo(); if (userInfo != null) { byte[] bytes = userInfo.getBytes("UTF-8"); String auth = DatatypeConverter.printBase64Binary(bytes); request.putHeaderParameter("Proxy-Authorization", "Basic " + auth); } String hostname = proxyUrl.getHost(); int port = proxyUrl.getPort(); if (port == -1) { port = proxyUrl.getDefaultPort(); } SocketAddress addr = new InetSocketAddress(hostname, port); proxy = new Proxy(Proxy.Type.HTTP, addr); } catch (IOException e) { throw new ClientException("SDK.InvalidProxy", "proxy url is invalid"); } return proxy; } public static HttpHost getApacheProxy(String clientProxy, String envProxy, HttpRequest request) throws ClientException { try { String proxyStr = (!StringUtils.isEmpty(clientProxy) ? clientProxy : envProxy); if (StringUtils.isEmpty(proxyStr)) { return null; } URL proxyUrl = new URL(proxyStr); String userInfo = proxyUrl.getUserInfo(); if (userInfo != null) { byte[] bytes = userInfo.getBytes("UTF-8"); String auth = DatatypeConverter.printBase64Binary(bytes); request.putHeaderParameter("Proxy-Authorization", "Basic " + auth); } return new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol()); } catch (IOException e) { throw new ClientException("SDK.InvalidProxy", "proxy url is invalid"); } } public static boolean needProxy(String targetHost, String clientNoProxyList, String envNoProxyList) { String noProxyList = (!StringUtils.isEmpty(clientNoProxyList) ? clientNoProxyList : envNoProxyList); if (StringUtils.isEmpty(noProxyList)) { return true; } String[] noProxyArr = noProxyList.split(","); for (String host : noProxyArr) { if (host.equals(targetHost)) { return false; } } return true; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/IHttpClient.java
package com.aliyuncs.http; import com.aliyuncs.exceptions.ClientException; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.Future; public abstract class IHttpClient implements Closeable { protected HttpClientConfig clientConfig; public IHttpClient(HttpClientConfig clientConfig) throws ClientException { if (clientConfig == null) { clientConfig = HttpClientConfig.getDefault(); } this.clientConfig = clientConfig; init(clientConfig); } public IHttpClient() { // do nothing } protected abstract void init(HttpClientConfig clientConfig) throws ClientException; public abstract HttpResponse syncInvoke(HttpRequest apiRequest) throws IOException, ClientException; public abstract Future<HttpResponse> asyncInvoke(final HttpRequest apiRequest, final CallBack callback) throws IOException; @Deprecated public abstract void ignoreSSLCertificate(); @Deprecated public abstract void restoreSSLCertificate(); public abstract boolean isSingleton(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/MethodType.java
package com.aliyuncs.http; public enum MethodType { /** * GET * PUT * POST * PATCH * DELETE * HEAD * OPTIONS */ GET(false), PUT(true), POST(true), PATCH(true), DELETE(true), HEAD(false), OPTIONS(false); private boolean hasContent; MethodType(boolean hasContent) { this.hasContent = hasContent; } public boolean hasContent() { return hasContent; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/ProtocolType.java
package com.aliyuncs.http; public enum ProtocolType { /** * Define HTTP、HTTPS */ HTTP("http"), HTTPS("https"); private final String protocol; ProtocolType(String protocol) { this.protocol = protocol; } @Override public String toString() { return protocol; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/UserAgentConfig.java
package com.aliyuncs.http; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import com.aliyuncs.utils.StringUtils; public class UserAgentConfig { static { Properties sysProps = System.getProperties(); String coreVersion = ""; Properties props = new Properties(); try { props.load(UserAgentConfig.class.getClassLoader().getResourceAsStream("project.properties")); coreVersion = props.getProperty("sdk.project.version"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } DEFAULT_MESSAGE = String.format("AlibabaCloud (%s; %s) Java/%s %s/%s", sysProps.getProperty("os.name"), sysProps .getProperty("os.arch"), sysProps.getProperty("java.runtime.version"), "Core", coreVersion); } private static String DEFAULT_MESSAGE; private List<String> excludeList = new ArrayList<String>(); private final Map<String, String> userAgents = new LinkedHashMap<String, String>(); public UserAgentConfig() { excludeList.add("java"); excludeList.add("Core"); } public static String getDefaultMessage() { return DEFAULT_MESSAGE; } public void append(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return; } if (excludeList.contains(key.toLowerCase())) { return; } this.userAgents.put(key, value); } public Map<String, String> getSysUserAgentsMap() { return Collections.unmodifiableMap(this.userAgents); } public static String resolve(UserAgentConfig requestConfig, UserAgentConfig clientConfig) { Map<String, String> finalMap = new LinkedHashMap<String, String>(); if (clientConfig != null && clientConfig.getSysUserAgentsMap().size() > 0) { finalMap.putAll(clientConfig.getSysUserAgentsMap()); } if (requestConfig != null && requestConfig.getSysUserAgentsMap().size() > 0) { finalMap.putAll(requestConfig.getSysUserAgentsMap()); } StringBuilder agents = new StringBuilder(DEFAULT_MESSAGE); for (Map.Entry<String, String> entry : finalMap.entrySet()) { agents.append(" "); agents.append(entry.getKey()); agents.append("/"); agents.append(entry.getValue()); } return agents.toString(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/X509TrustAll.java
package com.aliyuncs.http; import com.aliyuncs.IAcsClient; @Deprecated public final class X509TrustAll { public static boolean ignoreSSLCerts = false; @Deprecated public static void restoreSSLCertificate() { ignoreSSLCerts = false; } @Deprecated public static void ignoreSSLCertificate() { ignoreSSLCerts = true; } @Deprecated public static void restoreSSLCertificate(IAcsClient client) { ignoreSSLCerts = false; } @Deprecated public static void ignoreSSLCertificate(IAcsClient client) { ignoreSSLCerts = true; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/clients/ApacheHttpClient.java
package com.aliyuncs.http.clients; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.*; import com.aliyuncs.utils.EnvironmentUtils; import com.aliyuncs.utils.IOUtils; import com.aliyuncs.utils.StringUtils; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import javax.net.ssl.*; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class ApacheHttpClient extends IHttpClient { protected static final String CONTENT_TYPE = "Content-Type"; protected static final String ACCEPT_ENCODING = "Accept-Encoding"; private static final String EXT_PARAM_KEY_BUILDER = "apache.httpclient.builder"; private static final int DEFAULT_THREAD_KEEP_ALIVE_TIME = 60; private ExecutorService executorService; private CloseableHttpClient httpClient; private PoolingHttpClientConnectionManager connectionManager; private AtomicBoolean initialized = new AtomicBoolean(false); private CountDownLatch latch = new CountDownLatch(1); private static volatile ApacheHttpClient client; /** * use ApacheHttpClient.getInstance() instead */ @Deprecated public static ApacheHttpClient getInstance(HttpClientConfig config) throws ClientException { throw new IllegalStateException("use ApacheHttpClient.getInstance() instead"); } public static ApacheHttpClient getInstance() { if (client == null) { synchronized (ApacheHttpClient.class) { if (client == null) { client = new ApacheHttpClient(); } } } return client; } private ApacheHttpClient() { super(); } private SSLConnectionSocketFactory createSSLConnectionSocketFactory() throws ClientException { try { if (null == clientConfig.getSslSocketFactory()) { List<TrustManager> trustManagerList = new ArrayList<TrustManager>(); X509TrustManager[] trustManagers = clientConfig.getX509TrustManagers(); if (null != trustManagers) { trustManagerList.addAll(Arrays.asList(trustManagers)); } // get trustManager using default certification from jdk TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); trustManagerList.addAll(Arrays.asList(tmf.getTrustManagers())); 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(clientConfig.isIgnoreSSLCerts()); KeyManager[] keyManagers = null; if (clientConfig.getKeyManagers() != null) { keyManagers = clientConfig.getKeyManagers(); } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, new TrustManager[]{compositeX509TrustManager}, clientConfig.getSecureRandom()); HostnameVerifier hostnameVerifier = null; if (clientConfig.isIgnoreSSLCerts()) { hostnameVerifier = new NoopHostnameVerifier(); } else if (clientConfig.getHostnameVerifier() != null) { hostnameVerifier = clientConfig.getHostnameVerifier(); } else { hostnameVerifier = new DefaultHostnameVerifier(); } return new SSLConnectionSocketFactory(sslContext, hostnameVerifier); } else { HostnameVerifier hostnameVerifier; if (null == clientConfig.getHostnameVerifier()) { hostnameVerifier = new NoopHostnameVerifier(); } else { hostnameVerifier = clientConfig.getHostnameVerifier(); } return new SSLConnectionSocketFactory(clientConfig.getSslSocketFactory(), hostnameVerifier); } } catch (Exception e) { throw new ClientException("SDK.InitFailed", "Init https with SSL socket failed", e); } } private void initConnectionManager() throws ClientException { // http RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder = RegistryBuilder.create(); socketFactoryRegistryBuilder.register("http", new PlainConnectionSocketFactory()); // https SSLConnectionSocketFactory sslConnectionSocketFactory = createSSLConnectionSocketFactory(); socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory); // connPool connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistryBuilder.build()); connectionManager.setMaxTotal(clientConfig.getMaxRequests()); connectionManager.setDefaultMaxPerRoute(clientConfig.getMaxRequestsPerHost()); } private HttpClientBuilder initHttpClientBuilder() { HttpClientBuilder builder; if (clientConfig.containsExtParam(EXT_PARAM_KEY_BUILDER)) { builder = (HttpClientBuilder) clientConfig.getExtParam(EXT_PARAM_KEY_BUILDER); } else { builder = HttpClientBuilder.create(); } return builder; } private void initExecutor() { // async if (clientConfig.getExecutorService() == null) { executorService = new ThreadPoolExecutor(0, clientConfig.getMaxRequests(), DEFAULT_THREAD_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new DefaultAsyncThreadFactory()); } else { executorService = clientConfig.getExecutorService(); } } @Override protected void init(final HttpClientConfig config0) throws ClientException { if (!initialized.compareAndSet(false, true)) { try { latch.await(); } catch (InterruptedException e) { throw new ClientException("SDK.InitFailed", "Init apacheHttpClient failed", e); } return; } final HttpClientConfig config = (config0 != null ? config0 : HttpClientConfig.getDefault()); this.clientConfig = config; HttpClientBuilder builder = initHttpClientBuilder(); CredentialsProvider credentialsProvider = this.clientConfig.getCredentialsProvider(); if (null != credentialsProvider) { builder.setDefaultCredentialsProvider(credentialsProvider); } // default request config RequestConfig defaultConfig = RequestConfig.custom().setConnectTimeout((int) config .getConnectionTimeoutMillis()).setSocketTimeout((int) config.getReadTimeoutMillis()) .setConnectionRequestTimeout((int) config.getWriteTimeoutMillis()).build(); builder.setDefaultRequestConfig(defaultConfig); initConnectionManager(); builder.setConnectionManager(connectionManager); ApacheIdleConnectionCleaner.registerConnectionManager(connectionManager, config.getMaxIdleTimeMillis()); initExecutor(); builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); // keepAlive if (config.getKeepAliveDurationMillis() > 0) { builder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(org.apache.http.HttpResponse response, HttpContext context) { long duration = DefaultConnectionKeepAliveStrategy.INSTANCE.getKeepAliveDuration(response, context); if (duration > 0 && duration < config.getKeepAliveDurationMillis()) { return duration; } else { return config.getKeepAliveDurationMillis(); } } }); } httpClient = builder.build(); latch.countDown(); } private HttpUriRequest parseToHttpRequest(HttpRequest apiReq) throws IOException, ClientException { RequestBuilder builder = RequestBuilder.create(apiReq.getSysMethod().name()); builder.setUri(apiReq.getSysUrl()); if (apiReq.getSysMethod().hasContent() && apiReq.getHttpContent() != null && apiReq.getHttpContent().length > 0) { EntityBuilder bodyBuilder = EntityBuilder.create(); String contentType = apiReq.getHeaderValue(CONTENT_TYPE); if (StringUtils.isEmpty(contentType)) { contentType = apiReq.getContentTypeValue(apiReq.getHttpContentType(), apiReq.getSysEncoding()); } bodyBuilder.setContentType(ContentType.parse(contentType)); bodyBuilder.setBinary(apiReq.getHttpContent()); builder.setEntity(bodyBuilder.build()); } builder.addHeader(ACCEPT_ENCODING, "identity"); // calcProxy will modify the "Proxy-Authorization" header of the request HttpHost proxy = calcProxy(apiReq); for (Map.Entry<String, String> entry : apiReq.getSysHeaders().entrySet()) { if ("Content-Length".equalsIgnoreCase(entry.getKey())) { continue; } builder.addHeader(entry.getKey(), entry.getValue()); } int connectTimeout; int readTimeout; if (null != apiReq.getSysConnectTimeout()) { connectTimeout = apiReq.getSysConnectTimeout(); } else { connectTimeout = (int) clientConfig.getConnectionTimeoutMillis(); } if (null != apiReq.getSysReadTimeout()) { readTimeout = apiReq.getSysReadTimeout(); } else { readTimeout = (int) clientConfig.getReadTimeoutMillis(); } RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(connectTimeout).setSocketTimeout( readTimeout).setConnectionRequestTimeout((int) clientConfig.getWriteTimeoutMillis()).build(); builder.setConfig(requestConfig); return builder.build(); } private HttpHost calcProxy(HttpRequest apiReq) throws MalformedURLException, ClientException { boolean needProxy = HttpUtil.needProxy(new URL(apiReq.getSysUrl()).getHost(), clientConfig.getNoProxy(), EnvironmentUtils.getNoProxy()); if (!needProxy) { return null; } URL url = new URL(apiReq.getSysUrl()); HttpHost proxy = null; if ("https".equalsIgnoreCase(url.getProtocol())) { proxy = HttpUtil.getApacheProxy(clientConfig.getHttpsProxy(), EnvironmentUtils.getHttpsProxy(), apiReq); } else { proxy = HttpUtil.getApacheProxy(clientConfig.getHttpProxy(), EnvironmentUtils.getHttpProxy(), apiReq); } return proxy; } private HttpResponse parseToHttpResponse(org.apache.http.HttpResponse httpResponse) throws IOException { com.aliyuncs.http.HttpResponse result = new com.aliyuncs.http.HttpResponse(); // status code result.setStatus(httpResponse.getStatusLine().getStatusCode()); result.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase()); boolean existed = ((httpResponse.getEntity() != null && (httpResponse.getEntity().getContentLength() > 0 || httpResponse .getEntity().isChunked()))); if (existed) { // content type Header contentTypeHeader = httpResponse.getEntity().getContentType(); if (null == contentTypeHeader) { throw new RuntimeException("contentType cannot be empty"); } ContentType contentType = ContentType.parse(contentTypeHeader.getValue()); FormatType formatType = FormatType.mapAcceptToFormat(contentType.getMimeType()); result.setHttpContentType(formatType); String charset = "utf-8"; if (contentType.getCharset() != null) { charset = contentType.getCharset().toString(); } // body result.setHttpContent(EntityUtils.toByteArray(httpResponse.getEntity()), charset, formatType); } // headers for (Header header : httpResponse.getAllHeaders()) { result.putHeaderParameter(header.getName(), header.getValue()); } return result; } @Override public final HttpResponse syncInvoke(HttpRequest apiRequest) throws IOException, ClientException { HttpUriRequest httpRequest = parseToHttpRequest(apiRequest); CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); return parseToHttpResponse(httpResponse); } finally { IOUtils.closeQuietly(httpResponse); } } @Override public final Future<com.aliyuncs.http.HttpResponse> asyncInvoke(final HttpRequest apiRequest, final CallBack callback) { return executorService.submit(new Callable<com.aliyuncs.http.HttpResponse>() { @Override public com.aliyuncs.http.HttpResponse call() throws Exception { com.aliyuncs.http.HttpResponse result; try { result = syncInvoke(apiRequest); } catch (Exception e) { if (callback != null) { callback.onFailure(apiRequest, e); } throw e; } if (callback != null) { callback.onResponse(apiRequest, result); } return result; } }); } /** * use HttpClientConfig.setIgnoreSSLCerts(true) instead */ @Override public void ignoreSSLCertificate() { throw new IllegalStateException("Apache httpclient does not support modify sslFactory after inited, " + "use HttpClientConfig.setIgnoreSSLCerts(true) while building client"); } /** * use HttpClientConfig.setIgnoreSSLCerts(false) instead */ @Override public void restoreSSLCertificate() { throw new IllegalStateException("Apache httpclient does not support modify sslFactory after inited, " + "use HttpClientConfig.setIgnoreSSLCerts(true) while building client"); } @Override public boolean isSingleton() { return true; } @Override public void close() throws IOException { client = null; if (initialized.compareAndSet(true, false)) { executorService.shutdown(); ApacheIdleConnectionCleaner.removeConnectionManager(connectionManager); connectionManager.shutdown(); IOUtils.closeQuietly(httpClient); } } private class DefaultAsyncThreadFactory implements ThreadFactory { private AtomicInteger counter = new AtomicInteger(0); @Override public Thread newThread(Runnable runnable) { return new Thread(runnable, "Aliyun_SDK_Async_ThreadPool_" + counter.incrementAndGet()); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/clients/ApacheIdleConnectionCleaner.java
package com.aliyuncs.http.clients; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.conn.HttpClientConnectionManager; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; public class ApacheIdleConnectionCleaner extends Thread { private static final Log LOG = LogFactory.getLog(ApacheIdleConnectionCleaner.class); public static int getPeriodSec() { return periodSec; } public static void setPeriodSec(int periodSec) { ApacheIdleConnectionCleaner.periodSec = periodSec; } private static final int DEFAULT_PERIOD_SEC = 60; private static int periodSec = DEFAULT_PERIOD_SEC; private static final Map<HttpClientConnectionManager, Long> CONNMGRMAP = new ConcurrentHashMap<HttpClientConnectionManager, Long>(); private static volatile ApacheIdleConnectionCleaner instance; private volatile boolean isShuttingDown; private ApacheIdleConnectionCleaner() { super("sdk-apache-idle-connection-cleaner"); setDaemon(true); } public static void registerConnectionManager(HttpClientConnectionManager connMgr, Long idleTimeMills) { if (instance == null) { synchronized (ApacheIdleConnectionCleaner.class) { if (instance == null) { instance = new ApacheIdleConnectionCleaner(); instance.start(); } } } CONNMGRMAP.put(connMgr, idleTimeMills); } public static void removeConnectionManager(HttpClientConnectionManager connectionManager) { CONNMGRMAP.remove(connectionManager); if (CONNMGRMAP.isEmpty()) { shutdown(); } } public static void shutdown() { if (instance != null) { instance.isShuttingDown = true; instance.interrupt(); CONNMGRMAP.clear(); instance = null; } } @Override public void run() { while (true) { if (isShuttingDown) { LOG.debug("Shutting down."); return; } try { Thread.sleep(periodSec * 1000); for (Entry<HttpClientConnectionManager, Long> entry : CONNMGRMAP.entrySet()) { try { entry.getKey().closeIdleConnections(entry.getValue(), TimeUnit.MILLISECONDS); } catch (Exception t) { LOG.warn("close idle connections failed", t); } } } catch (InterruptedException e) { LOG.debug("interrupted.", e); } } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/http/clients/CompatibleUrlConnClient.java
package com.aliyuncs.http.clients; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.*; import com.aliyuncs.utils.EnvironmentUtils; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier; import javax.net.ssl.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Future; public class CompatibleUrlConnClient extends IHttpClient { protected static final String CONTENT_TYPE = "Content-Type"; protected static final String ACCEPT_ENCODING = "Accept-Encoding"; public CompatibleUrlConnClient(HttpClientConfig clientConfig) throws ClientException { super(clientConfig); } public static HttpResponse compatibleGetResponse(HttpRequest request) throws IOException, ClientException { CompatibleUrlConnClient client = new CompatibleUrlConnClient(null); HttpResponse response = client.syncInvoke(request); client.close(); return response; } @Override protected void init(HttpClientConfig clientConfig) { // do nothing } @Override public HttpResponse syncInvoke(HttpRequest request) throws IOException, ClientException { InputStream content = null; HttpResponse response; HttpURLConnection httpConn = buildHttpConnection(request); OutputStream out; try { httpConn.connect(); if (null != request.getHttpContent() && request.getHttpContent().length > 0) { out = httpConn.getOutputStream(); if (request.getSysMethod().hasContent()) { out.write(request.getHttpContent()); } out.flush(); } content = httpConn.getInputStream(); response = new HttpResponse(httpConn.getURL().toString()); parseHttpConn(response, httpConn, content); return response; } catch (IOException e) { content = httpConn.getErrorStream(); response = new HttpResponse(httpConn.getURL().toString()); parseHttpConn(response, httpConn, content); return response; } finally { if (content != null) { content.close(); } httpConn.disconnect(); } } @Override public Future<HttpResponse> asyncInvoke(HttpRequest apiRequest, CallBack callback) { throw new IllegalStateException("not supported"); } private boolean calcIgnoreSSLCert(HttpRequest request) { return request.isIgnoreSSLCerts() ? request.isIgnoreSSLCerts() : clientConfig.isIgnoreSSLCerts(); } private CompositeX509TrustManager calcX509TrustManager(HttpRequest request) throws KeyStoreException, NoSuchAlgorithmException { X509TrustManager[] trustManagers = null; if (clientConfig.getX509TrustManagers() != null) { trustManagers = clientConfig.getX509TrustManagers(); } if (request.getX509TrustManagers() != null) { trustManagers = request.getX509TrustManagers(); } List<TrustManager> trustManagerList = new ArrayList<TrustManager>(); if (null != trustManagers) { trustManagerList.addAll(Arrays.asList(trustManagers)); } // get trustManager using default certification from jdk TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); trustManagerList.addAll(Arrays.asList(tmf.getTrustManagers())); 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(calcIgnoreSSLCert(request)); return compositeX509TrustManager; } private KeyManager[] calcKeyManager(HttpRequest request) { KeyManager[] keyManagers = null; if (clientConfig.getKeyManagers() != null) { keyManagers = clientConfig.getKeyManagers(); } if (request.getKeyManagers() != null) { keyManagers = request.getKeyManagers(); } return keyManagers; } private SSLSocketFactory createSSLSocketFactory(HttpRequest request) throws ClientException { try { CompositeX509TrustManager compositeX509TrustManager = calcX509TrustManager(request); KeyManager[] keyManagers = calcKeyManager(request); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, new TrustManager[]{compositeX509TrustManager}, clientConfig.getSecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new ClientException("SDK.InitFailed", "Init https with SSL socket failed", e); } } private HostnameVerifier createHostnameVerifier(HttpRequest request) { boolean ignoreSSLCert = request.isIgnoreSSLCerts() ? request.isIgnoreSSLCerts() : clientConfig.isIgnoreSSLCerts(); if (ignoreSSLCert) { return new NoopHostnameVerifier(); } else if (clientConfig.getHostnameVerifier() != null) { return clientConfig.getHostnameVerifier(); } else { return new DefaultHostnameVerifier(); } } private 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."); } } private Proxy calcProxy(URL url, HttpRequest request) throws ClientException { String targetHost = url.getHost(); boolean needProxy = HttpUtil.needProxy(targetHost, clientConfig.getNoProxy(), EnvironmentUtils.getNoProxy()); if (!needProxy) { return Proxy.NO_PROXY; } Proxy proxy; if ("https".equalsIgnoreCase(url.getProtocol())) { String httpsProxy = EnvironmentUtils.getHttpsProxy(); proxy = HttpUtil.getJDKProxy(clientConfig.getHttpsProxy(), httpsProxy, request); } else { String httpProxy = EnvironmentUtils.getHttpProxy(); proxy = HttpUtil.getJDKProxy(clientConfig.getHttpProxy(), httpProxy, request); } return proxy; } private HttpURLConnection initHttpConnection(URL url, HttpRequest request) throws ClientException, IOException { HttpURLConnection httpConn = null; Proxy proxy = calcProxy(url, request); if ("https".equalsIgnoreCase(url.getProtocol())) { SSLSocketFactory sslSocketFactory = createSSLSocketFactory(request); HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection(proxy); httpsConn.setSSLSocketFactory(sslSocketFactory); HostnameVerifier hostnameVerifier = createHostnameVerifier(request); httpsConn.setHostnameVerifier(hostnameVerifier); httpConn = httpsConn; } if (httpConn == null) { httpConn = (HttpURLConnection) url.openConnection(proxy); } httpConn.setRequestMethod(request.getSysMethod().toString()); httpConn.setInstanceFollowRedirects(false); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); setConnectionTimeout(httpConn, request); setConnectionRequestProperty(httpConn, request); return httpConn; } private void setConnectionTimeout(HttpURLConnection httpConn, HttpRequest request) { if (request.getSysConnectTimeout() != null) { httpConn.setConnectTimeout(request.getSysConnectTimeout()); } else { httpConn.setConnectTimeout((int) clientConfig.getConnectionTimeoutMillis()); } if (request.getSysReadTimeout() != null) { httpConn.setReadTimeout(request.getSysReadTimeout()); } else { httpConn.setReadTimeout((int) clientConfig.getReadTimeoutMillis()); } } private void setConnectionRequestProperty(HttpURLConnection httpConn, HttpRequest request) { Map<String, String> mappedHeaders = request.getSysHeaders(); httpConn.setRequestProperty(ACCEPT_ENCODING, "identity"); for (Entry<String, String> entry : mappedHeaders.entrySet()) { httpConn.setRequestProperty(entry.getKey(), entry.getValue()); } if (null != request.getHeaderValue(CONTENT_TYPE)) { httpConn.setRequestProperty(CONTENT_TYPE, request.getHeaderValue(CONTENT_TYPE)); } else { String contentTypeValue = request.getContentTypeValue(request.getHttpContentType(), request .getSysEncoding()); if (null != contentTypeValue) { httpConn.setRequestProperty(CONTENT_TYPE, contentTypeValue); } } } private HttpURLConnection buildHttpConnection(HttpRequest request) throws IOException, ClientException { checkHttpRequest(request); String strUrl = request.getSysUrl(); URL url; String[] urlArray = null; if (MethodType.POST.equals(request.getSysMethod()) && null == request.getHttpContent()) { urlArray = strUrl.split("\\?"); url = new URL(urlArray[0]); } else { url = new URL(strUrl); } System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); HttpURLConnection httpConn = initHttpConnection(url, request); if (MethodType.POST.equals(request.getSysMethod()) && null != urlArray && urlArray.length == 2) { httpConn.getOutputStream().write(urlArray[1].getBytes()); } return httpConn; } private void parseHttpConn(HttpResponse response, HttpURLConnection httpConn, InputStream content) throws IOException { byte[] buff = readContent(content); response.setStatus(httpConn.getResponseCode()); response.setReasonPhrase(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()); } private byte[] readContent(InputStream content) throws IOException { if (content == null) { return null; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; while (true) { final int read = content.read(buff); if (read == -1) { break; } outputStream.write(buff, 0, read); } return outputStream.toByteArray(); } /** * use HttpClientConfig.setIgnoreSSLCerts(true) instead */ @Override public void ignoreSSLCertificate() { throw new IllegalStateException("use HttpClientConfig.setIgnoreSSLCerts(true) instead"); } /** * use HttpClientConfig.setIgnoreSSLCerts(false) instead */ @Override public void restoreSSLCertificate() { throw new IllegalStateException("use HttpClientConfig.setIgnoreSSLCerts(false) instead"); } @Override public boolean isSingleton() { return false; } @Override public void close() { // do nothing } /** * use HttpClientConfig.setIgnoreSSLCerts(true/false) instead */ @Deprecated public static final class HttpsCertIgnoreHelper { /** * use HttpClientConfig.setIgnoreSSLCerts(false) instead */ @Deprecated public static void restoreSSLCertificate() { X509TrustAll.ignoreSSLCerts = false; } /** * use HttpClientConfig.setIgnoreSSLCerts(true) instead */ @Deprecated public static void ignoreSSLCertificate() { X509TrustAll.ignoreSSLCerts = true; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/cache/ThrottlingPool.java
package com.aliyuncs.policy.cache; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import java.util.Map; import java.util.concurrent.*; public class ThrottlingPool { private final static Map<String, Entity> map = new ConcurrentHashMap<String, Entity>(); private final static ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("throttling-pool-%d").daemon(true).build()); public synchronized static void put(String key, Object data) { ThrottlingPool.put(key, data, -1); } public synchronized static void put(final String key, Object data, int expire) { ThrottlingPool.remove(key); if (data != null) { if (expire >= 0) { Future<?> future = executor.schedule(new Runnable() { @Override public void run() { synchronized (ThrottlingPool.class) { map.remove(key); } } }, expire, TimeUnit.MILLISECONDS); map.put(key, new Entity(data, expire, future)); } else { map.put(key, new Entity(data, expire, null)); } } } public synchronized static Object get(String key) { Entity entity = map.get(key); return entity != null ? entity.getValue() : null; } public synchronized static <T> T get(String key, Class<T> clazz) { return clazz.cast(ThrottlingPool.get(key)); } public synchronized static int getExpire(String key) { Entity entity = map.get(key); return entity != null ? entity.getExpire() : 0; } public synchronized static Object remove(String key) { Entity entity = map.remove(key); if (entity == null) return null; Future<?> future = entity.getFuture(); if (future != null) future.cancel(true); return entity.getValue(); } public synchronized static int size() { return map.size(); } public synchronized static void clear() { for (Entity entity : map.values()) { if (entity != null) { Future<?> future = entity.getFuture(); if (future != null) future.cancel(true); } } map.clear(); } public synchronized static Map<String, Entity> getPool() { return map; } private static class Entity { private Object value; private int expire; private Future<?> future; public Entity(Object value, int expire, Future<?> future) { this.value = value; this.expire = expire; this.future = future; } public Object getValue() { return value; } public int getExpire() { return expire; } public Future<?> getFuture() { return future; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/RetryPolicy.java
package com.aliyuncs.policy.retry; import com.aliyuncs.exceptions.ThrottlingException; import com.aliyuncs.policy.cache.ThrottlingPool; import com.aliyuncs.policy.retry.backoff.BackoffStrategy; import com.aliyuncs.policy.retry.backoff.EqualJitterBackoffStrategy; import com.aliyuncs.policy.retry.conditions.ExceptionsCondition; import com.aliyuncs.policy.retry.conditions.HeadersCondition; import com.aliyuncs.policy.retry.conditions.RetryCondition; import com.aliyuncs.policy.retry.conditions.StatusCodeCondition; import java.text.SimpleDateFormat; import java.util.*; public final class RetryPolicy { private final int maxNumberOfRetries; private final int maxDelayTimeMillis; private final BackoffStrategy backoffStrategy; private final Set<RetryCondition> retryConditions; private final Set<RetryCondition> throttlingConditions; private final Boolean enableAliyunThrottlingControl; private RetryPolicy(BuilderImpl builder) { this.maxNumberOfRetries = builder.maxNumberOfRetries; this.maxDelayTimeMillis = builder.maxDelayTimeMillis; this.backoffStrategy = builder.backoffStrategy; this.retryConditions = builder.retryConditions; this.throttlingConditions = builder.throttlingConditions; this.enableAliyunThrottlingControl = builder.enableAliyunThrottlingControl; } /** * Use default retry policy * * @param enableAliyunThrottlingControl use or not use aliyun gateway throttling * @return retryPolicy */ public static RetryPolicy defaultRetryPolicy(Boolean enableAliyunThrottlingControl) { return builder().enableAliyunThrottlingControl(enableAliyunThrottlingControl).build(); } public static RetryPolicy none() { return builder() .maxNumberOfRetries(0) .build(); } public Boolean shouldRetry(RetryPolicyContext context) { if (context.retriesAttempted() > maxNumberOfRetries) { return false; } if (throttlingConditions != null && !throttlingConditions.isEmpty()) { for (RetryCondition throttlingCondition : throttlingConditions) { if (throttlingCondition.meetState(context)) { if (throttlingCondition.escapeTime(context) <= RetryUtil.DEFAULT_ESCAPE_TIME) { return false; } if (enableAliyunThrottlingControl) { long current = System.currentTimeMillis(); int escapeTime = throttlingCondition.escapeTime(context); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String endTime = df.format(new Date(current + escapeTime)); ThrottlingPool.put(context.coordinate(), endTime, escapeTime); if (context.exception() == null || !ThrottlingException.class.isAssignableFrom(context.exception().getClass())) { context.updateException(new ThrottlingException("SDK.TriggerThrottlingPolicy", "Client triggered throttling policy, server cannot be accessed before " + endTime + (context.exception() != null ? ". Error message: \n" + context.exception().getMessage() : "."), context.exception())); } } } } } if (getBackoffDelay(context) > maxDelayTimeMillis) { return false; } if (retryConditions != null && !retryConditions.isEmpty()) { for (RetryCondition retryCondition : retryConditions) { if (retryCondition.meetState(context)) { return true; } } } return context.retriesAttempted() == RetryUtil.FIRST_ATTEMPTED; } public int getBackoffDelay(RetryPolicyContext context) { if (context.retriesAttempted() == RetryUtil.FIRST_ATTEMPTED) { if (ThrottlingPool.get(context.coordinate()) != null) { long current = System.currentTimeMillis(); int escapeTime = ThrottlingPool.getExpire(context.coordinate()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String endTime = df.format(new Date(current + escapeTime)); if (context.exception() == null || !ThrottlingException.class.isAssignableFrom(context.exception().getClass())) { context.updateException(new ThrottlingException("SDK.TriggerThrottlingPolicy", "Client triggered throttling policy, server cannot be accessed before " + endTime + (context.exception() != null ? ". Error message: \n" + context.exception().getMessage() : "."), context.exception())); } return escapeTime; } else { return RetryUtil.DEFAULT_ESCAPE_TIME; } } int delayTimeMillis = this.backoffStrategy.computeDelayBeforeNextRetry(context); if (throttlingConditions != null && !throttlingConditions.isEmpty()) { for (RetryCondition throttlingCondition : throttlingConditions) { if (throttlingCondition.meetState(context)) { delayTimeMillis = Math.max(delayTimeMillis, throttlingCondition.escapeTime(context)); } } } return delayTimeMillis; } public static Builder builder() { return new BuilderImpl(); } public int maxNumberOfRetries() { return maxNumberOfRetries; } public int maxDelayTimeMillis() { return maxDelayTimeMillis; } public BackoffStrategy backoffStrategy() { return backoffStrategy; } public Set<RetryCondition> retryConditions() { return retryConditions; } public Set<RetryCondition> throttlingConditions() { return throttlingConditions; } public Boolean enableAliyunThrottlingControl() { return enableAliyunThrottlingControl; } public Builder toBuilder() { return builder() .maxNumberOfRetries(maxNumberOfRetries) .maxDelayTimeMillis(maxDelayTimeMillis) .backoffStrategy(backoffStrategy) .retryConditions(retryConditions) .throttlingConditions(throttlingConditions) .enableAliyunThrottlingControl(enableAliyunThrottlingControl); } public interface Builder { Builder maxNumberOfRetries(int numRetries); Builder maxDelayTimeMillis(int delayTime); Builder backoffStrategy(BackoffStrategy backoffStrategy); Builder retryConditions(Set<RetryCondition> retryConditions); Builder throttlingConditions(Set<RetryCondition> throttlingConditions); Builder enableAliyunThrottlingControl(Boolean enableThrottlingControl); RetryPolicy build(); } public static final class BuilderImpl implements Builder { private int maxNumberOfRetries; private int maxDelayTimeMillis; private BackoffStrategy backoffStrategy; private Set<RetryCondition> retryConditions = new HashSet<RetryCondition>(); private Set<RetryCondition> throttlingConditions = new HashSet<RetryCondition>(); private Boolean enableAliyunThrottlingControl = false; private static RetryCondition aliyunThrottlingCondition = HeadersCondition.create(RetryUtil.THROTTLING_PATTERNS); private BuilderImpl() { this.maxNumberOfRetries = RetryUtil.DEFAULT_MAX_RETRIES; this.maxDelayTimeMillis = RetryUtil.MAX_BACKOFF; this.backoffStrategy = new EqualJitterBackoffStrategy(RetryUtil.BASE_DELAY, this.maxDelayTimeMillis, new Random()); this.retryConditions.add(ExceptionsCondition.create(RetryUtil.RETRYABLE_EXCEPTIONS)); this.retryConditions.add(StatusCodeCondition.create(RetryUtil.RETRYABLE_STATUS_CODES)); } @Override public Builder maxNumberOfRetries(int maxNumberOfRetries) { this.maxNumberOfRetries = maxNumberOfRetries; return this; } @Override public Builder maxDelayTimeMillis(int maxDelayTimeMillis) { this.maxDelayTimeMillis = maxDelayTimeMillis; return this; } @Override public Builder backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } @Override public Builder retryConditions(Set<RetryCondition> retryConditions) { this.retryConditions = retryConditions; return this; } public Builder retryConditions(RetryCondition... retryCondition) { this.retryConditions = new HashSet<RetryCondition>(Arrays.asList(retryCondition)); return this; } @Override public Builder throttlingConditions(Set<RetryCondition> throttlingConditions) { this.throttlingConditions = throttlingConditions; return this; } public Builder throttlingConditions(RetryCondition... throttlingCondition) { this.throttlingConditions = new HashSet<RetryCondition>(Arrays.asList(throttlingCondition)); return this; } @Override public Builder enableAliyunThrottlingControl(Boolean enableAliyunThrottlingControl) { this.enableAliyunThrottlingControl = enableAliyunThrottlingControl; if (this.enableAliyunThrottlingControl) { if (!this.throttlingConditions.contains(aliyunThrottlingCondition)) { this.throttlingConditions.add(aliyunThrottlingCondition); } } else { if (this.throttlingConditions.contains(aliyunThrottlingCondition)) { this.throttlingConditions.remove(aliyunThrottlingCondition); } } return this; } @Override public RetryPolicy build() { return new RetryPolicy(this); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/RetryPolicyContext.java
package com.aliyuncs.policy.retry; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.http.HttpResponse; import java.util.Map; public final class RetryPolicyContext { private final String coordinate; private final HttpRequest httpRequest; private final HttpResponse httpResponse; private Throwable exception; private final int retriesAttempted; private final Integer httpStatusCode; private final Map<String, String> httpHeaders; private RetryPolicyContext(Builder builder) { this.coordinate = builder.coordinate; this.httpRequest = builder.httpRequest; this.httpResponse = builder.httpResponse; this.exception = builder.exception; this.retriesAttempted = builder.retriesAttempted; this.httpStatusCode = this.httpResponse != null ? this.httpResponse.getStatus() : null; this.httpHeaders = this.httpResponse != null ? this.httpResponse.getSysHeaders() : null; } public static Builder builder() { return new Builder(); } public String coordinate() { return this.coordinate; } public HttpRequest httpRequest() { return this.httpRequest; } public HttpResponse httpResponse() { return this.httpResponse; } public Throwable exception() { return this.exception; } public RetryPolicyContext updateException(Throwable exception) { this.exception = exception; return this; } public int retriesAttempted() { return this.retriesAttempted; } public Integer httpStatusCode() { return this.httpStatusCode; } public Map<String, String> httpHeaders() { return this.httpHeaders; } public static final class Builder { private String coordinate; private HttpRequest httpRequest; private HttpResponse httpResponse; private Throwable exception; private int retriesAttempted; private Builder() { } public Builder coordinate(String coordinate) { this.coordinate = coordinate; return this; } public Builder httpRequest(HttpRequest httpRequest) { this.httpRequest = httpRequest; return this; } public Builder httpResponse(HttpResponse httpResponse) { this.httpResponse = httpResponse; return this; } public Builder exception(Throwable exception) { this.exception = exception; return this; } public Builder retriesAttempted(int retriesAttempted) { this.retriesAttempted = retriesAttempted; return this; } public RetryPolicyContext build() { return new RetryPolicyContext(this); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/RetryUtil.java
package com.aliyuncs.policy.retry; import com.aliyuncs.policy.retry.pattern.AliyunThrottlingPattern; import com.aliyuncs.policy.retry.pattern.Pattern; import java.io.IOException; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static java.util.Collections.unmodifiableSet; import static java.util.Collections.unmodifiableMap; public class RetryUtil { public static final int FIRST_ATTEMPTED = 0; public static final int DEFAULT_ESCAPE_TIME = -1; public static final int BASE_DELAY = 100; public static final int MAX_BACKOFF = 2 * 60 * 1000; public static final int DEFAULT_MAX_RETRIES = 3; private static int HTTP_STATUS_TOO_MANY_REQUESTS = 429; public static final Set<Integer> RETRYABLE_STATUS_CODES; public static final Set<Class<? extends Exception>> RETRYABLE_EXCEPTIONS; public static final Map<String, Pattern> THROTTLING_PATTERNS; public static final String DEFAULT_USER_API_THROTTLING_KEY = "X-RateLimit-User-API"; public static final String DEFAULT_PATTERNS = "Remain:1"; public static final String DEFAULT_USER_THROTTLING_KEY = "X-RateLimit-User"; static { Set<Integer> retryableStatusCodes = new HashSet<Integer>(); retryableStatusCodes.add(HttpURLConnection.HTTP_CLIENT_TIMEOUT); retryableStatusCodes.add(HTTP_STATUS_TOO_MANY_REQUESTS); retryableStatusCodes.add(HttpURLConnection.HTTP_INTERNAL_ERROR); retryableStatusCodes.add(HttpURLConnection.HTTP_BAD_GATEWAY); retryableStatusCodes.add(HttpURLConnection.HTTP_UNAVAILABLE); retryableStatusCodes.add(HttpURLConnection.HTTP_GATEWAY_TIMEOUT); RETRYABLE_STATUS_CODES = unmodifiableSet(retryableStatusCodes); Set<Class<? extends Exception>> retryableExceptions = new HashSet<Class<? extends Exception>>(); retryableExceptions.add(IOException.class); RETRYABLE_EXCEPTIONS = unmodifiableSet(retryableExceptions); Map<String, Pattern> throttlingPatterns = new HashMap<String, Pattern>(); throttlingPatterns.put(DEFAULT_USER_API_THROTTLING_KEY, new AliyunThrottlingPattern(DEFAULT_PATTERNS)); throttlingPatterns.put(DEFAULT_USER_THROTTLING_KEY, new AliyunThrottlingPattern(DEFAULT_PATTERNS)); THROTTLING_PATTERNS = unmodifiableMap(throttlingPatterns); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/backoff/BackoffStrategy.java
package com.aliyuncs.policy.retry.backoff; import com.aliyuncs.policy.retry.RetryPolicyContext; public abstract class BackoffStrategy { /** * Max permitted retry times. To prevent exponentialDelay from overflow, there must be 2 ^ retriesAttempted * <= 2 ^ 31 - 1, which means retriesAttempted <= 30, so that is the ceil for retriesAttempted. */ int RETRIES_ATTEMPTED_CEILING = (int) Math.floor(Math.log(Integer.MAX_VALUE) / Math.log(2)); public abstract int computeDelayBeforeNextRetry(RetryPolicyContext context); int calculateExponentialDelay(int retriesAttempted, int baseDelay, int maxBackoffTime) { int cappedRetries = Math.min(retriesAttempted, RETRIES_ATTEMPTED_CEILING); return (int) Math.min(baseDelay * (1L << cappedRetries), maxBackoffTime); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/backoff/EqualJitterBackoffStrategy.java
package com.aliyuncs.policy.retry.backoff; import com.aliyuncs.policy.retry.RetryPolicyContext; import java.util.Random; public final class EqualJitterBackoffStrategy extends BackoffStrategy { private static final int BASE_DELAY_CEILING = 24 * 60 * 60 * 1000; private static final int MAX_BACKOFF_CEILING = 24 * 60 * 60 * 1000; private final int baseDelay; private final int maxBackoffTime; private final Random random; public EqualJitterBackoffStrategy(final Integer baseDelay, final int maxBackoffTime, final Random random) { this.baseDelay = Math.min(baseDelay, BASE_DELAY_CEILING); this.maxBackoffTime = Math.min(maxBackoffTime, MAX_BACKOFF_CEILING); this.random = random; } @Override public int computeDelayBeforeNextRetry(RetryPolicyContext context) { int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime); return (ceil / 2) + random.nextInt((ceil / 2) + 1); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/conditions/ExceptionsCondition.java
package com.aliyuncs.policy.retry.conditions; import com.aliyuncs.policy.retry.RetryPolicyContext; import com.aliyuncs.policy.retry.RetryUtil; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public final class ExceptionsCondition implements RetryCondition { private final Set<Class<? extends Exception>> exceptionsToRetryOn; private ExceptionsCondition(Set<Class<? extends Exception>> exceptionsToRetryOn) { this.exceptionsToRetryOn = new HashSet<Class<? extends Exception>>(exceptionsToRetryOn); } @Override public boolean meetState(RetryPolicyContext context) { Throwable exception = context.exception(); if (exception == null) { return false; } for (Class<? extends Exception> ex : exceptionsToRetryOn) { if (ex.isAssignableFrom(exception.getClass()) || (exception.getCause() != null && ex.isAssignableFrom(exception.getCause().getClass()))) { return true; } } return false; } @Override public int escapeTime(RetryPolicyContext context) { return RetryUtil.DEFAULT_ESCAPE_TIME; } public static ExceptionsCondition create(Set<Class<? extends Exception>> exceptionsToRetryOn) { return new ExceptionsCondition(exceptionsToRetryOn); } public static ExceptionsCondition create(Class<? extends Exception>... exceptionsToRetryOn) { return new ExceptionsCondition(new HashSet<Class<? extends Exception>>(Arrays.asList(exceptionsToRetryOn))); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/conditions/HeadersCondition.java
package com.aliyuncs.policy.retry.conditions; import com.aliyuncs.policy.retry.RetryPolicyContext; import com.aliyuncs.policy.retry.RetryUtil; import com.aliyuncs.policy.retry.pattern.Pattern; import java.util.*; public final class HeadersCondition implements RetryCondition { private final Map<String, Pattern> headersConditionToRetryOn; private HeadersCondition(Map<String, Pattern> headersToRetryOn) { this.headersConditionToRetryOn = new HashMap<String, Pattern>(headersToRetryOn); } @Override public boolean meetState(RetryPolicyContext context) { Map<String, String> realHeaders = context.httpHeaders(); if (realHeaders == null) { return false; } for (String key : headersConditionToRetryOn.keySet()) { Pattern pattern = headersConditionToRetryOn.get(key); if (pattern != null && realHeaders.containsKey(key)) { pattern.readFormHeadersContent(realHeaders.get(key)); if (pattern.meetState()) { return true; } } } return false; } // 逃脱时间,即这段时间内既不进行重试又不直接限制(主要用在限流时) @Override public int escapeTime(RetryPolicyContext context) { int escapeTimeMillis = RetryUtil.DEFAULT_ESCAPE_TIME; Map<String, String> realHeaders = context.httpHeaders(); if (realHeaders == null) { return RetryUtil.DEFAULT_ESCAPE_TIME; } for (String key : headersConditionToRetryOn.keySet()) { Pattern pattern = headersConditionToRetryOn.get(key); if (pattern != null && realHeaders.containsKey(key)) { pattern.readFormHeadersContent(realHeaders.get(key)); if (pattern.meetState()) { escapeTimeMillis = Math.max(escapeTimeMillis, pattern.escapeTime()); } } } return escapeTimeMillis; } public static HeadersCondition create(Map<String, Pattern> headersToRetryOn) { return new HeadersCondition(headersToRetryOn); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/conditions/RetryCondition.java
package com.aliyuncs.policy.retry.conditions; import com.aliyuncs.policy.retry.RetryPolicyContext; public interface RetryCondition { boolean meetState(RetryPolicyContext context); int escapeTime(RetryPolicyContext context); }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/conditions/StatusCodeCondition.java
package com.aliyuncs.policy.retry.conditions; import com.aliyuncs.policy.retry.RetryPolicyContext; import com.aliyuncs.policy.retry.RetryUtil; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public final class StatusCodeCondition implements RetryCondition { private final Set<Integer> statusCodesToRetryOn; private StatusCodeCondition(Set<Integer> statusCodesToRetryOn) { this.statusCodesToRetryOn = new HashSet<Integer>(statusCodesToRetryOn); } @Override public boolean meetState(RetryPolicyContext context) { Integer code = context.httpStatusCode(); if (code == null) { return false; } for (Integer s : statusCodesToRetryOn) { if (code.equals(s)) { return true; } } return false; } @Override public int escapeTime(RetryPolicyContext context) { return RetryUtil.DEFAULT_ESCAPE_TIME; } public static StatusCodeCondition create(Set<Integer> statusCodesToRetryOn) { return new StatusCodeCondition(statusCodesToRetryOn); } public static StatusCodeCondition create(Integer... statusCodesToRetryOn) { return new StatusCodeCondition(new HashSet<Integer>(Arrays.asList(statusCodesToRetryOn))); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/pattern/AliyunThrottlingPattern.java
package com.aliyuncs.policy.retry.pattern; import com.aliyuncs.policy.retry.RetryUtil; import com.aliyuncs.utils.StringUtils; import java.util.HashMap; import java.util.Map; public class AliyunThrottlingPattern implements Pattern { private Map<String, String> throttlingMap = new HashMap<String, String>(); private static String Remain = "remain"; private static String TimeLeft = "timeleft"; private AliyunThrottlingPattern anotherPattern; public AliyunThrottlingPattern(String content) { throttlingMap.clear(); if (!StringUtils.isEmpty(content)) { String[] strs = content.split(","); for (String s : strs) { String[] context = s.split(":"); if (context.length == 2) { throttlingMap.put(context[0].toLowerCase(), context[1].toLowerCase()); } } } } private Map<String, String> getThrottlingMap() { return throttlingMap; } @Override public Boolean meetState() { Map<String, String> realThrottlingMap = anotherPattern.getThrottlingMap(); if (realThrottlingMap.containsKey(Remain) && throttlingMap.containsKey(Remain)) { int realRemain = Integer.parseInt(realThrottlingMap.get(Remain)); int needRemain = Integer.parseInt(throttlingMap.get(Remain)); return realRemain < needRemain && realRemain != -1; } return false; } @Override public int escapeTime() { int escapeTimeMillis = RetryUtil.DEFAULT_ESCAPE_TIME; Map<String, String> realThrottlingMap = anotherPattern.getThrottlingMap(); if (realThrottlingMap.containsKey(TimeLeft)) { escapeTimeMillis = Integer.parseInt(realThrottlingMap.get(TimeLeft)) + RetryUtil.BASE_DELAY; } return escapeTimeMillis; } public void readFormHeadersContent(String content) { this.anotherPattern = new AliyunThrottlingPattern(content); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/pattern/Pattern.java
package com.aliyuncs.policy.retry.pattern; public interface Pattern { Boolean meetState(); void readFormHeadersContent(String content); int escapeTime(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/policy/retry/pattern/SimplePattern.java
package com.aliyuncs.policy.retry.pattern; import com.aliyuncs.policy.retry.RetryUtil; public class SimplePattern implements Pattern { private static String context; private SimplePattern anotherPattern; public SimplePattern(String context) { SimplePattern.context = context; } public String getContext() { return context; } @Override public Boolean meetState() { return anotherPattern != null && context.equals(anotherPattern.getContext()); } @Override public int escapeTime() { return RetryUtil.DEFAULT_ESCAPE_TIME; } public void readFormHeadersContent(String content) { this.anotherPattern = new SimplePattern(content); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/profile/DefaultProfile.java
package com.aliyuncs.profile; import com.aliyuncs.auth.*; import com.aliyuncs.endpoint.DefaultEndpointResolver; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpClientConfig; import com.aliyuncs.utils.ParameterHelper; import org.slf4j.Logger; import static com.aliyuncs.utils.LogUtils.DEFAULT_LOG_FORMAT; @SuppressWarnings("deprecation") public class DefaultProfile implements IClientProfile { private static DefaultProfile profile = null; private String regionId = null; private FormatType acceptFormat = null; private ICredentialProvider icredential = null; private volatile AlibabaCloudCredentialsProvider credentialsProvider = null; private Credential credential; private String certPath; private HttpClientConfig httpClientConfig = HttpClientConfig.getDefault(); private boolean usingInternalLocationService = false; private boolean usingVpcEndpoint = false; private Logger logger; private String logFormat = DEFAULT_LOG_FORMAT; private boolean isCloseTrace = false; private String locationServiceEndpoint = null; private String locationServiceApiVersion = null; private DefaultProfile() { } private DefaultProfile(String regionId) { this.regionId = regionId; } private DefaultProfile(String regionId, Credential creden) { this.credential = creden; this.regionId = regionId; } private DefaultProfile(String region, ICredentialProvider icredential) { this.regionId = region; this.icredential = icredential; } public synchronized static DefaultProfile getProfile() { if (null == profile) { profile = new DefaultProfile(); } return profile; } /** * @deprecated : Use DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider) instead of this */ @Deprecated public synchronized static DefaultProfile getProfile(String regionId, ICredentialProvider icredential) { profile = new DefaultProfile(regionId, icredential); return profile; } public synchronized static DefaultProfile getProfile(String regionId, String accessKeyId, String secret) { profile = new DefaultProfile(regionId, new Credential(accessKeyId, secret)); return profile; } public synchronized static DefaultProfile getProfile(String regionId, String accessKeyId, String secret, String stsToken) { Credential creden = new Credential(accessKeyId, secret, stsToken); profile = new DefaultProfile(regionId, creden); return profile; } public synchronized static DefaultProfile getProfile(String regionId) { return new DefaultProfile(regionId); } /** * @deprecated : Use addEndpoint(String regionId, String product, String endpoint) instead of this */ @Deprecated public synchronized static void addEndpoint(String endpointName, String regionId, String product, String domain) { addEndpoint(endpointName, regionId, product, domain, true); } /** * @deprecated : Use addEndpoint(String regionId, String product, String endpoint) instead of this */ @Deprecated public synchronized static void addEndpoint(String endpointName, String regionId, String product, String domain, boolean isNeverExpire) { // endpointName, isNeverExpire take no effect addEndpoint(regionId, product, domain); } public synchronized static void addEndpoint(String regionId, String product, String endpoint) { ParameterHelper.validateParameter(regionId, "regionId"); DefaultEndpointResolver.predefinedEndpointResolver.putEndpointEntry(regionId, product, endpoint); } @Override public synchronized String getRegionId() { return regionId; } @Override public synchronized FormatType getFormat() { return acceptFormat; } @Override public AlibabaCloudCredentialsProvider getCredentialsProvider() { return credentialsProvider; } @Override public synchronized Credential getCredential() { if (null == credential && null != icredential) { credential = icredential.fresh(); } return credential; } @Override @Deprecated public ISigner getSigner() { return null; } /** * @deprecated : Use DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider) instead of this */ @Override @Deprecated public void setCredentialsProvider(AlibabaCloudCredentialsProvider credentialsProvider) { if (credential == null) { credential = new CredentialsBackupCompatibilityAdaptor(credentialsProvider); } this.credentialsProvider = credentialsProvider; } @Override public String getCertPath() { return certPath; } @Override public void setCertPath(String certPath) { this.certPath = certPath; } @Override public HttpClientConfig getHttpClientConfig() { return httpClientConfig; } @Override public void setHttpClientConfig(HttpClientConfig httpClientConfig) { this.httpClientConfig = httpClientConfig; } @Override public void enableUsingInternalLocationService() { usingInternalLocationService = true; } @Override public boolean isUsingInternalLocationService() { return usingInternalLocationService; } @Override public boolean isUsingVpcEndpoint() { return usingVpcEndpoint; } @Override public void enableUsingVpcEndpoint() { this.usingVpcEndpoint = true; } /** * @deprecated : use enableUsingInternalLocationService instead of this. */ @Override @Deprecated public void setUsingInternalLocationService() { enableUsingInternalLocationService(); } @Override public Logger getLogger() { return logger; } @Override public void setLogger(Logger logger) { this.logger = logger; } @Override public String getLogFormat() { return logFormat; } @Override public void setLogFormat(String logFormat) { this.logFormat = logFormat; } @Override public boolean isCloseTrace() { return isCloseTrace; } @Override public void setCloseTrace(boolean closeTrace) { isCloseTrace = closeTrace; } @Override public String getLocationServiceEndpoint() { return locationServiceEndpoint; } @Override public void setLocationServiceEndpoint(String locationServiceEndpoint) { this.locationServiceEndpoint = locationServiceEndpoint; } @Override public String getLocationServiceApiVersion() { return locationServiceApiVersion; } @Override public void setLocationServiceApiVersion(String locationServiceApiVersion) { this.locationServiceApiVersion = locationServiceApiVersion; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/profile/IClientProfile.java
package com.aliyuncs.profile; import com.aliyuncs.auth.AlibabaCloudCredentialsProvider; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpClientConfig; import org.slf4j.Logger; public interface IClientProfile { /** * @deprecated : Use Signer.getSigner(AlibabaCloudCredentials credentials) instead of this */ @Deprecated ISigner getSigner(); String getRegionId(); FormatType getFormat(); AlibabaCloudCredentialsProvider getCredentialsProvider(); /** * @deprecated : Use AlibabaCloudCredentialsProvider getCredentials() instead of this */ @Deprecated Credential getCredential(); /** * This method exists because ClientProfile holds too much modules like endpoint management * * @deprecated : Use DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider) instead of this */ @Deprecated void setCredentialsProvider(AlibabaCloudCredentialsProvider credentialsProvider); /** * use HttpClientConfig.getCertPath instead */ @Deprecated String getCertPath(); /** * use HttpClientConfig.setCertPath instead * * @param certPath */ @Deprecated void setCertPath(String certPath); /** * http client configs */ HttpClientConfig getHttpClientConfig(); void setHttpClientConfig(HttpClientConfig httpClientConfig); void enableUsingInternalLocationService(); boolean isUsingInternalLocationService(); boolean isUsingVpcEndpoint(); void enableUsingVpcEndpoint(); /** * @Deprecated : Use enableUsingInternalLocationService instead of this */ @Deprecated void setUsingInternalLocationService(); Logger getLogger(); void setLogger(Logger logger); String getLogFormat(); void setLogFormat(String logFormat); boolean isCloseTrace(); void setCloseTrace(boolean closeTrace); String getLocationServiceEndpoint(); void setLocationServiceEndpoint(String locationServiceEndpoint); String getLocationServiceApiVersion(); void setLocationServiceApiVersion(String locationServiceApiVersion); }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/reader/JsonReader.java
package com.aliyuncs.reader; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.HashMap; import java.util.Map; @Deprecated public class JsonReader implements Reader { private static final Object ARRAY_END_TOKEN = new Object(); private static final Object OBJECT_END_TOKEN = new Object(); private static final Object COMMA_TOKEN = new Object(); private static final Object COLON_TOKEN = new Object(); private static final int FIRST_POSITION = 0; private static final int CURRENT_POSITION = 1; private static final int NEXT_POSITION = 2; private static Map<Character, Character> escapes = new HashMap<Character, Character>(); static { escapes.put(Character.valueOf('\\'), Character.valueOf('\\')); escapes.put(Character.valueOf('/'), Character.valueOf('/')); escapes.put(Character.valueOf('"'), Character.valueOf('"')); escapes.put(Character.valueOf('t'), Character.valueOf('\t')); escapes.put(Character.valueOf('n'), Character.valueOf('\n')); escapes.put(Character.valueOf('r'), Character.valueOf('\r')); escapes.put(Character.valueOf('b'), Character.valueOf('\b')); escapes.put(Character.valueOf('f'), Character.valueOf('\f')); } private CharacterIterator ct; private char c; private Object token; private StringBuffer stringBuffer = new StringBuffer(); private Map<String, String> map = new HashMap<String, String>(); public static String trimFromLast(String str, String stripString) { int pos = str.lastIndexOf(stripString); if (pos > -1) { return str.substring(0, pos); } else { return str; } } @Override public Map<String, String> read(String response, String endpoint) { return read(new StringCharacterIterator(response), endpoint, FIRST_POSITION); } @Override public Map<String, String> readForHideArrayItem(String response, String endpoint) { return readForHideItem(new StringCharacterIterator(response), endpoint, FIRST_POSITION); } public Map<String, String> read(CharacterIterator ci, String endpoint, int start) { ct = ci; switch (start) { case FIRST_POSITION: c = ct.first(); break; case CURRENT_POSITION: c = ct.current(); break; case NEXT_POSITION: c = ct.next(); break; default: break; } readJson(endpoint); return map; } public Map<String, String> readForHideItem(CharacterIterator ci, String endpoint, int start) { ct = ci; switch (start) { case FIRST_POSITION: c = ct.first(); break; case CURRENT_POSITION: c = ct.current(); break; case NEXT_POSITION: c = ct.next(); break; } readJsonForHideItem(endpoint); return map; } private Object readJson(String baseKey) { skipWhiteSpace(); char ch = c; nextChar(); switch (ch) { case '{': processObject(baseKey); break; case '}': token = OBJECT_END_TOKEN; break; case '[': if (c == '"') { processList(baseKey); break; } else { processArray(baseKey); break; } case ']': token = ARRAY_END_TOKEN; break; case '"': token = processString(); break; case ',': token = COMMA_TOKEN; break; case ':': token = COLON_TOKEN; break; case 't': nextChar(); nextChar(); nextChar(); token = Boolean.TRUE; break; case 'n': nextChar(); nextChar(); nextChar(); token = null; break; case 'f': nextChar(); nextChar(); nextChar(); nextChar(); token = Boolean.FALSE; break; default: c = ct.previous(); if (Character.isDigit(c) || c == '-') { token = processNumber(); } } return token; } private Object readJsonForHideItem(String baseKey) { skipWhiteSpace(); char ch = c; nextChar(); switch (ch) { case '{': processObjectForHideItemName(baseKey); break; case '}': token = OBJECT_END_TOKEN; break; case '[': if (c == '"') { processListForHideItem(baseKey); break; } else { processArrayForHideItem(baseKey); break; } case ']': token = ARRAY_END_TOKEN; break; case '"': token = processString(); break; case ',': token = COMMA_TOKEN; break; case ':': token = COLON_TOKEN; break; case 't': nextChar(); nextChar(); nextChar(); token = Boolean.TRUE; break; case 'n': nextChar(); nextChar(); nextChar(); token = null; break; case 'f': nextChar(); nextChar(); nextChar(); nextChar(); token = Boolean.FALSE; break; default: c = ct.previous(); if (Character.isDigit(c) || c == '-') { token = processNumber(); } } return token; } private void processObject(String baseKey) { String key = baseKey + "." + readJson(baseKey); while (!token.equals(OBJECT_END_TOKEN)) { readJson(key); if (!token.equals(OBJECT_END_TOKEN)) { Object object = readJson(key); if (object instanceof String || object instanceof Number || object instanceof Boolean) { map.put(key, String.valueOf(object)); } if (readJson(key) == COMMA_TOKEN) { key = String.valueOf(readJson(key)); key = baseKey + "." + key; } } } } private void processObjectForHideItemName(String baseKey) { String key = baseKey + "." + readJsonForHideItem(baseKey); while (!token.equals(OBJECT_END_TOKEN)) { readJsonForHideItem(key); if (!token.equals(OBJECT_END_TOKEN)) { Object object = readJsonForHideItem(key); if (object instanceof String || object instanceof Number || object instanceof Boolean) { map.put(key, String.valueOf(object)); } if (readJson(key) == COMMA_TOKEN) { key = String.valueOf(readJson(key)); key = baseKey + "." + key; } } } } private void processList(String baseKey) { Object value = readJson(baseKey); int index = 0; while (!token.equals(ARRAY_END_TOKEN)) { String key = trimFromLast(baseKey, ".") + "[" + (index++) + "]"; map.put(key, String.valueOf(value)); if (readJson(baseKey) == COMMA_TOKEN) { value = readJson(baseKey); } } map.put(trimFromLast(baseKey, ".") + ".Length", String.valueOf(index)); } private void processListForHideItem(String baseKey) { Object value = readJsonForHideItem(baseKey); int index = 0; while (!token.equals(ARRAY_END_TOKEN)) { String key = baseKey + "[" + (index++) + "]"; map.put(key, String.valueOf(value)); if (readJsonForHideItem(baseKey) == COMMA_TOKEN) { value = readJsonForHideItem(baseKey); } } map.put(baseKey + ".Length", String.valueOf(index)); } private void processArray(String baseKey) { int index = 0; String preKey = baseKey.substring(0, baseKey.lastIndexOf(".")); String key = preKey + "[" + index + "]"; Object value = readJson(key); while (!token.equals(ARRAY_END_TOKEN)) { map.put(preKey + ".Length", String.valueOf(index + 1)); if (value instanceof String) { map.put(key, String.valueOf(value)); } if (readJson(baseKey) == COMMA_TOKEN) { key = preKey + "[" + (++index) + "]"; value = readJson(key); } } } private void processArrayForHideItem(String baseKey) { int index = 0; String preKey = baseKey; String key = preKey + "[" + index + "]"; Object value = readJsonForHideItem(key); while (!token.equals(ARRAY_END_TOKEN)) { map.put(preKey + ".Length", String.valueOf(index + 1)); if (value instanceof String) { map.put(key, String.valueOf(value)); } if (readJsonForHideItem(baseKey) == COMMA_TOKEN) { key = preKey + "[" + (++index) + "]"; value = readJsonForHideItem(key); } } } private Object processNumber() { stringBuffer.setLength(0); if ('-' == c) { addChar(); } addDigits(); if ('.' == c) { addChar(); addDigits(); } if ('e' == c || 'E' == c) { addChar(); if ('+' == c || '-' == c) { addChar(); } addDigits(); } return stringBuffer.toString(); } private void addDigits() { while (Character.isDigit(c)) { addChar(); } } private void skipWhiteSpace() { while (Character.isWhitespace(c)) { nextChar(); } } private char nextChar() { c = ct.next(); return c; } private Object processString() { stringBuffer.setLength(0); while (c != '"') { if (c == '\\') { nextChar(); Object value = escapes.get(Character.valueOf(c)); if (value != null) { addChar(((Character) value).charValue()); } } else { addChar(); } } nextChar(); return stringBuffer.toString(); } private void addChar(char ch) { stringBuffer.append(ch); nextChar(); } private void addChar() { addChar(c); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/reader/Reader.java
package com.aliyuncs.reader; import com.aliyuncs.exceptions.ClientException; import java.util.Map; @Deprecated public interface Reader { Map<String, String> read(String response, String endpoint) throws ClientException; Map<String, String> readForHideArrayItem(String response, String endpoint) throws ClientException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/reader/ReaderFactory.java
package com.aliyuncs.reader; import com.aliyuncs.http.FormatType; @Deprecated public class ReaderFactory { public static Reader createInstance(FormatType format) { if (FormatType.JSON == format) { return new JsonReader(); } if (FormatType.XML == format) { return new XmlReader(); } throw new IllegalStateException("Server response has a bad format type: " + format); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/reader/XmlReader.java
package com.aliyuncs.reader; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.utils.XmlUtils; import org.w3c.dom.Element; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @Deprecated public class XmlReader implements Reader { Map<String, String> map = new HashMap<String, String>(); @Override public Map<String, String> read(String response, String endpoint) throws ClientException { Element root; try { root = XmlUtils.getRootElementFromString(response); read(root, endpoint, false); } catch (ParserConfigurationException e) { throw new ClientException("SDK.InvalidXMLParser", e.toString()); } catch (SAXException e) { throw new ClientException("SDK.InvalidXMLFormat", e.toString()); } catch (IOException e) { throw new ClientException("SDK.InvalidContent", e.toString()); } return map; } @Override public Map<String, String> readForHideArrayItem(String response, String endpoint) throws ClientException { return read(response, endpoint); } private void read(Element element, String path, boolean appendPath) { path = buildPath(element, path, appendPath); List<Element> childElements = XmlUtils.getChildElements(element); if (childElements.isEmpty()) { map.put(path, element.getTextContent()); return; } List<Element> listElements = XmlUtils.getChildElements(element, childElements.get(0).getNodeName()); //be list if (listElements.size() > 1 && childElements.size() == listElements.size()) { elementsAsList(childElements, path); //may be list } else if (listElements.size() == 1 && childElements.size() == 1) { //as list elementsAsList(listElements, path); //as not list read(childElements.get(0), path, true); //not list } else { for (Element childElement : childElements) { read(childElement, path, true); } } } private String buildPath(Element element, String path, boolean appendPath) { return appendPath ? path + "." + element.getNodeName() : path; } private void elementsAsList(List<Element> listElements, String path) { map.put(path + ".Length", String.valueOf(listElements.size())); for (int i = 0; i < listElements.size(); i++) { read(listElements.get(i), path + "[" + i + "]", false); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/regions/ProductDomain.java
package com.aliyuncs.regions; public class ProductDomain { private String productName; private String domainName; public ProductDomain(String product, String domain) { this.productName = product; this.domainName = domain; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getDomainName() { return domainName; } public void setDomainName(String domainName) { this.domainName = domainName; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/transform/UnmarshallerContext.java
package com.aliyuncs.transform; import com.aliyuncs.http.HttpResponse; import com.aliyuncs.utils.FlattenMapUtil; import java.util.List; import java.util.Map; public class UnmarshallerContext { private int httpStatus; private Map<String, String> responseMap; private HttpResponse httpResponse; public Integer integerValue(String key) { String value = responseMap.get(key); if (null == value || value.isEmpty()) { return null; } return Integer.valueOf(value); } public String stringValue(String key) { return responseMap.get(key); } public Long longValue(String key) { String value = responseMap.get(key); if (null == value || value.isEmpty()) { return null; } return Long.valueOf(responseMap.get(key)); } public Boolean booleanValue(String key) { String value = responseMap.get(key); if (null == value || value.isEmpty()) { return null; } return Boolean.valueOf(responseMap.get(key)); } public Float floatValue(String key) { String value = responseMap.get(key); if (null == value || value.isEmpty()) { return null; } return Float.valueOf(responseMap.get(key)); } public Double doubleValue(String key) { String value = responseMap.get(key); if (null == value || value.isEmpty()) { return null; } return Double.valueOf(responseMap.get(key)); } public int lengthValue(String key) { String value = responseMap.get(key); if (null == value || value.isEmpty()) { return 0; } return Integer.valueOf(responseMap.get(key)); } public List<Map<Object, Object>> listMapValue(String key) { return FlattenMapUtil.toListMap(responseMap, key); } public Map<Object, Object> mapValue(String key) { return FlattenMapUtil.toMap(responseMap, key); } public int getHttpStatus() { return httpStatus; } public void setHttpStatus(int httpStatus) { this.httpStatus = httpStatus; } public Map<String, String> getResponseMap() { return responseMap; } public void setResponseMap(Map<String, String> responseMap) { this.responseMap = responseMap; } public HttpResponse getHttpResponse() { return httpResponse; } public void setHttpResponse(HttpResponse httpResponse) { this.httpResponse = httpResponse; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/unmarshaller/JsonUnmashaller.java
package com.aliyuncs.unmarshaller; import com.aliyuncs.AcsResponse; import com.aliyuncs.exceptions.ClientException; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; public class JsonUnmashaller implements Unmarshaller { @Override public <T extends AcsResponse> T unmarshal(Class<T> clazz, String content) throws ClientException { try { return (new Gson()).fromJson(content, clazz); } catch (JsonSyntaxException e) { throw newUnmarshalException(clazz, content, e); } } private ClientException newUnmarshalException(Class<?> clazz, String content, Exception e) { return new ClientException("SDK.UnmarshalFailed", "unmarshal response from json content failed, clazz = " + clazz.getSimpleName() + ", origin response = " + content, e); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/unmarshaller/Unmarshaller.java
package com.aliyuncs.unmarshaller; import com.aliyuncs.AcsResponse; import com.aliyuncs.exceptions.ClientException; public interface Unmarshaller { <T extends AcsResponse> T unmarshal(Class<T> clazz, String content) throws ClientException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/unmarshaller/UnmarshallerFactory.java
package com.aliyuncs.unmarshaller; import com.aliyuncs.http.FormatType; public class UnmarshallerFactory { public static Unmarshaller getUnmarshaller(FormatType format) throws IllegalStateException { switch (format) { case JSON: return new JsonUnmashaller(); case XML: return new XmlUnmashaller(); default: throw new IllegalStateException("Unsupported response format: " + format); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/unmarshaller/XmlUnmashaller.java
package com.aliyuncs.unmarshaller; import com.aliyuncs.AcsResponse; import com.aliyuncs.exceptions.ClientException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import java.io.StringReader; public class XmlUnmashaller implements Unmarshaller { @Override public <T extends AcsResponse> T unmarshal(Class<T> clazz, String content) throws ClientException { try { JAXBContext jc = JAXBContext.newInstance(clazz); javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller(); return (T) unmarshaller.unmarshal(new StringReader(content)); } catch (JAXBException e) { throw newUnmarshalException(clazz, content, e); } } private ClientException newUnmarshalException(Class<?> clazz, String xmlContent, Exception e) { return new ClientException("SDK.UnmarshalFailed", "unmarshal response from xml content failed, clazz = " + clazz.getSimpleName() + ", origin response = " + xmlContent, e); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/AuthUtils.java
package com.aliyuncs.utils; import java.io.FileInputStream; import java.io.IOException; public class AuthUtils { private static volatile String clientType = System.getenv("ALIBABA_CLOUD_PROFILE"); private static volatile String environmentAccessKeyId; private static volatile String environmentAccesskeySecret; private static volatile String environmentSecurityToken; private static volatile String environmentECSMetaData; 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 String privateKey; private static volatile String OIDCToken; 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 readFile(String filePath) { FileInputStream in = null; byte[] buffer; try { in = new FileInputStream(filePath); buffer = new byte[in.available()]; in.read(buffer); return new String(buffer, "UTF-8"); } catch (IOException e) { e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Deprecated public static String getPrivateKey(String filePath) { return readFile(filePath); } @Deprecated public static void setPrivateKey(String key) { } public static String getClientType() { if (null == clientType) { AuthUtils.clientType = "default"; } return AuthUtils.clientType; } public static void setClientType(String clientType) { AuthUtils.clientType = clientType; } public static String getEnvironmentAccessKeyId() { if (null == AuthUtils.environmentAccessKeyId) { return System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); } else { return AuthUtils.environmentAccessKeyId; } } public static void setEnvironmentAccessKeyId(String environmentAccessKeyId) { AuthUtils.environmentAccessKeyId = environmentAccessKeyId; } public static String getEnvironmentAccessKeySecret() { if (null == AuthUtils.environmentAccesskeySecret) { return System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); } else { return 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 String getEnvironmentECSMetaData() { if (null == AuthUtils.environmentECSMetaData) { return System.getenv("ALIBABA_CLOUD_ECS_METADATA"); } else { return AuthUtils.environmentECSMetaData; } } public static void setEnvironmentECSMetaData(String environmentECSMetaData) { AuthUtils.environmentECSMetaData = environmentECSMetaData; } public static String getEnvironmentCredentialsFile() { if (null == AuthUtils.environmentCredentialsFile) { return System.getenv("ALIBABA_CLOUD_CREDENTIALS_FILE"); } else { return AuthUtils.environmentCredentialsFile; } } public static void setEnvironmentCredentialsFile(String environmentCredentialsFile) { AuthUtils.environmentCredentialsFile = environmentCredentialsFile; } 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 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-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/Base64Helper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.utils; import java.io.UnsupportedEncodingException; public class Base64Helper { private static final String BASE64_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/"; private static final int[] BASE64_DECODE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; private static byte[] zeroPad(int length, byte[] bytes) { byte[] padded = new byte[length]; System.arraycopy(bytes, 0, padded, 0, bytes.length); return padded; } public synchronized static String encode(byte[] buff) { if (null == buff) { return null; } 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(); } public synchronized static String encode(String string, String encoding) throws UnsupportedEncodingException { if (null == string || null == encoding) { return null; } byte[] stringArray = string.getBytes(encoding); return encode(stringArray); } public synchronized static String decode(String string, String encoding) throws UnsupportedEncodingException { if (null == string || null == encoding) { return null; } int posIndex = 0; int decodeLen = string.endsWith("==") ? (string.length() - 2) : string.endsWith("=") ? (string.length() - 1) : string.length(); byte[] buff = new byte[decodeLen * 3 / 4]; int count4 = decodeLen - decodeLen % 4; for (int i = 0; i < count4; i += 4) { int c0 = BASE64_DECODE[string.charAt(i)]; int c1 = BASE64_DECODE[string.charAt(i + 1)]; int c2 = BASE64_DECODE[string.charAt(i + 2)]; int c3 = BASE64_DECODE[string.charAt(i + 3)]; buff[posIndex++] = (byte) (((c0 << 2) | (c1 >> 4)) & 0xFF); buff[posIndex++] = (byte) ((((c1 & 0xF) << 4) | (c2 >> 2)) & 0xFF); buff[posIndex++] = (byte) ((((c2 & 3) << 6) | c3) & 0xFF); } if (2 <= decodeLen % 4) { int c0 = BASE64_DECODE[string.charAt(count4)]; int c1 = BASE64_DECODE[string.charAt(count4 + 1)]; buff[posIndex++] = (byte) (((c0 << 2) | (c1 >> 4)) & 0xFF); if (3 == decodeLen % 4) { int c2 = BASE64_DECODE[string.charAt(count4 + 2)]; buff[posIndex++] = (byte) ((((c1 & 0xF) << 4) | (c2 >> 2)) & 0xFF); } } return new String(buff, encoding); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/EnvironmentUtils.java
package com.aliyuncs.utils; public class EnvironmentUtils { private static volatile String httpProxy; private static volatile String httpsProxy; private static volatile String noProxy; public static String getHttpProxy() { if (null == httpProxy) { String proxy0 = System.getenv("HTTP_PROXY"); String proxy1 = System.getenv("http_proxy"); return (!StringUtils.isEmpty(proxy0) ? proxy0 : proxy1); } else { return httpProxy; } } public static void setHttpProxy(String httpProxy) { EnvironmentUtils.httpProxy = httpProxy; } public static String getHttpsProxy() { if (null == httpsProxy) { return System.getenv("HTTPS_PROXY"); } else { return httpsProxy; } } public static void setHttpsProxy(String httpsProxy) { EnvironmentUtils.httpsProxy = httpsProxy; } public static String getNoProxy() { if (null == noProxy) { return System.getenv("NO_PROXY"); } else { return noProxy; } } public static void setNoProxy(String noProxy) { EnvironmentUtils.noProxy = noProxy; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/FlattenMapUtil.java
package com.aliyuncs.utils; import java.util.*; public class FlattenMapUtil { public static List<Map<Object, Object>> toListMap(Map<String, String> flattenMap, String prefix) { MapUtils mapUtils = new MapUtils(); return mapUtils.convertMapToListMap(flattenMap, prefix); } public static Map<Object, Object> toMap(Map<String, String> flattenMap, String prefix) { MapUtils mapUtils = new MapUtils(); return mapUtils.convertMapToMap(flattenMap, prefix); } public static Object put(Map<String, String> flattenMap, Object object, String[] subKeys, int subKeysIndex) { if (subKeysIndex >= subKeys.length) { return object; } String key = subKeys[subKeysIndex]; if (key.endsWith("]")) { int index = parseIndex(key); if (index == -1) { return null; } ArrayList<Object> arrayList; if (object == null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < subKeysIndex; i++) { sb.append(subKeys[i]).append("."); } sb.append(key); int length = parseLength(flattenMap, sb.toString()); if (length == -1) { return null; } arrayList = new ArrayList<Object>(Collections.nCopies(length, null)); } else { arrayList = (ArrayList<Object>) object; } if (subKeys.length == subKeysIndex + 1) { arrayList.set(index, flattenMap.get(stringJoin(".", subKeys))); return arrayList; } else { arrayList.set(index, put(flattenMap, arrayList.get(index), subKeys, subKeysIndex + 1)); return arrayList; } } else { HashMap<Object, Object> hashMap; if (object == null) { hashMap = new HashMap<Object, Object>(); } else { hashMap = (HashMap<Object, Object>) object; } if (subKeys.length == subKeysIndex + 1) { hashMap.put(key, flattenMap.get(stringJoin(".", subKeys))); return hashMap; } else { hashMap.put(key, put(flattenMap, hashMap.get(key), subKeys, subKeysIndex + 1)); return hashMap; } } } public static Object putForMap(Map<String, String> flattenMap, Object object, String[] subKeys, int subKeysIndex) { if (subKeysIndex >= subKeys.length) { return object; } String key = subKeys[subKeysIndex]; if (key.endsWith("]")) { int index = parseIndex(key); if (index == -1) { return null; } if (object != null && !(object instanceof HashMap)) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < subKeysIndex; i++) { sb.append(subKeys[i]).append("."); } sb.append(key); int length = parseLength(flattenMap, sb.toString()); if (length == -1) { return null; } String name = parseArrayName(key); ArrayList<Object> arrayList; HashMap<Object, Object> hashMap; if (object != null) { hashMap = (HashMap<Object, Object>) object; if (!(hashMap.get(name) instanceof ArrayList)) { arrayList = new ArrayList<Object>(Collections.nCopies(length, null)); hashMap.put(name, arrayList); } else { arrayList = (ArrayList<Object>) hashMap.get(name); } } else { hashMap = new HashMap<Object, Object>(); arrayList = new ArrayList<Object>(Collections.nCopies(length, null)); hashMap.put(name, arrayList); object = hashMap; } if (subKeys.length == subKeysIndex + 1) { arrayList.set(index, flattenMap.get(stringJoin(".", subKeys))); return object; } else { arrayList.set(index, putForMap(flattenMap, arrayList.get(index), subKeys, subKeysIndex + 1)); return object; } } else { HashMap<Object, Object> hashMap; if (object == null) { hashMap = new HashMap<Object, Object>(); } else { hashMap = (HashMap<Object, Object>) object; } if (subKeys.length == subKeysIndex + 1) { hashMap.put(key, flattenMap.get(stringJoin(".", subKeys))); return hashMap; } else { hashMap.put(key, putForMap(flattenMap, hashMap.get(key), subKeys, subKeysIndex + 1)); return hashMap; } } } public static int parseIndex(String key) { int start = key.indexOf("["); int end = key.indexOf("]"); if (start == -1 || end == -1 || end <= start) { return -1; } try { return Integer.parseInt(key.substring(start + 1, end)); } catch (Exception e) { return -1; } } public static int parseLength(Map<String, String> flattenMap, String key) { int end = key.lastIndexOf("["); if (end == -1) { return -1; } try { return Integer.parseInt(flattenMap.get(key.substring(0, end) + ".Length")); } catch (Exception e) { return -1; } } public static String parseArrayName(String key) { if (key == null) { return null; } int end = key.lastIndexOf("["); if (end == -1) { return null; } return key.substring(0, end); } public static String stringJoin(String delimiter, String... sequences) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < sequences.length; i++) { sb.append(sequences[i]); if (i < sequences.length - 1) { sb.append(delimiter); } } return sb.toString(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/HttpHeadersInjectAdapter.java
package com.aliyuncs.utils; import com.aliyuncs.AcsRequest; import io.opentracing.propagation.TextMap; import java.util.Iterator; import java.util.Map; public class HttpHeadersInjectAdapter implements TextMap { private AcsRequest request ; public HttpHeadersInjectAdapter(AcsRequest request) { this.request = request; } @Override public void put(String key, String value) { request.putHeaderParameter(key, value); } @Override public Iterator<Map.Entry<String, String>> iterator() { throw new UnsupportedOperationException("This class should be used only with tracer#inject()"); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/IOUtils.java
package com.aliyuncs.utils; import java.io.Closeable; import java.io.IOException; public class IOUtils { public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/LogUtils.java
package com.aliyuncs.utils; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.http.HttpResponse; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LogUtils { public final static String REQUEST = "{request}"; public final static String RESPONSE = "{response}"; public final static String TS = "{ts}"; public final static String DATE_ISO_8601 = "{date_iso_8601}"; public final static String DATE_COMMON_LOG = "{date_common_log}"; public final static String HOST = "{host}"; public final static String METHOD = "{method}"; public final static String URI = "{uri}"; public final static String VERSION = "{version}"; public final static String TARGET = "{target}"; public final static String HOSTNAME = "{hostname}"; public final static String CODE = "{code}"; public final static String PHRASE = "{phrase}"; public final static String REQ_HEADERS = "{req_headers}"; public final static String RES_HEADERS = "{res_headers}"; public final static String REQ_BODY = "{req_body}"; public final static String RES_BODY = "{res_body}"; public final static String PID = "{pid}"; public final static String COST = "{cost}"; public final static String START_TIME = "{start_time}"; public final static String TIME = "{time}"; public final static String ERROR = "{error}"; public final static String DEFAULT_LOG_FORMAT = "{method} {uri} HTTP/{version} {code} {cost} {hostname} {pid} {error}"; public final static Pattern REQ_HEADER_PATTERN = Pattern.compile("\\{req_header_(.*?)\\}"); public final static Pattern RES_HEADER_PATTERN = Pattern.compile("\\{res_header_(.*?)\\}"); public static String fillContent(String format, LogUnit logUnit) { String content = format.replace(REQUEST, logUnit.getHttpRequest().toString()) .replace(TS, logUnit.getTs()) .replace(DATE_ISO_8601, logUnit.getTs()) .replace(DATE_COMMON_LOG, logUnit.getTs()) .replace(HOST, logUnit.getHost()) .replace(METHOD, logUnit.getMethod()) .replace(URI, logUnit.getUrl()) .replace(VERSION, logUnit.getVersion()) .replace(TARGET, logUnit.getTarget()) .replace(HOSTNAME, logUnit.getHostname()) .replace(ERROR, logUnit.getError()) .replace(REQ_HEADERS, logUnit.getReqHeaders()) .replace(RES_HEADERS, logUnit.getResHeaders()) .replace(REQ_BODY, logUnit.getReqBody()) .replace(PID, logUnit.getPid()) .replace(COST, logUnit.getCost()) .replace(START_TIME, logUnit.getStartTime()) .replace(TIME, logUnit.getTime()); if (null != logUnit.getHttpResponse()) { content = content.replace(RESPONSE, logUnit.getHttpResponse().toString()). replace(RES_BODY, logUnit.getResBody()). replace(PHRASE, logUnit.getPhrase()). replace(CODE, logUnit.getCode()); } Matcher m = REQ_HEADER_PATTERN.matcher(content); while (m.find()) { String headerKey = m.group(1); if (null != logUnit.getHttpRequest().getHeaderValue(headerKey)) { content = content.replace(m.group(), logUnit.getHttpRequest().getHeaderValue(headerKey)); } } m = RES_HEADER_PATTERN.matcher(content); while (m.find()) { String headerKey = m.group(1); if (null != logUnit.getHttpResponse().getHeaderValue(headerKey)) { content = content.replace(m.group(), logUnit.getHttpResponse().getHeaderValue(headerKey)); } } return content; } public static String utcNow() { return formatLocaleNow(TimeZone.getTimeZone("UTC")); } public static String localeNow() { return formatLocaleNow(TimeZone.getDefault()); } private static String formatLocaleNow(TimeZone tz) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS'Z'"); df.setTimeZone(tz); return df.format(new Date()); } public static long getCurrentPID() { String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); return Long.parseLong(processName.split("@")[0]); } public static String getLocalHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } return "unknown host name"; } public static LogUnit createLogUnit(HttpRequest httpRequest, HttpResponse httpResponse) { return new LogUnit(httpRequest, httpResponse); } public static class LogUnit { private HttpRequest httpRequest; private HttpResponse httpResponse; private String ts; private String host; private String method; private String url; private String version = "1.1"; private String target; private String hostname; private String code; private String phrase; private String reqHeaders; private String resHeaders; private String reqBody; private String resBody; private String pid; private String cost; private String startTime; private String time; private String error; public LogUnit(HttpRequest httpRequest, HttpResponse httpResponse) { this.httpRequest = httpRequest; this.httpResponse = httpResponse; this.ts = utcNow(); try { URL url = new URL(httpRequest.getSysUrl()); this.host = url.getHost(); this.target = ""; String path = url.getPath(); String query = url.getQuery(); String ref = url.getRef(); if (null != path) { this.target += path; } if (null != query) { this.target += "?" + query; } if (null != ref) { this.target += "#" + ref; } } catch (MalformedURLException e) { e.printStackTrace(); } this.method = httpRequest.getSysMethod().name(); this.url = httpRequest.getSysUrl(); this.hostname = getLocalHostName(); this.reqHeaders = httpRequest.getSysHeaders().toString(); try { this.reqBody = httpRequest.getHttpContentString(); if (null != httpResponse) { this.resHeaders = httpResponse.getSysHeaders().toString(); this.code = String.valueOf(httpResponse.getStatus()); this.phrase = (httpResponse.getReasonPhrase() != null ? httpResponse.getReasonPhrase() : ""); this.resBody = httpResponse.getHttpContentString(); } } catch (ClientException e) { e.printStackTrace(); } this.pid = String.valueOf(getCurrentPID()); this.time = localeNow(); } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public HttpRequest getHttpRequest() { return httpRequest; } public void setHttpRequest(HttpRequest httpRequest) { this.httpRequest = httpRequest; } public HttpResponse getHttpResponse() { return httpResponse; } public void setHttpResponse(HttpResponse httpResponse) { this.httpResponse = httpResponse; } public String getTs() { return ts; } public void setTs(String ts) { this.ts = ts; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getReqHeaders() { return reqHeaders; } public void setReqHeaders(String reqHeaders) { this.reqHeaders = reqHeaders; } public String getResHeaders() { return resHeaders; } public void setResHeaders(String resHeaders) { this.resHeaders = resHeaders; } public String getPhrase() { return phrase; } public void setPhrase(String phrase) { this.phrase = phrase; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public String getReqBody() { return reqBody; } public void setReqBody(String reqBody) { this.reqBody = reqBody; } public String getResBody() { return resBody; } public void setResBody(String resBody) { this.resBody = resBody; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getCost() { return cost; } public void setCost(String cost) { this.cost = cost; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/MapUtils.java
package com.aliyuncs.utils; import java.util.*; public class MapUtils { public static String getMapString(Map<String, String> map) { if (map == null) { return ""; } StringBuilder sb = new StringBuilder("{"); for (Map.Entry<String, String> entry : map.entrySet()) { sb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\""); } sb.append("}"); return sb.toString(); } public Map<Object, Object> convertMapToMap(Map<String, String> flattenMap, String prefix) { Object obj = new HashMap<Object, Object>(); obj = parse(obj, flattenMap, prefix); return (Map<Object, Object>) obj; } public List<Map<Object, Object>> convertMapToListMap(Map<String, String> flattenMap, String prefix) { Object obj = new ArrayList<Object>(); obj = parse(obj, flattenMap, prefix); return (List<Map<Object, Object>>) obj; } private Object parse(Object objSource, Map<String, String> flattenMap, String prefix) { Object obj = objSource; for (Map.Entry<String, String> entry : flattenMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key.indexOf(prefix) == 0) { String remainKey = key.replace(prefix, ""); if (!remainKey.toLowerCase().endsWith(".length") && (remainKey.indexOf("[") == 0 || remainKey.indexOf(".") == 0)) { obj = resolve(obj, remainKey, value); } } } return obj; } private Object resolve(Object objSource, String currKey, String value) { Object obj = objSource; if (currKey.equalsIgnoreCase("length") || currKey.equalsIgnoreCase(".length")) { return obj; } String key = popKey(currKey); String remainKey = popRemainKey(currKey); if (remainKey.equalsIgnoreCase("length") || remainKey.equalsIgnoreCase(".length")) { Map currMap = initMap(obj, key); int len = Integer.parseInt(value); List currList = initList(currMap.get(key), len); currMap.put(key, currList); obj = currMap; return obj; } if (remainKey.isEmpty()) { if (key.contains("[")) { int index = getIndexFromKey(key); List currList = initList(obj, index); currList.set(index, value); obj = currList; } else { Map currMap = initMap(obj, key); currMap.put(key, value); obj = currMap; } return obj; } if (key.contains("[")) { int index = getIndexFromKey(key); List currList = initList(obj, index); Object newObj = currList.get(index); currList.set(index, resolve(newObj, remainKey, value)); obj = currList; } else { Map currMap = initMap(obj, key); currMap.put(key, resolve(currMap.get(key), remainKey, value)); obj = currMap; } return obj; } private Map initMap(Object obj, String key) { Map currMap = (Map) obj; if (null == currMap) { currMap = new HashMap<Object, Object>(); } if (!currMap.containsKey(key)) { currMap.put(key, null); } return currMap; } private List initList(Object obj, int index) { List currList = (List) obj; if (null == currList) { currList = new ArrayList<Object>(); } while (currList.size() <= index) { currList.add(null); } return currList; } private int getIndexFromKey(String key) { return Integer.parseInt(key.replace("[", "").replace("]", "")); } private String getMapKeyFromListIndex(String key) { return key.substring(0, key.indexOf("[")); } private String popKey(String keyString) { String key = keyString; if (key.startsWith(".")) { key = key.substring(1); } String[] keys = key.split("\\."); key = keys[0]; if (key.contains("[") && key.indexOf("[") != 0) { return getMapKeyFromListIndex(key); } return key; } private String popRemainKey(String keyString) { String key = keyString; if (key.startsWith(".")) { key = key.substring(1); } String popKey = popKey(key); if (popKey.endsWith("Length")) { return ""; } String remainKey = key.substring(popKey.length()); if (remainKey.startsWith(".")) { remainKey = remainKey.substring(1); } return remainKey; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/ParameterHelper.java
package com.aliyuncs.utils; import com.google.gson.Gson; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; import java.util.Random; public class ParameterHelper { private final static String TIME_ZONE = "GMT"; private final static String FORMAT_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss'Z'"; private final static String FORMAT_RFC2616 = "EEE, dd MMM yyyy HH:mm:ss zzz"; public final static String PATTERN = "^[a-zA-Z0-9_-]+$"; private static AtomicLong seqId = new AtomicLong(0); private static final long processStartTime = System.currentTimeMillis(); public ParameterHelper() { } public static String getUniqueNonce() { // thread id long threadId = Thread.currentThread().getId(); // timestamp: ms long currentTime = System.currentTimeMillis(); // sequence number Random random = new Random(); long seq = seqId.getAndIncrement(); long rand = random.nextLong(); StringBuffer sb = new StringBuffer(); sb.append(processStartTime).append('-') .append(threadId).append('-') .append(currentTime).append('-') .append(seq).append('-') .append(rand); try { // hash MessageDigest digest = MessageDigest.getInstance("MD5"); // hex byte[] msg = sb.toString().getBytes(); sb.setLength(0); for (byte b : digest.digest(msg)) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage(), e); } return sb.toString(); } public static void validateParameter(String parameter, String parameterName) { if (null == parameter || "".equals(parameter.trim())) { return; } if (Pattern.matches(ParameterHelper.PATTERN, parameter)) { return; } throw new RuntimeException("The parameter " + parameterName + " not match with " + ParameterHelper.PATTERN); } 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 String getRFC2616Date(Date date) { SimpleDateFormat df = new SimpleDateFormat(FORMAT_RFC2616, Locale.ENGLISH); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); return df.format(date); } public static Date parse(String strDate) throws ParseException { if (null == strDate || "".equals(strDate)) { return null; } // The format contains 4 ' if (strDate.length() == FORMAT_ISO8601.length() - 4) { return parseISO8601(strDate); } else if (strDate.length() == FORMAT_RFC2616.length()) { return parseRFC2616(strDate); } return null; } public static Date parseISO8601(String strDate) throws ParseException { if (null == strDate || "".equals(strDate)) { return null; } // The format contains 4 ' symbol if (strDate.length() != (FORMAT_ISO8601.length() - 4)) { return null; } SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); return df.parse(strDate); } public static Date parseRFC2616(String strDate) throws ParseException { if (null == strDate || "".equals(strDate) || strDate.length() != FORMAT_RFC2616.length()) { return null; } SimpleDateFormat df = new SimpleDateFormat(FORMAT_RFC2616, Locale.ENGLISH); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); return df.parse(strDate); } public static String md5Sum(byte[] buff) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(buff); return Base64Helper.encode(messageDigest); } catch (Exception e) { // TODO: should not eat the excepiton } return null; } public static byte[] getXmlData(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder xml = new StringBuilder(); xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); xml.append("<" + entry.getKey() + ">"); xml.append(entry.getValue()); xml.append("</" + entry.getKey() + ">"); } return xml.toString().getBytes("UTF-8"); } public static byte[] getJsonData(Map<String, String> params) throws UnsupportedEncodingException { String json = new Gson().toJson(params); return json.getBytes("UTF-8"); } public static byte[] getFormData(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) { first = false; } else { result.append("&"); } result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString().getBytes("UTF-8"); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/ProfileUtils.java
package com.aliyuncs.utils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.*; 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 final static Log log = LogFactory.getLog(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())) { log.warn("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; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/StringUtils.java
package com.aliyuncs.utils; public class StringUtils { public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } public static String join(String delimiter, Iterable<? extends String> elements) { if (isEmpty(delimiter) || elements == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(); for (String value : elements) { stringBuilder.append(value); stringBuilder.append(delimiter); } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/TraceUtils.java
package com.aliyuncs.utils; import io.opentracing.Span; import io.opentracing.tag.Tags; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; public class TraceUtils { public static void onError(Throwable throwable, Span span) { Tags.ERROR.set(span, Boolean.TRUE); if (throwable != null) { span.log(errorLogs(throwable)); } } private static Map<String, Object> errorLogs(Throwable throwable) { Map<String, Object> errorLogs = new HashMap<String, Object>(10); errorLogs.put("event", Tags.ERROR.getKey()); errorLogs.put("error.object", throwable); errorLogs.put("error.kind", throwable.getClass().getName()); String message = throwable.getCause() != null ? throwable.getCause().getMessage() : throwable.getMessage(); if (message != null) { errorLogs.put("message", message); } StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw)); errorLogs.put("stack", sw.toString()); return errorLogs; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core/4.7.6/com/aliyuncs/utils/XmlUtils.java
package com.aliyuncs.utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; public final class XmlUtils { public static Document getDocument(String payload) throws ParserConfigurationException, SAXException, IOException { if (payload == null || payload.length() < 1) { return null; } StringReader sr = new StringReader(payload); InputSource source = new InputSource(sr); Document doc; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); doc = builder.parse(source); } finally { IOUtils.closeQuietly(source.getByteStream()); } return doc; } public static Element getRootElementFromString(String payload) throws ParserConfigurationException, SAXException, IOException { Document doc = getDocument(payload); if (doc == null) { return null; } return doc.getDocumentElement(); } public static List<Element> getChildElements(Element parent, String tagName) { if (null == parent) { return null; } NodeList nodes = parent.getElementsByTagName(tagName); List<Element> elements = new ArrayList<Element>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getParentNode() == parent) { elements.add((Element) node); } } return elements; } public static List<Element> getChildElements(Element parent) { if (null == parent) { return null; } NodeList nodes = parent.getChildNodes(); List<Element> elements = new ArrayList<Element>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { elements.add((Element) node); } } return elements; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/AcsError.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import com.aliyuncs.transform.UnmarshallerContext; public class AcsError extends AcsResponse{ private int statusCode; private String errorCode; private String errorMessage; private String 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 int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } @Override public AcsError getInstance(UnmarshallerContext context) { return AcsErrorUnmarshaller.unmarshall(this, context); } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/AcsErrorUnmarshaller.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.util.Map; import com.aliyuncs.transform.UnmarshallerContext; public class AcsErrorUnmarshaller { public static AcsError unmarshall(AcsError error, UnmarshallerContext context) { Map<String,String> map = context.getResponseMap(); error.setStatusCode(context.getHttpStatus()); error.setRequestId(map.get("Error.RequestId")); error.setErrorCode(map.get("Error.Code")); error.setErrorMessage(map.get("Error.Message")); return error; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/AcsRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.http.ProtocolType; import com.aliyuncs.regions.ProductDomain; import com.aliyuncs.auth.AcsURLEncoder; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISignatureComposer; import com.aliyuncs.auth.ISigner; public abstract class AcsRequest<T extends AcsResponse> extends HttpRequest { private String version = null; private String product = null; private String actionName = null; private String regionId = null; private String securityToken = null; private FormatType acceptFormat = null; protected ISignatureComposer composer = null; private ProtocolType protocol = ProtocolType.HTTP; private Map<String, String> queryParameters = new HashMap<String, String>(); private Map<String, String> domainParameters = new HashMap<String, String>(); private String serviceCode; private String endpointType; public AcsRequest(String product) { super(null); this.headers.put("x-sdk-client", "Java/2.0.0"); this.product = product; } public AcsRequest(String product, String version) { super(null); this.product = product; this.setVersion(version); } public String getServiceCode() { return serviceCode; } public void setServiceCode(String serviceCode) { this.serviceCode = serviceCode; } public String getEndpointType() { return endpointType; } public void setEndpointType(String endpointType) { this.endpointType = endpointType; } public String getActionName() { return actionName; } public void setActionName(String actionName) { this.actionName = actionName; } public String getProduct() { return product; } public ProtocolType getProtocol() { return protocol; } public void setProtocol(ProtocolType protocol) { this.protocol = protocol; } public Map<String, String> getQueryParameters() { return Collections.unmodifiableMap(queryParameters); } public <K> void putQueryParameter(String name, K value) { setParameter(this.queryParameters, name, value); } protected void putQueryParameter(String name, String value) { setParameter(this.queryParameters, name, value); } public Map<String, String> getDomainParameters() { return Collections.unmodifiableMap(domainParameters); } protected void putDomainParameter(String name, Object value) { setParameter(this.domainParameters, name, value); } protected void putDomainParameter(String name, String value) { setParameter(this.domainParameters, name, value); } protected <K> void setParameter(Map<String, String> map, String name, K value) { if (null == map || null == name || null == value){ return; } map.put(name,String.valueOf(value)); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public FormatType getAcceptFormat() { return acceptFormat; } public void setAcceptFormat(FormatType acceptFormat) { this.acceptFormat = acceptFormat; this.putHeaderParameter("Accept", FormatType.mapFormatToAccept(acceptFormat)); } public String getRegionId() { return regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public String getSecurityToken() { return securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; } public static String concatQueryString(Map<String, String> parameters) throws UnsupportedEncodingException { if (null == parameters) return null; StringBuilder urlBuilder = new StringBuilder(""); for(Entry<String, String> entry : parameters.entrySet()){ String key = entry.getKey(); String val = entry.getValue(); urlBuilder.append(AcsURLEncoder.encode(key)); if (val != null){ urlBuilder.append("=").append(AcsURLEncoder.encode(val)); } urlBuilder.append("&"); } int strIndex = urlBuilder.length(); if (parameters.size() > 0) urlBuilder.deleteCharAt(strIndex - 1); return urlBuilder.toString(); } public abstract HttpRequest signRequest(ISigner signer, Credential credential, FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException; public abstract String composeUrl(String endpoint, Map<String, String> queries) throws UnsupportedEncodingException; public abstract Class<T> getResponseClass(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/AcsResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.transform.UnmarshallerContext; public abstract class AcsResponse { public abstract AcsResponse getInstance(UnmarshallerContext context) throws ClientException, ServerException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/DefaultAcsClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.concurrent.TimeoutException; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.http.HttpResponse; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.reader.Reader; import com.aliyuncs.reader.ReaderFactory; import com.aliyuncs.regions.Endpoint; import com.aliyuncs.regions.ProductDomain; import com.aliyuncs.transform.UnmarshallerContext; public class DefaultAcsClient implements IAcsClient{ private int maxRetryNumber = 3; private boolean autoRetry = true; private IClientProfile clientProfile = null; public DefaultAcsClient() { this.clientProfile = DefaultProfile.getProfile(); } public DefaultAcsClient(IClientProfile profile) { this.clientProfile = profile; } public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request) throws ClientException, ServerException { return this.doAction(request, autoRetry, maxRetryNumber, this.clientProfile); } public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ClientException, ServerException { return this.doAction(request, autoRetry, maxRetryCounts, this.clientProfile); } public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, IClientProfile profile) throws ClientException, ServerException { return this.doAction(request, this.autoRetry, this.maxRetryNumber, profile); } public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, String regionId, Credential credential) throws ClientException, ServerException { boolean retry = this.autoRetry; int retryNumber = this.maxRetryNumber; ISigner signer = null; FormatType format = null; List<Endpoint> endpoints = null; if (null != this.clientProfile) { signer = clientProfile.getSigner(); format = clientProfile.getFormat(); try { endpoints = clientProfile.getEndpoints(request.getProduct(), request.getServiceCode(), request.getEndpointType()); } catch (Throwable e) { endpoints = clientProfile.getEndpoints(); } } return this.doAction(request, retry, retryNumber, regionId, credential, signer, format, endpoints); } public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request) throws ServerException, ClientException{ HttpResponse baseResponse = this.doAction(request); return parseAcsResponse(request.getResponseClass(), baseResponse); } public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ServerException, ClientException{ HttpResponse baseResponse = this.doAction(request, autoRetry, maxRetryCounts); return parseAcsResponse(request.getResponseClass(), baseResponse); } public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request,IClientProfile profile) throws ServerException, ClientException{ HttpResponse baseResponse = this.doAction(request, profile); return parseAcsResponse(request.getResponseClass(), baseResponse); } public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId, Credential credential) throws ServerException, ClientException { HttpResponse baseResponse = this.doAction(request, regionId, credential); return parseAcsResponse(request.getResponseClass(), baseResponse); } public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts, IClientProfile profile) throws ClientException, ServerException { if (null == profile){ throw new ClientException("SDK.InvalidProfile", "No active profile found."); } boolean retry = autoRetry; int retryNumber = maxRetryCounts; String region = profile.getRegionId(); Credential credential = profile.getCredential(); ISigner signer = profile.getSigner(); FormatType format = profile.getFormat(); List<Endpoint> endpoints; try { endpoints = clientProfile.getEndpoints(request.getProduct(), request.getServiceCode(), request.getEndpointType()); } catch (Throwable e) { endpoints = clientProfile.getEndpoints(); } return this.doAction(request, retry, retryNumber, region, credential, signer, format, endpoints); } private <T extends AcsResponse> T parseAcsResponse(Class<T> clasz, HttpResponse baseResponse) throws ServerException, ClientException { FormatType format = baseResponse.getContentType(); if (baseResponse.isSuccess()) { return readResponse(clasz, baseResponse, format); } else { AcsError error = readError(baseResponse, format); if (500 <= baseResponse.getStatus()){ throw new ServerException(error.getErrorCode(), error.getErrorMessage(), error.getRequestId()); } else{ throw new ClientException(error.getErrorCode(), error.getErrorMessage(), error.getRequestId()); } } } public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber, String regionId, Credential credential, ISigner signer, FormatType format, List<Endpoint> endpoints) throws ClientException, ServerException { try { FormatType requestFormatType = request.getAcceptFormat(); if (null != requestFormatType){ format = requestFormatType; } if(null == request.getRegionId()){ request.setRegionId(regionId); } ProductDomain domain = Endpoint.findProductDomain(regionId, request.getProduct(), endpoints); if (null == domain){ throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access."); } HttpRequest httpRequest = request.signRequest(signer, credential, format, domain); int retryTimes = 1; HttpResponse response = HttpResponse.getResponse(httpRequest); while (500 <= response.getStatus() && autoRetry && retryTimes < maxRetryNumber) { httpRequest = request.signRequest(signer, credential, format, domain); response = HttpResponse.getResponse(httpRequest); retryTimes ++; } return response; } catch (InvalidKeyException exp) { throw new ClientException("SDK.InvalidAccessSecret","Speicified access secret is not valid."); }catch (SocketTimeoutException exp){ throw new ClientException("SDK.ServerUnreachable","SocketTimeoutException has occurred on a socket read or accept."); }catch (IOException exp) { throw new ClientException("SDK.ServerUnreachable", "Speicified endpoint or uri is not valid."); } catch (NoSuchAlgorithmException exp) { throw new ClientException("SDK.InvalidMD5Algorithm", "MD5 hash is not supported by client side."); } } private <T extends AcsResponse> T readResponse(Class<T> clasz, HttpResponse httpResponse, FormatType format) throws ClientException { Reader reader = ReaderFactory.createInstance(format); UnmarshallerContext context = new UnmarshallerContext(); T response = null; String stringContent = getResponseContent(httpResponse); try { response = clasz.newInstance(); } catch (Exception e) { throw new ClientException("SDK.InvalidResponseClass", "Unable to allocate "+ clasz.getName() + " class"); } String responseEndpoint= clasz.getName().substring(clasz.getName().lastIndexOf(".") + 1); context.setResponseMap(reader.read(stringContent,responseEndpoint)); context.setHttpResponse(httpResponse); response.getInstance(context); return response; } private String getResponseContent(HttpResponse httpResponse) throws ClientException { String stringContent = null; try { if(null == httpResponse.getEncoding()){ stringContent = new String(httpResponse.getContent()); } else { stringContent = new String(httpResponse.getContent(), httpResponse.getEncoding()); } } catch(UnsupportedEncodingException exp) { throw new ClientException("SDK.UnsupportedEncoding", "Can not parse response due to un supported encoding."); } return stringContent; } private AcsError readError(HttpResponse httpResponse, FormatType format) throws ClientException { AcsError error = new AcsError(); String responseEndpoint= "Error"; Reader reader = ReaderFactory.createInstance(format); UnmarshallerContext context = new UnmarshallerContext(); String stringContent = getResponseContent(httpResponse); context.setResponseMap(reader.read(stringContent,responseEndpoint)); return error.getInstance(context); } public boolean isAutoRetry() { return autoRetry; } public void setAutoRetry(boolean autoRetry) { this.autoRetry = autoRetry; } public int getMaxRetryNumber() { return maxRetryNumber; } public void setMaxRetryNumber(int maxRetryNumber) { this.maxRetryNumber = maxRetryNumber; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/IAcsClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.util.List; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpResponse; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.regions.Endpoint; public interface IAcsClient { public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request) throws ClientException, ServerException ; public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ClientException, ServerException ; public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, IClientProfile profile) throws ClientException, ServerException; public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, String regionId, Credential credential) throws ClientException, ServerException; public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request) throws ServerException, ClientException; public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ServerException, ClientException; public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, IClientProfile profile) throws ServerException, ClientException; public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId, Credential credential) throws ServerException, ClientException; public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts, IClientProfile profile) throws ClientException, ServerException; public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber, String regionId, Credential credential, ISigner signer, FormatType format, List<Endpoint> endpoints) throws ClientException, ServerException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/OssAcsRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.auth.OssSignatureComposer; import com.aliyuncs.auth.RoaSignatureComposer; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.regions.ProductDomain; public abstract class OssAcsRequest<T extends AcsResponse> extends RoaAcsRequest<T> { private String bucketName = null; public OssAcsRequest(String product, String actionName) { super(product); this.setActionName(actionName); this.composer = OssSignatureComposer.getComposer(); } @Override public void setVersion(String version) { } @Override public String composeUrl(String endpoint, Map<String, String> queries) throws UnsupportedEncodingException{ Map<String, String> mapQueries = queries == null?this.getQueryParameters():queries; StringBuilder urlBuilder = new StringBuilder(""); urlBuilder.append(this.getProtocol().toString()); urlBuilder.append("://"); if (null != this.bucketName) urlBuilder.append(this.bucketName).append("."); urlBuilder.append(endpoint); if (null != this.uriPattern) urlBuilder.append( RoaSignatureComposer.replaceOccupiedParameters (uriPattern, this.getPathParameters())); if (-1 == urlBuilder.indexOf("?")) urlBuilder.append("?"); String query = concatQueryString(mapQueries); return urlBuilder.append(query).toString(); } @Override public HttpRequest signRequest(ISigner signer, Credential credential, FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException { Map<String, String> imutableMap = new HashMap<String, String>(this.getHeaders()); if (null != signer && null != credential) { String accessKeyId = credential.getAccessKeyId(); String accessSecret = credential.getAccessSecret(); imutableMap = this.composer.refreshSignParameters (this.getHeaders(), signer, accessKeyId, format); String uri = this.uriPattern; if (null != this.bucketName){ uri = "/" + bucketName + uri; } String strToSign = this.composer.composeStringToSign(this.getMethod(), uri, signer, this.getQueryParameters(), imutableMap, this.getPathParameters()); String signature = signer.signString(strToSign, accessSecret); imutableMap.put("Authorization", "OSS "+ accessKeyId+":"+signature); } HttpRequest request = new HttpRequest( this.composeUrl(domain.getDomianName(), this.getQueryParameters()), imutableMap); request.setMethod(this.getMethod()); request.setContent(this.getContent(), this.getEncoding(), this.getContentType()); return request; } public abstract Class<T> getResponseClass(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/RoaAcsRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.auth.RoaSignatureComposer; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.regions.ProductDomain; public abstract class RoaAcsRequest<T extends AcsResponse> extends AcsRequest<T>{ protected String uriPattern = null; private Map<String, String> pathParameters = new HashMap<String, String>(); public RoaAcsRequest(String product) { super(product); initialize(); } public RoaAcsRequest(String product, String version) { super(product, version); this.setVersion(version); initialize(); } public RoaAcsRequest(String product, String version, String action) { super(product); this.setVersion(version); this.setActionName(action); initialize(); } public RoaAcsRequest(String product, String version, String action, String serviceCode) { super(product); this.setVersion(version); this.setActionName(action); this.setServiceCode(serviceCode); initialize(); } public RoaAcsRequest(String product, String version, String action, String serviceCode, String endpointType) { super(product); this.setVersion(version); this.setActionName(action); this.setServiceCode(serviceCode); this.setEndpointType(endpointType); initialize(); } private void initialize() { this.composer = RoaSignatureComposer.getComposer(); this.setContent(new byte[0], "utf-8", FormatType.RAW); } @Override public void setVersion(String version) { super.setVersion(version); this.putHeaderParameter("x-acs-version", version); } @Override public void setSecurityToken(String securityToken) { super.setSecurityToken(securityToken); this.putHeaderParameter("x-acs-security-token", securityToken); } public Map<String, String> getPathParameters() { return Collections.unmodifiableMap(pathParameters); } protected void putPathParameter(String name, Object value) { setParameter(this.pathParameters, name, value); } protected void putPathParameter(String name, String value) { setParameter(this.pathParameters, name, value); } public String composeUrl(String endpoint, Map<String, String> queries) throws UnsupportedEncodingException{ Map<String, String> mapQueries = (queries == null) ? this.getQueryParameters():queries; StringBuilder urlBuilder = new StringBuilder(""); urlBuilder.append(this.getProtocol().toString()); urlBuilder.append("://").append(endpoint); if (null != this.uriPattern){ urlBuilder.append(RoaSignatureComposer.replaceOccupiedParameters(uriPattern, this.getPathParameters())); } if (-1 == urlBuilder.indexOf("?")){ urlBuilder.append("?"); } else if(!urlBuilder.toString().endsWith("?")) { urlBuilder.append("&"); } String query = concatQueryString(mapQueries); String url = urlBuilder.append(query).toString(); if(url.endsWith("?") || url.endsWith("&")){ url = url.substring(0, url.length()-1); } return url; } public String getUriPattern() { return uriPattern; } public void setUriPattern(String uriPattern) { this.uriPattern = uriPattern; } @Override public HttpRequest signRequest(ISigner signer, Credential credential, FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException { Map<String, String> imutableMap = new HashMap<String, String>(this.getHeaders()); if (null != signer && null != credential) { String accessKeyId = credential.getAccessKeyId(); String accessSecret = credential.getAccessSecret(); imutableMap = this.composer.refreshSignParameters(this.getHeaders(), signer, accessKeyId, format); String strToSign = this.composer.composeStringToSign(this.getMethod(), this.getUriPattern(), signer, this.getQueryParameters(), imutableMap, this.getPathParameters()); String signature = signer.signString(strToSign, accessSecret); imutableMap.put("Authorization", "acs "+ accessKeyId+":"+signature); } this.setUrl(this.composeUrl(domain.getDomianName(), this.getQueryParameters())); this.headers = imutableMap; return this; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/RpcAcsRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.util.HashMap; import java.util.Map; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.auth.RpcSignatureComposer; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.regions.ProductDomain; public abstract class RpcAcsRequest<T extends AcsResponse> extends AcsRequest<T> { public RpcAcsRequest(String product) { super(product); initialize(); } public RpcAcsRequest(String product, String version) { super(product); this.setVersion(version); initialize(); } public RpcAcsRequest(String product, String version, String action) { super(product); this.setVersion(version); this.setActionName(action); initialize(); } public RpcAcsRequest(String product, String version, String action, String serviceCode) { super(product); this.setVersion(version); this.setActionName(action); this.setServiceCode(serviceCode); initialize(); } public RpcAcsRequest(String product, String version, String action, String serviceCode, String endpointType) { super(product); this.setVersion(version); this.setActionName(action); this.setServiceCode(serviceCode); this.setEndpointType(endpointType); initialize(); } private void initialize() { this.setMethod(MethodType.GET); this.setAcceptFormat(FormatType.XML); this.composer = RpcSignatureComposer.getComposer(); } @Override public void setActionName(String actionName) { super.setActionName(actionName); this.putQueryParameter("Action", actionName); } @Override public void setVersion(String version) { super.setVersion(version); this.putQueryParameter("Version", version); } @Override public void setSecurityToken(String securityToken) { super.setSecurityToken(securityToken); this.putQueryParameter("SecurityToken", securityToken); } @Override public void setAcceptFormat(FormatType acceptFormat) { super.setAcceptFormat(acceptFormat); this.putQueryParameter("Format", acceptFormat.toString()); } public String composeUrl(String endpoint, Map<String, String> queries) throws UnsupportedEncodingException{ Map<String, String> mapQueries = (queries == null) ? this.getQueryParameters():queries; StringBuilder urlBuilder = new StringBuilder(""); urlBuilder.append(this.getProtocol().toString()); urlBuilder.append("://").append(endpoint); if (-1 == urlBuilder.indexOf("?")){ urlBuilder.append("/?"); } String query = concatQueryString(mapQueries); return urlBuilder.append(query).toString(); } @Override public HttpRequest signRequest(ISigner signer, Credential credential,FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException { Map<String, String> imutableMap = new HashMap<String, String>(this.getQueryParameters()); if (null != signer && null != credential) { String accessKeyId = credential.getAccessKeyId(); String accessSecret = credential.getAccessSecret(); imutableMap = this.composer.refreshSignParameters (this.getQueryParameters(), signer, accessKeyId, format); imutableMap.put("RegionId", getRegionId()); String strToSign = this.composer.composeStringToSign (this.getMethod(), null, signer, imutableMap, null, null); String signature = signer.signString(strToSign, accessSecret + "&"); imutableMap.put("Signature", signature); } setUrl(this.composeUrl(domain.getDomianName(), imutableMap)); return this; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/AcsURLEncoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; 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) throws UnsupportedEncodingException { return URLEncoder.encode(value, URL_ENCODING); } public static String percentEncode(String value) throws UnsupportedEncodingException{ return value != null ? URLEncoder.encode(value, URL_ENCODING).replace("+", "%20") .replace("*", "%2A").replace("%7E", "~") : null; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/Credential.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.util.Calendar; import java.util.Date; public class Credential { private Date refreshDate; private Date expiredDate; private String accessKeyId; private String accessSecret; private String securityToken; public Credential() { this.refreshDate = new Date(); } public Credential(String keyId, String secret) { this.accessKeyId = keyId; this.accessSecret = secret; this.refreshDate = new Date(); } public Credential(String keyId, String secret, int expiredHours) { this.accessKeyId = keyId; this.accessSecret = secret; this.refreshDate = new Date(); setExpiredDate(expiredHours); } private void setExpiredDate(int expiredHours) { if (expiredHours > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.HOUR, expiredHours); expiredDate = cal.getTime(); } } public String getAccessKeyId() { return accessKeyId; } public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; } public String getAccessSecret() { return accessSecret; } public void setAccessSecret(String accessSecret) { this.accessSecret = accessSecret; } public boolean isExpired() { if (this.expiredDate == null){ return false; } if (this.expiredDate.after(new Date())){ return false; } return true; } public String getSecurityToken() { return securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; } public Date getRefreshDate() { return refreshDate; } public Date getExpiredDate() { return expiredDate; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/ICredentialProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; public interface ICredentialProvider { public Credential fresh(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/ISignatureComposer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.util.Map; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.MethodType; public interface ISignatureComposer { public Map<String, String> refreshSignParameters(Map<String, String> parameters, ISigner signer, String accessKeyId, FormatType format); public String composeStringToSign(MethodType method, String uriPattern,ISigner signer, Map<String, String> queries, Map<String, String> headers, Map<String, String> paths); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/ISigner.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.security.InvalidKeyException; public interface ISigner { public String getSignerName(); public String getSignerVersion(); public String signString(String source, String accessSecret) throws InvalidKeyException, IllegalStateException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/OssSignatureComposer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.util.HashMap; import java.util.Map; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.MethodType; import com.aliyuncs.utils.ParameterHelper; public class OssSignatureComposer extends RoaSignatureComposer { private static ISignatureComposer composer = null; @Override public Map<String, String> refreshSignParameters(Map<String, String> parameters, ISigner signer, String accessKeyId, FormatType format) { Map<String, String> immutableMap = new HashMap<String, String>(parameters); immutableMap.put("Date", ParameterHelper.getRFC2616Date(null)); return immutableMap; } private String buildQueryString(String uri, Map<String, String> queries) { StringBuilder queryBuilder = new StringBuilder(uri); if (0 < queries.size()) queryBuilder.append("?"); for (Map.Entry<String, String> e : queries.entrySet()) { queryBuilder.append(e.getKey()); if(null != e.getValue()) queryBuilder.append("=").append(e.getValue()); queryBuilder.append(QUERY_SEPARATOR); } String queryString = queryBuilder.toString(); if (queryString.endsWith(QUERY_SEPARATOR)) queryString = queryString.substring(0, queryString.length() - 1); return queryString; } public String composeStringToSign(MethodType method, String uriPattern, ISigner signer, Map<String, String> queries, Map<String, String> headers, Map<String, String> paths) { StringBuilder sb = new StringBuilder(); sb.append(method).append(HEADER_SEPARATOR); if (headers.get("Content-MD5") != null) { sb.append(headers.get("Content-MD5")); } sb.append(HEADER_SEPARATOR); if (headers.get("Content-Type") != null) { sb.append(headers.get("Content-Type")); } sb.append(HEADER_SEPARATOR); if (headers.get("Date") != null) { sb.append(headers.get("Date")); } sb.append(HEADER_SEPARATOR); sb.append(buildCanonicalHeaders(headers, "x-oss-")); sb.append(buildQueryString(uriPattern, queries)); return sb.toString(); } public static ISignatureComposer getComposer() { if (null == composer) composer = new OssSignatureComposer(); return composer; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/RoaSignatureComposer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.MethodType; import com.aliyuncs.utils.ParameterHelper; public class RoaSignatureComposer implements ISignatureComposer { private static ISignatureComposer composer = null; protected final static String QUERY_SEPARATOR = "&"; protected final static String HEADER_SEPARATOR = "\n"; public Map<String, String> refreshSignParameters(Map<String, String> parameters, ISigner signer, String accessKeyId, FormatType format) { Map<String, String> immutableMap = new HashMap<String, String>(parameters); immutableMap.put("Date", ParameterHelper.getRFC2616Date(null)); if (null == format) format = FormatType.RAW; immutableMap.put("Accept", FormatType.mapFormatToAccept(format)); immutableMap.put("x-acs-signature-method", signer.getSignerName()); immutableMap.put("x-acs-signature-version",signer.getSignerVersion()); return immutableMap; } private String[] splitSubResource(String uri) { int queIndex = uri.indexOf("?"); String[] uriParts = new String[2]; if ( -1 != queIndex ) { uriParts[0] = uri.substring(0, queIndex); uriParts[1] = uri.substring(queIndex + 1); } else uriParts[0] = uri; return uriParts; } private String buildQueryString(String uri, Map<String, String> queries) { String[] uriParts = splitSubResource(uri); Map<String, String> sortMap = new TreeMap<String, String>(queries); if (null != uriParts[1]){ sortMap.put(uriParts[1], null); } StringBuilder queryBuilder = new StringBuilder(uriParts[0]); if (0 < sortMap.size()){ queryBuilder.append("?"); } for (Map.Entry<String, String> e : sortMap.entrySet()) { queryBuilder.append(e.getKey()); if(null != e.getValue()){ queryBuilder.append("=").append(e.getValue()); } queryBuilder.append(QUERY_SEPARATOR); } String queryString = queryBuilder.toString(); if (queryString.endsWith(QUERY_SEPARATOR)){ queryString = queryString.substring(0, queryString.length() - 1); } return queryString; } protected String buildCanonicalHeaders(Map<String, String> headers, String headerBegin) { Map<String, String> sortMap = new TreeMap<String, String>(); for (Map.Entry<String, String> e : headers.entrySet()) { String key = e.getKey().toLowerCase(); String val = e.getValue(); if (key.startsWith(headerBegin)){ sortMap.put(key, val); } } StringBuilder headerBuilder = new StringBuilder(); for (Map.Entry<String, String> e : sortMap.entrySet()) { headerBuilder.append(e.getKey()); headerBuilder.append(':').append(e.getValue()); headerBuilder.append(HEADER_SEPARATOR); } return headerBuilder.toString(); } public static String replaceOccupiedParameters(String url, Map<String, String> paths) { String result = url; for (Map.Entry<String, String> entry: paths.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String target = "[" + key + "]"; result = result.replace(target, value); } return result; } public String composeStringToSign(MethodType method, String uriPattern,ISigner signer, Map<String, String> queries, Map<String, String> headers, Map<String, String> paths) { StringBuilder sb = new StringBuilder(); sb.append(method).append(HEADER_SEPARATOR); if (headers.get("Accept") != null) { sb.append(headers.get("Accept")); } sb.append(HEADER_SEPARATOR); if (headers.get("Content-MD5") != null) { sb.append(headers.get("Content-MD5")); } sb.append(HEADER_SEPARATOR); if (headers.get("Content-Type") != null) { sb.append(headers.get("Content-Type")); } sb.append(HEADER_SEPARATOR); if (headers.get("Date") != null) { sb.append(headers.get("Date")); } sb.append(HEADER_SEPARATOR); String uri = replaceOccupiedParameters(uriPattern, paths); sb.append(buildCanonicalHeaders(headers, "x-acs-")); sb.append(buildQueryString(uri, queries)); return sb.toString(); } public static ISignatureComposer getComposer() { if (null == composer){ composer = new RoaSignatureComposer(); } return composer; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/RpcSignatureComposer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.MethodType; import com.aliyuncs.utils.ParameterHelper; public class RpcSignatureComposer implements ISignatureComposer { private static ISignatureComposer composer = null; private final static String SEPARATOR = "&"; private RpcSignatureComposer() { } public Map<String, String> refreshSignParameters(Map<String, String> parameters, ISigner signer, String accessKeyId, FormatType format) { Map<String, String> immutableMap = new HashMap<String, String>(parameters); immutableMap.put("Timestamp", ParameterHelper.getISO8601Time(null)); immutableMap.put("SignatureMethod", signer.getSignerName()); immutableMap.put("SignatureVersion",signer.getSignerVersion()); immutableMap.put("SignatureNonce", ParameterHelper.getUniqueNonce()); immutableMap.put("AccessKeyId", accessKeyId); if (null != format) immutableMap.put("Format", format.toString()); return immutableMap; } public String composeStringToSign(MethodType method, String uriPattern, ISigner signer, Map<String, String> queries, Map<String, String> headers, Map<String, String> paths) { String[] sortedKeys = queries.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); StringBuilder canonicalizedQueryString = new StringBuilder(); try { 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(); } catch (UnsupportedEncodingException exp) { throw new RuntimeException("UTF-8 encoding is not supported."); } } public static ISignatureComposer getComposer() { if (null == composer) composer = new RpcSignatureComposer(); return composer; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/ShaHmac1.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.aliyuncs.utils.Base64Helper; public class ShaHmac1 implements ISigner { private final static String AGLORITHM_NAME = "HmacSHA1"; public String signString(String source, String accessSecret) throws InvalidKeyException, IllegalStateException { try { Mac mac = Mac.getInstance(AGLORITHM_NAME); mac.init(new SecretKeySpec( accessSecret.getBytes(AcsURLEncoder.URL_ENCODING),AGLORITHM_NAME)); byte[] signData = mac.doFinal(source.getBytes(AcsURLEncoder.URL_ENCODING)); return Base64Helper.encode(signData); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("HMAC-SHA1 not supported."); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported."); } } public String getSignerName() { return "HMAC-SHA1"; } public String getSignerVersion() { return "1.0"; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/ShaHmac1Singleton.java
package com.aliyuncs.auth; /** * Created by hi.yan.li on 2016/4/1. */ public enum ShaHmac1Singleton { INSTANCE; private ISigner signer; ShaHmac1Singleton() { signer = new ShaHmac1(); } public ISigner getInstance() { return this.signer; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/auth/ShaHmac256.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.auth; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.aliyuncs.utils.Base64Helper; public class ShaHmac256 implements ISigner { private final static String AGLORITHM_NAME = "HmacSHA256"; public String signString(String source, String accessSecret) throws InvalidKeyException, IllegalStateException { try { Mac mac = Mac.getInstance(AGLORITHM_NAME); mac.init(new SecretKeySpec( accessSecret.getBytes(AcsURLEncoder.URL_ENCODING),AGLORITHM_NAME)); byte[] signData = mac.doFinal(source.getBytes(AcsURLEncoder.URL_ENCODING)); return Base64Helper.encode(signData); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("HMAC-SHA1 not supported."); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported."); } } public String getSignerName() { return "HMAC-SHA256"; } public String getSignerVersion() { return "1.0"; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/exceptions/ClientException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public class ClientException extends Exception { private static final long serialVersionUID = 534996425110290578L; private String requestId; private String errCode; private String errMsg; private ErrorType errorType; public ClientException(String errCode, String errMsg, String requestId) { this(errCode, errMsg); this.requestId = requestId; } public ClientException(String errCode, String errMsg) { super(errCode + " : " + errMsg); this.errCode = errCode; this.errMsg = errMsg; this.setErrorType(ErrorType.Client); } public ClientException(String message) { super(message); } public ClientException(Throwable cause) { super(cause); } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getErrCode() { return errCode; } public void setErrCode(String errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public ErrorType getErrorType() { return errorType; } public void setErrorType(ErrorType errorType) { this.errorType = errorType; } @Override public String getMessage() { return super.getMessage() + (null == getRequestId() ? "" : "\r\nRequestId : " + getRequestId()); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/exceptions/ErrorType.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public enum ErrorType { Client, Server, Throttling, Unknown, }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/exceptions/ServerException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.exceptions; public class ServerException extends ClientException { private static final long serialVersionUID = -7345371390798165336L; public ServerException(String errorCode, String errorMessage) { super(errorCode, errorMessage); this.setErrorType(ErrorType.Server); } public ServerException(String errCode, String errMsg, String requestId) { this(errCode, errMsg); this.setRequestId(requestId); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/http/FormatType.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.http; public enum FormatType { XML, JSON, RAW; public static String mapFormatToAccept(FormatType format) { if (FormatType.XML == format) return "application/xml"; if (FormatType.JSON == format) return "application/json"; return "application/octet-stream"; } public static FormatType mapAcceptToFormat(String accept) { if (accept.toLowerCase().equals("application/xml") || accept.toLowerCase().equals("text/xml")) return FormatType.XML; if (accept.toLowerCase().equals("application/json")) return FormatType.JSON; return FormatType.RAW; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/http/HttpRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.http; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.Collections; import java.util.Map.Entry; import com.aliyuncs.utils.ParameterHelper; public class HttpRequest { protected static final String CONTENT_TYPE = "Content-Type"; protected static final String CONTENT_MD5 = "Content-MD5"; protected static final String CONTENT_LENGTH ="Content-Length"; private String url = null; private MethodType method = null; protected FormatType contentType = null; protected byte[] content = null; protected String encoding = null; protected Map<String, String> headers = null; protected Integer connectTimeout = null; protected Integer readTimeout = null; public HttpRequest(String strUrl) { this.url = strUrl; this.headers = new HashMap<String, String>(); } public HttpRequest(String strUrl, Map<String, String> tmpHeaders) { this.url = strUrl; if (null != tmpHeaders) this.headers = tmpHeaders; } public HttpRequest() { } public String getUrl() { return url; } protected void setUrl(String url) { this.url = url; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public FormatType getContentType() { return contentType; } public void setContentType(FormatType contentType) { this.contentType = contentType; if (null != this.content || null != contentType) { this.headers.put(CONTENT_TYPE, getContentTypeValue(this.contentType, this.encoding)); } else { this.headers.remove(CONTENT_TYPE); } } public MethodType getMethod() { return method; } public void setMethod(MethodType method) { this.method = method; } public byte[] getContent() { return content; } public String getHeaderValue(String name) { return this.headers.get(name); } public Integer getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public Integer getReadTimeout() { return readTimeout; } public void setReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; } public void putHeaderParameter(String name, String value) { if (null != name && null != value) this.headers.put(name, value); } public void setContent(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.contentType = null; this.content = null; this.encoding = null; return; } this.content = content; this.encoding = encoding; String contentLen =String.valueOf(content.length); String strMd5 = ParameterHelper.md5Sum(content); if (null != format) { this.contentType = format; } else { this.contentType = FormatType.RAW; } this.headers.put(CONTENT_MD5, strMd5); this.headers.put(CONTENT_LENGTH, contentLen); this.headers.put(CONTENT_TYPE, getContentTypeValue(contentType, encoding)); } public Map<String, String> getHeaders() { return Collections.unmodifiableMap(headers); } public HttpURLConnection getHttpConnection() throws IOException { Map<String, String> mappedHeaders = this.headers; String strUrl = url; if (null == strUrl || null == this.method){ return null; } URL url = null; String[] urlArray = null; if(MethodType.POST.equals(this.method) && null == getContent()){ urlArray = strUrl.split("\\?"); url = new URL(urlArray[0]); } else { url = new URL(strUrl); } System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod(this.method.toString()); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); if (this.getConnectTimeout() != null) { httpConn.setConnectTimeout(this.getConnectTimeout()); } if (this.getReadTimeout() != null) { httpConn.setReadTimeout(this.getReadTimeout()); } for(Entry<String, String> entry: mappedHeaders.entrySet()) { httpConn.setRequestProperty(entry.getKey(), entry.getValue()); } if(null != getHeaderValue(CONTENT_TYPE)){ httpConn.setRequestProperty(CONTENT_TYPE, getHeaderValue(CONTENT_TYPE)); } else { String contentTypeValue = getContentTypeValue(contentType, encoding); if(null != contentTypeValue){ httpConn.setRequestProperty(CONTENT_TYPE, contentTypeValue); } } if(MethodType.POST.equals(this.method) && null != urlArray && urlArray.length == 2){ httpConn.getOutputStream().write(urlArray[1].getBytes()); } return httpConn; } private String getContentTypeValue(FormatType contentType, String encoding) { if(null != contentType && null != encoding){ return FormatType.mapFormatToAccept(contentType) + ";charset=" + encoding.toLowerCase(); } else if (null != contentType) { return FormatType.mapFormatToAccept(contentType); } return null; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/http/HttpResponse.java
/* Z * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class HttpResponse extends HttpRequest { private int status; public HttpResponse(String strUrl) { super(strUrl); } public HttpResponse() { } @Override public void setContent(byte[] content, String encoding, FormatType format) { this.content = content; this.encoding = encoding; this.contentType = format; } @Override public String getHeaderValue(String name) { String value = this.headers.get(name); if (null == value){ value = this.headers.get(name.toLowerCase()); } return value; } private static byte[] readContent(InputStream content) throws IOException { if (content == null){ return null; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; while(true) { final int read = content.read(buff); if(read == -1) break; outputStream.write(buff,0,read); } return outputStream.toByteArray(); } private static void pasrseHttpConn(HttpResponse response, HttpURLConnection httpConn, InputStream content) throws IOException { byte[] buff = readContent(content); response.setStatus(httpConn.getResponseCode()); 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.setEncoding("UTF-8"); String[] split = type.split(";"); response.setContentType(FormatType.mapAcceptToFormat(split[0].trim())); if (split.length > 1 && split[1].contains("=")) { String[] codings = split[1].split("="); response.setEncoding(codings[1].trim().toUpperCase()); } } response.setStatus(httpConn.getResponseCode()); response.setContent(buff, response.getEncoding(), response.getContentType()); } public static HttpResponse getResponse(HttpRequest request) throws IOException { OutputStream out= null; InputStream content = null; HttpResponse response = null; HttpURLConnection httpConn = request.getHttpConnection(); try { httpConn.connect(); if (null != request.getContent() && request.getContent().length > 0) { out = httpConn.getOutputStream(); out.write(request.getContent()); } content = httpConn.getInputStream(); response = new HttpResponse(httpConn.getURL().toString()); pasrseHttpConn(response, httpConn, content); return response; } catch (IOException e) { content = httpConn.getErrorStream(); response = new HttpResponse(httpConn.getURL().toString()); pasrseHttpConn(response, httpConn, content); return response; } finally { if (content != null) content.close(); httpConn.disconnect(); } } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public boolean isSuccess() { if (200 <= this.status && 300 > this.status) return true; return false; } }