Search in sources :

Example 1 with HttpResponse

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

the class IndividualEnrollmentManager method getAttestationMechanism.

AttestationMechanism getAttestationMechanism(String registrationId) throws ProvisioningServiceClientException {
    if (Tools.isNullOrEmpty(registrationId)) {
        throw new IllegalArgumentException("registrationId cannot be null or empty.");
    }
    String enrollmentAttestationMechanismPath = IndividualEnrollmentManager.getEnrollmentAttestationMechanismPath(registrationId);
    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)

Example 2 with HttpResponse

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

the class IndividualEnrollmentManager method bulkOperation.

/**
 * Rum a bulk individualEnrollment operation.
 *
 * @see ProvisioningServiceClient#runBulkEnrollmentOperation(BulkOperationMode, Collection)
 *
 * @param bulkOperationMode the {@link BulkOperationMode} that defines the single operation to do over the individualEnrollments. It cannot be {@code null}.
 * @param individualEnrollments the collection of {@link IndividualEnrollment} that contains the description of each individualEnrollment. It cannot be {@code null} or empty.
 * @return An {@link BulkEnrollmentOperationResult} with the result of the bulk operation request.
 * @throws IllegalArgumentException if the provided parameters are 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 bulk operation.
 */
BulkEnrollmentOperationResult bulkOperation(BulkOperationMode bulkOperationMode, Collection<IndividualEnrollment> individualEnrollments) throws ProvisioningServiceClientException {
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_012: [The BulkEnrollmentOperation shall throw IllegalArgumentException if the provided bulkOperationMode is null.] */
    if (bulkOperationMode == null) {
        throw new IllegalArgumentException("bulkOperationMode cannot be null.");
    }
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_013: [The BulkEnrollmentOperation shall throw IllegalArgumentException if the provided individualEnrollments is null or empty.] */
    if ((individualEnrollments == null) || individualEnrollments.isEmpty()) {
        throw new IllegalArgumentException("individualEnrollments cannot be null or empty.");
    }
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_014: [The BulkEnrollmentOperation shall send a Http request for the path `individualEnrollments`.] */
    String bulkEnrollmentPath = IndividualEnrollmentManager.getEnrollmentsPath();
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_015: [The BulkEnrollmentOperation shall send a Http request with a body with the individualEnrollments content in JSON format.] */
    String bulkEnrollmentPayload = BulkEnrollmentOperation.toJson(bulkOperationMode, individualEnrollments);
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_016: [The BulkEnrollmentOperation shall send a Http request with a Http verb `POST`.] */
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_017: [The BulkEnrollmentOperation shall throw ProvisioningServiceClientTransportException if the request failed. Threw by the callee.] */
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_018: [The BulkEnrollmentOperation shall throw ProvisioningServiceClientException if the Device Provisioning Service could not successfully execute the request. Threw by the callee.] */
    HttpResponse httpResponse = contractApiHttp.request(HttpMethod.POST, bulkEnrollmentPath, null, bulkEnrollmentPayload);
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_043: [The BulkEnrollmentOperation shall throw ProvisioningServiceClientServiceException if the heepResponse contains a null body.] */
    byte[] body = httpResponse.getBody();
    if (body == null) {
        throw new ProvisioningServiceClientServiceException("Http response for BulkEnrollmentOperation cannot contains a null body");
    }
    /* SRS_INDIVIDUAL_ENROLLMENT_MANAGER_21_019: [The BulkEnrollmentOperation shall return a BulkEnrollmentOperationResult object created from the body of the response for the Http request .] */
    return new BulkEnrollmentOperationResult(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)

Example 3 with HttpResponse

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

the class Query method next.

/**
 * Return the next page of result for the query.
 *
 * @return A {@link QueryResult} with the next page of items for the query.
 * @throws NoSuchElementException if the query does no have more pages to return.
 */
@Override
public QueryResult next() {
    if (!hasNext) {
        throw new NoSuchElementException("There are no more pending elements");
    }
    Map<String, String> headerParameters = new HashMap<>();
    if (pageSize != 0) {
        headerParameters.put(PAGE_SIZE_KEY, Integer.toString(pageSize));
    }
    if (!Tools.isNullOrEmpty(this.continuationToken)) {
        headerParameters.put(CONTINUATION_TOKEN_KEY, this.continuationToken);
    }
    HttpResponse httpResponse;
    try {
        httpResponse = contractApiHttp.request(HttpMethod.POST, queryPath, headerParameters, querySpecificationJson);
    } catch (ProvisioningServiceClientException e) {
        // Because Query implements the iterator interface, the next cannot throws ProvisioningServiceClientException.
        throw new IllegalArgumentException(e);
    }
    byte[] body = httpResponse.getBody();
    if (body == null) {
        throw new IllegalArgumentException("Http response for next cannot contains a null body");
    }
    String bodyStr = new String(body, StandardCharsets.UTF_8);
    Map<String, String> headers = httpResponse.getHeaderFields();
    String type = headers.get(ITEM_TYPE_KEY);
    this.continuationToken = headers.get(CONTINUATION_TOKEN_KEY);
    hasNext = (this.continuationToken != null);
    return new QueryResult(type, bodyStr, this.continuationToken);
}
Also used : QueryResult(com.microsoft.azure.sdk.iot.provisioning.service.configs.QueryResult) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse) ProvisioningServiceClientException(com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientException)

