Search in sources :

Example 6 with HttpResponse

use of com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse 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 7 with HttpResponse

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

the class EnrollmentGroupManager method getAttestationMechanism.

AttestationMechanism getAttestationMechanism(String enrollmentGroupId) throws ProvisioningServiceClientException {
    if (Tools.isNullOrEmpty(enrollmentGroupId)) {
        throw new IllegalArgumentException("enrollmentGroupId cannot be null or empty.");
    }
    String enrollmentAttestationMechanismPath = getEnrollmentGroupAttestationMechanismPath(enrollmentGroupId);
    String payload = "{}";
    HttpResponse httpResponse = contractApiHttp.request(HttpMethod.POST, enrollmentAttestationMechanismPath, null, payload);
    byte[] body = httpResponse.getBody();
    if (body == null) {
        throw new ProvisioningServiceClientServiceException("Unexpected empty body received from service");
    }
    return new AttestationMechanism(new String(body, StandardCharsets.UTF_8));
}
Also used : ProvisioningServiceClientServiceException(com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientServiceException) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse) AttestationMechanism(com.microsoft.azure.sdk.iot.provisioning.service.configs.AttestationMechanism)

Example 8 with HttpResponse

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

the class EnrollmentGroupManager method createOrUpdate.

/**
 * Create or update an enrollmentGroup record.
 *
 * @param enrollmentGroup is an {@link EnrollmentGroup} that describes the enrollmentGroup that will be created or
 *                        updated. It cannot be {@code null}.
 * @return a {@link EnrollmentGroup} with the result of the creation or update request.
 * @throws IllegalArgumentException if the provided parameter is not correct.
 * @throws ProvisioningServiceClientTransportException if the SDK failed to send the request to the Device Provisioning Service.
 * @throws ProvisioningServiceClientException if the Device Provisioning Service was not able to create or update the enrollmentGroup.
 */
EnrollmentGroup createOrUpdate(EnrollmentGroup enrollmentGroup) throws ProvisioningServiceClientException {
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_005: [The createOrUpdate shall throw IllegalArgumentException if the provided enrollmentGroup is null.] */
    if (enrollmentGroup == null) {
        throw new IllegalArgumentException("enrollmentGroup cannot be null.");
    }
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_006: [The createOrUpdate shall send a Http request for the path `enrollmentGroups/[enrollmentGroupId]`.] */
    String id = enrollmentGroup.getEnrollmentGroupId();
    String enrollmentGroupPath = EnrollmentGroupManager.getEnrollmentGroupPath(id);
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_007: [The createOrUpdate shall send a Http request with a body with the enrollmentGroup content in JSON format.] */
    String enrollmentGroupPayload = enrollmentGroup.toJson();
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_045: [If the enrollmentGroup contains eTag, the createOrUpdate shall send a Http request with `If-Match` the eTag in the header.] */
    Map<String, String> headerParameters = new HashMap<>();
    if (!Tools.isNullOrEmpty(enrollmentGroup.getEtag())) {
        headerParameters.put(CONDITION_KEY, enrollmentGroup.getEtag());
    }
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_008: [The createOrUpdate shall send a Http request with a Http verb `PUT`.] */
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_009: [The createOrUpdate shall throw ProvisioningServiceClientTransportException if the request failed. Threw by the callee.] */
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_010: [The createOrUpdate shall throw ProvisioningServiceClientException if the Device Provisioning Service could not successfully execute the request. Threw by the callee.] */
    HttpResponse httpResponse = contractApiHttp.request(HttpMethod.PUT, enrollmentGroupPath, headerParameters, enrollmentGroupPayload);
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_042: [The createOrUpdate shall throw ProvisioningServiceClientServiceException if the heepResponse contains a null body.] */
    byte[] body = httpResponse.getBody();
    if (body == null) {
        throw new ProvisioningServiceClientServiceException("Http response for createOrUpdate cannot contains a null body");
    }
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_011: [The createOrUpdate shall return an EnrollmentGroup object created from the body of the response for the Http request .] */
    return new EnrollmentGroup(new String(body, StandardCharsets.UTF_8));
}
Also used : ProvisioningServiceClientServiceException(com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientServiceException) HashMap(java.util.HashMap) EnrollmentGroup(com.microsoft.azure.sdk.iot.provisioning.service.configs.EnrollmentGroup) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)

