use of com.microsoft.azure.sdk.iot.device.exceptions.TransportException in project azure-iot-sdk-java by Azure.
the class Mqtt method publish.
/**
* Method to publish to mqtt broker connection.
*
* @param publishTopic the topic to publish on mqtt broker connection.
* @param message the message to publish.
* @throws TransportException if sas token has expired, if connection hasn't been established yet, or if Paho throws
* for any other reason
*/
void publish(String publishTopic, Message message) throws TransportException {
try {
if (!this.mqttAsyncClient.isConnected()) {
TransportException transportException = new TransportException("Cannot publish when mqtt client is disconnected");
transportException.setRetryable(true);
throw transportException;
}
if (message == null || publishTopic == null || publishTopic.length() == 0 || message.getBytes() == null) {
throw new IllegalArgumentException("Cannot publish on null or empty publish topic");
}
byte[] payload = message.getBytes();
// Or wait until the connection is lost so the message can be requeued for later
while (this.mqttAsyncClient.getPendingDeliveryTokens().length >= MAX_IN_FLIGHT_COUNT) {
// noinspection BusyWait
Thread.sleep(10);
if (!this.mqttAsyncClient.isConnected()) {
TransportException transportException = new TransportException("Cannot publish when mqtt client is holding " + MAX_IN_FLIGHT_COUNT + " tokens and is disconnected");
transportException.setRetryable(true);
throw transportException;
}
}
MqttMessage mqttMessage = (payload.length == 0) ? new MqttMessage() : new MqttMessage(payload);
mqttMessage.setQos(QOS);
synchronized (this.unacknowledgedSentMessagesLock) {
log.trace("Publishing message ({}) to MQTT topic {}", message, publishTopic);
IMqttDeliveryToken publishToken = this.mqttAsyncClient.publish(publishTopic, mqttMessage);
unacknowledgedSentMessages.put(publishToken.getMessageId(), message);
log.trace("Message published to MQTT topic {}. Mqtt message id {} added to list of messages to wait for acknowledgement ({})", publishTopic, publishToken.getMessageId(), message);
}
} catch (MqttException e) {
log.warn("Message could not be published to MQTT topic {} ({})", publishTopic, message, e);
throw PahoExceptionTranslator.convertToMqttException(e, "Unable to publish message on topic : " + publishTopic);
} catch (InterruptedException e) {
throw new TransportException("Interrupted, Unable to publish message on topic : " + publishTopic, e);
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.TransportException in project azure-iot-sdk-java by Azure.
the class Mqtt method connectionLost.
/**
* Event fired when the connection with the MQTT broker is lost.
* @param throwable Reason for losing the connection.
*/
@Override
public void connectionLost(Throwable throwable) {
log.warn("Mqtt connection lost", throwable);
this.disconnect();
if (this.listener != null) {
if (throwable instanceof MqttException) {
throwable = PahoExceptionTranslator.convertToMqttException((MqttException) throwable, "Mqtt connection lost");
log.trace("Mqtt connection loss interpreted into transport exception", throwable);
} else {
throwable = new TransportException(throwable);
}
ReconnectionNotifier.notifyDisconnectAsync(throwable, this.listener, this.connectionId);
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.TransportException in project azure-iot-sdk-java by Azure.
the class MqttDeviceTwin method throwDeviceTwinTransportException.
private void throwDeviceTwinTransportException(Exception e) throws TransportException {
TransportException transportException = new TransportException(e);
transportException.setIotHubService(TransportException.IotHubService.TWIN);
throw transportException;
}
use of com.microsoft.azure.sdk.iot.device.exceptions.TransportException in project azure-iot-sdk-java by Azure.
the class HttpsIotHubConnection method sendMessage.
/**
* Sends an event message.
*
* @param message the event message.
*
* @return the IotHubStatusCode from sending the event message.
*
* @throws TransportException if the IoT Hub could not be reached.
*/
public IotHubStatusCode sendMessage(Message message) throws TransportException {
synchronized (HTTPS_CONNECTION_LOCK) {
// Here we check if it's a bulk message and serialize it.
HttpsMessage httpsMessage;
if (message instanceof BatchMessage) {
try {
List<HttpsSingleMessage> httpsMessageList = new ArrayList<>();
for (Message msg : ((BatchMessage) message).getNestedMessages()) {
httpsMessageList.add(HttpsSingleMessage.parseHttpsMessage(msg));
}
httpsMessage = new HttpsBatchMessage(httpsMessageList);
} catch (IotHubSizeExceededException e) {
throw new TransportException("Failed to create HTTPS batch message", e);
}
} else {
httpsMessage = HttpsSingleMessage.parseHttpsMessage(message);
}
String iotHubHostname = getHostName();
String deviceId = this.config.getDeviceId();
String moduleId = this.config.getModuleId();
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_002: [The function shall send a request to the URL 'https://[iotHubHostname]/devices/[deviceId]/messages/events?api-version=2016-02-03'.]
IotHubEventUri iotHubEventUri = new IotHubEventUri(iotHubHostname, deviceId, moduleId);
URL eventUrl = this.buildUrlFromString(HTTPS_HEAD_TAG + iotHubEventUri.toString());
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_003: [The function shall send a POST request.]
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_004: [The function shall set the request body to the message body.]
HttpsRequest request = new HttpsRequest(eventUrl, HttpsMethod.POST, httpsMessage.getBody(), this.config.getProductInfo().getUserAgentString(), config.getProxySettings());
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_005: [The function shall write each message property as a request header.]
for (MessageProperty property : httpsMessage.getProperties()) {
request.setHeaderField(property.getName(), property.getValue());
}
if (message.getContentEncoding() != null) {
// Codes_SRS_HTTPSIOTHUBCONNECTION_34_073: [If the provided message has a content encoding, this function shall set the request header to include that value with the key "iothub-contentencoding".]
request.setHeaderField(MessageProperty.IOTHUB_CONTENT_ENCODING, message.getContentEncoding());
}
if (message.getContentType() != null) {
// Codes_SRS_HTTPSIOTHUBCONNECTION_34_074: [If the provided message has a content type, this function shall set the request header to include that value with the key "iothub-contenttype".]
request.setHeaderField(MessageProperty.IOTHUB_CONTENT_TYPE, message.getContentType());
}
if (message.getCreationTimeUTC() != null) {
// Codes_SRS_HTTPSIOTHUBCONNECTION_34_075: [If the provided message has a creation time utc, this function shall set the request header to include that value with the key "iothub-contenttype".]
request.setHeaderField(MessageProperty.IOTHUB_CREATION_TIME_UTC, message.getCreationTimeUTCString());
}
if (message.isSecurityMessage()) {
request.setHeaderField(MessageProperty.IOTHUB_SECURITY_INTERFACE_ID, MessageProperty.IOTHUB_SECURITY_INTERFACE_ID_VALUE);
}
Map<String, String> systemProperties = httpsMessage.getSystemProperties();
for (String systemProperty : systemProperties.keySet()) {
request.setHeaderField(systemProperty, systemProperties.get(systemProperty));
}
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_008: [The function shall set the header field 'iothub-to' to be '/devices/[deviceId]/messages/events'.]
request.setHeaderField(HTTPS_PROPERTY_IOTHUB_TO_TAG, iotHubEventUri.getPath()).setHeaderField(HTTPS_PROPERTY_CONTENT_TYPE_TAG, httpsMessage.getContentType());
// Codes_SRS_HTTPSIOTHUBCONNECTION_25_040: [The function shall set the IotHub SSL context by calling setSSLContext on the request.]
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_007: [The function shall set the header field 'authorization' to be a valid SAS token generated from the configuration parameters.]
// Codes_SRS_HTTPSIOTHUBCONNECTION_34_059: [If this config is using x509 authentication, this function shall retrieve its sslcontext from its x509 Authentication object.]
// Codes_SRS_HTTPSIOTHUBCONNECTION_11_006: [The function shall set the request read timeout to be the configuration parameter readTimeoutMillis.]
log.trace("Sending message using http request ({})", message);
HttpsResponse response = this.sendRequest(request);
IotHubStatusCode status = IotHubStatusCode.getIotHubStatusCode(response.getStatus());
log.trace("Iot Hub responded to http message for iot hub message ({}) with status code {}", message, status);
IotHubTransportMessage transportMessage = new IotHubTransportMessage(httpsMessage.getBody(), message.getMessageType(), message.getMessageId(), message.getCorrelationId(), message.getProperties());
if (status == IotHubStatusCode.OK || status == IotHubStatusCode.OK_EMPTY) {
// Codes_SRS_HTTPSIOTHUBCONNECTION_34_067: [If the response from the service is OK or OK_EMPTY, this function shall notify its listener that a message was sent with no exception.]
this.listener.onMessageSent(transportMessage, this.config.getDeviceId(), null);
}
return status;
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.TransportException in project azure-iot-sdk-java by Azure.
the class AmqpsIotHubConnectionTest method openWaitsForReactorToBeReadyAndForEnoughLinkCreditToBeAvailable.
// Tests_SRS_AMQPSIOTHUBCONNECTION_15_010: [The function shall wait for the reactor to be ready and for
// enough link credit to become available.]
@Test
public void openWaitsForReactorToBeReadyAndForEnoughLinkCreditToBeAvailable() 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;
}
};
final AmqpsIotHubConnection connection = new AmqpsIotHubConnection(mockConfig, "");
connection.setListener(mockedIotHubListener);
setLatches(connection);
// act
try {
connection.open();
} catch (TransportException e) {
// exception will be thrown, but we aren't testing for what it is nor do we care that it threw
}
}
Aggregations