Example 4 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 request.

/**
 * This function sends a raw information to the Device Provisioning Service service using http protocol.
 * <p>
 *    The purpose of this function is be the base communication between the controllers and the
 *    Service, and should be used only if you have full understanding of the Device Provisioning Service rest APIs.
 *    We highly recommend that you uses the APis under <b>{@link ProvisioningServiceClient}</b>
 *    instead of directly access the rest API using this class.
 * </p>
 *
 * @param httpMethod is the http verb in the request (GET, POST, PUT, DELETE, PATCH).
 * @param path is the path to the resource in the service that will compose the URL.
 * @param headerParameters is a list of pairs key values that contains optional parameters in the http header.
 * @param payload is the body of the message.
 * @return the {@code HttpResponse} that contains the response of the request.
 * @throws ProvisioningServiceClientTransportException if the Service Client failed to exchange http messages with the Provisioning Service.
 * @throws ProvisioningServiceClientException if the Provisioning Service response contains an error message.
 * @throws IllegalArgumentException if the provided parameters are not correct.
 */
public synchronized HttpResponse request(HttpMethod httpMethod, String path, Map<String, String> headerParameters, String payload) throws ProvisioningServiceClientException {
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_005: [The request shall create a SAS token based on the connection string.*/
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_006: [If the request get problem to create the SAS token, it shall throw IllegalArgumentException.*/
    String sasTokenString = new ProvisioningSasToken(this.provisioningConnectionString).toString();
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_007: [The request shall create a HTTP URL based on the Device Registration path.*/
    URL url = getUrlForPath(path);
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_010: [The request shall create a new HttpRequest.*/
    HttpRequest request = createRequest(url, httpMethod, headerParameters, payload.getBytes(StandardCharsets.UTF_8), sasTokenString);
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_014: [The request shall send the request to the Device Provisioning Service service by using the HttpRequest.send().*/
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_015: [If the HttpRequest failed send the message, the request shall throw ProvisioningServiceClientTransportException, threw by the callee.*/
    HttpResponse httpResponse;
    try {
        httpResponse = request.send();
    } catch (IOException e) {
        throw new ProvisioningServiceClientTransportException(e);
    }
    /* SRS_HTTP_DEVICE_REGISTRATION_CLIENT_21_016: [If the Device Provisioning Service service respond to the HttpRequest with any error code, the request shall throw the appropriated ProvisioningServiceClientException, by calling ProvisioningServiceClientExceptionManager.responseVerification().*/
    ProvisioningServiceClientExceptionManager.httpResponseVerification(httpResponse.getStatus(), new String(httpResponse.getErrorReason(), StandardCharsets.UTF_8));
    return httpResponse;
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.deps.transport.http.HttpRequest) ProvisioningServiceClientTransportException(com.microsoft.azure.sdk.iot.provisioning.service.exceptions.ProvisioningServiceClientTransportException) ProvisioningSasToken(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken) HttpResponse(com.microsoft.azure.sdk.iot.deps.transport.http.HttpResponse) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) IOException(java.io.IOException) URL(java.net.URL)

Example 5 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 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)

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