Search in sources :

Example 6 with HttpRequest

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

the class ContractAPIHttp method prepareRequest.

private HttpRequest prepareRequest(URL url, HttpMethod method, byte[] payload, Map<String, String> headersMap) throws IllegalArgumentException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Null URL");
    }
    if (method == null) {
        throw new IllegalArgumentException("Null method");
    }
    if (payload == null) {
        throw new IllegalArgumentException("Null payload");
    }
    if (ContractAPIHttp.DEFAULT_HTTP_TIMEOUT_MS < 0) {
        throw new IllegalArgumentException("HTTP Request timeout shouldn't be negative");
    }
    HttpRequest request = new HttpRequest(url, method, payload);
    /*
            Set this method with appropriate time value once discussion with service concludes
            request.setReadTimeoutMillis(timeoutInMs);
        */
    request.setHeaderField(USER_AGENT, USER_AGENT_VALUE);
    request.setHeaderField(ACCEPT, ACCEPT_VALUE);
    request.setHeaderField(CONTENT_TYPE, ACCEPT_VALUE + "; " + ACCEPT_CHARSET);
    request.setHeaderField(CONTENT_LENGTH, String.valueOf(payload.length));
    if (headersMap != null) {
        for (Map.Entry<String, String> header : headersMap.entrySet()) {
            request.setHeaderField(header.getKey(), header.getValue());
        }
    }
    return request;
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with HttpRequest

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

the class ContractAPIHttp method requestNonceForTPM.

/**
 * Requests hub to provide a device key to begin authentication over HTTP (Only for TPM)
 * @param responseCallback A non {@code null} value for the callback
 * @param dpsAuthorizationCallbackContext An object for context. Can be {@code null}
 * @param requestData A non {@code null} value with all the required request data
 * @throws ProvisioningDeviceClientException If any of the parameters are invalid ({@code null} or empty)
 * @throws ProvisioningDeviceTransportException If any of the API calls to transport fail
 * @throws ProvisioningDeviceHubException If hub responds back with status other than 300 or less
 */
public synchronized void requestNonceForTPM(RequestData requestData, ResponseCallback responseCallback, Object dpsAuthorizationCallbackContext) throws ProvisioningDeviceClientException {
    // SRS_ContractAPIHttp_25_003: [If either registrationId, sslcontext or responseCallback is null or if registrationId is empty then this method shall throw ProvisioningDeviceClientException.]
    if (requestData.getRegistrationId() == null || requestData.getRegistrationId().isEmpty()) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("registration Id cannot be null or empty"));
    }
    if (requestData.getEndorsementKey() == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("Endorsement key cannot be null"));
    }
    if (requestData.getStorageRootKey() == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("Storage root key cannot be null"));
    }
    if (requestData.getSslContext() == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("sslContext cannot be null"));
    }
    if (responseCallback == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("responseCallback cannot be null"));
    }
    try {
        // SRS_ContractAPIHttp_25_004: [This method shall retrieve the Url by calling 'generateRegisterUrl' on an object for UrlPathBuilder.]
        String url = new UrlPathBuilder(this.hostName, this.idScope, ProvisioningDeviceClientTransportProtocol.HTTPS).generateRegisterUrl(requestData.getRegistrationId());
        String base64EncodedEk = new String(encodeBase64(requestData.getEndorsementKey()), StandardCharsets.UTF_8);
        String base64EncodedSrk = new String(encodeBase64(requestData.getStorageRootKey()), StandardCharsets.UTF_8);
        // SRS_ContractAPIHttp_25_025: [ This method shall build the required Json input using parser. ]
        byte[] payload = new DeviceRegistrationParser(requestData.getRegistrationId(), requestData.getPayload(), base64EncodedEk, base64EncodedSrk).toJson().getBytes(StandardCharsets.UTF_8);
        // SRS_ContractAPIHttp_25_005: [This method shall prepare the PUT request by setting following headers on a HttpRequest 1. User-Agent : User Agent String for the SDK 2. Accept : "application/json" 3. Content-Type: "application/json; charset=utf-8".]
        HttpRequest httpRequest = this.prepareRequest(new URL(url), HttpMethod.PUT, payload, null);
        // SRS_ContractAPIHttp_25_006: [This method shall set the SSLContext for the Http Request.]
        httpRequest.setSSLContext(requestData.getSslContext());
        HttpResponse httpResponse = null;
        try {
            // SRS_ContractAPIHttp_25_007: [This method shall send http request and verify the status by calling 'ProvisioningDeviceClientExceptionManager.verifyHttpResponse'.]
            httpResponse = httpRequest.send();
            ProvisioningDeviceClientExceptionManager.verifyHttpResponse(httpResponse);
        } catch (ProvisioningDeviceHubException e) {
            // SRS_ContractAPIHttp_25_008: [If service return a status as 404 then this method shall trigger the callback to the user with the response message.]
            if (httpResponse.getStatus() == ACCEPTABLE_NONCE_HTTP_STATUS) {
                String tpmRegistrationResultJson = new String(httpResponse.getErrorReason(), StandardCharsets.UTF_8);
                TpmRegistrationResultParser registerResponseTPMParser = TpmRegistrationResultParser.createFromJson(tpmRegistrationResultJson);
                byte[] base64DecodedAuthKey = decodeBase64(registerResponseTPMParser.getAuthenticationKey().getBytes(StandardCharsets.UTF_8));
                responseCallback.run(new ResponseData(base64DecodedAuthKey, ContractState.DPS_REGISTRATION_RECEIVED, 0), dpsAuthorizationCallbackContext);
                return;
            } else {
                // SRS_ContractAPIHttp_25_009: [If service return any other status other than 404 then this method shall throw ProvisioningDeviceTransportException in case of 202 or ProvisioningDeviceHubException on any other status.]
                throw e;
            }
        }
    } catch (IOException e) {
        throw new ProvisioningDeviceTransportException(e);
    }
    throw new ProvisioningDeviceTransportException("Service did not return any authorization request");
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest) ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse) TpmRegistrationResultParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.TpmRegistrationResultParser) IOException(java.io.IOException) URL(java.net.URL) UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)

