Search in sources :

Example 1 with MethodResult

use of com.microsoft.azure.sdk.iot.device.edge.MethodResult 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 2 with MethodResult

use of com.microsoft.azure.sdk.iot.device.edge.MethodResult in project azure-iot-sdk-java by Azure.

the class MethodResultTest method constructorParsesJsonAndGettersWork.

// Tests_SRS_DIRECTMETHODRESULT_34_001: [This function shall return the saved status.]
// Tests_SRS_DIRECTMETHODRESULT_34_002: [This function shall return the saved status.]
// Tests_SRS_DIRECTMETHODRESULT_34_003: [This constructor shall retrieve the payload and status from the provided json.]
@Test
public void constructorParsesJsonAndGettersWork() {
    // arrange
    String json = "{\n" + "  \"status\": \"2\",\n" + "  \"payload\": \"somePayload\"\n" + "}";
    // act
    MethodResult result = new MethodResult(json);
    // assert
    assertEquals("somePayload", result.getPayload());
    assertEquals(2, result.getStatus());
}
Also used : MethodResult(com.microsoft.azure.sdk.iot.device.edge.MethodResult) Test(org.junit.Test)

Example 3 with MethodResult

use of com.microsoft.azure.sdk.iot.device.edge.MethodResult in project azure-iot-sdk-java by Azure.

the class ModuleClientTest method invokeMethodOnDeviceSuccess.

// Tests_SRS_MODULECLIENT_34_033: [This function shall create an HttpsTransportManager and use it to invoke the method on the device.]
@Test
public void invokeMethodOnDeviceSuccess() throws URISyntaxException, ModuleClientException, IOException, TransportException {
    // arrange
    baseExpectations();
    ModuleClient client = new ModuleClient("connection string", IotHubClientProtocol.AMQPS);
    final String expectedDeviceId = "someDevice";
    new NonStrictExpectations() {

        {
            new HttpsTransportManager((DeviceClientConfig) any);
            result = mockedHttpsTransportManager;
            mockedHttpsTransportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, "");
            result = mockedMethodResult;
        }
    };
    // act
    MethodResult actualResult = client.invokeMethod(expectedDeviceId, mockedMethodRequest);
    // assert
    assertEquals(mockedMethodResult, actualResult);
    new Verifications() {

        {
            mockedHttpsTransportManager.open();
            times = 1;
            mockedHttpsTransportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, "");
            times = 1;
        }
    };
}
Also used : HttpsTransportManager(com.microsoft.azure.sdk.iot.device.transport.https.HttpsTransportManager) MethodResult(com.microsoft.azure.sdk.iot.device.edge.MethodResult) Test(org.junit.Test)

Example 4 with MethodResult

use of com.microsoft.azure.sdk.iot.device.edge.MethodResult in project azure-iot-sdk-java by Azure.

the class ModuleClientTest method invokeMethodOnModuleSuccess.

// Tests_SRS_MODULECLIENT_34_035: [This function shall create an HttpsTransportManager and use it to invoke the method on the module.]
@Test
public void invokeMethodOnModuleSuccess() throws URISyntaxException, ModuleClientException, IOException, TransportException {
    // arrange
    baseExpectations();
    ModuleClient client = new ModuleClient("connection string", IotHubClientProtocol.AMQPS);
    final String expectedDeviceId = "someDevice";
    final String expectedModuleId = "someModule";
    new NonStrictExpectations() {

        {
            new HttpsTransportManager((DeviceClientConfig) any);
            result = mockedHttpsTransportManager;
            mockedHttpsTransportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, expectedModuleId);
            result = mockedMethodResult;
        }
    };
    // act
    MethodResult actualResult = client.invokeMethod(expectedDeviceId, expectedModuleId, mockedMethodRequest);
    // assert
    assertEquals(mockedMethodResult, actualResult);
    new Verifications() {

        {
            mockedHttpsTransportManager.open();
            times = 1;
            mockedHttpsTransportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, expectedModuleId);
            times = 1;
        }
    };
}
Also used : HttpsTransportManager(com.microsoft.azure.sdk.iot.device.transport.https.HttpsTransportManager) MethodResult(com.microsoft.azure.sdk.iot.device.edge.MethodResult) Test(org.junit.Test)

