Search in sources :

Example 6 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 setAndGetState.

// SRS_ResponseData_25_004: [ This method shall save the value of ContractState. ]
// SRS_ResponseData_25_005: [ This method shall return the saved value of ContractState. ]
@Test
public void setAndGetState(@Mocked ContractState mockedContractState) throws Exception {
    // arrange
    ResponseData testResponseData = newInstance(ResponseData.class);
    // act
    invoke(testResponseData, "setContractState", mockedContractState);
    // assert
    assertEquals(mockedContractState, invoke(testResponseData, "getContractState"));
}
Also used : ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) Test(org.junit.Test)

Example 7 with ResponseData

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

the class AmqpsProvisioningSaslHandlerTest method handleChallengeThirdChallengeSuccess.

// Tests_SRS_AMQPSPROVISIONINGSASLHANDLER_34_013: [If this object is waiting for the second challenge, this function shall read the challenge in the format "control byte + nonce (first half)" and save the nonce portion.]
// Tests_SRS_AMQPSPROVISIONINGSASLHANDLER_34_016: [If this object is waiting for the third challenge, this function shall read the challenge in the format "control byte + nonce (second half)" and save the nonce portion.]
// Tests_SRS_AMQPSPROVISIONINGSASLHANDLER_34_017: [If this object is waiting for the third challenge, this function shall put together the full nonce byte array and run the saved responseCallback with the nonce and DPS_REGISTRATION_RECEIVED.]
// Tests_SRS_AMQPSPROVISIONINGSASLHANDLER_34_018: [If this object is waiting for the third challenge, after running the saved responseCallback, this function shall wait for the sas token to be set before returning a payload in the format "control byte + sas token".]
@Test
public void handleChallengeThirdChallengeSuccess() throws ProvisioningDeviceClientException {
    // arrange
    AmqpsProvisioningSaslHandler handler = Deencapsulation.newInstance(AmqpsProvisioningSaslHandler.class, idScope, registrationId, endorsementKey, storageRootKey, mockedResponseCallback, new Object());
    handler.chooseSaslMechanism(new String[] { "TPM", "notTPM" });
    handler.getInitPayload("TPM");
    handler.handleChallenge(validFirstChallenge);
    handler.handleChallenge(validSecondChallenge);
    Deencapsulation.setField(handler, "sasToken", sasToken);
    new NonStrictExpectations() {

        {
            new ResponseData(expectedFullNonce, ContractState.DPS_REGISTRATION_RECEIVED, 0);
            result = mockedResponseData;
        }
    };
    // act
    byte[] actualFinalChallengeResponsePayload = handler.handleChallenge(validThirdChallenge);
    // assert
    assertArraysEqual(expectedFinalChallengeResponsePayload, actualFinalChallengeResponsePayload);
    new Verifications() {

        {
            mockedResponseCallback.run(mockedResponseData, any);
            times = 1;
        }
    };
}
Also used : ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) AmqpsProvisioningSaslHandler(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.amqp.AmqpsProvisioningSaslHandler) Verifications(mockit.Verifications) NonStrictExpectations(mockit.NonStrictExpectations) Test(org.junit.Test)

Example 8 with ResponseData

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

the class ProvisioningAmqpOperations method retrieveAmqpMessage.

private void retrieveAmqpMessage(ResponseCallback responseCallback, Object callbackContext) throws ProvisioningDeviceClientException {
    if (this.receivedMessages.size() > 0) {
        AmqpMessage message = this.receivedMessages.remove();
        // Need to keep property around to get the retry-after value
        this.messageAppProperties = message.getApplicationProperty();
        byte[] msgData = message.getAmqpBody();
        if (msgData != null) {
            responseCallback.run(new ResponseData(msgData, ContractState.DPS_REGISTRATION_RECEIVED, 0), callbackContext);
        }
    }
}
Also used : ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)

Example 9 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 getRegistrationStatus.

