headers, byte[] payload) {
19 | acquireNativeHandle(messageNew(Header.marshallHeadersForJNI(headers), payload));
20 | }
21 |
22 | /**
23 | * Get the binary format of this message (i.e. for sending across the wire manually)
24 | * @return ByteBuffer wrapping the underlying message data. This buffer is only valid
25 | * as long as the message itself is valid.
26 | */
27 | public ByteBuffer getMessageBuffer() {
28 | return messageBuffer(getNativeHandle());
29 | }
30 |
31 | @Override
32 | protected void releaseNativeHandle() {
33 | if (!isNull()) {
34 | messageDelete(getNativeHandle());
35 | }
36 | }
37 |
38 | @Override
39 | protected boolean canReleaseReferencesImmediately() {
40 | return true;
41 | }
42 |
43 | private static native long messageNew(byte[] serializedHeaders, byte[] payload);
44 | private static native void messageDelete(long messageHandle);
45 | private static native ByteBuffer messageBuffer(long messageHandle);
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/eventstream/MessageFlags.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.eventstream;
2 |
3 | /**
4 | * Java mirror of the native aws_event_stream_rpc_message_flag enum, specifying rpc message-related flags
5 | */
6 | public enum MessageFlags {
7 | ConnectionAccepted(1),
8 | TerminateStream(2);
9 |
10 | private int byteValue;
11 |
12 | MessageFlags(int byteValue) {
13 | this.byteValue = byteValue;
14 | }
15 |
16 | /**
17 | * @return the native enum value associated with this Java enum value
18 | */
19 | public int getByteValue() {
20 | return this.byteValue;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/eventstream/MessageFlushCallback.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.eventstream;
2 |
3 | /**
4 | * Functor interface for receiving message flush events.
5 | */
6 | public interface MessageFlushCallback {
7 | /**
8 | * Invoked when a message has been flushed to the underlying transport mechanism.
9 | * @param errorCode If this is 0, the message was successfully written. Otherwise,
10 | * errorCode represents the reason the message flush failed.
11 | */
12 | void onCallbackInvoked(int errorCode);
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/eventstream/MessageType.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.eventstream;
2 |
3 | /**
4 | * Java mirror of the native aws_event_stream_rpc_message_type enum, specifying the type of rpc message
5 | */
6 | public enum MessageType {
7 | ApplicationMessage((byte)0),
8 | ApplicationError((byte)1),
9 | Ping((byte)2),
10 | PingResponse((byte)3),
11 | Connect((byte)4),
12 | ConnectAck((byte)5),
13 | ProtocolError((byte)6),
14 | ServerError((byte)7);
15 |
16 | private byte enumValue;
17 |
18 | MessageType(byte enumValue) {
19 | this.enumValue = enumValue;
20 | }
21 |
22 | /**
23 | * @return the native enum value associated with this Java enum value
24 | */
25 | public byte getEnumValue() {
26 | return this.enumValue;
27 | }
28 |
29 | /**
30 | * Create a MessageType enum value from a native enum value
31 | * @param enumValue native enum value
32 | * @return a new MessageType enum value
33 | */
34 | public static MessageType fromEnumValue(int enumValue) {
35 | for (MessageType type : MessageType.values()) {
36 | if (type.enumValue == enumValue) {
37 | return type;
38 | }
39 | }
40 |
41 | throw new IllegalArgumentException("Unknown MessageType enum value: " + enumValue);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/eventstream/ServerListenerHandler.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.eventstream;
2 |
3 | /**
4 | * Handler interface for processing incoming event-stream-rpc connections and their lifetimes.
5 | */
6 | public abstract class ServerListenerHandler {
7 | /**
8 | * Invoked upon receiving a new connection, or if an error happened upon connection
9 | * creation. If errorCode is non-zero, onConnectionShutdown() will never be invoked.
10 | *
11 | * @param serverConnection The new server connection to use for communications. Is non-null
12 | * when errorCode is 0.
13 | * @param errorCode represents any error that occurred during connection establishment
14 | * @return Return an instance of ServerConnectionHandler, for processing connection specific events.
15 | */
16 | protected abstract ServerConnectionHandler onNewConnection(final ServerConnection serverConnection, int errorCode);
17 |
18 | /**
19 | * Invoked upon connection shutdown. serverConnection will never be null. This function is
20 | * only invoked if onNewConnection() was invoked with a zero errorCode.
21 | * @param serverConnection connection the shutdown occurred on.
22 | * @param errorCode shutdown reason. 0 means clean shutdown.
23 | */
24 | protected abstract void onConnectionShutdown(final ServerConnection serverConnection, int errorCode);
25 |
26 | /**
27 | * Invoked from JNI. Completes the closure future and invokes onConnectionShutdown()
28 | */
29 | void onConnectionShutdownShim(final ServerConnection serverConnection, int errorCode) {
30 | onConnectionShutdown(serverConnection, errorCode);
31 | serverConnection.closedFuture.complete(errorCode);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/Http2Request.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.http;
7 |
8 | import software.amazon.awssdk.crt.http.HttpVersion;
9 |
10 | /**
11 | * Represents a single Client Request to be sent on a HTTP connection
12 | */
13 | public class Http2Request extends HttpRequestBase {
14 | /**
15 | * An empty HTTP/2 Request.
16 | */
17 | public Http2Request() {
18 | this(new HttpHeader[] {}, null);
19 | }
20 |
21 | /**
22 | * An empty HTTP/2 Request with headers and body stream.
23 | *
24 | * @param headers set of http request headers to include, note: pseudo
25 | * headers should be set to make a good HTTP/2 request.
26 | * @param bodyStream (optional) interface to an object that will stream out the
27 | * request body
28 | */
29 | public Http2Request(HttpHeader[] headers, HttpRequestBodyStream bodyStream) {
30 | super(headers, bodyStream);
31 | this.version = HttpVersion.HTTP_2;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/Http2Stream.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.http;
7 |
8 | import software.amazon.awssdk.crt.CrtRuntimeException;
9 |
10 | import java.util.concurrent.CompletableFuture;
11 |
12 | /**
13 | * An HttpStream represents a single HTTP/2 specific Http Request/Response.
14 | */
15 | public class Http2Stream extends HttpStreamBase {
16 |
17 | protected Http2Stream(long ptr) {
18 | super(ptr);
19 | }
20 |
21 | /**
22 | * Reset the HTTP/2 stream. Note that if the stream closes before this async
23 | * call is fully processed, the RST_STREAM frame will not be sent.
24 | *
25 | * @param errorCode aws_http2_error_code. Reason to reset the stream.
26 | */
27 | public void resetStream(final Http2ClientConnection.Http2ErrorCode errorCode) {
28 | if (isNull()) {
29 | throw new IllegalStateException("Http2Stream has been closed.");
30 | }
31 | http2StreamResetStream(getNativeHandle(), errorCode.getValue());
32 | }
33 |
34 | /**
35 | * TODO: getters for reset stream. Not sure anyone needs it though.
36 | */
37 | private static native void http2StreamResetStream(long http_stream, int errorCode);
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/HttpException.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.http;
7 |
8 | import software.amazon.awssdk.crt.CRT;
9 |
10 | /**
11 | * This exception will be thrown by any exceptional cases encountered within the
12 | * JNI bindings to the AWS Common Runtime
13 | */
14 | public class HttpException extends RuntimeException {
15 | private final int errorCode;
16 |
17 | /**
18 | * Constructs a new HttpException
19 | * @param errorCode native error code representing the error source/reason
20 | */
21 | public HttpException(int errorCode) {
22 | super(CRT.awsErrorString(errorCode));
23 | this.errorCode = errorCode;
24 | }
25 |
26 | /**
27 | * Returns the error code captured when the exception occurred. This can be fed to CRT.awsErrorString() to
28 | * get a user-friendly error string
29 | * @return The error code associated with this exception
30 | */
31 | public int getErrorCode() {
32 | return errorCode;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/HttpHeaderBlock.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.http;
7 |
8 | /**
9 | * Type of header block. Syncs with the native enum aws_http_header_block
10 | */
11 | public enum HttpHeaderBlock {
12 |
13 | MAIN(0),
14 |
15 | INFORMATIONAL(1),
16 |
17 | TRAILING(2);
18 |
19 | private int blockType;
20 |
21 | HttpHeaderBlock(int value) {
22 | blockType = value;
23 | }
24 |
25 | /**
26 | * @return the native enum value associated with this Java enum value
27 | */
28 | public int getValue() {
29 | return blockType;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/HttpManagerMetrics.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.http;
2 |
3 | public class HttpManagerMetrics {
4 | private final long availableConcurrency;
5 | private final long pendingConcurrencyAcquires;
6 | private final long leasedConcurrency;
7 |
8 | HttpManagerMetrics(long availableConcurrency, long pendingConcurrencyAcquires, long leasedConcurrency) {
9 | this.availableConcurrency = availableConcurrency;
10 | this.pendingConcurrencyAcquires = pendingConcurrencyAcquires;
11 | this.leasedConcurrency = leasedConcurrency;
12 | }
13 |
14 | /**
15 | * @return The number of additional concurrent requests that can be supported by the HTTP manager without needing to
16 | * establish additional connections to the target server.
17 | *
18 | * For connection manager, this value represents idle connections.
19 | * For stream manager, this value represents the number of streams that are possible to be made without creating new
20 | * connections, although the implementation can create new connection without fully filling it.
21 | */
22 | public long getAvailableConcurrency() {
23 | return availableConcurrency;
24 | }
25 |
26 | /**
27 | * @return The number of requests that are awaiting concurrency to be made available from the HTTP manager.
28 | */
29 | public long getPendingConcurrencyAcquires() {
30 | return pendingConcurrencyAcquires;
31 | }
32 |
33 | /**
34 | * @return the amount of concurrency units currently out for lease. For http 1.1 this will be connections while
35 | * for http2 this will be number of streams leased out.
36 | */
37 | public long getLeasedConcurrency() {
38 | return this.leasedConcurrency;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/HttpRequestBodyStream.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.http;
7 |
8 | import java.nio.ByteBuffer;
9 |
10 | /**
11 | * Interface that Native code knows how to call when handling Http Request bodies
12 | *
13 | */
14 | public interface HttpRequestBodyStream {
15 |
16 |
17 | /**
18 | * Called from Native when the Http Request has a Body (Eg PUT/POST requests).
19 | * Note that this function may be called many times as Native sends the Request Body.
20 | *
21 | * Do NOT keep a reference to this ByteBuffer past the lifetime of this function call. The CommonRuntime reserves
22 | * the right to use DirectByteBuffers pointing to memory that only lives as long as the function call.
23 | *
24 | * @param bodyBytesOut The Buffer to write the Request Body Bytes to.
25 | * @return True if Request body is complete, false otherwise.
26 | */
27 | default boolean sendRequestBody(ByteBuffer bodyBytesOut) {
28 | /* Optional Callback, return empty request body by default unless user wants to return one. */
29 | return true;
30 | }
31 |
32 | /**
33 | * Called from native when the processing needs the stream to rewind itself back to its beginning.
34 | * If the stream does not support rewinding or the rewind fails, false should be returned
35 | *
36 | * Signing requires a rewindable stream, but basic http does not.
37 | *
38 | * @return True if the stream was successfully rewound, false otherwise.
39 | */
40 | default boolean resetPosition() { return false; }
41 |
42 | /**
43 | * Called from native when the processing needs to know the length of the stream.
44 | * If the stream does not know/support length, 0 should be returned.
45 | *
46 | * Signing requires a rewindable stream, but basic http does not.
47 | *
48 | * @return Stream length, or 0 if unknown stream or length is unsupported
49 | */
50 | default long getLength() { return 0; }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/http/HttpVersion.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.http;
7 |
8 | import java.util.Map;
9 | import java.util.HashMap;
10 |
11 | public enum HttpVersion {
12 |
13 | UNKNOWN(0),
14 | HTTP_1_0(1),
15 | HTTP_1_1(2),
16 | HTTP_2(3);
17 |
18 | private int value;
19 | private static Map enumMapping = buildEnumMapping();
20 |
21 | HttpVersion(int value) {
22 | this.value = value;
23 | }
24 |
25 | public static HttpVersion getEnumValueFromInteger(int value) {
26 | HttpVersion enumValue = enumMapping.get(value);
27 | if (enumValue != null) {
28 | return enumValue;
29 | }
30 |
31 | throw new RuntimeException("Illegal signature type value in signing configuration");
32 | }
33 |
34 | private static Map buildEnumMapping() {
35 | Map enumMapping = new HashMap();
36 | enumMapping.put(UNKNOWN.getValue(), UNKNOWN);
37 | enumMapping.put(HTTP_1_0.getValue(), HTTP_1_0);
38 | enumMapping.put(HTTP_1_1.getValue(), HTTP_1_1);
39 | enumMapping.put(HTTP_2.getValue(), HTTP_2);
40 |
41 | return enumMapping;
42 | }
43 |
44 | public int getValue() {
45 | return value;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/internal/GraalVMNativeFeature.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.internal;
6 |
7 | import org.graalvm.nativeimage.hosted.Feature;
8 |
9 | import software.amazon.awssdk.crt.CRT;
10 |
11 | /**
12 | * Implementation of GraalVM feature to extract the share lib to the image path.
13 | * From GraalVM docs:
14 | * > When loading native libraries using System.loadLibrary() (and related APIs),
15 | * > the native image will search the directory containing the native image before searching the Java library path
16 | * https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/JNI/#loading-native-libraries
17 | * Internal API, not for external usage.
18 | */
19 | public class GraalVMNativeFeature implements Feature {
20 |
21 | @Override
22 | public void afterImageWrite(AfterImageWriteAccess access) {
23 | new CRT();
24 | ExtractLib.extractLibrary(access.getImagePath().getParent().toString());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/ClientTlsContext.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.io;
6 |
7 | import software.amazon.awssdk.crt.CrtRuntimeException;
8 |
9 | /**
10 | * This class wraps the aws_tls_context from aws-c-io to provide access to TLS
11 | * configuration contexts in the AWS Common Runtime.
12 | */
13 | public final class ClientTlsContext extends TlsContext {
14 |
15 | /**
16 | * Creates a new Client TlsContext. There are significant native resources
17 | * consumed to create a TlsContext, so most applications will only need to
18 | * create one and re-use it for all connections.
19 | *
20 | * @param options A set of options for this context
21 | * @throws CrtRuntimeException If the provided options are malformed or the
22 | * system is unable to allocate space for a native
23 | * tls context
24 | */
25 | public ClientTlsContext(TlsContextOptions options) throws CrtRuntimeException {
26 | super(options);
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/DirectoryTraversal.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.io;
2 |
3 | /**
4 | * This class wraps the directory traversal implementation provided by the CRT.
5 | *
6 | * @deprecated It is currently an EXPERIMENTAL feature meant for internal use only. It may be changed incompatibly
7 | * or removed in a future version.
8 | */
9 | @Deprecated()
10 | public final class DirectoryTraversal {
11 |
12 | /**
13 | * Traverse a directory starting at the path provided.
14 | * If you want the traversal to recurse the entire directory, pass recursive as true. Passing false for this parameter
15 | * will only iterate the contents of the directory, but will not descend into any directories it encounters.
16 | *
17 | * If recursive is set to true, the traversal is performed post-order, depth-first
18 | * (for practical reasons such as deleting a directory that contains subdirectories or files).
19 | *
20 | * The traversal iteration can be cancelled by the user by returning false from the callback. If the
21 | * traversal is cancelled either returning false from the callback or an unhandled exception is thrown
22 | * from the callback, the traverse method will throw a RuntimeException to notify user about incomplete
23 | * results.
24 | *
25 | * @param path directory to traverse.
26 | * @param recursive true to recurse the entire directory, false will only iterate the path specified
27 | * @param handler callback to invoke for each file or directory found during the traversal.
28 | */
29 | public static void traverse(final String path, boolean recursive, final DirectoryTraversalHandler handler) {
30 | if (path == null) {
31 | throw new IllegalArgumentException("path must not be null");
32 | }
33 | if (handler == null) {
34 | throw new IllegalArgumentException("handler must not be null");
35 | }
36 |
37 | crtTraverse(path, recursive, handler);
38 | }
39 |
40 | private static native void crtTraverse(final String path, boolean recursive, final DirectoryTraversalHandler handler);
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/DirectoryTraversalHandler.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.io;
2 |
3 | /**
4 | * Handler invoked during calls to DirectoryTraversal.traverse() as each entry is encountered.
5 | */
6 | public interface DirectoryTraversalHandler {
7 |
8 | /**
9 | * Invoked during calls to DirectoryTraversal.traverse() as each entry is encountered.
10 | *
11 | * @param directoryEntry Information about the directory entry encountered
12 | * @return true to continue the traversal, or false to abort it
13 | */
14 | boolean onDirectoryEntry(final DirectoryEntry directoryEntry);
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/ServerBootstrap.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.io;
2 |
3 | import software.amazon.awssdk.crt.CrtResource;
4 | import software.amazon.awssdk.crt.CrtRuntimeException;
5 |
6 | /**
7 | * This class wraps the aws_server_bootstrap from aws-c-io to provide
8 | * a server context for all protocol stacks in the AWS Common Runtime.
9 | */
10 | public class ServerBootstrap extends CrtResource {
11 | private EventLoopGroup eventLoopGroup = null;
12 |
13 | /**
14 | * @param elg event loop group to map server connections into
15 | */
16 | public ServerBootstrap(final EventLoopGroup elg) {
17 | eventLoopGroup = elg;
18 | acquireNativeHandle(serverBootstrapNew(this, eventLoopGroup.getNativeHandle()));
19 | addReferenceTo(eventLoopGroup);
20 | }
21 |
22 | @Override
23 | protected void releaseNativeHandle() {
24 | if (!isNull()) {
25 | serverBootstrapDestroy(getNativeHandle());
26 | removeReferenceTo(eventLoopGroup);
27 | }
28 | }
29 |
30 | @Override
31 | protected boolean canReleaseReferencesImmediately() {
32 | return false;
33 | }
34 |
35 | private static native long serverBootstrapNew(ServerBootstrap bootstrap, long elg) throws CrtRuntimeException;
36 | private static native void serverBootstrapDestroy(long bootstrap);
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/ServerTlsContext.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.io;
6 |
7 | import software.amazon.awssdk.crt.CrtRuntimeException;
8 |
9 | /**
10 | * This class wraps the aws_tls_context from aws-c-io to provide access to TLS
11 | * configuration contexts in the AWS Common Runtime.
12 | */
13 | public final class ServerTlsContext extends TlsContext {
14 |
15 | /**
16 | * Creates a new Server TlsContext. There are significant native resources
17 | * consumed to create a TlsContext, so most applications will only need to
18 | * create one and re-use it for all connections.
19 | *
20 | * @param options A set of options for this context
21 | * @throws CrtRuntimeException If the provided options are malformed or the
22 | * system is unable to allocate space for a native
23 | * tls context
24 | */
25 | public ServerTlsContext(TlsContextOptions options) throws CrtRuntimeException {
26 | super(options);
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/StandardRetryOptions.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.io;
7 |
8 | /**
9 | * Top-level configuration for http retries.
10 | */
11 | public class StandardRetryOptions {
12 |
13 | private ExponentialBackoffRetryOptions backoffRetryOptions;
14 | private long initialBucketCapacity;
15 |
16 | /**
17 | * Sets the exponential backoff configuration
18 | * @param backoffRetryOptions exponential backoff configuration
19 | * @return this options object
20 | */
21 | public StandardRetryOptions withBackoffRetryOptions(ExponentialBackoffRetryOptions backoffRetryOptions) {
22 | this.backoffRetryOptions = backoffRetryOptions;
23 | return this;
24 | }
25 |
26 | /**
27 | * @return current exponential backoff retry options
28 | */
29 | public ExponentialBackoffRetryOptions getBackoffRetryOptions() {
30 | return this.backoffRetryOptions;
31 | }
32 |
33 | /**
34 | * Sets the initial capacity of the token bucket in the standard retry strategy
35 | * @param initialBucketCapacity initial token bucket capacity
36 | * @return this options object
37 | */
38 | public StandardRetryOptions withInitialBucketCapacity(long initialBucketCapacity) {
39 | this.initialBucketCapacity = initialBucketCapacity;
40 | return this;
41 | }
42 |
43 | /**
44 | * @return current initial bucket capacity
45 | */
46 | public long getInitialBucketCapacity() {
47 | return this.initialBucketCapacity;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/TlsContext.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.io;
6 |
7 | import software.amazon.awssdk.crt.CrtResource;
8 | import software.amazon.awssdk.crt.CrtRuntimeException;
9 |
10 | /**
11 | * This class wraps the aws_tls_context from aws-c-io to provide
12 | * access to TLS configuration contexts in the AWS Common Runtime.
13 | */
14 | public class TlsContext extends CrtResource {
15 |
16 | /**
17 | * Creates a new Client TlsContext. There are significant native resources consumed to create a TlsContext, so most
18 | * applications will only need to create one and re-use it for all connections.
19 | * @param options A set of options for this context
20 | * @throws CrtRuntimeException If the provided options are malformed or the system is unable
21 | * to allocate space for a native tls context
22 | */
23 | public TlsContext(TlsContextOptions options) throws CrtRuntimeException {
24 | acquireNativeHandle(tlsContextNew(options.getNativeHandle()));
25 | }
26 |
27 | /**
28 | * Creates a new Client TlsContext. There are significant native resources consumed to create a TlsContext, so most
29 | * applications will only need to create one and re-use it for all connections.
30 | */
31 | public TlsContext() throws CrtRuntimeException {
32 | try (TlsContextOptions options = TlsContextOptions.createDefaultClient()) {
33 | acquireNativeHandle(tlsContextNew(options.getNativeHandle()));
34 | }
35 | }
36 |
37 | /**
38 | * Determines whether a resource releases its dependencies at the same time the native handle is released or if it waits.
39 | * Resources that wait are responsible for calling releaseReferences() manually.
40 | */
41 | @Override
42 | protected boolean canReleaseReferencesImmediately() { return true; }
43 |
44 | /**
45 | * Frees all native resources associated with the context. This object is unusable after close is called.
46 | */
47 | @Override
48 | protected void releaseNativeHandle() {
49 | if (!isNull()) {
50 | tlsContextDestroy(getNativeHandle());
51 | }
52 | }
53 |
54 | protected static native long tlsContextNew(long options) throws CrtRuntimeException;
55 |
56 | private static native void tlsContextDestroy(long elg);
57 | };
58 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/TlsHashAlgorithm.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.io;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * The hash algorithm of a TLS private key operation. Any custom private key operation handlers are expected to perform
12 | * operations on the input TLS data using the correct hash algorithm or fail the operation.
13 | */
14 | public enum TlsHashAlgorithm {
15 | UNKNOWN(0), SHA1(1), SHA224(2), SHA256(3), SHA384(4), SHA512(5);
16 |
17 | static Map buildEnumMapping() {
18 | Map enumMapping = new HashMap();
19 | for (TlsHashAlgorithm i : TlsHashAlgorithm.values()) {
20 | enumMapping.put(i.nativeValue, i);
21 | }
22 | return enumMapping;
23 | }
24 |
25 | public static TlsHashAlgorithm getEnumValueFromInteger(int value) {
26 | TlsHashAlgorithm enumValue = enumMapping.get(value);
27 | if (enumValue != null) {
28 | return enumValue;
29 | }
30 | throw new RuntimeException("Illegal TlsKeyOperation.TlsHashAlgorithm");
31 | }
32 |
33 | TlsHashAlgorithm(int nativeValue) {
34 | this.nativeValue = nativeValue;
35 | }
36 |
37 | public int getNativeValue() {
38 | return nativeValue;
39 | }
40 |
41 | int nativeValue;
42 | static Map enumMapping = buildEnumMapping();
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/TlsKeyOperationHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.io;
6 |
7 | import software.amazon.awssdk.crt.Log;
8 | import software.amazon.awssdk.crt.Log.LogLevel;
9 | import software.amazon.awssdk.crt.Log.LogSubject;
10 |
11 | /**
12 | * Interface for handling private key operations during the TLS handshake.
13 | */
14 | public interface TlsKeyOperationHandler {
15 |
16 | /**
17 | * Invoked each time a private key operation needs to be performed.
18 | *
19 | * You MUST call either operation.complete(output) or
20 | * operation.completeExceptionally(exception) or the TLS connection will hang
21 | * forever.
22 | *
23 | * You may complete the operation synchronously, or async. You may complete the
24 | * operation on any thread.
25 | *
26 | * The function is always invoked from an IO event-loop thread. Therefore you
27 | * MUST NOT perform an async call and wait for it in a blocking way from within
28 | * this function. Such behavior is likely to deadlock your program.
29 | *
30 | * Additionally, this may be called from multiple times from multiple threads
31 | * at once, so keep this in mind if using a private key operation that has to
32 | * be single-threaded and synchronously called.
33 | *
34 | * @param operation The operation to be acted on
35 | */
36 | void performOperation(TlsKeyOperation operation);
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/io/TlsSignatureAlgorithm.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.io;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * The signature of a TLS private key operation. Any custom private key operation handlers are expected to perform
12 | * operations on the input TLS data using the correct signature algorithm or fail the operation.
13 | */
14 | public enum TlsSignatureAlgorithm {
15 | UNKNOWN(0), RSA(1), ECDSA(2);
16 |
17 | static Map buildEnumMapping() {
18 | Map enumMapping = new HashMap();
19 | for (TlsSignatureAlgorithm i : TlsSignatureAlgorithm.values()) {
20 | enumMapping.put(i.nativeValue, i);
21 | }
22 | return enumMapping;
23 | }
24 |
25 | public static TlsSignatureAlgorithm getEnumValueFromInteger(int value) {
26 | TlsSignatureAlgorithm enumValue = enumMapping.get(value);
27 | if (enumValue != null) {
28 | return enumValue;
29 | }
30 | throw new RuntimeException("Illegal TlsKeyOperation.TlsSignatureAlgorithm");
31 | }
32 |
33 | TlsSignatureAlgorithm(int nativeValue) {
34 | this.nativeValue = nativeValue;
35 | }
36 |
37 | public int getNativeValue() {
38 | return nativeValue;
39 | }
40 |
41 | int nativeValue;
42 | static Map enumMapping = buildEnumMapping();
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/iot/IncomingPublishEvent.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.iot;
7 |
8 | import software.amazon.awssdk.crt.mqtt5.packets.UserProperty;
9 |
10 | import java.util.List;
11 |
12 | /**
13 | * An event that describes an incoming publish message received on a streaming operation.
14 | */
15 | public class IncomingPublishEvent {
16 |
17 | private final byte[] payload;
18 |
19 | private final String topic;
20 |
21 | private String contentType;
22 |
23 | private List userProperties;
24 |
25 | private Long messageExpiryIntervalSeconds;
26 |
27 | private IncomingPublishEvent(byte[] payload, String topic) {
28 | this.payload = payload;
29 | this.topic = topic;
30 | }
31 |
32 | /**
33 | * Gets the payload of the IncomingPublishEvent.
34 | *
35 | * @return Payload of the IncomingPublishEvent.
36 | */
37 | public byte[] getPayload() {
38 | return payload;
39 | }
40 |
41 | /**
42 | * Gets the topic of the IncomingPublishEvent.
43 | *
44 | * @return Topic of the IncomingPublishEvent.
45 | */
46 | public String getTopic() {
47 | return topic;
48 | }
49 |
50 | /**
51 | * Gets the content type of the IncomingPublishEvent.
52 | *
53 | * @return Content type of the IncomingPublishEvent.
54 | */
55 | public String getContentType() {
56 | return contentType;
57 | }
58 |
59 | /**
60 | * Gets the user properties of the IncomingPublishEvent.
61 | *
62 | * @return User properties of the IncomingPublishEvent.
63 | */
64 | public List getUserProperties() {
65 | return userProperties;
66 | }
67 |
68 | /**
69 | * Gets the message expiry interval seconds of the IncomingPublishEvent.
70 | *
71 | * @return Message expiry interval seconds of the IncomingPublishEvent.
72 | */
73 | public Long getMessageExpiryIntervalSeconds() {
74 | return messageExpiryIntervalSeconds;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/iot/MqttRequestResponse.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.iot;
7 |
8 | /**
9 | * Encapsulates a response to an AWS IoT Core MQTT-based service request
10 | */
11 | public class MqttRequestResponse {
12 |
13 | private String topic;
14 | private byte[] payload;
15 |
16 | private MqttRequestResponse() {
17 | }
18 |
19 | /**
20 | * Gets the MQTT topic that the response was received on.
21 | *
22 | * Different topics map to different types within the
23 | * service model, so we need this value in order to know what to deserialize the payload into.
24 | *
25 | * @return the MQTT topic that the response was received on
26 | */
27 | public String getTopic() {
28 | return topic;
29 | }
30 |
31 | /**
32 | * Gets the payload of the response that correlates to a submitted request.
33 | *
34 | * @return Payload of the response that correlates to a submitted request.
35 | */
36 | public byte[] getPayload() {
37 | return payload;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/iot/SubscriptionStatusEvent.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.iot;
7 |
8 | import java.util.Optional;
9 |
10 | /**
11 | * An event that describes a change in subscription status for a streaming operation.
12 | */
13 | public class SubscriptionStatusEvent {
14 | private final SubscriptionStatusEventType type;
15 | private final Optional error;
16 |
17 | private SubscriptionStatusEvent(SubscriptionStatusEventType type, int errorCode) {
18 | this.type = type;
19 | if (errorCode != 0) {
20 | this.error = Optional.of(errorCode);
21 | } else {
22 | this.error = Optional.empty();
23 | }
24 | }
25 |
26 | /**
27 | * Gets the type of status change represented by the event.
28 | *
29 | * @return The type of status change represented by the event
30 | */
31 | public SubscriptionStatusEventType getType() {
32 | return this.type;
33 | }
34 |
35 | /**
36 | * Gets the underlying reason for the event. Only set for SubscriptionLost and SubscriptionHalted. Use
37 | * CRT.awsErrorString() to convert the integer error code into an error description.
38 | *
39 | * @return underlying reason for the event
40 | */
41 | public Optional getError() {
42 | return this.error;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/iot/SubscriptionStatusEventType.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.iot;
7 |
8 | import java.util.Map;
9 | import java.util.function.Function;
10 | import java.util.stream.Collectors;
11 | import java.util.stream.Stream;
12 |
13 | /**
14 | * The type of change to the state of a streaming operation subscription
15 | */
16 | public enum SubscriptionStatusEventType {
17 |
18 | /**
19 | * The streaming operation is successfully subscribed to its topic (filter)
20 | */
21 | SUBSCRIPTION_ESTABLISHED(0),
22 |
23 | /**
24 | * The streaming operation has temporarily lost its subscription to its topic (filter)
25 | */
26 | SUBSCRIPTION_LOST(1),
27 |
28 | /**
29 | * The streaming operation has entered a terminal state where it has given up trying to subscribe
30 | * to its topic (filter). This is always due to user error (bad topic filter or IoT Core permission policy).
31 | */
32 | SUBSCRIPTION_HALTED(2);
33 |
34 | private final int type;
35 |
36 | SubscriptionStatusEventType(int value) {
37 | type = value;
38 | }
39 |
40 |
41 | /**
42 | * @return the native enum integer value associated with this Java enum value
43 | */
44 | public int getValue() {
45 | return type;
46 | }
47 |
48 | /**
49 | * Creates a Java SubscriptionStatusEventType enum value from a native integer value
50 | * @param value native integer value to convert to a SubscriptionStatusEventType instance
51 | * @return a SubscriptionStatusEventType value
52 | */
53 | public static SubscriptionStatusEventType getEnumValueFromInteger(int value) {
54 | SubscriptionStatusEventType enumValue = enumMapping.get(value);
55 | if (enumValue != null) {
56 | return enumValue;
57 | }
58 | throw new RuntimeException("Illegal SubscriptionStatusEventType");
59 | }
60 |
61 | private static Map buildEnumMapping() {
62 | return Stream.of(SubscriptionStatusEventType.values())
63 | .collect(Collectors.toMap(SubscriptionStatusEventType::getValue, Function.identity()));
64 | }
65 |
66 | private final static Map enumMapping = buildEnumMapping();
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt/MqttClientConnectionEvents.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | * SPDX-License-Identifier: Apache-2.0.
5 | */
6 | package software.amazon.awssdk.crt.mqtt;
7 |
8 | /**
9 | * Interface used to receive connection events from the CRT
10 | */
11 | public interface MqttClientConnectionEvents {
12 | /**
13 | * Called when the connection was lost (or disconnected), reconnect will be attempted automatically until
14 | * disconnect() is called
15 | * @param errorCode AWS CRT error code, pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error
16 | */
17 | void onConnectionInterrupted(int errorCode);
18 |
19 | /**
20 | * Called whenever a reconnect succeeds; not called on an initial connect success
21 | * @param sessionPresent true if the session has been resumed, false if the session is clean
22 | */
23 | void onConnectionResumed(boolean sessionPresent);
24 |
25 | /**
26 | * Called on every successful connect and every successful reconnect.
27 | * Optional and is not required to be defined.
28 | * @param data The data sent from the client alongside the successful connection callback.
29 | */
30 | default void onConnectionSuccess(OnConnectionSuccessReturn data) {};
31 |
32 | /**
33 | * Called on every unsuccessful connect and every unsuccessful disconnect.
34 | * Optional and is not required to be defined.
35 | * @param data The data sent from the client alongside the failed connection callback.
36 | */
37 | default void onConnectionFailure(OnConnectionFailureReturn data) {};
38 |
39 | /**
40 | * Called when the connection was disconnected and shutdown successfully.
41 | * Optional and is not required to be defined.
42 | * @param data The data sent from the client alongside the successful disconnect.
43 | */
44 | default void onConnectionClosed(OnConnectionClosedReturn data) {};
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt/MqttClientConnectionOperationStatistics.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.mqtt;
2 |
3 | /**
4 | * Simple statistics about the current state of the connection's queue of operations
5 | */
6 | public class MqttClientConnectionOperationStatistics {
7 |
8 | private long incompleteOperationCount;
9 | private long incompleteOperationSize;
10 | private long unackedOperationCount;
11 | private long unackedOperationSize;
12 |
13 | public MqttClientConnectionOperationStatistics() {}
14 |
15 | /**
16 | * Returns the total number of operations submitted to the connection that have not yet been completed.
17 | * Note: Unacked operations are a subset of this.
18 | * @return Total number of operations submitted to the connection that have not yet been completed
19 | */
20 | public long getIncompleteOperationCount() {
21 | return incompleteOperationCount;
22 | }
23 |
24 | /**
25 | * Returns the total packet size of operations submitted to the connection that have not yet been completed.
26 | * Note: Unacked operations are a subset of this.
27 | * @return Total packet size of operations submitted to the connection that have not yet been completed
28 | */
29 | public long getIncompleteOperationSize() {
30 | return incompleteOperationSize;
31 | }
32 |
33 | /**
34 | * Returns the total number of operations that have been sent and are waiting for a corresponding ACK before
35 | * they can be completed.
36 | * @return Total number of operations that have been sent and are waiting for a corresponding ACK
37 | */
38 | public long getUnackedOperationCount() {
39 | return unackedOperationCount;
40 | }
41 |
42 | /**
43 | * Returns the total packet size of operations that have been sent and are waiting for a corresponding ACK before
44 | * they can be completed.
45 | * @return Total packet size of operations that have been sent and are waiting for a corresponding ACK
46 | */
47 | public long getUnackedOperationSize() {
48 | return unackedOperationSize;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt/MqttException.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt;
6 |
7 | import software.amazon.awssdk.crt.CRT;
8 |
9 | /**
10 | * This exception will be thrown by any exceptional cases encountered within the
11 | * JNI bindings to the AWS Common Runtime
12 | */
13 | public class MqttException extends RuntimeException {
14 | private int errorCode;
15 |
16 | /**
17 | * @param msg mqtt exception message
18 | */
19 | public MqttException(String msg) {
20 | super(msg);
21 | this.errorCode = -1;
22 | }
23 |
24 | /**
25 | * @param errorCode native CRT error code indicating the reason for the exception
26 | */
27 | public MqttException(int errorCode) {
28 | super(CRT.awsErrorString(errorCode));
29 | this.errorCode = errorCode;
30 | }
31 |
32 | /**
33 | * Returns the error code captured when the exception occurred. This can be fed to {@link CRT.awsErrorString} to
34 | * get a user-friendly error string
35 | * @return The error code associated with this exception
36 | */
37 | int getErrorCode() {
38 | return errorCode;
39 | }
40 | };
41 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt/OnConnectionClosedReturn.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.mqtt;
2 |
3 | /**
4 | * The data returned when the connection closed callback is invoked in a connection.
5 | *
6 | * Note: This class is currently empty, but this may contain additional data in the future.
7 | * @see software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents
8 | */
9 | public class OnConnectionClosedReturn {
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt/OnConnectionFailureReturn.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.mqtt;
2 |
3 | /**
4 | * The data returned when the connection failure callback is invoked in a connection.
5 | * @see software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents
6 | */
7 | public class OnConnectionFailureReturn {
8 |
9 | private int errorCode;
10 |
11 | /**
12 | * Gets the AWS CRT error code for the connection failure.
13 | * Pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error
14 | * @return The AWS CRT error code for the connection failure.
15 | */
16 | public int getErrorCode() {
17 | return errorCode;
18 | }
19 |
20 | /**
21 | * Constructs a new OnConnectionFailureReturn with an error code
22 | * @param errorCode The AWS CRT error code
23 | */
24 | protected OnConnectionFailureReturn(int errorCode) {
25 | this.errorCode = errorCode;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt/OnConnectionSuccessReturn.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.mqtt;
2 |
3 | /**
4 | * The data returned when the connection success callback is invoked in a connection.
5 | * @see software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents
6 | */
7 | public class OnConnectionSuccessReturn {
8 |
9 | private boolean sessionPresent;
10 |
11 | /**
12 | * Returns whether a session was present and resumed for this successful connection.
13 | * Will be set to true if the connection resumed an already present MQTT connection session.
14 | * @return whether a session was present and resumed
15 | */
16 | public boolean getSessionPresent() {
17 | return sessionPresent;
18 | }
19 |
20 | /**
21 | * Constructs a new OnConnectionSuccessReturn with a session present.
22 | * @param sessionPresent whether a session was present and resumed
23 | */
24 | protected OnConnectionSuccessReturn(boolean sessionPresent) {
25 | this.sessionPresent = sessionPresent;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/Mqtt5ClientOperationStatistics.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | /**
8 | * Simple statistics about the current state of the client's queue of operations
9 | */
10 | public class Mqtt5ClientOperationStatistics {
11 |
12 | private long incompleteOperationCount;
13 | private long incompleteOperationSize;
14 | private long unackedOperationCount;
15 | private long unackedOperationSize;
16 |
17 | public Mqtt5ClientOperationStatistics() {}
18 |
19 | /**
20 | * Returns the total number of operations submitted to the client that have not yet been completed.
21 | * Note: Unacked operations are a subset of this.
22 | * @return Total number of operations submitted to the client that have not yet been completed
23 | */
24 | public long getIncompleteOperationCount() {
25 | return incompleteOperationCount;
26 | }
27 |
28 | /**
29 | * Returns the total packet size of operations submitted to the client that have not yet been completed.
30 | * Note: Unacked operations are a subset of this.
31 | * @return Total packet size of operations submitted to the client that have not yet been completed
32 | */
33 | public long getIncompleteOperationSize() {
34 | return incompleteOperationSize;
35 | }
36 |
37 | /**
38 | * Returns the total number of operations that have been sent and are waiting for a corresponding ACK before
39 | * they can be completed.
40 | * @return Total number of operations that have been sent and are waiting for a corresponding ACK
41 | */
42 | public long getUnackedOperationCount() {
43 | return unackedOperationCount;
44 | }
45 |
46 | /**
47 | * Returns the total packet size of operations that have been sent and are waiting for a corresponding ACK before
48 | * they can be completed.
49 | * @return Total packet size of operations that have been sent and are waiting for a corresponding ACK
50 | */
51 | public long getUnackedOperationSize() {
52 | return unackedOperationSize;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/OnAttemptingConnectReturn.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | /**
8 | * The data returned when AttemptingConnect is invoked in the LifecycleEvents callback.
9 | * Currently empty, but may be used in the future for passing additional data.
10 | */
11 | public class OnAttemptingConnectReturn {
12 | /**
13 | * This is only called in JNI to make a new OnAttemptingConnectReturn.
14 | */
15 | private OnAttemptingConnectReturn() {}
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/OnConnectionFailureReturn.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | import software.amazon.awssdk.crt.mqtt5.packets.ConnAckPacket;
8 |
9 | /**
10 | * The data returned when OnConnectionFailure is invoked in the LifecycleEvents callback.
11 | * The data contained within can be gotten using the get
functions.
12 | * For example, getConnAckPacket
will return the ConnAckPacket from the server.
13 | */
14 | public class OnConnectionFailureReturn {
15 | private int errorCode;
16 | private ConnAckPacket connAckPacket;
17 |
18 | /**
19 | * Returns the error code returned from the server on the connection failure.
20 | * Pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error.
21 | * @return The error code returned from the server.
22 | */
23 | public int getErrorCode() {
24 | return errorCode;
25 | }
26 |
27 | /**
28 | * Returns the ConnAckPacket returned from the server on the connection failure, or Null if none was returned.
29 | * @return The ConnAckPacket returned from the server.
30 | */
31 | public ConnAckPacket getConnAckPacket() {
32 | return connAckPacket;
33 | }
34 |
35 | /**
36 | * This is only called in JNI to make a new OnConnectionFailureReturn.
37 | */
38 | private OnConnectionFailureReturn(int newErrorCode, ConnAckPacket newConnAckPacket)
39 | {
40 | this.errorCode = newErrorCode;
41 | this.connAckPacket = newConnAckPacket;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/OnConnectionSuccessReturn.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | import software.amazon.awssdk.crt.mqtt5.packets.ConnAckPacket;
8 |
9 | /**
10 | * The data returned when OnConnectionSuccess is invoked in the LifecycleEvents callback.
11 | * The data contained within can be gotten using the get
functions.
12 | * For example, getResultPublishPacket
will return the PublishPacket from the server.
13 | */
14 | public class OnConnectionSuccessReturn {
15 | private ConnAckPacket connAckPacket;
16 | private NegotiatedSettings negotiatedSettings;
17 |
18 | /**
19 | * Returns the ConnAckPacket returned from the server on the connection success or Null if none was returned.
20 | * @return The ConnAckPacket returned from the server.
21 | */
22 | public ConnAckPacket getConnAckPacket() {
23 | return connAckPacket;
24 | }
25 |
26 | /**
27 | * Returns the NegotiatedSettings returned from the server on the connection success or Null if none was returned.
28 | * @return The NegotiatedSettings returned from the server.
29 | */
30 | public NegotiatedSettings getNegotiatedSettings() {
31 | return negotiatedSettings;
32 | }
33 |
34 | /**
35 | * This is only called in JNI to make a new OnConnectionSuccessReturn.
36 | */
37 | private OnConnectionSuccessReturn(ConnAckPacket newConnAckPacket, NegotiatedSettings newNegotiatedSettings)
38 | {
39 | this.connAckPacket = newConnAckPacket;
40 | this.negotiatedSettings = newNegotiatedSettings;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/OnDisconnectionReturn.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | import software.amazon.awssdk.crt.mqtt5.packets.DisconnectPacket;
8 |
9 | /**
10 | * The data returned when OnDisconnect is invoked in the LifecycleEvents callback.
11 | * The data contained within can be gotten using the get
functions.
12 | * For example, getDisconnectPacket
will return the DisconnectPacket from the server.
13 | */
14 | public class OnDisconnectionReturn {
15 | private int errorCode;
16 | private DisconnectPacket disconnectPacket;
17 |
18 | /**
19 | * Returns the error code returned from the server on the disconnection.
20 | * Pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error.
21 | * @return The error code returned from the server.
22 | */
23 | public int getErrorCode() {
24 | return errorCode;
25 | }
26 |
27 | /**
28 | * Returns the ConnAckPacket returned from the server on the disconnection, or Null if none was returned.
29 | * @return The ConnAckPacket returned from the server.
30 | */
31 | public DisconnectPacket getDisconnectPacket() {
32 | return disconnectPacket;
33 | }
34 |
35 | /**
36 | * This is only called in JNI to make a new OnDisconnectionReturn.
37 | */
38 | private OnDisconnectionReturn(int newErrorCode, DisconnectPacket newDisconnectPacket)
39 | {
40 | this.errorCode = newErrorCode;
41 | this.disconnectPacket = newDisconnectPacket;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/OnStoppedReturn.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | /**
8 | * The data returned when OnStopped is invoked in the LifecycleEvents callback.
9 | * Currently empty, but may be used in the future for passing additional data.
10 | */
11 | public class OnStoppedReturn {
12 | /**
13 | * This is only called in JNI to make a new OnStoppedReturn.
14 | */
15 | private OnStoppedReturn() {}
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/PublishReturn.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5;
6 |
7 | import software.amazon.awssdk.crt.mqtt5.packets.PublishPacket;
8 |
9 | /**
10 | * The data returned when a publish is made to a topic the MQTT5 client is subscribed to.
11 | * The data contained within can be gotten using the get
functions.
12 | * For example, getPublishPacket
will return the PublishPacket received from the server.
13 | */
14 | public class PublishReturn {
15 | private PublishPacket publishPacket;
16 |
17 | /**
18 | * Returns the PublishPacket returned from the server or Null if none was returned.
19 | * @return The PublishPacket returned from the server.
20 | */
21 | public PublishPacket getPublishPacket() {
22 | return publishPacket;
23 | }
24 |
25 | /**
26 | * This is only called in JNI to make a new PublishReturn with a PUBLISH packet.
27 | * @param newPublishPacket The PubAckPacket data for QoS 1 packets. Can be null if result is non QoS 1.
28 | * @return A newly created PublishResult
29 | */
30 | private PublishReturn(PublishPacket newPublishPacket) {
31 | this.publishPacket = newPublishPacket;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/QOS.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.mqtt5;
7 |
8 | import java.util.Map;
9 | import java.util.function.Function;
10 | import java.util.stream.Collectors;
11 | import java.util.stream.Stream;
12 |
13 | /**
14 | * MQTT message delivery quality of service.
15 | *
16 | * Enum values match MQTT5 spec encoding values.
17 | */
18 | public enum QOS {
19 | /**
20 | * The message is delivered according to the capabilities of the underlying network. No response is sent by the
21 | * receiver and no retry is performed by the sender. The message arrives at the receiver either once or not at all.
22 | */
23 | AT_MOST_ONCE(0),
24 |
25 | /**
26 | * A level of service that ensures that the message arrives at the receiver at least once.
27 | */
28 | AT_LEAST_ONCE(1),
29 |
30 | /**
31 | * A level of service that ensures that the message arrives at the receiver exactly once.
32 | */
33 | EXACTLY_ONCE(2);
34 |
35 | private int qos;
36 |
37 | private QOS(int value) {
38 | qos = value;
39 | }
40 |
41 | /**
42 | * @return The native enum integer value associated with this Java enum value
43 | */
44 | public int getValue() {
45 | return qos;
46 | }
47 |
48 | /**
49 | * Creates a Java QualityOfService enum value from a native integer value.
50 | *
51 | * @param value native integer value for quality of service
52 | * @return a new QualityOfService value
53 | */
54 | public static QOS getEnumValueFromInteger(int value) {
55 | QOS enumValue = enumMapping.get(value);
56 | if (enumValue != null) {
57 | return enumValue;
58 | }
59 | throw new RuntimeException("Illegal QOS");
60 | }
61 |
62 | private static Map buildEnumMapping() {
63 | return Stream.of(QOS.values())
64 | .collect(Collectors.toMap(QOS::getValue, Function.identity()));
65 | }
66 |
67 | private static Map enumMapping = buildEnumMapping();
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/mqtt5/packets/UserProperty.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.mqtt5.packets;
6 |
7 | /**
8 | * A simple key-value pair struct to define a user property.
9 | * A user property is a name-value pair of utf-8 strings that can be added to MQTT5 packets.
10 | */
11 | public class UserProperty {
12 |
13 | public final String key;
14 | public final String value;
15 |
16 | public UserProperty(String key, String value) {
17 | this.key = key;
18 | this.value = value;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProperties.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.s3;
6 |
7 | public class S3ExpressCredentialsProperties {
8 | private String hostValue;
9 | private String region;
10 |
11 | public S3ExpressCredentialsProperties withHostValue (String hostValue) {
12 | this.hostValue = hostValue;
13 | return this;
14 | }
15 |
16 | public String getHostValue () {
17 | return this.hostValue;
18 | }
19 |
20 | public S3ExpressCredentialsProperties withRegion (String region) {
21 | this.region = region;
22 | return this;
23 | }
24 |
25 | public String getRegion () {
26 | return this.region;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProvider.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.s3;
6 |
7 | import software.amazon.awssdk.crt.auth.credentials.Credentials;
8 |
9 | /**
10 | * The Java object for Native code to invoke.
11 | */
12 | public class S3ExpressCredentialsProvider {
13 |
14 | private S3ExpressCredentialsProviderHandler handler;
15 |
16 | public S3ExpressCredentialsProvider(S3ExpressCredentialsProviderHandler handler) {
17 | this.handler = handler;
18 | }
19 |
20 | public void getS3ExpressCredentials(S3ExpressCredentialsProperties properties, Credentials origCredentials, long nativeHandler) {
21 | handler.getS3ExpressCredentials(properties, origCredentials).whenComplete((result, ex) -> {
22 | if(ex != null) {
23 | s3expressCredentialsProviderGetCredentialsCompleted(nativeHandler, null);
24 | } else {
25 | s3expressCredentialsProviderGetCredentialsCompleted(nativeHandler, result);
26 | }
27 | });
28 | }
29 |
30 | public void destroyProvider() throws Exception {
31 | /* Block until handler finishes shutdown. It doesn't matter to wait for shutdown */
32 | this.handler.destroyProvider().get();
33 | }
34 |
35 | /*******************************************************************************
36 | * native methods
37 | ******************************************************************************/
38 | private static native void s3expressCredentialsProviderGetCredentialsCompleted(long nativeHandler, Credentials credentials);
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProviderFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.s3;
6 |
7 |
8 | public interface S3ExpressCredentialsProviderFactory {
9 | /**
10 | * A handler to create a S3ExpressCredentialsProvider for the client to use.
11 | *
12 | * Warning:
13 | * You cannot use the client while creating the provider
14 | * (You can use the client for fetching credentials)
15 | * @param client The S3Client creates and owns the provider.
16 | * @return S3ExpressCredentialsProvider created.
17 | */
18 | public S3ExpressCredentialsProvider createS3ExpressCredentialsProvider(S3Client client);
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProviderHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.s3;
6 |
7 | import java.util.concurrent.CompletableFuture;
8 |
9 | import software.amazon.awssdk.crt.auth.credentials.Credentials;
10 |
11 | /**
12 | * Interface to override the S3Express Credentials provider.
13 | */
14 | public interface S3ExpressCredentialsProviderHandler {
15 | /**
16 | * To resolve the S3Express Credentials. Invoked when a single request needs to be signed.
17 | *
18 | * @param properties The properties needed to derive the S3Express credentials from.
19 | * @param origCredentials The original Credentials for fetching S3Express credentials.
20 | * @return The future to be resolved when the S3 Express credentials are resolved.
21 | */
22 | public CompletableFuture getS3ExpressCredentials(S3ExpressCredentialsProperties properties, Credentials origCredentials);
23 |
24 | /**
25 | * Invoked when the S3 client starts to destroy to clean up related resource.
26 | *
27 | * @return The future to be resolved when the resource finishes cleaning up.
28 | */
29 | public CompletableFuture destroyProvider();
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3MetaRequestProgress.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.s3;
6 |
7 | /**
8 | * Information about the meta request progress.
9 | */
10 | public class S3MetaRequestProgress {
11 |
12 | private long bytesTransferred;
13 | private long contentLength;
14 |
15 | /**
16 | * @param bytesTransferred bytes transferred since the previous progress update
17 | * @return this progress object
18 | */
19 | public S3MetaRequestProgress withBytesTransferred(long bytesTransferred) {
20 | this.bytesTransferred = bytesTransferred;
21 | return this;
22 | }
23 |
24 | /**
25 | * @return bytes transferred since the previous progress update
26 | */
27 | public long getBytesTransferred() {
28 | return bytesTransferred;
29 | }
30 |
31 | /**
32 | * @param contentLength length of the entire meta request operation
33 | * @return this progress object
34 | */
35 | public S3MetaRequestProgress withContentLength(long contentLength) {
36 | this.contentLength = contentLength;
37 | return this;
38 | }
39 |
40 | /**
41 | *
42 | * @return length of the entire meta request operation
43 | */
44 | public long getContentLength() {
45 | return contentLength;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3MetaRequestResponseHandlerNativeAdapter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | package software.amazon.awssdk.crt.s3;
6 |
7 | import software.amazon.awssdk.crt.http.HttpHeader;
8 |
9 | import java.nio.ByteBuffer;
10 |
11 | class S3MetaRequestResponseHandlerNativeAdapter {
12 | private S3MetaRequestResponseHandler responseHandler;
13 |
14 | S3MetaRequestResponseHandlerNativeAdapter(S3MetaRequestResponseHandler responseHandler) {
15 | this.responseHandler = responseHandler;
16 | }
17 |
18 | int onResponseBody(byte[] bodyBytesIn, long objectRangeStart, long objectRangeEnd) {
19 | return this.responseHandler.onResponseBody(ByteBuffer.wrap(bodyBytesIn), objectRangeStart, objectRangeEnd);
20 | }
21 |
22 | void onFinished(int errorCode, int responseStatus, byte[] errorPayload, String errorOperationName, int checksumAlgorithm, boolean didValidateChecksum, Throwable cause, final ByteBuffer headersBlob) {
23 | HttpHeader[] errorHeaders = headersBlob == null ? null : HttpHeader.loadHeadersFromMarshalledHeadersBlob(headersBlob);
24 | S3FinishedResponseContext context = new S3FinishedResponseContext(errorCode, responseStatus, errorPayload, errorOperationName, ChecksumAlgorithm.getEnumValueFromInteger(checksumAlgorithm), didValidateChecksum, cause, errorHeaders);
25 | this.responseHandler.onFinished(context);
26 | }
27 |
28 | void onResponseHeaders(final int statusCode, final ByteBuffer headersBlob) {
29 | responseHandler.onResponseHeaders(statusCode, HttpHeader.loadHeadersFromMarshalledHeadersBlob(headersBlob));
30 | }
31 |
32 | void onProgress(final S3MetaRequestProgress progress) {
33 | responseHandler.onProgress(progress);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/s3/S3TcpKeepAliveOptions.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.s3;
2 |
3 | /**
4 | * This class provides access to setting Tcp Keep Alive Options.
5 | * If interval or timeout are zero, then default values are used.
6 | */
7 | public class S3TcpKeepAliveOptions {
8 |
9 | private short keepAliveIntervalSec;
10 |
11 | private short keepAliveTimeoutSec;
12 |
13 | /* If set, sets the number of keep alive probes allowed to fail before the connection is considered
14 | * lost. If zero OS defaults are used. On Windows, this option is meaningless until Windows 10 1703.*/
15 | private short keepAliveMaxFailedProbes;
16 |
17 | public short getKeepAliveIntervalSec() {
18 | return keepAliveIntervalSec;
19 | }
20 |
21 | public void setKeepAliveIntervalSec(short keepAliveIntervalSec) {
22 | this.keepAliveIntervalSec = keepAliveIntervalSec;
23 | }
24 |
25 | public short getKeepAliveTimeoutSec() {
26 | return keepAliveTimeoutSec;
27 | }
28 |
29 | public void setKeepAliveTimeoutSec(short keepAliveTimeoutSec) {
30 | this.keepAliveTimeoutSec = keepAliveTimeoutSec;
31 | }
32 |
33 | public short getKeepAliveMaxFailedProbes() {
34 | return keepAliveMaxFailedProbes;
35 | }
36 |
37 | public void setKeepAliveMaxFailedProbes(short keepAliveMaxFailedProbes) {
38 | this.keepAliveMaxFailedProbes = keepAliveMaxFailedProbes;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/utils/ByteBufferUtils.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.utils;
7 |
8 | import java.nio.ByteBuffer;
9 | import java.nio.Buffer;
10 |
11 | /**
12 | * Utility Class with Helper functions for working with ByteBuffers
13 | */
14 | public class ByteBufferUtils {
15 | private ByteBufferUtils() {}
16 |
17 | /**
18 | * Transfers as much data as possible from an input ByteBuffer to an output ByteBuffer
19 | * @param in The input ByteBuffer
20 | * @param out The output ByteBuffer
21 | * @return The number of bytes transferred
22 | */
23 | public static int transferData(ByteBuffer in, ByteBuffer out) {
24 | int amtToTransfer = Math.min(in.remaining(), out.remaining());
25 |
26 | // Make a new ByteBuffer that shares the same underlying buffer as the input ByteBuffer
27 | ByteBuffer shallowCopy = in.duplicate();
28 |
29 | // Modify the shallow copy's read limit so that it matches the write space remaining in the output Buffer so
30 | // we don't throw an OutOfBounds exception
31 | // The weird cast is to avoid certain JDK8 JREs that don't think ByteBuffer
32 | // inherits from Buffer
33 | ((Buffer) shallowCopy).limit(shallowCopy.position() + amtToTransfer);
34 |
35 | // Transfer the data
36 | out.put(shallowCopy);
37 |
38 | // Increment the read position of the original input buffer by the number of bytes transferred
39 | in.position(in.position() + amtToTransfer);
40 | return amtToTransfer;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/software/amazon/awssdk/crt/utils/StringUtils.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.utils;
2 |
3 | import software.amazon.awssdk.crt.CRT;
4 |
5 | public class StringUtils {
6 | static {
7 | new CRT();
8 | };
9 |
10 | /**
11 | * Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
12 | * Like `Strings.join()` but works on Android before API 26.
13 | *
14 | * @param delimiter a sequence of characters that is used to separate each of the elements in the resulting String
15 | * @param elements an Iterable that will have its elements joined together
16 | * @return a new String that is composed from the elements argument
17 | */
18 | public static String join(CharSequence delimiter, Iterable extends CharSequence> elements) {
19 | if (delimiter == null || elements == null) throw new NullPointerException("delimiter and elements must not be null");
20 | StringBuilder sb = new StringBuilder();
21 |
22 | boolean first = true;
23 | for(CharSequence cs : elements) {
24 | if (!first) {
25 | sb.append(delimiter);
26 | }
27 | sb.append(cs);
28 | first = false;
29 | }
30 | return sb.toString();
31 | }
32 |
33 | /**
34 | * Encode a byte array into a Base64 byte array.
35 | * @param data The byte array to encode
36 | * @return The byte array encoded as Byte64
37 | */
38 | public static byte[] base64Encode(byte[] data) {
39 | return stringUtilsBase64Encode(data);
40 | }
41 |
42 | /**
43 | * Decode a Base64 byte array into a non-Base64 byte array.
44 | * @param data The byte array to decode.
45 | * @return Byte array decoded from Base64.
46 | */
47 | public static byte[] base64Decode(byte[] data) {
48 | return stringUtilsBase64Decode(data);
49 | }
50 |
51 | private static native byte[] stringUtilsBase64Encode(byte[] data_to_encode);
52 | private static native byte[] stringUtilsBase64Decode(byte[] data_to_decode);
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/native-image/software.amazon.awssdk/crt/aws-crt/native-image.properties:
--------------------------------------------------------------------------------
1 | Args=--enable-url-protocols=jar --features=software.amazon.awssdk.crt.internal.GraalVMNativeFeature
2 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/native-image/software.amazon.awssdk/crt/aws-crt/reflect-config.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "condition": {
4 | "typeReachable": "org.junit.Assume"
5 | },
6 | "name": "org.hamcrest.core.Every",
7 | "queryAllDeclaredMethods": true
8 | }
9 | ]
--------------------------------------------------------------------------------
/src/native/aws_signing.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_AWS_SIGNING_H
7 | #define AWS_JNI_CRT_AWS_SIGNING_H
8 |
9 | #include
10 | #include
11 |
12 | struct aws_signing_config_aws;
13 |
14 | struct aws_signing_config_data {
15 | JavaVM *jvm;
16 | struct aws_string *region;
17 | struct aws_string *service;
18 | struct aws_string *signed_body_value;
19 |
20 | jobject java_sign_header_predicate;
21 | struct aws_credentials *credentials;
22 | jobject java_credentials_provider;
23 | };
24 |
25 | /* Initialize the native `config` from Java Object and Keep the required data around with `config_data`. You need to
26 | * clean up the `config_data` after the signing config is not used anymore */
27 | int aws_build_signing_config(
28 | JNIEnv *env,
29 | jobject java_config,
30 | struct aws_signing_config_data *config_data,
31 | struct aws_signing_config_aws *config);
32 |
33 | void aws_signing_config_data_clean_up(struct aws_signing_config_data *data, JNIEnv *env);
34 |
35 | #endif /* AWS_JNI_CRT_AWS_SIGNING_H */
36 |
--------------------------------------------------------------------------------
/src/native/build.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | plugins {
3 | `c`
4 | }
5 |
6 | description = "JNI bindings for the AWS Common Runtime"
7 |
8 | buildDir = File("../../build")
9 |
10 | var buildType = "RelWithDebInfo"
11 | if (project.hasProperty("buildType")) {
12 | buildType = project.property("buildType").toString()
13 | logger.info("Using custom build type: ${buildType}")
14 | }
15 |
16 | val cmakeConfigure = tasks.register("cmakeConfigure") {
17 | var cmakeArgs = listOf(
18 | "-B${buildDir}/cmake-build",
19 | "-H${projectDir}/../../",
20 | "-DCMAKE_BUILD_TYPE=${buildType}",
21 | "-DCMAKE_INSTALL_PREFIX=${buildDir}/cmake-build",
22 | "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
23 | "-DBUILD_DEPS=ON",
24 | "-DBUILD_TESTING=OFF"
25 | )
26 |
27 | inputs.file("../../CMakeLists.txt")
28 | outputs.file("${buildDir}/cmake-build/CMakeCache.txt")
29 |
30 | doLast {
31 | val argsStr = cmakeArgs.joinToString(separator=" ")
32 | logger.info("cmake ${argsStr}")
33 | exec {
34 | executable("cmake")
35 | args(cmakeArgs)
36 | environment(mapOf("JAVA_HOME" to System.getProperty("java.home")))
37 | }
38 | }
39 | }
40 |
41 | val cmakeBuild = tasks.register("cmakeBuild") {
42 | dependsOn(cmakeConfigure)
43 | inputs.file("../../CMakeLists.txt")
44 | inputs.file("${buildDir}/cmake-build/CMakeCache.txt")
45 | inputs.files(fileTree(".").matching {
46 | include(listOf("**/*.c", "**/*.h"))
47 | })
48 | inputs.files(fileTree("../../crt").matching {
49 | include(listOf("**/CMakeLists.txt", "**/*.c", "**/*.h"))
50 | })
51 | outputs.file("${buildDir}/cmake-build/lib/libaws-crt-jni.so")
52 | outputs.upToDateWhen { false } //shared lib doesn't seem to get placed in jar without this
53 |
54 | var cmakeArgs = listOf(
55 | "--build", "${buildDir}/cmake-build",
56 | "--target", "all"
57 | )
58 |
59 | doLast {
60 | val argsStr = cmakeArgs.joinToString(separator=" ")
61 | logger.info("cmake ${argsStr}")
62 | exec {
63 | executable("cmake")
64 | args(cmakeArgs)
65 | }
66 | }
67 | }
68 |
69 | tasks.assemble {
70 | dependsOn(cmakeBuild)
71 | }
72 |
--------------------------------------------------------------------------------
/src/native/credentials.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_CREDENTIALS_H
7 | #define AWS_JNI_CRT_CREDENTIALS_H
8 |
9 | #include
10 |
11 | struct aws_credentials;
12 |
13 | struct aws_credentials *aws_credentials_new_from_java_credentials(JNIEnv *env, jobject java_credentials);
14 | jobject aws_java_credentials_from_native_new(JNIEnv *env, const struct aws_credentials *credentials);
15 |
16 | #endif /* AWS_JNI_CRT_CREDENTIALS_H */
17 |
--------------------------------------------------------------------------------
/src/native/custom_key_op_handler.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | #ifndef AWS_JNI_CRT_CUSTOM_KEY_OP_HANDLER_H
6 | #define AWS_JNI_CRT_CUSTOM_KEY_OP_HANDLER_H
7 |
8 | #include "crt.h"
9 | #include
10 |
11 | struct aws_custom_key_op_handler *aws_custom_key_op_handler_java_new(JNIEnv *env, jobject jni_custom_key_op);
12 |
13 | void aws_custom_key_op_handler_java_release(struct aws_custom_key_op_handler *java_custom_key_op_handler);
14 |
15 | #endif /* AWS_JNI_CRT_CUSTOM_KEY_OP_HANDLER_H */
16 |
--------------------------------------------------------------------------------
/src/native/event_stream_message.h:
--------------------------------------------------------------------------------
1 | #ifndef CRT_EVENT_STREAM_MESSAGE_H
2 | #define CRT_EVENT_STREAM_MESSAGE_H
3 | /**
4 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | * SPDX-License-Identifier: Apache-2.0.
6 | */
7 | #include
8 |
9 | #include
10 | #include
11 |
12 | struct aws_event_stream_rpc_marshalled_message {
13 | struct aws_allocator *allocator;
14 | bool headers_init;
15 | struct aws_array_list headers_list;
16 | struct aws_byte_buf headers_buf;
17 | struct aws_byte_buf payload_buf;
18 | struct aws_byte_buf operation_buf;
19 | struct aws_event_stream_rpc_message_args message_args;
20 | };
21 |
22 | int aws_event_stream_rpc_marshall_message_args_init(
23 | struct aws_event_stream_rpc_marshalled_message *message_args,
24 | struct aws_allocator *allocator,
25 | JNIEnv *env,
26 | jbyteArray headers,
27 | jbyteArray payload,
28 | jbyteArray operation,
29 | jint message_flags,
30 | jint message_type);
31 |
32 | void aws_event_stream_rpc_marshall_message_args_clean_up(struct aws_event_stream_rpc_marshalled_message *message_args);
33 |
34 | jbyteArray aws_event_stream_rpc_marshall_headers_to_byteArray(
35 | struct aws_allocator *allocator,
36 | JNIEnv *env,
37 | struct aws_event_stream_header_value_pair *pair,
38 | size_t length);
39 |
40 | #endif /* CRT_EVENT_STREAM_MESSAGE_H */
41 |
--------------------------------------------------------------------------------
/src/native/http_connection_manager.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_HTTP_CONNECTION_MANAGER_H
7 | #define AWS_JNI_CRT_HTTP_CONNECTION_MANAGER_H
8 |
9 | #include
10 |
11 | struct aws_http_connection;
12 | struct aws_http_connection_manager;
13 | struct aws_http_proxy_options;
14 | struct aws_tls_connection_options;
15 | struct aws_tls_ctx;
16 |
17 | struct aws_http_connection_binding {
18 | JavaVM *jvm;
19 | jobject java_acquire_connection_future;
20 | struct aws_http_connection_manager *manager;
21 | struct aws_http_connection *connection;
22 | };
23 |
24 | #endif /* AWS_JNI_CRT_HTTP_CONNECTION_MANAGER_H */
25 |
--------------------------------------------------------------------------------
/src/native/http_proxy_options.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_HTTP_PROXY_OPTIONS_H
7 | #define AWS_JNI_CRT_HTTP_PROXY_OPTIONS_H
8 |
9 | #include
10 |
11 | struct aws_http_proxy_options;
12 | struct aws_tls_connection_options;
13 | struct aws_tls_ctx;
14 |
15 | void aws_http_proxy_options_jni_init(
16 | JNIEnv *env,
17 | struct aws_http_proxy_options *options,
18 | jint proxy_connection_type,
19 | struct aws_tls_connection_options *tls_options,
20 | jbyteArray proxy_host,
21 | jint proxy_port,
22 | jbyteArray proxy_authorization_username,
23 | jbyteArray proxy_authorization_password,
24 | int proxy_authorization_type,
25 | struct aws_tls_ctx *proxy_tls_ctx);
26 |
27 | void aws_http_proxy_options_jni_clean_up(
28 | JNIEnv *env,
29 | struct aws_http_proxy_options *options,
30 | jbyteArray proxy_host,
31 | jbyteArray proxy_authorization_username,
32 | jbyteArray proxy_authorization_password);
33 |
34 | #endif /* AWS_JNI_CRT_HTTP_PROXY_OPTIONS_H */
35 |
--------------------------------------------------------------------------------
/src/native/http_proxy_options_environment_variable.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #include "crt.h"
7 | #include "java_class_ids.h"
8 |
9 | #include
10 | #include
11 |
12 | #include
13 | #include
14 |
15 | /* on 32-bit platforms, casting pointers to longs throws a warning we don't need */
16 | #if UINTPTR_MAX == 0xffffffff
17 | # if defined(_MSC_VER)
18 | # pragma warning(push)
19 | # pragma warning(disable : 4305) /* 'type cast': truncation from 'jlong' to 'jni_tls_ctx_options *' */
20 | # else
21 | # pragma GCC diagnostic push
22 | # pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
23 | # pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
24 | # endif
25 | #endif
26 |
27 | void aws_http_proxy_environment_variable_setting_jni_init(
28 | struct proxy_env_var_settings *options,
29 | jint environment_variable_proxy_connection_type,
30 | jint environment_variable_type,
31 | struct aws_tls_connection_options *proxy_tls_connection_options) {
32 | options->connection_type = environment_variable_proxy_connection_type;
33 | options->env_var_type = environment_variable_type;
34 | options->tls_options = proxy_tls_connection_options;
35 | }
36 |
37 | #if UINTPTR_MAX == 0xffffffff
38 | # if defined(_MSC_VER)
39 | # pragma warning(pop)
40 | # else
41 | # pragma GCC diagnostic pop
42 | # endif
43 | #endif
44 |
--------------------------------------------------------------------------------
/src/native/http_proxy_options_environment_variable.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_HTTP_PROXY_ENVIRONMENT_VARIABLE_SETTING_H
7 | #define AWS_JNI_CRT_HTTP_PROXY_ENVIRONMENT_VARIABLE_SETTING_H
8 |
9 | #include
10 |
11 | struct proxy_env_var_settings;
12 | struct aws_tls_connection_options;
13 | struct aws_tls_ctx;
14 |
15 | void aws_http_proxy_environment_variable_setting_jni_init(
16 | struct proxy_env_var_settings *options,
17 | jint environment_variable_proxy_connection_type,
18 | jint environment_variable_type,
19 | struct aws_tls_connection_options *proxy_tls_connection_options);
20 |
21 | #endif /* AWS_JNI_CRT_HTTP_PROXY_ENVIRONMENT_VARIABLE_SETTING_H */
22 |
--------------------------------------------------------------------------------
/src/native/http_request_response.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_HTTP_REQUEST_RESPONSE_H
7 | #define AWS_JNI_CRT_HTTP_REQUEST_RESPONSE_H
8 |
9 | #include
10 | #include
11 |
12 | struct aws_http_message;
13 | struct aws_http_stream;
14 | struct aws_byte_buf;
15 | struct aws_atomic_var;
16 |
17 | struct http_stream_binding {
18 | JavaVM *jvm;
19 |
20 | // TEMP: Until Java API changes to match "H1B" native HTTP API,
21 | // create aws_http_message and aws_input_stream under the hood.
22 | struct aws_http_message *native_request;
23 |
24 | jobject java_http_response_stream_handler;
25 | jobject java_http_stream_base;
26 | struct aws_http_stream *native_stream;
27 | struct aws_byte_buf headers_buf;
28 | int response_status;
29 | /* For the native http stream and the Java stream object */
30 | struct aws_atomic_var ref;
31 | };
32 |
33 | jobject aws_java_http_stream_from_native_new(JNIEnv *env, void *opaque, int version);
34 | void aws_java_http_stream_from_native_delete(JNIEnv *env, jobject jHttpStream);
35 |
36 | void *aws_http_stream_binding_release(JNIEnv *env, struct http_stream_binding *binding);
37 | void *aws_http_stream_binding_acquire(struct http_stream_binding *binding);
38 |
39 | // If error occurs, A Java exception is thrown and NULL is returned.
40 | struct http_stream_binding *aws_http_stream_binding_new(JNIEnv *env, jobject java_callback_handler);
41 |
42 | /* Default callbacks using binding */
43 | int aws_java_http_stream_on_incoming_headers_fn(
44 | struct aws_http_stream *stream,
45 | enum aws_http_header_block block_type,
46 | const struct aws_http_header *header_array,
47 | size_t num_headers,
48 | void *user_data);
49 | int aws_java_http_stream_on_incoming_header_block_done_fn(
50 | struct aws_http_stream *stream,
51 | enum aws_http_header_block block_type,
52 | void *user_data);
53 | int aws_java_http_stream_on_incoming_body_fn(
54 | struct aws_http_stream *stream,
55 | const struct aws_byte_cursor *data,
56 | void *user_data);
57 | void aws_java_http_stream_on_stream_complete_fn(struct aws_http_stream *stream, int error_code, void *user_data);
58 | void aws_java_http_stream_on_stream_destroy_fn(void *user_data);
59 |
60 | #endif /* AWS_JNI_CRT_HTTP_REQUEST_RESPONSE_H */
61 |
--------------------------------------------------------------------------------
/src/native/http_request_utils.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #ifndef AWS_JNI_CRT_HTTP_REQUEST_UTILS_H
7 | #define AWS_JNI_CRT_HTTP_REQUEST_UTILS_H
8 |
9 | #include
10 |
11 | #include
12 |
13 | struct aws_allocator;
14 | struct aws_http_header;
15 | struct aws_http_headers;
16 | struct aws_http_message;
17 | struct aws_input_stream;
18 |
19 | struct aws_input_stream *aws_input_stream_new_from_java_http_request_body_stream(
20 | struct aws_allocator *allocator,
21 | JNIEnv *env,
22 | jobject http_request_body_stream);
23 |
24 | struct aws_http_message *aws_http_request_new_from_java_http_request(
25 | JNIEnv *env,
26 | jbyteArray marshalled_request,
27 | jobject jni_body_stream);
28 |
29 | struct aws_http_headers *aws_http_headers_new_from_java_http_headers(JNIEnv *env, jbyteArray marshalled_headers);
30 |
31 | int aws_marshal_http_headers_array_to_dynamic_buffer(
32 | struct aws_byte_buf *buf,
33 | const struct aws_http_header *header_array,
34 | size_t num_headers);
35 |
36 | int aws_marshal_http_headers_to_dynamic_buffer(struct aws_byte_buf *buf, const struct aws_http_headers *headers);
37 |
38 | /* if this fails a java exception has been set. */
39 | int aws_apply_java_http_request_changes_to_native_request(
40 | JNIEnv *env,
41 | jbyteArray marshalled_request,
42 | jobject jni_body_stream,
43 | struct aws_http_message *message);
44 |
45 | /* if this fails a java exception has been set. */
46 | jobject aws_java_http_request_from_native(JNIEnv *env, struct aws_http_message *message, jobject request_body_stream);
47 |
48 | #endif /* AWS_JNI_CRT_HTTP_REQUEST_UTILS_H */
49 |
--------------------------------------------------------------------------------
/src/native/jni.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | #include
6 |
7 | /* Tell the JNI loader that JNI 1.6 (JDK7) is required */
8 | JNIEXPORT
9 | jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
10 | (void)vm;
11 | (void)reserved;
12 | return JNI_VERSION_1_6;
13 | }
14 |
--------------------------------------------------------------------------------
/src/native/logging.h:
--------------------------------------------------------------------------------
1 | #ifndef AWS_JNI_LOGGING_H
2 | #define AWS_JNI_LOGGING_H
3 |
4 | /**
5 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 | * SPDX-License-Identifier: Apache-2.0.
7 | */
8 |
9 | #include
10 |
11 | /*******************************************************************************
12 | * aws_jni_cleanup_logging - cleans up the native logger; invoked on atexit
13 | ******************************************************************************/
14 | void aws_jni_cleanup_logging(void);
15 |
16 | #endif /* AWS_JNI_LOGGING_H */
17 |
--------------------------------------------------------------------------------
/src/native/mqtt5_client_jni.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | #ifndef AWS_JNI_CLIENT_H
6 | #define AWS_JNI_CLIENT_H
7 |
8 | #include
9 |
10 | #include
11 |
12 | struct aws_mqtt5_client;
13 |
14 | struct aws_mqtt5_client_java_jni {
15 | struct aws_mqtt5_client *client;
16 | jobject jni_client;
17 | JavaVM *jvm;
18 |
19 | struct aws_tls_connection_options tls_options;
20 | struct aws_tls_connection_options http_proxy_tls_options;
21 |
22 | jobject jni_publish_events;
23 | jobject jni_lifecycle_events;
24 | };
25 |
26 | #endif /* AWS_JNI_CLIENT_H */
27 |
--------------------------------------------------------------------------------
/src/native/mqtt_client.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | #include
6 |
7 | #include
8 |
9 | #include "crt.h"
10 | #include "java_class_ids.h"
11 |
12 | /* on 32-bit platforms, casting pointers to longs throws a warning we don't need */
13 | #if UINTPTR_MAX == 0xffffffff
14 | # if defined(_MSC_VER)
15 | # pragma warning(push)
16 | # pragma warning(disable : 4305) /* 'type cast': truncation from 'jlong' to 'jni_tls_ctx_options *' */
17 | # else
18 | # pragma GCC diagnostic push
19 | # pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
20 | # pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
21 | # endif
22 | #endif
23 |
24 | JNIEXPORT jlong JNICALL
25 | Java_software_amazon_awssdk_crt_mqtt_MqttClient_mqttClientNew(JNIEnv *env, jclass jni_class, jlong jni_bootstrap) {
26 | (void)jni_class;
27 | aws_cache_jni_ids(env);
28 |
29 | struct aws_client_bootstrap *bootstrap = (struct aws_client_bootstrap *)jni_bootstrap;
30 | if (!bootstrap) {
31 | aws_jni_throw_runtime_exception(env, "Invalid ClientBootstrap");
32 | return (jlong)NULL;
33 | }
34 |
35 | struct aws_allocator *allocator = aws_jni_get_allocator();
36 | struct aws_mqtt_client *client = aws_mqtt_client_new(allocator, bootstrap);
37 | if (client == NULL) {
38 | aws_jni_throw_runtime_exception(env, "MqttClient.mqtt_client_init: aws_mqtt_client_new failed");
39 | return (jlong)NULL;
40 | }
41 |
42 | return (jlong)client;
43 | }
44 |
45 | JNIEXPORT void JNICALL Java_software_amazon_awssdk_crt_mqtt_MqttClient_mqttClientDestroy(
46 | JNIEnv *env,
47 | jclass jni_class,
48 | jlong jni_mqtt_client) {
49 | (void)jni_class;
50 | aws_cache_jni_ids(env);
51 |
52 | struct aws_mqtt_client *client = (struct aws_mqtt_client *)jni_mqtt_client;
53 | if (!client) {
54 | aws_jni_throw_runtime_exception(env, "MqttClient.mqtt_client_destroy: Invalid/null client");
55 | return;
56 | }
57 |
58 | aws_mqtt_client_release(client);
59 | }
60 |
61 | #if UINTPTR_MAX == 0xffffffff
62 | # if defined(_MSC_VER)
63 | # pragma warning(pop)
64 | # else
65 | # pragma GCC diagnostic pop
66 | # endif
67 | #endif
68 |
--------------------------------------------------------------------------------
/src/native/mqtt_connection.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 | #ifndef AWS_JAVA_CRT_MQTT_CONNECTION_H
6 | #define AWS_JAVA_CRT_MQTT_CONNECTION_H
7 |
8 | #include
9 |
10 | #include
11 | #include
12 | #include
13 | #include
14 |
15 | struct aws_mqtt_client;
16 | struct aws_mqtt_client_connection;
17 | struct mqtt_jni_connection;
18 |
19 | /*******************************************************************************
20 | * mqtt_jni_async_callback - carries an AsyncCallback around as user data to mqtt
21 | * async ops, and is used to deliver callbacks. Also hangs on to JNI references
22 | * to buffers and strings that need to outlive the request
23 | ******************************************************************************/
24 | struct mqtt_jni_async_callback {
25 | struct mqtt_jni_connection *connection;
26 | jobject async_callback;
27 | struct aws_byte_buf buffer; /* payloads or other pinned resources go in here, freed when callback is delivered */
28 | };
29 |
30 | /*******************************************************************************
31 | * mqtt_jni_connection - represents an aws_mqtt_client_connection to Java
32 | ******************************************************************************/
33 | struct mqtt_jni_connection {
34 | struct aws_mqtt_client *client; /* Provided to mqtt_connect */
35 | struct aws_mqtt_client_connection *client_connection;
36 | struct aws_socket_options socket_options;
37 | struct aws_tls_connection_options tls_options;
38 |
39 | JavaVM *jvm;
40 | jweak java_mqtt_connection; /* MqttClientConnection instance */
41 | struct mqtt_jni_async_callback *on_message;
42 |
43 | struct aws_atomic_var ref_count;
44 | };
45 |
46 | #endif /* AWS_JAVA_CRT_MQTT_CONNECTION_H */
47 |
--------------------------------------------------------------------------------
/src/native/process.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #include
7 | #include
8 |
9 | #include "java_class_ids.h"
10 |
11 | JNIEXPORT
12 | jint JNICALL Java_software_amazon_awssdk_crt_Process_processGetPid(JNIEnv *env, jclass jni_crt_class) {
13 | (void)jni_crt_class;
14 | aws_cache_jni_ids(env);
15 |
16 | return (jint)aws_get_pid();
17 | }
18 |
19 | JNIEXPORT
20 | jlong JNICALL
21 | Java_software_amazon_awssdk_crt_Process_processGetMaxIOHandlesSoftLimit(JNIEnv *env, jclass jni_crt_class) {
22 | (void)jni_crt_class;
23 | aws_cache_jni_ids(env);
24 |
25 | return (jlong)aws_get_soft_limit_io_handles();
26 | }
27 |
28 | JNIEXPORT
29 | jlong JNICALL
30 | Java_software_amazon_awssdk_crt_Process_processGetMaxIOHandlesHardLimit(JNIEnv *env, jclass jni_crt_class) {
31 | (void)jni_crt_class;
32 | aws_cache_jni_ids(env);
33 |
34 | return (jlong)aws_get_hard_limit_io_handles();
35 | }
36 |
37 | JNIEXPORT
38 | jboolean JNICALL Java_software_amazon_awssdk_crt_Process_processSetMaxIOHandlesSoftLimit(
39 | JNIEnv *env,
40 | jclass jni_crt_class,
41 | jlong max_handles) {
42 | (void)jni_crt_class;
43 | (void)max_handles;
44 | aws_cache_jni_ids(env);
45 |
46 | return aws_set_soft_limit_io_handles((size_t)max_handles) == AWS_OP_SUCCESS;
47 | }
48 |
--------------------------------------------------------------------------------
/src/native/retry_utils.h:
--------------------------------------------------------------------------------
1 | #ifndef AWS_JNI_RETRY_UTILS_H
2 | #define AWS_JNI_RETRY_UTILS_H
3 |
4 | /**
5 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 | * SPDX-License-Identifier: Apache-2.0.
7 | */
8 |
9 | #include
10 |
11 | struct aws_exponential_backoff_retry_options;
12 | struct aws_standard_retry_options;
13 |
14 | int aws_exponential_backoff_retry_options_from_java(
15 | JNIEnv *env,
16 | jobject jni_backoff_retry_options,
17 | struct aws_exponential_backoff_retry_options *backoff_retry_options);
18 |
19 | int aws_standard_retry_options_from_java(
20 | JNIEnv *env,
21 | jobject jni_standard_retry_options,
22 | struct aws_standard_retry_options *standard_retry_options);
23 |
24 | bool aws_exponential_backoff_retry_options_equals(
25 | const struct aws_exponential_backoff_retry_options *options,
26 | const struct aws_exponential_backoff_retry_options *expected_options);
27 |
28 | bool aws_standard_retry_options_equals(
29 | const struct aws_standard_retry_options *options,
30 | const struct aws_standard_retry_options *expected_options);
31 |
32 | #endif /* AWS_JNI_RETRY_STRATEGY_H */
33 |
--------------------------------------------------------------------------------
/src/native/system_info.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #include
7 |
8 | #include
9 |
10 | #include "crt.h"
11 | #include "java_class_ids.h"
12 |
13 | JNIEXPORT
14 | jint JNICALL Java_software_amazon_awssdk_crt_SystemInfo_processorCount(JNIEnv *env, jclass cls) {
15 | (void)cls;
16 | aws_cache_jni_ids(env);
17 |
18 | return (jint)aws_system_info_processor_count();
19 | }
20 |
21 | JNIEXPORT
22 | jshort JNICALL Java_software_amazon_awssdk_crt_SystemInfo_cpuGroupCount(JNIEnv *env, jclass cls) {
23 | (void)cls;
24 | aws_cache_jni_ids(env);
25 |
26 | return aws_get_cpu_group_count();
27 | }
28 |
29 | JNIEXPORT
30 | jobjectArray JNICALL
31 | Java_software_amazon_awssdk_crt_SystemInfo_cpuInfoForGroup(JNIEnv *env, jclass cls, jshort groupIdx) {
32 | (void)cls;
33 | aws_cache_jni_ids(env);
34 |
35 | size_t cpu_count = aws_get_cpu_count_for_group(groupIdx);
36 |
37 | struct aws_cpu_info *cpu_info = aws_mem_calloc(aws_default_allocator(), cpu_count, sizeof(struct aws_cpu_info));
38 | AWS_FATAL_ASSERT(cpu_info && "allocation failed in Java_software_amazon_awssdk_crt_SystemInfo_getCpuIdsForGroup");
39 |
40 | aws_get_cpu_ids_for_group(groupIdx, cpu_info, cpu_count);
41 |
42 | jobjectArray cpu_info_array =
43 | (*env)->NewObjectArray(env, (jsize)cpu_count, cpu_info_properties.cpu_info_class, NULL);
44 |
45 | for (size_t i = 0; i < cpu_count; ++i) {
46 | jobject cpu_info_obj = (*env)->NewObject(
47 | env,
48 | cpu_info_properties.cpu_info_class,
49 | cpu_info_properties.cpu_info_constructor,
50 | cpu_info[i].cpu_id,
51 | cpu_info[i].suspected_hyper_thread);
52 | (*env)->SetObjectArrayElement(env, cpu_info_array, (jsize)i, cpu_info_obj);
53 | (*env)->DeleteLocalRef(env, cpu_info_obj);
54 | }
55 |
56 | aws_mem_release(aws_default_allocator(), cpu_info);
57 |
58 | return cpu_info_array;
59 | }
60 |
--------------------------------------------------------------------------------
/src/native/tls_context_pkcs11_options.h:
--------------------------------------------------------------------------------
1 | #ifndef AWS_JNI_CRT_TLS_CONTEXT_PKCS11_OPTIONS_H
2 | #define AWS_JNI_CRT_TLS_CONTEXT_PKCS11_OPTIONS_H
3 | /**
4 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | * SPDX-License-Identifier: Apache-2.0.
6 | */
7 |
8 | #include
9 |
10 | struct aws_tls_ctx_pkcs11_options;
11 |
12 | /* Create a aws_tls_ctx_pkcs11_options from a TlsContextPkcs11Options java object.
13 | * All values are copied out of the Java object and stored in this allocation,
14 | * there's no need to keep the java object around.
15 | * This MUST be destroyed via aws_pkcs11_tls_options_from_java_destroy().
16 | * Returns NULL and throws a java exception if something goes wrong. */
17 | struct aws_tls_ctx_pkcs11_options *aws_tls_ctx_pkcs11_options_from_java_new(JNIEnv *env, jobject options_jni);
18 |
19 | void aws_tls_ctx_pkcs11_options_from_java_destroy(struct aws_tls_ctx_pkcs11_options *options);
20 |
21 | #endif /* AWS_JNI_CRT_TLS_CONTEXT_PKCS11_OPTIONS_H */
22 |
--------------------------------------------------------------------------------
/src/native/tls_ctx.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | #include
7 |
8 | #include
9 | #include
10 |
11 | #include "crt.h"
12 | #include "java_class_ids.h"
13 |
14 | /* on 32-bit platforms, casting pointers to longs throws a warning we don't need */
15 | #if UINTPTR_MAX == 0xffffffff
16 | # if defined(_MSC_VER)
17 | # pragma warning(push)
18 | # pragma warning(disable : 4305) /* 'type cast': truncation from 'jlong' to 'jni_tls_ctx_options *' */
19 | # else
20 | # pragma GCC diagnostic push
21 | # pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
22 | # pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
23 | # endif
24 | #endif
25 |
26 | JNIEXPORT
27 | jlong JNICALL
28 | Java_software_amazon_awssdk_crt_io_TlsContext_tlsContextNew(JNIEnv *env, jclass jni_class, jlong jni_options) {
29 | (void)jni_class;
30 | aws_cache_jni_ids(env);
31 |
32 | struct aws_tls_ctx_options *options = (struct aws_tls_ctx_options *)jni_options;
33 | if (!options) {
34 | aws_jni_throw_runtime_exception(env, "TlsContext.tls_ctx_new: Invalid TlsOptions");
35 | return (jlong)NULL;
36 | }
37 |
38 | struct aws_allocator *allocator = aws_jni_get_allocator();
39 | struct aws_tls_ctx *tls_ctx = aws_tls_client_ctx_new(allocator, options);
40 | if (!tls_ctx) {
41 | aws_jni_throw_runtime_exception(env, "TlsContext.tls_ctx_new: Failed to create new aws_tls_ctx");
42 | return (jlong)NULL;
43 | }
44 | return (jlong)tls_ctx;
45 | }
46 |
47 | JNIEXPORT
48 | void JNICALL
49 | Java_software_amazon_awssdk_crt_io_TlsContext_tlsContextDestroy(JNIEnv *env, jclass jni_class, jlong jni_ctx) {
50 | (void)jni_class;
51 | aws_cache_jni_ids(env);
52 |
53 | struct aws_tls_ctx *tls_ctx = (struct aws_tls_ctx *)jni_ctx;
54 | if (!tls_ctx) {
55 | return;
56 | }
57 |
58 | aws_tls_ctx_release(tls_ctx);
59 | }
60 |
61 | #if UINTPTR_MAX == 0xffffffff
62 | # if defined(_MSC_VER)
63 | # pragma warning(pop)
64 | # else
65 | # pragma GCC diagnostic pop
66 | # endif
67 | #endif
68 |
--------------------------------------------------------------------------------
/src/test/android/testapp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | .gradle
3 | /local.properties
--------------------------------------------------------------------------------
/src/test/android/testapp/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/src/test/android/testapp/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Necessary file for the testapp gradle project
3 | */
--------------------------------------------------------------------------------
/src/test/android/testapp/src/androidTest/assets/.gitignore:
--------------------------------------------------------------------------------
1 | *.txt
2 | *.pem
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/assets/.gitignore:
--------------------------------------------------------------------------------
1 | *.txt
2 | *.pem
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/java/software/amazon/awssdk/crttest/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crttest
7 |
8 | import androidx.appcompat.app.AppCompatActivity
9 |
10 | /*
11 | * The "TEST APP" is merely a shell that contains the aws-crt-java android library and is used by the
12 | * instrumentation test package to test against. There is nothing here. The assets folder will contain the
13 | * files generated in GitHub CI for testing and the res folder contains the bare essentials for an android app.
14 | */
15 |
16 | class MainActivity : AppCompatActivity() {
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
21 |
22 |
40 |
41 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CRTAndroidTest
3 |
4 |
--------------------------------------------------------------------------------
/src/test/android/testapp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/ClientBootstrapTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.test;
7 |
8 | import org.junit.Test;
9 | import software.amazon.awssdk.crt.CrtResource;
10 | import software.amazon.awssdk.crt.CrtRuntimeException;
11 | import software.amazon.awssdk.crt.io.ClientBootstrap;
12 | import software.amazon.awssdk.crt.io.EventLoopGroup;
13 | import software.amazon.awssdk.crt.io.HostResolver;
14 |
15 | import java.util.concurrent.ExecutionException;
16 |
17 | import static org.junit.Assert.*;
18 |
19 | public class ClientBootstrapTest extends CrtTestFixture {
20 | public ClientBootstrapTest() {}
21 |
22 | @Test
23 | public void testCreateDestroy() throws ExecutionException, InterruptedException {
24 | EventLoopGroup elg = new EventLoopGroup(1);
25 | HostResolver hostResolver = new HostResolver(elg);
26 | ClientBootstrap bootstrap = new ClientBootstrap(elg, hostResolver);
27 |
28 | assertNotNull(bootstrap);
29 | bootstrap.close();
30 | bootstrap.getShutdownCompleteFuture().get();
31 | hostResolver.close();
32 | elg.close();
33 | }
34 | };
35 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/CrtTestContext.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.test;
7 |
8 | // Encapsulates any platform-specific configuration for tests
9 | // TODO remove this. We are going to be using System Properties for tests
10 | public class CrtTestContext {
11 | // Trust store PEM blob
12 | public byte[] trustStore = null;
13 | // IoT Thing certificate for testing
14 | public byte[] iotClientCertificate = null;
15 | // IoT Thing private key for testing
16 | public byte[] iotClientPrivateKey = null;
17 | // IoT Thing ecc certificate for testing
18 | public byte[] iotClientECCCertificate = null;
19 | // IoT Thing ecc private key for testing
20 | public byte[] iotClientECCPrivateKey = null;
21 | // IoT ATS endpoint for testing
22 | public String iotEndpoint = null;
23 | // IoT CA Root
24 | public byte[] iotCARoot = null;
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/EccKeyPairTest.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.test;
2 |
3 | import org.junit.Test;
4 | import software.amazon.awssdk.crt.auth.credentials.Credentials;
5 | import software.amazon.awssdk.crt.cal.EccKeyPair;
6 |
7 | import static org.junit.Assert.assertNotNull;
8 | import static org.junit.Assert.assertTrue;
9 |
10 | public class EccKeyPairTest extends CrtTestFixture {
11 | public EccKeyPairTest() {}
12 |
13 | private static byte[] TEST_ACCESS_KEY_ID = "AKISORANDOMAASORANDOM".getBytes();
14 | private static byte[] TEST_SECRET_ACCESS_KEY = "q+jcrXGc+0zWN6uzclKVhvMmUsIfRPa4rlRandom".getBytes();
15 |
16 | static Credentials credentials = new Credentials(TEST_ACCESS_KEY_ID, TEST_SECRET_ACCESS_KEY, null);
17 |
18 | @Test
19 | public void testCreateDestroy() {
20 | try (EccKeyPair keyPair = EccKeyPair.newDeriveFromCredentials(credentials, EccKeyPair.AwsEccCurve.AWS_ECDSA_P256)) {
21 | assertNotNull(keyPair);
22 | }
23 | }
24 |
25 | @Test
26 | public void testSignMessage() {
27 | try (EccKeyPair keyPair = EccKeyPair.newDeriveFromCredentials(credentials, EccKeyPair.AwsEccCurve.AWS_ECDSA_P256)) {
28 | byte[] signatureBytes = keyPair.signMessage("".getBytes());
29 | assertTrue(signatureBytes.length > 0);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/EventLoopGroupTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.test;
7 |
8 | import org.junit.Test;
9 | import static org.junit.Assert.assertNotNull;
10 | import static org.junit.Assert.assertTrue;
11 | import static org.junit.Assert.fail;
12 | import software.amazon.awssdk.crt.*;
13 | import software.amazon.awssdk.crt.io.EventLoopGroup;
14 |
15 | public class EventLoopGroupTest extends CrtTestFixture {
16 | public EventLoopGroupTest() {}
17 |
18 | @Test
19 | public void testCreateDestroy() {
20 | try (EventLoopGroup elg = new EventLoopGroup(1)) {
21 | assertNotNull(elg);
22 | assertTrue(!elg.isNull());
23 | } catch (CrtRuntimeException ex) {
24 | fail(ex.getMessage());
25 | }
26 | }
27 |
28 | @Test
29 | public void testCreateDestroyWithCpuGroup() {
30 | try (EventLoopGroup elg = new EventLoopGroup(0,2)) {
31 | assertNotNull(elg);
32 | assertTrue(!elg.isNull());
33 | } catch (CrtRuntimeException ex) {
34 | fail(ex.getMessage());
35 | }
36 | }
37 | };
38 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/FailFastListener.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.test;
2 |
3 | import org.junit.runner.notification.Failure;
4 | import org.junit.runner.notification.RunListener;
5 |
6 | public class FailFastListener extends RunListener {
7 | public void testFailure(Failure failure) throws Exception {
8 | System.err.println("FAILURE: " + failure);
9 | System.exit(-1);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/InitTest.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.test;
2 |
3 | import org.junit.Test;
4 |
5 | /*
6 | This test exercises a case that used to deadlock the CRT. To properly exercise init, the test must be run by
7 | itself; a successful run when other tests have run doesn't mean anything.
8 |
9 | For CI, we explicitly run this test by itself as part of `.builder/actions/aws_crt_java_test.py`
10 | */
11 | public class InitTest {
12 |
13 | @Test
14 | public void testConcurrentInitForDeadlock() {
15 |
16 | for (int i = 0; i < 100; i++) {
17 | try {
18 | new Thread(() -> {
19 | try {
20 | Class.forName("software.amazon.awssdk.crt.CRT");
21 | } catch (ClassNotFoundException e) {
22 | throw new RuntimeException(e);
23 | }
24 | }).start();
25 | Class.forName("software.amazon.awssdk.crt.CrtResource");
26 | } catch (Exception e) {
27 | throw new RuntimeException(e);
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/JniExceptionTest.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.test;
2 |
3 | import org.junit.Test;
4 | import software.amazon.awssdk.crt.CRT;
5 |
6 | public class JniExceptionTest extends CrtTestFixture {
7 | public JniExceptionTest() {}
8 |
9 | @Test(expected = RuntimeException.class)
10 | public void testExceptionCheck() {
11 | CRT.checkJniExceptionContract(false);
12 | }
13 |
14 | @Test
15 | public void testExceptionClear() {
16 | CRT.checkJniExceptionContract(true);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/PackageInfoTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.test;
7 |
8 | import org.junit.Test;
9 | import org.junit.Assert;
10 | import software.amazon.awssdk.crt.utils.PackageInfo;
11 |
12 | public class PackageInfoTest extends CrtTestFixture {
13 | public PackageInfoTest() {}
14 |
15 | @Test
16 | public void testPackageInfo() {
17 | PackageInfo pkgInfo = new PackageInfo();
18 | Assert.assertNotEquals("UNKNOWN", pkgInfo.version.toString());
19 | Assert.assertEquals(0, pkgInfo.version.major);
20 | Assert.assertEquals(0, pkgInfo.version.minor);
21 | Assert.assertEquals(0, pkgInfo.version.patch);
22 | Assert.assertEquals("UNITTEST", pkgInfo.version.tag);
23 | }
24 | };
25 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/ProcessTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.test;
7 |
8 | import org.junit.Test;
9 |
10 | import static org.junit.Assert.assertEquals;
11 | import static org.junit.Assert.assertTrue;
12 |
13 | import software.amazon.awssdk.crt.CrtRuntimeException;
14 | import software.amazon.awssdk.crt.Process;
15 |
16 | public class ProcessTest extends CrtTestFixture {
17 | public ProcessTest() {}
18 |
19 | @Test
20 | public void testGetPid() {
21 | int pid = Process.getPid();
22 | assertTrue(pid > 0);
23 | }
24 |
25 | @Test
26 | public void testGetIOHandleLimits() {
27 | long softLimit = Process.getMaxIOHandlesSoftLimit();
28 | long hardLimit = Process.getMaxIOHandlesHardLimit();
29 |
30 | assertTrue(softLimit > 0);
31 | assertTrue(hardLimit >= softLimit);
32 | }
33 |
34 | @Test
35 | public void testSetSoftIOHandleLimits() {
36 | long softLimit = Process.getMaxIOHandlesSoftLimit();
37 | long hardLimit = Process.getMaxIOHandlesHardLimit();
38 |
39 | assertTrue(softLimit > 0);
40 | assertTrue(hardLimit >= softLimit);
41 |
42 | try {
43 | Process.setMaxIOHandlesSoftLimit(softLimit - 1);
44 | } catch (CrtRuntimeException ex) {
45 | // make sure it's the not-implemented exception if it was thrown.
46 | assertEquals("AWS_ERROR_UNIMPLEMENTED", ex.errorName);
47 | }
48 | }
49 | };
50 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/ServerBootstrapTest.java:
--------------------------------------------------------------------------------
1 | package software.amazon.awssdk.crt.test;
2 |
3 | import org.junit.Test;
4 | import software.amazon.awssdk.crt.io.EventLoopGroup;
5 | import software.amazon.awssdk.crt.io.ServerBootstrap;
6 |
7 | import java.util.concurrent.ExecutionException;
8 |
9 | import static org.junit.Assert.assertNotNull;
10 |
11 | public class ServerBootstrapTest extends CrtTestFixture {
12 | public ServerBootstrapTest() {}
13 |
14 | @Test
15 | public void testCreateDestroy() throws ExecutionException, InterruptedException {
16 | EventLoopGroup elg = new EventLoopGroup(1);
17 | ServerBootstrap bootstrap = new ServerBootstrap(elg);
18 |
19 | assertNotNull(bootstrap);
20 | bootstrap.close();
21 | elg.close();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/software/amazon/awssdk/crt/test/SystemInfoTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | * SPDX-License-Identifier: Apache-2.0.
4 | */
5 |
6 | package software.amazon.awssdk.crt.test;
7 |
8 | import org.junit.Test;
9 |
10 | import software.amazon.awssdk.crt.*;
11 |
12 | import static org.junit.Assert.*;
13 |
14 | import org.junit.Assume;
15 |
16 | public class SystemInfoTest extends CrtTestFixture {
17 | public SystemInfoTest() { }
18 |
19 | @Test
20 | public void testCpuIteration() {
21 | int processorCount = SystemInfo.getProcessorCount();
22 | assertNotEquals(0, processorCount);
23 |
24 | short cpuGroupCount = SystemInfo.getCpuGroupCount();
25 | assertNotEquals(0, cpuGroupCount);
26 |
27 | int iteratedCpuCount = 0;
28 | for (short i = 0; i < cpuGroupCount; ++i) {
29 | SystemInfo.CpuInfo[] cpus = SystemInfo.getCpuInfoForGroup(i);
30 | assertNotNull(cpus);
31 | assertNotEquals(0, cpus.length);
32 |
33 | for (SystemInfo.CpuInfo cpuInfo : cpus) {
34 | iteratedCpuCount++;
35 | System.out.println(String.format("Found Cpu %d in group %d. Suspected hyper-thread? %s", cpuInfo.cpuId, i, cpuInfo.isSuspectedHyperThread ? "yes" : "no"));
36 | }
37 | }
38 |
39 | assertEquals(processorCount, iteratedCpuCount);
40 | }
41 |
42 | @Test
43 | public void testIsFIPS() {
44 | Assume.assumeTrue(System.getenv("CRT_FIPS") != null);
45 | assertTrue(CRT.isFIPS());
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/utils/Canary/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 | 4.0.0
6 |
7 | canary.mqtt5
8 | mqtt5
9 | 1.0.0-SNAPSHOT
10 |
11 |
12 | UTF-8
13 | 1.8
14 | 1.8
15 |
16 |
17 |
18 |
19 | software.amazon.awssdk.crt
20 | aws-crt
21 | 1.0.0-SNAPSHOT
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------