index
int64
repo_id
string
file_path
string
content
string
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/RefreshCachedSupplier.java
package com.aliyun.auth.credentials.utils; import com.aliyun.core.utils.SdkAutoCloseable; import com.aliyun.core.utils.Validate; import java.time.Duration; import java.time.Instant; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; public final class RefreshCachedSupplier<T> implements Supplier<T>, SdkAutoCloseable { private static final Duration REFRESH_BLOCKING_MAX_WAIT = Duration.ofSeconds(5); private final Lock refreshLock = new ReentrantLock(); private final PrefetchStrategy prefetchStrategy; private volatile RefreshResult<T> cachedValue = RefreshResult.builder((T) null) .staleTime(Instant.MIN) .prefetchTime(Instant.MIN) .build(); private final Supplier<RefreshResult<T>> valueSupplier; private RefreshCachedSupplier(Builder<T> builder) { this.valueSupplier = Validate.notNull(builder.supplier, "CachedSupplier.supplier is null."); this.prefetchStrategy = Validate.notNull(builder.prefetchStrategy, "CachedSupplier.prefetchStrategy is null."); } public static <T> Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new Builder<>(valueSupplier); } @Override public T get() { if (cacheIsStale()) { refreshCache(); } else if (shouldInitiateCachePrefetch()) { prefetchCache(); } return this.cachedValue.value(); } private boolean cacheIsStale() { return Instant.now().isAfter(cachedValue.staleTime()); } private boolean shouldInitiateCachePrefetch() { return Instant.now().isAfter(cachedValue.prefetchTime()); } private void prefetchCache() { prefetchStrategy.prefetch(this::refreshCache); } private void refreshCache() { try { boolean lockAcquired = refreshLock.tryLock(REFRESH_BLOCKING_MAX_WAIT.getSeconds(), TimeUnit.SECONDS); try { if (cacheIsStale() || shouldInitiateCachePrefetch()) { cachedValue = valueSupplier.get(); } } finally { if (lockAcquired) { refreshLock.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted waiting to refresh the value.", e); } } @Override public void close() { prefetchStrategy.close(); } public static final class Builder<T> { private final Supplier<RefreshResult<T>> supplier; private PrefetchStrategy prefetchStrategy = new OneCallerBlocks(); private Builder(Supplier<RefreshResult<T>> supplier) { this.supplier = supplier; } public Builder<T> prefetchStrategy(PrefetchStrategy prefetchStrategy) { this.prefetchStrategy = prefetchStrategy; return this; } public RefreshCachedSupplier<T> build() { return new RefreshCachedSupplier<>(this); } } @FunctionalInterface public interface PrefetchStrategy extends SdkAutoCloseable { void prefetch(Runnable valueUpdater); default void close() { } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/credentials/utils/RefreshResult.java
package com.aliyun.auth.credentials.utils; import java.time.Instant; public final class RefreshResult<T> { private final T value; private final Instant staleTime; private final Instant prefetchTime; private RefreshResult(Builder<T> builder) { this.value = builder.value; this.staleTime = builder.staleTime; this.prefetchTime = builder.prefetchTime; } public static <T> Builder<T> builder(T value) { return new Builder<>(value); } public T value() { return value; } public Instant staleTime() { return staleTime; } public Instant prefetchTime() { return prefetchTime; } public static final class Builder<T> { private final T value; private Instant staleTime = Instant.MAX; private Instant prefetchTime = Instant.MAX; private Builder(T value) { this.value = value; } public Builder<T> staleTime(Instant staleTime) { this.staleTime = staleTime; return this; } public Builder<T> prefetchTime(Instant prefetchTime) { this.prefetchTime = prefetchTime; return this; } public RefreshResult<T> build() { return new RefreshResult<>(this); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/Signer.java
package com.aliyun.auth.signature; public interface Signer { }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/SignerParams.java
package com.aliyun.auth.signature; import com.aliyun.auth.credentials.ICredential; public class SignerParams { private ICredential credentials; protected SignerParams() { } public static SignerParams create() { return new SignerParams(); } public SignerParams setCredentials(ICredential credentials) { this.credentials = credentials; return this; } public ICredential credentials() { return this.credentials; } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/exception/SignatureException.java
package com.aliyun.auth.signature.exception; public class SignatureException extends RuntimeException { private static final long serialVersionUID = 634786425123290589L; public SignatureException(String message) { super(message); } public SignatureException(String message, Throwable cause) { super(message, cause); } @Override public String getMessage() { return super.getMessage(); } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/signer/SignAlgorithmHmacSHA1.java
package com.aliyun.auth.signature.signer; import com.aliyun.auth.signature.exception.SignatureException; import javax.crypto.Mac; import java.security.NoSuchAlgorithmException; public enum SignAlgorithmHmacSHA1 { HmacSHA1("HmacSHA1"); private final ThreadLocal<Mac> reference; private final String algorithmName; SignAlgorithmHmacSHA1(String algorithmName) { this.algorithmName = algorithmName; reference = new MacThreadLocal(algorithmName); } public String getAlgorithmName(){ return this.algorithmName; } public Mac getMac() { return reference.get(); } private static class MacThreadLocal extends ThreadLocal<Mac> { private final String algorithmName; MacThreadLocal(String algorithmName) { this.algorithmName = algorithmName; } @Override protected Mac initialValue() { try { return Mac.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new SignatureException("Unable to fetch Mac instance for Algorithm " + algorithmName + e.getMessage()); } } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/signer/SignAlgorithmHmacSHA256.java
package com.aliyun.auth.signature.signer; import com.aliyun.auth.signature.exception.SignatureException; import javax.crypto.Mac; import java.security.NoSuchAlgorithmException; public enum SignAlgorithmHmacSHA256 { HmacSHA256("HmacSHA256"); private final ThreadLocal<Mac> reference; private final String algorithmName; SignAlgorithmHmacSHA256(String algorithmName) { this.algorithmName = algorithmName; reference = new MacThreadLocal(algorithmName); } public String getAlgorithmName() { return this.algorithmName; } public Mac getMac() { return reference.get(); } private static class MacThreadLocal extends ThreadLocal<Mac> { private final String algorithmName; MacThreadLocal(String algorithmName) { this.algorithmName = algorithmName; } @Override protected Mac initialValue() { try { return Mac.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new SignatureException("Unable to fetch Mac instance for Algorithm " + algorithmName + e.getMessage()); } } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/signer/SignAlgorithmHmacSM3.java
package com.aliyun.auth.signature.signer; import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.crypto.macs.HMac; public enum SignAlgorithmHmacSM3 { HMAC_SM3("HMAC-SM3"); private final ThreadLocal<HMac> reference; private final String algorithmName; SignAlgorithmHmacSM3(String algorithmName) { this.algorithmName = algorithmName; reference = new MacThreadLocal(); } public String getAlgorithmName(){ return this.algorithmName; } @Override public String toString(){ return this.algorithmName; } public HMac getMac() { return reference.get(); } private static class MacThreadLocal extends ThreadLocal<HMac> { @Override protected HMac initialValue() { return new HMac(new SM3Digest()); } } }
0
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature
java-sources/com/aliyun/aliyun-java-auth/0.3.2-beta/com/aliyun/auth/signature/signer/SignAlgorithmSHA256withRSA.java
package com.aliyun.auth.signature.signer; import com.aliyun.auth.signature.exception.SignatureException; import java.security.NoSuchAlgorithmException; import java.security.Signature; public enum SignAlgorithmSHA256withRSA { SHA256withRSA("SHA256withRSA", "RSA"); private final ThreadLocal<Signature> reference; private final String algorithmName; private final String keyName; SignAlgorithmSHA256withRSA(String algorithmName, String keyName) { this.algorithmName = algorithmName; this.keyName = keyName; reference = new MacThreadLocal(algorithmName); } public String getAlgorithmName(){ return this.algorithmName; } @Override public String toString(){ return this.keyName; } public Signature getSignature() { return reference.get(); } private static class MacThreadLocal extends ThreadLocal<Signature> { private final String algorithmName; MacThreadLocal(String algorithmName) { this.algorithmName = algorithmName; } @Override protected Signature initialValue() { try { return Signature.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new SignatureException("Unable to fetch Signature instance for Algorithm " + algorithmName + e.getMessage()); } } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/Body.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.FIELD; @Documented @Retention(RUNTIME) @Target(FIELD) public @interface Body { /** * Get the body params in HTTP request. */ // String value(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/EnumType.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.TYPE; @Documented @Retention(RUNTIME) @Target(TYPE) public @interface EnumType { }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/Header.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.FIELD; @Documented @Retention(RUNTIME) @Target(FIELD) public @interface Header { /** * Get the header params in HTTP request. */ // String value(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/Host.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Documented @Retention(RUNTIME) @Target(FIELD) public @interface Host { /** * Get the header params in HTTP request. */ // String value(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/NameInMap.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; @Documented @Retention(RUNTIME) @Target({FIELD, METHOD}) public @interface NameInMap { /** * @return the desired name of the field when it is serialized or deserialized */ String value(); /** * @return the alternative names of the field when it is deserialized */ String[] alternate() default {}; }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/ParentIgnore.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Documented @Retention(RUNTIME) @Target(FIELD) public @interface ParentIgnore { /** * Parent name. */ String value(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/Path.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.FIELD; @Documented @Retention(RUNTIME) @Target(FIELD) public @interface Path { /** * Get the path params in HTTP request. */ // String value(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/Query.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.FIELD; @Documented @Retention(RUNTIME) @Target(FIELD) public @interface Query { /** * Get the query params in HTTP request. */ // String value(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/annotation/Validation.java
package com.aliyun.core.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; @Documented @Retention(RUNTIME) @Target({FIELD, METHOD}) public @interface Validation { String pattern() default ""; int maxLength() default 0; int minLength() default 0; double maximum() default Double.MAX_VALUE; double minimum() default -Double.MAX_VALUE; boolean required() default false; }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/exception/AliyunException.java
package com.aliyun.core.exception; import com.aliyun.core.utils.StringUtils; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AliyunException extends RuntimeException { private static final long serialVersionUID = 1L; public String code; public String message; public Map<String, Object> data; public AliyunException() { super(); } public AliyunException(final String message) { super(message); this.setMessage(message); } public AliyunException(final Throwable cause) { super(cause); } public AliyunException(final String message, final Throwable cause) { super(message, cause); } public AliyunException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public AliyunException(Map<String, Object> map) { setData(map); } public AliyunException(Map<String, Object> map, String message, Throwable cause) { super(message, cause); setData(map); } @Override public String getMessage() { if (StringUtils.isEmpty(message)) { return super.getMessage(); } return message; } public void setMessage(String message) { this.message = message; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public void setData(Map<String, Object> map) { this.setCode(String.valueOf(map.get("code"))); this.setMessage(String.valueOf(map.get("message"))); Object obj = map.get("data"); if (obj == null) { return; } if (obj instanceof Map) { data = (Map<String, Object>) obj; return; } Map<String, Object> hashMap = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); try { hashMap.put(field.getName(), field.get(obj)); } catch (Exception e) { continue; } } this.data = hashMap; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/BodyType.java
package com.aliyun.core.http; public final class BodyType { public static final String BYTE = "byte"; public static final String BIN = "binary"; public static final String STRING = "string"; public static final String JSON = "json"; public static final String ARRAY = "array"; public static final String FORM = "form"; public static final String NONE = "none"; public static final String ANY = "object"; public static final String XML = "xml"; public static final String BINARY = "binary"; private BodyType() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/BufferedHttpResponse.java
package com.aliyun.core.http; import com.aliyun.core.utils.BaseUtils; import java.nio.ByteBuffer; import java.nio.charset.Charset; public final class BufferedHttpResponse extends HttpResponse { private final HttpResponse innerHttpResponse; private final ByteBuffer cachedBody; public BufferedHttpResponse(HttpResponse innerHttpResponse) { super(innerHttpResponse.getRequest()); this.innerHttpResponse = innerHttpResponse; this.cachedBody = innerHttpResponse.getBody(); } @Override public int getStatusCode() { return innerHttpResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return innerHttpResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return innerHttpResponse.getHeaders(); } @Override public ByteBuffer getBody() { return cachedBody; } @Override public byte[] getBodyAsByteArray() { return cachedBody.array(); } @Override public String getBodyAsString() { return BaseUtils.bomAwareToString(cachedBody.array(), innerHttpResponse.getHeaderValue("Content-Type")); } @Override public String getBodyAsString(Charset charset) { return new String(cachedBody.array(), charset); } @Override public BufferedHttpResponse buffer() { return this; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/FormatType.java
package com.aliyun.core.http; public final class FormatType { /** * the default XML Content-Type header. */ public static final String XML = "application/xml"; /** * the default JSON Content-Type header. */ public static final String JSON = "application/json"; /** * the default binary Content-Type header. */ public static final String RAW = "application/octet-stream"; /** * The default form data Content-Type header. */ public static final String FORM = "application/x-www-form-urlencoded"; public static final String MULTI = "multipart/form-data"; public static final String PLAIN = "text/plain; charset=UTF-8"; private FormatType() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/Header.java
package com.aliyun.core.http; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; public class Header { private final String name; private final List<String> values; private String cachedStringValue; public Header(String name, String value) { Objects.requireNonNull(name, "'name' cannot be null."); this.name = name; this.values = new LinkedList<>(); this.values.add(value); } public Header(String name, String... values) { Objects.requireNonNull(name, "'name' cannot be null."); this.name = name; this.values = new LinkedList<>(); for (String value : values) { this.values.add(value); } } public Header(String name, List<String> values) { Objects.requireNonNull(name, "'name' cannot be null."); this.name = name; this.values = new LinkedList<>(values); } public String getName() { return name; } public String getValue() { checkCachedStringValue(); return cachedStringValue; } public String[] getValues() { return values.toArray(new String[]{}); } public List<String> getValuesList() { return Collections.unmodifiableList(values); } public void addValue(String value) { this.values.add(value); this.cachedStringValue = null; } @Override public String toString() { checkCachedStringValue(); return name + ":" + cachedStringValue; } private void checkCachedStringValue() { if (cachedStringValue == null) { cachedStringValue = String.join(",", values); } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpClient.java
package com.aliyun.core.http; import com.aliyun.core.utils.Context; import com.aliyun.core.utils.HttpClientOptions; import com.aliyun.core.utils.SdkAutoCloseable; import java.util.concurrent.CompletableFuture; public interface HttpClient extends SdkAutoCloseable { CompletableFuture<HttpResponse> send(HttpRequest request); default CompletableFuture<HttpResponse> send(HttpRequest request, Context context) { return send(request); } static HttpClient createDefault() { return createDefault(null); } static HttpClient createDefault(HttpClientOptions clientOptions) { return HttpClientProviders.createInstance(clientOptions); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpClientProvider.java
package com.aliyun.core.http; import com.aliyun.core.utils.HttpClientOptions; @FunctionalInterface public interface HttpClientProvider { HttpClient createInstance(); default HttpClient createInstance(HttpClientOptions clientOptions) { return createInstance(); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpClientProviders.java
package com.aliyun.core.http; import com.aliyun.core.utils.ClientOptions; import com.aliyun.core.utils.HttpClientOptions; import java.util.Iterator; import java.util.ServiceLoader; public final class HttpClientProviders { private static final String CANNOT_FIND_HTTP_CLIENT = "A request was made to load the default HttpClient provider."; private static HttpClientProvider defaultProvider; static { ServiceLoader<HttpClientProvider> serviceLoader = ServiceLoader.load(HttpClientProvider.class); Iterator<HttpClientProvider> it = serviceLoader.iterator(); if (it.hasNext()) { defaultProvider = it.next(); } } private HttpClientProviders() { // no-op } public static HttpClient createInstance() { return createInstance(null); } public static HttpClient createInstance(ClientOptions clientOptions) { if (defaultProvider == null) { throw new IllegalStateException(CANNOT_FIND_HTTP_CLIENT); } if (clientOptions instanceof HttpClientOptions) { return defaultProvider.createInstance((HttpClientOptions) clientOptions); } return defaultProvider.createInstance(); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpContentPublisher.java
package com.aliyun.core.http; import org.reactivestreams.Publisher; import java.nio.ByteBuffer; public interface HttpContentPublisher extends Publisher<ByteBuffer> { }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpHeader.java
package com.aliyun.core.http; import java.util.List; public class HttpHeader extends Header { public HttpHeader(String name, String value) { super(name, value); } public HttpHeader(String name, List<String> values) { super(name, values); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpHeaders.java
package com.aliyun.core.http; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class HttpHeaders implements Iterable<HttpHeader> { private final Map<String, HttpHeader> headers = new HashMap<>(); public HttpHeaders() { } public HttpHeaders(Map<String, String> headers) { headers.forEach(this::set); } public HttpHeaders(Iterable<HttpHeader> headers) { for (final HttpHeader header : headers) { this.set(header.getName(), header.getValue()); } } public int getSize() { return headers.size(); } public HttpHeaders set(String name, String value) { if (name == null) { return this; } String caseInsensitiveName = formatKey(name); if (value == null) { remove(caseInsensitiveName); } else { headers.put(caseInsensitiveName, new HttpHeader(name, value)); } return this; } public HttpHeaders set(String name, List<String> values) { if (name == null) { return this; } String caseInsensitiveName = formatKey(name); if (values == null) { remove(caseInsensitiveName); } else { headers.put(caseInsensitiveName, new HttpHeader(name, values)); } return this; } public HttpHeaders setAll(Map<String, List<String>> headers) { headers.forEach(this::set); return this; } public HttpHeader get(String name) { return headers.get(formatKey(name)); } public HttpHeader remove(String name) { return headers.remove(formatKey(name)); } public String getValue(String name) { final HttpHeader header = get(name); return header == null ? null : header.getValue(); } public String[] getValues(String name) { final HttpHeader header = get(name); return header == null ? null : header.getValues(); } private String formatKey(final String key) { return key.toLowerCase(Locale.ROOT); } public Map<String, String> toMap() { final Map<String, String> result = new HashMap<>(); for (final HttpHeader header : headers.values()) { result.put(header.getName(), header.getValue()); } return Collections.unmodifiableMap(result); } public Map<String, String> toCaseInsensitiveMap() { final Map<String, String> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (final HttpHeader header : headers.values()) { result.put(header.getName(), header.getValue()); } return Collections.unmodifiableMap(result); } public HttpHeaders putAll(HttpHeaders headers) { this.headers.putAll(headers.headers); return this; } @Override public Iterator<HttpHeader> iterator() { return headers.values().iterator(); } public Stream<HttpHeader> stream() { return headers.values().stream(); } @Override public String toString() { return this.stream() .map(header -> header.getName() + "=" + header.getValue()) .collect(Collectors.joining(", ")); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpMethod.java
package com.aliyun.core.http; import com.aliyun.core.annotation.EnumType; @EnumType public enum HttpMethod { /** * The HTTP GET method. */ GET, /** * The HTTP PUT method. */ PUT, /** * The HTTP POST method. */ POST, /** * The HTTP PATCH method. */ PATCH, /** * The HTTP DELETE method. */ DELETE, /** * The HTTP HEAD method. */ HEAD, /** * The HTTP OPTIONS method. */ OPTIONS, /** * The HTTP TRACE method. */ TRACE, /** * The HTTP CONNECT method. */ CONNECT }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpRequest.java
package com.aliyun.core.http; import com.aliyun.core.logging.ClientLogger; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.concurrent.CompletableFuture; public class HttpRequest { private final ClientLogger logger = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; private HttpHeaders headers; private ByteBuffer body; private Duration connectTimeout; private Duration writeTimeout; private Duration responseTimeout; private Duration readTimeout; private ProxyOptions proxyOptions; private InputStream streamBody; public HttpRequest(HttpMethod httpMethod) { this.httpMethod = httpMethod; this.headers = new HttpHeaders(); } public HttpRequest(HttpMethod httpMethod, URL url) { this.httpMethod = httpMethod; this.url = url; this.headers = new HttpHeaders(); } public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; try { this.url = new URL(url); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex)); } this.headers = new HttpHeaders(); } public HttpRequest(HttpMethod httpMethod, URL url, HttpHeaders headers, ByteBuffer body) { this.httpMethod = httpMethod; this.url = url; this.headers = headers; this.body = body; } public HttpMethod getHttpMethod() { return httpMethod; } public HttpRequest setHttpMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } public URL getUrl() { return url; } public HttpRequest setUrl(URL url) { this.url = url; return this; } public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } public HttpHeaders getHeaders() { return headers; } public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; return this; } public HttpRequest setHeader(String name, String value) { headers.set(name, value); return this; } public ByteBuffer getBody() { return body; } public HttpRequest setBody(String content) { final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8); return setBody(bodyBytes); } public HttpRequest setBody(byte[] content) { return setBody(ByteBuffer.wrap(content)); } public HttpRequest setBody(ByteBuffer content) { this.body = content; return this; } public HttpRequest setStreamBody(InputStream inputstream) { this.streamBody = inputstream; return this; } public InputStream getStreamBody() { return this.streamBody; } public HttpRequest setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public ProxyOptions getProxyOptions() { return this.proxyOptions; } public Duration getConnectTimeout() { return this.connectTimeout; } public HttpRequest setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } public Duration getWriteTimeout() { return this.writeTimeout; } public HttpRequest setWriteTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } public Duration getResponseTimeout() { return this.responseTimeout; } public HttpRequest setResponseTimeout(Duration responseTimeout) { this.responseTimeout = responseTimeout; return this; } public Duration getReadTimeout() { return this.readTimeout; } public HttpRequest setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } public HttpRequest copy() { final HttpHeaders bufferedHeaders = new HttpHeaders(headers); return new HttpRequest(httpMethod, url, bufferedHeaders, body); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpResponse.java
package com.aliyun.core.http; import java.io.Closeable; import java.nio.ByteBuffer; import java.nio.charset.Charset; public abstract class HttpResponse implements Closeable { private final HttpRequest request; protected HttpResponse(HttpRequest request) { this.request = request; } public abstract int getStatusCode(); public abstract String getHeaderValue(String name); public abstract HttpHeaders getHeaders(); public abstract ByteBuffer getBody(); public abstract byte[] getBodyAsByteArray(); public abstract String getBodyAsString(); public abstract String getBodyAsString(Charset charset); public final HttpRequest getRequest() { return request; } public HttpResponse buffer() { return new BufferedHttpResponse(this); } @Override public void close() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/HttpResponseHandler.java
package com.aliyun.core.http; import org.reactivestreams.Publisher; import java.nio.ByteBuffer; public interface HttpResponseHandler { /** * Called when the response stream is ready. */ void onStream(Publisher<ByteBuffer> publisher, int httpStatusCode, HttpHeaders headers); void onError(Throwable throwable); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/ProtocolType.java
package com.aliyun.core.http; public final class ProtocolType { public static final String HTTP = "http"; public static final String HTTPS = "https"; private ProtocolType() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/ProxyOptions.java
package com.aliyun.core.http; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.Configuration; import com.aliyun.core.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; import java.util.regex.Pattern; public class ProxyOptions { private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class); private static final String INVALID_CONFIGURATION_MESSAGE = "'configuration' cannot be 'Configuration.NONE'."; private static final String INVALID_ALIYUN_PROXY_URL = "Configuration {} is an invalid URL and is being ignored."; private static final String JAVA_PROXY_PREREQUISITE = "java.net.useSystemProxies"; private static final String JAVA_PROXY_HOST = "proxyHost"; private static final String JAVA_PROXY_PORT = "proxyPort"; private static final String JAVA_PROXY_USER = "proxyUser"; private static final String JAVA_PROXY_PASSWORD = "proxyPassword"; private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts"; private static final String HTTPS = "https"; private static final int DEFAULT_HTTPS_PORT = 443; private static final String HTTP = "http"; private static final int DEFAULT_HTTP_PORT = 80; private static final List<BiFunction<Configuration, Boolean, ProxyOptions>> ENVIRONMENT_LOAD_ORDER = Arrays.asList( (configuration, resolveProxy) -> attemptToLoadAliProxy(configuration, resolveProxy, Configuration.PROPERTY_HTTPS_PROXY), (configuration, resolveProxy) -> attemptToLoadAliProxy(configuration, resolveProxy, Configuration.PROPERTY_HTTP_PROXY), (configuration, resolveProxy) -> attemptToLoadJavaProxy(configuration, resolveProxy, HTTPS), (configuration, resolveProxy) -> attemptToLoadJavaProxy(configuration, resolveProxy, HTTP) ); private final InetSocketAddress address; private final Type type; private String scheme; private String username; private String password; private String nonProxyHosts; public ProxyOptions(Type type, InetSocketAddress address) { this.type = type; this.address = address; } public ProxyOptions(Type type, InetSocketAddress address, String scheme) { this.type = type; this.address = address; this.scheme = scheme; } public ProxyOptions setCredentials(String username, String password) { this.username = Objects.requireNonNull(username, "proxy 'username' cannot be null."); this.password = Objects.requireNonNull(password, "proxy 'password' cannot be null."); return this; } public ProxyOptions setNonProxyHosts(String nonProxyHosts) { this.nonProxyHosts = sanitizeNoProxy(nonProxyHosts); return this; } /** * The address of the proxy. */ public InetSocketAddress getAddress() { return address; } /** * The type of the proxy. */ public Type getType() { return type; } /** * The scheme of the proxy host : http or https. */ public String getScheme() { return scheme; } /** * The proxy user name. */ public String getUsername() { return this.username; } /** * The proxy password. */ public String getPassword() { return this.password; } /** * The hosts that bypass the proxy. */ public String getNonProxyHosts() { return this.nonProxyHosts; } public static ProxyOptions fromConfiguration(Configuration configuration) { return fromConfiguration(configuration, false); } public static ProxyOptions fromConfiguration(Configuration configuration, boolean createUnresolved) { if (configuration == Configuration.NONE) { throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(INVALID_CONFIGURATION_MESSAGE)); } Configuration proxyConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; for (BiFunction<Configuration, Boolean, ProxyOptions> loader : ENVIRONMENT_LOAD_ORDER) { ProxyOptions proxyOptions = loader.apply(proxyConfiguration, createUnresolved); if (proxyOptions != null) { return proxyOptions; } } return null; } private static ProxyOptions attemptToLoadAliProxy(Configuration configuration, boolean createUnresolved, String proxyProperty) { String proxyConfiguration = configuration.get(proxyProperty); // No proxy configuration setup. if (StringUtils.isEmpty(proxyConfiguration)) { return null; } try { URL proxyUrl = new URL(proxyConfiguration); int port = (proxyUrl.getPort() == -1) ? proxyUrl.getDefaultPort() : proxyUrl.getPort(); InetSocketAddress socketAddress = (createUnresolved) ? InetSocketAddress.createUnresolved(proxyUrl.getHost(), port) : new InetSocketAddress(proxyUrl.getHost(), port); ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, socketAddress, proxyUrl.getProtocol()); String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY); if (!StringUtils.isEmpty(nonProxyHostsString)) { proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString); } String userInfo = proxyUrl.getUserInfo(); if (userInfo != null) { String[] usernamePassword = userInfo.split(":", 2); if (usernamePassword.length == 2) { try { proxyOptions.setCredentials( URLDecoder.decode(usernamePassword[0], StandardCharsets.UTF_8.toString()), URLDecoder.decode(usernamePassword[1], StandardCharsets.UTF_8.toString()) ); } catch (UnsupportedEncodingException e) { return null; } } } return proxyOptions; } catch (MalformedURLException ex) { LOGGER.warning(INVALID_ALIYUN_PROXY_URL, proxyProperty); return null; } } private static String sanitizeNoProxy(String noProxyString) { String[] nonProxyHosts = noProxyString.split(","); for (int i = 0; i < nonProxyHosts.length; i++) { String prefixWildcard = ""; String suffixWildcard = ""; String body = nonProxyHosts[i]; if (body.startsWith(".*")) { prefixWildcard = ".*"; body = body.substring(2); } else if (body.startsWith("*") || body.startsWith(".")) { prefixWildcard = ".*"; body = body.substring(1); } if (body.endsWith(".*")) { suffixWildcard = ".*"; body = body.substring(0, body.length() - 2); } else if (body.endsWith("*") || body.endsWith(".")) { suffixWildcard = ".*"; body = body.substring(0, body.length() - 1); } nonProxyHosts[i] = prefixWildcard + Pattern.quote(body) + suffixWildcard; } return String.join("|", nonProxyHosts); } private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, boolean createUnresolved, String type) { if (!Boolean.parseBoolean(configuration.get(JAVA_PROXY_PREREQUISITE))) { return null; } String host = configuration.get(type + "." + JAVA_PROXY_HOST); if (StringUtils.isEmpty(host)) { return null; } int port; try { port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT)); } catch (NumberFormatException ex) { port = HTTPS.equals(type) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT; } InetSocketAddress socketAddress = (createUnresolved) ? InetSocketAddress.createUnresolved(host, port) : new InetSocketAddress(host, port); ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, socketAddress, type); String nonProxyHostsString = configuration.get(JAVA_NON_PROXY_HOSTS); if (!StringUtils.isEmpty(nonProxyHostsString)) { proxyOptions.nonProxyHosts = sanitizeJavaHttpNonProxyHosts(nonProxyHostsString); } String username = configuration.get(type + "." + JAVA_PROXY_USER); String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD); if (username != null && password != null) { proxyOptions.setCredentials(username, password); } return proxyOptions; } private static String sanitizeJavaHttpNonProxyHosts(String nonProxyHostsString) { String[] nonProxyHosts = nonProxyHostsString.split("\\|"); for (int i = 0; i < nonProxyHosts.length; i++) { String prefixWildcard = ""; String suffixWildcard = ""; String body = nonProxyHosts[i]; if (body.startsWith("*")) { prefixWildcard = ".*"; body = body.substring(1); } if (body.endsWith("*")) { suffixWildcard = ".*"; body = body.substring(0, body.length() - 1); } nonProxyHosts[i] = prefixWildcard + Pattern.quote(body) + suffixWildcard; } return String.join("|", nonProxyHosts); } /** * The type of the proxy. */ public enum Type { /** * HTTP proxy type. */ HTTP(Proxy.Type.HTTP), /** * SOCKS4 proxy type. */ SOCKS4(Proxy.Type.SOCKS), /** * SOCKS5 proxy type. */ SOCKS5(Proxy.Type.SOCKS); private final Proxy.Type proxyType; Type(Proxy.Type proxyType) { this.proxyType = proxyType; } /** * Get the {@link Proxy.Type} equivalent of this type. * * @return the proxy type */ public Proxy.Type toProxyType() { return proxyType; } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/policy/HttpLogDetailLevel.java
package com.aliyun.core.http.policy; public enum HttpLogDetailLevel { /** * Logging is turned off. */ NONE, /** * Logs only URLs, HTTP methods, and time to finish the request. */ BASIC, /** * Logs everything in BASIC, plus all the request and response headers. */ HEADERS, /** * Logs everything in BASIC, plus all the request and response body. */ BODY, /** * Logs everything in HEADERS and BODY. */ BODY_AND_HEADERS; /** * a value indicating whether a request's URL should be logged. */ public boolean shouldLogUrl() { return this != NONE; } /** * a value indicating whether HTTP message headers should be logged. */ public boolean shouldLogHeaders() { return this == HEADERS || this == BODY_AND_HEADERS; } /** * a value indicating whether HTTP message bodies should be logged. */ public boolean shouldLogBody() { return this == BODY || this == BODY_AND_HEADERS; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/policy/HttpLogOptions.java
package com.aliyun.core.http.policy; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.utils.StringUtils; import java.util.*; public class HttpLogOptions { private String applicationId; private HttpLogDetailLevel logLevel; private Set<String> allowedHeaderNames; private Set<String> allowedQueryParamNames; private boolean prettyPrintBody; private final ClientLogger logger = new ClientLogger(HttpLogOptions.class); private static final int MAX_APPLICATION_ID_LENGTH = 24; private static final List<String> DEFAULT_HEADERS_WHITELIST = Arrays.asList( "host", "x-acs-action", "x-acs-version", "Accept", "Content-Length", "Content-Type", "Date", "request-Id", "user-agent", "authorization" ); public HttpLogOptions() { logLevel = HttpLogDetailLevel.NONE; allowedHeaderNames = new HashSet<>(DEFAULT_HEADERS_WHITELIST); allowedQueryParamNames = new HashSet<>(); applicationId = null; } public HttpLogDetailLevel getLogLevel() { return logLevel; } public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) { this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel; return this; } public Set<String> getAllowedHeaderNames() { return allowedHeaderNames; } public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) { this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames; return this; } public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) { Objects.requireNonNull(allowedHeaderName); this.allowedHeaderNames.add(allowedHeaderName); return this; } public Set<String> getAllowedQueryParamNames() { return allowedQueryParamNames; } public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) { this.allowedQueryParamNames = allowedQueryParamNames == null ? new HashSet<>() : allowedQueryParamNames; return this; } public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) { this.allowedQueryParamNames.add(allowedQueryParamName); return this; } public boolean isPrettyPrintBody() { return prettyPrintBody; } public HttpLogOptions setPrettyPrintBody(boolean prettyPrintBody) { this.prettyPrintBody = prettyPrintBody; return this; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/http/policy/HttpLoggingPolicy.java
package com.aliyun.core.http.policy; import com.aliyun.core.http.*; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.logging.LogLevel; import com.aliyun.core.utils.StringUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.Collections; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class HttpLoggingPolicy { private static final int MAX_BODY_LOG_SIZE = 1024 * 16; private static final String REDACTED_PLACEHOLDER = "REDACTED"; private final HttpLogDetailLevel httpLogDetailLevel; private final Set<String> allowedHeaderNames; private final Set<String> allowedQueryParameterNames; private final boolean prettyPrintBody; public static final String RETRY_COUNT_CONTEXT = "requestRetryCount"; public HttpLoggingPolicy(HttpLogOptions httpLogOptions) { if (httpLogOptions == null) { this.httpLogDetailLevel = HttpLogDetailLevel.NONE; this.allowedHeaderNames = Collections.emptySet(); this.allowedQueryParameterNames = Collections.emptySet(); this.prettyPrintBody = false; } else { this.httpLogDetailLevel = httpLogOptions.getLogLevel(); this.allowedHeaderNames = httpLogOptions.getAllowedHeaderNames() .stream() .map(headerName -> headerName.toLowerCase(Locale.ROOT)) .collect(Collectors.toSet()); this.allowedQueryParameterNames = httpLogOptions.getAllowedQueryParamNames() .stream() .map(queryParamName -> queryParamName.toLowerCase(Locale.ROOT)) .collect(Collectors.toSet()); this.prettyPrintBody = httpLogOptions.isPrettyPrintBody(); } } private void logRequest(final ClientLogger logger, final HttpRequest request, final Optional<Object> optionalRetryCount) { if (!logger.canLogAtLevel(LogLevel.INFORMATIONAL)) { return; } StringBuilder requestLogMessage = new StringBuilder(); if (httpLogDetailLevel.shouldLogUrl()) { requestLogMessage.append("--> ") .append(request.getHttpMethod()) .append(" ") // .append(getRedactedUrl(request.getUrl())) .append(System.lineSeparator()); optionalRetryCount.ifPresent(o -> requestLogMessage.append("Try count: ") .append(o) .append(System.lineSeparator())); } addHeadersToLogMessage(logger, request.getHeaders(), requestLogMessage); if (!httpLogDetailLevel.shouldLogBody()) { logAndReturn(logger, requestLogMessage, null); return; } if (request.getBody() == null) { requestLogMessage.append("(empty body)") .append(System.lineSeparator()) .append("--> END ") .append(request.getHttpMethod()) .append(System.lineSeparator()); logAndReturn(logger, requestLogMessage, null); return; } String contentType = request.getHeaders().getValue("Content-Type"); long contentLength = getContentLength(logger, request.getHeaders()); if (shouldBodyBeLogged(contentType, contentLength)) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream((int) contentLength); requestLogMessage.append(contentLength) .append("-byte body:") .append(System.lineSeparator()) .append(convertStreamToString(outputStream, logger)) .append(System.lineSeparator()) .append("--> END ") .append(request.getHttpMethod()) .append(System.lineSeparator()); logger.info(requestLogMessage.toString()); } else { requestLogMessage.append(contentLength) .append("-byte body: (content not logged)") .append(System.lineSeparator()) .append("--> END ") .append(request.getHttpMethod()) .append(System.lineSeparator()); logAndReturn(logger, requestLogMessage, null); } } /* * Logs thr HTTP response. */ private HttpResponse logResponse(final ClientLogger logger, final HttpResponse response, long startNs) throws IOException { if (!logger.canLogAtLevel(LogLevel.INFORMATIONAL)) { return response; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.getHeaderValue("Content-Length"); String bodySize = (StringUtils.isEmpty(contentLengthString)) ? "unknown-length body" : contentLengthString + "-byte body"; StringBuilder responseLogMessage = new StringBuilder(); if (httpLogDetailLevel.shouldLogUrl()) { responseLogMessage.append("<-- ") .append(response.getStatusCode()) .append(" ") // .append(getRedactedUrl(response.getRequest().getUrl())) .append(" (") .append(tookMs) .append(" ms, ") .append(bodySize) .append(")") .append(System.lineSeparator()); } addHeadersToLogMessage(logger, response.getHeaders(), responseLogMessage); if (!httpLogDetailLevel.shouldLogBody()) { responseLogMessage.append("<-- END HTTP"); return logAndReturn(logger, responseLogMessage, response); } String contentTypeHeader = response.getHeaderValue("Content-Type"); long contentLength = getContentLength(logger, response.getHeaders()); if (shouldBodyBeLogged(contentTypeHeader, contentLength)) { HttpResponse bufferedResponse = response.buffer(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream((int) contentLength); WritableByteChannel bodyContentChannel = Channels.newChannel(outputStream); writeBufferToBodyStream(bodyContentChannel, bufferedResponse.getBody()); responseLogMessage.append("Response body:") .append(System.lineSeparator()) .append(convertStreamToString(outputStream, logger)) .append(System.lineSeparator()) .append("<-- END HTTP"); logger.info(responseLogMessage.toString()); return bufferedResponse; } else { responseLogMessage.append("(body content not logged)") .append(System.lineSeparator()) .append("<-- END HTTP"); return logAndReturn(logger, responseLogMessage, response); } } private <T> T logAndReturn(ClientLogger logger, StringBuilder logMessageBuilder, T data) { logger.info(logMessageBuilder.toString()); return data; } private String getAllowedQueryString(String queryString) { if (StringUtils.isEmpty(queryString)) { return ""; } StringBuilder queryStringBuilder = new StringBuilder(); String[] queryParams = queryString.split("&"); for (String queryParam : queryParams) { if (queryStringBuilder.length() > 0) { queryStringBuilder.append("&"); } String[] queryPair = queryParam.split("=", 2); if (queryPair.length == 2) { String queryName = queryPair[0]; if (allowedQueryParameterNames.contains(queryName.toLowerCase(Locale.ROOT))) { queryStringBuilder.append(queryParam); } else { queryStringBuilder.append(queryPair[0]).append("=").append(REDACTED_PLACEHOLDER); } } else { queryStringBuilder.append(queryParam); } } return queryStringBuilder.toString(); } /* * Adds HTTP headers into the StringBuilder that is generating the log message. * * @param headers HTTP headers on the request or response. * @param sb StringBuilder that is generating the log message. * @param logLevel Log level the environment is configured to use. */ private void addHeadersToLogMessage(ClientLogger logger, HttpHeaders headers, StringBuilder sb) { // Either headers shouldn't be logged or the logging level isn't set to VERBOSE, don't add headers. if (!httpLogDetailLevel.shouldLogHeaders() || !logger.canLogAtLevel(LogLevel.VERBOSE)) { return; } for (HttpHeader header : headers) { String headerName = header.getName(); sb.append(headerName).append(":"); if (allowedHeaderNames.contains(headerName.toLowerCase(Locale.ROOT))) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } sb.append(System.lineSeparator()); } } private long getContentLength(ClientLogger logger, HttpHeaders headers) { long contentLength = 0; String contentLengthString = headers.getValue("Content-Length"); if (StringUtils.isEmpty(contentLengthString)) { return contentLength; } try { contentLength = Long.parseLong(contentLengthString); } catch (NumberFormatException | NullPointerException e) { logger.warning("Could not parse the HTTP header content-length: '{}'.", headers.getValue("content-length"), e); } return contentLength; } private boolean shouldBodyBeLogged(String contentTypeHeader, long contentLength) { return !FormatType.RAW.equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE; } private static String convertStreamToString(ByteArrayOutputStream stream, ClientLogger logger) { try { return stream.toString("UTF-8"); } catch (UnsupportedEncodingException ex) { throw logger.logExceptionAsError(new RuntimeException(ex)); } } private static CompletableFuture<ByteBuffer> writeBufferToBodyStream(WritableByteChannel channel, ByteBuffer byteBuffer) throws IOException { channel.write(byteBuffer.duplicate()); return CompletableFuture.completedFuture(byteBuffer); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/io/BoundedInputStream.java
package com.aliyun.core.io; import java.io.IOException; import java.io.InputStream; /** * This is a stream that will only supply bytes up to a certain length - if its * position goes above that, it will stop. * <p> * This is useful to wrap ServletInputStreams. The ServletInputStream will block * if you try to read content from it that isn't there, because it doesn't know * whether the content hasn't arrived yet or whether the content has finished. * So, one of these, initialized with the Content-length sent in the * ServletInputStream's header, will stop it blocking, providing it's been sent * with a correct content length. * * @since 2.1.1 */ public class BoundedInputStream extends InputStream { /** the wrapped input stream */ private final InputStream in; /** the max length to provide */ private final long max; /** the number of bytes already returned */ private long pos = 0; /** the marked position */ private long mark = -1; /** flag if close shoud be propagated */ private boolean propagateClose = true; /** * Creates a new <code>BoundedInputStream</code> that wraps the given input * stream and limits it to a certain size. * * @param in * The wrapped input stream * @param size * The maximum number of bytes to return */ public BoundedInputStream(InputStream in, long size) { // Some badly designed methods - eg the servlet API - overload length // such that "-1" means stream finished this.max = size; this.in = in; } /** * Creates a new <code>BoundedInputStream</code> that wraps the given input * stream and is unlimited. * * @param in * The wrapped input stream */ public BoundedInputStream(InputStream in) { this(in, -1); } /** * Invokes the delegate's <code>read()</code> method if the current position * is less than the limit. * * @return the byte read or -1 if the end of stream or the limit has been * reached. * @throws IOException * if an I/O error occurs */ @Override public int read() throws IOException { if (max >= 0 && pos >= max) { return -1; } int result = in.read(); pos++; return result; } /** * Invokes the delegate's <code>read(byte[])</code> method. * * @param b * the buffer to read the bytes into * @return the number of bytes read or -1 if the end of stream or the limit * has been reached. * @throws IOException * if an I/O error occurs */ @Override public int read(byte[] b) throws IOException { return this.read(b, 0, b.length); } /** * Invokes the delegate's <code>read(byte[], int, int)</code> method. * * @param b * the buffer to read the bytes into * @param off * The start offset * @param len * The number of bytes to read * @return the number of bytes read or -1 if the end of stream or the limit * has been reached. * @throws IOException * if an I/O error occurs */ @Override public int read(byte[] b, int off, int len) throws IOException { if (max >= 0 && pos >= max) { return -1; } long maxRead = max >= 0 ? Math.min(len, max - pos) : len; int bytesRead = in.read(b, off, (int) maxRead); if (bytesRead == -1) { return -1; } pos += bytesRead; return bytesRead; } /** * Invokes the delegate's <code>skip(long)</code> method. * * @param n * the number of bytes to skip * @return the actual number of bytes skipped * @throws IOException * if an I/O error occurs */ @Override public long skip(long n) throws IOException { long toSkip = max >= 0 ? Math.min(n, max - pos) : n; long skippedBytes = in.skip(toSkip); pos += skippedBytes; return skippedBytes; } /** * {@inheritDoc} */ @Override public int available() throws IOException { if (max >= 0 && pos >= max) { return 0; } return in.available(); } /** * Invokes the delegate's <code>toString()</code> method. * * @return the delegate's <code>toString()</code> */ @Override public String toString() { return in.toString(); } /** * Invokes the delegate's <code>close()</code> method if * {@link #isPropagateClose()} is {@code true}. * * @throws IOException * if an I/O error occurs */ @Override public void close() throws IOException { if (propagateClose) { in.close(); } } /** * Invokes the delegate's <code>reset()</code> method. * * @throws IOException * if an I/O error occurs */ @Override public synchronized void reset() throws IOException { in.reset(); pos = mark; } /** * Invokes the delegate's <code>mark(int)</code> method. * * @param readlimit * read ahead limit */ @Override public synchronized void mark(int readlimit) { in.mark(readlimit); mark = pos; } /** * Invokes the delegate's <code>markSupported()</code> method. * * @return true if mark is supported, otherwise false */ @Override public boolean markSupported() { return in.markSupported(); } /** * Indicates whether the {@link #close()} method should propagate to the * underling {@link InputStream}. * * @return {@code true} if calling {@link #close()} propagates to the * <code>close()</code> method of the underlying stream or * {@code false} if it does not. */ public boolean isPropagateClose() { return propagateClose; } /** * Set whether the {@link #close()} method should propagate to the underling * {@link InputStream}. * * @param propagateClose * {@code true} if calling {@link #close()} propagates to the * <code>close()</code> method of the underlying stream or * {@code false} if it does not. */ public void setPropagateClose(boolean propagateClose) { this.propagateClose = propagateClose; } /** * Get original input stream * * @return original input stream */ public InputStream getWrappedInputStream() { return this.in; } /** * Go back current position * * @param backoff */ protected void backoff(long backoff) { this.pos -= backoff; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/io/NonCloseableInputStream.java
package com.aliyun.core.io; import java.io.FilterInputStream; import java.io.InputStream; public class NonCloseableInputStream extends FilterInputStream { /** * Creates a <code>FilterInputStream</code> * by assigning the argument <code>in</code> * to the field <code>this.in</code> so as * to remember it for later use. * * @param in the underlying input stream, or <code>null</code> if * this instance is to be created without an underlying stream. */ public NonCloseableInputStream(InputStream in) { super(in); } @Override public final void close() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/logging/ClientLogger.java
package com.aliyun.core.logging; import com.aliyun.core.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.NOPLogger; import java.util.Arrays; import java.util.Objects; import java.util.regex.Pattern; public class ClientLogger { private static final Pattern CRLF_PATTERN = Pattern.compile("[\r\n]"); private final Logger logger; public ClientLogger(Class<?> clazz) { this(clazz.getName()); } public ClientLogger(String className) { Logger initLogger = LoggerFactory.getLogger(className); logger = initLogger instanceof NOPLogger ? new DefaultLogger(className) : initLogger; } public void verbose(String message) { if (logger.isDebugEnabled()) { logger.debug(sanitizeLogMessageInput(message)); } } public void verbose(String format, Object... args) { if (logger.isDebugEnabled()) { performLogging(LogLevel.VERBOSE, false, format, args); } } public void info(String message) { if (logger.isInfoEnabled()) { logger.info(sanitizeLogMessageInput(message)); } } public void info(String format, Object... args) { if (logger.isInfoEnabled()) { performLogging(LogLevel.INFORMATIONAL, false, format, args); } } public void warning(String message) { if (logger.isWarnEnabled()) { logger.warn(sanitizeLogMessageInput(message)); } } public void warning(String format, Object... args) { if (logger.isWarnEnabled()) { performLogging(LogLevel.WARNING, false, format, args); } } public void error(String message) { if (logger.isErrorEnabled()) { logger.error(sanitizeLogMessageInput(message)); } } public void error(String format, Object... args) { if (logger.isErrorEnabled()) { performLogging(LogLevel.ERROR, false, format, args); } } public RuntimeException logExceptionAsWarning(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); return logThrowableAsWarning(runtimeException); } public <T extends Throwable> T logThrowableAsWarning(T throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (!logger.isWarnEnabled()) { return throwable; } performLogging(LogLevel.WARNING, true, throwable.getMessage(), throwable); return throwable; } public RuntimeException logExceptionAsError(RuntimeException runtimeException) { Objects.requireNonNull(runtimeException, "'runtimeException' cannot be null."); return logThrowableAsError(runtimeException); } public <T extends Throwable> T logThrowableAsError(T throwable) { Objects.requireNonNull(throwable, "'throwable' cannot be null."); if (!logger.isErrorEnabled()) { return throwable; } performLogging(LogLevel.ERROR, true, throwable.getMessage(), throwable); return throwable; } private void performLogging(LogLevel logLevel, boolean isExceptionLogging, String format, Object... args) { String throwableMessage = ""; if (doesArgsHaveThrowable(args)) { if (!isExceptionLogging) { Object throwable = args[args.length - 1]; if (throwable instanceof Throwable) { throwableMessage = ((Throwable) throwable).getMessage(); } } if (!logger.isDebugEnabled()) { args = removeThrowable(args); } } sanitizeLogMessageInput(format); switch (logLevel) { case VERBOSE: logger.debug(format, args); break; case INFORMATIONAL: logger.info(format, args); break; case WARNING: if (!StringUtils.isEmpty(throwableMessage)) { format += System.lineSeparator() + throwableMessage; } logger.warn(format, args); break; case ERROR: if (!StringUtils.isEmpty(throwableMessage)) { format += System.lineSeparator() + throwableMessage; } logger.error(format, args); break; default: // Don't do anything, this state shouldn't be possible. break; } } public boolean canLogAtLevel(LogLevel logLevel) { if (logLevel == null) { return false; } switch (logLevel) { case VERBOSE: return logger.isDebugEnabled(); case INFORMATIONAL: return logger.isInfoEnabled(); case WARNING: return logger.isWarnEnabled(); case ERROR: return logger.isErrorEnabled(); default: return false; } } private boolean doesArgsHaveThrowable(Object... args) { if (args.length == 0) { return false; } return args[args.length - 1] instanceof Throwable; } private Object[] removeThrowable(Object... args) { return Arrays.copyOf(args, args.length - 1); } private static String sanitizeLogMessageInput(String logMessage) { if (StringUtils.isEmpty(logMessage)) { return logMessage; } return CRLF_PATTERN.matcher(logMessage).replaceAll(""); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/logging/DefaultLogger.java
package com.aliyun.core.logging; import com.aliyun.core.utils.Configuration; import com.aliyun.core.utils.StringUtils; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MarkerIgnoringBase; import org.slf4j.helpers.MessageFormatter; import java.io.PrintWriter; import java.io.StringWriter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public final class DefaultLogger extends MarkerIgnoringBase { private static final long serialVersionUID = -144261058636441630L; private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); private static final String WHITESPACE = " "; private static final String HYPHEN = " - "; private static final String OPEN_BRACKET = " ["; private static final String CLOSE_BRACKET = "]"; public static final String WARN = "WARN"; public static final String DEBUG = "DEBUG"; public static final String INFO = "INFO"; public static final String ERROR = "ERROR"; public static final String TRACE = "TRACE"; private final String classPath; private final boolean isTraceEnabled; private final boolean isDebugEnabled; private final boolean isInfoEnabled; private final boolean isWarnEnabled; private final boolean isErrorEnabled; public DefaultLogger(Class<?> clazz) { this(clazz.getName()); } public DefaultLogger(String className) { String classPath; try { classPath = Class.forName(className).getCanonicalName(); } catch (ClassNotFoundException e) { classPath = className; } this.classPath = classPath; int configuredLogLevel = LogLevel.fromString( !StringUtils.isEmpty(Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_ALIBABA_CLOUD_LOG_LEVEL)) ? Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_ALIBABA_CLOUD_LOG_LEVEL) : WARN) .getLogLevel(); isTraceEnabled = LogLevel.VERBOSE.getLogLevel() > configuredLogLevel; isDebugEnabled = LogLevel.VERBOSE.getLogLevel() >= configuredLogLevel; isInfoEnabled = LogLevel.INFORMATIONAL.getLogLevel() >= configuredLogLevel; isWarnEnabled = LogLevel.WARNING.getLogLevel() >= configuredLogLevel; isErrorEnabled = LogLevel.ERROR.getLogLevel() >= configuredLogLevel; } @Override public String getName() { return classPath; } @Override public boolean isTraceEnabled() { return isTraceEnabled; } @Override public void trace(final String msg) { logMessageWithFormat(TRACE, msg); } @Override public void trace(final String format, final Object arg1) { logMessageWithFormat(TRACE, format, arg1); } @Override public void trace(final String format, final Object arg1, final Object arg2) { logMessageWithFormat(TRACE, format, arg1, arg2); } @Override public void trace(final String format, final Object... arguments) { logMessageWithFormat(TRACE, format, arguments); } @Override public void trace(final String msg, final Throwable t) { log(TRACE, msg, t); } @Override public boolean isDebugEnabled() { return isDebugEnabled; } @Override public void debug(final String msg) { logMessageWithFormat(DEBUG, msg); } @Override public void debug(String format, Object arg) { logMessageWithFormat(DEBUG, format, arg); } @Override public void debug(final String format, final Object arg1, final Object arg2) { logMessageWithFormat(DEBUG, format, arg1, arg2); } @Override public void debug(String format, Object... args) { logMessageWithFormat(DEBUG, format, args); } @Override public void debug(final String msg, final Throwable t) { log(DEBUG, msg, t); } @Override public boolean isInfoEnabled() { return isInfoEnabled; } @Override public void info(final String msg) { logMessageWithFormat(INFO, msg); } @Override public void info(String format, Object arg) { logMessageWithFormat(INFO, format, arg); } @Override public void info(final String format, final Object arg1, final Object arg2) { logMessageWithFormat(INFO, format, arg1, arg2); } @Override public void info(String format, Object... args) { logMessageWithFormat(INFO, format, args); } @Override public void info(final String msg, final Throwable t) { log(INFO, msg, t); } @Override public boolean isWarnEnabled() { return isWarnEnabled; } @Override public void warn(final String msg) { logMessageWithFormat(WARN, msg); } @Override public void warn(String format, Object arg) { logMessageWithFormat(WARN, format, arg); } @Override public void warn(final String format, final Object arg1, final Object arg2) { logMessageWithFormat(WARN, format, arg1, arg2); } @Override public void warn(String format, Object... args) { logMessageWithFormat(WARN, format, args); } @Override public void warn(final String msg, final Throwable t) { log(WARN, msg, t); } @Override public boolean isErrorEnabled() { return isErrorEnabled; } @Override public void error(String format, Object arg) { logMessageWithFormat(ERROR, format, arg); } @Override public void error(final String msg) { logMessageWithFormat(ERROR, msg); } @Override public void error(final String format, final Object arg1, final Object arg2) { logMessageWithFormat(ERROR, format, arg1, arg2); } @Override public void error(String format, Object... args) { logMessageWithFormat(ERROR, format, args); } @Override public void error(final String msg, final Throwable t) { log(ERROR, msg, t); } private void logMessageWithFormat(String levelName, String format, Object... arguments) { FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments); log(levelName, tp.getMessage(), tp.getThrowable()); } private void log(String levelName, String message, Throwable t) { String dateTime = getFormattedDate(); String threadName = Thread.currentThread().getName(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder .append(dateTime) .append(OPEN_BRACKET) .append(threadName) .append(CLOSE_BRACKET) .append(OPEN_BRACKET) .append(levelName) .append(CLOSE_BRACKET) .append(WHITESPACE) .append(classPath) .append(HYPHEN) .append(message) .append(System.lineSeparator()); writeWithThrowable(stringBuilder, t); } private String getFormattedDate() { LocalDateTime now = LocalDateTime.now(); return DATE_FORMAT.format(now); } void writeWithThrowable(StringBuilder stringBuilder, Throwable t) { if (t != null) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { t.printStackTrace(pw); stringBuilder.append(sw.toString()); } } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/logging/LogLevel.java
package com.aliyun.core.logging; import java.util.HashMap; import java.util.Locale; public enum LogLevel { /** * Indicates that log level is at verbose level. */ VERBOSE(1, "1", "verbose", "debug"), /** * Indicates that log level is at information level. */ INFORMATIONAL(2, "2", "info", "information", "informational"), /** * Indicates that log level is at warning level. */ WARNING(3, "3", "warn", "warning"), /** * Indicates that log level is at error level. */ ERROR(4, "4", "err", "error"), /** * Indicates that no log level is set. */ NOT_SET(5, "5"); private final int numericValue; private final String[] allowedLogLevelVariables; private static final HashMap<String, LogLevel> LOG_LEVEL_STRING_MAPPER = new HashMap<>(); static { for (LogLevel logLevel : LogLevel.values()) { for (String val : logLevel.allowedLogLevelVariables) { LOG_LEVEL_STRING_MAPPER.put(val, logLevel); } } } LogLevel(int numericValue, String... allowedLogLevelVariables) { this.numericValue = numericValue; this.allowedLogLevelVariables = allowedLogLevelVariables; } public int getLogLevel() { return numericValue; } public static LogLevel fromString(String logLevelVal) { if (logLevelVal == null) { return LogLevel.NOT_SET; } String caseInsensitiveLogLevel = logLevelVal.toLowerCase(Locale.ROOT); if (!LOG_LEVEL_STRING_MAPPER.containsKey(caseInsensitiveLogLevel)) { throw new IllegalArgumentException("We currently do not support the log level you set. LogLevel: " + logLevelVal); } return LOG_LEVEL_STRING_MAPPER.get(caseInsensitiveLogLevel); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/AccessibleByteArrayOutputStream.java
package com.aliyun.core.utils; import java.io.ByteArrayOutputStream; public class AccessibleByteArrayOutputStream extends ByteArrayOutputStream { @Override public synchronized byte[] toByteArray() { return buf; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/AttributeMap.java
package com.aliyun.core.utils; import java.util.HashMap; import java.util.Map; public class AttributeMap implements SdkAutoCloseable, Copyable { private final Map<Key<?>, Object> attributes; private AttributeMap(Map<? extends Key<?>, ?> attributes) { this.attributes = new HashMap<>(attributes); } public <T> boolean containsKey(Key<T> typedKey) { return attributes.containsKey(typedKey); } public <T> T get(Key<T> key) { Validate.notNull(key, "Key to retrieve must not be null."); return key.convertValue(attributes.get(key)); } public <T> AttributeMap put(Key<T> key, T value) { Validate.notNull(key, "Key to set must not be null."); attributes.put(key, value); return this; } public <T> AttributeMap putIfAbsent(Key<T> key, T value) { Validate.notNull(key, "Key to set must not be null."); attributes.putIfAbsent(key, value); return this; } public AttributeMap merge(AttributeMap lowerPrecedence) { Map<Key<?>, Object> copiedConfiguration = new HashMap<>(attributes); lowerPrecedence.attributes.forEach(copiedConfiguration::putIfAbsent); return new AttributeMap(copiedConfiguration); } @Override public AttributeMap copy() { Map<Key<?>, Object> map = new HashMap<>(); attributes.forEach((key, value) -> { key.validateValue(value); map.put(key, value); }); return new AttributeMap(map); } public static AttributeMap empty() { return new AttributeMap(new HashMap<>()); } @Override public void close() { attributes.values().forEach(v -> IOUtils.closeIfCloseable(v, null)); } public abstract static class Key<T> { private final Class<?> valueType; protected Key(Class<T> valueType) { this.valueType = valueType; } protected Key(UnsafeValueType unsafeValueType) { this.valueType = unsafeValueType.valueType; } protected static class UnsafeValueType { private final Class<?> valueType; public UnsafeValueType(Class<?> valueType) { this.valueType = valueType; } } final void validateValue(Object value) { if (value != null) { Validate.isAssignableFrom(valueType, value.getClass(), "Invalid option: %s. Required value of type %s, but was %s.", this, valueType, value.getClass()); } } public final T convertValue(Object value) { validateValue(value); T result = (T) valueType.cast(value); return result; } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/Base64Url.java
package com.aliyun.core.utils; import java.nio.charset.StandardCharsets; import java.util.Arrays; public final class Base64Url { private final byte[] bytes; public Base64Url(String string) { if (string == null) { this.bytes = null; } else { string = unquote(string); this.bytes = string.getBytes(StandardCharsets.UTF_8); } } public Base64Url(byte[] bytes) { this.bytes = unquote(bytes); } private static byte[] unquote(byte[] bytes) { if (bytes != null && bytes.length > 1) { bytes = unquote(new String(bytes, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); } return bytes; } private static String unquote(String string) { if (string != null && !string.isEmpty()) { final char firstCharacter = string.charAt(0); if (firstCharacter == '\"' || firstCharacter == '\'') { final int base64UrlStringLength = string.length(); final char lastCharacter = string.charAt(base64UrlStringLength - 1); if (lastCharacter == firstCharacter) { string = string.substring(1, base64UrlStringLength - 1); } } } return string; } public static Base64Url encode(byte[] bytes) { if (bytes == null) { return new Base64Url((String) null); } else { return new Base64Url(Base64Util.encodeURLWithoutPadding(bytes)); } } public byte[] encodedBytes() { return bytes; } public byte[] decodedBytes() { if (this.bytes == null) { return null; } return Base64Util.decodeURL(bytes); } @Override public String toString() { return bytes == null ? "" : new String(bytes, StandardCharsets.UTF_8); } @Override public int hashCode() { return Arrays.hashCode(bytes); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Base64Url)) { return false; } Base64Url rhs = (Base64Url) obj; return Arrays.equals(this.bytes, rhs.encodedBytes()); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/Base64Util.java
package com.aliyun.core.utils; import java.util.Base64; public final class Base64Util { public static byte[] encode(byte[] src) { return src == null ? null : Base64.getEncoder().encode(src); } public static byte[] encodeURLWithoutPadding(byte[] src) { return src == null ? null : Base64.getUrlEncoder().withoutPadding().encode(src); } public static String encodeToString(byte[] src) { return src == null ? null : Base64.getEncoder().encodeToString(src); } public static byte[] decode(byte[] encoded) { return encoded == null ? null : Base64.getDecoder().decode(encoded); } /** * Decodes a byte array in base64 URL format. */ public static byte[] decodeURL(byte[] src) { return src == null ? null : Base64.getUrlDecoder().decode(src); } /** * Decodes a base64 encoded string. */ public static byte[] decodeString(String encoded) { return encoded == null ? null : Base64.getDecoder().decode(encoded); } // Private Ctr private Base64Util() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/BaseUtils.java
package com.aliyun.core.utils; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.util.*; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public final class BaseUtils { private static final String COMMA = ","; private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=([\\S]+)\\b", Pattern.CASE_INSENSITIVE); private BaseUtils() { // Exists only to defeat instantiation. } public static byte[] clone(byte[] source) { if (source == null) { return null; } byte[] copy = new byte[source.length]; System.arraycopy(source, 0, copy, 0, source.length); return copy; } public static int[] clone(int[] source) { if (source == null) { return null; } int[] copy = new int[source.length]; System.arraycopy(source, 0, copy, 0, source.length); return copy; } public static <T> T[] clone(T[] source) { if (source == null) { return null; } return Arrays.copyOf(source, source.length); } public static boolean isNullOrEmpty(Object[] array) { return array == null || array.length == 0; } public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } public static boolean isNullOrEmpty(Map<?, ?> map) { return map == null || map.isEmpty(); } public static <T> String arrayToString(T[] array, Function<T, String> mapper) { if (isNullOrEmpty(array)) { return null; } return Arrays.stream(array).map(mapper).collect(Collectors.joining(COMMA)); } public static <T> T findFirstOfType(Object[] args, Class<T> clazz) { if (isNullOrEmpty(args)) { return null; } for (Object arg : args) { if (clazz.isInstance(arg)) { return clazz.cast(arg); } } return null; } public static String bomAwareToString(byte[] bytes, String contentType) { if (bytes == null) { return null; } /* * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't * present or invalid fallback to 'UTF-8' for the default charset. */ if (!StringUtils.isEmpty(contentType)) { try { Matcher charsetMatcher = CHARSET_PATTERN.matcher(contentType); if (charsetMatcher.find()) { return new String(bytes, Charset.forName(charsetMatcher.group(1))); } else { return new String(bytes, StandardCharsets.UTF_8); } } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) { return new String(bytes, StandardCharsets.UTF_8); } } else { return new String(bytes, StandardCharsets.UTF_8); } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/BinaryUtils.java
package com.aliyun.core.utils; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; public final class BinaryUtils { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private BinaryUtils() { } public static String toBase64(byte[] data) { return data == null ? null : new String(toBase64Bytes(data), StandardCharsets.UTF_8); } public static byte[] toBase64Bytes(byte[] data) { return data == null ? null : Base64.getEncoder().encode(data); } public static byte[] fromBase64(String b64Data) { return b64Data == null ? null : Base64.getDecoder().decode(b64Data); } public static byte[] fromBase64Bytes(byte[] b64Data) { return b64Data == null ? null : Base64.getDecoder().decode(b64Data); } public static ByteArrayInputStream toStream(ByteBuffer byteBuffer) { if (byteBuffer == null) { return new ByteArrayInputStream(new byte[0]); } return new ByteArrayInputStream(copyBytesFrom(byteBuffer)); } public static byte[] copyAllBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (bb.hasArray()) { return Arrays.copyOfRange( bb.array(), bb.arrayOffset(), bb.arrayOffset() + bb.limit()); } ByteBuffer copy = bb.asReadOnlyBuffer(); copy.rewind(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } public static byte[] copyBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (bb.hasArray()) { return Arrays.copyOfRange( bb.array(), bb.arrayOffset() + bb.position(), bb.arrayOffset() + bb.limit()); } byte[] dst = new byte[bb.remaining()]; bb.asReadOnlyBuffer().get(dst); return dst; } public static byte[] calculateMd5(byte[] binaryData) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 algorithm not found."); } messageDigest.update(binaryData); return messageDigest.digest(); } public static String encodeMD5(byte[] binaryData) { byte[] md5Bytes = calculateMd5(binaryData); int len = md5Bytes.length; char buf[] = new char[len * 2]; for (int i = 0; i < len; i++) { buf[i * 2] = HEX_DIGITS[(md5Bytes[i] >>> 4) & 0x0f]; buf[i * 2 + 1] = HEX_DIGITS[md5Bytes[i] & 0x0f]; } return new String(buf); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/BufferFutureUtil.java
//package com.aliyun.core.utils; // //import com.aliyun.core.http.HttpHeaders; //import com.aliyun.core.logging.ClientLogger; //import org.reactivestreams.Subscriber; //import org.reactivestreams.Subscription; // //import java.io.IOException; //import java.io.InputStream; //import java.lang.reflect.Type; //import java.nio.ByteBuffer; //import java.nio.channels.AsynchronousFileChannel; //import java.nio.channels.CompletionHandler; //import java.util.Collections; //import java.util.Map; //import java.util.Map.Entry; //import java.util.Objects; //import java.util.concurrent.CompletableFuture; //import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; //import java.util.concurrent.atomic.AtomicLongFieldUpdater; //import java.util.function.Function; //import java.util.stream.Collectors; // //public final class BufferFutureUtil { // private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // // public static boolean isFutureByteBuffer(Type entityType) { // if (TypeUtil.isTypeOrSubTypeOf(entityType, CompletableFuture.class)) { // final Type innerType = TypeUtil.getTypeArguments(entityType)[0]; // return TypeUtil.isTypeOrSubTypeOf(innerType, ByteBuffer.class); // } // return false; // } // // public static CompletableFuture<byte[]> collectBytesInByteBufferStream(CompletableFuture<ByteBuffer> stream) { // // return stream.collect(ByteBufferCollector::new, ByteBufferCollector::write) // .map(ByteBufferCollector::toByteArray); // } // // public static CompletableFuture<byte[]> collectBytesInByteBufferStream(CompletableFuture<ByteBuffer> stream, int sizeHint) { // return stream.collect(() -> new ByteBufferCollector(sizeHint), ByteBufferCollector::write) // .map(ByteBufferCollector::toByteArray); // } // // public static CompletableFuture<byte[]> collectBytesFromNetworkResponse(CompletableFuture<ByteBuffer> stream, HttpHeaders headers) { // Objects.requireNonNull(headers, "'headers' cannot be null."); // // String contentLengthHeader = headers.getValue("Content-Length"); // // if (contentLengthHeader == null) { // return BufferFutureUtil.collectBytesInByteBufferStream(stream); // } else { // try { // int contentLength = Integer.parseInt(contentLengthHeader); // if (contentLength > 0) { // return BufferFutureUtil.collectBytesInByteBufferStream(stream, contentLength); // } else { // return CompletableFuture.completedFuture(EMPTY_BYTE_ARRAY); // } // } catch (NumberFormatException ex) { // return BufferFutureUtil.collectBytesInByteBufferStream(stream); // } // } // } // // public static byte[] byteBufferToArray(ByteBuffer byteBuffer) { // int length = byteBuffer.remaining(); // byte[] byteArray = new byte[length]; // byteBuffer.get(byteArray); // return byteArray; // } // // public static CompletableFuture<ByteBuffer> toByteBuffer(InputStream inputStream) { // return toByteBuffer(inputStream, 4096); // } // // public static CompletableFuture<ByteBuffer> toByteBuffer(InputStream inputStream, int chunkSize) { // if (chunkSize <= 0) { // throw new IllegalArgumentException("'chunkSize' must be greater than 0."); // } // // if (inputStream == null) { // return CompletableFuture.completedFuture(null); // } // // return Flux.<ByteBuffer, InputStream>generate(() -> inputStream, (stream, sink) -> { // byte[] buffer = new byte[chunkSize]; // // try { // int offset = 0; // // while (offset < chunkSize) { // int readCount = inputStream.read(buffer, offset, chunkSize - offset); // // // We have finished reading the stream, trigger onComplete. // if (readCount == -1) { // // If there were bytes read before reaching the end emit the buffer before completing. // if (offset > 0) { // sink.next(ByteBuffer.wrap(buffer, 0, offset)); // } // sink.complete(); // return stream; // } // // offset += readCount; // } // // sink.next(ByteBuffer.wrap(buffer)); // } catch (IOException ex) { // sink.error(ex); // } // // return stream; // }).filter(ByteBuffer::hasRemaining); // } // // public static CompletableFuture<Void> writeFile(CompletableFuture<ByteBuffer> content, AsynchronousFileChannel outFile) { // return writeFile(content, outFile, 0); // } // // public static CompletableFuture<Void> writeFile(CompletableFuture<ByteBuffer> content, AsynchronousFileChannel outFile, long position) { // return CompletableFuture.supplyAsync(new Subscriber<ByteBuffer>() { // volatile boolean isWriting = false; // volatile boolean isCompleted = false; // volatile Subscription subscription; // volatile long pos = position; // // @Override // public void onSubscribe(Subscription s) { // subscription = s; // s.request(1); // } // // @Override // public void onNext(ByteBuffer bytes) { // isWriting = true; // outFile.write(bytes, pos, null, onWriteCompleted); // } // // // final CompletionHandler<Integer, Object> onWriteCompleted = new CompletionHandler<Integer, Object>() { // @Override // public void completed(Integer bytesWritten, Object attachment) { // isWriting = false; // if (isCompleted) { // return; // } // //noinspection NonAtomicOperationOnVolatileField // pos += bytesWritten; // subscription.request(1); // } // // @Override // public void failed(Throwable exc, Object attachment) { // subscription.cancel(); // return; // } // }; // // @Override // public void onError(Throwable throwable) { // subscription.cancel(); // return; // } // // @Override // public void onComplete() { // isCompleted = true; // if (!isWriting) { // return; // } // } // })); // } // // public static CompletableFuture<ByteBuffer> readFile(AsynchronousFileChannel fileChannel, int chunkSize, long offset, // long length) { // return new FileReadFlux(fileChannel, chunkSize, offset, length); // } // // public static CompletableFuture<ByteBuffer> readFile(AsynchronousFileChannel fileChannel, long offset, long length) { // return readFile(fileChannel, DEFAULT_CHUNK_SIZE, offset, length); // } // // public static CompletableFuture<ByteBuffer> readFile(AsynchronousFileChannel fileChannel) { // try { // long size = fileChannel.size(); // return readFile(fileChannel, DEFAULT_CHUNK_SIZE, 0, size); // } catch (IOException e) { // return Flux.error(new RuntimeException("Failed to read the file.", e)); // } // } // // private static final int DEFAULT_CHUNK_SIZE = 1024 * 64; // // private static final class FileReadFlux extends CompletableFuture<ByteBuffer> { // private final AsynchronousFileChannel fileChannel; // private final int chunkSize; // private final long offset; // private final long length; // // FileReadFlux(AsynchronousFileChannel fileChannel, int chunkSize, long offset, long length) { // this.fileChannel = fileChannel; // this.chunkSize = chunkSize; // this.offset = offset; // this.length = length; // } // // @Override // public void subscribe(CoreSubscriber<? super ByteBuffer> actual) { // FileReadSubscription subscription = // new FileReadSubscription(actual, fileChannel, chunkSize, offset, length); // actual.onSubscribe(subscription); // } // // static final class FileReadSubscription implements Subscription, CompletionHandler<Integer, ByteBuffer> { // private static final int NOT_SET = -1; // private static final long serialVersionUID = -6831808726875304256L; // private final Subscriber<? super ByteBuffer> subscriber; // private volatile long position; // private final AsynchronousFileChannel fileChannel; // private final int chunkSize; // private final long offset; // private final long length; // private volatile boolean done; // private Throwable error; // private volatile ByteBuffer next; // private volatile boolean cancelled; // volatile int wip; // @SuppressWarnings("rawtypes") // static final AtomicIntegerFieldUpdater<FileReadSubscription> WIP = // AtomicIntegerFieldUpdater.newUpdater(FileReadSubscription.class, "wip"); // volatile long requested; // @SuppressWarnings("rawtypes") // static final AtomicLongFieldUpdater<FileReadSubscription> REQUESTED = // AtomicLongFieldUpdater.newUpdater(FileReadSubscription.class, "requested"); // // FileReadSubscription(Subscriber<? super ByteBuffer> subscriber, AsynchronousFileChannel fileChannel, // int chunkSize, long offset, long length) { // this.subscriber = subscriber; // this.fileChannel = fileChannel; // this.chunkSize = chunkSize; // this.offset = offset; // this.length = length; // this.position = NOT_SET; // } // // @Override // public void request(long n) { // if (Operators.validate(n)) { // Operators.addCap(REQUESTED, this, n); // drain(); // } // } // // @Override // public void cancel() { // this.cancelled = true; // } // // @Override // public void completed(Integer bytesRead, ByteBuffer buffer) { // if (!cancelled) { // if (bytesRead == -1) { // done = true; // } else { // // use local variable to perform fewer volatile reads // long pos = position; // int bytesWanted = Math.min(bytesRead, maxRequired(pos)); // long position2 = pos + bytesWanted; // //noinspection NonAtomicOperationOnVolatileField // position = position2; // buffer.position(bytesWanted); // buffer.flip(); // next = buffer; // if (position2 >= offset + length) { // done = true; // } // } // drain(); // } // } // // @Override // public void failed(Throwable exc, ByteBuffer attachment) { // if (!cancelled) { // // must set error before setting done to true // // so that is visible in drain loop // error = exc; // done = true; // drain(); // } // } // // //endregion // // private void drain() { // if (WIP.getAndIncrement(this) != 0) { // return; // } // // on first drain (first request) we initiate the first read // if (position == NOT_SET) { // position = offset; // doRead(); // } // int missed = 1; // while (true) { // if (cancelled) { // return; // } // if (REQUESTED.get(this) > 0) { // boolean emitted = false; // // read d before next to avoid race // boolean d = done; // ByteBuffer bb = next; // if (bb != null) { // next = null; // subscriber.onNext(bb); // emitted = true; // } // if (d) { // if (error != null) { // subscriber.onError(error); // } else { // subscriber.onComplete(); // } // // // exit without reducing wip so that further drains will be NOOP // return; // } // if (emitted) { // // do this after checking d to avoid calling read // // when done // Operators.produced(REQUESTED, this, 1); // // // doRead(); // } // } // missed = WIP.addAndGet(this, -missed); // if (missed == 0) { // return; // } // } // } // // private void doRead() { // // use local variable to limit volatile reads // long pos = position; // ByteBuffer innerBuf = ByteBuffer.allocate(Math.min(chunkSize, maxRequired(pos))); // fileChannel.read(innerBuf, pos, innerBuf, this); // } // // private int maxRequired(long pos) { // long maxRequired = offset + length - pos; // if (maxRequired <= 0) { // return 0; // } else { // int m = (int) (maxRequired); // // support really large files by checking for overflow // if (m < 0) { // return Integer.MAX_VALUE; // } else { // return m; // } // } // } // } // } // // private BufferFutureUtil() { // } //}
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/ByteBufferCollector.java
package com.aliyun.core.utils; import com.aliyun.core.logging.ClientLogger; import java.nio.ByteBuffer; import java.util.Arrays; public final class ByteBufferCollector { private static final int DEFAULT_INITIAL_SIZE = 1024; private static final String INVALID_INITIAL_SIZE = "'initialSize' cannot be equal to or less than 0."; private static final String REQUESTED_BUFFER_INVALID = "Required capacity is greater than Integer.MAX_VALUE."; private final ClientLogger logger = new ClientLogger(ByteBufferCollector.class); private byte[] buffer; private int position; public ByteBufferCollector() { this(DEFAULT_INITIAL_SIZE); } public ByteBufferCollector(int initialSize) { if (initialSize <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_INITIAL_SIZE)); } this.buffer = new byte[initialSize]; this.position = 0; } public synchronized void write(ByteBuffer byteBuffer) { // Null buffer. if (byteBuffer == null) { return; } int remaining = byteBuffer.remaining(); // Nothing to write. if (remaining == 0) { return; } ensureCapacity(remaining); byteBuffer.get(buffer, position, remaining); position += remaining; } public synchronized byte[] toByteArray() { return Arrays.copyOf(buffer, position); } private void ensureCapacity(int byteBufferRemaining) throws OutOfMemoryError { int currentCapacity = buffer.length; int requiredCapacity = position + byteBufferRemaining; if (((position ^ requiredCapacity) & (byteBufferRemaining ^ requiredCapacity)) < 0) { throw logger.logExceptionAsError(new IllegalStateException(REQUESTED_BUFFER_INVALID)); } if (currentCapacity >= requiredCapacity) { return; } int proposedNewCapacity = currentCapacity << 1; if ((proposedNewCapacity - requiredCapacity) < 0) { proposedNewCapacity = requiredCapacity; } if (proposedNewCapacity < 0) { proposedNewCapacity = Integer.MAX_VALUE - 8; } buffer = Arrays.copyOf(buffer, proposedNewCapacity); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/ClientOptions.java
package com.aliyun.core.utils; import com.aliyun.core.logging.ClientLogger; import com.aliyun.core.http.Header; import java.util.Collections; public class ClientOptions { private static final int MAX_APPLICATION_ID_LENGTH = 24; private static final String INVALID_APPLICATION_ID_LENGTH = "'productId' length cannot be greater than " + MAX_APPLICATION_ID_LENGTH; private static final String INVALID_APPLICATION_ID_SPACE = "'productId' cannot contain spaces."; private final ClientLogger logger = new ClientLogger(ClientOptions.class); private Iterable<Header> headers; private String productId; public String getProductId() { return productId; } public ClientOptions setProductId(String productId) { if (StringUtils.isEmpty(productId)) { this.productId = productId; } else if (productId.length() > MAX_APPLICATION_ID_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_LENGTH)); } else if (productId.contains(" ")) { throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE)); } else { this.productId = productId; } return this; } public ClientOptions setHeaders(Iterable<Header> headers) { this.headers = headers; return this; } public Iterable<Header> getHeaders() { if (headers == null) { return Collections.emptyList(); } return headers; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/Configuration.java
package com.aliyun.core.utils; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; public class Configuration implements Cloneable { public static final String PROPERTY_HTTP_PROXY = "HTTP_PROXY"; public static final String PROPERTY_HTTPS_PROXY = "HTTPS_PROXY"; public static final String PROPERTY_NO_PROXY = "NO_PROXY"; public static final String PROPERTY_ALIBABA_CLOUD_LOG_LEVEL = "ALIBABA_CLOUD_SDK_LOG_LEVEL"; private static final String[] DEFAULT_CONFIGURATIONS = { PROPERTY_HTTP_PROXY, PROPERTY_HTTPS_PROXY, PROPERTY_NO_PROXY, PROPERTY_ALIBABA_CLOUD_LOG_LEVEL, }; /* * Gets the global configuration shared by all client libraries. */ private static final Configuration GLOBAL_CONFIGURATION = new Configuration(); public static final Configuration NONE = new NoopConfiguration(); private final ConcurrentMap<String, String> configurations; public Configuration() { this.configurations = new ConcurrentHashMap<>(); loadBaseConfiguration(this); } private Configuration(ConcurrentMap<String, String> configurations) { this.configurations = new ConcurrentHashMap<>(configurations); } public static Configuration getGlobalConfiguration() { return GLOBAL_CONFIGURATION; } public String get(String name) { return getOrLoad(name); } public <T> T get(String name, T defaultValue) { return convertOrDefault(getOrLoad(name), defaultValue); } public <T> T get(String name, Function<String, T> converter) { String value = getOrLoad(name); if (StringUtils.isEmpty(value)) { return null; } return converter.apply(value); } private String getOrLoad(String name) { String value = configurations.get(name); if (value != null) { return value; } value = load(name); if (value != null) { configurations.put(name, value); return value; } return null; } private String load(String name) { String value = loadFromProperties(name); if (value != null) { return value; } return loadFromEnvironment(name); } String loadFromEnvironment(String name) { return System.getenv(name); } String loadFromProperties(String name) { return System.getProperty(name); } public Configuration put(String name, String value) { configurations.put(name, value); return this; } public String remove(String name) { return configurations.remove(name); } public boolean contains(String name) { return configurations.containsKey(name); } @SuppressWarnings("CloneDoesntCallSuperClone") public Configuration clone() { return new Configuration(configurations); } @SuppressWarnings("unchecked") private static <T> T convertOrDefault(String value, T defaultValue) { if (StringUtils.isEmpty(value)) { return defaultValue; } Object convertedValue; if (defaultValue instanceof Byte) { convertedValue = Byte.parseByte(value); } else if (defaultValue instanceof Short) { convertedValue = Short.parseShort(value); } else if (defaultValue instanceof Integer) { convertedValue = Integer.parseInt(value); } else if (defaultValue instanceof Long) { convertedValue = Long.parseLong(value); } else if (defaultValue instanceof Float) { convertedValue = Float.parseFloat(value); } else if (defaultValue instanceof Double) { convertedValue = Double.parseDouble(value); } else if (defaultValue instanceof Boolean) { convertedValue = Boolean.parseBoolean(value); } else { convertedValue = value; } return (T) convertedValue; } private void loadBaseConfiguration(Configuration configuration) { for (String config : DEFAULT_CONFIGURATIONS) { String value = load(config); if (value != null) { configuration.put(config, value); } } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/Context.java
package com.aliyun.core.utils; import com.aliyun.core.logging.ClientLogger; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; public class Context { private final ClientLogger logger = new ClientLogger(Context.class); public static final Context NONE = new Context(null, null, null); private final Context parent; private final Object key; private final Object value; public Context(Object key, Object value) { this.parent = null; this.key = Objects.requireNonNull(key, "'key' cannot be null."); this.value = value; } private Context(Context parent, Object key, Object value) { this.parent = parent; this.key = key; this.value = value; } public Context addData(Object key, Object value) { if (key == null) { throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null")); } return new Context(this, key, value); } public static Context of(Map<Object, Object> keyValues) { if (StringUtils.isEmpty(keyValues)) { throw new IllegalArgumentException("Key value map cannot be null or empty"); } Context context = null; for (Map.Entry<Object, Object> entry : keyValues.entrySet()) { if (context == null) { context = new Context(entry.getKey(), entry.getValue()); } else { context = context.addData(entry.getKey(), entry.getValue()); } } return context; } public Optional<Object> getData(Object key) { if (key == null) { throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null")); } for (Context c = this; c != null; c = c.parent) { if (key.equals(c.key)) { return Optional.of(c.value); } } return Optional.empty(); } public Map<Object, Object> getValues() { return getValuesHelper(new HashMap<>()); } private Map<Object, Object> getValuesHelper(Map<Object, Object> values) { if (key != null) { values.putIfAbsent(key, value); } return (parent == null) ? values : parent.getValuesHelper(values); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/Copyable.java
package com.aliyun.core.utils; public interface Copyable<T> { T copy(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/DateUtil.java
package com.aliyun.core.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.SimpleTimeZone; public class DateUtil { // RFC 822 Date Format private static final String RFC822_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; // ISO 8601 format private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // Alternate ISO 8601 format without fractional seconds private static final String ALTERNATIVE_ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Formats Date to GMT string. */ public static String formatRfc822Date(Date date) { return getRfc822DateFormat().format(date); } /** * Parses a GMT-format string. */ public static Date parseRfc822Date(String dateString) throws ParseException { return getRfc822DateFormat().parse(dateString); } private static DateFormat getRfc822DateFormat() { SimpleDateFormat rfc822DateFormat = new SimpleDateFormat(RFC822_DATE_FORMAT, Locale.US); rfc822DateFormat.setTimeZone(new SimpleTimeZone(0, "GMT")); return rfc822DateFormat; } public static String formatIso8601Date(Date date) { return getIso8601DateFormat().format(date); } public static String formatAlternativeIso8601Date(Date date) { return getAlternativeIso8601DateFormat().format(date); } /** * Parse a date string in the format of ISO 8601. * * @param dateString * @return a {@link Date} instance. * @throws ParseException */ public static Date parseIso8601Date(String dateString) throws ParseException { try { return getIso8601DateFormat().parse(dateString); } catch (ParseException e) { return getAlternativeIso8601DateFormat().parse(dateString); } } private static DateFormat getIso8601DateFormat() { SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df; } private static DateFormat getAlternativeIso8601DateFormat() { SimpleDateFormat df = new SimpleDateFormat(ALTERNATIVE_ISO8601_DATE_FORMAT, Locale.US); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/EncodeUtil.java
package com.aliyun.core.utils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class EncodeUtil { private static String URL_ENCODING = "UTF-8"; public static String HMAC_SHA256 = "ACS3-HMAC-SHA256"; public static String percentEncode(String value) throws UnsupportedEncodingException { return value != null ? URLEncoder.encode(value, URL_ENCODING).replace("+", "%20") .replace("*", "%2A").replace("%7E", "~") : null; } public static String encode(String value) throws UnsupportedEncodingException { return URLEncoder.encode(value, URL_ENCODING).replace("+", "%20"); } public static String hexEncode(byte[] raw) { if (raw == null) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < raw.length; i++) { String hex = Integer.toHexString(raw[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex); } return sb.toString(); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/FunctionalUtils.java
package com.aliyun.core.utils; import org.slf4j.Logger; import java.io.IOException; import java.io.UncheckedIOException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public final class FunctionalUtils { private FunctionalUtils() { } public static void runAndLogError(Logger log, String errorMsg, UnsafeRunnable runnable) { try { runnable.run(); } catch (Exception e) { log.error(errorMsg, e); } } public static <T> Consumer<T> noOpConsumer() { return ignored -> { }; } public static Runnable noOpRunnable() { return () -> { }; } public static <I> Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer) { return (input) -> { try { unsafeConsumer.accept(input); } catch (Exception e) { throw asRuntimeException(e); } }; } public static <T, R> Function<T, R> safeFunction(UnsafeFunction<T, R> unsafeFunction) { return t -> { try { return unsafeFunction.apply(t); } catch (Exception e) { throw asRuntimeException(e); } }; } public static <T> Supplier<T> safeSupplier(UnsafeSupplier<T> unsafeSupplier) { return () -> { try { return unsafeSupplier.get(); } catch (Exception e) { throw asRuntimeException(e); } }; } public static Runnable safeRunnable(UnsafeRunnable unsafeRunnable) { return () -> { try { unsafeRunnable.run(); } catch (Exception e) { throw asRuntimeException(e); } }; } public static <I, O> Function<I, O> toFunction(Supplier<O> supplier) { return ignore -> supplier.get(); } public static <T> T invokeSafely(UnsafeSupplier<T> unsafeSupplier) { return safeSupplier(unsafeSupplier).get(); } public static void invokeSafely(UnsafeRunnable unsafeRunnable) { safeRunnable(unsafeRunnable).run(); } public interface UnsafeConsumer<I> { void accept(I input) throws Exception; } public interface UnsafeFunction<T, R> { R apply(T t) throws Exception; } public interface UnsafeSupplier<T> { T get() throws Exception; } public interface UnsafeRunnable { void run() throws Exception; } private static RuntimeException asRuntimeException(Exception exception) { if (exception instanceof RuntimeException) { return (RuntimeException) exception; } if (exception instanceof IOException) { return new UncheckedIOException((IOException) exception); } if (exception instanceof InterruptedException) { Thread.currentThread().interrupt(); } return new RuntimeException(exception); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/HttpClientOptions.java
package com.aliyun.core.utils; import com.aliyun.core.http.Header; import com.aliyun.core.http.ProxyOptions; import java.time.Duration; public final class HttpClientOptions extends ClientOptions { private static final Duration MINIMUM_TIMEOUT = Duration.ofSeconds(5); private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); private static final Duration NO_TIMEOUT = Duration.ZERO; private ProxyOptions proxyOptions; private Configuration configuration; private Duration writeTimeout; private Duration responseTimeout; private Duration readTimeout; @Override public HttpClientOptions setProductId(String productId) { super.setProductId(productId); return this; } @Override public HttpClientOptions setHeaders(Iterable<Header> headers) { super.setHeaders(headers); return this; } public HttpClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } public ProxyOptions getProxyOptions() { return proxyOptions; } public HttpClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public Configuration getConfiguration() { return configuration; } public HttpClientOptions setWriteTimeout(Duration writeTimeout) { this.writeTimeout = writeTimeout; return this; } public Duration getWriteTimeout() { return getTimeout(writeTimeout); } public HttpClientOptions responseTimeout(Duration responseTimeout) { this.responseTimeout = responseTimeout; return this; } public Duration getResponseTimeout() { return getTimeout(responseTimeout); } public HttpClientOptions readTimeout(Duration readTimeout) { this.readTimeout = readTimeout; return this; } public Duration getReadTimeout() { return getTimeout(readTimeout); } private static Duration getTimeout(Duration timeout) { // Timeout is null, use the 60 second default. if (timeout == null) { return DEFAULT_TIMEOUT; } // Timeout is less than or equal to zero, return no timeout. if (timeout.isZero() || timeout.isNegative()) { return NO_TIMEOUT; } // Return the maximum of the timeout period and the minimum allowed timeout period. return timeout.compareTo(MINIMUM_TIMEOUT) > 0 ? timeout : MINIMUM_TIMEOUT; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/IOUtils.java
package com.aliyun.core.utils; import com.aliyun.core.logging.ClientLogger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public class IOUtils { private static final ClientLogger DEFAULT_LOGGER = new ClientLogger(IOUtils.class); private static final int BUFFER_SIZE = 1024 * 4; private IOUtils() { } /** * Reads and returns the rest of the given input stream as a byte array. * Caller is responsible for closing the given input stream. */ public static byte[] toByteArray(InputStream is) throws IOException { try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { byte[] b = new byte[BUFFER_SIZE]; int n = 0; while ((n = is.read(b)) != -1) { output.write(b, 0, n); } return output.toByteArray(); } } /** * Reads and returns the rest of the given input stream as a string. * Caller is responsible for closing the given input stream. */ public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } /** * Closes the given Closeable quietly. * * @param is the given closeable * @param log logger used to log any failure should the close fail */ public static void closeQuietly(AutoCloseable is, ClientLogger log) { if (is != null) { try { is.close(); } catch (Exception ex) { ClientLogger logger = log == null ? DEFAULT_LOGGER : log; logger.verbose("Ignore failure in closing the Closeable", ex); } } } /** * Closes the given Closeable quietly. * * @param maybeCloseable the given closeable * @param log logger used to log any failure should the close fail */ public static void closeIfCloseable(Object maybeCloseable, ClientLogger log) { if (maybeCloseable instanceof AutoCloseable) { closeQuietly((AutoCloseable) maybeCloseable, log); } } /** * Copies all bytes from the given input stream to the given output stream. * Caller is responsible for closing the streams. * * @throws IOException * if there is any IO exception during read or write. */ public static long copy(InputStream in, OutputStream out) throws IOException { return copy(in, out, Long.MAX_VALUE); } /** * Copies all bytes from the given input stream to the given output stream. * Caller is responsible for closing the streams. * * @throws IOException if there is any IO exception during read or write or the read limit is exceeded. */ public static long copy(InputStream in, OutputStream out, long readLimit) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; long count = 0; int n = 0; while ((n = in.read(buf)) > -1) { out.write(buf, 0, n); count += n; if (count >= readLimit) { throw new IOException("Read limit exceeded: " + readLimit); } } return count; } /** * Read all remaining data in the stream. * * @param in InputStream to read. */ public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { // Do nothing. } } catch (IOException ignored) { // Stream may be self closed by HTTP client so we ignore any failures. } } /** * If the stream supports marking, marks the stream at the current position with a {@code readLimit} value of * 128 KiB. * * @param s The stream. */ public static void markStreamWithMaxReadLimit(InputStream s) { if (s.markSupported()) { s.mark(1 << 17); } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/IterableStream.java
package com.aliyun.core.utils; import java.util.ArrayList; import java.util.Iterator; import java.util.Objects; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class IterableStream<T> implements Iterable<T> { private static final int DEFAULT_BATCH_SIZE = 1; private static final IterableStream<Object> EMPTY = new IterableStream<>(new ArrayList<>()); private final Iterable<T> iterable; public IterableStream(Iterable<T> iterable) { this.iterable = Objects.requireNonNull(iterable, "'iterable' cannot be null."); } public Stream<T> stream() { return StreamSupport.stream(iterable.spliterator(), false); } @Override public Iterator<T> iterator() { return iterable.iterator(); } @SuppressWarnings("unchecked") public static <T> IterableStream<T> of(Iterable<T> iterable) { if (iterable == null) { return (IterableStream<T>) EMPTY; } else { return new IterableStream<T>(iterable); } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/MapTypeAdapter.java
package com.aliyun.core.utils; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class MapTypeAdapter extends TypeAdapter<Object> { private final TypeAdapter<Object> delegate = new Gson().getAdapter(Object.class); @Override public Object read(JsonReader in) throws IOException { JsonToken token = in.peek(); switch (token) { case BEGIN_ARRAY: List<Object> list = new ArrayList<Object>(); in.beginArray(); while (in.hasNext()) { list.add(read(in)); } in.endArray(); return list; case BEGIN_OBJECT: Map<String, Object> map = new LinkedTreeMap<String, Object>(); in.beginObject(); while (in.hasNext()) { map.put(in.nextName(), read(in)); } in.endObject(); return map; case STRING: return in.nextString(); case NUMBER: /** * 改写数字的处理逻辑,将数字值分为整型与浮点型。 */ String s1 = in.nextString(); if (s1.contains(".")) { return Double.parseDouble(s1); } else { return Long.parseLong(s1); } case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; default: throw new IllegalStateException(); } } @Override public void write(JsonWriter out, Object value) throws IOException { delegate.write(out, value); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/MapUtils.java
package com.aliyun.core.utils; import java.util.HashMap; import java.util.Map; import java.util.Set; public class MapUtils { /** * concat two same map to new one * * @param m1 first map * @param m2 second map * @return */ public static <T> Map<String, T> concat(Map<String, T> m1, Map<String, T> m2) { Map<String, T> newMap = new HashMap<>(); newMap.putAll(m1); newMap.putAll(m2); return newMap; } public static <T> Map<String, T> merge(Class<T> t, Map<String, ?>... maps) { Map<String, T> out = new HashMap<String, T>(); for (int i = 0; i < maps.length; i++) { Map<String, ?> map = maps[i]; if (null == map) { continue; } Set<? extends Map.Entry<String, ?>> entries = map.entrySet(); for (Map.Entry<String, ?> entry : entries) { if (null != entry.getValue()) { out.put(entry.getKey(), (T) entry.getValue()); } } } return out; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/NoopConfiguration.java
package com.aliyun.core.utils; import java.util.function.Function; class NoopConfiguration extends Configuration { @Override public String get(String name) { return null; } @Override public <T> T get(String name, T defaultValue) { return defaultValue; } @Override public <T> T get(String name, Function<String, T> converter) { return null; } @Override public NoopConfiguration put(String name, String value) { return this; } @Override public String remove(String name) { return null; } @Override public boolean contains(String name) { return false; } @Override @SuppressWarnings("CloneDoesntCallSuperClone") public NoopConfiguration clone() { return new NoopConfiguration(); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/ParseUtil.java
package com.aliyun.core.utils; import com.aliyun.core.exception.AliyunException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; import org.dom4j.DocumentException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.*; public class ParseUtil { /** * Parse it by JSON format * * @return the parsed result */ public static Object parseJSON(String json) { Gson gson = new GsonBuilder() .registerTypeAdapter(new TypeToken<Map<String, Object>>() { }.getType(), new MapTypeAdapter()).create(); JsonElement jsonElement = gson.fromJson(json, JsonElement.class); return jsonElement.isJsonArray() ? gson.fromJson(json, List.class) : gson.fromJson(json, new TypeToken<Map<String, Object>>() { }.getType()); } /** * Read data from a readable stream, and compose it to a bytes * * @param stream the readable stream * @return the bytes result */ public static byte[] readAsBytes(InputStream stream) { try { if (null == stream) { return new byte[]{}; } else { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; while (true) { int read = stream.read(buff); if (read == -1) { return os.toByteArray(); } os.write(buff, 0, read); } } } catch (Exception e) { throw new AliyunException(e.getMessage(), e); } finally { if (null != stream) { try { stream.close(); } catch (IOException e) { throw new AliyunException(e.getMessage(), e); } } } } /** * Read data from a readable stream, and compose it to a string * * @param stream the readable stream * @return the string result */ public static String readAsString(InputStream stream) { try { return new String(readAsBytes(stream), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AliyunException(e.getMessage(), e); } } /** * Read data from a readable stream, and parse it by JSON format * * @param str the readable stream * @return the parsed result */ public static Object readAsJSON(String str) { // String body = readAsString(stream); try { return parseJSON(str); } catch (Exception exception) { throw new AliyunException("Error: convert to JSON, response is:\n" + str); } } /** * If not set the real, use default value * * @return the return string */ public static String toJSONString(Object object) { if (object instanceof String) { return (String) object; } return new Gson().toJson(object); } public static Map<String, Object> parseXml(String str) throws DocumentException { return XmlUtil.deserializeXml(str); } public static Map<String, Object> readAsXML(String str) { try { return parseXml(str); } catch (Exception exception) { throw new AliyunException("Error: XML convert to MAP, response is:\n" + str); } } public static String toXmlString(Map<String, Object> xmlMap, String rootName) { return XmlUtil.serializeXml(xmlMap, rootName); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/SdkAutoCloseable.java
package com.aliyun.core.utils; // CHECKSTYLE:OFF - This is the only place we're allowed to use AutoCloseable public interface SdkAutoCloseable extends AutoCloseable { // CHECKSTYLE:ON @Override void close(); }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/StringUtils.java
package com.aliyun.core.utils; import com.aliyun.core.exception.AliyunException; import java.io.UncheckedIOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.Objects; /** * Operations on {@link String} that are {@code null} safe. */ public class StringUtils { /** * The empty String {@code ""}. */ public static final String EMPTY = ""; /** * {@code StringUtils} instances should NOT be constructed in * standard programming. */ private StringUtils() { } /** * Checks if a CharSequence is empty ("") or null. * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null */ public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } /** * Checks if a object is empty or null. * * @param object the String.valueOf(object) to check, may be null * @return {@code true} if the String.valueOf(object) is empty or null */ public static boolean isEmpty(Object object) { if (null != object) { return isEmpty(String.valueOf(object)); } return true; } /** * Checks if a CharSequence is empty (""), null or whitespace only. * <p> * Whitespace is defined by {@link Character#isWhitespace(char)}. * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace only */ public static boolean isBlank(final CharSequence cs) { if (cs == null || cs.length() == 0) { return true; } for (int i = 0; i < cs.length(); i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32. * * @param str the String to be trimmed, may be null * @return the trimmed string, {@code null} if null String input */ public static String trim(final String str) { return str == null ? null : str.trim(); } /** * Compares two Strings, returning {@code true} if they represent * equal sequences of characters. * * @param cs1 the first String, may be {@code null} * @param cs2 the second String, may be {@code null} * @return {@code true} if the Strings are equal (case-sensitive), or both {@code null} * @see Object#equals(Object) */ public static boolean equals(final String cs1, final String cs2) { if (cs1 == null || cs2 == null) { return false; } if (cs1.length() != cs2.length()) { return false; } return cs1.equals(cs2); } /** * Join any Strings. * * @param delimiter the delimiter which split two Strings, should not be {@code null} * @param elements the Strings Iterable, should not be {@code null} * @return {@code String} */ public static String join(String delimiter, Iterable<? extends String> elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); StringBuilder stringBuilder = new StringBuilder(); for (String value : elements) { stringBuilder.append(value); stringBuilder.append(delimiter); } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } /** * Gets a substring from the specified String avoiding exceptions. * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means count back from the end of the String by this many characters * @param end the position to end at (exclusive), negative means count back from the end of the String by this many * characters * @return substring from start position to end position, * {@code null} if null String input */ public static String substring(final String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { end = str.length(); } // if start is greater than end, return "" if (start > end) { return EMPTY; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } /** * Converts a String to upper case as per {@link String#toUpperCase()}. * <p> * This uses "ENGLISH" as the locale. * * @param str the String to upper case, may be null * @return the upper cased String, {@code null} if null String input */ public static String upperCase(final String str) { if (str == null) { return null; } return str.toUpperCase(Locale.ENGLISH); } /** * Converts a String to lower case as per {@link String#toLowerCase()}. * <p> * This uses "ENGLISH" as the locale. * * @param str the String to lower case, may be null * @return the lower cased String, {@code null} if null String input */ public static String lowerCase(final String str) { if (str == null) { return null; } return str.toLowerCase(Locale.ENGLISH); } /** * Encode the given bytes as a string using the given charset * * @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded using the * provided charset. */ public static String fromBytes(byte[] bytes, Charset charset) throws UncheckedIOException { try { return charset.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); } catch (CharacterCodingException e) { throw new UncheckedIOException("Cannot encode string.", e); } } /** * Tests if this string starts with the specified prefix ignoring case considerations. * * @param str the string to be tested * @param prefix the prefix * @return true if the string starts with the prefix ignoring case */ public static boolean startsWithIgnoreCase(String str, String prefix) { return str.regionMatches(true, 0, prefix, 0, prefix.length()); } /** * Convert a string to boolean safely (as opposed to the less strict {@link Boolean#parseBoolean(String)}). If a customer * specifies a boolean value it should be "true" or "false" (case insensitive) or an exception will be thrown. */ public static boolean safeStringToBoolean(String value) { if (value.equalsIgnoreCase("true")) { return true; } else if (value.equalsIgnoreCase("false")) { return false; } throw new IllegalArgumentException("Value was defined as '" + value + "', but should be 'false' or 'true'"); } /** * Create a to-string result for the given class name and field map. * * @param className The name of the class being toString. * @param fieldMap The key and value of the field. Value is ignored if null. */ public static String toAliString(String className, Map<String, Object> fieldMap) { StringBuilder result = new StringBuilder(className).append("("); fieldMap.forEach((fieldName, field) -> { if (field != null) { String value; if (field.getClass().isArray()) { if (field instanceof byte[]) { value = ((byte[]) field).length == 0 ? "" : "0x" + new String((byte[]) field); } else { value = Arrays.toString((Object[]) field); } } else { value = String.valueOf(field); } result.append(fieldName).append("=").append(value).append(", "); } }); return result.append(")").toString(); } public static byte[] toBytes(String str) { try { return str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AliyunException(e); } } /** * Convert a bytes to string(utf8) * * @return the return string */ public static String toString(byte[] bytes) { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AliyunException(e); } } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/TypeUtil.java
package com.aliyun.core.utils; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public final class TypeUtil { private static final Map<Type, Type> SUPER_TYPE_MAP = new ConcurrentHashMap<>(); public static List<Class<?>> getAllClasses(Class<?> clazz) { List<Class<?>> types = new ArrayList<>(); while (clazz != null) { types.add(clazz); clazz = clazz.getSuperclass(); } return types; } public static Type[] getTypeArguments(Type type) { if (!(type instanceof ParameterizedType)) { return new Type[0]; } return ((ParameterizedType) type).getActualTypeArguments(); } public static Type getTypeArgument(Type type) { if (!(type instanceof ParameterizedType)) { return null; } return ((ParameterizedType) type).getActualTypeArguments()[0]; } @SuppressWarnings("unchecked") public static Class<?> getRawClass(Type type) { if (type instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) type).getRawType(); } else { return (Class<?>) type; } } public static Type getSuperType(final Type type) { return SUPER_TYPE_MAP.computeIfAbsent(type, _type -> { if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; final Type genericSuperClass = ((Class<?>) parameterizedType.getRawType()).getGenericSuperclass(); if (genericSuperClass instanceof ParameterizedType) { final Type[] superTypeArguments = getTypeArguments(genericSuperClass); final Type[] typeParameters = ((GenericDeclaration) parameterizedType.getRawType()).getTypeParameters(); int k = 0; for (int i = 0; i != superTypeArguments.length; i++) { for (int j = 0; i < typeParameters.length; j++) { if (typeParameters[j].equals(superTypeArguments[i])) { superTypeArguments[i] = parameterizedType.getActualTypeArguments()[k++]; break; } } } return createParameterizedType(((ParameterizedType) genericSuperClass).getRawType(), superTypeArguments); } else { return genericSuperClass; } } else { return ((Class<?>) type).getGenericSuperclass(); } }); } public static Type getSuperType(Type subType, Class<?> rawSuperType) { while (subType != null && getRawClass(subType) != rawSuperType) { subType = getSuperType(subType); } return subType; } public static boolean isTypeOrSubTypeOf(Type subType, Type superType) { return getRawClass(superType).isAssignableFrom(getRawClass(subType)); } public static ParameterizedType createParameterizedType(Type rawClass, Type... genericTypes) { return new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return genericTypes; } @Override public Type getRawType() { return rawClass; } @Override public Type getOwnerType() { return null; } }; } public static boolean restResponseTypeExpectsBody(ParameterizedType restResponseReturnType) { return getRestResponseBodyType(restResponseReturnType) != Void.class; } public static Type getRestResponseBodyType(Type restResponseReturnType) { final Type[] restResponseTypeArguments = TypeUtil.getTypeArguments(restResponseReturnType); if (restResponseTypeArguments != null && restResponseTypeArguments.length > 0) { return restResponseTypeArguments[restResponseTypeArguments.length - 1]; } else { return getRestResponseBodyType(TypeUtil.getSuperType(restResponseReturnType)); } } // Private Ctr private TypeUtil() { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/UnixTime.java
package com.aliyun.core.utils; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; public final class UnixTime { private final OffsetDateTime dateTime; public UnixTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public UnixTime(long unixSeconds) { this.dateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond(unixSeconds), ZoneOffset.UTC); } public OffsetDateTime getDateTime() { return this.dateTime; } @Override public String toString() { return String.valueOf(dateTime.toEpochSecond()); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof UnixTime)) { return false; } UnixTime rhs = (UnixTime) obj; return this.dateTime.equals(rhs.getDateTime()); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/UrlBuilder.java
package com.aliyun.core.utils; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public final class UrlBuilder { private static final Map<String, UrlBuilder> PARSED_URLS = new ConcurrentHashMap<>(); private String scheme; private String host; private String port; private String path; private final Map<String, String> query = new LinkedHashMap<>(); public UrlBuilder setScheme(String scheme) { if (scheme == null || scheme.isEmpty()) { this.scheme = null; } else { with(scheme, UrlTokenizerState.SCHEME); } return this; } public String getScheme() { return scheme; } public UrlBuilder setHost(String host) { if (host == null || host.isEmpty()) { this.host = null; } else { with(host, UrlTokenizerState.SCHEME_OR_HOST); } return this; } public String getHost() { return host; } public UrlBuilder setPort(String port) { if (port == null || port.isEmpty()) { this.port = null; } else { with(port, UrlTokenizerState.PORT); } return this; } public UrlBuilder setPort(int port) { return setPort(Integer.toString(port)); } public Integer getPort() { return port == null ? null : Integer.valueOf(port); } public UrlBuilder setPath(String path) { if (path == null || path.isEmpty()) { this.path = null; } else { with(path, UrlTokenizerState.PATH); } return this; } public String getPath() { return path; } public UrlBuilder setQueryParameter(String queryParameterName, String queryParameterEncodedValue) { query.put(queryParameterName, queryParameterEncodedValue); return this; } public UrlBuilder setQuery(String query) { if (query == null || query.isEmpty()) { this.query.clear(); } else { with(query, UrlTokenizerState.QUERY); } return this; } /** * Get the query that has been assigned to this UrlBuilder. */ public Map<String, String> getQuery() { return query; } /** * Returns the query string currently configured in this UrlBuilder instance. */ public String getQueryString() { if (query.isEmpty()) { return ""; } StringBuilder queryBuilder = new StringBuilder("?"); for (Map.Entry<String, String> entry : query.entrySet()) { if (queryBuilder.length() > 1) { queryBuilder.append("&"); } queryBuilder.append(entry.getKey()); queryBuilder.append("="); queryBuilder.append(entry.getValue()); } return queryBuilder.toString(); } private UrlBuilder with(String text, UrlTokenizerState startState) { final UrlTokenizer tokenizer = new UrlTokenizer(text, startState); while (tokenizer.next()) { final UrlToken token = tokenizer.current(); final String tokenText = token.text(); final UrlTokenType tokenType = token.type(); switch (tokenType) { case SCHEME: scheme = emptyToNull(tokenText); break; case HOST: host = emptyToNull(tokenText); break; case PORT: port = emptyToNull(tokenText); break; case PATH: final String tokenPath = emptyToNull(tokenText); if (path == null || path.equals("/") || !tokenPath.equals("/")) { path = tokenPath; } break; case QUERY: String queryString = emptyToNull(tokenText); if (queryString != null) { if (queryString.startsWith("?")) { queryString = queryString.substring(1); } for (String entry : queryString.split("&")) { String[] nameValue = entry.split("="); if (nameValue.length == 2) { setQueryParameter(nameValue[0], nameValue[1]); } else { setQueryParameter(nameValue[0], ""); } } } break; default: break; } } return this; } public URL toUrl() throws MalformedURLException { return new URL(toString()); } @Override public String toString() { final StringBuilder result = new StringBuilder(); final boolean isAbsolutePath = path != null && (path.startsWith("http://") || path.startsWith("https://")); if (!isAbsolutePath) { if (scheme != null) { result.append(scheme); if (!scheme.endsWith("://")) { result.append("://"); } } if (host != null) { result.append(host); } } if (port != null) { result.append(":"); result.append(port); } if (path != null) { if (result.length() != 0 && !path.startsWith("/")) { result.append('/'); } result.append(path); } result.append(getQueryString()); return result.toString(); } public static UrlBuilder parse(String url) { String concurrentSafeUrl = (url == null) ? "" : url; return PARSED_URLS.computeIfAbsent(concurrentSafeUrl, u -> new UrlBuilder().with(u, UrlTokenizerState.SCHEME_OR_HOST)).copy(); } public static UrlBuilder parse(URL url) { final UrlBuilder result = new UrlBuilder(); if (url != null) { final String protocol = url.getProtocol(); if (protocol != null && !protocol.isEmpty()) { result.setScheme(protocol); } final String host = url.getHost(); if (host != null && !host.isEmpty()) { result.setHost(host); } final int port = url.getPort(); if (port != -1) { result.setPort(port); } final String path = url.getPath(); if (path != null && !path.isEmpty()) { result.setPath(path); } final String query = url.getQuery(); if (query != null && !query.isEmpty()) { result.setQuery(query); } } return result; } private static String emptyToNull(String value) { return value == null || value.isEmpty() ? null : value; } private UrlBuilder copy() { UrlBuilder copy = new UrlBuilder(); copy.scheme = this.scheme; copy.host = this.host; copy.path = this.path; copy.port = this.port; copy.query.putAll(this.query); return copy; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/UrlToken.java
package com.aliyun.core.utils; class UrlToken { private final String text; private final UrlTokenType type; UrlToken(String text, UrlTokenType type) { this.text = text; this.type = type; } String text() { return text; } UrlTokenType type() { return type; } @Override public boolean equals(Object rhs) { return rhs instanceof UrlToken && equals((UrlToken) rhs); } public boolean equals(UrlToken rhs) { return rhs != null && text.equals(rhs.text) && type == rhs.type; } @Override public String toString() { return "\"" + text + "\" (" + type + ")"; } @Override public int hashCode() { return (text == null ? 0 : text.hashCode()) ^ type.hashCode(); } static UrlToken scheme(String text) { return new UrlToken(text, UrlTokenType.SCHEME); } static UrlToken host(String text) { return new UrlToken(text, UrlTokenType.HOST); } static UrlToken port(String text) { return new UrlToken(text, UrlTokenType.PORT); } static UrlToken path(String text) { return new UrlToken(text, UrlTokenType.PATH); } static UrlToken query(String text) { return new UrlToken(text, UrlTokenType.QUERY); } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/UrlTokenType.java
package com.aliyun.core.utils; enum UrlTokenType { SCHEME, HOST, PORT, PATH, QUERY, }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/UrlTokenizer.java
package com.aliyun.core.utils; class UrlTokenizer { private final String text; private final int textLength; private UrlTokenizerState state; private int currentIndex; private UrlToken currentToken; UrlTokenizer(String text) { this(text, UrlTokenizerState.SCHEME_OR_HOST); } UrlTokenizer(String text, UrlTokenizerState state) { this.text = text; this.textLength = (text == null ? 0 : text.length()); this.state = state; this.currentIndex = 0; this.currentToken = null; } private boolean hasCurrentCharacter() { return currentIndex < textLength; } private char currentCharacter() { return text.charAt(currentIndex); } private void nextCharacter() { nextCharacter(1); } private void nextCharacter(int step) { if (hasCurrentCharacter()) { currentIndex += step; } } private String peekCharacters(int charactersToPeek) { int endIndex = currentIndex + charactersToPeek; if (textLength < endIndex) { endIndex = textLength; } return text.substring(currentIndex, endIndex); } UrlToken current() { return currentToken; } boolean next() { if (!hasCurrentCharacter()) { currentToken = null; } else { switch (state) { case SCHEME: final String scheme = readUntilNotLetterOrDigit(); currentToken = UrlToken.scheme(scheme); if (!hasCurrentCharacter()) { state = UrlTokenizerState.DONE; } else { state = UrlTokenizerState.HOST; } break; case SCHEME_OR_HOST: final String schemeOrHost = readUntilCharacter(':', '/', '?'); if (!hasCurrentCharacter()) { currentToken = UrlToken.host(schemeOrHost); state = UrlTokenizerState.DONE; } else if (currentCharacter() == ':') { if (peekCharacters(3).equals("://")) { currentToken = UrlToken.scheme(schemeOrHost); state = UrlTokenizerState.HOST; } else { currentToken = UrlToken.host(schemeOrHost); state = UrlTokenizerState.PORT; } } else if (currentCharacter() == '/') { currentToken = UrlToken.host(schemeOrHost); state = UrlTokenizerState.PATH; } else if (currentCharacter() == '?') { currentToken = UrlToken.host(schemeOrHost); state = UrlTokenizerState.QUERY; } break; case HOST: if (peekCharacters(3).equals("://")) { nextCharacter(3); } final String host = readUntilCharacter(':', '/', '?'); currentToken = UrlToken.host(host); if (!hasCurrentCharacter()) { state = UrlTokenizerState.DONE; } else if (currentCharacter() == ':') { state = UrlTokenizerState.PORT; } else if (currentCharacter() == '/') { state = UrlTokenizerState.PATH; } else { state = UrlTokenizerState.QUERY; } break; case PORT: if (currentCharacter() == ':') { nextCharacter(); } final String port = readUntilCharacter('/', '?'); currentToken = UrlToken.port(port); if (!hasCurrentCharacter()) { state = UrlTokenizerState.DONE; } else if (currentCharacter() == '/') { state = UrlTokenizerState.PATH; } else { state = UrlTokenizerState.QUERY; } break; case PATH: final String path = readUntilCharacter('?'); currentToken = UrlToken.path(path); if (!hasCurrentCharacter()) { state = UrlTokenizerState.DONE; } else { state = UrlTokenizerState.QUERY; } break; case QUERY: if (currentCharacter() == '?') { nextCharacter(); } final String query = readRemaining(); currentToken = UrlToken.query(query); state = UrlTokenizerState.DONE; break; default: break; } } return currentToken != null; } private String readUntilNotLetterOrDigit() { String result = ""; if (hasCurrentCharacter()) { final StringBuilder builder = new StringBuilder(); while (hasCurrentCharacter()) { final char currentCharacter = currentCharacter(); if (!Character.isLetterOrDigit(currentCharacter)) { break; } else { builder.append(currentCharacter); nextCharacter(); } } result = builder.toString(); } return result; } private String readUntilCharacter(char... terminatingCharacters) { String result = ""; if (hasCurrentCharacter()) { final StringBuilder builder = new StringBuilder(); boolean foundTerminator = false; while (hasCurrentCharacter()) { final char currentCharacter = currentCharacter(); for (final char terminatingCharacter : terminatingCharacters) { if (currentCharacter == terminatingCharacter) { foundTerminator = true; break; } } if (foundTerminator) { break; } else { builder.append(currentCharacter); nextCharacter(); } } result = builder.toString(); } return result; } private String readRemaining() { String result = ""; if (currentIndex < textLength) { result = text.substring(currentIndex, textLength); currentIndex = textLength; } return result; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/UrlTokenizerState.java
package com.aliyun.core.utils; enum UrlTokenizerState { SCHEME, SCHEME_OR_HOST, HOST, PORT, PATH, QUERY, DONE }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/Validate.java
package com.aliyun.core.utils; import java.time.Duration; import java.util.Collection; import java.util.Map; public final class Validate { private static final String DEFAULT_NULL_EX_MESSAGE = "The object is validated as null"; private Validate() { } public static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } public static <T> T notNull(final T object, final String message, final Object... values) { if (object == null) { throw new IllegalArgumentException(String.format(message, values)); } return object; } public static <T> void isNull(final T object, final String message, final Object... values) { if (object != null) { throw new IllegalArgumentException(String.format(message, values)); } } public static <T> T paramNotNull(final T object, final String paramName) { if (object == null) { throw new IllegalArgumentException(String.format("%s must not be null.", paramName)); } return object; } public static <T extends CharSequence> T paramNotBlank(final T chars, final String paramName) { if (chars == null) { throw new IllegalArgumentException(String.format("%s must not be null.", paramName)); } if (StringUtils.isBlank(chars)) { throw new IllegalArgumentException(String.format("%s must not be blank or empty.", paramName)); } return chars; } public static <T extends CharSequence> T notEmpty(final T chars, final String paramName) { if (chars == null) { throw new IllegalArgumentException(String.format("%s must not be null.", paramName)); } if (StringUtils.isEmpty(chars)) { throw new IllegalArgumentException(String.format("%s must not be empty.", paramName)); } return chars; } public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) { if (array == null) { throw new IllegalArgumentException(String.format(message, values)); } if (array.length == 0) { throw new IllegalArgumentException(String.format(message, values)); } return array; } public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) { if (collection == null) { throw new NullPointerException(String.format(message, values)); } if (collection.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return collection; } public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) { if (map == null) { throw new NullPointerException(String.format(message, values)); } if (map.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return map; } public static int isPositive(int num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } public static long isPositive(long num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } public static int isNotNegative(int num, String fieldName) { if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } public static long isNotNegative(long num, String fieldName) { if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } public static Duration isPositive(Duration duration, String fieldName) { if (duration == null) { throw new IllegalArgumentException(String.format("%s cannot be null", fieldName)); } if (duration.isNegative() || duration.isZero()) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return duration; } public static Duration isNotNegative(Duration duration, String fieldName) { if (duration == null) { throw new IllegalArgumentException(String.format("%s cannot be null", fieldName)); } if (duration.isNegative()) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return duration; } public static <T> Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type, final String message, final Object... values) { if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(String.format(message, values)); } return (Class<? extends T>) type; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/XmlUtil.java
package com.aliyun.core.utils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.util.*; public class XmlUtil { public static Map<String, Object> deserializeXml(String xmlStr) throws DocumentException { if (StringUtils.isEmpty(xmlStr)) { return null; } return DomToMap(DocumentHelper.parseText(xmlStr)); } public static String serializeXml(Map xmlMap, String rootName) { if (xmlMap == null) { return null; } return MapToDom(xmlMap, rootName).asXML(); } private static Map<String, Object> DomToMap(Document document) { Element rootElement = document.getRootElement(); Map<String, Object> map = new HashMap(); ElementToMap(rootElement, map); return map; } private static Object ElementToMap(Element element, Map<String, Object> map) { List<Element> elements = element.elements(); if (elements.size() == 0) { // String context = StringUtils.isEmpty(element.getTextTrim()) ? null : element.getTextTrim(); if (null != map) { map.put(element.getName(), element.getTextTrim()); } return element.getTextTrim(); } else { Map<String, Object> subMap = new HashMap<>(); if (null != map) { map.put(element.getName(), subMap); } for (Element elem : elements) { if (subMap.containsKey(elem.getName())) { Object o = subMap.get(elem.getName()); Class clazz = o.getClass(); if (List.class.isAssignableFrom(clazz)) { ((List) o).add(ElementToMap(elem, null)); } else if (Map.class.isAssignableFrom(clazz)) { List list = new ArrayList(); Map remove = (Map) subMap.remove(elem.getName()); list.add(remove); list.add(ElementToMap(elem, null)); subMap.put(elem.getName(), list); } else { List list = new ArrayList(); Object remove = subMap.remove(elem.getName()); list.add(remove); list.add(ElementToMap(elem, null)); subMap.put(elem.getName(), list); } } else { ElementToMap(elem, subMap); } } return subMap; } } public static Document MapToDom(Map map, String rootName) { Document document = DocumentHelper.createDocument(); Element root = document.addElement(rootName); MapToElement(root, map); return document; } private static void MapToElement(Element root, Map<String, ?> map) { if (null == map) { return; } for (Map.Entry<String, ?> en : map.entrySet()) { if (null == en.getValue()) { continue; } if (en.getValue() instanceof Map) { Element element = root.addElement(en.getKey()); MapToElement(element, (Map<String, ?>) en.getValue()); } else if (en.getValue() instanceof List) { List<?> value = (List<?>) en.getValue(); for (Object obj : value) { Element element = root.addElement(en.getKey()); if (obj instanceof Map) { MapToElement(element, (Map<String, ?>) obj); } else { element.add(DocumentHelper.createText(obj.toString())); } } } else { Element element = root.addElement(en.getKey()); element.add(DocumentHelper.createText(en.getValue().toString())); } } return; } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/tracing/ProcessKind.java
package com.aliyun.core.utils.tracing; public enum ProcessKind { /** * Amqp Send Message process call to send data. */ SEND, /** * Amqp message process call to receive data. */ MESSAGE, /** * Custom process call to process received messages. */ PROCESS }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/tracing/Tracer.java
package com.aliyun.core.utils.tracing; import com.aliyun.core.utils.Context; import java.time.OffsetDateTime; import java.util.Map; public interface Tracer { String DISABLE_TRACING_KEY = "disable-tracing"; Context start(String methodName, Context context); Context start(String methodName, Context context, ProcessKind processKind); void end(int responseCode, Throwable error, Context context); void end(String statusMessage, Throwable error, Context context); void setAttribute(String key, String value, Context context); Context setSpanName(String spanName, Context context); void addLink(Context context); Context extractContext(String diagnosticId, Context context); default Context getSharedSpanBuilder(String spanName, Context context) { // no-op return Context.NONE; } default void addEvent(String name, Map<String, Object> attributes, OffsetDateTime timestamp) { } }
0
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils
java-sources/com/aliyun/aliyun-java-core/0.3.2-beta/com/aliyun/core/utils/tracing/TracerProxy.java
package com.aliyun.core.utils.tracing; import com.aliyun.core.utils.Context; import java.util.Iterator; import java.util.ServiceLoader; public final class TracerProxy { private static Tracer tracer; static { ServiceLoader<Tracer> serviceLoader = ServiceLoader.load(Tracer.class); Iterator<?> iterator = serviceLoader.iterator(); if (iterator.hasNext()) { tracer = serviceLoader.iterator().next(); } } private TracerProxy() { // no-op } public static Context start(String methodName, Context context) { if (tracer == null) { return context; } return tracer.start(methodName, context); } public static void setAttribute(String key, String value, Context context) { if (tracer == null) { return; } tracer.setAttribute(key, value, context); } public static void end(int responseCode, Throwable error, Context context) { if (tracer == null) { return; } tracer.end(responseCode, error, context); } public static Context setSpanName(String spanName, Context context) { if (tracer == null) { return context; } return tracer.setSpanName(spanName, context); } public static boolean isTracingEnabled() { return tracer != null; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/Endpoint.java
/* * Licensed 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.aas; import java.util.HashMap; public class Endpoint { public static HashMap<String, String> endpointMap = new HashMap<String, String>() { { put("cn-shanghai-internal-test-1", "aas.aliyuncs.com"); put("cn-beijing-gov-1", "aas.aliyuncs.com"); put("cn-shenzhen-su18-b01", "aas.aliyuncs.com"); put("cn-shanghai-inner", "aas.aliyuncs.com"); put("cn-shenzhen-st4-d01", "aas.aliyuncs.com"); put("cn-haidian-cm12-c01", "aas.aliyuncs.com"); put("cn-hangzhou-internal-prod-1", "aas.aliyuncs.com"); put("cn-north-2-gov-1", "aas.aliyuncs.com"); put("cn-yushanfang", "aas.aliyuncs.com"); put("cn-hongkong-finance-pop", "aas.aliyuncs.com"); put("cn-qingdao-nebula", "aas.aliyuncs.com"); put("cn-shanghai", "aas-vpc.cn-shanghai.aliyuncs.com"); put("cn-shanghai-finance-1", "aas.aliyuncs.com"); put("cn-beijing-finance-pop", "aas.aliyuncs.com"); put("cn-wuhan", "aas.aliyuncs.com"); put("cn-shenzhen", "aas.aliyuncs.com"); put("cn-zhengzhou-nebula-1", "aas.aliyuncs.com"); put("rus-west-1-pop", "aas.ap-northeast-1.aliyuncs.com"); put("cn-shanghai-et15-b01", "aas.aliyuncs.com"); put("cn-hangzhou-bj-b01", "aas.aliyuncs.com"); put("cn-hangzhou-internal-test-1", "aas.aliyuncs.com"); put("eu-west-1-oxs", "aas.ap-northeast-1.aliyuncs.com"); put("cn-zhangbei-na61-b01", "aas.aliyuncs.com"); put("cn-beijing-finance-1", "aas.aliyuncs.com"); put("cn-hangzhou-internal-test-3", "aas.aliyuncs.com"); put("cn-hangzhou-internal-test-2", "aas.aliyuncs.com"); put("cn-shenzhen-finance-1", "aas.aliyuncs.com"); put("cn-chengdu", "aas.aliyuncs.com"); put("cn-hangzhou-test-306", "aas.aliyuncs.com"); put("cn-shanghai-et2-b01", "aas.aliyuncs.com"); put("cn-hangzhou-finance", "aas.aliyuncs.com"); put("cn-beijing-nu16-b01", "aas.aliyuncs.com"); put("cn-edge-1", "aas.aliyuncs.com"); put("cn-huhehaote", "aas.aliyuncs.com"); put("cn-fujian", "aas.aliyuncs.com"); put("us-east-1", "aas.ap-northeast-1.aliyuncs.com"); put("ap-northeast-2-pop", "aas.ap-northeast-1.aliyuncs.com"); put("cn-shenzhen-inner", "aas.aliyuncs.com"); put("cn-zhangjiakou-na62-a01", "aas.aliyuncs.com"); } }; public static String endpointRegionalType = "regional"; }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/ChangePreferredLanguageRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class ChangePreferredLanguageRequest extends RpcAcsRequest<ChangePreferredLanguageResponse> { private String preferredLanguage; public ChangePreferredLanguageRequest() { super("Aas", "2015-07-01", "ChangePreferredLanguage"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getPreferredLanguage() { return this.preferredLanguage; } public void setPreferredLanguage(String preferredLanguage) { this.preferredLanguage = preferredLanguage; if(preferredLanguage != null){ putQueryParameter("PreferredLanguage", preferredLanguage); } } @Override public Class<ChangePreferredLanguageResponse> getResponseClass() { return ChangePreferredLanguageResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/ChangePreferredLanguageResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.ChangePreferredLanguageResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class ChangePreferredLanguageResponse extends AcsResponse { private String requestId; private String code; private String message; private Boolean success; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } @Override public ChangePreferredLanguageResponse getInstance(UnmarshallerContext context) { return ChangePreferredLanguageResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CheckMfaBindRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class CheckMfaBindRequest extends RpcAcsRequest<CheckMfaBindResponse> { public CheckMfaBindRequest() { super("Aas", "2015-07-01", "CheckMfaBind"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } @Override public Class<CheckMfaBindResponse> getResponseClass() { return CheckMfaBindResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CheckMfaBindResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CheckMfaBindResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CheckMfaBindResponse extends AcsResponse { private String requestId; private Boolean isBindMfa; private Integer code; private String message; private Boolean success; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Boolean getIsBindMfa() { return this.isBindMfa; } public void setIsBindMfa(Boolean isBindMfa) { this.isBindMfa = isBindMfa; } public Integer getCode() { return this.code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } @Override public CheckMfaBindResponse getInstance(UnmarshallerContext context) { return CheckMfaBindResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateAccessKeyForAccountRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class CreateAccessKeyForAccountRequest extends RpcAcsRequest<CreateAccessKeyForAccountResponse> { private String aKSecret; private String pK; public CreateAccessKeyForAccountRequest() { super("Aas", "2015-07-01", "CreateAccessKeyForAccount"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getAKSecret() { return this.aKSecret; } public void setAKSecret(String aKSecret) { this.aKSecret = aKSecret; if(aKSecret != null){ putQueryParameter("AKSecret", aKSecret); } } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; if(pK != null){ putQueryParameter("PK", pK); } } @Override public Class<CreateAccessKeyForAccountResponse> getResponseClass() { return CreateAccessKeyForAccountResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateAccessKeyForAccountResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CreateAccessKeyForAccountResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateAccessKeyForAccountResponse extends AcsResponse { private String requestId; private String pK; private AccessKey accessKey; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } public AccessKey getAccessKey() { return this.accessKey; } public void setAccessKey(AccessKey accessKey) { this.accessKey = accessKey; } public static class AccessKey { private String createTime; private String accessKeyId; private String accessKeySecret; private String accessKeyStatus; private String accessKeyType; public String getCreateTime() { return this.createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getAccessKeyId() { return this.accessKeyId; } public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; } public String getAccessKeySecret() { return this.accessKeySecret; } public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; } public String getAccessKeyStatus() { return this.accessKeyStatus; } public void setAccessKeyStatus(String accessKeyStatus) { this.accessKeyStatus = accessKeyStatus; } public String getAccessKeyType() { return this.accessKeyType; } public void setAccessKeyType(String accessKeyType) { this.accessKeyType = accessKeyType; } } @Override public CreateAccessKeyForAccountResponse getInstance(UnmarshallerContext context) { return CreateAccessKeyForAccountResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateAliyunAccountRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class CreateAliyunAccountRequest extends RpcAcsRequest<CreateAliyunAccountResponse> { private String aliyunId; public CreateAliyunAccountRequest() { super("Aas", "2015-07-01", "CreateAliyunAccount"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getAliyunId() { return this.aliyunId; } public void setAliyunId(String aliyunId) { this.aliyunId = aliyunId; if(aliyunId != null){ putQueryParameter("AliyunId", aliyunId); } } @Override public Class<CreateAliyunAccountResponse> getResponseClass() { return CreateAliyunAccountResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateAliyunAccountResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CreateAliyunAccountResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateAliyunAccountResponse extends AcsResponse { private String requestId; private String pK; private String aliyunId; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } public String getAliyunId() { return this.aliyunId; } public void setAliyunId(String aliyunId) { this.aliyunId = aliyunId; } @Override public CreateAliyunAccountResponse getInstance(UnmarshallerContext context) { return CreateAliyunAccountResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateAliyunAccountWithBindHidRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class CreateAliyunAccountWithBindHidRequest extends RpcAcsRequest<CreateAliyunAccountWithBindHidResponse> { private String innerAccountHid; public CreateAliyunAccountWithBindHidRequest() { super("Aas", "2015-07-01", "CreateAliyunAccountWithBindHid"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getInnerAccountHid() { return this.innerAccountHid; } public void setInnerAccountHid(String innerAccountHid) { this.innerAccountHid = innerAccountHid; if(innerAccountHid != null){ putQueryParameter("InnerAccountHid", innerAccountHid); } } @Override public Class<CreateAliyunAccountWithBindHidResponse> getResponseClass() { return CreateAliyunAccountWithBindHidResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateAliyunAccountWithBindHidResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CreateAliyunAccountWithBindHidResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateAliyunAccountWithBindHidResponse extends AcsResponse { private String requestId; private String pK; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } @Override public CreateAliyunAccountWithBindHidResponse getInstance(UnmarshallerContext context) { return CreateAliyunAccountWithBindHidResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateIntlAliyunAccountRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class CreateIntlAliyunAccountRequest extends RpcAcsRequest<CreateIntlAliyunAccountResponse> { private String nationalityCode; public CreateIntlAliyunAccountRequest() { super("Aas", "2015-07-01", "CreateIntlAliyunAccount"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getNationalityCode() { return this.nationalityCode; } public void setNationalityCode(String nationalityCode) { this.nationalityCode = nationalityCode; if(nationalityCode != null){ putQueryParameter("NationalityCode", nationalityCode); } } @Override public Class<CreateIntlAliyunAccountResponse> getResponseClass() { return CreateIntlAliyunAccountResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateIntlAliyunAccountResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CreateIntlAliyunAccountResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateIntlAliyunAccountResponse extends AcsResponse { private String requestId; private String pK; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } @Override public CreateIntlAliyunAccountResponse getInstance(UnmarshallerContext context) { return CreateIntlAliyunAccountResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateShortTermAccessKeyForAccountRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class CreateShortTermAccessKeyForAccountRequest extends RpcAcsRequest<CreateShortTermAccessKeyForAccountResponse> { private String expireTime; private Boolean isMfaPresent; private String pK; public CreateShortTermAccessKeyForAccountRequest() { super("Aas", "2015-07-01", "CreateShortTermAccessKeyForAccount"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getExpireTime() { return this.expireTime; } public void setExpireTime(String expireTime) { this.expireTime = expireTime; if(expireTime != null){ putQueryParameter("ExpireTime", expireTime); } } public Boolean getIsMfaPresent() { return this.isMfaPresent; } public void setIsMfaPresent(Boolean isMfaPresent) { this.isMfaPresent = isMfaPresent; if(isMfaPresent != null){ putQueryParameter("IsMfaPresent", isMfaPresent.toString()); } } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; if(pK != null){ putQueryParameter("PK", pK); } } @Override public Class<CreateShortTermAccessKeyForAccountResponse> getResponseClass() { return CreateShortTermAccessKeyForAccountResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/CreateShortTermAccessKeyForAccountResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CreateShortTermAccessKeyForAccountResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateShortTermAccessKeyForAccountResponse extends AcsResponse { private String requestId; private String pK; private AccessKey accessKey; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } public AccessKey getAccessKey() { return this.accessKey; } public void setAccessKey(AccessKey accessKey) { this.accessKey = accessKey; } public static class AccessKey { private String createTime; private String accessKeyId; private String accessKeySecret; private String accessKeyStatus; private String accessKeyType; private String expireTime; public String getCreateTime() { return this.createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getAccessKeyId() { return this.accessKeyId; } public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; } public String getAccessKeySecret() { return this.accessKeySecret; } public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; } public String getAccessKeyStatus() { return this.accessKeyStatus; } public void setAccessKeyStatus(String accessKeyStatus) { this.accessKeyStatus = accessKeyStatus; } public String getAccessKeyType() { return this.accessKeyType; } public void setAccessKeyType(String accessKeyType) { this.accessKeyType = accessKeyType; } public String getExpireTime() { return this.expireTime; } public void setExpireTime(String expireTime) { this.expireTime = expireTime; } } @Override public CreateShortTermAccessKeyForAccountResponse getInstance(UnmarshallerContext context) { return CreateShortTermAccessKeyForAccountResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/DeleteAccessKeyForAccountRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class DeleteAccessKeyForAccountRequest extends RpcAcsRequest<DeleteAccessKeyForAccountResponse> { private String aKId; private String pK; public DeleteAccessKeyForAccountRequest() { super("Aas", "2015-07-01", "DeleteAccessKeyForAccount"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getAKId() { return this.aKId; } public void setAKId(String aKId) { this.aKId = aKId; if(aKId != null){ putQueryParameter("AKId", aKId); } } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; if(pK != null){ putQueryParameter("PK", pK); } } @Override public Class<DeleteAccessKeyForAccountResponse> getResponseClass() { return DeleteAccessKeyForAccountResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/DeleteAccessKeyForAccountResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.DeleteAccessKeyForAccountResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class DeleteAccessKeyForAccountResponse extends AcsResponse { private String requestId; private String pK; private String result; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } public String getResult() { return this.result; } public void setResult(String result) { this.result = result; } @Override public DeleteAccessKeyForAccountResponse getInstance(UnmarshallerContext context) { return DeleteAccessKeyForAccountResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/GenerateAccountLoginTokenRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class GenerateAccountLoginTokenRequest extends RpcAcsRequest<GenerateAccountLoginTokenResponse> { private String targetPk; public GenerateAccountLoginTokenRequest() { super("Aas", "2015-07-01", "GenerateAccountLoginToken"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getTargetPk() { return this.targetPk; } public void setTargetPk(String targetPk) { this.targetPk = targetPk; if(targetPk != null){ putQueryParameter("TargetPk", targetPk); } } @Override public Class<GenerateAccountLoginTokenResponse> getResponseClass() { return GenerateAccountLoginTokenResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/GenerateAccountLoginTokenResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.GenerateAccountLoginTokenResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GenerateAccountLoginTokenResponse extends AcsResponse { private String requestId; private LoginToken loginToken; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public LoginToken getLoginToken() { return this.loginToken; } public void setLoginToken(LoginToken loginToken) { this.loginToken = loginToken; } public static class LoginToken { private String targetPk; private String loginTokenString; public String getTargetPk() { return this.targetPk; } public void setTargetPk(String targetPk) { this.targetPk = targetPk; } public String getLoginTokenString() { return this.loginTokenString; } public void setLoginTokenString(String loginTokenString) { this.loginTokenString = loginTokenString; } } @Override public GenerateAccountLoginTokenResponse getInstance(UnmarshallerContext context) { return GenerateAccountLoginTokenResponseUnmarshaller.unmarshall(this, context); } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/GetAliyunAccountWithBindHidRequest.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; import com.aliyuncs.aas.Endpoint; /** * @author auto create * @version */ public class GetAliyunAccountWithBindHidRequest extends RpcAcsRequest<GetAliyunAccountWithBindHidResponse> { private String innerAccountHid; public GetAliyunAccountWithBindHidRequest() { super("Aas", "2015-07-01", "GetAliyunAccountWithBindHid"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getInnerAccountHid() { return this.innerAccountHid; } public void setInnerAccountHid(String innerAccountHid) { this.innerAccountHid = innerAccountHid; if(innerAccountHid != null){ putQueryParameter("InnerAccountHid", innerAccountHid); } } @Override public Class<GetAliyunAccountWithBindHidResponse> getResponseClass() { return GetAliyunAccountWithBindHidResponse.class; } }
0
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model
java-sources/com/aliyun/aliyun-java-sdk-aas/2.4.1/com/aliyuncs/aas/model/v20150701/GetAliyunAccountWithBindHidResponse.java
/* * Licensed 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.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.GetAliyunAccountWithBindHidResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GetAliyunAccountWithBindHidResponse extends AcsResponse { private String requestId; private String pK; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } @Override public GetAliyunAccountWithBindHidResponse getInstance(UnmarshallerContext context) { return GetAliyunAccountWithBindHidResponseUnmarshaller.unmarshall(this, context); } }