Search in sources :

Example 61 with HttpResponse

use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.

the class DeviceMethod method invoke.

/**
     * Directly invokes a method on the device and return its result.
     *
     * @param deviceId is the device identification.
     * @param methodName is the name of the method that shall be invoked on the device.
     * @param responseTimeoutInSeconds is the maximum waiting time for a response from the device in seconds.
     * @param connectTimeoutInSeconds is the maximum waiting time for a response from the connection in seconds.
     * @param payload is the the method parameter
     * @return the status and payload resulted from the method invoke
     * @throws IotHubException This exception is thrown if the response verification failed
     * @throws IOException This exception is thrown if the IO operation failed
     */
public synchronized MethodResult invoke(String deviceId, String methodName, Long responseTimeoutInSeconds, Long connectTimeoutInSeconds, Object payload) throws IotHubException, IOException {
    /* Codes_SRS_DEVICEMETHOD_21_004: [The invoke shall throw IllegalArgumentException if the provided deviceId is null or empty.] */
    if ((deviceId == null) || deviceId.isEmpty()) {
        throw new IllegalArgumentException("deviceId is empty or null.");
    }
    /* Codes_SRS_DEVICEMETHOD_21_005: [The invoke shall throw IllegalArgumentException if the provided methodName is null, empty, or not valid.] */
    if ((methodName == null) || methodName.isEmpty()) {
        throw new IllegalArgumentException("methodName is empty or null.");
    }
    /* Codes_SRS_DEVICEMETHOD_21_006: [The invoke shall throw IllegalArgumentException if the provided responseTimeoutInSeconds is negative.] */
    /* Codes_SRS_DEVICEMETHOD_21_007: [The invoke shall throw IllegalArgumentException if the provided connectTimeoutInSeconds is negative.] */
    /* Codes_SRS_DEVICEMETHOD_21_014: [The invoke shall bypass the Exception if one of the functions called by invoke failed.] */
    MethodParser methodParser = new MethodParser(methodName, responseTimeoutInSeconds, connectTimeoutInSeconds, payload);
    /* Codes_SRS_DEVICEMETHOD_21_011: [The invoke shall add a HTTP body with Json created by the `serializer.MethodParser`.] */
    String json = methodParser.toJson();
    if (json == null) {
        /* Codes_SRS_DEVICEMETHOD_21_012: [If `MethodParser` return a null Json, the invoke shall throw IllegalArgumentException.] */
        throw new IllegalArgumentException("MethodParser return null Json");
    }
    /* Codes_SRS_DEVICEMETHOD_21_008: [The invoke shall build the Method URL `{iot hub}/twins/{device id}/methods/` by calling getUrlMethod.] */
    URL url = this.iotHubConnectionString.getUrlMethod(deviceId);
    long responseTimeout, connectTimeout;
    if (responseTimeoutInSeconds == null) {
        // If timeout is not set, it defaults to 30 seconds
        responseTimeout = DEFAULT_RESPONSE_TIMEOUT;
    } else {
        responseTimeout = responseTimeoutInSeconds;
    }
    if (connectTimeoutInSeconds == null) {
        connectTimeout = DEFAULT_CONNECT_TIMEOUT;
    } else {
        connectTimeout = connectTimeoutInSeconds;
    }
    // Calculate total timeout in milliseconds
    long timeoutInMs = (responseTimeout + connectTimeout) * THOUSAND_MS;
    /* Codes_SRS_DEVICEMETHOD_21_009: [The invoke shall send the created request and get the response using the HttpRequester.] */
    /* Codes_SRS_DEVICEMETHOD_21_010: [The invoke shall create a new HttpRequest with http method as `POST`.] */
    HttpResponse response = DeviceOperations.request(this.iotHubConnectionString, url, HttpMethod.POST, json.getBytes(StandardCharsets.UTF_8), String.valueOf(requestId++), timeoutInMs);
    /* Codes_SRS_DEVICEMETHOD_21_013: [The invoke shall deserialize the payload using the `serializer.MethodParser`.] */
    MethodParser methodParserResponse = new MethodParser();
    methodParserResponse.fromJson(new String(response.getBody(), StandardCharsets.UTF_8));
    /* Codes_SRS_DEVICEMETHOD_21_015: [If the HttpStatus represents success, the invoke shall return the status and payload using the `MethodResult` class.] */
    return new MethodResult(methodParserResponse.getStatus(), methodParserResponse.getPayload());
}
Also used : HttpResponse(com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) URL(java.net.URL) MethodParser(com.microsoft.azure.sdk.iot.deps.serializer.MethodParser)

