Search in sources :

Example 11 with CrtRuntimeException

use of software.amazon.awssdk.crt.CrtRuntimeException in project aws-crt-java by awslabs.

the class MqttClientConnection method connect.

/**
 * Connect to the service endpoint and start a session
 *
 * @return Future result is true if resuming a session, false if clean session
 * @throws MqttException If the port is out of range
 */
public CompletableFuture<Boolean> connect() throws MqttException {
    TlsContext tls = config.getMqttClient().getTlsContext();
    // Just clamp the pingTimeout, no point in throwing
    short pingTimeout = (short) Math.max(0, Math.min(config.getPingTimeoutMs(), Short.MAX_VALUE));
    short port = (short) config.getPort();
    if (port > Short.MAX_VALUE || port <= 0) {
        throw new MqttException("Port must be betweeen 0 and " + Short.MAX_VALUE);
    }
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    connectAck = AsyncCallback.wrapFuture(future, null);
    SocketOptions socketOptions = config.getSocketOptions();
    try {
        mqttClientConnectionConnect(getNativeHandle(), config.getEndpoint(), port, socketOptions != null ? socketOptions.getNativeHandle() : 0, tls != null ? tls.getNativeHandle() : 0, config.getClientId(), config.getCleanSession(), config.getKeepAliveSecs(), pingTimeout, config.getProtocolOperationTimeoutMs());
    } catch (CrtRuntimeException ex) {
        future.completeExceptionally(ex);
    }
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) TlsContext(software.amazon.awssdk.crt.io.TlsContext)

Example 12 with CrtRuntimeException

use of software.amazon.awssdk.crt.CrtRuntimeException in project aws-iot-device-sdk-java-v2 by aws.

the class RawConnect method main.

public static void main(String[] args) {
    cmdUtils = new CommandLineUtils();
    cmdUtils.registerProgramName("RawConnect");
    cmdUtils.addCommonMQTTCommands();
    cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
    cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
    cmdUtils.addCommonProxyCommands();
    cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
    cmdUtils.registerCommand("username", "<str>", "Username to use as part of the connection/authentication process.");
    cmdUtils.registerCommand("password", "<str>", "Password to use as part of the connection/authentication process.");
    cmdUtils.registerCommand("protocol", "<str>", "ALPN protocol to use (optional, default='x-amzn-mqtt-ca').");
    cmdUtils.registerCommand("auth_params", "<comma delimited list>", "Comma delimited list of auth parameters. For websockets these will be set as headers. " + "For raw mqtt these will be appended to user_name. (optional)");
    cmdUtils.sendArguments(args);
    String endpoint = cmdUtils.getCommandRequired("endpoint", "");
    String clientId = cmdUtils.getCommandOrDefault("client_id", "test-" + UUID.randomUUID().toString());
    String caPath = cmdUtils.getCommandOrDefault("ca_file", "");
    String certPath = cmdUtils.getCommandRequired("cert", "");
    String keyPath = cmdUtils.getCommandRequired("key", "");
    String proxyHost = cmdUtils.getCommandOrDefault("proxy_host", "");
    int proxyPort = Integer.parseInt(cmdUtils.getCommandOrDefault("proxy_port", "8080"));
    String userName = cmdUtils.getCommandRequired("username", "");
    String password = cmdUtils.getCommandRequired("password", "");
    String protocolName = cmdUtils.getCommandOrDefault("protocol", "x-amzn-mqtt-ca");
    List<String> authParams = null;
    if (cmdUtils.hasCommand("auth_params")) {
        authParams = Arrays.asList(cmdUtils.getCommand("auth_params").split("\\s*,\\s*"));
    }
    MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {

        @Override
        public void onConnectionInterrupted(int errorCode) {
            if (errorCode != 0) {
                System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
            }
        }

        @Override
        public void onConnectionResumed(boolean sessionPresent) {
            System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
        }
    };
    if (authParams != null && authParams.size() > 0) {
        if (userName.length() > 0) {
            StringBuilder usernameBuilder = new StringBuilder();
            usernameBuilder.append(userName);
            usernameBuilder.append("?");
            for (int i = 0; i < authParams.size(); ++i) {
                usernameBuilder.append(authParams.get(i));
                if (i + 1 < authParams.size()) {
                    usernameBuilder.append("&");
                }
            }
            userName = usernameBuilder.toString();
        }
    }
    try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsFromPath(certPath, keyPath)) {
        if (caPath != null) {
            tlsContextOptions.overrideDefaultTrustStoreFromPath(null, caPath);
        }
        int port = 8883;
        if (TlsContextOptions.isAlpnSupported()) {
            port = 443;
            tlsContextOptions.withAlpnList(protocolName);
        }
        try (TlsContext tlsContext = new TlsContext(tlsContextOptions);
            MqttClient client = new MqttClient(tlsContext);
            MqttConnectionConfig config = new MqttConnectionConfig()) {
            config.setMqttClient(client);
            config.setClientId(clientId);
            config.setConnectionCallbacks(callbacks);
            config.setCleanSession(true);
            config.setEndpoint(endpoint);
            config.setPort(port);
            if (userName != null && userName.length() > 0) {
                config.setLogin(userName, password);
            }
            try (MqttClientConnection connection = new MqttClientConnection(config)) {
                // Connect and disconnect using the connection we created
                // (see sampleConnectAndDisconnect for implementation)
                cmdUtils.sampleConnectAndDisconnect(connection);
            }
        }
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        System.out.println("Exception encountered: " + ex.toString());
    }
    CrtResource.waitForNoResources();
    System.out.println("Complete!");
}
Also used : CommandLineUtils(utils.commandlineutils.CommandLineUtils) TlsContextOptions(software.amazon.awssdk.crt.io.TlsContextOptions) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) TlsContext(software.amazon.awssdk.crt.io.TlsContext) ExecutionException(java.util.concurrent.ExecutionException)

