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());
}
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));
}
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));
}
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);
}
}
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();
}
}
Aggregations