Search in sources :

Example 36 with TransportException

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

the class ReactorRunner method call.

@Override
public Object call() {
    try {
        String threadName = this.threadPrefix + "-" + THREAD_NAME + "-" + this.threadPostfix;
        Thread.currentThread().setName(threadName);
        this.reactor.setTimeout(10);
        this.reactor.start();
        // noinspection StatementWithEmptyBody
        while (this.reactor.process()) {
        // The empty while loop is to ensure that reactor thread runs as long as it has messages to process
        }
        this.reactor.stop();
        this.reactor.process();
    } catch (HandlerException e) {
        TransportException transportException = new TransportException(e);
        // unclassified exceptions are treated as retryable in ProtonJExceptionParser, so they should be treated
        // the same way here. Exceptions caught here tend to be transient issues.
        transportException.setRetryable(true);
        // Notify the AMQP connection layer so it can tear down the reactor's resources that would usually
        // get cleaned up in a graceful close of the reactor
        this.reactorRunnerStateCallback.onReactorClosedUnexpectedly();
        this.listener.onConnectionLost(transportException, connectionId);
    } finally {
        reactor.free();
    }
    return null;
}
Also used : HandlerException(org.apache.qpid.proton.engine.HandlerException) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException)

Example 37 with TransportException

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

the class ModuleClient method createFromEnvironment.

/**
 * Create a module client instance from your environment variables
 * @param protocol the protocol the module client instance will use
 * @param clientOptions The options that allow configuration of the module client instance during initialization
 * @return the created module client instance
 * @throws ModuleClientException if the module client cannot be created
 */
