Search in sources :

Example 6 with ModuleClientException

use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.

the class SendReceiveModuleSample method main.

/**
 * Receives requests from an IoT Hub. Default protocol is to use
 * use MQTT transport.
 *
 * @param args
 * args[0] = IoT Hub connection string
 * args[1] = number of requests to send
 * args[2] = protocol (optional, one of 'mqtt' or 'amqps' or 'https' or 'amqps_ws')
 * args[3] = path to certificate to enable one-way authentication over ssl for amqps (optional, default shall be used if unspecified).
 */
public static void main(String[] args) throws IOException, URISyntaxException, ModuleClientException {
    System.out.println("Starting...");
    System.out.println("Beginning setup.");
    String pathToCertificate = null;
    if (args.length <= 1 || args.length >= 5) {
        System.out.format(SAMPLE_USAGE_WITH_WRONG_ARGS, args.length);
        return;
    }
    String connString = args[0];
    int numRequests;
    try {
        numRequests = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
        System.out.format("Could not parse the number of requests to send. " + "Expected an int but received:\n%s.\n", args[1]);
        return;
    }
    IotHubClientProtocol protocol;
    if (args.length == 2) {
        protocol = IotHubClientProtocol.MQTT;
    } else {
        String protocolStr = args[2];
        if (protocolStr.equalsIgnoreCase("amqps")) {
            protocol = IotHubClientProtocol.AMQPS;
        } else if (protocolStr.equalsIgnoreCase("mqtt")) {
            protocol = IotHubClientProtocol.MQTT;
        } else if (protocolStr.equalsIgnoreCase("amqps_ws")) {
            protocol = IotHubClientProtocol.AMQPS_WS;
        } else if (protocolStr.equalsIgnoreCase("mqtt_ws")) {
            protocol = IotHubClientProtocol.MQTT_WS;
        } else {
            System.out.format(SAMPLE_USAGE_WITH_INVALID_PROTOCOL, protocolStr);
            return;
        }
        if (args.length == 3) {
            pathToCertificate = null;
        } else {
            pathToCertificate = args[3];
        }
    }
    System.out.println("Successfully read input parameters.");
    System.out.format("Using communication protocol %s.\n", protocol.name());
    ModuleClient client = new ModuleClient(connString, protocol);
    if (pathToCertificate != null) {
        client.setOption("SetCertificatePath", pathToCertificate);
    }
    System.out.println("Successfully created an IoT Hub client.");
    if (protocol == IotHubClientProtocol.MQTT) {
        MessageCallbackMqtt callback = new MessageCallbackMqtt();
        Counter counter = new Counter(0);
        client.setMessageCallback(callback, counter);
    } else {
        MessageCallback callback = new MessageCallback();
        Counter counter = new Counter(0);
        client.setMessageCallback(callback, counter);
    }
    System.out.println("Successfully set message callback.");
    // Set your token expiry time limit here
    long time = 2400;
    client.setOption("SetSASTokenExpiryTime", time);
    client.registerConnectionStatusChangeCallback(new IotHubConnectionStatusChangeCallbackLogger(), new Object());
    client.open();
    System.out.println("Opened connection to IoT Hub.");
    System.out.println("Beginning to receive messages...");
    System.out.println("Sending the following event messages: ");
    System.out.println("Updated token expiry time to " + time);
    String deviceId = "MyJavaDevice";
    double temperature;
    double humidity;
    for (int i = 0; i < numRequests; ++i) {
        temperature = 20 + Math.random() * 10;
        humidity = 30 + Math.random() * 20;
        String msgStr = "{\"deviceId\":\"" + deviceId + "\",\"messageId\":" + i + ",\"temperature\":" + temperature + ",\"humidity\":" + humidity + "}";
        try {
            Message msg = new Message(msgStr);
            msg.setContentTypeFinal("application/json");
            msg.setProperty("temperatureAlert", temperature > 28 ? "true" : "false");
            msg.setMessageId(java.util.UUID.randomUUID().toString());
            msg.setExpiryTime(D2C_MESSAGE_TIMEOUT);
            System.out.println(msgStr);
            EventCallback eventCallback = new EventCallback();
            client.sendEventAsync(msg, eventCallback, msg);
        } catch (Exception e) {
            // Trace the exception
            e.printStackTrace();
        }
    }
    System.out.println("Wait for " + D2C_MESSAGE_TIMEOUT / 1000 + " second(s) for response from the IoT Hub...");
    // Wait for IoT Hub to respond.
    try {
        Thread.sleep(D2C_MESSAGE_TIMEOUT);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("In receive mode. Waiting for receiving C2D messages (only for MQTT and AMQP). Press ENTER to close. To receive in Https, send message and then start the sample.");
    Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
    scanner.nextLine();
    // close the connection
    System.out.println("Closing");
    client.closeNow();
    if (!failedMessageListOnClose.isEmpty()) {
        System.out.println("List of messages that were cancelled on close:" + failedMessageListOnClose.toString());
    }
    System.out.println("Shutting down...");
}
Also used : Scanner(java.util.Scanner) URISyntaxException(java.net.URISyntaxException) ModuleClientException(com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException) IOException(java.io.IOException)

Example 7 with ModuleClientException

use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.

the class ModuleGlue method connect.

public void connect(String transportType, String connectionString, Certificate caCertificate, Handler<AsyncResult<ConnectResponse>> handler) {
    System.out.printf("Connect called with transport %s%n", transportType);
    IotHubClientProtocol protocol = this.transportFromString(transportType);
    if (protocol == null) {
        handler.handle(Future.failedFuture(new MainApiException(500, "invalid transport")));
        return;
    }
    try {
        ModuleClient client = new ModuleClient(connectionString, protocol);
        String cert = caCertificate.getCert();
        if (cert != null && !cert.isEmpty()) {
            client.setOption("SetCertificateAuthority", cert);
        }
        client.open();
        this._clientCount++;
        String connectionId = "moduleClient_" + this._clientCount;
        this._map.put(connectionId, client);
        ConnectResponse cr = new ConnectResponse();
        cr.setConnectionId(connectionId);
        handler.handle(Future.succeededFuture(cr));
    } catch (ModuleClientException | URISyntaxException | IOException e) {
        handler.handle(Future.failedFuture(e));
    }
}
Also used : ConnectResponse(io.swagger.server.api.model.ConnectResponse) ModuleClientException(com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException) IOException(java.io.IOException) MainApiException(io.swagger.server.api.MainApiException)

Example 8 with ModuleClientException

use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.

the class ModuleGlue method connectFromEnvironment.

public void connectFromEnvironment(String transportType, Handler<AsyncResult<ConnectResponse>> handler) {
    System.out.printf("ConnectFromEnvironment called with transport %s%n", transportType);
    // This is the default URL stream handler factory
    URLStreamHandlerFactory fac = protocol -> {
        if (protocol.equals("http")) {
            return new sun.net.www.protocol.http.Handler();
        } else if (protocol.equals("https")) {
            return new sun.net.www.protocol.https.Handler();
        }
        return null;
    };
    try {
        /*
            This line of code used to be run in older versions of the SDK, and it caused bugs when this library builds
            a module client from environment through the edgelet in conjunction with any other library that called this API.
            This API can only be called once per JVM process, so we had to remove the call to this API from our SDK to maintain
            compatibility with other libraries that call this API. We call this API in this test now so that we guarantee
            that our module client code works even when this API is used beforehand to avoid regression
             */
        URL.setURLStreamHandlerFactory(fac);
    } catch (Error e) {
    // this function only throws if the factory has already been set, so we can ignore this error
    }
    IotHubClientProtocol protocol = this.transportFromString(transportType);
    if (protocol == null) {
        handler.handle(Future.failedFuture(new MainApiException(500, "invalid transport")));
        return;
    }
    try {
        ModuleClient client = ModuleClient.createFromEnvironment(protocol);
        client.open();
        this._clientCount++;
        String connectionId = "moduleClient_" + this._clientCount;
        this._map.put(connectionId, client);
        ConnectResponse cr = new ConnectResponse();
        cr.setConnectionId(connectionId);
        handler.handle(Future.succeededFuture(cr));
    } catch (ModuleClientException | IOException e) {
        handler.handle(Future.failedFuture(e));
    }
}
Also used : Property(com.microsoft.azure.sdk.iot.device.DeviceTwin.Property) MainApiException(io.swagger.server.api.MainApiException) RoundtripMethodCallBody(io.swagger.server.api.model.RoundtripMethodCallBody) DeviceMethodData(com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodData) Json(io.vertx.core.json.Json) java.util(java.util) com.microsoft.azure.sdk.iot.device(com.microsoft.azure.sdk.iot.device) DeviceMethodCallback(com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodCallback) TwinPropertyCallBack(com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertyCallBack) IOException(java.io.IOException) MethodRequest(com.microsoft.azure.sdk.iot.device.edge.MethodRequest) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) MethodResult(com.microsoft.azure.sdk.iot.device.edge.MethodResult) ConnectResponse(io.swagger.server.api.model.ConnectResponse) java.net(java.net) ModuleClientException(com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException) JsonObject(io.vertx.core.json.JsonObject) Certificate(io.swagger.server.api.model.Certificate) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ConnectResponse(io.swagger.server.api.model.ConnectResponse) ModuleClientException(com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException) Handler(io.vertx.core.Handler) IOException(java.io.IOException) java.net(java.net) MainApiException(io.swagger.server.api.MainApiException)