Example 62 with HttpResponse

use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.

the class DeviceOperationsTest method invoke_throwOnUserAgent_failed.

/* Tests_SRS_DEVICE_OPERATIONS_21_012: [The request shall add to the HTTP header a `User-Agent` key with the client Id and service version.] */
@Test(expected = IllegalArgumentException.class)
public void invoke_throwOnUserAgent_failed(@Mocked IotHubServiceSasToken iotHubServiceSasToken, @Mocked HttpRequest httpRequest) throws Exception {
    //arrange
    new NonStrictExpectations() {

        {
            iotHubServiceSasToken.toString();
            result = STANDARD_SASTOKEN_STRING;
            httpRequest.setReadTimeoutMillis(DEFAULT_HTTP_TIMEOUT_MS);
            result = httpRequest;
            httpRequest.setHeaderField(AUTHORIZATION, STANDARD_SASTOKEN_STRING);
            result = httpRequest;
            httpRequest.setHeaderField(REQUEST_ID, STANDARD_REQUEST_ID);
            result = httpRequest;
            httpRequest.setHeaderField(USER_AGENT, TransportUtils.getJavaServiceClientIdentifier() + TransportUtils.getServiceVersion());
            result = new IllegalArgumentException();
        }
    };
    //act
    HttpResponse response = DeviceOperations.request(IOT_HUB_CONNECTION_STRING, new URL(STANDARD_URL), HttpMethod.POST, STANDARD_PAYLOAD, STANDARD_REQUEST_ID, 0);
}
Also used : HttpResponse(com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Example 63 with HttpResponse

use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.

the class DeviceOperationsTest method invoke_succeed.

/* Tests_SRS_DEVICE_OPERATIONS_21_017: [If the resulted status represents success, the request shall return the http response.] */
@Test
public void invoke_succeed(@Mocked IotHubServiceSasToken iotHubServiceSasToken, @Mocked HttpRequest httpRequest) throws Exception {
    //arrange
    final int status = 200;
    final byte[] body = { 1 };
    final Map<String, List<String>> headerFields = new HashMap<>();
    final byte[] errorReason = "succeed".getBytes();
    HttpResponse sendResponse = new HttpResponse(status, body, headerFields, errorReason);
    new NonStrictExpectations() {

        {
            iotHubServiceSasToken.toString();
            result = STANDARD_SASTOKEN_STRING;
            httpRequest.setReadTimeoutMillis(DEFAULT_HTTP_TIMEOUT_MS);
            result = httpRequest;
            httpRequest.setHeaderField(AUTHORIZATION, STANDARD_SASTOKEN_STRING);
            result = httpRequest;
            httpRequest.setHeaderField(REQUEST_ID, STANDARD_REQUEST_ID);
            result = httpRequest;
            httpRequest.setHeaderField(USER_AGENT, TransportUtils.getJavaServiceClientIdentifier() + TransportUtils.getServiceVersion());
            result = httpRequest;
            httpRequest.setHeaderField(ACCEPT, ACCEPT_VALUE);
            result = httpRequest;
            httpRequest.setHeaderField(CONTENT_TYPE, ACCEPT_VALUE + "; " + ACCEPT_CHARSET);
            result = httpRequest;
            httpRequest.send();
            result = sendResponse;
            IotHubExceptionManager.httpResponseVerification(sendResponse);
        }
    };
    //act
    HttpResponse response = DeviceOperations.request(IOT_HUB_CONNECTION_STRING, new URL(STANDARD_URL), HttpMethod.POST, STANDARD_PAYLOAD, STANDARD_REQUEST_ID, 0);
    //assert
    assertEquals(response, sendResponse);
    new Verifications() {

        {
            iotHubServiceSasToken.toString();
            times = 1;
            httpRequest.setReadTimeoutMillis(DEFAULT_HTTP_TIMEOUT_MS);
            times = 1;
            httpRequest.setHeaderField(anyString, anyString);
            times = 5;
            httpRequest.send();
            times = 1;
            IotHubExceptionManager.httpResponseVerification(sendResponse);
            times = 1;
        }
    };
}
Also used : HashMap(java.util.HashMap) HttpResponse(com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse) List(java.util.List) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) URL(java.net.URL) Test(org.junit.Test)