public static ModuleClient createFromEnvironment(IotHubClientProtocol protocol, ClientOptions clientOptions) throws ModuleClientException {
    log.info("Creating module client from environment with protocol {}...", protocol);
    Map<String, String> envVariables = System.getenv();
    // Codes_SRS_MODULECLIENT_34_013: [This function shall check for a saved edgehub connection string.]
    log.debug("Checking for an edgehub connection string...");
    String connectionString = envVariables.get(EdgehubConnectionstringVariableName);
    if (connectionString == null) {
        log.debug("No edgehub connection string was configured, checking for an IoThub connection string...");
        // Codes_SRS_MODULECLIENT_34_019: [If no edgehub connection string is present, this function shall check for a saved iothub connection string.]
        connectionString = envVariables.get(IothubConnectionstringVariableName);
    }
    // First try to create from connection string and if env variable for connection string is not found try to create from edgedUri
    if (connectionString != null) {
        log.debug("Creating module client with the provided connection string");
        // Codes_SRS_MODULECLIENT_34_020: [If an edgehub or iothub connection string is present, this function shall create a module client instance using that connection string and the provided protocol.]
        ModuleClient moduleClient;
        try {
            moduleClient = new ModuleClient(connectionString, protocol, clientOptions);
        } catch (URISyntaxException e) {
            throw new ModuleClientException("Could not create module client", e);
        }
        // Check for a different default cert to be used
        String alternativeDefaultTrustedCert = envVariables.get(EdgeCaCertificateFileVariableName);
        if (alternativeDefaultTrustedCert != null && !alternativeDefaultTrustedCert.isEmpty()) {
            log.debug("Configuring module client to use the configured alternative trusted certificate");
            // Codes_SRS_MODULECLIENT_34_031: [If an alternative default trusted cert is saved in the environment
            // variables, this function shall set that trusted cert in the created module client.]
            moduleClient.setOption_SetCertificatePath(alternativeDefaultTrustedCert);
        }
        return moduleClient;
    } else {
        log.info("No connection string was configured for this module, so it will get its credentials from the edgelet");
        // Codes_SRS_MODULECLIENT_34_014: [This function shall check for environment variables for edgedUri, deviceId, moduleId,
        // hostname, authScheme, gatewayHostname, and generationId. If any of these other than gatewayHostname is missing,
        // this function shall throw a ModuleClientException.]
        String edgedUri = envVariables.get(IotEdgedUriVariableName);
        String deviceId = envVariables.get(DeviceIdVariableName);
        String moduleId = envVariables.get(ModuleIdVariableName);
        String hostname = envVariables.get(IotHubHostnameVariableName);
        String authScheme = envVariables.get(AuthSchemeVariableName);
        String gatewayHostname = envVariables.get(GatewayHostnameVariableName);
        String generationId = envVariables.get(ModuleGenerationIdVariableName);
        if (edgedUri == null) {
            throw new ModuleClientException("Environment variable " + IotEdgedUriVariableName + " is required.");
        }
        if (deviceId == null) {
            throw new ModuleClientException("Environment variable " + DeviceIdVariableName + " is required.");
        }
        if (moduleId == null) {
            throw new ModuleClientException("Environment variable " + ModuleIdVariableName + " is required.");
        }
        if (hostname == null) {
            throw new ModuleClientException("Environment variable " + IotHubHostnameVariableName + " is required.");
        }
        if (authScheme == null) {
            throw new ModuleClientException("Environment variable " + AuthSchemeVariableName + " is required.");
        }
        if (generationId == null) {
            throw new ModuleClientException("Environment variable " + ModuleGenerationIdVariableName + " is required");
        }
        if (!authScheme.equalsIgnoreCase(SasTokenAuthScheme)) {
            // Codes_SRS_MODULECLIENT_34_030: [If the auth scheme environment variable is not "SasToken", this function shall throw a moduleClientException.]
            throw new ModuleClientException("Unsupported authentication scheme. Supported scheme is " + SasTokenAuthScheme + ".");
        }
        SignatureProvider signatureProvider;
        try {
            signatureProvider = new HttpHsmSignatureProvider(edgedUri, DEFAULT_API_VERSION);
        } catch (NoSuchAlgorithmException | URISyntaxException e) {
            throw new ModuleClientException("Could not use Hsm Signature Provider", e);
        }
        try {
            // Codes_SRS_MODULECLIENT_34_017: [This function shall create an authentication provider using the created
            // signature provider, and the environment variables for deviceid, moduleid, hostname, gatewayhostname,
            // and the default time for tokens to live and the default sas token buffer time.]
            IotHubAuthenticationProvider iotHubAuthenticationProvider = IotHubSasTokenHsmAuthenticationProvider.create(signatureProvider, deviceId, moduleId, hostname, gatewayHostname, generationId, DEFAULT_SAS_TOKEN_TIME_TO_LIVE_SECONDS, DEFAULT_SAS_TOKEN_BUFFER_PERCENTAGE);
            // Codes_SRS_MODULECLIENT_34_018: [This function shall return a new ModuleClient instance built from the created authentication provider and the provided protocol.]
            ModuleClient moduleClient = new ModuleClient(iotHubAuthenticationProvider, protocol, SEND_PERIOD_MILLIS, getReceivePeriod(protocol));
            if (gatewayHostname != null && !gatewayHostname.isEmpty()) {
                // Codes_SRS_MODULECLIENT_34_032: [This function shall retrieve the trust bundle from the hsm and set them in the module client.]
                TrustBundleProvider trustBundleProvider = new HttpsHsmTrustBundleProvider();
                String trustCertificates = trustBundleProvider.getTrustBundleCerts(edgedUri, DEFAULT_API_VERSION);
                moduleClient.setTrustedCertificates(trustCertificates);
            }
            return moduleClient;
        } catch (IOException | TransportException | HsmException | URISyntaxException e) {
            throw new ModuleClientException(e);
        }
    }
}
Also used : HttpsHsmTrustBundleProvider(com.microsoft.azure.sdk.iot.device.edge.HttpsHsmTrustBundleProvider) TrustBundleProvider(com.microsoft.azure.sdk.iot.device.edge.TrustBundleProvider) ModuleClientException(com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException) SignatureProvider(com.microsoft.azure.sdk.iot.device.auth.SignatureProvider) HttpHsmSignatureProvider(com.microsoft.azure.sdk.iot.device.hsm.HttpHsmSignatureProvider) IotHubAuthenticationProvider(com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider) HsmException(com.microsoft.azure.sdk.iot.device.hsm.HsmException) HttpsHsmTrustBundleProvider(com.microsoft.azure.sdk.iot.device.edge.HttpsHsmTrustBundleProvider) HttpHsmSignatureProvider(com.microsoft.azure.sdk.iot.device.hsm.HttpHsmSignatureProvider)

Example 38 with TransportException

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

the class HttpsConnectionTest method readErrorAlwaysClosesStream.

// Tests_SRS_HTTPSCONNECTION_11_020: [The function shall close the error stream after it has been completely read.]
@Test
public void readErrorAlwaysClosesStream(@Mocked final InputStream mockIs) throws IOException, TransportException {
    final HttpsMethod httpsMethod = HttpsMethod.GET;
    new NonStrictExpectations() {

        {
            mockUrl.getProtocol();
            result = "https";
            mockUrl.openConnection();
            result = mockUrlConn;
            mockUrlConn.getRequestMethod();
            result = httpsMethod.name();
            mockUrlConn.getErrorStream();
            result = mockIs;
            mockIs.read();
            result = new TransportException("This is a test exception");
        }
    };
    HttpsConnection conn = new HttpsConnection(mockUrl, httpsMethod);
    conn.connect();
    // act
    try {
        byte[] testError = conn.readError();
    } catch (TransportException e) {
    // expected exception, but not testing for it, so it can be ignored
    }
    new Verifications() {

        {
            mockIs.close();
            times = 1;
        }
    };
}
Also used : HttpsConnection(com.microsoft.azure.sdk.iot.device.transport.https.HttpsConnection) HttpsMethod(com.microsoft.azure.sdk.iot.device.transport.https.HttpsMethod) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException) Test(org.junit.Test)

