Search in sources :

Example 1 with IotHubTransportMessage

use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.

the class AmqpsReceiverLinkHandler method protonMessageToIoTHubMessage.

IotHubTransportMessage protonMessageToIoTHubMessage(AmqpsMessage protonMsg) {
    log.trace("Converting proton message to iot hub message for {} receiver link with address {} and link correlation id {}. Proton message correlation id {}", getLinkInstanceType(), this.receiverLinkAddress, this.linkCorrelationId, protonMsg.getCorrelationId());
    byte[] msgBody;
    Data d = (Data) protonMsg.getBody();
    if (d != null) {
        Binary b = d.getValue();
        msgBody = new byte[b.getLength()];
        ByteBuffer buffer = b.asByteBuffer();
        buffer.get(msgBody);
    } else {
        msgBody = new byte[0];
    }
    IotHubTransportMessage iotHubTransportMessage = new IotHubTransportMessage(msgBody, MessageType.UNKNOWN);
    Properties properties = protonMsg.getProperties();
    if (properties != null) {
        if (properties.getCorrelationId() != null) {
            iotHubTransportMessage.setCorrelationId(properties.getCorrelationId().toString());
        }
        if (properties.getMessageId() != null) {
            iotHubTransportMessage.setMessageId(properties.getMessageId().toString());
        }
        if (properties.getTo() != null) {
            iotHubTransportMessage.setProperty(AMQPS_APP_PROPERTY_PREFIX + TO_KEY, properties.getTo());
        }
        if (properties.getUserId() != null) {
            iotHubTransportMessage.setProperty(AMQPS_APP_PROPERTY_PREFIX + USER_ID_KEY, properties.getUserId().toString());
        }
        if (properties.getContentEncoding() != null) {
            iotHubTransportMessage.setContentEncoding(properties.getContentEncoding().toString());
        }
        if (properties.getContentType() != null) {
            iotHubTransportMessage.setContentTypeFinal(properties.getContentType().toString());
        }
    }
    if (protonMsg.getApplicationProperties() != null) {
        Map<String, Object> applicationProperties = protonMsg.getApplicationProperties().getValue();
        for (Map.Entry<String, Object> entry : applicationProperties.entrySet()) {
            String propertyKey = entry.getKey();
            if (propertyKey.equalsIgnoreCase(MessageProperty.CONNECTION_DEVICE_ID)) {
                iotHubTransportMessage.setConnectionDeviceId(entry.getValue().toString());
            } else if (propertyKey.equalsIgnoreCase(MessageProperty.CONNECTION_MODULE_ID)) {
                iotHubTransportMessage.setConnectionModuleId(entry.getValue().toString());
            } else if (!MessageProperty.RESERVED_PROPERTY_NAMES.contains(propertyKey)) {
                iotHubTransportMessage.setProperty(entry.getKey(), entry.getValue().toString());
            }
        }
    }
    return iotHubTransportMessage;
}
Also used : Data(org.apache.qpid.proton.amqp.messaging.Data) Binary(org.apache.qpid.proton.amqp.Binary) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) Properties(org.apache.qpid.proton.amqp.messaging.Properties) ByteBuffer(java.nio.ByteBuffer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with IotHubTransportMessage

use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.

the class HttpsIotHubConnection method receiveMessage.

/**
 * Receives an IotHubTransportMessage, if one exists.
 *
 * @return an IotHubTransportMessage, or null if none exists.
 *
 * @throws TransportException if the IoT Hub could not be reached.
 */
public IotHubTransportMessage receiveMessage() throws TransportException {
    synchronized (HTTPS_CONNECTION_LOCK) {
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_013: [The function shall send a request to the URL 'https://[iotHubHostname]/devices/[deviceId]/messages/devicebound?api-version=2016-02-03'.]
        IotHubMessageUri messageUri = new IotHubMessageUri(getHostName(), this.config.getDeviceId(), this.config.getModuleId());
        URL messageUrl = this.buildUrlFromString(HTTPS_HEAD_TAG + messageUri.toString());
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_014: [The function shall send a GET request.]
        HttpsRequest request = new HttpsRequest(messageUrl, HttpsMethod.GET, new byte[0], this.config.getProductInfo().getUserAgentString(), config.getProxySettings()).setHeaderField(HTTPS_PROPERTY_IOTHUB_TO_TAG, messageUri.getPath()).setHeaderField(HTTPS_PROPERTY_IOTHUB_MESSAGELOCKTIMEOUT_TAG, Integer.toString(this.config.getMessageLockTimeoutSecs()));
        // Codes_SRS_HTTPSIOTHUBCONNECTION_34_057: [This function shall retrieve a sas token from its config to use in the https request header.]
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_016: [The function shall set the header field 'authorization' to be a valid SAS token generated from the configuration parameters.]
        // Codes_SRS_HTTPSIOTHUBCONNECTION_34_061: [If this config is using x509 authentication, this function shall retrieve its sslcontext from its x509 Authentication object.]
        // Codes_SRS_HTTPSIOTHUBCONNECTION_25_041: [The function shall set the IotHub SSL context by calling setSSLContext on the request.]
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_015: [The function shall set the request read timeout to be the configuration parameter readTimeoutMillis.]
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_023: [If the IoT Hub could not be reached, the function shall throw a TransportException.]
        log.trace("Sending http request to check if any messages are ready to be received...");
        HttpsResponse response = this.sendRequest(request);
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_021: [If a response with IoT Hub status code OK is not received, the function shall return null.]
        IotHubTransportMessage transportMessage = null;
        // Codes_SRS_HTTPSIOTHUBCONNECTION_11_019: [If a response with IoT Hub status code OK is received, the function shall return the IoT Hub message included in the response.]
        IotHubStatusCode messageStatus = IotHubStatusCode.getIotHubStatusCode(response.getStatus());
        if (messageStatus == IotHubStatusCode.OK) {
            // Codes_SRS_HTTPSIOTHUBCONNECTION_11_020: [If a response with IoT Hub status code OK is received, the function shall save the response header field 'etag'.]
            String messageEtag = sanitizeEtag(response.getHeaderField(HTTPS_PROPERTY_ETAG_TAG));
            HttpsSingleMessage httpsMsg = HttpsSingleMessage.parseHttpsMessage(response);
            Message message = httpsMsg.toMessage();
            // callbacks are always for telemetry as HTTPS does not support Twin or Methods
            transportMessage = new IotHubTransportMessage(message.getBytes(), message.getMessageType(), message.getMessageId(), message.getCorrelationId(), message.getProperties());
            transportMessage.setMessageCallback(this.config.getDeviceTelemetryMessageCallback(message.getInputName()));
            transportMessage.setMessageCallbackContext(this.config.getDeviceTelemetryMessageContext(message.getInputName()));
            log.trace("Received http message with etag {} in transport message ({})", messageEtag, transportMessage);
            // Codes_SRS_HTTPSIOTHUBCONNECTION_11_070: [If the message status was OK this function shall save the received message and its eTag into its map.]
            this.messageToETagMap.put(transportMessage, messageEtag);
        }
        return transportMessage;
    }
}
Also used : IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) URL(java.net.URL)