Example 9 with HttpResponse

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

the class EnrollmentGroupManager method get.

/**
 * Get enrollmentGroup information.
 *
 * @see ProvisioningServiceClient#getEnrollmentGroup(String)
 *
 * @param enrollmentGroupId the {@code String} that identifies the enrollmentGroup. It cannot be {@code null} or empty.
 * @return An {@link EnrollmentGroup} with the enrollmentGroup information.
 * @throws IllegalArgumentException if the provided parameter is not correct.
 * @throws ProvisioningServiceClientTransportException if the SDK failed to send the request to the Device Provisioning Service.
 * @throws ProvisioningServiceClientException if the Device Provisioning Service was not able to execute the get operation.
 */
EnrollmentGroup get(String enrollmentGroupId) throws ProvisioningServiceClientException {
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_020: [The get shall throw IllegalArgumentException if the provided enrollmentGroupId is null or empty.] */
    if (Tools.isNullOrEmpty(enrollmentGroupId)) {
        throw new IllegalArgumentException("enrollmentGroupId cannot be null or empty.");
    }
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_021: [The get shall send a Http request for the path `enrollmentGroups/[enrollmentGroupId]`.] */
    String enrollmentGroupPath = EnrollmentGroupManager.getEnrollmentGroupPath(enrollmentGroupId);
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_022: [The get shall send a Http request with a Http verb `GET`.] */
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_023: [The get shall throw ProvisioningServiceClientTransportException if the request failed. Threw by the callee.] */
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_024: [The get shall throw ProvisioningServiceClientException if the Device Provisioning Service could not successfully execute the request. Threw by the callee.] */
    HttpResponse httpResponse = contractApiHttp.request(HttpMethod.GET, enrollmentGroupPath, null, "");
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_043: [The get shall throw ProvisioningServiceClientServiceException if the heepResponse contains a null body.] */
    byte[] body = httpResponse.getBody();
    if (body == null) {
        throw new ProvisioningServiceClientServiceException("Http response for get cannot contains a null body");
    }
    /* SRS_ENROLLMENT_GROUP_MANAGER_21_025: [The get shall return an EnrollmentGroup object created from the body of the response for the Http request .] */
    return new EnrollmentGroup(new String(body, StandardCharsets.UTF_8));
}
Also used : ProvisioningServiceClientServiceException(com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientServiceException) EnrollmentGroup(com.microsoft.azure.sdk.iot.provisioning.service.configs.EnrollmentGroup) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)

Example 10 with HttpResponse

use of com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse 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)

Aggregations

HttpResponse (com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse)26 Test (org.junit.Test)12 HttpRequest (com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest)10 HashMap (java.util.HashMap)10 LinkedList (java.util.LinkedList)8 List (java.util.List)8 ProvisioningServiceClientServiceException (com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientServiceException)7 IOException (java.io.IOException)7 HttpMethod (com.microsoft.azure.sdk.iot.deps.transport.http.HttpMethod)6 URL (java.net.URL)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 DeviceRegistrationParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser)2 EnrollmentGroup (com.microsoft.azure.sdk.iot.provisioning.service.configs.EnrollmentGroup)2 TpmRegistrationResultParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.TpmRegistrationResultParser)1 ProvisioningConnectionString (com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString)1 ProvisioningSasToken (com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken)1 AttestationMechanism (com.microsoft.azure.sdk.iot.provisioning.service.configs.AttestationMechanism)1 DeviceRegistrationState (com.microsoft.azure.sdk.iot.provisioning.service.configs.DeviceRegistrationState)1 QueryResult (com.microsoft.azure.sdk.iot.provisioning.service.configs.QueryResult)1