Example 64 with HttpResponse

use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.

the class DeviceOperationsTest method invoke_throwOnAutorization_failed.

/* Tests_SRS_DEVICE_OPERATIONS_21_010: [The request shall add to the HTTP header an `authorization` key with the SASToken.] */
@Test(expected = IllegalArgumentException.class)
public void invoke_throwOnAutorization_failed(@Mocked IotHubServiceSasToken iotHubServiceSasToken, @Mocked HttpRequest httpRequest) throws Exception {
    //arrange
    new NonStrictExpectations() {

        {
            iotHubServiceSasToken.toString();
            result = STANDARD_SASTOKEN_STRING;
            httpRequest.setReadTimeoutMillis(DEFAULT_HTTP_TIMEOUT_MS);
            result = httpRequest;
            httpRequest.setHeaderField(AUTHORIZATION, STANDARD_SASTOKEN_STRING);
            result = new IllegalArgumentException();
        }
    };
    //act
    HttpResponse response = DeviceOperations.request(IOT_HUB_CONNECTION_STRING, new URL(STANDARD_URL), HttpMethod.POST, STANDARD_PAYLOAD, STANDARD_REQUEST_ID, 0);
}
Also used : HttpResponse(com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Example 65 with HttpResponse

use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.

the class DeviceOperationsTest method invoke_throwOnCreateIotHubServiceSasToken_failed.

/* Tests_SRS_DEVICE_OPERATIONS_21_006: [The request shall create a new SASToken with the ServiceConnect rights.] */
@Test(expected = IllegalArgumentException.class)
public void invoke_throwOnCreateIotHubServiceSasToken_failed() throws Exception {
    //arrange
    new MockUp<IotHubServiceSasToken>() {

        @Mock
        void $init(IotHubConnectionString iotHubConnectionString) {
            throw new IllegalArgumentException();
        }
    };
    //act
    HttpResponse response = DeviceOperations.request(IOT_HUB_CONNECTION_STRING, new URL(STANDARD_URL), HttpMethod.POST, STANDARD_PAYLOAD, STANDARD_REQUEST_ID, 0);
}
Also used : HttpResponse(com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) URL(java.net.URL) Test(org.junit.Test)

Aggregations

HttpResponse (com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse)130 Test (org.junit.Test)91 HashMap (java.util.HashMap)63 List (java.util.List)60 URL (java.net.URL)56 HttpRequest (com.microsoft.azure.sdk.iot.service.transport.http.HttpRequest)39 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)24 LinkedList (java.util.LinkedList)16 HttpMethod (com.microsoft.azure.sdk.iot.service.transport.http.HttpMethod)14 IOException (java.io.IOException)10 DeviceParser (com.microsoft.azure.sdk.iot.deps.serializer.DeviceParser)8 Proxy (java.net.Proxy)7 ProxyOptions (com.microsoft.azure.sdk.iot.service.ProxyOptions)6 IotHubServiceSasToken (com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken)6 Map (java.util.Map)6 IotHubBadFormatException (com.microsoft.azure.sdk.iot.service.exceptions.IotHubBadFormatException)5 IotHubException (com.microsoft.azure.sdk.iot.service.exceptions.IotHubException)5 ConfigurationParser (com.microsoft.azure.sdk.iot.deps.serializer.ConfigurationParser)4 QueryRequestParser (com.microsoft.azure.sdk.iot.deps.serializer.QueryRequestParser)4 MalformedURLException (java.net.MalformedURLException)4