Example 3 with IotHubTransportMessage

use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.

the class HttpsTransportManager method invokeMethod.

/**
 * Invoke a direct method to the provided uri
 * @param methodRequest the method request to make
 * @param uri the path to send the request to
 * @return the result of that request
 * @throws IOException if the IotHub cannot be reached
 */
private MethodResult invokeMethod(MethodRequest methodRequest, URI uri) throws IOException, TransportException {
    if (methodRequest == null) {
        // Codes_SRS_HTTPSTRANSPORTMANAGER_34_019: [If the provided method request is null, this function shall throw an IllegalArgumentException.]
        throw new IllegalArgumentException("direct method request cannot be null");
    }
    if (uri == null || uri.toString().isEmpty()) {
        // Codes_SRS_HTTPSTRANSPORTMANAGER_34_020: [If the provided uri is null or empty, this function shall throw an IllegalArgumentException.]
        throw new IllegalArgumentException("uri cannot be null or be an empty path");
    }
    // Codes_SRS_HTTPSTRANSPORTMANAGER_34_021: [This function shall set the methodrequest json as the body of the http message.]
    IotHubTransportMessage message = new IotHubTransportMessage(methodRequest.toJson());
    // Codes_SRS_HTTPSTRANSPORTMANAGER_34_022: [This function shall set the http method to POST.]
    message.setIotHubMethod(IotHubMethod.POST);
    // Codes_SRS_HTTPSTRANSPORTMANAGER_34_023: [This function shall set the http message's uri path to the provided uri path.]
    message.setUriPath(uri.toString());
    // Codes_SRS_HTTPSTRANSPORTMANAGER_34_024 [This function shall set a custom property of 'x-ms-edge-moduleId' to the value of <device id>/<module id> of the sending module/device.]
    Map<String, String> additionalHeaders = new HashMap<>();
    additionalHeaders.put(MODULE_ID, this.config.getDeviceId() + "/" + this.config.getModuleId());
    // Codes_SRS_HTTPSTRANSPORTMANAGER_34_025 [This function shall send the built message.]
    ResponseMessage responseMessage = this.send(message, additionalHeaders);
    if (responseMessage.getStatus() != IotHubStatusCode.OK && responseMessage.getStatus() != IotHubStatusCode.OK_EMPTY) {
        // Codes_SRS_HTTPSTRANSPORTMANAGER_34_026 [If the http response contains an error code, this function shall throw the associated exception.]
        throw IotHubStatusCode.getConnectionStatusException(responseMessage.getStatus(), new String(responseMessage.getBytes(), StandardCharsets.UTF_8));
    }
    // Codes_SRS_HTTPSTRANSPORTMANAGER_34_027 [If the http response doesn't contain an error code, this function return a method result with the response message body as the method result body.]
    String resultJson = new String(responseMessage.getBytes(), StandardCharsets.UTF_8);
    return new MethodResult(resultJson);
}
Also used : HashMap(java.util.HashMap) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) MethodResult(com.microsoft.azure.sdk.iot.device.edge.MethodResult)