Example 39 with TransportException

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

the class AmqpsIotHubConnectionTest method openClearsLocalStateIfWorkerLinksTimeout.

@Test
public void openClearsLocalStateIfWorkerLinksTimeout() throws TransportException, InterruptedException {
    // arrange
    baseExpectations();
    final CountDownLatch workerLinkLatch = new CountDownLatch(0);
    final AmqpsIotHubConnection connection = new AmqpsIotHubConnection(mockConfig, "");
    connection.setListener(mockedIotHubListener);
    new Expectations() {

        {
            new CountDownLatch(anyInt);
            result = workerLinkLatch;
            workerLinkLatch.await(anyLong, TimeUnit.SECONDS);
            // simulates timing out waiting for the worker links to open
            result = false;
        }
    };
    // act
    try {
        connection.open();
        fail("expected an exception to be thrown");
    } catch (TransportException e) {
    // expected exception
    }
    Map<String, AmqpsSessionHandler> sessionHandlers = Deencapsulation.getField(connection, "sessionHandlers");
    Queue<AmqpsSasTokenRenewalHandler> sasTokenRenewalHandlers = Deencapsulation.getField(connection, "sasTokenRenewalHandlers");
    assertTrue(sessionHandlers.isEmpty());
    assertTrue(sasTokenRenewalHandlers.isEmpty());
}
Also used : NonStrictExpectations(mockit.NonStrictExpectations) Expectations(mockit.Expectations) IotHubConnectionString(com.microsoft.azure.sdk.iot.device.IotHubConnectionString) CountDownLatch(java.util.concurrent.CountDownLatch) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException) Test(org.junit.Test)

Example 40 with TransportException

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

the class AmqpsIotHubConnectionTest method openTriggersProtonReactor.

// Tests_SRS_AMQPSIOTHUBCONNECTION_15_009: [The function shall trigger the Reactor (Proton) to begin running.]
@Test
public void openTriggersProtonReactor(@Mocked final Reactor mockedReactor) throws TransportException, InterruptedException {
    // arrange
    baseExpectations();
    final CountDownLatch closeLatch = new CountDownLatch(1);
    new Expectations() {

        {
            new CountDownLatch(anyInt);
            result = mockAuthLatch;
            mockAuthLatch.await(anyLong, TimeUnit.MILLISECONDS);
            result = true;
        }
    };
    AmqpsIotHubConnection connection = new AmqpsIotHubConnection(mockConfig, "");
    connection.setListener(mockedIotHubListener);
    setLatches(connection);
    // act
    try {
        connection.open();
    } catch (TransportException e) {
    // exception will be thrown, but this unit test does not care
    }
    // assert
    new Verifications() {

        {
            new ReactorRunner((Reactor) any, (IotHubListener) any, anyString, anyString, anyString, (ReactorRunnerStateCallback) any);
            times = 1;
        }
    };
}
Also used : NonStrictExpectations(mockit.NonStrictExpectations) Expectations(mockit.Expectations) CountDownLatch(java.util.concurrent.CountDownLatch) Verifications(mockit.Verifications) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException) Test(org.junit.Test)

Aggregations

TransportException (com.microsoft.azure.sdk.iot.device.exceptions.TransportException)46 Test (org.junit.Test)18 IOException (java.io.IOException)14 ProtocolException (com.microsoft.azure.sdk.iot.device.exceptions.ProtocolException)8 MqttException (org.eclipse.paho.client.mqttv3.MqttException)7 CountDownLatch (java.util.concurrent.CountDownLatch)4 Expectations (mockit.Expectations)4 NonStrictExpectations (mockit.NonStrictExpectations)4 Message (com.microsoft.azure.sdk.iot.device.Message)3 HttpsConnection (com.microsoft.azure.sdk.iot.device.transport.https.HttpsConnection)3 HttpsMethod (com.microsoft.azure.sdk.iot.device.transport.https.HttpsMethod)3 MqttMessaging (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttMessaging)3 Pair (org.apache.commons.lang3.tuple.Pair)3 IotHubConnectionString (com.microsoft.azure.sdk.iot.device.IotHubConnectionString)2 ModuleClientException (com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException)2 URISyntaxException (java.net.URISyntaxException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 IotHubSSLContext (com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext)1 IotHubAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider)1 SignatureProvider (com.microsoft.azure.sdk.iot.device.auth.SignatureProvider)1