はじめに
JavaでBigQueryのテーブルがあるかないか確認する方法です。
GCPまわりはAPIのSDK(com.google.api.services.*
)よりもそれをラップしたSDK(com.google.cloud.*
)を使う方がだいぶ簡単ですね。
ぐぐるとcom.google.api.services
のほうがよく出るのでそれを真似るととても複雑なコードになってしまいます
依存
build.gradle
はこんな感じです。
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+')
}
}
コード
見つかればFound、見つからなければNot foundと出力します。
引数でサービスアカウントのJSON Keyを指定すればそれで認証し、なければデフォルトのアカウントを使うようになっています。
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"
# もしくは
$ ./gradlew run
おわりに
com.google.api.services
の方だけで頑張るとこんな感じで、認証まわりだけでもめちゃくちゃ複雑です
https://github.com/googlearchive/bigquery-samples-java/blob/master/src/main/java/com/google/cloud/bigquery/samples/BigQueryJavaGettingStarted.java
今回のコードはこちらにあります
https://github.com/nownabe/examples/tree/master/bigquery-table-existence