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;
}
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);
}
}
}
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;
}
};
}
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());
}
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;
}
};
}
Aggregations