Example 4 with IotHubTransportMessage

use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.

the class AmqpsMethodsSenderLinkHandler method iotHubMessageToProtonMessage.

@Override
protected MessageImpl iotHubMessageToProtonMessage(Message message) {
    if (message.getMessageType() == MessageType.DEVICE_METHODS) {
        MessageImpl protonMessage = super.iotHubMessageToProtonMessage(message);
        IotHubTransportMessage deviceMethodMessage = (IotHubTransportMessage) message;
        Properties properties;
        if (protonMessage.getProperties() != null) {
            properties = protonMessage.getProperties();
        } else {
            properties = new Properties();
        }
        if (deviceMethodMessage.getRequestId() != null) {
            properties.setCorrelationId(UUID.fromString(deviceMethodMessage.getRequestId()));
        }
        protonMessage.setProperties(properties);
        Map<String, Object> userProperties = new HashMap<>();
        if (deviceMethodMessage.getStatus() != null) {
            userProperties.put(APPLICATION_PROPERTY_KEY_IOTHUB_STATUS, Integer.parseInt(deviceMethodMessage.getStatus()));
        }
        if (protonMessage.getApplicationProperties() != null && protonMessage.getApplicationProperties().getValue() != null) {
            Map<String, Object> applicationPropertiesMap = protonMessage.getApplicationProperties().getValue();
            userProperties.putAll(applicationPropertiesMap);
        }
        ApplicationProperties applicationProperties = new ApplicationProperties(userProperties);
        protonMessage.setApplicationProperties(applicationProperties);
        return protonMessage;
    }
    return null;
}
Also used : HashMap(java.util.HashMap) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage) Properties(org.apache.qpid.proton.amqp.messaging.Properties) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) MessageImpl(org.apache.qpid.proton.message.impl.MessageImpl)

Example 5 with IotHubTransportMessage

use of com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage in project azure-iot-sdk-java by Azure.

the class FileUploadTask method sendNotification.

// Public method
@SuppressWarnings("UnusedReturnValue")
public IotHubStatusCode sendNotification(FileUploadCompletionNotification fileUploadStatusParser) throws IOException {
    IotHubTransportMessage message = new IotHubTransportMessage(fileUploadStatusParser.toJson());
    message.setIotHubMethod(IotHubMethod.POST);
    httpsTransportManager.open();
    ResponseMessage responseMessage = httpsTransportManager.sendFileUploadNotification(message);
    httpsTransportManager.close();
    validateServiceStatusCode(responseMessage, "Failed to complete the file upload notification");
    return responseMessage.getStatus();
}
Also used : ResponseMessage(com.microsoft.azure.sdk.iot.device.ResponseMessage) IotHubTransportMessage(com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage)

Aggregations

IotHubTransportMessage (com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage)129 Test (org.junit.Test)108 Message (com.microsoft.azure.sdk.iot.device.Message)37 MutablePair (org.apache.commons.lang3.tuple.MutablePair)33 Pair (org.apache.commons.lang3.tuple.Pair)33 DeviceTwin (com.microsoft.azure.sdk.iot.device.DeviceTwin)30 MqttDeviceTwin (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceTwin)25 HashMap (java.util.HashMap)24 DeviceOperations (com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceOperations)16 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)16 MessageType (com.microsoft.azure.sdk.iot.device.MessageType)14 Verifications (mockit.Verifications)10 MqttDeviceMethod (com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttDeviceMethod)8 NonStrictExpectations (mockit.NonStrictExpectations)8 IOException (java.io.IOException)5 FileUploadTask (com.microsoft.azure.sdk.iot.device.fileupload.FileUploadTask)4 MessageCallback (com.microsoft.azure.sdk.iot.device.MessageCallback)3 MethodResult (com.microsoft.azure.sdk.iot.device.edge.MethodResult)3 HttpsTransportManager (com.microsoft.azure.sdk.iot.device.transport.https.HttpsTransportManager)3 HashSet (java.util.HashSet)3