Search in sources :

Example 26 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class HttpExample method publishMessage.

// [END iot_http_getconfig]
// [START iot_http_publish]
/**
 * Publish an event or state message using Cloud IoT Core via the HTTP API.
 */
public static void publishMessage(String payload, String urlPath, String messageType, String token, String projectId, String cloudRegion, String registryId, String deviceId) throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
    // Build the resource path of the device that is going to be authenticated.
    String devicePath = String.format("projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryId, deviceId);
    String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";
    // Data sent through the wire has to be base64 encoded.
    Base64.Encoder encoder = Base64.getEncoder();
    String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));
    urlPath = urlPath + devicePath + ":" + urlSuffix;
    final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    HttpHeaders heads = new HttpHeaders();
    heads.setAuthorization(String.format("Bearer %s", token));
    heads.setContentType("application/json; charset=UTF-8");
    heads.setCacheControl("no-cache");
    // Add post data. The data sent depends on whether we're updating state or publishing events.
    JSONObject data = new JSONObject();
    if (messageType.equals("event")) {
        data.put("binary_data", encPayload);
    } else {
        JSONObject state = new JSONObject();
        state.put("binary_data", encPayload);
        data.put("state", state);
    }
    ByteArrayContent content = new ByteArrayContent("application/json", data.toString().getBytes("UTF-8"));
    final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
    req.setHeaders(heads);
    req.setContent(content);
    req.setRequestMethod("POST");
    ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
    req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
    HttpResponse res = req.execute();
    System.out.println(res.getStatusCode());
    System.out.println(res.getStatusMessage());
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Base64(java.util.Base64) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JwtBuilder(io.jsonwebtoken.JwtBuilder) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) JSONObject(org.json.JSONObject) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 27 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class LabelsSample method labelTable.

/**
 * Add or modify a label on a table.
 *
 * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(String projectId, String datasetId, String tableId, String labelKey, String labelValue) throws IOException {
    // Authenticate requests using Google Application Default credentials.
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
    // Get a new access token.
    // Note that access tokens have an expiration. You can reuse a token rather than requesting a
    // new one if it is not yet expired.
    credential.refreshToken();
    String accessToken = credential.getAccessToken();
    // Set the content of the request.
    Table table = new Table();
    table.addLabel(labelKey, labelValue);
    HttpContent content = new JsonHttpContent(JSON_FACTORY, table);
    // Send the request to the BigQuery API.
    String urlFormat = "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s" + "?fields=labels&access_token=%s";
    GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, tableId, accessToken));
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(url, content);
    request.setParser(JSON_FACTORY.createJsonObjectParser());
    // Workaround for transports which do not support PATCH requests.
    // See: http://stackoverflow.com/a/32503192/101923
    request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
    HttpResponse response = request.execute();
    // Check for errors.
    if (response.getStatusCode() != 200) {
        throw new RuntimeException(response.getStatusMessage());
    }
    Table responseTable = response.parseAs(Table.class);
    System.out.printf("Updated label \"%s\" with value \"%s\"\n", labelKey, responseTable.getLabels().get(labelKey));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent) GenericUrl(com.google.api.client.http.GenericUrl) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent) HttpContent(com.google.api.client.http.HttpContent)

Example 28 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class LabelsSample method labelDataset.

/**
 * Add or modify a label on a dataset.
 *
 * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(String projectId, String datasetId, String labelKey, String labelValue) throws IOException {
    // Authenticate requests using Google Application Default credentials.
    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
    // Get a new access token.
    // Note that access tokens have an expiration. You can reuse a token rather than requesting a
    // new one if it is not yet expired.
    credential.refreshToken();
    String accessToken = credential.getAccessToken();
    // Set the content of the request.
    Dataset dataset = new Dataset();
    dataset.addLabel(labelKey, labelValue);
    HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);
    // Send the request to the BigQuery API.
    String urlFormat = "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s" + "?fields=labels&access_token=%s";
    GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken));
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(url, content);
    request.setParser(JSON_FACTORY.createJsonObjectParser());
    // Workaround for transports which do not support PATCH requests.
    // See: http://stackoverflow.com/a/32503192/101923
    request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
    HttpResponse response = request.execute();
    // Check for errors.
    if (response.getStatusCode() != 200) {
        throw new RuntimeException(response.getStatusMessage());
    }
    Dataset responseDataset = response.parseAs(Dataset.class);
    System.out.printf("Updated label \"%s\" with value \"%s\"\n", labelKey, responseDataset.getLabels().get(labelKey));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent) GenericUrl(com.google.api.client.http.GenericUrl) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent) HttpContent(com.google.api.client.http.HttpContent)

Example 29 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class CustomerSuppliedEncryptionKeysSamples method rotateKey.

/**
 * Given an existing, CSEK-protected object, changes the key used to store that object.
 *
 * @param storage A Storage object, ready for use
 * @param bucketName The name of the destination bucket
 * @param objectName The name of the destination object
 * @param originalBase64Key The AES256 key currently associated with this object,
 *     encoded as a base64 string.
 * @param originalBase64KeyHash The SHA-256 hash of the above key,
 *     also encoded as a base64 string.
 * @param newBase64Key An AES256 key which will replace the existing key,
 *     encoded as a base64 string.
 * @param newBase64KeyHash The SHA-256 hash of the above key, also encoded as a base64 string.
 * @throws IOException if there was some error download from GCS.
 */