Example 13 with CrtRuntimeException

use of software.amazon.awssdk.crt.CrtRuntimeException in project aws-iot-device-sdk-java-v2 by aws.

the class ShadowSample method main.

public static void main(String[] args) {
    cmdUtils = new CommandLineUtils();
    cmdUtils.registerProgramName("ShadowSample");
    cmdUtils.addCommonMQTTCommands();
    cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
    cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
    cmdUtils.registerCommand("port", "<int>", "Port to use (optional, default='8883').");
    cmdUtils.registerCommand("thing_name", "<str>", "The name of the IoT thing.");
    cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*')");
    cmdUtils.sendArguments(args);
    thingName = cmdUtils.getCommandRequired("thing_name", "");
    MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {

        @Override
        public void onConnectionInterrupted(int errorCode) {
            if (errorCode != 0) {
                System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
            }
        }

        @Override
        public void onConnectionResumed(boolean sessionPresent) {
            System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
        }
    };
    try {
        MqttClientConnection connection = cmdUtils.buildMQTTConnection(callbacks);
        shadow = new IotShadowClient(connection);
        CompletableFuture<Boolean> connected = connection.connect();
        try {
            boolean sessionPresent = connected.get();
            System.out.println("Connected to " + (!sessionPresent ? "clean" : "existing") + " session!");
        } catch (Exception ex) {
            throw new RuntimeException("Exception occurred during connect", ex);
        }
        System.out.println("Subscribing to shadow delta events...");
        ShadowDeltaUpdatedSubscriptionRequest requestShadowDeltaUpdated = new ShadowDeltaUpdatedSubscriptionRequest();
        requestShadowDeltaUpdated.thingName = thingName;
        CompletableFuture<Integer> subscribedToDeltas = shadow.SubscribeToShadowDeltaUpdatedEvents(requestShadowDeltaUpdated, QualityOfService.AT_LEAST_ONCE, ShadowSample::onShadowDeltaUpdated);
        subscribedToDeltas.get();
        System.out.println("Subscribing to update respones...");
        UpdateShadowSubscriptionRequest requestUpdateShadow = new UpdateShadowSubscriptionRequest();
        requestUpdateShadow.thingName = thingName;
        CompletableFuture<Integer> subscribedToUpdateAccepted = shadow.SubscribeToUpdateShadowAccepted(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowAccepted);
        CompletableFuture<Integer> subscribedToUpdateRejected = shadow.SubscribeToUpdateShadowRejected(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowRejected);
        subscribedToUpdateAccepted.get();
        subscribedToUpdateRejected.get();
        System.out.println("Subscribing to get responses...");
        GetShadowSubscriptionRequest requestGetShadow = new GetShadowSubscriptionRequest();
        requestGetShadow.thingName = thingName;
        CompletableFuture<Integer> subscribedToGetShadowAccepted = shadow.SubscribeToGetShadowAccepted(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowAccepted);
        CompletableFuture<Integer> subscribedToGetShadowRejected = shadow.SubscribeToGetShadowRejected(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowRejected);
        subscribedToGetShadowAccepted.get();
        subscribedToGetShadowRejected.get();
        gotResponse = new CompletableFuture<>();
        System.out.println("Requesting current shadow state...");
        GetShadowRequest getShadowRequest = new GetShadowRequest();
        getShadowRequest.thingName = thingName;
        CompletableFuture<Integer> publishedGetShadow = shadow.PublishGetShadow(getShadowRequest, QualityOfService.AT_LEAST_ONCE);
        publishedGetShadow.get();
        gotResponse.get();
        String newValue = "";
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print(SHADOW_PROPERTY + "> ");
            System.out.flush();
            newValue = scanner.next();
            if (newValue.compareToIgnoreCase("quit") == 0) {
                break;
            }
            gotResponse = new CompletableFuture<>();
            changeShadowValue(newValue).get();
            gotResponse.get();
        }
        scanner.close();
        CompletableFuture<Void> disconnected = connection.disconnect();
        disconnected.get();
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        System.out.println("Exception encountered: " + ex.toString());
    }
    System.out.println("Complete!");
    CrtResource.waitForNoResources();
}
Also used : Scanner(java.util.Scanner) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) MqttClientConnectionEvents(software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents) UpdateShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest) IotShadowClient(software.amazon.awssdk.iot.iotshadow.IotShadowClient) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) GetShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest) CommandLineUtils(utils.commandlineutils.CommandLineUtils) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) GetShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest) ExecutionException(java.util.concurrent.ExecutionException) ShadowDeltaUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest) ExecutionException(java.util.concurrent.ExecutionException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException)