/**
 * Gets the registration status over HTTP
 * @param requestData A non {@code null} value with all the 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 getRegistrationStatus(RequestData requestData, ResponseCallback responseCallback, Object dpsAuthorizationCallbackContext) throws ProvisioningDeviceClientException {
    // SRS_ContractAPIHttp_25_018: [If either operationId, registrationId, sslcontext or responseCallback is null or if operationId, registrationId is empty then this method shall throw ProvisioningDeviceClientException.]
    if (requestData.getOperationId() == null || requestData.getOperationId().isEmpty()) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("operationId cannot be null or empty"));
    }
    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_019: [This method shall retrieve the Url by calling generateRequestUrl on an object for UrlPathBuilder.]
        String url = new UrlPathBuilder(this.hostName, this.idScope, ProvisioningDeviceClientTransportProtocol.HTTPS).generateRequestUrl(requestData.getRegistrationId(), requestData.getOperationId());
        Map<String, String> headersMap = null;
        if (requestData.getSasToken() != null) {
            headersMap = new HashMap<>();
            headersMap.put(AUTHORIZATION, requestData.getSasToken());
        }
        // SRS_ContractAPIHttp_25_020: [This method shall prepare the GET 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.GET, new byte[0], headersMap);
        // SRS_ContractAPIHttp_25_021: [This method shall set the SSLContext for the Http Request.]
        httpRequest.setSSLContext(requestData.getSslContext());
        // SRS_ContractAPIHttp_25_022: [This method shall send http request and verify the status by calling 'ProvisioningDeviceClientExceptionManager.verifyHttpResponse'.]
        // SRS_ContractAPIHttp_25_024: [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 from the service
        processRetryAfterValue(httpResponse);
        // SRS_ContractAPIHttp_25_023: [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) UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) 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)

Example 10 with ResponseData

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

the class AmqpsProvisioningSaslHandler method handleThirdChallenge.

private byte[] handleThirdChallenge(byte[] challengeData) throws ProvisioningDeviceClientException {
    // validate challenge
    if (challengeData.length < 1 || challengeData[0] != FINAL_SEGMENT_CONTROL_BYTE) {
        // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_015: [If this object is waiting for the third challenge, this function shall validate that this challenge payload contains a control byte with the mask 0xC1 and shall throw an IllegalStateException if it is not.]
        throw new IllegalStateException("Unexpected challenge data");
    }
    // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_016: [If this object is waiting for the third challenge, this function shall read the challenge in the format "control byte + nonce (second half)" and save the nonce portion.]
    this.challengeKey = buildNonceFromThirdChallenge(challengeData);
    // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_017: [If this object is waiting for the third challenge, this function shall put together the full nonce byte array and run the saved responseCallback with the nonce and DPS_REGISTRATION_RECEIVED.]
    this.responseCallback.run(new ResponseData(this.challengeKey, ContractState.DPS_REGISTRATION_RECEIVED, 0), this.authorizationCallbackContext);
    this.challengeState = ChallengeState.WAITING_TO_SEND_SAS_TOKEN;
    // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_018: [If this object is waiting for the third challenge, after running the saved responseCallback, this function shall wait for the sas token to be set before returning a payload in the format "control byte + sas token".]
    long millisecondsElapsed = 0;
    long waitTimeStart = System.currentTimeMillis();
    while (this.sasToken == null && millisecondsElapsed < MAX_MILLISECONDS_TIMEOUT_FOR_SAS_TOKEN_WAIT) {
        try {
            // noinspection BusyWait
            Thread.sleep(WAIT_INTERVALS);
        } catch (InterruptedException e) {
            throw new ProvisioningDeviceClientException(e);
        }
        millisecondsElapsed = System.currentTimeMillis() - waitTimeStart;
    }
    if (millisecondsElapsed >= MAX_MILLISECONDS_TIMEOUT_FOR_SAS_TOKEN_WAIT) {
        // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_019: [If this object is waiting for the third challenge, and if the sas token is not provided within 3 minutes of waiting, this function shall throw a SecurityException.]
        throw new ProvisioningDeviceSecurityException("Sasl negotiation failed: Sas token was never supplied to finish negotiation");
    }
    this.challengeState = ChallengeState.WAITING_FOR_FINAL_OUTCOME;
    return prependByteArrayWithControlByte(INIT_SEGMENT_CONTROL_BYTE, sasToken.getBytes(StandardCharsets.UTF_8));
}
Also used : ProvisioningDeviceSecurityException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException) ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)

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