Example 8 with HttpRequest

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

the class ContractAPIHttp method authenticateWithProvisioningService.

/**
 * Requests hub to authenticate this connection and start the registration process over HTTP
 * @param requestData A non {@code null} value with all the required request data
 * @param responseCallback A non {@code null} value for the callback
 * @param dpsAuthorizationCallbackContext An object for context. Can be {@code null}
 * @throws ProvisioningDeviceClientException If any of the parameters are invalid ({@code null} or empty)
 * @throws ProvisioningDeviceTransportException If any of the API calls to transport fail
 * @throws ProvisioningDeviceHubException If hub responds back with status other than 300 or less
 */
public synchronized void authenticateWithProvisioningService(RequestData requestData, ResponseCallback responseCallback, Object dpsAuthorizationCallbackContext) throws ProvisioningDeviceClientException {
    // SRS_ContractAPIHttp_25_011: [If either registrationId, sslcontext or responseCallback is null or if registrationId is empty then this method shall throw ProvisioningDeviceClientException.]
    if (requestData.getRegistrationId() == null || requestData.getRegistrationId().isEmpty()) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("registration Id cannot be null or empty"));
    }
    if (requestData.getSslContext() == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("sslContext cannot be null"));
    }
    if (responseCallback == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("responseCallback cannot be null"));
    }
    try {
        // SRS_ContractAPIHttp_25_012: [This method shall retrieve the Url by calling 'generateRegisterUrl' on an object for UrlPathBuilder.]
        String url = new UrlPathBuilder(this.hostName, this.idScope, ProvisioningDeviceClientTransportProtocol.HTTPS).generateRegisterUrl(requestData.getRegistrationId());
        Map<String, String> headersMap = null;
        if (requestData.getSasToken() != null) {
            headersMap = new HashMap<>();
            headersMap.put(AUTHORIZATION, requestData.getSasToken());
        }
        // SRS_ContractAPIHttp_25_026: [ This method shall build the required Json input using parser. ]
        byte[] payload;
        if (requestData.getEndorsementKey() != null && requestData.getStorageRootKey() != null) {
            // SRS_ContractAPIHttp_25_027: [ This method shall base 64 encoded endorsement key, storage root key. ]
            String base64EncodedEk = new String(encodeBase64(requestData.getEndorsementKey()), StandardCharsets.UTF_8);
            String base64EncodedSrk = new String(encodeBase64(requestData.getStorageRootKey()), StandardCharsets.UTF_8);
            payload = new DeviceRegistrationParser(requestData.getRegistrationId(), requestData.getPayload(), base64EncodedEk, base64EncodedSrk).toJson().getBytes(StandardCharsets.UTF_8);
        } else {
            payload = new DeviceRegistrationParser(requestData.getRegistrationId(), requestData.getPayload()).toJson().getBytes(StandardCharsets.UTF_8);
        }
        // SRS_ContractAPIHttp_25_013: [This method shall prepare the PUT request by setting following headers on a HttpRequest 1. User-Agent : User Agent String for the SDK 2. Accept : "application/json" 3. Content-Type: "application/json; charset=utf-8" 4. Authorization: specified sas token as authorization if a non null value is given.]
        HttpRequest httpRequest = this.prepareRequest(new URL(url), HttpMethod.PUT, payload, headersMap);
        // SRS_ContractAPIHttp_25_014: [This method shall set the SSLContext for the Http Request.]
        httpRequest.setSSLContext(requestData.getSslContext());
        // SRS_ContractAPIHttp_25_015: [This method shall send http request and verify the status by calling 'ProvisioningDeviceClientExceptionManager.verifyHttpResponse'.]
        // SRS_ContractAPIHttp_25_017: [If service return any other status other than <300 then this method shall throw ProvisioningDeviceHubException.]
        HttpResponse httpResponse = this.sendRequest(httpRequest);
        // Set the retry after value
        processRetryAfterValue(httpResponse);
        // SRS_ContractAPIHttp_25_016: [If service return a status as < 300 then this method shall trigger the callback to the user with the response message.]
        responseCallback.run(new ResponseData(httpResponse.getBody(), ContractState.DPS_REGISTRATION_RECEIVED, 0), dpsAuthorizationCallbackContext);
    } catch (IOException e) {
        throw new ProvisioningDeviceTransportException(e);
    }
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest) ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL) UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)