Example 14 with CrtRuntimeException

use of software.amazon.awssdk.crt.CrtRuntimeException in project aws-iot-device-sdk-java-v2 by aws.

the class MQTTConnect method main.

public static void main(String[] args) {
    if (!DATestUtils.init(DATestUtils.TestType.CONNECT)) {
        throw new RuntimeException("Failed to initialize environment variables.");
    }
    try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) {
        builder.withClientId(clientId).withEndpoint(DATestUtils.endpoint).withPort((short) port).withCleanSession(true).withPingTimeoutMs(60000).withProtocolOperationTimeoutMs(60000);
        try (MqttClientConnection connection = builder.build()) {
            CompletableFuture<Boolean> connected = connection.connect();
            try {
                boolean sessionPresent = connected.get();
            } catch (Exception ex) {
                throw new RuntimeException("Exception occurred during connect", ex);
            }
            CompletableFuture<Void> disconnected = connection.disconnect();
            disconnected.get();
        }
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        System.out.print("failed: " + ex.getMessage());
    }
    System.exit(0);
}
Also used : MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ExecutionException(java.util.concurrent.ExecutionException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Example 15 with CrtRuntimeException

use of software.amazon.awssdk.crt.CrtRuntimeException in project aws-iot-device-sdk-java-v2 by aws.

the class MQTTPublish method main.

public static void main(String[] args) {
    if (!DATestUtils.init(DATestUtils.TestType.SUB_PUB)) {
        throw new RuntimeException("Failed to initialize environment variables.");
    }
    try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) {
        builder.withClientId(clientId).withEndpoint(DATestUtils.endpoint).withPort((short) port).withCleanSession(true).withPingTimeoutMs(60000).withProtocolOperationTimeoutMs(60000);
        try (MqttClientConnection connection = builder.build()) {
            CompletableFuture<Boolean> connected = connection.connect();
            try {
                boolean sessionPresent = connected.get();
            } catch (Exception ex) {
                throw new RuntimeException("Exception occurred during connect", ex);
            }
            CompletableFuture<Integer> published = connection.publish(new MqttMessage(DATestUtils.topic, message.getBytes(), QualityOfService.AT_MOST_ONCE, false));
            published.get();
            Thread.sleep(1000);
            CompletableFuture<Void> disconnected = connection.disconnect();
            disconnected.get();
        }
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        onApplicationFailure(ex);
    }
    System.exit(0);
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ExecutionException(java.util.concurrent.ExecutionException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

CrtRuntimeException (software.amazon.awssdk.crt.CrtRuntimeException)37 ExecutionException (java.util.concurrent.ExecutionException)14 CompletableFuture (java.util.concurrent.CompletableFuture)13 MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)12 Test (org.junit.Test)11 CommandLineUtils (utils.commandlineutils.CommandLineUtils)10 MqttClientConnectionEvents (software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents)8 GetObjectOutput (com.amazonaws.s3.model.GetObjectOutput)7 ByteBuffer (java.nio.ByteBuffer)7 CredentialsProvider (software.amazon.awssdk.crt.auth.credentials.CredentialsProvider)6 List (java.util.List)5 HttpRequest (software.amazon.awssdk.crt.http.HttpRequest)5 AwsIotMqttConnectionBuilder (software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder)5 Duration (java.time.Duration)3 ArrayList (java.util.ArrayList)3 CompletionException (java.util.concurrent.CompletionException)3 TlsContext (software.amazon.awssdk.crt.io.TlsContext)3 DeleteObjectOutput (com.amazonaws.s3.model.DeleteObjectOutput)2 DeleteObjectRequest (com.amazonaws.s3.model.DeleteObjectRequest)2 GetObjectRequest (com.amazonaws.s3.model.GetObjectRequest)2