-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
BigQuery REST samples to label datasets and tables. #495
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
# Getting Started with BigQuery with the REST API | ||
|
||
Google's BigQuery Service features a REST-based API that allows developers to | ||
create applications to run ad-hoc queries on massive datasets. These sample | ||
Java applications demonstrate how to access the BigQuery API directly using the | ||
Google HTTP Client. | ||
|
||
## Quickstart | ||
|
||
Install [Maven](http://maven.apache.org/). | ||
|
||
Build your project with: | ||
|
||
mvn clean package -DskipTests | ||
|
||
You can then run a given `ClassName` via: | ||
|
||
mvn exec:java -Dexec.mainClass=com.example.bigquery.ClassName \ | ||
-Dexec.args="any arguments to the app" | ||
|
||
### Labeling a dataset | ||
|
||
[Label a dataset](https://cloud.google.com/bigquery/docs/labeling-datasets). | ||
|
||
mvn exec:java -Dexec.mainClass=com.example.bigquery.LabelsSample \ | ||
-Dexec.args="project-id dataset-id label-key label-value" | ||
|
||
## Products | ||
- [Google BigQuery][2] | ||
|
||
## Language | ||
- [Java][3] | ||
|
||
## Dependencies | ||
- [Google HTTP Client Library for Java][4] | ||
|
||
[2]: https://cloud.google.com/bigquery | ||
[3]: https://java.com | ||
[4]: https://github.com/google/google-http-java-client | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
<!-- | ||
Copyright 2016 Google Inc. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
--> | ||
<project> | ||
<modelVersion>4.0.0</modelVersion> | ||
<version>1.0.0</version> | ||
|
||
<groupId>com.google.cloud.samples</groupId> | ||
<artifactId>bigquery-rest-samples</artifactId> | ||
<packaging>jar</packaging> | ||
|
||
<!-- Parent POM defines common plugins and properties. --> | ||
<parent> | ||
<artifactId>doc-samples</artifactId> | ||
<groupId>com.google.cloud</groupId> | ||
<version>1.0.0</version> | ||
<relativePath>../..</relativePath> | ||
</parent> | ||
|
||
<properties> | ||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||
</properties> | ||
|
||
<dependencies> | ||
<dependency> | ||
<groupId>com.google.guava</groupId> | ||
<artifactId>guava</artifactId> | ||
<version>20.0</version> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.api-client</groupId> | ||
<artifactId>google-api-client</artifactId> | ||
<version>1.22.0</version> | ||
<exclusions> | ||
<exclusion> <!-- exclude an old version of Guava --> | ||
<groupId>com.google.guava</groupId> | ||
<artifactId>guava-jdk5</artifactId> | ||
</exclusion> | ||
</exclusions> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.http-client</groupId> | ||
<artifactId>google-http-client</artifactId> | ||
<version>1.22.0</version> | ||
<exclusions> | ||
<exclusion> <!-- exclude an old version of Guava --> | ||
<groupId>com.google.guava</groupId> | ||
<artifactId>guava-jdk5</artifactId> | ||
</exclusion> | ||
</exclusions> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.oauth-client</groupId> | ||
<artifactId>google-oauth-client</artifactId> | ||
<version>1.22.0</version> | ||
<exclusions> | ||
<exclusion> <!-- exclude an old version of Guava --> | ||
<groupId>com.google.guava</groupId> | ||
<artifactId>guava-jdk5</artifactId> | ||
</exclusion> | ||
</exclusions> | ||
</dependency> | ||
|
||
<!-- Test dependencies --> | ||
<dependency> | ||
<groupId>junit</groupId> | ||
<artifactId>junit</artifactId> | ||
<version>4.12</version> | ||
<scope>test</scope> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.truth</groupId> | ||
<artifactId>truth</artifactId> | ||
<version>0.31</version> | ||
<scope>test</scope> | ||
</dependency> | ||
</dependencies> | ||
|
||
<build> | ||
<sourceDirectory>src/main/java</sourceDirectory> | ||
<resources> | ||
<resource> | ||
<directory>src/main/resources</directory> | ||
</resource> | ||
</resources> | ||
</build> | ||
|
||
</project> |
210 changes: 210 additions & 0 deletions
210
bigquery/rest/src/main/java/com/example/bigquery/LabelsSample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,210 @@ | ||
/* | ||
* Copyright 2016 Google Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.example.bigquery; | ||
|
||
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; | ||
import com.google.api.client.http.GenericUrl; | ||
import com.google.api.client.http.HttpContent; | ||
import com.google.api.client.http.HttpHeaders; | ||
import com.google.api.client.http.HttpRequest; | ||
import com.google.api.client.http.HttpRequestFactory; | ||
import com.google.api.client.http.HttpResponse; | ||
import com.google.api.client.http.HttpTransport; | ||
import com.google.api.client.http.javanet.NetHttpTransport; | ||
import com.google.api.client.http.json.JsonHttpContent; | ||
import com.google.api.client.json.JsonFactory; | ||
import com.google.api.client.json.jackson2.JacksonFactory; | ||
import com.google.api.client.util.Key; | ||
|
||
import java.io.IOException; | ||
import java.util.Arrays; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
/** Sample demonstrating labeling a BigQuery dataset or table. */ | ||
public class LabelsSample { | ||
|
||
// [START label_dataset] | ||
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); | ||
static final JsonFactory JSON_FACTORY = new JacksonFactory(); | ||
|
||
public static class Dataset { | ||
@Key private Map<String, String> labels; | ||
|
||
public Map<String, String> getLabels() { | ||
return this.labels; | ||
} | ||
|
||
public Dataset addLabel(String key, String value) { | ||
if (this.labels == null) { | ||
this.labels = new HashMap<>(); | ||
} | ||
this.labels.put(key, value); | ||
return this; | ||
} | ||
} | ||
|
||
/** | ||
* 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)); | ||
} | ||
// [END label_dataset] | ||
|
||
// [START label_table] | ||
public static class Table { | ||
@Key private Map<String, String> labels; | ||
|
||
public Map<String, String> getLabels() { | ||
return this.labels; | ||
} | ||
|
||
public Table addLabel(String key, String value) { | ||
if (this.labels == null) { | ||
this.labels = new HashMap<>(); | ||
} | ||
this.labels.put(key, value); | ||
return this; | ||
} | ||
} | ||
|
||
/** | ||
* 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)); | ||
} | ||
// [END label_table] | ||
|
||
public static void printUsage() { | ||
System.err.println("Command expects 4 or 5 arguments:"); | ||
System.err.println("\tproject dataset [table] key value"); | ||
} | ||
|
||
public static void main(final String[] args) throws IOException, InterruptedException { | ||
if (args.length != 4 && args.length != 5) { | ||
printUsage(); | ||
System.exit(1); | ||
} | ||
|
||
if (args.length == 4) { | ||
String projectId = args[0]; | ||
String datasetId = args[1]; | ||
String labelKey = args[2]; | ||
String labelValue = args[3]; | ||
labelDataset(projectId, datasetId, labelKey, labelValue); | ||
} else { | ||
String projectId = args[0]; | ||
String datasetId = args[1]; | ||
String tableId = args[2]; | ||
String labelKey = args[3]; | ||
String labelValue = args[4]; | ||
labelTable(projectId, datasetId, tableId, labelKey, labelValue); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you want to mention that they should update the constants if they do a verify?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done. I added a section on testing the sample.