index
int64
repo_id
string
file_path
string
content
string
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/MethodType.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 MethodType { GET, PUT, POST, DELETE, HEAD, OPTIONS }
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/PositionType.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 PositionType { Host, Path, Query, Header, Body }
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/ProtocolType.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 ProtocolType { HTTP("http"), HTTPS("https"); private final String protocol; private ProtocolType(String protocol) { this.protocol = protocol; } @Override public String toString() { return protocol; } }
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/X509TrustAll.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.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public final class X509TrustAll implements X509TrustManager,HostnameVerifier { private static HostnameVerifier defaultVerifier; private static SSLSocketFactory defaultSSLFactory; public boolean verify(String hostname, SSLSession session) { return true; } public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } public static void restoreSSLCertificate() { if (null != defaultSSLFactory) { HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLFactory); HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier); } } public static void ignoreSSLCertificate() { try { X509TrustAll trustAll = new X509TrustAll(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{trustAll}, new java.security.SecureRandom()); if (null == defaultSSLFactory) { defaultSSLFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); } HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(trustAll); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed setting up all thrusting certificate manager.", e); } catch (KeyManagementException e) { throw new RuntimeException("Failed setting up all thrusting certificate manager.", e); } } }
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/profile/DefaultProfile.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.profile; import java.util.*; import com.aliyuncs.auth.*; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.FormatType; import com.aliyuncs.regions.*; import com.aliyuncs.regions.inner.DescribeEndpointInnerServiceImpl; public class DefaultProfile implements IClientProfile { public static final String LOCATION_INNER = "Location-inner"; private static DefaultProfile profile = null; private static List<Endpoint> endpoints = null; private Credential credential = null; private String regionId = null; private FormatType acceptFormat = null; private ISigner isigner = null; private IEndpointsProvider iendpoints = null; private IEndpointsProvider remoteProvider = null; private ICredentialProvider icredential = null; private LocationConfig locationConfig = new LocationConfig(); private DefaultProfile() { this.locationConfig = new LocationConfig(); this.iendpoints = new InternalEndpointsParser(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(); } private DefaultProfile(String region, Credential creden) { this.iendpoints = new InternalEndpointsParser(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(); this.credential = creden; this.regionId = region; this.locationConfig = new LocationConfig(); } private DefaultProfile(String region, Credential creden, IEndpointsProvider provider) { this.iendpoints = provider; this.credential = creden; this.regionId = region; this.locationConfig = new LocationConfig(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(); } private DefaultProfile(ICredentialProvider icredential) { this.icredential = icredential; this.iendpoints = new InternalEndpointsParser(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(); this.locationConfig = new LocationConfig(); } private DefaultProfile(String region, ICredentialProvider icredential) { this.regionId = region; this.icredential = icredential; this.iendpoints = new InternalEndpointsParser(); this.locationConfig = new LocationConfig(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(); } private DefaultProfile(ICredentialProvider icredential, String region, FormatType format) { this.regionId = region; this.acceptFormat = format; this.icredential = icredential; this.iendpoints = new InternalEndpointsParser(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(); this.locationConfig = new LocationConfig(); } public synchronized ISigner getSigner() { if (null == isigner) this.isigner = ShaHmac1Singleton.INSTANCE.getInstance(); return isigner; } public synchronized String getRegionId() { return regionId; } public synchronized FormatType getFormat() { return acceptFormat; } public synchronized Credential getCredential() { if (null == credential && null != icredential) credential = icredential.fresh(); return credential; } public synchronized void setLocationConfig(String regionId, String product, String endpoint) { this.locationConfig = LocationConfig.createLocationConfig(regionId, product, endpoint); /** inner logic */ if (LOCATION_INNER.equalsIgnoreCase(product)) { DescribeEndpointService describeEndpointService = new DescribeEndpointInnerServiceImpl(); this.remoteProvider = RemoteEndpointsParser.initRemoteEndpointsParser(describeEndpointService); } } public synchronized List<Endpoint> getEndpoints() throws ClientException { if (null == endpoints) endpoints = iendpoints.getEndpoints(); return endpoints; } public synchronized List<Endpoint> getEndpoints(String product, String serviceCode, String endpointType) throws ClientException { if (null == endpoints || Endpoint.findProductDomain(regionId, product, endpoints) == null) { endpoints = remoteProvider.getEndpoints(regionId, serviceCode, endpointType, credential, locationConfig); if (endpoints == null) { endpoints = iendpoints.getEndpoints(); } } return endpoints; } public synchronized static DefaultProfile getProfile() { if (null == profile) profile = new DefaultProfile(); return profile; } 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) { Credential creden = new Credential(accessKeyId, secret); profile = new DefaultProfile(regionId, creden); return profile; } /** * @param regionId,eg: cn-hangzhou * @param productDomainMap,eg: Map<String, String> productDomainMap= new * HashMap<String,String>(); * productDomainMap.put("ecs","ecs.aliyuncs.com") * @param accessKeyId * @param secret * @return */ public synchronized static DefaultProfile getProfile(String regionId, Map<String, String> productDomainMap, String accessKeyId, String secret) { Credential creden = new Credential(accessKeyId, secret); IEndpointsProvider provider = CustomizedEndpointsParser.initParser(regionId, productDomainMap); profile = new DefaultProfile(regionId, creden, provider); return profile; } public synchronized static DefaultProfile getProfile(String regionId, IEndpointsProvider provider, String accessKeyId, String secret) { Credential creden = new Credential(accessKeyId, secret); profile = new DefaultProfile(regionId, creden, provider); return profile; } public synchronized static void addEndpoint(String endpointName, String regionId, String product, String domain) throws ClientException { if (null == endpoints) { endpoints = getProfile().getEndpoints(); } Endpoint endpoint = findEndpointByRegionId(regionId); if (null == endpoint) { addEndpoint_(endpointName, regionId, product, domain); } else { updateEndpoint(regionId, product, domain, endpoint); } } private static void addEndpoint_(String endpointName, String regionId, String product, String domain) { Set<String> regions = new HashSet<String>(); regions.add(regionId); List<ProductDomain> productDomains = new ArrayList<ProductDomain>(); productDomains.add(new ProductDomain(product, domain)); Endpoint endpoint = new Endpoint(endpointName, regions, productDomains); endpoints.add(endpoint); } private static void updateEndpoint(String regionId, String product, String domain, Endpoint endpoint) { Set<String> regionIds = endpoint.getRegionIds(); regionIds.add(regionId); List<ProductDomain> productDomains = endpoint.getProductDomains(); ProductDomain productDomain = findProductDomain(productDomains, product); if (null == productDomain) { productDomains.add(new ProductDomain(product, domain)); } else { productDomain.setDomianName(domain); } } private static Endpoint findEndpointByRegionId(String regionId) { for (Endpoint endpoint : endpoints) { if (endpoint.getRegionIds().contains(regionId)) { return endpoint; } } return null; } private static ProductDomain findProductDomain(List<ProductDomain> productDomains, String product) { for (ProductDomain productDomain : productDomains) { if (productDomain.getProductName().equals(product)) { return productDomain; } } 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/profile/IClientProfile.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.profile; import java.util.List; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.FormatType; import com.aliyuncs.regions.Endpoint; public interface IClientProfile { public ISigner getSigner(); public String getRegionId(); public FormatType getFormat(); public Credential getCredential(); public void setLocationConfig(String regionId, String product, String endpoint); public List<Endpoint> getEndpoints() throws ClientException; public List<Endpoint> getEndpoints(String product, String serviceCode, String endpointType) throws ClientException; }
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/reader/JsonReader.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.reader; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.HashMap; import java.util.Map; 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 CharacterIterator ct; private char c; private Object token; private StringBuffer stringBuffer = new StringBuffer(); private Map<String, String> map = new HashMap<String, String>(); 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')); } public Map<String, String> read(String response,String endpoint) { return read(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; } readJson(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 void processObject(String baseKey) { String key = baseKey + "." + readJson(baseKey); while (token != OBJECT_END_TOKEN) { readJson(key); if (token != 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 processList(String baseKey) { Object value = readJson(baseKey); int index = 0; while (token != 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 processArray(String baseKey) { int index = 0; String preKey = baseKey.substring(0,baseKey.lastIndexOf(".")); String key = preKey + "["+ index +"]"; Object value = readJson(key); while (token != 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 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); } public static String trimFromLast(String str, String stripString) { int pos = str.lastIndexOf(stripString); if (pos > -1) { return str.substring(0, pos); } else { return str; } } }
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/reader/Reader.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.reader; import java.util.Map; import com.aliyuncs.exceptions.ClientException; public interface Reader { public Map<String, String> read(String response,String endpoint) throws ClientException; }
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/reader/ReaderFactory.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.reader; import com.aliyuncs.http.FormatType; public class ReaderFactory { public static Reader createInstance(FormatType format) { if (FormatType.JSON == format) return new JsonReader(); if (FormatType.XML == format) return new XmlReader(); 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/reader/XmlReader.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.reader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.xml.sax.SAXException; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.utils.XmlUtils; public class XmlReader implements Reader { Map<String, String> map = new HashMap<String, String>(); 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) { new ClientException("SDK.InvalidXMLParser", e.toString()); } catch (SAXException e) { new ClientException("SDK.InvalidXMLFormat", e.toString()); } catch (IOException e) { new ClientException("SDK.InvalidContent", e.toString()); } return map; } private void read(Element element, String path, boolean appendPath) { path = buildPath(element, path, appendPath); List<Element> childElements = XmlUtils.getChildElements(element); if(childElements.size() == 0){ map.put(path, element.getTextContent()); return; } List<Element> listElements = XmlUtils.getChildElements(element, childElements.get(0).getNodeName()); if(listElements.size() > 1 && childElements.size() == listElements.size()){//be list elementsAsList(childElements, path); } else if(listElements.size() == 1 && childElements.size() == 1){//may be list elementsAsList(listElements, path);//as list read(childElements.get(0), path,true);//as not list } else {//not list 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-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/regions/CustomizedEndpointsParser.java
package com.aliyuncs.regions; import com.aliyuncs.auth.Credential; import com.aliyuncs.exceptions.ClientException; import java.util.*; public class CustomizedEndpointsParser implements IEndpointsProvider { private List<Endpoint> endpoints; public void setEndpoints(List<Endpoint> endpoints) { this.endpoints = endpoints; } @Override public List<Endpoint> getEndpoints() throws ClientException { return this.endpoints; } @Override public List<Endpoint> getEndpoints(String region, String product, String endpointType, Credential credential, LocationConfig locationConfig) throws ClientException { throw new UnsupportedOperationException(); } public static CustomizedEndpointsParser initParser(String regionId, Map<String, String> productDomainMap) { CustomizedEndpointsParser parser = new CustomizedEndpointsParser(); if (regionId == null || regionId.length() == 0 || productDomainMap == null) { return null; } Set<String> regionIds = new HashSet<String>(); regionIds.add(regionId); List<ProductDomain> productDomainList = new ArrayList<ProductDomain>(); for (String productName : productDomainMap.keySet()) { productDomainList.add(new ProductDomain(productName, productDomainMap.get(productName))); } Endpoint endpoint = new Endpoint(regionId, regionIds, productDomainList); parser.setEndpoints(Arrays.asList(endpoint)); return parser; } }
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/regions/DescribeEndpointRequest.java
package com.aliyuncs.regions; import com.aliyuncs.RpcAcsRequest; /** * Created by hi.yan.li on 2016/3/31. */ public class DescribeEndpointRequest extends RpcAcsRequest<DescribeEndpointResponse> { public DescribeEndpointRequest() { super("Location", "2015-06-12", "DescribeEndpoint"); } private String id; private String serviceCode; private String password; 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 getPassword() { return this.password; } public void setPassword(String password) { this.password = password; putQueryParameter("Password", password); } @Override public Class<DescribeEndpointResponse> getResponseClass() { return DescribeEndpointResponse.class; } }
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/regions/DescribeEndpointResponse.java
package com.aliyuncs.regions; import com.aliyuncs.AcsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.transform.UnmarshallerContext; import java.io.Serializable; /** * Created by hi.yan.li on 2016/3/29. */ public class DescribeEndpointResponse extends AcsResponse { private String endpoint; private String regionId; private String requestId; private String product; public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public String getRegionId() { return regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public static void main(String[] args) { } @Override public AcsResponse getInstance(UnmarshallerContext context) throws ClientException, ServerException { 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/regions/DescribeEndpointService.java
package com.aliyuncs.regions; import com.aliyuncs.auth.Credential; /** * Created by hi.yan.li on 2016/4/26. */ public interface DescribeEndpointService { DescribeEndpointResponse describeEndpoint(String regionId, String serviceCode, String endpointType, Credential credential, LocationConfig locationConfig); }
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/regions/DescribeEndpointServiceImpl.java
package com.aliyuncs.regions; import com.aliyuncs.AcsError; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.auth.ShaHmac1Singleton; 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.reader.Reader; import com.aliyuncs.reader.ReaderFactory; import com.aliyuncs.transform.UnmarshallerContext; import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by hi.yan.li on 2016/4/26. */ public class DescribeEndpointServiceImpl implements DescribeEndpointService { private boolean isEmpty(String str) { return ((str == null) || (str.length() == 0)); } @Override public DescribeEndpointResponse describeEndpoint(String regionId, String serviceCode, String endpointType, Credential credential, LocationConfig locationConfig) { if (isEmpty(serviceCode)) { return null; } DescribeEndpointRequest request = new DescribeEndpointRequest(); request.setAcceptFormat(FormatType.JSON); request.setId(regionId); request.setRegionId(locationConfig.getRegionId()); request.setServiceCode(serviceCode); ISigner signer = ShaHmac1Singleton.INSTANCE.getInstance(); ProductDomain domain = new ProductDomain(locationConfig.getProduct(), locationConfig.getEndpoint()); try { HttpRequest httpRequest = request.signRequest(signer, credential, FormatType.JSON, domain); HttpResponse httpResponse = HttpResponse.getResponse(httpRequest); if (httpResponse.isSuccess()) { String data = new String(httpResponse.getContent(), "utf-8"); DescribeEndpointResponse response = getEndpointResponse(data); if (isEmpty(response.getEndpoint())) { return null; } return response; } AcsError error = readError(httpResponse, FormatType.JSON); if (500 <= httpResponse.getStatus()) { throw new ServerException(error.getErrorCode(), error.getErrorMessage(), error.getRequestId()); } throw new ClientException(error.getErrorCode(), error.getErrorMessage(), error.getRequestId()); } catch (Exception e) { return null; } } private DescribeEndpointResponse getEndpointResponse(String data) throws ClientException { Reader reader = ReaderFactory.createInstance(FormatType.JSON); UnmarshallerContext context = new UnmarshallerContext(); DescribeEndpointResponse response = new DescribeEndpointResponse(); context.setResponseMap(reader.read(data, "DescribeEndpointResponse")); response.setRequestId(context.stringValue("DescribeEndpointResponse.RequestId")); response.setProduct(context.stringValue("DescribeEndpointResponse.SerivceCode")); response.setEndpoint(context.stringValue("DescribeEndpointResponse.Endpoint")); response.setRegionId(context.stringValue("DescribeEndpointResponse.Id")); return response; } 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)); error = error.getInstance(context); if (httpResponse.getStatus() > 0) { error.setStatusCode(httpResponse.getStatus()); } return error; } 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; } }
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/regions/Endpoint.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.regions; import java.util.List; import java.util.Map; import java.util.Set; public class Endpoint { private String name = null; private Set<String> regionIds = null; private List<ProductDomain> productDomains = null; public Endpoint(String name, Set<String> regionIds, List<ProductDomain> productDomains) { this.name = name; this.regionIds= regionIds; this.productDomains = productDomains; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<String> getRegionIds() { return regionIds; } public void setRegionIds(Set<String> regionIds) { this.regionIds = regionIds; } public List<ProductDomain> getProductDomains() { return productDomains; } public void setProductDomains(List<ProductDomain> productDomains) { this.productDomains = productDomains; } public static ProductDomain findProductDomain(String regionId, String product, List<Endpoint> endpoints) { if (null == regionId || null == product || null == endpoints){ return null; } for (Endpoint endpoint : endpoints) { if (endpoint.getRegionIds().contains(regionId)) { ProductDomain domain = findProductDomainByProduct(endpoint.getProductDomains(), product); return domain; } } return null; } private static ProductDomain findProductDomainByProduct(List<ProductDomain> productDomains, String product) { if(null == productDomains){ return null; } for (ProductDomain productDomain : productDomains) { if(product.equalsIgnoreCase(productDomain.getProductName())){ return productDomain; } } 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/regions/IEndpointsProvider.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.regions; import java.util.List; import com.aliyuncs.auth.Credential; import com.aliyuncs.exceptions.ClientException; public interface IEndpointsProvider { List<Endpoint> getEndpoints() throws ClientException; List<Endpoint> getEndpoints(String region, String serviceCode, String endpointType, Credential credential, LocationConfig locationConfig) throws ClientException; }
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/regions/InternalEndpointsParser.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.regions; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import com.aliyuncs.auth.Credential; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.utils.XmlUtils; public class InternalEndpointsParser implements IEndpointsProvider { private final static String BUNDLED_ENDPOINTS_RESOURCE_PATH = "/com/aliyuncs/endpoints/endpoints.xml"; private static List<Endpoint> parseEndpoints(final InputStream input) throws IOException, ParserConfigurationException, SAXException { Document document = XmlUtils.getDocument(new InputSource(input), null); NodeList endpointNodes = document.getElementsByTagName("Endpoint"); List<Endpoint> endpoints = new ArrayList<Endpoint>(); for (int i = 0; i < endpointNodes.getLength(); i++) { Element endpoint = (Element) endpointNodes.item(i); Set<String> regionIds = new HashSet<String>(); List<ProductDomain> products = new ArrayList<ProductDomain>(); NodeList regionNodes = endpoint.getElementsByTagName("RegionId"); NodeList productNodes = endpoint.getElementsByTagName("Product"); for (int j = 0; j < regionNodes.getLength(); j++) regionIds.add(((Element) regionNodes.item(j)).getTextContent()); for (int j = 0; j < productNodes.getLength(); j++) { Element element = (Element) (productNodes.item(j)); NodeList productNames = element.getElementsByTagName("ProductName"); NodeList domainNames = element.getElementsByTagName("DomainName"); for (int k = 0; k < productNames.getLength(); k++) { String productName = ((Element) productNames.item(k)).getTextContent(); String domainName = ((Element) domainNames.item(k)).getTextContent(); products.add(new ProductDomain(productName, domainName)); } } endpoints.add(new Endpoint(endpoint.getAttribute("name"), regionIds, products)); } return endpoints; } public List<Endpoint> getEndpoints() throws ClientException { InputStream stream = this.getClass().getResourceAsStream(BUNDLED_ENDPOINTS_RESOURCE_PATH); try { return parseEndpoints(stream); } catch (IOException e) { throw new ClientException("SDK.MissingEndpointsFile", "Internal endpoints file is missing."); } catch (ParserConfigurationException e) { throw new ClientException("SDK.InvalidEndpointsFile", "Internal endpoints file is missing."); } catch (SAXException e) { throw new ClientException("SDK.EndpointsFileMalformed", "Internal endpoints file is missing."); } } @Override public List<Endpoint> getEndpoints(String region, String product, String endpointType, Credential credential, LocationConfig locationConfig) throws ClientException { throw new UnsupportedOperationException(); } }
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/regions/LocationConfig.java
package com.aliyuncs.regions; public final class LocationConfig { public static final String LOCATION_INNER_ENDPOINT = "location-inner.aliyuncs.com"; public static final String LOCATION_INNER_PRODUCT = "Location-inner"; private String regionId = "cn-hangzhou"; private String product = "Location"; private String endpoint = "location.aliyuncs.com"; public LocationConfig() { super(); } public LocationConfig(String regionId, String product, String endpoint) { this.regionId = regionId; this.product = product; this.endpoint = endpoint; } public synchronized static LocationConfig createLocationConfig(String regionId, String product, String endpoint) { return new LocationConfig(regionId, product, endpoint); } public String getRegionId() { return regionId; } public String getProduct() { return product; } public String getEndpoint() { return endpoint; } }
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/regions/ProductDomain.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.regions; public class ProductDomain { private String productName; private String domianName; public ProductDomain(String product, String domain) { this.productName = product; this.domianName = domain; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getDomianName() { return domianName; } public void setDomianName(String domianName) { this.domianName = domianName; } }
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/regions/RemoteEndpointsParser.java
package com.aliyuncs.regions; import com.aliyuncs.auth.Credential; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.regions.inner.DescribeEndpointInnerServiceImpl; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class RemoteEndpointsParser implements IEndpointsProvider { private ConcurrentMap<String, List<Endpoint>> endpointMap = new ConcurrentHashMap<String, List<Endpoint>>(); private DescribeEndpointService describeEndpointService; public void setDescribeEndpointService(DescribeEndpointService describeEndpointService) { this.describeEndpointService = describeEndpointService; } public static RemoteEndpointsParser initRemoteEndpointsParser() { RemoteEndpointsParser parser = new RemoteEndpointsParser(); parser.setDescribeEndpointService(new DescribeEndpointServiceImpl()); return parser; } public static RemoteEndpointsParser initRemoteEndpointsParser(DescribeEndpointService describeEndpointService) { RemoteEndpointsParser parser = new RemoteEndpointsParser(); parser.setDescribeEndpointService(describeEndpointService); return parser; } @Override public List<Endpoint> getEndpoints() throws ClientException { throw new UnsupportedOperationException(); } @Override public List<Endpoint> getEndpoints(String regionId, String serviceCode, String endpointType, Credential credential, LocationConfig locationConfig) throws ClientException { if (serviceCode == null || serviceCode.length() == 0) { return null; } List<Endpoint> endpoints = endpointMap.get(serviceCode); if (endpoints != null) { return endpoints; } DescribeEndpointResponse response = describeEndpointService.describeEndpoint(regionId, serviceCode, endpointType, credential, locationConfig); if (response == null) { return endpoints; } Set<String> regionIds = new HashSet<String>(); regionIds.add(response.getRegionId()); List<ProductDomain> productDomainList = Arrays.asList(new ProductDomain(response.getProduct(), response .getEndpoint())); Endpoint endpoint = new Endpoint(response.getRegionId(), regionIds, productDomainList); endpoints = Arrays.asList(endpoint); endpointMap.putIfAbsent(serviceCode, endpoints); return endpoints; } public static void main(String[] args) throws ClientException { IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "account", "secret"); profile.setLocationConfig("cn-hangzhou", LocationConfig.LOCATION_INNER_PRODUCT, LocationConfig.LOCATION_INNER_ENDPOINT); List<Endpoint> list = profile.getEndpoints("Ecs", "ecs", ""); System.out.println(list.get(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/regions.inner/DescribeEndpointInnerServiceImpl.java
package com.aliyuncs.regions.inner; import com.aliyuncs.AcsError; import com.aliyuncs.auth.Credential; import com.aliyuncs.auth.ISigner; import com.aliyuncs.auth.ShaHmac1Singleton; 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.reader.Reader; import com.aliyuncs.reader.ReaderFactory; import com.aliyuncs.regions.*; import com.aliyuncs.transform.UnmarshallerContext; import java.io.UnsupportedEncodingException; /** * Created by hi.yan.li on 2016/4/26. */ public class DescribeEndpointInnerServiceImpl implements DescribeEndpointService { private boolean isEmpty(String str) { return ((str == null) || (str.length() == 0)); } @Override public DescribeEndpointResponse describeEndpoint(String regionId, String serviceCode, String endpointType, Credential credential, LocationConfig locationConfig) { if (serviceCode == null || serviceCode.length() == 0) { return null; } if (endpointType == null || endpointType.length() == 0) { return null; } DescribeEndpointsRequest request = new DescribeEndpointsRequest(); request.setAcceptFormat(FormatType.JSON); request.setId(regionId); request.setRegionId(locationConfig.getRegionId()); request.setServiceCode(serviceCode); request.setEndpointType(endpointType); ISigner signer = ShaHmac1Singleton.INSTANCE.getInstance(); ProductDomain domain = new ProductDomain(locationConfig.getProduct(), locationConfig.getEndpoint()); try { HttpRequest httpRequest = request.signRequest(signer, credential, FormatType.JSON, domain); HttpResponse httpResponse = HttpResponse.getResponse(httpRequest); if (httpResponse.isSuccess()) { String data = new String(httpResponse.getContent(), "utf-8"); DescribeEndpointResponse response = getEndpointResponse(data, endpointType); if (response == null || isEmpty(response.getEndpoint())) { return null; } return response; } AcsError error = readError(httpResponse, FormatType.JSON); if (500 <= httpResponse.getStatus()) { System.out.println("Invoke_Error, requestId:" + error.getRequestId() + "; code:" + error.getErrorCode() + "; Msg" + error.getErrorMessage()); return null; } System.out.println("Invoke_Error, requestId:" + error.getRequestId() + "; code:" + error.getErrorCode() + "; Msg" + error.getErrorMessage()); return null; } catch (Throwable e) { System.out.println("Invoke Remote Error,Msg" + e.getMessage()); return null; } } private DescribeEndpointResponse getEndpointResponse(String data, String endpointType) throws ClientException { Reader reader = ReaderFactory.createInstance(FormatType.JSON); UnmarshallerContext context = new UnmarshallerContext(); context.setResponseMap(reader.read(data, "DescribeEndpointsResponse")); int endpointsLength = context.lengthValue("DescribeEndpointsResponse.Endpoints.Length"); for (int i = 0; i < endpointsLength; i++) { if (endpointType.equalsIgnoreCase(context .stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Type"))) { DescribeEndpointResponse response = new DescribeEndpointResponse(); response.setRequestId(context.stringValue("DescribeEndpointsResponse.RequestId")); response.setProduct(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].SerivceCode")); response.setEndpoint(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Endpoint")); response.setRegionId(context.stringValue("DescribeEndpointsResponse.Endpoints[" + i + "].Id")); return response; } } return null; } 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)); error = error.getInstance(context); if (httpResponse.getStatus() > 0) { error.setStatusCode(httpResponse.getStatus()); } return error; } 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; } }
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/regions.inner/DescribeEndpointsRequest.java
package com.aliyuncs.regions.inner; import com.aliyuncs.RpcAcsRequest; /** * Created by hi.yan.li on 2016/3/31. */ public class DescribeEndpointsRequest extends RpcAcsRequest<DescribeEndpointsResponse> { public DescribeEndpointsRequest() { super("Location-inner", "2015-12-25", "DescribeEndpoints"); } private String id; private String serviceCode; private String password; 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 getPassword() { return this.password; } public void setPassword(String password) { this.password = password; putQueryParameter("Password", password); } @Override public Class<DescribeEndpointsResponse> getResponseClass() { return DescribeEndpointsResponse.class; } }
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/regions.inner/DescribeEndpointsResponse.java
package com.aliyuncs.regions.inner; import com.aliyuncs.AcsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.transform.UnmarshallerContext; import java.util.List; /** * Created by hi.yan.li on 2016/4/27. */ 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; } 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; } } @Override public AcsResponse getInstance(UnmarshallerContext context) throws ClientException, ServerException { 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/transform/UnmarshallerContext.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.transform; import java.util.Map; import com.aliyuncs.http.HttpResponse; 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 || 0 == value.length()){ 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 || 0 == value.length()){ return null; } return Long.valueOf(responseMap.get(key)); } public Boolean booleanValue(String key) { String value = responseMap.get(key); if(null == value || 0 == value.length()){ return null; } return Boolean.valueOf(responseMap.get(key)); } public Float floatValue(String key) { String value = responseMap.get(key); if(null == value || 0 == value.length()){ return null; } return Float.valueOf(responseMap.get(key)); } public Double doubleValue(String key) { String value = responseMap.get(key); if(null == value || 0 == value.length()){ return null; } return Double.valueOf(responseMap.get(key)); } public int lengthValue(String key) { String value = responseMap.get(key); if(null == value || 0 == value.length()){ return 0; } return Integer.valueOf(responseMap.get(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-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/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-inner/3.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-inner/3.0.2/com/aliyuncs/utils/ParameterHelper.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.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.UUID; 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 ParameterHelper() { } public static String getUniqueNonce() { UUID uuid = UUID.randomUUID(); return uuid.toString(); } public static String getISO8601Time(Date date) { Date nowDate = date; if (null == date){ nowDate = new Date(); } SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); return df.format(nowDate); } public static String getRFC2616Date(Date date) { Date nowDate = date; if (null == date){ nowDate = new Date(); } SimpleDateFormat df = new SimpleDateFormat(FORMAT_RFC2616, Locale.ENGLISH); df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); return df.format(nowDate); } public static Date parse(String strDate) throws ParseException { if (null == strDate || "".equals(strDate)){ return null; } try { return parseISO8601(strDate); } catch (ParseException exp) { return parseRFC2616(strDate); } } public static Date parseISO8601(String strDate) throws ParseException { if (null == strDate || "".equals(strDate)){ 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) { } 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/utils/XmlUtils.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.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; 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; 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); return getDocument(source, null); } public static Document getDocument(InputSource xml, InputStream xsd) throws ParserConfigurationException,SAXException,IOException { Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); if (xsd != null) { dbf.setNamespaceAware(true); } DocumentBuilder builder = dbf.newDocumentBuilder(); doc = builder.parse(xml); if (xsd != null) validateXml(doc, xsd); } finally { closeStream(xml.getByteStream()); } return doc; } public static Element getRootElementFromString(String payload) throws ParserConfigurationException, SAXException, IOException { return getDocument(payload).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; } public static void validateXml(InputStream xml, InputStream xsd) throws SAXException, IOException, ParserConfigurationException { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = dbf.newDocumentBuilder().parse(xml); validateXml(doc, xsd); } finally { closeStream(xml); closeStream(xsd); } } public static void validateXml(Node root, InputStream xsd) throws SAXException, IOException { try { Source source = new StreamSource(xsd); Schema schema = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source); Validator validator = schema.newValidator(); validator.validate(new DOMSource(root)); } finally { closeStream(xsd); } } private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin/sdkcore/ProxyAcsClient.java
package com.aliyun.kms.secretsmanager.plugin.sdkcore; import com.aliyun.kms.secretsmanager.plugin.common.AKExpireHandler; import com.aliyun.kms.secretsmanager.plugin.common.AliyunSDKSecretsManagerPlugin; import com.aliyun.kms.secretsmanager.plugin.common.AliyunSDKSecretsManagerPluginsManager; import com.aliyuncs.auth.AlibabaCloudCredentials; import com.aliyuncs.auth.AlibabaCloudCredentialsProvider; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; public class ProxyAcsClient extends ProxyDefaultSdkCoreClient { public ProxyAcsClient(String secretName) throws ClientException { this(secretName, (AKExpireHandler<ClientException>) null); } public ProxyAcsClient(String secretName, AKExpireHandler<ClientException> handler) throws ClientException { super(secretName, handler); AliyunSDKSecretsManagerPlugin secretsManagerPlugin = AliyunSDKSecretsManagerPluginsManager.getSecretsManagerPlugin(); super.setSecretsManagerPlugin(secretsManagerPlugin); initProxyAcsClient(DefaultProfile.getProfile(), secretName, handler); } public ProxyAcsClient(String regionId, String secretName) throws ClientException { this(regionId, secretName, null); } public ProxyAcsClient(String regionId, String secretName, AKExpireHandler<ClientException> handler) throws ClientException { super(regionId, secretName, handler); AliyunSDKSecretsManagerPlugin secretsManagerPlugin = AliyunSDKSecretsManagerPluginsManager.getSecretsManagerPlugin(); super.setSecretsManagerPlugin(secretsManagerPlugin); initProxyAcsClient(regionId, secretName, handler); } public ProxyAcsClient(IClientProfile profile, String secretName) { this(profile, secretName, null); } public ProxyAcsClient(IClientProfile profile, String secretName, AKExpireHandler<ClientException> handler) { super(profile, secretName, handler); AliyunSDKSecretsManagerPlugin secretsManagerPlugin = AliyunSDKSecretsManagerPluginsManager.getSecretsManagerPlugin(); super.setSecretsManagerPlugin(secretsManagerPlugin); initProxyAcsClient(profile, secretName, handler); } public ProxyAcsClient(IClientProfile profile, AlibabaCloudCredentials credentials, String secretName) { this(profile, credentials, secretName, null); } public ProxyAcsClient(IClientProfile profile, AlibabaCloudCredentials credentials, String secretName, AKExpireHandler<ClientException> handler) { super(profile, credentials, secretName, handler); throw new UnsupportedOperationException("Not support such constructors"); } public ProxyAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider, String secretName) { this(profile, credentialsProvider, secretName, null); } public ProxyAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider, String secretName, AKExpireHandler<ClientException> handler) { super(profile, credentialsProvider, secretName, handler); throw new UnsupportedOperationException("Not support such constructors"); } protected void initProxyAcsClient(String regionId, String secretName, AKExpireHandler<ClientException> handler) { try { SecretsManagerSdkCorePluginManager.getSdkCoreClient(regionId, secretName, handler, this); } catch (CacheSecretException e) { throw new RuntimeException(e); } } protected void initProxyAcsClient(IClientProfile profile, String secretName, AKExpireHandler<ClientException> handler) { try { SecretsManagerSdkCorePluginManager.getSdkCoreClient((DefaultProfile) profile, secretName, handler, this); } catch (CacheSecretException e) { throw new RuntimeException(e); } } @Override public void shutdown() { super.shutdown(this); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin/sdkcore/SdkCorePluginAKExpireHandler.java
package com.aliyun.kms.secretsmanager.plugin.sdkcore; import com.aliyun.kms.secretsmanager.plugin.common.AKExpireHandler; import com.aliyuncs.exceptions.ClientException; import java.util.HashSet; import java.util.Set; public class SdkCorePluginAKExpireHandler implements AKExpireHandler<ClientException> { private final static String[] AK_EXPIRE_ERROR_CODES = new String[]{"InvalidAccessKeyId.NotFound", "InvalidAccessKeyId"}; private Set<String> errorCodeSet = new HashSet<>(); public SdkCorePluginAKExpireHandler() { for (String akExpireCode : AK_EXPIRE_ERROR_CODES) { errorCodeSet.add(akExpireCode); } } public SdkCorePluginAKExpireHandler(String[] akExpireErrorCodes) { if (akExpireErrorCodes == null || akExpireErrorCodes.length == 0) { for (String akExpireCode : AK_EXPIRE_ERROR_CODES) { errorCodeSet.add(akExpireCode); } } else { for (String akExpireCode : akExpireErrorCodes) { errorCodeSet.add(akExpireCode); } } } @Override public boolean judgeAKExpire(ClientException e) { return errorCodeSet.contains(e.getErrCode()); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin/sdkcore/SdkCorePluginCredentialProvider.java
package com.aliyun.kms.secretsmanager.plugin.sdkcore; import com.aliyuncs.auth.AlibabaCloudCredentials; import com.aliyuncs.auth.AlibabaCloudCredentialsProvider; public class SdkCorePluginCredentialProvider implements AlibabaCloudCredentialsProvider { private AlibabaCloudCredentials credentials; public SdkCorePluginCredentialProvider(AlibabaCloudCredentials credentials) { this.credentials = credentials; } @Override public AlibabaCloudCredentials getCredentials() { return credentials; } public void setCredentials(AlibabaCloudCredentials credentials) { this.credentials = credentials; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin/sdkcore/SdkCorePluginCredentialUpdater.java
package com.aliyun.kms.secretsmanager.plugin.sdkcore; import com.aliyun.kms.secretsmanager.plugin.common.SecretsManagerPluginCredentialUpdater; import com.aliyun.kms.secretsmanager.plugin.common.auth.SecretsManagerPluginCredentials; import com.aliyun.kms.secretsmanager.plugin.common.utils.CredentialsUtils; import com.aliyuncs.IAcsClient; import com.aliyuncs.auth.BasicCredentials; import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo; import java.io.IOException; public class SdkCorePluginCredentialUpdater implements SecretsManagerPluginCredentialUpdater<IAcsClient> { private final IAcsClient client; private final SdkCorePluginCredentialProvider provider; public SdkCorePluginCredentialUpdater(IAcsClient client, SdkCorePluginCredentialProvider provider) { this.client = client; this.provider = provider; } @Override public IAcsClient getClient() { return client; } @Override public void updateCredential(SecretInfo secretInfo) { SecretsManagerPluginCredentials credentials = CredentialsUtils.generateCredentialsBySecret(secretInfo.getSecretValue()); this.provider.setCredentials(new BasicCredentials(credentials.getAccessKeyId(), credentials.getAccessKeySecret())); } @Override public void close() throws IOException { if (client != null) { client.shutdown(); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin/sdkcore/SecretsManagerSdkCorePlugin.java
package com.aliyun.kms.secretsmanager.plugin.sdkcore; import com.aliyun.kms.secretsmanager.plugin.common.CloudClientBuilder; import com.aliyun.kms.secretsmanager.plugin.common.AliyunSDKSecretsManagerPlugin; import com.aliyun.kms.secretsmanager.plugin.common.SecretsManagerPluginCredentialUpdater; import com.aliyun.kms.secretsmanager.plugin.common.AKExpireHandler; import com.aliyun.kms.secretsmanager.plugin.common.auth.SecretsManagerPluginCredentials; import com.aliyun.kms.secretsmanager.plugin.common.utils.CredentialsUtils; import com.aliyuncs.*; import com.aliyuncs.auth.*; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.FormatType; import com.aliyuncs.http.HttpClientConfig; import com.aliyuncs.http.HttpResponse; import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException; import com.aliyuncs.kms.secretsmanager.client.model.SecretInfo; import com.aliyuncs.kms.secretsmanager.client.utils.CacheClientConstant; import com.aliyuncs.kms.secretsmanager.client.utils.CommonLogger; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import org.slf4j.Logger; import java.io.IOException; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; public class SecretsManagerSdkCorePlugin { private static Set<Class<? extends SecretsManagerPluginCredentialUpdater>> secretsManagerCredentialUpdaterSet = new HashSet(); private final static String CREDENTIALS_PROVIDER_FIELD_NAME = "credentialsProvider"; private AKExpireHandler<ClientException> akExpireHandler; private AliyunSDKSecretsManagerPlugin secretsManagerPlugin; static { secretsManagerCredentialUpdaterSet.add(SdkCorePluginCredentialUpdater.class); } /** * use for spring bean */ public SecretsManagerSdkCorePlugin() { } public SecretsManagerSdkCorePlugin(AliyunSDKSecretsManagerPlugin secretsManagerPlugin) { this.secretsManagerPlugin = secretsManagerPlugin; } /** * use for spring bean * * @param secretsManagerPlugin */ public void setSecretsManagerPlugin(AliyunSDKSecretsManagerPlugin secretsManagerPlugin) { this.secretsManagerPlugin = secretsManagerPlugin; } /** * use for spring bean * * @param akExpireHandler */ public void setAkExpireHandler(AKExpireHandler<ClientException> akExpireHandler) { this.akExpireHandler = akExpireHandler; } public IAcsClient getSdkCoreClient(String regionId, String secretName) throws CacheSecretException { return getSdkCoreClient(DefaultProfile.getProfile(regionId), secretName); } public IAcsClient getSdkCoreClient(String regionId, String secretName, AKExpireHandler<ClientException> akExpireHandler) throws CacheSecretException { return getSdkCoreClient(DefaultProfile.getProfile(regionId), secretName, akExpireHandler); } public IAcsClient getSdkCoreClient(DefaultProfile profile, String secretName) throws CacheSecretException { return getSdkCoreClient(profile, secretName, null); } public IAcsClient getSdkCoreClient(DefaultProfile profile, String secretName, AKExpireHandler<ClientException> akExpireHandler) throws CacheSecretException { return getSdkCoreClient(profile, secretName, akExpireHandler, null); } protected IAcsClient getSdkCoreClient(String regionId, String secretName, AKExpireHandler<ClientException> akExpireHandler, ProxyDefaultSdkCoreClient acsClient) throws CacheSecretException { return getSdkCoreClient(DefaultProfile.getProfile(regionId), secretName, akExpireHandler, acsClient); } protected IAcsClient getSdkCoreClient(DefaultProfile profile, String secretName, AKExpireHandler<ClientException> akExpireHandler, ProxyDefaultSdkCoreClient acsClient) throws CacheSecretException { String realSecretName = this.secretsManagerPlugin.getSecretName(secretName); SecretInfo secretInfo = secretsManagerPlugin.getSecretInfo(realSecretName); SecretsManagerPluginCredentials credentials = CredentialsUtils.generateCredentialsBySecret(secretInfo.getSecretValue()); SdkCorePluginCredentialProvider provider = new SdkCorePluginCredentialProvider(new BasicCredentials(credentials.getAccessKeyId(), credentials.getAccessKeySecret())); if (akExpireHandler == null) { akExpireHandler = this.akExpireHandler == null ? new SdkCorePluginAKExpireHandler() : this.akExpireHandler; } IAcsClient client = acsClient; if (client == null) { client = new SdkCoreClientBuilder(provider, profile, secretName, akExpireHandler).build(); } else { Class<?> defaultAcsClientClazz = client.getClass().getSuperclass().getSuperclass(); try { Field credentialsProvider = defaultAcsClientClazz.getDeclaredField(CREDENTIALS_PROVIDER_FIELD_NAME); credentialsProvider.setAccessible(true); credentialsProvider.set(client, provider); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } SecretsManagerPluginCredentialUpdater pluginCredentialUpdater = new SdkCorePluginCredentialUpdater(client, provider); secretsManagerPlugin.registerSecretsManagerPluginUpdater(secretInfo.getSecretName(), pluginCredentialUpdater); return client; } public void closeSdkCoreClient(IAcsClient client, String secretName) throws IOException { String realSecretName = this.secretsManagerPlugin.getSecretName(secretName); secretsManagerPlugin.closeSecretsManagerPluginUpdaterAndClient(realSecretName, client); } public void destroy() throws IOException { secretsManagerPlugin.closeSecretsManagerPluginUpdaterAndClient(secretsManagerCredentialUpdaterSet); } class SdkCoreClientBuilder implements CloudClientBuilder<IAcsClient> { private final String secretName; private final AKExpireHandler<ClientException> handler; private final SdkCorePluginCredentialProvider provider; private DefaultProfile defaultProfile; public SdkCoreClientBuilder(SdkCorePluginCredentialProvider provider, DefaultProfile defaultProfile, String secretName, AKExpireHandler<ClientException> handler) { this.secretName = secretName; this.handler = handler; this.provider = provider; this.defaultProfile = defaultProfile; } @Override public IAcsClient build() { if (provider == null) { throw new IllegalArgumentException("Provider cannot be null."); } if (defaultProfile == null) { defaultProfile = DefaultProfile.getProfile(); } SecretsManagerPluginProfile profile = new SecretsManagerPluginProfile(defaultProfile, provider); ProxyDefaultSdkCoreClient client = new ProxyDefaultSdkCoreClient(profile, provider, secretName, handler); client.setSecretsManagerPlugin(secretsManagerPlugin); return client; } private class SecretsManagerPluginProfile implements IClientProfile { private final DefaultProfile defaultProfile; private final SdkCorePluginCredentialProvider provider; private SecretsManagerPluginProfile(DefaultProfile defaultProfile, SdkCorePluginCredentialProvider provider) { this.defaultProfile = defaultProfile; this.provider = provider; } @Override public ISigner getSigner() { return defaultProfile.getSigner(); } @Override public String getRegionId() { return defaultProfile.getRegionId(); } @Override public FormatType getFormat() { return defaultProfile.getFormat(); } @Override public Credential getCredential() { return defaultProfile.getCredential(); } @Override public void setCredentialsProvider(AlibabaCloudCredentialsProvider alibabaCloudCredentialsProvider) { defaultProfile.setCredentialsProvider(this.provider); } @Override public String getCertPath() { return defaultProfile.getCertPath(); } @Override public void setCertPath(String s) { defaultProfile.setCertPath(s); } @Override public HttpClientConfig getHttpClientConfig() { return defaultProfile.getHttpClientConfig(); } @Override public void setHttpClientConfig(HttpClientConfig httpClientConfig) { defaultProfile.setHttpClientConfig(httpClientConfig); } @Override public void enableUsingInternalLocationService() { defaultProfile.enableUsingInternalLocationService(); } @Override public boolean isUsingInternalLocationService() { return defaultProfile.isUsingInternalLocationService(); } @Override public boolean isUsingVpcEndpoint() { return defaultProfile.isUsingVpcEndpoint(); } @Override public void enableUsingVpcEndpoint() { defaultProfile.enableUsingVpcEndpoint(); } @Override public void setUsingInternalLocationService() { defaultProfile.setUsingInternalLocationService(); } @Override public Logger getLogger() { return defaultProfile.getLogger(); } @Override public void setLogger(Logger logger) { defaultProfile.setLogger(logger); } @Override public String getLogFormat() { return defaultProfile.getLogFormat(); } @Override public void setLogFormat(String s) { defaultProfile.setLogFormat(s); } @Override public boolean isCloseTrace() { return defaultProfile.isCloseTrace(); } @Override public void setCloseTrace(boolean b) { defaultProfile.setCloseTrace(b); } } } } class ProxyDefaultSdkCoreClient extends DefaultAcsClient { private final String secretName; private final AKExpireHandler<ClientException> handler; private boolean isClosing; private AliyunSDKSecretsManagerPlugin secretsManagerPlugin; public ProxyDefaultSdkCoreClient(String secretName, AKExpireHandler<ClientException> handler) throws ClientException { super(); this.secretName = secretName; if (handler == null) { handler = new SdkCorePluginAKExpireHandler(); } this.handler = handler; } public ProxyDefaultSdkCoreClient(String regionId, String secretName, AKExpireHandler<ClientException> handler) throws ClientException { super(regionId); this.secretName = secretName; if (handler == null) { handler = new SdkCorePluginAKExpireHandler(); } this.handler = handler; } public ProxyDefaultSdkCoreClient(IClientProfile profile, String secretName, AKExpireHandler<ClientException> handler) { super(profile); this.secretName = secretName; if (handler == null) { handler = new SdkCorePluginAKExpireHandler(); } this.handler = handler; } public ProxyDefaultSdkCoreClient(IClientProfile profile, AlibabaCloudCredentials credentials, String secretName, AKExpireHandler<ClientException> handler) { super(profile, credentials); this.secretName = secretName; this.handler = handler; throw new UnsupportedOperationException("Not support such constructors"); } public ProxyDefaultSdkCoreClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider, String secretName, AKExpireHandler<ClientException> handler) { super(profile, credentialsProvider); this.secretName = secretName; if (handler == null) { handler = new SdkCorePluginAKExpireHandler(); } this.handler = handler; } public void setSecretsManagerPlugin(AliyunSDKSecretsManagerPlugin secretsManagerPlugin) { this.secretsManagerPlugin = secretsManagerPlugin; } private boolean judgeTempAKExpire(ClientException e) { return this.handler.judgeAKExpire(e); } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request) throws ClientException, ServerException { try { return super.doAction(request); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.doAction(request); } else { throw e; } } } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ClientException, ServerException { try { return super.doAction(request, autoRetry, maxRetryCounts); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.doAction(request, autoRetry, maxRetryCounts); } else { throw e; } } } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, IClientProfile profile) throws ClientException, ServerException { try { return super.doAction(request, profile); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.doAction(request, profile); } else { throw e; } } } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, String regionId, Credential credential) throws ClientException, ServerException { try { return super.doAction(request, regionId, credential); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.doAction(request, regionId, credential); } else { throw e; } } } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request) throws ServerException, ClientException { try { return super.getAcsResponse(request); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.getAcsResponse(request); } else { throw e; } } } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ServerException, ClientException { try { return super.getAcsResponse(request, autoRetry, maxRetryCounts); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.getAcsResponse(request, autoRetry, maxRetryCounts); } else { throw e; } } } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, IClientProfile profile) throws ServerException, ClientException { try { return super.getAcsResponse(request, profile); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.getAcsResponse(request, profile); } else { throw e; } } } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId, Credential credential) throws ServerException, ClientException { try { return super.getAcsResponse(request, regionId, credential); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.getAcsResponse(request, regionId, credential); } else { throw e; } } } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId) throws ServerException, ClientException { try { return super.getAcsResponse(request, regionId); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.getAcsResponse(request, regionId); } else { throw e; } } } @Override public CommonResponse getCommonResponse(CommonRequest request) throws ServerException, ClientException { try { return super.getCommonResponse(request); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.getCommonResponse(request); } else { throw e; } } } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts, IClientProfile profile) throws ClientException, ServerException { try { return super.doAction(request, autoRetry, maxRetryCounts, profile); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.doAction(request, autoRetry, maxRetryCounts, profile); } else { throw e; } } } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber, String regionId, Credential credential, Signer signer, FormatType format) throws ClientException, ServerException { try { return super.doAction(request, autoRetry, maxRetryNumber, regionId, credential, signer, format); } catch (ClientException e) { if (judgeTempAKExpire(e)) { secretsManagerPlugin.refreshSecretInfo(secretName); return super.doAction(request, autoRetry, maxRetryNumber, regionId, credential, signer, format); } else { throw e; } } } @Override public void shutdown() { shutdown(this); } protected void shutdown(ProxyDefaultSdkCoreClient client) { if (!isClosing) { isClosing = true; try { super.shutdown(); secretsManagerPlugin.closeSecretsManagerPluginUpdaterAndClient(secretName, client); } catch (Exception e) { CommonLogger.getCommonLogger(CacheClientConstant.MODE_NAME).errorf("action:shutdown", e); } } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin
java-sources/com/aliyun/aliyun-java-sdk-core-managed-credentials-provider/1.3.5/com/aliyun/kms/secretsmanager/plugin/sdkcore/SecretsManagerSdkCorePluginManager.java
package com.aliyun.kms.secretsmanager.plugin.sdkcore; import com.aliyun.kms.secretsmanager.plugin.common.AliyunSDKSecretsManagerPlugin; import com.aliyun.kms.secretsmanager.plugin.common.AliyunSDKSecretsManagerPluginsManager; import com.aliyun.kms.secretsmanager.plugin.common.AKExpireHandler; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.kms.secretsmanager.client.exception.CacheSecretException; import com.aliyuncs.profile.DefaultProfile; import java.io.IOException; public class SecretsManagerSdkCorePluginManager { private static AKExpireHandler<ClientException> akExpireHandler; private static SecretsManagerSdkCorePlugin client; public static IAcsClient getSdkCoreClient(String regionId, String secretName) throws CacheSecretException { return getSdkCoreClient(regionId, secretName, null); } public static IAcsClient getSdkCoreClient(String regionId, String secretName, AKExpireHandler<ClientException> akExpireHandle) throws CacheSecretException { initSecretsManagerPlugin(); return client.getSdkCoreClient(regionId, secretName, akExpireHandle); } protected static IAcsClient getSdkCoreClient(String regionId, String secretName, AKExpireHandler<ClientException> akExpireHandle, ProxyDefaultSdkCoreClient acsClient) throws CacheSecretException { initSecretsManagerPlugin(); return client.getSdkCoreClient(regionId, secretName, akExpireHandle, acsClient); } protected static IAcsClient getSdkCoreClient(DefaultProfile profile, String secretName, AKExpireHandler<ClientException> akExpireHandle, ProxyDefaultSdkCoreClient acsClient) throws CacheSecretException { initSecretsManagerPlugin(); return client.getSdkCoreClient(profile, secretName, akExpireHandle, acsClient); } public static IAcsClient getSdkCoreClient(DefaultProfile profile, String secretName) throws CacheSecretException { initSecretsManagerPlugin(); return client.getSdkCoreClient(profile, secretName); } public static IAcsClient getSdkCoreClient(DefaultProfile profile, String secretName, AKExpireHandler<ClientException> akExpireHandle) throws CacheSecretException { initSecretsManagerPlugin(); return client.getSdkCoreClient(profile, secretName, akExpireHandle); } public static void closeSdkCoreClient(IAcsClient acsClient, String secretName) throws IOException { initSecretsManagerPlugin(); client.closeSdkCoreClient(acsClient, secretName); } public static void setAKExpireHandler(AKExpireHandler<ClientException> akExpireHandler) { SecretsManagerSdkCorePluginManager.akExpireHandler = akExpireHandler; } public static void destroy() throws IOException { if (client != null) { client.destroy(); } } private static void initSecretsManagerPlugin() { if (client == null) { synchronized (SecretsManagerSdkCorePluginManager.class) { if (client == null) { try { AliyunSDKSecretsManagerPluginsManager.init(); AliyunSDKSecretsManagerPlugin secretsManagerPlugin = AliyunSDKSecretsManagerPluginsManager.getSecretsManagerPlugin(); client = new SecretsManagerSdkCorePlugin(secretsManagerPlugin); if (akExpireHandler != null) { client.setAkExpireHandler(akExpireHandler); } } catch (Exception e) { throw new RuntimeException(e); } } } } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/AcsError.java
package com.aliyuncs.v5; import com.aliyuncs.v5.transform.UnmarshallerContext; public class AcsError extends AcsResponse { private int statusCode; private String errorCode; private String errorMessage; private String requestId; private String errorDescription; 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; } public String getErrorDescription() { return errorDescription; } public void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } @Override public AcsError getInstance(UnmarshallerContext context) { return AcsErrorUnmarshaller.unmarshall(this, context); } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public String toString() { final StringBuffer sb = new StringBuffer("AcsError{"); sb.append("statusCode=").append(statusCode); sb.append(", errorCode='").append(errorCode).append('\''); sb.append(", errorMessage='").append(errorMessage).append('\''); sb.append(", requestId='").append(requestId).append('\''); sb.append(", errorDescription='").append(errorDescription).append('\''); sb.append('}'); return sb.toString(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/AcsErrorUnmarshaller.java
package com.aliyuncs.v5; import com.aliyuncs.v5.transform.UnmarshallerContext; import java.util.Map; 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") == null ? map.get("Error.requestId") : map.get("Error.RequestId")); error.setErrorCode(map.get("Error.Code") == null ? map.get("Error.code") : map.get("Error.Code")); error.setErrorMessage(map.get("Error.Message") == null ? map.get("Error.message") : map.get("Error.Message")); error.setErrorDescription(map.get("Error.Description") == null ? map.get("Error.description") : map.get("Error.Description")); return error; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/AcsRequest.java
package com.aliyuncs.v5; import com.aliyuncs.v5.auth.AcsURLEncoder; import com.aliyuncs.v5.auth.AlibabaCloudCredentials; import com.aliyuncs.v5.auth.ISignatureComposer; import com.aliyuncs.v5.auth.Signer; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.HttpRequest; import com.aliyuncs.v5.http.ProtocolType; import com.aliyuncs.v5.http.UserAgentConfig; import com.aliyuncs.v5.regions.ProductDomain; 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; @SuppressWarnings("deprecation") public abstract class AcsRequest<T extends AcsResponse> extends HttpRequest { private final Map<String, String> queryParameters = new HashMap<String, String>(); private final Map<String, String> domainParameters = new HashMap<String, String>(); private final Map<String, String> bodyParameters = new HashMap<String, String>(); private UserAgentConfig userAgentConfig; protected ISignatureComposer composer = null; private String version = null; private String product = null; private String actionName = null; private String regionId = null; private String securityToken = null; private FormatType acceptFormat = null; private ProtocolType protocol = null; private String locationProduct; private String endpointType; private ProductDomain productDomain = null; protected String strToSign; public HashMap<String, String> productEndpointMap = null; public String productEndpointRegional = null; public String productNetwork = "public"; public String productSuffix = ""; public AcsRequest(String product) { super(null); this.headers.put("x-sdk-client", "Java/2.0.0"); this.headers.put("x-sdk-invoke-type", "normal"); this.product = product; } 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(); } /** * @deprecated : Use setSysEndpoint instead of this */ @Deprecated public void setEndpoint(String endpoint) { ProductDomain productDomain = new ProductDomain(product, endpoint); setProductDomain(productDomain); } /** * @deprecated : Use getSysVersion instead of this */ @Deprecated public String getVersion() { return version; } /** * @deprecated : Use setSysVersion instead of this */ @Deprecated public void setVersion(String version) { this.version = version; } /** * @deprecated : Use getSysProduct instead of this */ @Deprecated public String getProduct() { return product; } /** * @deprecated : Use getSysActionName instead of this */ @Deprecated public String getActionName() { return actionName; } /** * @deprecated : Use setSysActionName instead of this */ @Deprecated public void setActionName(String actionName) { this.actionName = actionName; } /** * @deprecated : Use getSysRegionId instead of this */ @Deprecated public String getRegionId() { return regionId; } /** * @deprecated : Use setSysRegionId instead of this */ @Deprecated public void setRegionId(String regionId) { this.regionId = regionId; } /** * @deprecated : Use getSysSecurityToken instead of this */ @Deprecated public String getSecurityToken() { return securityToken; } /** * @deprecated : Use setSysSecurityToken instead of this */ @Deprecated public void setSecurityToken(String securityToken) { this.securityToken = securityToken; putQueryParameter("SecurityToken", securityToken); } /** * @deprecated : Use getSysAcceptFormat instead of this */ @Deprecated public FormatType getAcceptFormat() { return acceptFormat; } /** * @deprecated : Use setSysAcceptFormat instead of this */ @Deprecated public void setAcceptFormat(FormatType acceptFormat) { this.acceptFormat = acceptFormat; this.putHeaderParameter("Accept", FormatType.mapFormatToAccept(acceptFormat)); } /** * @deprecated : Use getSysProtocol instead of this */ @Deprecated public ProtocolType getProtocol() { return protocol; } /** * @deprecated : Use setSysProtocol instead of this */ @Deprecated public void setProtocol(ProtocolType protocol) { this.protocol = protocol; } /** * @deprecated : Use getSysQueryParameters instead of this */ @Deprecated public Map<String, String> getQueryParameters() { return Collections.unmodifiableMap(queryParameters); } public Map<String, String> getSysQueryParameters() { 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); } /** * @deprecated : Use getSysDomainParameters instead of this */ @Deprecated public Map<String, String> getDomainParameters() { return Collections.unmodifiableMap(domainParameters); } public Map<String, String> getSysDomainParameters() { return Collections.unmodifiableMap(domainParameters); } protected void putDomainParameter(String name, Object value) { setParameter(this.domainParameters, name, value); } /** * @deprecated : Use getSysBodyParameters instead of this */ @Deprecated public Map<String, String> getBodyParameters() { return Collections.unmodifiableMap(bodyParameters); } public Map<String, String> getSysBodyParameters() { return Collections.unmodifiableMap(bodyParameters); } protected void putDomainParameter(String name, String value) { setParameter(this.domainParameters, name, value); } protected void putBodyParameter(String name, Object value) { setParameter(this.bodyParameters, name, value); } protected void setParameter(Map<String, String> map, String name, Object value) { if (null == map || name == null || value == null) { return; } map.put(name, String.valueOf(value)); } /** * @deprecated : Use getSysLocationProduct instead of this */ @Deprecated public String getLocationProduct() { return locationProduct; } /** * @deprecated : Use setSysLocationProduct instead of this */ @Deprecated public void setLocationProduct(String locationProduct) { this.locationProduct = locationProduct; putQueryParameter("ServiceCode", locationProduct); } /** * @deprecated : Use getSysEndpointType instead of this */ @Deprecated public String getEndpointType() { return endpointType; } /** * @deprecated : Use setSysEndpointType instead of this */ @Deprecated public void setEndpointType(String endpointType) { this.endpointType = endpointType; putQueryParameter("Type", endpointType); } /** * @deprecated : Use getSysProductDomain instead of this */ @Deprecated public ProductDomain getProductDomain() { return productDomain; } /** * @deprecated : Use setSysProductDomain instead of this */ @Deprecated public void setProductDomain(ProductDomain productDomain) { this.productDomain = productDomain; } public abstract HttpRequest signRequest(Signer signer, AlibabaCloudCredentials credentials, 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(); public String getSysVersion() { return version; } public void setSysVersion(String version) { this.version = version; } public String getSysProduct() { return product; } public String getSysActionName() { return actionName; } public void setSysActionName(String actionName) { this.actionName = actionName; } public String getSysRegionId() { return regionId; } public void setSysRegionId(String regionId) { this.regionId = regionId; } public String getSysSecurityToken() { return securityToken; } public void setSysSecurityToken(String securityToken) { this.securityToken = securityToken; putQueryParameter("SecurityToken", securityToken); } public FormatType getSysAcceptFormat() { return acceptFormat; } public void setSysAcceptFormat(FormatType acceptFormat) { this.acceptFormat = acceptFormat; this.putHeaderParameter("Accept", FormatType.mapFormatToAccept(acceptFormat)); } public ProtocolType getSysProtocol() { return protocol; } public void setSysProtocol(ProtocolType protocol) { this.protocol = protocol; } public void setSysEndpoint(String endpoint) { ProductDomain productDomain = new ProductDomain(product, endpoint); setSysProductDomain(productDomain); } public String getSysLocationProduct() { return locationProduct; } public void setSysLocationProduct(String locationProduct) { this.locationProduct = locationProduct; putQueryParameter("ServiceCode", locationProduct); } public String getSysEndpointType() { return endpointType; } public void setSysEndpointType(String endpointType) { this.endpointType = endpointType; putQueryParameter("Type", endpointType); } public ProductDomain getSysProductDomain() { return productDomain; } public void setSysProductDomain(ProductDomain productDomain) { this.productDomain = productDomain; } public UserAgentConfig getSysUserAgentConfig() { return userAgentConfig; } public void appendUserAgent(String key, String value) { if (this.userAgentConfig == null) { this.userAgentConfig = new UserAgentConfig(); } this.userAgentConfig.append(key, value); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/AcsResponse.java
package com.aliyuncs.v5; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.transform.UnmarshallerContext; public abstract class AcsResponse { public abstract AcsResponse getInstance(UnmarshallerContext context) throws ClientException, ServerException; public boolean checkShowJsonItemName() { return true; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/CommonRequest.java
package com.aliyuncs.v5; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.http.ProtocolType; import com.aliyuncs.v5.regions.ProductDomain; import java.util.HashMap; import java.util.Map; public class CommonRequest { private final Map<String, String> queryParameters = new HashMap<String, String>(); private final Map<String, String> bodyParameters = new HashMap<String, String>(); private final Map<String, String> headParameters = new HashMap<String, String>(); private String version = null; private String product = null; private String action = null; private String locationProduct = null; private String endpointType = null; private String regionId = null; private ProtocolType protocol = null; private Integer connectTimeout = null; private Integer readTimeout = null; private MethodType method = null; private FormatType httpContentType = null; private byte[] httpContent = null; private String encoding = null; private String uriPattern = null; private Map<String, String> pathParameters = new HashMap<String, String>(); private String domain = null; @SuppressWarnings("rawtypes") public AcsRequest buildRequest() { if (uriPattern != null) { CommonRoaRequest request = new CommonRoaRequest(product); request.setSysUriPattern(uriPattern); for (String pathParamKey : pathParameters.keySet()) { request.putPathParameter(pathParamKey, pathParameters.get(pathParamKey)); } fillParams(request); return request; } else { CommonRpcRequest request = new CommonRpcRequest(product); fillParams(request); return request; } } @SuppressWarnings("rawtypes") private void fillParams(AcsRequest request) { request.putHeaderParameter("x-sdk-invoke-type", "common"); if (version != null) { request.setSysVersion(version); } if (action != null) { request.setSysActionName(action); } if (regionId != null) { request.setSysRegionId(regionId); } if (locationProduct != null) { request.setSysLocationProduct(locationProduct); } if (endpointType != null) { request.setSysEndpointType(endpointType); } if (connectTimeout != null) { request.setSysConnectTimeout(connectTimeout); } if (readTimeout != null) { request.setSysReadTimeout(readTimeout); } if (method != null) { request.setSysMethod(method); } if (protocol != null) { request.setSysProtocol(protocol); } if (domain != null) { ProductDomain productDomain = new ProductDomain(product, domain); request.setSysProductDomain(productDomain); } if (httpContent != null) { request.setHttpContent(httpContent, encoding, httpContentType); } for (String queryParamKey : queryParameters.keySet()) { request.putQueryParameter(queryParamKey, queryParameters.get(queryParamKey)); } for (String bodyParamKey : bodyParameters.keySet()) { request.putBodyParameter(bodyParamKey, bodyParameters.get(bodyParamKey)); } for (String headParamKey : headParameters.keySet()) { request.putHeaderParameter(headParamKey, headParameters.get(headParamKey)); } } /** * @Deprecated : Use getSysVersion instead of this */ @Deprecated public String getVersion() { return version; } /** * @Deprecated : Use setSysVersion instead of this */ @Deprecated public void setVersion(String version) { this.version = version; } /** * @Deprecated : Use getSysProduct instead of this */ @Deprecated public String getProduct() { return product; } /** * @Deprecated : Use setSysProduct instead of this */ @Deprecated public void setProduct(String product) { this.product = product; } /** * @Deprecated : Use getSysAction instead of this */ @Deprecated public String getAction() { return action; } /** * @Deprecated : Use setSysAction instead of this */ @Deprecated public void setAction(String action) { this.action = action; } /** * @Deprecated : Use getSysLocationProduct instead of this */ @Deprecated public String getLocationProduct() { return locationProduct; } /** * @Deprecated : Use setSysLocationProduct instead of this */ @Deprecated public void setLocationProduct(String locationProduct) { this.locationProduct = locationProduct; } /** * @Deprecated : Use getSysEndpointType instead of this */ @Deprecated public String getEndpointType() { return endpointType; } /** * @Deprecated : Use setSysEndpointType instead of this */ @Deprecated public void setEndpointType(String endpointType) { this.endpointType = endpointType; } /** * @Deprecated : Use getSysRegionId instead of this */ @Deprecated public String getRegionId() { return regionId; } /** * @Deprecated : Use setSysRegionId instead of this */ @Deprecated public void setRegionId(String regionId) { this.regionId = regionId; } /** * @Deprecated : Use getSysProtocol instead of this */ @Deprecated public ProtocolType getProtocol() { return protocol; } /** * @Deprecated : Use setSysProtocol instead of this */ @Deprecated public void setProtocol(ProtocolType protocol) { this.protocol = protocol; } public void putBodyParameter(String name, Object value) { setParameter(this.bodyParameters, name, value); } public void putQueryParameter(String name, String value) { setParameter(this.queryParameters, name, value); } public void putHeadParameter(String name, String value) { setParameter(this.headParameters, name, value); } private void setParameter(Map<String, String> map, String name, Object value) { if (null == map || name == null || value == null) { return; } map.put(name, String.valueOf(value)); } /** * @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 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; } /** * @Deprecated : Use getSysUriPattern instead of this */ @Deprecated public String getUriPattern() { return uriPattern; } /** * @Deprecated : Use setSysUriPattern instead of this */ @Deprecated public void setUriPattern(String uriPattern) { this.uriPattern = uriPattern; } public void putPathParameter(String name, String value) { setParameter(this.pathParameters, name, value); } /** * @Deprecated : Use getSysDomain instead of this */ @Deprecated public String getDomain() { return domain; } /** * @Deprecated : Use setSysDomain instead of this */ @Deprecated public void setDomain(String domain) { this.domain = domain; } public FormatType getHttpContentType() { return httpContentType; } public byte[] getHttpContent() { return httpContent; } /** * @Deprecated : Use getSysEncoding instead of this */ @Deprecated public String getEncoding() { return encoding; } /** * @Deprecated : Use getSysQueryParameters instead of this */ @Deprecated public Map<String, String> getQueryParameters() { return queryParameters; } /** * @Deprecated : Use getSysBodyParameters instead of this */ @Deprecated public Map<String, String> getBodyParameters() { return bodyParameters; } /** * @Deprecated : Use getSysHeadParameters instead of this */ @Deprecated public Map<String, String> getHeadParameters() { return headParameters; } /** * @Deprecated : Use getSysPathParameters instead of this */ @Deprecated public Map<String, String> getPathParameters() { return pathParameters; } public void setHttpContent(byte[] content, String encoding, FormatType format) { if (content == null || encoding == null || format == null) { return; } this.httpContent = content; this.httpContentType = format; this.encoding = encoding; } public String getSysVersion() { return version; } public void setSysVersion(String version) { this.version = version; } public String getSysProduct() { return product; } public void setSysProduct(String product) { this.product = product; } public String getSysAction() { return action; } public void setSysAction(String action) { this.action = action; } public String getSysLocationProduct() { return locationProduct; } public void setSysLocationProduct(String locationProduct) { this.locationProduct = locationProduct; } public String getSysEndpointType() { return endpointType; } public void setSysEndpointType(String endpointType) { this.endpointType = endpointType; } public String getSysRegionId() { return regionId; } public void setSysRegionId(String regionId) { this.regionId = regionId; } public ProtocolType getSysProtocol() { return protocol; } public void setSysProtocol(ProtocolType protocol) { this.protocol = protocol; } 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 MethodType getSysMethod() { return method; } public void setSysMethod(MethodType method) { this.method = method; } public String getSysUriPattern() { return uriPattern; } public void setSysUriPattern(String uriPattern) { this.uriPattern = uriPattern; } public String getSysDomain() { return domain; } public void setSysDomain(String domain) { this.domain = domain; } public String getSysEncoding() { return encoding; } public Map<String, String> getSysQueryParameters() { return queryParameters; } public Map<String, String> getSysBodyParameters() { return bodyParameters; } public Map<String, String> getSysHeadParameters() { return headParameters; } public Map<String, String> getSysPathParameters() { return pathParameters; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/CommonResponse.java
package com.aliyuncs.v5; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.http.HttpResponse; import com.aliyuncs.v5.transform.UnmarshallerContext; public class CommonResponse extends AcsResponse { private String data; private int httpStatus; private HttpResponse httpResponse; @Override public AcsResponse getInstance(UnmarshallerContext context) throws ClientException, ServerException { return null; } public String getData() { return data; } public void setData(String data) { this.data = data; } public int getHttpStatus() { return httpStatus; } public void setHttpStatus(int httpStatus) { this.httpStatus = httpStatus; } public HttpResponse getHttpResponse() { return httpResponse; } public void setHttpResponse(HttpResponse httpResponse) { this.httpResponse = httpResponse; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/CommonRoaRequest.java
package com.aliyuncs.v5; import com.aliyuncs.v5.http.FormatType; public class CommonRoaRequest extends RoaAcsRequest<CommonResponse> { public CommonRoaRequest(String product) { super(product); setSysAcceptFormat(FormatType.JSON); } public CommonRoaRequest(String product, String version, String action) { super(product, version, action); setSysAcceptFormat(FormatType.JSON); } public CommonRoaRequest(String product, String version, String action, String locationProduct) { super(product, version, action, locationProduct); setSysAcceptFormat(FormatType.JSON); } public CommonRoaRequest(String product, String version, String action, String locationProduct, String endpointType) { super(product, version, action, locationProduct, endpointType); setSysAcceptFormat(FormatType.JSON); } @Override public Class<CommonResponse> getResponseClass() { return CommonResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/CommonRpcRequest.java
package com.aliyuncs.v5; import com.aliyuncs.v5.http.FormatType; public class CommonRpcRequest extends RpcAcsRequest<CommonResponse> { public CommonRpcRequest(String product) { super(product); setAcceptFormat(FormatType.JSON); } public CommonRpcRequest(String product, String version, String action) { super(product, version, action); setAcceptFormat(FormatType.JSON); } public CommonRpcRequest(String product, String version, String action, String locationProduct) { super(product, version, action, locationProduct); setAcceptFormat(FormatType.JSON); } public CommonRpcRequest(String product, String version, String action, String locationProduct, String endpointType) { super(product, version, action, locationProduct, endpointType); setAcceptFormat(FormatType.JSON); } @Override public Class<CommonResponse> getResponseClass() { return CommonResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/CoreMessage.java
package com.aliyuncs.v5; public interface CoreMessage { String coreVersion = "5.0.0"; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/DefaultAcsClient.java
package com.aliyuncs.v5; import com.aliyuncs.v5.auth.*; import com.aliyuncs.v5.endpoint.DefaultEndpointResolver; import com.aliyuncs.v5.endpoint.EndpointResolver; import com.aliyuncs.v5.endpoint.ResolveEndpointRequest; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ErrorCodeConstant; import com.aliyuncs.v5.exceptions.ErrorMessageConstant; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.http.*; import com.aliyuncs.v5.profile.DefaultProfile; import com.aliyuncs.v5.profile.IClientProfile; import com.aliyuncs.v5.reader.Reader; import com.aliyuncs.v5.reader.ReaderFactory; import com.aliyuncs.v5.regions.ProductDomain; import com.aliyuncs.v5.transform.UnmarshallerContext; import com.aliyuncs.v5.unmarshaller.Unmarshaller; import com.aliyuncs.v5.unmarshaller.UnmarshallerFactory; import com.aliyuncs.v5.utils.*; import io.opentracing.Span; import io.opentracing.Tracer; import io.opentracing.propagation.Format; import io.opentracing.tag.Tags; import io.opentracing.util.GlobalTracer; import org.slf4j.Logger; import javax.xml.bind.annotation.XmlRootElement; import java.io.IOException; import java.net.SocketTimeoutException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; @SuppressWarnings("deprecation") public class DefaultAcsClient implements IAcsClient { /* Now maxRetryNumber and autoRetry has no effect. */ private int maxRetryNumber = 3; private boolean autoRetry = true; private IClientProfile clientProfile = null; private AlibabaCloudCredentialsProvider credentialsProvider; private DefaultCredentialsProvider defaultCredentialsProvider; private IHttpClient httpClient; private EndpointResolver endpointResolver; private static final String SIGNATURE_BEGIN = "string to sign is:"; private final UserAgentConfig userAgentConfig = new UserAgentConfig(); /** * @Deprecated : Use DefaultAcsClient(String regionId) instead of this */ @Deprecated public DefaultAcsClient() throws ClientException { this.clientProfile = DefaultProfile.getProfile(); this.httpClient = HttpClientFactory.buildClient(this.clientProfile); } public DefaultAcsClient(String regionId) throws ClientException { this.clientProfile = DefaultProfile.getProfile(regionId); this.httpClient = HttpClientFactory.buildClient(this.clientProfile); this.defaultCredentialsProvider = new DefaultCredentialsProvider(); this.endpointResolver = new DefaultEndpointResolver(this); this.appendUserAgent("HTTPClient", this.httpClient.getClass().getSimpleName()); } public DefaultAcsClient(IClientProfile profile) { this(profile, new StaticCredentialsProvider(profile)); } public DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentials credentials) { this(profile, new StaticCredentialsProvider(credentials)); } public DefaultAcsClient(IClientProfile profile, AlibabaCloudCredentialsProvider credentialsProvider) { this.clientProfile = profile; this.credentialsProvider = credentialsProvider; this.clientProfile.setCredentialsProvider(this.credentialsProvider); this.httpClient = HttpClientFactory.buildClient(this.clientProfile); this.endpointResolver = new DefaultEndpointResolver(this, profile); this.appendUserAgent("HTTPClient", this.httpClient.getClass().getSimpleName()); } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request) throws ClientException, ServerException { return this.doAction(request, autoRetry, maxRetryNumber, this.clientProfile); } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ClientException, ServerException { return this.doAction(request, autoRetry, maxRetryCounts, this.clientProfile); } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, IClientProfile profile) throws ClientException, ServerException { return this.doAction(request, this.autoRetry, this.maxRetryNumber, profile); } @Override public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, String regionId, Credential credential) throws ClientException, ServerException { Signer signer = Signer.getSigner(new LegacyCredentials(credential)); FormatType format = null; if (null == request.getSysRegionId()) { request.setSysRegionId(regionId); } return doAction(request, autoRetry, maxRetryNumber, regionId, new LegacyCredentials(credential), signer, format); } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request) throws ServerException, ClientException { HttpResponse baseResponse = this.doAction(request); return parseAcsResponse(request, baseResponse); } @Override 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, baseResponse); } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, IClientProfile profile) throws ServerException, ClientException { HttpResponse baseResponse = this.doAction(request, profile); return parseAcsResponse(request, baseResponse); } @Override 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, baseResponse); } @Override public <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId) throws ServerException, ClientException { if (null == request.getSysRegionId()) { request.setSysRegionId(regionId); } HttpResponse baseResponse = this.doAction(request); return parseAcsResponse(request, baseResponse); } @SuppressWarnings("unchecked") @Override public CommonResponse getCommonResponse(CommonRequest request) throws ServerException, ClientException { HttpResponse baseResponse = this.doAction(request.buildRequest()); if (baseResponse.isSuccess()) { String stringContent = baseResponse.getHttpContentString(); CommonResponse response = new CommonResponse(); response.setData(stringContent); response.setHttpStatus(baseResponse.getStatus()); response.setHttpResponse(baseResponse); return response; } else { FormatType format = baseResponse.getHttpContentType(); 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()); } } } @Override 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(); if (null == request.getSysRegionId()) { request.setSysRegionId(region); } AlibabaCloudCredentials credentials; if (null == credentialsProvider) { credentials = this.defaultCredentialsProvider.getCredentials(); } else { credentials = this.credentialsProvider.getCredentials(); } Signer signer = Signer.getSigner(credentials); FormatType format = profile.getFormat(); return this.doAction(request, retry, retryNumber, request.getSysRegionId(), credentials, signer, format); } private <T extends AcsResponse> T parseAcsResponse(AcsRequest<T> request, HttpResponse baseResponse) throws ServerException, ClientException { FormatType format = baseResponse.getHttpContentType(); if (FormatType.JSON != format && FormatType.XML != format) { throw new ClientException(String.format("Server response has a bad format type: %s;\nThe original return is: %s;" , format, baseResponse.getHttpContentString())); } if (baseResponse.isSuccess()) { return readResponse(request.getResponseClass(), baseResponse, format); } else { AcsError error = readError(baseResponse, format); if (500 <= baseResponse.getStatus()) { throw new ServerException(error.getErrorCode(), error.getErrorMessage(), error.getRequestId()); } else if (400 == baseResponse.getStatus() && ("IncompleteSignature".equals(error.getErrorCode()) || "SignatureDoesNotMatch".equals(error.getErrorCode()))) { String errorMessage = error.getErrorMessage(); Pattern startPattern = Pattern.compile(SIGNATURE_BEGIN); Matcher startMatcher = startPattern.matcher(errorMessage); if (startMatcher.find()) { int start = startMatcher.end(); String errorStrToSign = errorMessage.substring(start); if (request.strToSign.equals(errorStrToSign)) { throw new ClientException("SDK.InvalidAccessKeySecret", "Specified Access Key Secret is not valid.", error.getRequestId()); } } } throw new ClientException(error.getErrorCode(), error.getErrorMessage(), error.getRequestId(), error.getErrorDescription()); } } /** * @Deprecated : Use other overload methods */ @Deprecated public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber, String regionId, Credential credential, Signer signer, FormatType format) throws ClientException, ServerException { return doAction(request, autoRetry, maxRetryNumber, regionId, new LegacyCredentials(credential), signer, format); } public ProductDomain getDomain(AcsRequest request, String regionId) throws ClientException { ProductDomain domain = null; if (request.getSysProductDomain() != null) { domain = request.getSysProductDomain(); } else { ResolveEndpointRequest resolveEndpointRequest = new ResolveEndpointRequest(regionId, request.getSysProduct(), request.getSysLocationProduct(), request.getSysEndpointType()); resolveEndpointRequest.setProductEndpointMap(request.productEndpointMap); resolveEndpointRequest.setProductEndpointRegional(request.productEndpointRegional); resolveEndpointRequest.setProductNetwork(request.productNetwork); resolveEndpointRequest.setProductSuffix(request.productSuffix); String endpoint = endpointResolver.resolve(resolveEndpointRequest); domain = new ProductDomain(request.getSysProduct(), endpoint); if (endpoint.endsWith("endpoint-test.exception.com")) { // For endpoint testability, if the endpoint is xxxx.endpoint-test.special.com // throw a client exception with this endpoint throw new ClientException(ErrorCodeConstant.SDK_ENDPOINT_TESTABILITY, endpoint); } } return domain; } private <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber, String regionId, AlibabaCloudCredentials credentials, Signer signer, FormatType format) throws ClientException, ServerException { if (!GlobalTracer.isRegistered() || clientProfile.isCloseTrace() ) { return doRealAction(request, autoRetry, maxRetryNumber, regionId, credentials, signer,format); } Tracer tracer = GlobalTracer.get(); Span span = tracer.buildSpan(request.getSysUrl()) .withTag(Tags.COMPONENT.getKey(), "aliyunApi") .withTag("actionName", request.getSysActionName()) .withTag("queryParam", MapUtils.getMapString(request.getQueryParameters())) .start(); tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpHeadersInjectAdapter(request)); try { HttpResponse response = doRealAction(request, autoRetry, maxRetryNumber, regionId, credentials, signer,format); span.setTag("status", response.getStatus()); span.setTag("ReasonPhrase", response.getReasonPhrase()); return response; } catch (ClientException ex) { TraceUtils.onError(ex, span); throw ex; } finally { span.finish(); } } private <T extends AcsResponse> HttpResponse doRealAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber, String regionId, AlibabaCloudCredentials credentials, Signer signer, FormatType format) throws ClientException, ServerException { doActionWithProxy(request.getSysProtocol(), System.getenv("HTTPS_PROXY"), System.getenv("HTTP_PROXY")); doActionWithIgnoreSSL(request, X509TrustAll.ignoreSSLCerts); Logger logger = clientProfile.getLogger(); String startTime = ""; String timeCost = ""; HttpResponse response = null; String errorMessage = ""; try { FormatType requestFormatType = request.getSysAcceptFormat(); if (null != requestFormatType) { format = requestFormatType; } ProductDomain domain = getDomain(request, regionId); if (request.getSysProtocol() == null) { request.setSysProtocol(this.clientProfile.getHttpClientConfig().getProtocolType()); } request.putHeaderParameter("User-Agent", UserAgentConfig.resolve(request.getSysUserAgentConfig(), this.userAgentConfig)); try { HttpRequest httpRequest = request.signRequest(signer, credentials, format, domain); HttpUtil.debugHttpRequest(request); startTime = LogUtils.localeNow(); long start = System.nanoTime(); response = this.httpClient.syncInvoke(httpRequest); long end = System.nanoTime(); timeCost = TimeUnit.NANOSECONDS.toMillis(end - start) + "ms"; HttpUtil.debugHttpResponse(response); return response; } catch (SocketTimeoutException exp) { errorMessage = exp.getMessage(); throw new ClientException("SDK.ReadTimeout", "SocketTimeoutException has occurred on a socket read or accept.The url is " + request.getSysUrl(), exp); } catch (IOException exp) { errorMessage = exp.getMessage(); throw new ClientException("SDK.ServerUnreachable", "Server unreachable: connection " + request.getSysUrl() + " failed", exp); } } catch (InvalidKeyException exp) { errorMessage = exp.getMessage(); throw new ClientException("SDK.InvalidAccessSecret", "Specified access secret is not valid.", exp); } catch (NoSuchAlgorithmException exp) { errorMessage = exp.getMessage(); throw new ClientException("SDK.InvalidMD5Algorithm", "MD5 hash is not supported by client side.", exp); } finally { if (null != logger) { try { LogUtils.LogUnit logUnit = LogUtils.createLogUnit(request, response); logUnit.setStartTime(startTime); logUnit.setCost(timeCost); logUnit.setError(errorMessage); String logContent = LogUtils.fillContent(clientProfile.getLogFormat(), logUnit); logger.info(logContent); } catch (Throwable e) { e.printStackTrace(); } } } } /** * 2019-01-03 change access control from private to protected, then subClass can * override it and rewrite httpResponse processing */ protected <T extends AcsResponse> T readResponse(Class<T> clasz, HttpResponse httpResponse, FormatType format) throws ClientException { // new version response contains "@XmlRootElement" annotation if (clasz.isAnnotationPresent(XmlRootElement.class) && !clientProfile.getHttpClientConfig().isCompatibleMode()) { Unmarshaller unmarshaller = UnmarshallerFactory.getUnmarshaller(format); return unmarshaller.unmarshal(clasz, httpResponse.getHttpContentString()); } else { Reader reader = ReaderFactory.createInstance(format); UnmarshallerContext context = new UnmarshallerContext(); T response = null; String stringContent = httpResponse.getHttpContentString(); if (stringContent == null) { throw new ClientException(ErrorCodeConstant.SDK_INVALID_SERVER_RESPONSE, ErrorMessageConstant.SERVER_RESPONSE_HTTP_BODY_EMPTY); } 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); if (response.checkShowJsonItemName()) { context.setResponseMap(reader.read(stringContent, responseEndpoint)); } else { context.setResponseMap(reader.readForHideArrayItem(stringContent, responseEndpoint)); } context.setHttpResponse(httpResponse); response.getInstance(context); return response; } } 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 = httpResponse.getHttpContentString(); if (stringContent == null) { error.setErrorCode("(null)"); error.setErrorMessage("(null)"); error.setRequestId("(null)"); error.setStatusCode(httpResponse.getStatus()); return error; } else { context.setResponseMap(reader.read(stringContent, responseEndpoint)); return error.getInstance(context); } } /** * Compatible with previous versions of proxy Settings */ public void doActionWithProxy(ProtocolType protocolType, String httpsProxy, String httpProxy) { HttpClientConfig config = this.clientProfile.getHttpClientConfig(); if (protocolType == ProtocolType.HTTP && httpProxy != null) { config.setHttpProxy(httpProxy); return; } if (protocolType == ProtocolType.HTTPS && httpsProxy != null) { config.setHttpsProxy(httpsProxy); return; } } /** * Compatible with previous versions of SSL Settings */ public void doActionWithIgnoreSSL(AcsRequest request, boolean isIgnore) { if (isIgnore) { request.setIgnoreSSLCerts(true); } } @Deprecated public boolean isAutoRetry() { return autoRetry; } @Deprecated public void setAutoRetry(boolean autoRetry) { this.autoRetry = autoRetry; } @Deprecated public int getMaxRetryNumber() { return maxRetryNumber; } @Deprecated public void setMaxRetryNumber(int maxRetryNumber) { this.maxRetryNumber = maxRetryNumber; } @Override public void restoreSSLCertificate() { this.httpClient.restoreSSLCertificate(); } @Override public void ignoreSSLCertificate() { this.httpClient.ignoreSSLCertificate(); } public void setEndpointResolver(EndpointResolver resolver) { endpointResolver = resolver; } @Override public void shutdown() { if (!this.httpClient.isSingleton()) { IOUtils.closeQuietly(this.httpClient); this.httpClient = null; } } public DefaultProfile getProfile() { return (DefaultProfile) clientProfile; } public void appendUserAgent(String key, String value) { this.userAgentConfig.append(key, value); } public UserAgentConfig getUserAgentConfig() { return userAgentConfig; } public IHttpClient getHttpClient() { return httpClient; } public void setHttpClient(IHttpClient httpClient) { this.httpClient = httpClient; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/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.v5; import com.aliyuncs.v5.auth.Credential; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.http.HttpResponse; import com.aliyuncs.v5.profile.IClientProfile; public interface IAcsClient { <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request) throws ClientException, ServerException; <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ClientException, ServerException; <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, IClientProfile profile) throws ClientException, ServerException; <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, String regionId, Credential credential) throws ClientException, ServerException; <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request) throws ServerException, ClientException; <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts) throws ServerException, ClientException; <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, IClientProfile profile) throws ServerException, ClientException; <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId, Credential credential) throws ServerException, ClientException; <T extends AcsResponse> T getAcsResponse(AcsRequest<T> request, String regionId) throws ServerException, ClientException; CommonResponse getCommonResponse(CommonRequest request) throws ServerException, ClientException; <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryCounts, IClientProfile profile) throws ClientException, ServerException; void restoreSSLCertificate(); void ignoreSSLCertificate(); void shutdown(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/RoaAcsRequest.java
package com.aliyuncs.v5; import com.aliyuncs.v5.auth.*; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.HttpRequest; import com.aliyuncs.v5.regions.ProductDomain; import com.aliyuncs.v5.utils.ParameterHelper; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; 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, String action) { super(product); this.setSysVersion(version); this.setSysActionName(action); initialize(); } public RoaAcsRequest(String product, String version, String action, String locationProduct) { super(product); this.setSysVersion(version); this.setSysActionName(action); this.setSysLocationProduct(locationProduct); initialize(); } public RoaAcsRequest(String product, String version, String action, String locationProduct, String endpointType) { super(product); this.setSysVersion(version); this.setSysActionName(action); this.setSysLocationProduct(locationProduct); this.setSysEndpointType(endpointType); initialize(); } private void initialize() { this.composer = RoaSignatureComposer.getComposer(); this.setHttpContentType(FormatType.FORM); this.setHttpContent(new byte[0], "utf-8", null); } @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); } @Override public void setSysVersion(String version) { super.setSysVersion(version); this.putHeaderParameter("x-acs-version", version); } 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); } @Override public String composeUrl(String endpoint, Map<String, String> queries) throws UnsupportedEncodingException { Map<String, String> mapQueries = (queries == null) ? this.getSysQueryParameters() : queries; StringBuilder urlBuilder = new StringBuilder(""); urlBuilder.append(this.getSysProtocol().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; } /** * @Deprecated : Use getSysUriPattern instead of this */ @Deprecated public String getUriPattern() { return uriPattern; } /** * @Deprecated : Use setSysUriPattern instead of this */ @Deprecated public void setUriPattern(String uriPattern) { this.uriPattern = uriPattern; } public String getSysUriPattern() { return uriPattern; } public void setSysUriPattern(String uriPattern) { this.uriPattern = uriPattern; } @Override public HttpRequest signRequest(Signer signer, AlibabaCloudCredentials credentials, FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException { Map<String, String> bodyParams = this.getSysBodyParameters(); if (bodyParams != null && !bodyParams.isEmpty()) { byte[] data; if (FormatType.JSON == this.getHttpContentType()) { data = ParameterHelper.getJsonData(bodyParams); } else if (FormatType.XML == this.getHttpContentType()) { data = ParameterHelper.getXmlData(bodyParams); } else { // For contentType RAW and Form, the actual data format will be form data = ParameterHelper.getFormData(bodyParams); } this.setHttpContent(data, "UTF-8", null); } Map<String, String> imutableMap = new HashMap<String, String>(this.getSysHeaders()); if (null != signer && null != credentials) { String accessKeyId = credentials.getAccessKeyId(); imutableMap = this.composer.refreshSignParameters(this.getSysHeaders(), signer, accessKeyId, format); imutableMap.put("RegionId", this.getSysRegionId()); if (credentials instanceof BasicSessionCredentials) { String sessionToken = ((BasicSessionCredentials) credentials).getSessionToken(); if (null != sessionToken) { imutableMap.put("x-acs-security-token", sessionToken); } } if (credentials instanceof BearerTokenCredentials) { String bearerToken = ((BearerTokenCredentials) credentials).getBearerToken(); if (null != ((BearerTokenCredentials) credentials).getBearerToken()) { imutableMap.put("x-acs-bearer-token", bearerToken); } } String strToSign = this.composer.composeStringToSign(this.getSysMethod(), this.getSysUriPattern(), signer, this.getSysQueryParameters(), imutableMap, this.getPathParameters()); String signature = signer.signString(strToSign, credentials); imutableMap.put("Authorization", "acs " + accessKeyId + ":" + signature); } this.setSysUrl(this.composeUrl(domain.getDomainName(), this.getSysQueryParameters())); this.headers = imutableMap; return this; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/RpcAcsRequest.java
package com.aliyuncs.v5; import com.aliyuncs.v5.auth.*; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.HttpRequest; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.regions.ProductDomain; import com.aliyuncs.v5.utils.ParameterHelper; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.util.HashMap; import java.util.Map; public abstract class RpcAcsRequest<T extends AcsResponse> extends AcsRequest<T> { public RpcAcsRequest(String product) { super(product); initialize(); } public RpcAcsRequest(String product, String version, String action) { super(product); this.setSysVersion(version); this.setSysActionName(action); initialize(); } public RpcAcsRequest(String product, String version, String action, String locationProduct) { super(product); this.setSysVersion(version); this.setSysActionName(action); this.setSysLocationProduct(locationProduct); initialize(); } public RpcAcsRequest(String product, String version, String action, String locationProduct, String endpointType) { super(product); this.setSysVersion(version); this.setSysActionName(action); this.setSysLocationProduct(locationProduct); this.setSysEndpointType(endpointType); initialize(); } private void initialize() { this.setSysMethod(MethodType.GET); this.setSysAcceptFormat(FormatType.JSON); this.setHttpContentType(FormatType.FORM); 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()); } @Override public void setSysActionName(String actionName) { super.setSysActionName(actionName); this.putQueryParameter("Action", actionName); } @Override public void setSysVersion(String version) { super.setSysVersion(version); this.putQueryParameter("Version", version); } @Override public void setSysAcceptFormat(FormatType acceptFormat) { super.setSysAcceptFormat(acceptFormat); this.putQueryParameter("Format", acceptFormat.toString()); } @Override public void setSysSecurityToken(String securityToken) { super.setSysSecurityToken(securityToken); this.putQueryParameter("SecurityToken", securityToken); } @Override public String composeUrl(String endpoint, Map<String, String> queries) throws UnsupportedEncodingException { Map<String, String> mapQueries = (queries == null) ? this.getSysQueryParameters() : queries; StringBuilder urlBuilder = new StringBuilder(""); urlBuilder.append(this.getSysProtocol().toString()); urlBuilder.append("://").append(endpoint); if (-1 == urlBuilder.indexOf("?")) { urlBuilder.append("/?"); } String query = concatQueryString(mapQueries); return urlBuilder.append(query).toString(); } @Override public HttpRequest signRequest(Signer signer, AlibabaCloudCredentials credentials, FormatType format, ProductDomain domain) throws InvalidKeyException, IllegalStateException, UnsupportedEncodingException { Map<String, String> imutableMap = new HashMap<String, String>(this.getSysQueryParameters()); if (null != signer && null != credentials) { String accessKeyId = credentials.getAccessKeyId(); String accessSecret = credentials.getAccessKeySecret(); if (credentials instanceof BasicSessionCredentials) { String sessionToken = ((BasicSessionCredentials) credentials).getSessionToken(); if (null != sessionToken) { this.putQueryParameter("SecurityToken", sessionToken); } } if (credentials instanceof BearerTokenCredentials) { String bearerToken = ((BearerTokenCredentials) credentials).getBearerToken(); if (null != ((BearerTokenCredentials) credentials).getBearerToken()) { this.putQueryParameter("BearerToken", bearerToken); } } imutableMap = this.composer.refreshSignParameters(this.getSysQueryParameters(), signer, accessKeyId, format); imutableMap.put("RegionId", getSysRegionId()); Map<String, String> paramsToSign = new HashMap<String, String>(imutableMap); Map<String, String> bodyParams = this.getSysBodyParameters(); if (bodyParams != null && !bodyParams.isEmpty()) { byte[] data; if (FormatType.JSON == this.getHttpContentType()) { data = ParameterHelper.getJsonData(bodyParams); } else if (FormatType.XML == this.getHttpContentType()) { data = ParameterHelper.getXmlData(bodyParams); } else { // For contentType RAW and Form, the actual data format will be form data = ParameterHelper.getFormData(bodyParams); } this.setHttpContent(data, "UTF-8", null); paramsToSign.putAll(bodyParams); } String strToSign = this.composer.composeStringToSign( this.getSysMethod(), null, signer, paramsToSign, null, null); String signature; if (credentials instanceof KeyPairCredentials) { signature = signer.signString(strToSign, credentials); } else { signature = signer.signString(strToSign, accessSecret + "&"); } imutableMap.put("Signature", signature); this.strToSign = strToSign; } setSysUrl(this.composeUrl(domain.getDomainName(), imutableMap)); return this; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/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.v5.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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/AlibabaCloudCredentials.java
package com.aliyuncs.v5.auth; public interface AlibabaCloudCredentials { String getAccessKeyId(); String getAccessKeySecret(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/AlibabaCloudCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; public interface AlibabaCloudCredentialsProvider { AlibabaCloudCredentials getCredentials() throws ClientException, ServerException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/AuthConstant.java
package com.aliyuncs.v5.auth; public class AuthConstant { public static final String SYSTEM_ACCESSKEYID = "alibabacloud.accessKeyId"; public static final String SYSTEM_ACCESSKEYSECRET = "alibabacloud.accessKeyIdSecret"; public static final String DEFAULT_CREDENTIALS_FILE_PATH = System.getProperty("user.home") + "/.alibabacloud/credentials.ini"; public static final String INI_ACCESS_KEY_ID = "access_key_id"; public static final String INI_ACCESS_KEY_IDSECRET = "access_key_secret"; public static final String INI_TYPE = "type"; public static final String INI_TYPE_RAM = "ecs_ram_role"; public static final String INI_TYPE_ARN = "ram_role_arn"; public static final String INI_TYPE_KEY_PAIR = "rsa_key_pair"; public static final String INI_PUBLIC_KEY_ID = "public_key_id"; public static final String INI_PRIVATE_KEY_FILE = "private_key_file"; public static final String INI_PRIVATE_KEY = "private_key"; public static final String INI_ROLE_NAME = "role_name"; public static final String INI_ROLE_SESSION_NAME = "role_session_name"; public static final String INI_ROLE_ARN = "role_arn"; public static final String INI_POLICY = "policy"; public static final long TSC_VALID_TIME_SECONDS = 3600L; public static final String DEFAULT_REGION = "region_id"; public static final String INI_ENABLE = "enable"; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/BasicCredentials.java
package com.aliyuncs.v5.auth; public class BasicCredentials implements AlibabaCloudCredentials { private final String accessKeyId; private final String accessKeySecret; public BasicCredentials(String accessKeyId, String accessKeySecret) { if (accessKeyId == null) { throw new IllegalArgumentException("Access key ID cannot be null."); } if (accessKeySecret == null) { throw new IllegalArgumentException("Access key secret cannot be null."); } this.accessKeyId = accessKeyId; this.accessKeySecret = accessKeySecret; } @Override public String getAccessKeyId() { return accessKeyId; } @Override public String getAccessKeySecret() { return accessKeySecret; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/BasicSessionCredentials.java
package com.aliyuncs.v5.auth; public class BasicSessionCredentials implements AlibabaCloudCredentials { protected final long roleSessionDurationSeconds; private final String accessKeyId; private final String accessKeySecret; private final String sessionToken; private long sessionStartedTimeInMilliSeconds = 0; public BasicSessionCredentials(String accessKeyId, String accessKeySecret, String sessionToken) { this(accessKeyId, accessKeySecret, sessionToken, 0); } public BasicSessionCredentials(String accessKeyId, String accessKeySecret, String sessionToken, long roleSessionDurationSeconds) { if (accessKeyId == null) { throw new IllegalArgumentException("Access key ID cannot be null."); } if (accessKeySecret == null) { throw new IllegalArgumentException("Access key secret cannot be null."); } this.accessKeyId = accessKeyId; this.accessKeySecret = accessKeySecret; this.sessionToken = sessionToken; this.roleSessionDurationSeconds = roleSessionDurationSeconds; this.sessionStartedTimeInMilliSeconds = System.currentTimeMillis(); } @Override public String getAccessKeyId() { return accessKeyId; } @Override public String getAccessKeySecret() { return accessKeySecret; } public String getSessionToken() { return sessionToken; } public boolean willSoonExpire() { if (roleSessionDurationSeconds == 0) { return false; } long now = System.currentTimeMillis(); double expireFact = 0.95; return roleSessionDurationSeconds * expireFact < (now - sessionStartedTimeInMilliSeconds) / 1000.0; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/BearerTokenCredentials.java
package com.aliyuncs.v5.auth; public class BearerTokenCredentials implements AlibabaCloudCredentials { private String bearerToken; public BearerTokenCredentials(String bearerToken) { this.bearerToken = bearerToken; } @Override public String getAccessKeyId() { return null; } @Override public String getAccessKeySecret() { return null; } public String getBearerToken() { return bearerToken; } public void setBearerToken(String bearerToken) { this.bearerToken = bearerToken; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/BearerTokenSigner.java
package com.aliyuncs.v5.auth; public class BearerTokenSigner extends Signer { @Override public String signString(String stringToSign, AlibabaCloudCredentials credentials) { return null; } @Override public String signString(String stringToSign, String accessKeySecret) { return null; } @Override public String getSignerName() { return null; } @Override public String getSignerVersion() { return null; } @Override public String getSignerType() { return "BEARERTOKEN"; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/Credential.java
package com.aliyuncs.v5.auth; import java.util.Calendar; import java.util.Date; @Deprecated public class Credential { private final 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, String securityToken) { this.accessKeyId = keyId; this.accessSecret = secret; this.securityToken = securityToken; this.refreshDate = new Date(); } public Credential(String keyId, String secret, int expiredHours) { this.accessKeyId = keyId; this.accessSecret = secret; this.refreshDate = new Date(); setExpiredDate(expiredHours); } public Credential(String keyId, String secret, String securityToken, int expiredHours) { this.accessKeyId = keyId; this.accessSecret = secret; this.securityToken = securityToken; this.refreshDate = new Date(); setExpiredDate(expiredHours); } 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() { return this.expiredDate == null || this.expiredDate.after(new Date()); } public String getSecurityToken() { return securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; } public Date getRefreshDate() { return refreshDate; } public Date getExpiredDate() { return expiredDate; } private void setExpiredDate(int expiredHours) { if (expiredHours > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.HOUR, expiredHours); expiredDate = cal.getTime(); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/CredentialsBackupCompatibilityAdaptor.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; @Deprecated public class CredentialsBackupCompatibilityAdaptor extends Credential { private final AlibabaCloudCredentialsProvider provider; public CredentialsBackupCompatibilityAdaptor(AlibabaCloudCredentialsProvider provider) { this.provider = provider; } private AlibabaCloudCredentials getCredentials() { try { AlibabaCloudCredentials credentials = this.provider.getCredentials(); return credentials; } catch (ClientException e) { throw new RuntimeException(e.toString()); } } @Override public String getAccessKeyId() { return getCredentials().getAccessKeyId(); } @Override public String getAccessSecret() { return getCredentials().getAccessKeySecret(); } @Override public boolean isExpired() { return false; } @Override public String getSecurityToken() { AlibabaCloudCredentials credentials = getCredentials(); if (credentials instanceof BasicSessionCredentials) { return ((BasicSessionCredentials) credentials).getSessionToken(); } else { return null; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/CredentialsProviderFactory.java
package com.aliyuncs.v5.auth; public class CredentialsProviderFactory { public <T extends AlibabaCloudCredentialsProvider> T createCredentialsProvider(T classInstance) { return classInstance; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/DefaultCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.utils.AuthUtils; import java.util.ArrayList; import java.util.List; import java.util.Vector; public class DefaultCredentialsProvider implements AlibabaCloudCredentialsProvider { private List<AlibabaCloudCredentialsProvider> defaultProviders = new ArrayList<AlibabaCloudCredentialsProvider>(); private static final List<AlibabaCloudCredentialsProvider> USER_CONFIGURATION_PROVIDERS = new Vector<AlibabaCloudCredentialsProvider>(); public DefaultCredentialsProvider() throws ClientException { defaultProviders.add(new SystemPropertiesCredentialsProvider()); defaultProviders.add(new EnvironmentVariableCredentialsProvider()); defaultProviders.add(new ProfileCredentialsProvider()); String roleName = AuthUtils.getEnvironmentECSMetaData(); if (roleName != null) { if (roleName.length() == 0) { throw new ClientException("Environment variable roleName('ALIBABA_CLOUD_ECS_METADATA') cannot be empty"); } defaultProviders.add(new InstanceProfileCredentialsProvider(roleName)); } } @Override public AlibabaCloudCredentials getCredentials() throws ClientException { AlibabaCloudCredentials credential; if (USER_CONFIGURATION_PROVIDERS.size() > 0) { for (AlibabaCloudCredentialsProvider provider : USER_CONFIGURATION_PROVIDERS) { credential = provider.getCredentials(); if (null != credential) { return credential; } } } for (AlibabaCloudCredentialsProvider provider : defaultProviders) { credential = provider.getCredentials(); if (null != credential) { return credential; } } throw new ClientException("not found credentials"); } public static boolean addCredentialsProvider(AlibabaCloudCredentialsProvider provider) { return DefaultCredentialsProvider.USER_CONFIGURATION_PROVIDERS.add(provider); } public static boolean removeCredentialsProvider(AlibabaCloudCredentialsProvider provider) { return DefaultCredentialsProvider.USER_CONFIGURATION_PROVIDERS.remove(provider); } public static boolean containsCredentialsProvider(AlibabaCloudCredentialsProvider provider) { return DefaultCredentialsProvider.USER_CONFIGURATION_PROVIDERS.contains(provider); } public static void clearCredentialsProvider() { DefaultCredentialsProvider.USER_CONFIGURATION_PROVIDERS.clear(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/ECSMetadataServiceCredentialsFetcher.java
package com.aliyuncs.v5.auth; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by haowei.yao on 2017/9/12. */ import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.http.HttpRequest; import com.aliyuncs.v5.http.HttpResponse; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.http.clients.CompatibleUrlConnClient; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ECSMetadataServiceCredentialsFetcher { private static final String URL_IN_ECS_METADATA = "/latest/meta-data/ram/security-credentials/"; private static final int DEFAULT_TIMEOUT_IN_MILLISECONDS = 1000; private static final String ECS_METADAT_FETCH_ERROR_MSG = "Failed to get RAM session credentials from ECS metadata service."; private static final int DEFAULT_ECS_SESSION_TOKEN_DURATION_SECONDS = 3600 * 6; private URL credentialUrl; private String roleName; private String metadataServiceHost = "100.100.100.200"; private int connectionTimeoutInMilliseconds; public ECSMetadataServiceCredentialsFetcher() { this.connectionTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MILLISECONDS; } public void setRoleName(String roleName) { if (null == roleName) { throw new NullPointerException("You must specifiy a valid role name."); } this.roleName = roleName; setCredentialUrl(); } private void setCredentialUrl() { try { this.credentialUrl = new URL("http://" + metadataServiceHost + URL_IN_ECS_METADATA + roleName); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.toString()); } } public ECSMetadataServiceCredentialsFetcher withECSMetadataServiceHost(String host) { System.err.println("withECSMetadataServiceHost() method is only for testing, please don't use it"); this.metadataServiceHost = host; setCredentialUrl(); return this; } public ECSMetadataServiceCredentialsFetcher withConnectionTimeout(int milliseconds) { this.connectionTimeoutInMilliseconds = milliseconds; return this; } public String getMetadata() throws ClientException { HttpRequest request = new HttpRequest(credentialUrl.toString()); request.setSysMethod(MethodType.GET); request.setSysConnectTimeout(connectionTimeoutInMilliseconds); request.setSysReadTimeout(connectionTimeoutInMilliseconds); HttpResponse response; try { response = CompatibleUrlConnClient.compatibleGetResponse(request); } catch (Exception e) { throw new ClientException("Failed to connect ECS Metadata Service: " + e.toString()); } if (response.getStatus() != HttpURLConnection.HTTP_OK) { throw new ClientException(ECS_METADAT_FETCH_ERROR_MSG + " HttpCode=" + response.getStatus()); } return new String(response.getHttpContent()); } public InstanceProfileCredentials fetch() throws ClientException { String jsonContent = getMetadata(); JsonObject jsonObject = null; jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject(); if (jsonObject.has("Code") && jsonObject.has("AccessKeyId") && jsonObject.has("AccessKeySecret") && jsonObject .has("SecurityToken") && jsonObject.has("Expiration")) { } else { throw new ClientException("Invalid json got from ECS Metadata service."); } if (!"Success".equals(jsonObject.get("Code").getAsString())) { throw new ClientException(ECS_METADAT_FETCH_ERROR_MSG); } return new InstanceProfileCredentials(jsonObject.get("AccessKeyId").getAsString(), jsonObject.get( "AccessKeySecret").getAsString(), jsonObject.get("SecurityToken").getAsString(), jsonObject.get( "Expiration").getAsString(), DEFAULT_ECS_SESSION_TOKEN_DURATION_SECONDS); } public InstanceProfileCredentials fetch(int retryTimes) throws ClientException { for (int i = 0; i <= retryTimes; i++) { try { return fetch(); } catch (ClientException e) { if (i == retryTimes) { throw e; } } } throw new ClientException("Failed to connect ECS Metadata Service: Max retry times exceeded."); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/EnvironmentVariableCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.utils.AuthUtils; public class EnvironmentVariableCredentialsProvider implements AlibabaCloudCredentialsProvider { @Override public AlibabaCloudCredentials getCredentials() throws ClientException { if (!"default".equals(AuthUtils.getClientType())) { return null; } String accessKeyId = AuthUtils.getEnvironmentAccessKeyId(); String accessKeySecret = AuthUtils.getEnvironmentAccessKeySecret(); if (accessKeyId == null || accessKeySecret == null) { return null; } if (accessKeyId.length() == 0) { throw new ClientException("Environment variable accessKeyId cannot be empty"); } if (accessKeySecret.length() == 0) { throw new ClientException("Environment variable accessKeySecret cannot be empty"); } return new BasicCredentials(accessKeyId, accessKeySecret); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/HmacSHA1Signer.java
package com.aliyuncs.v5.auth; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; public class HmacSHA1Signer extends Signer { public static final String ENCODING = "UTF-8"; private static final String ALGORITHM_NAME = "HmacSHA1"; @Override public String signString(String stringToSign, String accessKeySecret) { try { Mac mac = Mac.getInstance(ALGORITHM_NAME); mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), ALGORITHM_NAME)); byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING)); return DatatypeConverter.printBase64Binary(signData); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e.toString()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.toString()); } catch (InvalidKeyException e) { throw new IllegalArgumentException(e.toString()); } } @Override public String signString(String stringToSign, AlibabaCloudCredentials credentials) { return signString(stringToSign, credentials.getAccessKeySecret()); } @Override public String getSignerName() { return "HMAC-SHA1"; } @Override public String getSignerVersion() { return "1.0"; } @Override public String getSignerType() { return null; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/ICredentialProvider.java
package com.aliyuncs.v5.auth; @Deprecated public interface ICredentialProvider { Credential fresh(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/ISignatureComposer.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.MethodType; import java.util.Map; public interface ISignatureComposer { Map<String, String> refreshSignParameters(Map<String, String> parameters, Signer signer, String accessKeyId, FormatType format); String composeStringToSign(MethodType method, String uriPattern, Signer signer, Map<String, String> queries, Map<String, String> headers, Map<String, String> paths); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/ISigner.java
package com.aliyuncs.v5.auth; import java.security.InvalidKeyException; @Deprecated public interface ISigner { String getSignerName(); String getSignerVersion(); String signString(String source, String accessSecret) throws InvalidKeyException, IllegalStateException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/InstanceProfileCredentials.java
package com.aliyuncs.v5.auth; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class InstanceProfileCredentials extends BasicSessionCredentials { private final long expiration; private final double expireFact = 0.95; private final long refreshIntervalInMillSeconds = 180000; private long lastFailedRefreshTime = 0; public InstanceProfileCredentials(String accessKeyId, String accessKeySecret, String sessionToken, String expiration, long roleSessionDurationSeconds) { super(accessKeyId, accessKeySecret, sessionToken, roleSessionDurationSeconds); SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); parser.setTimeZone(TimeZone.getTimeZone("GMT")); try { Date date = parser.parse(expiration.replace('T', ' ').replace('Z', ' ')); this.expiration = date.getTime(); } catch (ParseException e) { throw new IllegalArgumentException("Failed to get valid expiration time from ECS Metadata service."); } } @Override public boolean willSoonExpire() { long now = System.currentTimeMillis(); return this.roleSessionDurationSeconds * (1 - expireFact) > (expiration - now) / 1000; } public boolean isExpired() { long now = System.currentTimeMillis(); return now >= expiration - refreshIntervalInMillSeconds; } public boolean shouldRefresh() { long now = System.currentTimeMillis(); return now - lastFailedRefreshTime > refreshIntervalInMillSeconds; } public void setLastFailedRefreshTime() { lastFailedRefreshTime = System.currentTimeMillis(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/InstanceProfileCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; public class InstanceProfileCredentialsProvider implements AlibabaCloudCredentialsProvider { private static final int MAX_ECS_METADATA_FETCH_RETRY_TIMES = 3; private final String roleName; public int ecsMetadataServiceFetchCount = 0; private InstanceProfileCredentials credentials = null; private ECSMetadataServiceCredentialsFetcher fetcher; public InstanceProfileCredentialsProvider(String roleName) { if (null == roleName) { throw new NullPointerException("You must specifiy a valid role name."); } this.roleName = roleName; this.fetcher = new ECSMetadataServiceCredentialsFetcher(); this.fetcher.setRoleName(this.roleName); } public InstanceProfileCredentialsProvider withFetcher(ECSMetadataServiceCredentialsFetcher fetcher) { this.fetcher = fetcher; this.fetcher.setRoleName(roleName); return this; } @Override public AlibabaCloudCredentials getCredentials() throws ClientException { if (credentials == null || credentials.isExpired()) { ecsMetadataServiceFetchCount += 1; int maxRetryTimes = MAX_ECS_METADATA_FETCH_RETRY_TIMES; credentials = fetcher.fetch(maxRetryTimes); // } else if (credentials.isExpired()) { // throw new ClientException("SDK.SessionTokenExpired", "Current session token // has expired."); } else if (credentials.willSoonExpire() && credentials.shouldRefresh()) { try { ecsMetadataServiceFetchCount += 1; credentials = fetcher.fetch(); } catch (ClientException e) { // Use the current expiring session token and wait for next round credentials.setLastFailedRefreshTime(); } } return credentials; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/KeyPairCredentials.java
package com.aliyuncs.v5.auth; public class KeyPairCredentials implements AlibabaCloudCredentials { private String privateKeySecret; private String publicKeyId; public KeyPairCredentials(String publicKeyId, String privateKeySecret) { if (publicKeyId == null || privateKeySecret == null) { throw new IllegalArgumentException( "You must provide a valid pair of Public Key ID and Private Key Secret."); } this.publicKeyId = publicKeyId; this.privateKeySecret = privateKeySecret; } @Override public String getAccessKeyId() { return publicKeyId; } @Override public String getAccessKeySecret() { return privateKeySecret; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/LegacyCredentials.java
package com.aliyuncs.v5.auth; @SuppressWarnings("deprecation") public class LegacyCredentials implements AlibabaCloudCredentials { private final Credential legacyCredential; public LegacyCredentials(Credential legacyCrendential) { this.legacyCredential = legacyCrendential; } @Override public String getAccessKeyId() { return legacyCredential.getAccessKeyId(); } @Override public String getAccessKeySecret() { return legacyCredential.getAccessSecret(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/OssSignatureComposer.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.utils.ParameterHelper; import java.util.Date; import java.util.HashMap; import java.util.Map; public class OssSignatureComposer extends RoaSignatureComposer { private static ISignatureComposer composer = null; public static ISignatureComposer getComposer() { if (null == composer) { composer = new OssSignatureComposer(); } return composer; } @Override public Map<String, String> refreshSignParameters(Map<String, String> parameters, Signer signer, String accessKeyId, FormatType format) { Map<String, String> immutableMap = new HashMap<String, String>(parameters); immutableMap.put("Date", ParameterHelper.getRFC2616Date(new Date())); 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; } @Override public String composeStringToSign(MethodType method, String uriPattern, Signer 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(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/ProfileCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.utils.AuthUtils; import com.aliyuncs.v5.utils.StringUtils; import org.ini4j.Profile; import org.ini4j.Wini; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ProfileCredentialsProvider implements AlibabaCloudCredentialsProvider { private static volatile Wini ini; private static Wini getIni(String filePath) throws IOException { if (null == ini) { synchronized (ProfileCredentialsProvider.class) { if (null == ini) { ini = new Wini(new File(filePath)); } } } return ini; } @Override public AlibabaCloudCredentials getCredentials() throws ClientException { String filePath = AuthUtils.getEnvironmentCredentialsFile(); if (filePath == null) { filePath = AuthConstant.DEFAULT_CREDENTIALS_FILE_PATH; } if (filePath.length() == 0) { throw new ClientException("The specified credentials file is empty"); } Wini ini; try { ini = getIni(filePath); } catch (IOException e) { return null; } Map<String, Map<String, String>> client = loadIni(ini); Map<String, String> clientConfig = client.get(AuthUtils.getClientType()); if (clientConfig == null) { throw new ClientException("Client is not open in the specified credentials file"); } CredentialsProviderFactory credentialsProviderFactory = new CredentialsProviderFactory(); return createCredential(clientConfig, credentialsProviderFactory); } private Map<String, Map<String, String>> loadIni(Wini ini) { Map<String, Map<String, String>> client = new HashMap<String, Map<String, String>>(); boolean enable; for (Map.Entry<String, Profile.Section> clientType : ini.entrySet()) { enable = clientType.getValue().get(AuthConstant.INI_ENABLE, boolean.class); if (enable) { Map<String, String> clientConfig = new HashMap<String, String>(); for (Map.Entry<String, String> enabledClient : clientType.getValue().entrySet()) { clientConfig.put(enabledClient.getKey(), enabledClient.getValue()); } client.put(clientType.getKey(), clientConfig); } } return client; } private AlibabaCloudCredentials createCredential(Map<String, String> clientConfig, CredentialsProviderFactory factory) throws ClientException { String configType = clientConfig.get(AuthConstant.INI_TYPE); if (StringUtils.isEmpty(configType)) { throw new ClientException("The configured client type is empty"); } if (AuthConstant.INI_TYPE_ARN.equals(configType)) { return getSTSAssumeRoleSessionCredentials(clientConfig, factory); } if (AuthConstant.INI_TYPE_KEY_PAIR.equals(configType)) { return getSTSGetSessionAccessKeyCredentials(clientConfig, factory); } if (AuthConstant.INI_TYPE_RAM.equals(configType)) { return getInstanceProfileCredentials(clientConfig, factory); } String accessKeyId = clientConfig.get(AuthConstant.INI_ACCESS_KEY_ID); String accessKeySecret = clientConfig.get(AuthConstant.INI_ACCESS_KEY_IDSECRET); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { return null; } return new BasicCredentials(accessKeyId, accessKeySecret); } private AlibabaCloudCredentials getSTSAssumeRoleSessionCredentials(Map<String, String> clientConfig, CredentialsProviderFactory factory) throws ClientException { String accessKeyId = clientConfig.get(AuthConstant.INI_ACCESS_KEY_ID); String accessKeySecret = clientConfig.get(AuthConstant.INI_ACCESS_KEY_IDSECRET); String roleSessionName = clientConfig.get(AuthConstant.INI_ROLE_SESSION_NAME); String roleArn = clientConfig.get(AuthConstant.INI_ROLE_ARN); String regionId = clientConfig.get(AuthConstant.DEFAULT_REGION); String policy = clientConfig.get(AuthConstant.INI_POLICY); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { throw new ClientException("The configured access_key_id or access_key_secret is empty"); } if (StringUtils.isEmpty(roleSessionName) || StringUtils.isEmpty(roleArn)) { throw new ClientException("The configured role_session_name or role_arn is empty"); } STSAssumeRoleSessionCredentialsProvider provider = factory.createCredentialsProvider(new STSAssumeRoleSessionCredentialsProvider(accessKeyId, accessKeySecret, roleSessionName, roleArn, regionId, policy)); return provider.getCredentials(); } private AlibabaCloudCredentials getSTSGetSessionAccessKeyCredentials(Map<String, String> clientConfig, CredentialsProviderFactory factory) throws ClientException { String publicKeyId = clientConfig.get(AuthConstant.INI_PUBLIC_KEY_ID); String privateKeyFile = clientConfig.get(AuthConstant.INI_PRIVATE_KEY_FILE); if (StringUtils.isEmpty(privateKeyFile)) { throw new ClientException("The configured private_key_file is empty"); } String privateKey = AuthUtils.getPrivateKey(privateKeyFile); if (StringUtils.isEmpty(publicKeyId) || StringUtils.isEmpty(privateKey)) { throw new ClientException("The configured public_key_id or private_key_file content is empty"); } STSGetSessionAccessKeyCredentialsProvider provider = factory.createCredentialsProvider(new STSGetSessionAccessKeyCredentialsProvider(publicKeyId, privateKey)); return provider.getCredentials(); } private AlibabaCloudCredentials getInstanceProfileCredentials(Map<String, String> clientConfig, CredentialsProviderFactory factory) throws ClientException { String roleName = clientConfig.get(AuthConstant.INI_ROLE_NAME); if (StringUtils.isEmpty(roleName)) { throw new ClientException("The configured role_name is empty"); } InstanceProfileCredentialsProvider provider = factory.createCredentialsProvider(new InstanceProfileCredentialsProvider(roleName)); return provider.getCredentials(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/RoaSignatureComposer.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.utils.ParameterHelper; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class RoaSignatureComposer implements ISignatureComposer { protected final static String QUERY_SEPARATOR = "&"; protected final static String HEADER_SEPARATOR = "\n"; private static ISignatureComposer composer = null; 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 static ISignatureComposer getComposer() { if (null == composer) { composer = new RoaSignatureComposer(); } return composer; } @Override public Map<String, String> refreshSignParameters(Map<String, String> parameters, Signer signer, String accessKeyId, FormatType format) { Map<String, String> immutableMap = new HashMap<String, String>(parameters); immutableMap.put("Date", ParameterHelper.getRFC2616Date(new Date())); if (null == format) { format = FormatType.JSON; } immutableMap.put("Accept", FormatType.mapFormatToAccept(format)); immutableMap.put("x-acs-signature-method", signer.getSignerName()); immutableMap.put("x-acs-signature-version", signer.getSignerVersion()); if (signer.getSignerType() != null) { immutableMap.put("x-acs-signature-type", signer.getSignerType()); } 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()); String value = e.getValue(); if (value == null || value.isEmpty()) { queryBuilder.append(QUERY_SEPARATOR); continue; } queryBuilder.append("=").append(e.getValue()).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(); } @Override public String composeStringToSign(MethodType method, String uriPattern, Signer 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(); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/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.v5.auth; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.utils.ParameterHelper; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; public class RpcSignatureComposer implements ISignatureComposer { private final static String SEPARATOR = "&"; private static ISignatureComposer composer = null; private RpcSignatureComposer() { } public static ISignatureComposer getComposer() { if (null == composer) { composer = new RpcSignatureComposer(); } return composer; } @Override public Map<String, String> refreshSignParameters(Map<String, String> parameters, Signer signer, String accessKeyId, FormatType format) { Map<String, String> immutableMap = new HashMap<String, String>(parameters); immutableMap.put("Timestamp", ParameterHelper.getISO8601Time(new Date())); 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()); } if (signer.getSignerType() != null) { immutableMap.put("SignatureType", signer.getSignerType()); } return immutableMap; } @Override public String composeStringToSign(MethodType method, String uriPattern, Signer 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."); } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/SHA256withRSASigner.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.v5.auth; import javax.xml.bind.DatatypeConverter; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; /** * Created by haowei.yao on 2017/9/28. */ public class SHA256withRSASigner extends Signer { public static final String ENCODING = "UTF-8"; private static final String ALGORITHM_NAME = "SHA256withRSA"; @Override public String signString(String stringToSign, String accessKeySecret) { try { Signature rsaSign = Signature.getInstance("SHA256withRSA"); KeyFactory kf = KeyFactory.getInstance("RSA"); byte[] keySpec = DatatypeConverter.parseBase64Binary(accessKeySecret); PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(keySpec)); rsaSign.initSign(privateKey); rsaSign.update(stringToSign.getBytes(ENCODING)); byte[] sign = rsaSign.sign(); String signature = new String(DatatypeConverter.printBase64Binary(sign)); return signature; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e.toString()); } catch (InvalidKeySpecException e) { throw new IllegalArgumentException(e.toString()); } catch (InvalidKeyException e) { throw new IllegalArgumentException(e.toString()); } catch (SignatureException e) { throw new IllegalArgumentException(e.toString()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.toString()); } } @Override public String signString(String stringToSign, AlibabaCloudCredentials credentials) { return signString(stringToSign, credentials.getAccessKeySecret()); } @Override public String getSignerName() { return ALGORITHM_NAME; } @Override public String getSignerVersion() { return "1.0"; } @Override public String getSignerType() { return "PRIVATEKEY"; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/STSAssumeRoleSessionCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.DefaultAcsClient; import com.aliyuncs.v5.IAcsClient; import com.aliyuncs.v5.auth.sts.AssumeRoleRequest; import com.aliyuncs.v5.auth.sts.AssumeRoleResponse; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.profile.DefaultProfile; import com.aliyuncs.v5.profile.IClientProfile; /** * This implementation of AlibabaCloudCredentialsProvider accesses Alibaba Cloud STS service to assume a Role and get * back a temporary session for authentication. */ public class STSAssumeRoleSessionCredentialsProvider implements AlibabaCloudCredentialsProvider { /** * Default duration for started sessions. */ public static final int DEFAULT_DURATION_SECONDS = 3600; /** * The arn of the role to be assumed. */ private final String roleArn; /** * For test * To know how many rounds AssumeRole has been called */ public long assumeRoleRound = 0; /** * The client for starting STS sessions. */ private IAcsClient stsClient; /** * An identifier for the assumed role session. */ private String roleSessionName; /** * The Duration for assume role sessions. */ private long roleSessionDurationSeconds; private String policy; private BasicSessionCredentials credentials = null; public STSAssumeRoleSessionCredentialsProvider(AlibabaCloudCredentials longLivedCredentials, String roleArn, IClientProfile clientProfile) { this(new StaticCredentialsProvider(longLivedCredentials), roleArn, clientProfile); } public STSAssumeRoleSessionCredentialsProvider(AlibabaCloudCredentialsProvider longLivedCredentialsProvider, String roleArn, IClientProfile clientProfile) { if (roleArn == null) { throw new NullPointerException( "You must specify a value for roleArn."); } this.roleArn = roleArn; this.roleSessionName = getNewRoleSessionName(); this.stsClient = new DefaultAcsClient(clientProfile, longLivedCredentialsProvider); this.roleSessionDurationSeconds = DEFAULT_DURATION_SECONDS; } public STSAssumeRoleSessionCredentialsProvider(String accessKeyId, String accessKeySecret, String roleSessionName, String roleArn, String regionId) { this.roleArn = roleArn; this.roleSessionName = roleSessionName; DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret); this.stsClient = new DefaultAcsClient(profile); this.roleSessionDurationSeconds = AuthConstant.TSC_VALID_TIME_SECONDS; } public STSAssumeRoleSessionCredentialsProvider(String accessKeyId, String accessKeySecret, String roleSessionName, String roleArn, String regionId, String policy) { this(accessKeyId, accessKeySecret, roleSessionName, roleArn, regionId); this.policy = policy; } public static String getNewRoleSessionName() { return "aliyun-java-sdk-" + System.currentTimeMillis(); } public STSAssumeRoleSessionCredentialsProvider withRoleSessionName(String roleSessionName) { this.roleSessionName = roleSessionName; return this; } public STSAssumeRoleSessionCredentialsProvider withRoleSessionDurationSeconds(long roleSessionDurationSeconds) { if (roleSessionDurationSeconds < 900 || roleSessionDurationSeconds > 3600) { throw new IllegalArgumentException( "Assume Role session duration should be in the range of 15min - 1Hr"); } this.roleSessionDurationSeconds = roleSessionDurationSeconds; return this; } public STSAssumeRoleSessionCredentialsProvider withSTSClient(IAcsClient client) { this.stsClient = client; return this; } @Override public AlibabaCloudCredentials getCredentials() throws ClientException, ServerException { if (credentials == null || credentials.willSoonExpire()) { credentials = getNewSessionCredentials(); } return credentials; } private BasicSessionCredentials getNewSessionCredentials() throws ClientException, ServerException { assumeRoleRound += 1; AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest(); assumeRoleRequest.setRoleArn(roleArn); assumeRoleRequest.setRoleSessionName(roleSessionName); assumeRoleRequest.setDurationSeconds(roleSessionDurationSeconds); if (null != policy){ assumeRoleRequest.setPolicy(policy); } AssumeRoleResponse response = stsClient.getAcsResponse(assumeRoleRequest); return new BasicSessionCredentials( response.getCredentials().getAccessKeyId(), response.getCredentials().getAccessKeySecret(), response.getCredentials().getSecurityToken(), roleSessionDurationSeconds ); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/STSGetSessionAccessKeyCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.DefaultAcsClient; import com.aliyuncs.v5.IAcsClient; import com.aliyuncs.v5.auth.sts.GenerateSessionAccessKeyResponse; import com.aliyuncs.v5.auth.sts.GetSessionAccessKeyRequest; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.http.ProtocolType; import com.aliyuncs.v5.profile.DefaultProfile; import com.aliyuncs.v5.profile.IClientProfile; public class STSGetSessionAccessKeyCredentialsProvider implements AlibabaCloudCredentialsProvider { public static final int DEFAULT_DURATION_SECONDS = 3600; private KeyPairCredentials keyPairCredentials; private String publicKeyId; private IAcsClient stsClient; private long sessionDurationSeconds = DEFAULT_DURATION_SECONDS; private BasicSessionCredentials sessionCredentials = null; public STSGetSessionAccessKeyCredentialsProvider(KeyPairCredentials keyPairCredentials, IClientProfile profile) { this.keyPairCredentials = keyPairCredentials; this.stsClient = new DefaultAcsClient(profile, keyPairCredentials); } public STSGetSessionAccessKeyCredentialsProvider(String publicKeyId, String privateKey) { this.publicKeyId = publicKeyId; DefaultProfile profile = DefaultProfile.getProfile("ap-northeast-1", publicKeyId, privateKey); this.stsClient = new DefaultAcsClient(profile); } public STSGetSessionAccessKeyCredentialsProvider withDurationSeconds(long seconds) { this.sessionDurationSeconds = seconds; return this; } public STSGetSessionAccessKeyCredentialsProvider withSTSClient(IAcsClient client) { this.stsClient = client; return this; } @Override public AlibabaCloudCredentials getCredentials() throws ClientException, ServerException { if (sessionCredentials == null || sessionCredentials.willSoonExpire()) { sessionCredentials = getNewSessionCredentials(); } return sessionCredentials; } private BasicSessionCredentials getNewSessionCredentials() throws ClientException, ServerException { GetSessionAccessKeyRequest request = new GetSessionAccessKeyRequest(); if (null != publicKeyId) { request.setPublicKeyId(publicKeyId); } else { request.setPublicKeyId(keyPairCredentials.getAccessKeyId()); } request.setDurationSeconds((int) sessionDurationSeconds); request.setSysProtocol(ProtocolType.HTTPS); GenerateSessionAccessKeyResponse response = this.stsClient.getAcsResponse(request); return new BasicSessionCredentials( response.getSessionAccessKey().getSessionAccessKeyId(), response.getSessionAccessKey().getSessionAccessKeySecert(), null, sessionDurationSeconds ); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/Signer.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.v5.auth; /** * Created by haowei.yao on 2017/9/28. */ public abstract class Signer { private final static Signer HMACSHA1_SIGNER = new HmacSHA1Signer(); private final static Signer SHA256_WITH_RSA_SIGNER = new SHA256withRSASigner(); private final static Signer BEARER_TOKEN_SIGNER = new BearerTokenSigner(); public static Signer getSigner(AlibabaCloudCredentials credentials) { if (credentials instanceof KeyPairCredentials) { return SHA256_WITH_RSA_SIGNER; } else if (credentials instanceof BearerTokenCredentials) { return BEARER_TOKEN_SIGNER; } else { return HMACSHA1_SIGNER; } } public abstract String signString(String stringToSign, AlibabaCloudCredentials credentials); public abstract String signString(String stringToSign, String accessKeySecret); public abstract String getSignerName(); public abstract String getSignerVersion(); public abstract String getSignerType(); }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/StaticCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.profile.IClientProfile; public class StaticCredentialsProvider implements AlibabaCloudCredentialsProvider { private AlibabaCloudCredentials credentials = null; public StaticCredentialsProvider(AlibabaCloudCredentials credentials) { this.credentials = credentials; } @SuppressWarnings("deprecation") public StaticCredentialsProvider(IClientProfile clientProfile) { IClientProfile clientProfile1 = clientProfile; Credential legacyCredential = clientProfile1.getCredential(); if (null != legacyCredential.getSecurityToken()) { this.credentials = new BasicSessionCredentials(legacyCredential.getAccessKeyId(), legacyCredential .getAccessSecret(), legacyCredential.getSecurityToken()); } else { this.credentials = new LegacyCredentials(legacyCredential); } } @Override public AlibabaCloudCredentials getCredentials() { return this.credentials; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/SystemPropertiesCredentialsProvider.java
package com.aliyuncs.v5.auth; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ServerException; import com.aliyuncs.v5.utils.AuthUtils; import com.aliyuncs.v5.utils.StringUtils; public class SystemPropertiesCredentialsProvider implements AlibabaCloudCredentialsProvider { @Override public AlibabaCloudCredentials getCredentials() throws ClientException, ServerException { if (!"default".equals(AuthUtils.getClientType())) { return null; } String accessKeyId = System.getProperty(AuthConstant.SYSTEM_ACCESSKEYID); String accessKeySecret = System.getProperty(AuthConstant.SYSTEM_ACCESSKEYSECRET); if (StringUtils.isEmpty(accessKeyId) || StringUtils.isEmpty(accessKeySecret)) { return null; } return new BasicCredentials(accessKeyId, accessKeySecret); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/sts/AssumeRoleRequest.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.v5.auth.sts; /** * Created by haowei.yao on 2017/9/14. */ import com.aliyuncs.v5.RpcAcsRequest; import com.aliyuncs.v5.http.ProtocolType; /** * @author auto create */ public class AssumeRoleRequest extends RpcAcsRequest<AssumeRoleResponse> { private Long durationSeconds; private String policy; private String roleArn; private String roleSessionName; public AssumeRoleRequest() { super("Sts", "2015-04-01", "AssumeRole"); setSysProtocol(ProtocolType.HTTPS); } public Long getDurationSeconds() { return this.durationSeconds; } public void setDurationSeconds(Long durationSeconds) { this.durationSeconds = durationSeconds; putQueryParameter("DurationSeconds", String.valueOf(durationSeconds)); } public String getPolicy() { return this.policy; } public void setPolicy(String policy) { this.policy = policy; putQueryParameter("Policy", policy); } public String getRoleArn() { return this.roleArn; } public void setRoleArn(String roleArn) { this.roleArn = roleArn; putQueryParameter("RoleArn", roleArn); } public String getRoleSessionName() { return this.roleSessionName; } public void setRoleSessionName(String roleSessionName) { this.roleSessionName = roleSessionName; putQueryParameter("RoleSessionName", roleSessionName); } @Override public Class<AssumeRoleResponse> getResponseClass() { return AssumeRoleResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/sts/AssumeRoleResponse.java
package com.aliyuncs.v5.auth.sts; import com.aliyuncs.v5.AcsResponse; import com.aliyuncs.v5.transform.UnmarshallerContext; public class AssumeRoleResponse extends AcsResponse { private String requestId; private Credentials credentials; private AssumedRoleUser assumedRoleUser; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Credentials getCredentials() { return this.credentials; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } public AssumedRoleUser getAssumedRoleUser() { return this.assumedRoleUser; } public void setAssumedRoleUser(AssumedRoleUser assumedRoleUser) { this.assumedRoleUser = assumedRoleUser; } @Override public AssumeRoleResponse getInstance(UnmarshallerContext context) { return AssumeRoleResponseUnmarshaller.unmarshall(this, context); } public static class Credentials { private String securityToken; private String accessKeySecret; private String accessKeyId; private String expiration; public String getSecurityToken() { return this.securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; } public String getAccessKeySecret() { return this.accessKeySecret; } public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; } public String getAccessKeyId() { return this.accessKeyId; } public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; } public String getExpiration() { return this.expiration; } public void setExpiration(String expiration) { this.expiration = expiration; } } public static class AssumedRoleUser { private String arn; private String assumedRoleId; public String getArn() { return this.arn; } public void setArn(String arn) { this.arn = arn; } public String getAssumedRoleId() { return this.assumedRoleId; } public void setAssumedRoleId(String assumedRoleId) { this.assumedRoleId = assumedRoleId; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/sts/AssumeRoleResponseUnmarshaller.java
package com.aliyuncs.v5.auth.sts; import com.aliyuncs.v5.auth.sts.AssumeRoleResponse.AssumedRoleUser; import com.aliyuncs.v5.auth.sts.AssumeRoleResponse.Credentials; import com.aliyuncs.v5.transform.UnmarshallerContext; public class AssumeRoleResponseUnmarshaller { public static AssumeRoleResponse unmarshall(AssumeRoleResponse assumeRoleResponse, UnmarshallerContext context) { assumeRoleResponse.setRequestId(context.stringValue("AssumeRoleResponse.RequestId")); Credentials credentials = new Credentials(); credentials.setSecurityToken(context.stringValue("AssumeRoleResponse.Credentials.SecurityToken")); credentials.setAccessKeySecret(context.stringValue("AssumeRoleResponse.Credentials.AccessKeySecret")); credentials.setAccessKeyId(context.stringValue("AssumeRoleResponse.Credentials.AccessKeyId")); credentials.setExpiration(context.stringValue("AssumeRoleResponse.Credentials.Expiration")); assumeRoleResponse.setCredentials(credentials); AssumedRoleUser assumedRoleUser = new AssumedRoleUser(); assumedRoleUser.setArn(context.stringValue("AssumeRoleResponse.AssumedRoleUser.Arn")); assumedRoleUser.setAssumedRoleId(context.stringValue("AssumeRoleResponse.AssumedRoleUser.AssumedRoleId")); assumeRoleResponse.setAssumedRoleUser(assumedRoleUser); return assumeRoleResponse; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/sts/GenerateSessionAccessKeyResponse.java
package com.aliyuncs.v5.auth.sts; import com.aliyuncs.v5.AcsResponse; import com.aliyuncs.v5.transform.UnmarshallerContext; import com.google.gson.annotations.SerializedName; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "GenerateSessionAccessKeyResponse") public class GenerateSessionAccessKeyResponse extends AcsResponse { @SerializedName("RequestId") private String requestId; @SerializedName("SessionAccessKey") private SessionAccessKey sessionAccessKey; public String getRequestId() { return requestId; } @XmlElement(name = "RequestId") public void setRequestId(String requestId) { this.requestId = requestId; } @XmlElement(name = "SessionAccessKey") public SessionAccessKey getSessionAccessKey() { return sessionAccessKey; } public void setSessionAccessKey(SessionAccessKey sessionAccessKey) { this.sessionAccessKey = sessionAccessKey; } @Override public GenerateSessionAccessKeyResponse getInstance(UnmarshallerContext context) { return GetSessionAccessKeyResponseUnmarshaller.unmarshall(this, context); } public static class SessionAccessKey { @SerializedName("SessionAccessKeyId") private String sessionAccessKeyId; @SerializedName("SessionAccessKeySecret") private String sessionAccessKeySecret; @SerializedName("Expiration") private String expiration; public String getSessionAccessKeyId() { return sessionAccessKeyId; } @XmlElement(name = "SessionAccessKeyId") public void setSessionAccessKeyId(String sessionAccessKeyId) { this.sessionAccessKeyId = sessionAccessKeyId; } public String getSessionAccessKeySecert() { return sessionAccessKeySecret; } @XmlElement(name = "SessionAccessKeySecret") public void setSessionAccessKeySecert(String sessionAccessKeySecert) { this.sessionAccessKeySecret = sessionAccessKeySecert; } public String getExpiration() { return expiration; } @XmlElement(name = "Expiration") public void setExpiration(String expiration) { this.expiration = expiration; } } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/sts/GetSessionAccessKeyRequest.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.v5.auth.sts; import com.aliyuncs.v5.RpcAcsRequest; public class GetSessionAccessKeyRequest extends RpcAcsRequest<GenerateSessionAccessKeyResponse> { private static String version = "2015-04-01"; private static String product = "Sts"; private static String action = "GenerateSessionAccessKey"; private int durationSeconds = 3600; private String publicKeyId; public GetSessionAccessKeyRequest() { super(product, version, action); } public int getDurationSeconds() { return durationSeconds; } public void setDurationSeconds(int durationSeconds) { this.durationSeconds = durationSeconds; putQueryParameter("DurationSeconds", durationSeconds); } public String getPublicKeyId() { return publicKeyId; } public void setPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; putQueryParameter("PublicKeyId", publicKeyId); } @Override public Class<GenerateSessionAccessKeyResponse> getResponseClass() { return GenerateSessionAccessKeyResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/auth/sts/GetSessionAccessKeyResponseUnmarshaller.java
package com.aliyuncs.v5.auth.sts; import com.aliyuncs.v5.auth.sts.GenerateSessionAccessKeyResponse.SessionAccessKey; import com.aliyuncs.v5.transform.UnmarshallerContext; public class GetSessionAccessKeyResponseUnmarshaller { public static GenerateSessionAccessKeyResponse unmarshall(GenerateSessionAccessKeyResponse getSessionAccessKeyResponse, UnmarshallerContext context) { getSessionAccessKeyResponse.setRequestId(context.stringValue("GenerateSessionAccessKeyResponse.RequestId")); SessionAccessKey credentials = new SessionAccessKey(); credentials.setSessionAccessKeyId(context.stringValue("GenerateSessionAccessKeyResponse.SessionAccessKey.SessionAccessKeyId")); credentials.setSessionAccessKeySecert(context.stringValue("GenerateSessionAccessKeyResponse.SessionAccessKey.SessionAccessKeySecret")); credentials.setExpiration(context.stringValue("GenerateSessionAccessKeyResponse.SessionAccessKey.Expiration")); getSessionAccessKeyResponse.setSessionAccessKey(credentials); return getSessionAccessKeyResponse; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/ChainedEndpointResolver.java
package com.aliyuncs.v5.endpoint; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.exceptions.ErrorCodeConstant; import com.aliyuncs.v5.exceptions.ErrorMessageConstant; import java.util.List; import java.util.Set; @SuppressWarnings({"ALL", "AlibabaClassMustHaveAuthor"}) public class ChainedEndpointResolver implements EndpointResolver { protected List<EndpointResolverBase> endpointResolvers; public ChainedEndpointResolver(List<EndpointResolverBase> resolverChain) { this.endpointResolvers = resolverChain; } private void checkProductCode(ResolveEndpointRequest request) throws ClientException { boolean productCodeValid = false; for (EndpointResolverBase resolver : endpointResolvers) { if (resolver.isProductCodeValid(request)) { productCodeValid = true; } } if (!productCodeValid) { throw new ClientException(ErrorCodeConstant.SDK_ENDPOINT_RESOLVING_ERROR, String.format(ErrorMessageConstant.ENDPOINT_NO_PRODUCT, request.productCode)); } } private void checkRegionId(ResolveEndpointRequest request) throws ClientException { boolean regionIdValid = false; for (EndpointResolverBase resolver : endpointResolvers) { if (resolver.isRegionIdValid(request)) { regionIdValid = true; } } if (!regionIdValid) { throw new ClientException(ErrorCodeConstant.SDK_ENDPOINT_RESOLVING_ERROR, String.format(ErrorMessageConstant.INVALID_REGION_ID, request.regionId)); } } private String getAvailableRegionsHint(String productCode) { Set<String> availabeRegions = null; String availabeRegionsHint = ""; for (EndpointResolverBase resolver : endpointResolvers) { availabeRegions = resolver.getValidRegionIdsByProduct(productCode); if (availabeRegions != null) { availabeRegionsHint = "\nOr you can use the other available regions:"; for (String availabeRegion : availabeRegions) { availabeRegionsHint += " " + availabeRegion; } break; } } return availabeRegionsHint; } @Override public String resolve(ResolveEndpointRequest request) throws ClientException { for (EndpointResolverBase resolver : endpointResolvers) { String endpoint = resolver.resolve(request); if (endpoint != null) { return endpoint; } } checkProductCode(request); checkRegionId(request); throw new ClientException(ErrorCodeConstant.SDK_ENDPOINT_RESOLVING_ERROR, String.format(ErrorMessageConstant.ENDPOINT_NO_REGION, request.regionId, request.productCode, getAvailableRegionsHint(request.productCode))); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/DefaultEndpointResolver.java
package com.aliyuncs.v5.endpoint; import com.aliyuncs.v5.DefaultAcsClient; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.profile.DefaultProfile; import com.aliyuncs.v5.profile.IClientProfile; import java.util.ArrayList; import java.util.List; public class DefaultEndpointResolver implements EndpointResolver { public static UserCustomizedEndpointResolver predefinedEndpointResolver = new UserCustomizedEndpointResolver(); private UserCustomizedEndpointResolver userCustomizedEndpointResolver; private EndpointResolver insideEndpointResolver; public DefaultEndpointResolver( DefaultAcsClient client, String userConfig, IClientProfile profile) { userCustomizedEndpointResolver = new UserCustomizedEndpointResolver(); EndpointResolverRules endpointResolverRules = new EndpointResolverRules(); List<EndpointResolverBase> resolverChain = new ArrayList<EndpointResolverBase>(); // The order is very IMPORTANT! resolverChain.add(predefinedEndpointResolver); resolverChain.add(userCustomizedEndpointResolver); if (profile.isUsingVpcEndpoint()) { resolverChain.add(new UserVpcEndpointResolver()); } resolverChain.add(endpointResolverRules); if (userConfig == null) { resolverChain.add(new LocalConfigRegionalEndpointResolver()); resolverChain.add(new LocalConfigGlobalEndpointResolver()); } else { resolverChain.add(new LocalConfigRegionalEndpointResolver(userConfig)); resolverChain.add(new LocalConfigGlobalEndpointResolver(userConfig)); } if (profile.isUsingInternalLocationService()) { resolverChain.add(new InternalLocationServiceEndpointResolver(client)); } else { resolverChain.add(new LocationServiceEndpointResolver(client)); } insideEndpointResolver = new ChainedEndpointResolver(resolverChain); } public DefaultEndpointResolver(DefaultAcsClient client) { this(client, null, DefaultProfile.getProfile(null)); } public DefaultEndpointResolver(DefaultAcsClient client, IClientProfile profile) { this(client, null, profile); } @Override public String resolve(ResolveEndpointRequest request) throws ClientException { return this.insideEndpointResolver.resolve(request); } public void putEndpointEntry(String regionId, String productCode, String endpoint) { this.userCustomizedEndpointResolver.putEndpointEntry(regionId, productCode, endpoint); } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/EndpointResolver.java
package com.aliyuncs.v5.endpoint; import com.aliyuncs.v5.exceptions.ClientException; public interface EndpointResolver { String resolve(ResolveEndpointRequest request) throws ClientException; }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/EndpointResolverBase.java
package com.aliyuncs.v5.endpoint; import java.util.HashMap; import java.util.Map; import java.util.Set; public abstract class EndpointResolverBase implements EndpointResolver { protected 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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/EndpointResolverRules.java
package com.aliyuncs.v5.endpoint; 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) { 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 (this.productSuffix == null || "".equals(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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/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.v5.endpoint; import com.aliyuncs.v5.DefaultAcsClient; 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(DefaultAcsClient 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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/LocalConfigGlobalEndpointResolver.java
package com.aliyuncs.v5.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 = (new JsonParser()).parse(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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/LocalConfigRegionalEndpointResolver.java
package com.aliyuncs.v5.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 = (new JsonParser()).parse(jsonStr).getAsJsonObject(); } finally { if (null != scanner) { scanner.close(); } } } public LocalConfigRegionalEndpointResolver() { initLocalConfig(ENDPOINTS_JSON); } public LocalConfigRegionalEndpointResolver(String configJsonStr) { // For testability JsonObject obj = (new JsonParser()).parse(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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/LocationServiceEndpointResolver.java
package com.aliyuncs.v5.endpoint; import com.aliyuncs.v5.DefaultAcsClient; import com.aliyuncs.v5.endpoint.location.model.v20150612.DescribeEndpointsRequest; import com.aliyuncs.v5.endpoint.location.model.v20150612.DescribeEndpointsResponse; import com.aliyuncs.v5.exceptions.ClientException; import com.aliyuncs.v5.http.FormatType; import com.aliyuncs.v5.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 String locationServiceEndpoint = DEFAULT_LOCATION_SERVICE_ENDPOINT; protected String locationServiceApiVersion = DEFAULT_LOCATION_SERVICE_API_VERSION; private DefaultAcsClient client; private Set<String> invalidProductCodes; private Set<String> validProductCodes; private Set<String> invalidRegionIds; private Set<String> validRegionIds; public LocationServiceEndpointResolver(DefaultAcsClient client) { this.client = client; invalidProductCodes = new HashSet<String>(); invalidRegionIds = new HashSet<String>(); validProductCodes = new HashSet<String>(); validRegionIds = new HashSet<String>(); } public 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; } if (invalidRegionIds.contains(request.regionId)) { 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 invalidRegionIds.add(request.regionId); 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) { if (request.locationServiceCode != null) { return !invalidRegionIds.contains(request.regionId); } return false; } @Override public String makeEndpointKey(ResolveEndpointRequest request) { return makeEndpointKey( request.productCode, request.locationServiceCode, request.regionId, request.endpointType ); } public String makeEndpointKey(String productCode, String locationServiceCode, String regionId, String endpointType) { return productCode.toLowerCase() + "." + locationServiceCode + "." + regionId.toLowerCase() + "." + endpointType; } }
0
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/ResolveEndpointRequest.java
package com.aliyuncs.v5.endpoint; 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 = null; public String regionId = null; public String endpointType = null; public String locationServiceCode = null; public String productCodeLower = null; 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 (endpointType == null || endpointType.length() == 0) { 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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/UserCustomizedEndpointResolver.java
package com.aliyuncs.v5.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-v5/5.0.2/com/aliyuncs/v5
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/UserVpcEndpointResolver.java
package com.aliyuncs.v5.endpoint; import com.aliyuncs.v5.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 public 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-v5/5.0.2/com/aliyuncs/v5/endpoint/location/model
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/location/model/v20150612/DescribeEndpointsRequest.java
package com.aliyuncs.v5.endpoint.location.model.v20150612; import com.aliyuncs.v5.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-v5/5.0.2/com/aliyuncs/v5/endpoint/location/model
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/endpoint/location/model/v20150612/DescribeEndpointsResponse.java
package com.aliyuncs.v5.endpoint.location.model.v20150612; import com.aliyuncs.v5.AcsResponse; import com.aliyuncs.v5.endpoint.location.transform.v20150612.DescribeEndpointsResponseUnmarshaller; import com.aliyuncs.v5.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-v5/5.0.2/com/aliyuncs/v5/endpoint/location/transform
java-sources/com/aliyun/aliyun-java-sdk-core-v5/5.0.2/com/aliyuncs/v5/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.v5.endpoint.location.transform.v20150612; import com.aliyuncs.v5.endpoint.location.model.v20150612.DescribeEndpointsResponse; import com.aliyuncs.v5.endpoint.location.model.v20150612.DescribeEndpointsResponse.Endpoint; import com.aliyuncs.v5.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; } }