use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.
the class FileUploadTask method getFileUploadSasUri.
public FileUploadSasUriResponse getFileUploadSasUri(FileUploadSasUriRequest request) throws IOException {
IotHubTransportMessage message = new IotHubTransportMessage(request.toJson());
message.setIotHubMethod(IotHubMethod.POST);
ResponseMessage responseMessage;
httpsTransportManager.open();
responseMessage = httpsTransportManager.getFileUploadSasUri(message);
httpsTransportManager.close();
String responseMessagePayload = validateServiceStatusCode(responseMessage, "Failed to get the file upload SAS URI");
if (responseMessagePayload == null || responseMessagePayload.isEmpty()) {
throw new IOException("Sas URI response message had no payload");
}
return new FileUploadSasUriResponse(responseMessagePayload);
}
use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage 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.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.
the class AmqpsTelemetryReceiverLinkHandler method protonMessageToIoTHubMessage.
@Override
protected IotHubTransportMessage protonMessageToIoTHubMessage(AmqpsMessage protonMsg) {
IotHubTransportMessage iotHubTransportMessage = super.protonMessageToIoTHubMessage(protonMsg);
iotHubTransportMessage.setMessageType(MessageType.DEVICE_TELEMETRY);
iotHubTransportMessage.setDeviceOperationType(DEVICE_OPERATION_UNKNOWN);
if (protonMsg.getMessageAnnotations() != null && protonMsg.getMessageAnnotations().getValue() != null) {
Map<Symbol, Object> applicationProperties = protonMsg.getMessageAnnotations().getValue();
for (Map.Entry<Symbol, Object> entry : applicationProperties.entrySet()) {
String propertyKey = entry.getKey().toString();
if (propertyKey.equals(INPUT_NAME_PROPERTY_KEY)) {
iotHubTransportMessage.setInputName(entry.getValue().toString());
}
}
}
// inputName may be null, and if it is, then the default callback and default callback context will be used from config
String inputName = iotHubTransportMessage.getInputName();
MessageCallback messageCallback = deviceClientConfig.getDeviceTelemetryMessageCallback(inputName);
Object messageContext = deviceClientConfig.getDeviceTelemetryMessageContext(inputName);
iotHubTransportMessage.setMessageCallback(messageCallback);
iotHubTransportMessage.setMessageCallbackContext(messageContext);
return iotHubTransportMessage;
}
use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.
the class MqttDeviceTwin method receive.
@Override
public IotHubTransportMessage receive() throws TransportException {
synchronized (this.receivedMessagesLock) {
IotHubTransportMessage message = null;
Pair<String, byte[]> messagePair = this.receivedMessages.peek();
if (messagePair != null) {
String topic = messagePair.getKey();
if (topic != null && topic.length() > 0) {
if (topic.length() > TWIN.length() && topic.startsWith(TWIN)) {
byte[] data = messagePair.getValue();
// remove this message from the queue as this is the correct handler
this.receivedMessages.poll();
if (topic.length() > RES.length() && topic.startsWith(RES)) {
// Tokenize on backslash
String[] topicTokens = topic.split(Pattern.quote("/"));
if (data != null && data.length > 0) {
message = new IotHubTransportMessage(data, MessageType.DEVICE_TWIN);
} else {
// Case for $iothub/twin/res/{status}/?$rid={request id}
// empty body
message = new IotHubTransportMessage(new byte[0], MessageType.DEVICE_TWIN);
}
message.setDeviceOperationType(DeviceOperations.DEVICE_OPERATION_UNKNOWN);
// Case for $iothub/twin/res/{status}/?$rid={request id}&$version={new version}
if (topicTokens.length > STATUS_TOKEN) {
message.setStatus(getStatus(topicTokens[STATUS_TOKEN]));
} else {
this.throwDeviceTwinTransportException(new IotHubServiceException("Message received without status"));
}
if (topicTokens.length > REQID_TOKEN) {
String requestId = getRequestId(topicTokens[REQID_TOKEN]);
// MQTT does not have the concept of correlationId for request/response handling but it does have a requestId
// To handle this we are setting the correlationId to the requestId to better handle correlation
// whether we use MQTT or AMQP.
message.setRequestId(requestId);
message.setCorrelationId(requestId);
if (requestMap.containsKey(requestId)) {
switch(requestMap.remove(requestId)) {
case DEVICE_OPERATION_TWIN_GET_REQUEST:
message.setDeviceOperationType(DeviceOperations.DEVICE_OPERATION_TWIN_GET_RESPONSE);
break;
case DEVICE_OPERATION_TWIN_UPDATE_REPORTED_PROPERTIES_REQUEST:
message.setDeviceOperationType(DeviceOperations.DEVICE_OPERATION_TWIN_UPDATE_REPORTED_PROPERTIES_RESPONSE);
break;
default:
message.setDeviceOperationType(DeviceOperations.DEVICE_OPERATION_UNKNOWN);
}
} else {
this.throwDeviceTwinTransportException(new UnsupportedOperationException("Request Id is mandatory"));
}
}
if (topicTokens.length > VERSION_TOKEN) {
message.setVersion(getVersion(topicTokens[VERSION_TOKEN]));
}
} else if (topic.length() > PATCH.length() && topic.startsWith(PATCH)) {
if (topic.startsWith(PATCH + BACKSLASH + PROPERTIES + BACKSLASH + DESIRED)) {
if (data != null) {
message = new IotHubTransportMessage(data, MessageType.DEVICE_TWIN);
message.setDeviceOperationType(DeviceOperations.DEVICE_OPERATION_TWIN_SUBSCRIBE_DESIRED_PROPERTIES_RESPONSE);
} else {
this.throwDeviceTwinTransportException(new UnsupportedOperationException());
}
// Case for $iothub/twin/PATCH/properties/desired/?$version={new version}
// Tokenize on backslash
String[] topicTokens = topic.split(Pattern.quote("/"));
if (topicTokens.length > PATCH_VERSION_TOKEN) {
if (message != null) {
message.setVersion(getVersion(topicTokens[PATCH_VERSION_TOKEN]));
}
}
} else {
this.throwDeviceTwinTransportException(new UnsupportedOperationException());
}
} else {
this.throwDeviceTwinTransportException(new UnsupportedOperationException());
}
}
}
}
return message;
}
}
use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.
the class FileUploadTaskTest method runSendRequestThrows.
/* Tests_SRS_FILEUPLOADTASK_21_031: [If run failed to send the request, it shall call the userCallback with the status `ERROR`, and abort the upload.] */
@Test
public void runSendRequestThrows() throws IOException, IllegalArgumentException, URISyntaxException {
// arrange
new NonStrictExpectations() {
{
new FileUploadSasUriRequest(VALID_BLOB_NAME);
result = mockFileUploadSasUriRequest;
mockFileUploadSasUriRequest.toJson();
result = VALID_REQUEST_JSON;
new IotHubTransportMessage(VALID_REQUEST_JSON);
result = mockMessageRequest;
mockHttpsTransportManager.getFileUploadSasUri(mockMessageRequest);
result = new IOException();
}
};
FileUploadTask fileUploadTask = Deencapsulation.newInstance(FileUploadTask.class, new Class[] { String.class, InputStream.class, long.class, HttpsTransportManager.class, IotHubEventCallback.class, Object.class }, VALID_BLOB_NAME, mockInputStream, VALID_STREAM_LENGTH, mockHttpsTransportManager, mockIotHubEventCallback, VALID_CALLBACK_CONTEXT);
// act
Deencapsulation.invoke(fileUploadTask, "run");
// assert
new Verifications() {
{
mockHttpsTransportManager.getFileUploadSasUri(mockMessageRequest);
times = 1;
mockIotHubEventCallback.execute(IotHubStatusCode.ERROR, VALID_CALLBACK_CONTEXT);
times = 1;
}
};
}
Aggregations