Example 9 with HttpRequest

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

the class HttpsRequestTest method sendReturnsHeaderFields.

// Tests_SRS_HTTPSREQUEST_25_006: [The function shall return the HTTPS response received, including the status code, body, header fields, and error reason (if any).]
@Test
public void sendReturnsHeaderFields(@Mocked final HttpConnection mockConn, @Mocked final URL mockUrl) throws IOException {
    // Arrange
    final Map<String, List<String>> headerFields = new HashMap<>();
    final String field = "test-field";
    final List<String> values = new LinkedList<>();
    final String value0 = "test-value0";
    final String value1 = "test-value1";
    values.add(value0);
    values.add(value1);
    headerFields.put(field, values);
    final String expectedValues = value0 + "," + value1;
    final HttpMethod httpsMethod = HttpMethod.POST;
    final byte[] body = new byte[0];
    new NonStrictExpectations() {

        {
            mockUrl.getProtocol();
            result = "http";
            mockConn.getResponseHeaders();
            result = headerFields;
        }
    };
    HttpRequest request = new HttpRequest(mockUrl, httpsMethod, body);
    // Act
    HttpResponse response = request.send();
    String testValues = response.getHeaderField(field);
    // Assert
    assertThat(testValues, is(expectedValues));
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest) HashMap(java.util.HashMap) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse) List(java.util.List) LinkedList(java.util.LinkedList) LinkedList(java.util.LinkedList) HttpMethod(com.microsoft.azure.sdk.iot.deps.transport.http.HttpMethod) Test(org.junit.Test)

Example 10 with HttpRequest

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

the class HttpsRequestTest method sendHasCorrectHttpsMethod.

// Tests_SRS_HTTPSREQUEST_25_005: [The function shall send an HTTPS request as formatted in the constructor.]
@Test
public void sendHasCorrectHttpsMethod() throws IOException {
    // Arrange
    final HttpMethod expectedMethod = HttpMethod.GET;
    final byte[] body = new byte[0];
    new MockUp<HttpConnection>() {

        HttpMethod testMethod;

        @Mock
        public void $init(URL url, HttpMethod method) {
            this.testMethod = method;
        }

        @Mock
        public void connect() throws IOException {
            assertThat(testMethod, is(expectedMethod));
        }

        @Mock
        public void setRequestMethod(HttpMethod method) {
            this.testMethod = method;
        }

        // every method that is used must be manually mocked.
        @Mock
        public void setRequestHeader(String field, String value) {
        }

        @Mock
        public void writeOutput(byte[] body) {
        }

        @Mock
        public byte[] readInput() throws IOException {
            return new byte[0];
        }

        @Mock
        public byte[] readError() throws IOException {
            return new byte[0];
        }

        @Mock
        public int getResponseStatus() throws IOException {
            return 0;
        }

        @Mock
        public Map<String, List<String>> getResponseHeaders() throws IOException {
            return new HashMap<>();
        }
    };
    // Assert
    HttpRequest request = new HttpRequest(new URL("http://www.microsoft.com"), expectedMethod, body);
    // Act
    request.send();
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest) HashMap(java.util.HashMap) List(java.util.List) LinkedList(java.util.LinkedList) HttpMethod(com.microsoft.azure.sdk.iot.deps.transport.http.HttpMethod) URL(java.net.URL) Test(org.junit.Test)

Aggregations

HttpRequest (com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest)27 Test (org.junit.Test)21 HttpMethod (com.microsoft.azure.sdk.iot.deps.transport.http.HttpMethod)16 URL (java.net.URL)12 IOException (java.io.IOException)11 HttpResponse (com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)10 ProvisioningSasToken (com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken)6 HashMap (java.util.HashMap)6 ContractApiHttp (com.microsoft.azure.sdk.iot.provisioning.service.contract.ContractApiHttp)5 LinkedList (java.util.LinkedList)5 List (java.util.List)5 HttpConnection (com.microsoft.azure.sdk.iot.deps.transport.http.HttpConnection)4 UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)3 ResponseData (com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)3 Map (java.util.Map)3 DeviceRegistrationParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)2 ProvisioningConnectionString (com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString)2 ProvisioningServiceClientTransportException (com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientTransportException)2 TpmRegistrationResultParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.TpmRegistrationResultParser)1 ProvisioningServiceClientException (com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientException)1