Search in sources :

Example 1 with DiscoverResponse

use of software.amazon.awssdk.iot.discovery.model.DiscoverResponse in project aws-iot-device-sdk-java-v2 by aws.

the class BasicDiscovery method getClientFromDiscovery.

private static MqttClientConnection getClientFromDiscovery(final DiscoveryClient discoveryClient) throws ExecutionException, InterruptedException {
    final CompletableFuture<DiscoverResponse> futureResponse = discoveryClient.discover(thingName);
    final DiscoverResponse response = futureResponse.get();
    if (response.getGGGroups() != null) {
        final Optional<GGGroup> groupOpt = response.getGGGroups().stream().findFirst();
        if (groupOpt.isPresent()) {
            final GGGroup group = groupOpt.get();
            final GGCore core = group.getCores().stream().findFirst().get();
            for (ConnectivityInfo connInfo : core.getConnectivity()) {
                final String dnsOrIp = connInfo.getHostAddress();
                final Integer port = connInfo.getPortNumber();
                System.out.println(String.format("Connecting to group ID %s, with thing arn %s, using endpoint %s:%d", group.getGGGroupId(), core.getThingArn(), dnsOrIp, port));
                final AwsIotMqttConnectionBuilder connectionBuilder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(certPath, keyPath).withClientId(thingName).withPort(port.shortValue()).withEndpoint(dnsOrIp).withConnectionEventCallbacks(new MqttClientConnectionEvents() {

                    @Override
                    public void onConnectionInterrupted(int errorCode) {
                        System.out.println("Connection interrupted: " + errorCode);
                    }

                    @Override
                    public void onConnectionResumed(boolean sessionPresent) {
                        System.out.println("Connection resumed!");
                    }
                });
                if (group.getCAs() != null) {
                    connectionBuilder.withCertificateAuthority(group.getCAs().get(0));
                }
                try (MqttClientConnection connection = connectionBuilder.build()) {
                    if (connection.connect().get()) {
                        System.out.println("Session resumed");
                    } else {
                        System.out.println("Started a clean session");
                    }
                    /* This lets the connection escape the try block without getting cleaned up */
                    connection.addRef();
                    return connection;
                } catch (Exception e) {
                    System.out.println(String.format("Connection failed with exception %s", e.toString()));
                }
            }
            throw new RuntimeException("ThingName " + thingName + " could not connect to the green grass core using any of the endpoint connectivity options");
        }
    }
    throw new RuntimeException("ThingName " + thingName + " does not have a Greengrass group/core configuration");
}
Also used : ConnectivityInfo(software.amazon.awssdk.iot.discovery.model.ConnectivityInfo) DiscoverResponse(software.amazon.awssdk.iot.discovery.model.DiscoverResponse) ExecutionException(java.util.concurrent.ExecutionException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) GGCore(software.amazon.awssdk.iot.discovery.model.GGCore) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) GGGroup(software.amazon.awssdk.iot.discovery.model.GGGroup)

Example 2 with DiscoverResponse

use of software.amazon.awssdk.iot.discovery.model.DiscoverResponse in project aws-iot-device-sdk-java-v2 by aws.

the class DiscoveryClient method discover.

/**
 * Based on configuration, make an http request to query connectivity information about available Greengrass cores
 * @param thingName name of the thing/device making the greengrass core query
 * @return future holding connectivity information about greengrass cores available to the device/thing
 */
public CompletableFuture<DiscoverResponse> discover(final String thingName) {
    if (thingName == null) {
        throw new IllegalArgumentException("ThingName cannot be null!");
    }
    return CompletableFuture.supplyAsync(() -> {
        try (final HttpClientConnection connection = httpClientConnectionManager.acquireConnection().get()) {
            final String requestHttpPath = "/greengrass/discover/thing/" + thingName;
            final HttpHeader[] headers = new HttpHeader[] { new HttpHeader("host", httpClientConnectionManager.getUri().getHost()) };
            final HttpRequest request = new HttpRequest("GET", requestHttpPath, headers, null);
            // we are storing everything until we get the entire response
            final CompletableFuture<Integer> responseComplete = new CompletableFuture<>();
            final StringBuilder jsonBodyResponseBuilder = new StringBuilder();
            final Map<String, String> responseInfo = new HashMap<>();
            try (final HttpStream stream = connection.makeRequest(request, new HttpStreamResponseHandler() {

                @Override
                public void onResponseHeaders(HttpStream stream, int responseStatusCode, int blockType, HttpHeader[] httpHeaders) {
                    Arrays.stream(httpHeaders).forEach(header -> {
                        responseInfo.put(header.getName(), header.getValue());
                    });
                }

                @Override
                public int onResponseBody(HttpStream stream, byte[] bodyBytes) {
                    jsonBodyResponseBuilder.append(new String(bodyBytes, StandardCharsets.UTF_8));
                    return bodyBytes.length;
                }

                @Override
                public void onResponseComplete(HttpStream httpStream, int errorCode) {
                    responseComplete.complete(errorCode);
                }
            })) {
                stream.activate();
                responseComplete.get();
                if (stream.getResponseStatusCode() != 200) {
                    throw new RuntimeException(String.format("Error %s(%d); RequestId: %s", HTTP_HEADER_ERROR_TYPE, stream.getResponseStatusCode(), HTTP_HEADER_REQUEST_ID));
                }
                final String responseString = jsonBodyResponseBuilder.toString();
                return GSON.fromJson(new StringReader(responseString), DiscoverResponse.class);
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    });
}
Also used : DiscoverResponse(software.amazon.awssdk.iot.discovery.model.DiscoverResponse) ExecutionException(java.util.concurrent.ExecutionException) software.amazon.awssdk.crt.io(software.amazon.awssdk.crt.io) Arrays(java.util.Arrays) StringReader(java.io.StringReader) Gson(com.google.gson.Gson) Map(java.util.Map) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) URI(java.net.URI) software.amazon.awssdk.crt.http(software.amazon.awssdk.crt.http) StandardCharsets(java.nio.charset.StandardCharsets) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) StringReader(java.io.StringReader) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

ExecutionException (java.util.concurrent.ExecutionException)2 DiscoverResponse (software.amazon.awssdk.iot.discovery.model.DiscoverResponse)2 Gson (com.google.gson.Gson)1 StringReader (java.io.StringReader)1 URI (java.net.URI)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CrtRuntimeException (software.amazon.awssdk.crt.CrtRuntimeException)1 software.amazon.awssdk.crt.http (software.amazon.awssdk.crt.http)1 software.amazon.awssdk.crt.io (software.amazon.awssdk.crt.io)1 AwsIotMqttConnectionBuilder (software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder)1 ConnectivityInfo (software.amazon.awssdk.iot.discovery.model.ConnectivityInfo)1 GGCore (software.amazon.awssdk.iot.discovery.model.GGCore)1 GGGroup (software.amazon.awssdk.iot.discovery.model.GGGroup)1