How to check if there is a BigQuery table in Java.
Around GCP, it's much easier to use the SDK (com.google.cloud. *
) Wrapping it than the API SDK (com.google.api.services. *
).
If you go around, com.google.api.services
will appear more often, so if you copy it, it will be a very complicated code: sweat_smile:
build.gradle
looks like this.
apply plugin: 'java'
apply plugin: 'application'
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.cloud:google-cloud-bigquery:+'
}
mainClassName = "Main"
run {
if (project.hasProperty('args')) {
args project.args.split('\\s+')
}
}
If found, it outputs Found, and if not found, it outputs Not found. If you specify the JSON Key of the service account in the argument, it will authenticate with it, otherwise the default account will be used.
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.*;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
private static final String DATASET = "yourdataset";
private static final String TABLE = "yourtable";
public static void main(String args[]) throws IOException {
BigQuery bigQuery;
if (args.length > 0) {
bigQuery = getClientWithJsonKey(args[0]);
} else {
bigQuery = BigQueryOptions.getDefaultInstance().getService();
}
Table table = bigQuery.getTable(DATASET, TABLE);
if (table != null) {
System.out.println("Found!");
} else {
System.err.println("Not found");
}
}
private static BigQuery getClientWithJsonKey(String key) throws IOException {
return BigQueryOptions.newBuilder()
.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(key)))
.build()
.getService();
}
}
$ ./gradlew run -Pargs="/path/to/key.json"
#Or
$ ./gradlew run
If you do your best only with com.google.api.services
, it will look like this, and even just around authentication is insanely complicated: tired_face:
https://github.com/googlearchive/bigquery-samples-java/blob/master/src/main/java/com/google/cloud/bigquery/samples/BigQueryJavaGettingStarted.java
The code for this time is here: pencil: https://github.com/nownabe/examples/tree/master/bigquery-table-existence
Recommended Posts