1 package software.amazon.awssdk.crt.eventstream; 2 3 import java.nio.ByteBuffer; 4 import java.util.ArrayList; 5 import java.util.List; 6 import java.util.concurrent.CompletableFuture; 7 8 /** 9 * Handler interface for responding to continuation events. It's auto closable. 10 * By default, onContinuationClosed() releases the underlying resource. 11 */ 12 public abstract class ClientConnectionContinuationHandler implements AutoCloseable { 13 // this gets set upon creation of the using ClientConnectionContinuation 14 protected ClientConnectionContinuation continuation; 15 private CompletableFuture<Void> closedFuture = new CompletableFuture<>(); 16 17 /** 18 * Invoked when a message is received on a continuation. 19 * @param headers List of EventStream headers for the message received. 20 * @param payload Payload for the message received 21 * @param messageType message type for the message 22 * @param messageFlags message flags for the message 23 */ onContinuationMessage(final List<Header> headers, final byte[] payload, final MessageType messageType, int messageFlags)24 protected abstract void onContinuationMessage(final List<Header> headers, 25 final byte[] payload, final MessageType messageType, int messageFlags); 26 27 /** 28 * Invoked from JNI. Converts the native data into usable java objects and invokes 29 * onContinuationMessage(). 30 */ onContinuationMessageShim(final byte[] headersPayload, final byte[] payload, int messageType, int messageFlags)31 private void onContinuationMessageShim(final byte[] headersPayload, final byte[] payload, 32 int messageType, int messageFlags) { 33 List<Header> headers = new ArrayList<>(); 34 35 ByteBuffer headersBuffer = ByteBuffer.wrap(headersPayload); 36 while (headersBuffer.hasRemaining()) { 37 Header header = Header.fromByteBuffer(headersBuffer); 38 headers.add(header); 39 } 40 41 onContinuationMessage(headers, payload, MessageType.fromEnumValue(messageType), messageFlags); 42 } 43 44 /** 45 * By default closes the underlying resource. If you override this function, be sure to 46 * either call close() manually or invoke super.onContinuationClosed() before returning. 47 */ onContinuationClosed()48 protected void onContinuationClosed() { 49 this.close(); 50 } 51 52 /** 53 * Invoked from JNI. Calls onContinuationClosed(). 54 */ onContinuationClosedShim()55 void onContinuationClosedShim() { 56 onContinuationClosed(); 57 closedFuture.complete(null); 58 } 59 60 /** 61 * @return a future that will be completed upon the continuation being closed. 62 */ getContinuationClosedFuture()63 public CompletableFuture<Void> getContinuationClosedFuture() { 64 return closedFuture; 65 } 66 67 @Override close()68 public void close() { 69 if (continuation != null) { 70 continuation.decRef(); 71 continuation = null; 72 } 73 } 74 } 75