public static void rotateKey(Storage storage, String bucketName, String objectName, String originalBase64Key, String originalBase64KeyHash, String newBase64Key, String newBase64KeyHash) throws Exception {
    // Set the CSEK headers
    final HttpHeaders httpHeaders = new HttpHeaders();
    // Specify the exiting object's current CSEK.
    httpHeaders.set("x-goog-copy-source-encryption-algorithm", "AES256");
    httpHeaders.set("x-goog-copy-source-encryption-key", originalBase64Key);
    httpHeaders.set("x-goog-copy-source-encryption-key-sha256", originalBase64KeyHash);
    // Specify the new CSEK that we would like to apply.
    httpHeaders.set("x-goog-encryption-algorithm", "AES256");
    httpHeaders.set("x-goog-encryption-key", newBase64Key);
    httpHeaders.set("x-goog-encryption-key-sha256", newBase64KeyHash);
    Storage.Objects.Rewrite rewriteObject = storage.objects().rewrite(bucketName, objectName, bucketName, objectName, null);
    rewriteObject.setRequestHeaders(httpHeaders);
    try {
        RewriteResponse rewriteResponse = rewriteObject.execute();
        // rewrite until the operation completes.
        while (!rewriteResponse.getDone()) {
            System.out.println("Rewrite did not complete. Resuming...");
            rewriteObject.setRewriteToken(rewriteResponse.getRewriteToken());
            rewriteResponse = rewriteObject.execute();
        }
    } catch (GoogleJsonResponseException e) {
        System.out.println("Error rotating key: " + e.getContent());
        System.exit(1);
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) RewriteResponse(com.google.api.services.storage.model.RewriteResponse)

Example 30 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project google-cloud-intellij by GoogleCloudPlatform.

the class CloudRepositoryService method list.

@NotNull
public ListReposResponse list(CredentialedUser user, String cloudProject) throws CloudRepositoryServiceException {
    try {
        Credential credential = user.getCredential();
        HttpRequestInitializer initializer = httpRequest -> {
            HttpHeaders headers = new HttpHeaders();
            httpRequest.setConnectTimeout(LIST_TIMEOUT_MS);
            httpRequest.setReadTimeout(LIST_TIMEOUT_MS);
            httpRequest.setHeaders(headers);
            credential.initialize(httpRequest);
        };
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        String userAgent = ServiceManager.getService(PluginInfoService.class).getUserAgent();
        Source source = new Source.Builder(httpTransport, JacksonFactory.getDefaultInstance(), initializer).setRootUrl(CLOUD_SOURCE_API_ROOT_URL).setServicePath("").setApplicationName(userAgent).build();
        return new CustomUrlSourceRequest(source, cloudProject).execute();
    } catch (IOException | GeneralSecurityException ex) {
        throw new CloudRepositoryServiceException();
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) ListReposResponse(com.google.api.services.source.model.ListReposResponse) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) Preconditions(com.google.api.client.util.Preconditions) Source(com.google.api.services.source.Source) ServiceManager(com.intellij.openapi.components.ServiceManager) GeneralSecurityException(java.security.GeneralSecurityException) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) CredentialedUser(com.google.cloud.tools.intellij.login.CredentialedUser) PluginInfoService(com.google.cloud.tools.intellij.service.PluginInfoService) Key(com.google.api.client.util.Key) Credential(com.google.api.client.auth.oauth2.Credential) SourceRequest(com.google.api.services.source.SourceRequest) NotNull(org.jetbrains.annotations.NotNull) HttpHeaders(com.google.api.client.http.HttpHeaders) Credential(com.google.api.client.auth.oauth2.Credential) GeneralSecurityException(java.security.GeneralSecurityException) PluginInfoService(com.google.cloud.tools.intellij.service.PluginInfoService) IOException(java.io.IOException) Source(com.google.api.services.source.Source) HttpTransport(com.google.api.client.http.HttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

HttpHeaders (com.google.api.client.http.HttpHeaders)46 HttpRequest (com.google.api.client.http.HttpRequest)22 IOException (java.io.IOException)21 GenericUrl (com.google.api.client.http.GenericUrl)13 HttpResponse (com.google.api.client.http.HttpResponse)13 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)10 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)7 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)6 Test (org.junit.Test)6 HttpContent (com.google.api.client.http.HttpContent)5 Objects (com.google.api.services.storage.model.Objects)5 HttpResponseException (com.google.api.client.http.HttpResponseException)4 HttpTransport (com.google.api.client.http.HttpTransport)4 JsonObjectParser (com.google.api.client.json.JsonObjectParser)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 SocketTimeoutException (java.net.SocketTimeoutException)4 Map (java.util.Map)4 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)3