Aggregations

ModuleClientException (com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException)8 IOException (java.io.IOException)5 MethodRequest (com.microsoft.azure.sdk.iot.device.edge.MethodRequest)4 MethodResult (com.microsoft.azure.sdk.iot.device.edge.MethodResult)4 MainApiException (io.swagger.server.api.MainApiException)4 JsonObject (io.vertx.core.json.JsonObject)3 URISyntaxException (java.net.URISyntaxException)3 TransportException (com.microsoft.azure.sdk.iot.device.exceptions.TransportException)2 ConnectResponse (io.swagger.server.api.model.ConnectResponse)2 com.microsoft.azure.sdk.iot.device (com.microsoft.azure.sdk.iot.device)1 DeviceMethodCallback (com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodCallback)1 DeviceMethodData (com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodData)1 Property (com.microsoft.azure.sdk.iot.device.DeviceTwin.Property)1 TwinPropertyCallBack (com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertyCallBack)1 IotHubAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider)1 SignatureProvider (com.microsoft.azure.sdk.iot.device.auth.SignatureProvider)1 HttpsHsmTrustBundleProvider (com.microsoft.azure.sdk.iot.device.edge.HttpsHsmTrustBundleProvider)1 TrustBundleProvider (com.microsoft.azure.sdk.iot.device.edge.TrustBundleProvider)1 HsmException (com.microsoft.azure.sdk.iot.device.hsm.HsmException)1 HttpHsmSignatureProvider (com.microsoft.azure.sdk.iot.device.hsm.HttpHsmSignatureProvider)1