Search in sources :

Example 16 with UrlPathBuilder

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder in project azure-iot-sdk-java by Azure.

the class UrlPathBuilderTest method generateRequestUrlHttpThrowsOnNullOpID.

@Test(expected = IllegalArgumentException.class)
public void generateRequestUrlHttpThrowsOnNullOpID() throws IOException {
    // arrange
    UrlPathBuilder urlPathBuilder = new UrlPathBuilder(TEST_HOST_NAME, TEST_SCOPE, ProvisioningDeviceClientTransportProtocol.HTTPS);
    // act
    urlPathBuilder.generateRequestUrl(TEST_REGISTRATION_ID, null);
}
Also used : UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) Test(org.junit.Test)

Example 17 with UrlPathBuilder

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder 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 18 with UrlPathBuilder

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder 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 19 with UrlPathBuilder

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder in project azure-iot-sdk-java by Azure.

the class UrlPathBuilderTest method generateRegisterUrlHttpThrowsOnEmptyRegID.

@Test(expected = IllegalArgumentException.class)
public void generateRegisterUrlHttpThrowsOnEmptyRegID() throws IOException {
    // arrange
    UrlPathBuilder urlPathBuilder = new UrlPathBuilder(TEST_HOST_NAME, TEST_SCOPE, ProvisioningDeviceClientTransportProtocol.HTTPS);
    // act
    urlPathBuilder.generateRegisterUrl("");
}
Also used : UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) Test(org.junit.Test)

Example 20 with UrlPathBuilder

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder in project azure-iot-sdk-java by Azure.

the class UrlPathBuilderTest method generateRequestUrlHttpThrowsOnNullRegID.

// SRS_UrlPathBuilder_25_009: [ This method shall throw IllegalArgumentException if the registration id or operation id is null or empty. ]
@Test(expected = IllegalArgumentException.class)
public void generateRequestUrlHttpThrowsOnNullRegID() throws IOException {
    // arrange
    UrlPathBuilder urlPathBuilder = new UrlPathBuilder(TEST_HOST_NAME, TEST_SCOPE, ProvisioningDeviceClientTransportProtocol.HTTPS);
    // act
    urlPathBuilder.generateRequestUrl(null, TEST_OPERATION_ID);
// assert
}
Also used : UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) Test(org.junit.Test)

Aggregations

UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)29 Test (org.junit.Test)25 ContractAPIHttp (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.http.ContractAPIHttp)12 DeviceRegistrationParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)7 IOException (java.io.IOException)6 HttpRequest (com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest)3 HttpResponse (com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)3 ResponseData (com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)3 URL (java.net.URL)3 ProvisioningDeviceClientException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)1 ProvisioningDeviceSecurityException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException)1 TpmRegistrationResultParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.TpmRegistrationResultParser)1 SecurityProviderSymmetricKey (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey)1 SecurityProviderTpm (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm)1 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)1