Search in sources :

Example 1 with ResponseData

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

the class ResponseDataTest method constructorSucceeds.

// SRS_ResponseData_25_001: [ Constructor shall create null responseData and set the ContractState to DPS_REGISTRATION_UNKNOWN. ]
@Test
public void constructorSucceeds() throws Exception {
    // act
    ResponseData testResponseData = newInstance(ResponseData.class);
    // assert
    assertNull(invoke(testResponseData, "getResponseData"));
    assertEquals(DPS_REGISTRATION_UNKNOWN, invoke(testResponseData, "getContractState"));
}
Also used : ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) Test(org.junit.Test)

Example 2 with ResponseData

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

the class ContractAPIMqtt method executeProvisioningMessage.

private void executeProvisioningMessage(String topic, byte[] body, ResponseCallback responseCallback, Object callbackContext) throws IOException, ProvisioningDeviceClientException {
    // Send the message
    this.mqttConnection.publishMessage(topic, MqttQos.DELIVER_AT_MOST_ONCE, body);
    try {
        // SRS_ProvisioningAmqpOperations_07_011: [This method shall wait for the response of this message for MAX_WAIT_TO_SEND_MSG and call the responseCallback with the reply.]
        synchronized (this.receiveLock) {
            this.receiveLock.waitLock(MAX_WAIT_TO_SEND_MSG);
        }
        if (this.receivedMessages.size() > 0) {
            MqttMessage message = this.receivedMessages.remove();
            responseCallback.run(new ResponseData(message.getPayload(), ContractState.DPS_REGISTRATION_RECEIVED, 0), callbackContext);
        } else {
            throw new ProvisioningDeviceClientException("Invalid message received.");
        }
    } catch (InterruptedException e) {
        // SRS_ProvisioningAmqpOperations_07_012: [This method shall throw ProvisioningDeviceClientException if any failure is encountered.]
        throw new ProvisioningDeviceClientException("Provisioning service failed to reply is allotted time.");
    }
}
Also used : ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)

Example 3 with ResponseData

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData 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 4 with ResponseData

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData 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 5 with ResponseData

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

the class ResponseDataTest method setAndGetResponseData.

// SRS_ResponseData_25_002: [ This method shall save the value of responseData. ]
// SRS_ResponseData_25_003: [ This method shall return the saved value of responseData. ]
@Test
public void setAndGetResponseData() throws Exception {
    // arrange
    byte[] testData = "testData".getBytes(StandardCharsets.UTF_8);
    ResponseData testResponseData = newInstance(ResponseData.class);
    // act
    invoke(testResponseData, "setResponseData", testData);
    // assert
    assertEquals(testData, invoke(testResponseData, "getResponseData"));
}
Also used : ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) Test(org.junit.Test)

Aggregations

ResponseData (com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)10 Test (org.junit.Test)4 HttpRequest (com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest)3 HttpResponse (com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)3 UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)3 IOException (java.io.IOException)3 URL (java.net.URL)3 DeviceRegistrationParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)2 AmqpsProvisioningSaslHandler (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.amqp.AmqpsProvisioningSaslHandler)1 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 NonStrictExpectations (mockit.NonStrictExpectations)1 Verifications (mockit.Verifications)1