Example 5 with MethodResult

use of com.microsoft.azure.sdk.iot.device.edge.MethodResult in project azure-iot-sdk-java by Azure.

the class ModuleInvokeMethodSample method main.

/**
 * Receives requests from an IoT Hub. Default protocol is to use
 * MQTT transport.
 *
 * @param args
 * args[0] = IoT Hub connection string
 * args[1] = protocol (one of 'mqtt' or 'amqps' or 'mqtt_ws' or 'amqps_ws')
 * args[2] = the method name
 * args[3] = the string payload to send alongside the method invocation
 * args[4] = the device id of the device to invoke the method on
 * args[5] = (optional) the module id to invoke the method on
 */
public static void main(String[] args) throws IOException, URISyntaxException, ModuleClientException {
    System.out.println("Starting...");
    System.out.println("Beginning setup.");
    if (args.length != 4 && args.length != 5) {
        System.out.format("Expected 4 or 5 arguments but received: %d.\n" + "The program should be called with the following args: \n" + "1. (mqtt | https | amqps | amqps_ws | mqtt_ws)\n" + "2. The name of the method to invoke\n" + "3. The string payload to send alongside the method invocation\n" + "4. The id of the device to invoke the method on\n" + "5. (optional) The id of the module to invoke the method on\n", args.length);
        return;
    }
    IotHubClientProtocol protocol;
    String protocolStr = args[0];
    if (protocolStr.equalsIgnoreCase("https")) {
        throw new UnsupportedOperationException("Module Client does not support HTTPS communication");
    } else if (protocolStr.equalsIgnoreCase("amqps")) {
        protocol = IotHubClientProtocol.AMQPS;
    } else if (protocolStr.equalsIgnoreCase("mqtt")) {
        protocol = IotHubClientProtocol.MQTT;
    } else if (protocolStr.equalsIgnoreCase("amqps_ws")) {
        protocol = IotHubClientProtocol.AMQPS_WS;
    } else if (protocolStr.equalsIgnoreCase("mqtt_ws")) {
        protocol = IotHubClientProtocol.MQTT_WS;
    } else {
        System.out.format("Expected argument 2 to be one of 'mqtt', 'mqtt_ws', 'amqps' or 'amqps_ws' but received %s\n", protocolStr);
        return;
    }
    String methodName = args[1];
    String methodPayload = args[2];
    String deviceIdToInvokeOn = args[3];
    String moduleIdToInvokeOn = args.length > 4 ? args[4] : null;
    ModuleClient client = ModuleClient.createFromEnvironment(protocol);
    client.open();
    MethodRequest methodRequest = new MethodRequest(methodName, methodPayload);
    MethodResult result;
    try {
        if (moduleIdToInvokeOn == null || moduleIdToInvokeOn.isEmpty()) {
            result = invokeMethodOnDevice(methodName, deviceIdToInvokeOn, client, methodRequest);
        } else {
            result = invokeMethodOnModule(methodName, deviceIdToInvokeOn, moduleIdToInvokeOn, client, methodRequest);
        }
        System.out.println("Received response status: " + result.getStatus());
        System.out.println("Received response payload: " + result.getPayloadObject());
    } catch (ModuleClientException e) {
        System.out.println("Encountered an exception while invoking method");
        e.printStackTrace();
    } finally {
        client.closeNow();
    }
}
Also used : MethodRequest(com.microsoft.azure.sdk.iot.device.edge.MethodRequest) ModuleClientException(com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException) MethodResult(com.microsoft.azure.sdk.iot.device.edge.MethodResult)

Aggregations

MethodResult (com.microsoft.azure.sdk.iot.device.edge.MethodResult)11 Test (org.junit.Test)5 HttpsTransportManager (com.microsoft.azure.sdk.iot.device.transport.https.HttpsTransportManager)4 MethodRequest (com.microsoft.azure.sdk.iot.device.edge.MethodRequest)3 ModuleClientException (com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException)3 IotHubTransportMessage (com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage)3 MainApiException (io.swagger.server.api.MainApiException)2 JsonObject (io.vertx.core.json.JsonObject)2 HashMap (java.util.HashMap)1