Search in sources :

Example 6 with DeviceRegistrationParser

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

the class DeviceRegistrationParserTest method constructorWithTPMOnEmptyRegistrationIdThrows.

@Test(expected = IllegalArgumentException.class)
public void constructorWithTPMOnEmptyRegistrationIdThrows() throws Exception {
    final String eKey = "testEndorsementKey";
    final String sRKey = "testStorageRootKey";
    DeviceRegistrationParser deviceRegistrationParser = new DeviceRegistrationParser("", "", eKey, sRKey);
}
Also used : DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser) Test(org.junit.Test)

Example 7 with DeviceRegistrationParser

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser 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 DeviceRegistrationParser

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser 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 DeviceRegistrationParser

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

the class DeviceRegistrationParserTest method constructorWithoutTPMSucceed.

// SRS_DeviceRegistration_25_002: [ The constructor shall save the provided Registration Id. ]
// SRS_DeviceRegistration_25_007: [ This method shall create the expected Json with the provided Registration Id, EndorsementKey and StorageRootKey. ]
@Test
public void constructorWithoutTPMSucceed() throws Exception {
    final String expectedJson = "{\"registrationId\":\"" + TEST_REGISTRATION_ID + "\"}";
    DeviceRegistrationParser deviceRegistrationParser = new DeviceRegistrationParser(TEST_REGISTRATION_ID, "");
    assertNotNull(deviceRegistrationParser.toJson());
    assertEquals(expectedJson, deviceRegistrationParser.toJson());
}
Also used : DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser) Test(org.junit.Test)

Example 10 with DeviceRegistrationParser

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

the class DeviceRegistrationParserTest method constructorWithTPMSucceed.

// SRS_DeviceRegistration_25_006: [ The constructor shall save the provided Registration Id, EndorsementKey and StorageRootKey. ]
// SRS_DeviceRegistration_25_007: [ This method shall create the expected Json with the provided Registration Id, EndorsementKey and StorageRootKey. ]
@Test
public void constructorWithTPMSucceed() throws Exception {
    final String regID = "testID";
    final String eKey = "testEndorsementKey";
    final String sRKey = "testStorageRootKey";
    final String expectedJson = "{\"registrationId\":\"testID\"," + "\"tpm\":{" + "\"endorsementKey\":\"testEndorsementKey\"," + "\"storageRootKey\":\"testStorageRootKey\"" + "}}";
    DeviceRegistrationParser deviceRegistrationParser = new DeviceRegistrationParser(regID, "", eKey, sRKey);
    assertNotNull(deviceRegistrationParser.toJson());
    assertEquals(expectedJson, deviceRegistrationParser.toJson());
}
Also used : DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser) Test(org.junit.Test)

Aggregations

DeviceRegistrationParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)15 Test (org.junit.Test)13 UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)7 ContractAPIHttp (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.http.ContractAPIHttp)7 HttpRequest (com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest)2 HttpResponse (com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)2 ResponseData (com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)2 IOException (java.io.IOException)2 URL (java.net.URL)2 TpmRegistrationResultParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.TpmRegistrationResultParser)1 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)1