Skip to content

Commit b54ad45

Browse files
authored
Merge pull request #297 from GoogleCloudPlatform/tswast-bq-refactor
Refactor BigQuery samples.
2 parents a9ba257 + a9451b5 commit b54ad45

20 files changed

+261
-374
lines changed

bigquery/pom.xml

+4-5
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,17 @@
2828
<dependency>
2929
<groupId>com.google.oauth-client</groupId>
3030
<artifactId>google-oauth-client</artifactId>
31-
<version>${project.oauth.version}</version>
31+
<version>1.21.0</version>
3232
</dependency>
3333
<dependency>
3434
<groupId>com.google.http-client</groupId>
3535
<artifactId>google-http-client-jackson2</artifactId>
36-
<version>${project.http.version}</version>
36+
<version>1.21.0</version>
3737
</dependency>
3838
<dependency>
3939
<groupId>com.google.oauth-client</groupId>
4040
<artifactId>google-oauth-client-jetty</artifactId>
41-
<version>${project.oauth.version}</version>
41+
<version>1.21.0</version>
4242
</dependency>
4343
<dependency>
4444
<groupId>com.google.code.gson</groupId>
@@ -48,6 +48,7 @@
4848
<dependency>
4949
<groupId>junit</groupId>
5050
<artifactId>junit</artifactId>
51+
<version>4.12</version>
5152
<scope>test</scope>
5253
</dependency>
5354
<dependency>
@@ -59,8 +60,6 @@
5960
</dependencies>
6061

6162
<properties>
62-
<project.http.version>1.21.0</project.http.version>
63-
<project.oauth.version>1.21.0</project.oauth.version>
6463
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
6564
</properties>
6665

bigquery/src/main/java/com/google/cloud/bigquery/samples/AsyncQuerySample.java

+23-34
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,8 @@
1313
* License for the specific language governing permissions and limitations under
1414
* the License.
1515
*/
16-
1716
package com.google.cloud.bigquery.samples;
1817

19-
2018
import com.google.api.services.bigquery.Bigquery;
2119
import com.google.api.services.bigquery.Bigquery.Jobs.GetQueryResults;
2220
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
@@ -28,11 +26,10 @@
2826
import java.util.Iterator;
2927
import java.util.Scanner;
3028

31-
3229
/**
3330
* Example of authorizing with BigQuery and reading from a public dataset.
3431
*/
35-
public class AsyncQuerySample extends BigqueryUtils {
32+
public class AsyncQuerySample {
3633
// [START main]
3734
/**
3835
* Prompts for all the parameters required to make a query.
@@ -41,23 +38,20 @@ public class AsyncQuerySample extends BigqueryUtils {
4138
* @throws IOException IOException
4239
* @throws InterruptedException InterruptedException
4340
*/
44-
public static void main(final String[] args)
45-
throws IOException, InterruptedException {
41+
public static void main(final String[] args) throws IOException, InterruptedException {
4642
Scanner scanner = new Scanner(System.in);
4743
System.out.println("Enter your project id: ");
4844
String projectId = scanner.nextLine();
4945
System.out.println("Enter your query string: ");
5046
String queryString = scanner.nextLine();
5147
System.out.println("Run query in batch mode? [true|false] ");
5248
boolean batch = Boolean.valueOf(scanner.nextLine());
53-
System.out.println("Enter how often to check if your job is complete "
54-
+ "(milliseconds): ");
49+
System.out.println("Enter how often to check if your job is complete " + "(milliseconds): ");
5550
long waitTime = scanner.nextLong();
5651
scanner.close();
57-
Iterator<GetQueryResultsResponse> pages = run(projectId, queryString,
58-
batch, waitTime);
52+
Iterator<GetQueryResultsResponse> pages = run(projectId, queryString, batch, waitTime);
5953
while (pages.hasNext()) {
60-
printRows(pages.next().getRows(), System.out);
54+
BigQueryUtils.printRows(pages.next().getRows(), System.out);
6155
}
6256
}
6357
// [END main]
@@ -70,58 +64,53 @@ public static void main(final String[] args)
7064
* @param queryString Query we want to run against BigQuery
7165
* @param batch True if you want to batch the queries
7266
* @param waitTime How long to wait before retries
73-
* @return An interator to the result of your pages
67+
* @return An iterator to the result of your pages
7468
* @throws IOException Thrown if there's an IOException
7569
* @throws InterruptedException Thrown if there's an Interrupted Exception
7670
*/
77-
public static Iterator<GetQueryResultsResponse> run(final String projectId,
78-
final String queryString,
79-
final boolean batch,
80-
final long waitTime)
71+
public static Iterator<GetQueryResultsResponse> run(
72+
final String projectId, final String queryString, final boolean batch, final long waitTime)
8173
throws IOException, InterruptedException {
8274

83-
Bigquery bigquery = BigqueryServiceFactory.getService();
75+
Bigquery bigquery = BigQueryServiceFactory.getService();
8476

8577
Job query = asyncQuery(bigquery, projectId, queryString, batch);
86-
Bigquery.Jobs.Get getRequest = bigquery.jobs().get(
87-
projectId, query.getJobReference().getJobId());
78+
Bigquery.Jobs.Get getRequest =
79+
bigquery.jobs().get(projectId, query.getJobReference().getJobId());
8880

89-
//Poll every waitTime milliseconds,
90-
//retrying at most retries times if there are errors
91-
pollJob(getRequest, waitTime);
81+
// Poll every waitTime milliseconds,
82+
// retrying at most retries times if there are errors
83+
BigQueryUtils.pollJob(getRequest, waitTime);
9284

93-
GetQueryResults resultsRequest = bigquery.jobs().getQueryResults(
94-
projectId, query.getJobReference().getJobId());
85+
GetQueryResults resultsRequest =
86+
bigquery.jobs().getQueryResults(projectId, query.getJobReference().getJobId());
9587

96-
return getPages(resultsRequest);
88+
return BigQueryUtils.getPages(resultsRequest);
9789
}
9890
// [END run]
9991

10092
// [START asyncQuery]
10193
/**
10294
* Inserts an asynchronous query Job for a particular query.
10395
*
104-
* @param bigquery an authorized BigQuery client
96+
* @param bigquery an authorized BigQuery client
10597
* @param projectId a String containing the project ID
10698
* @param querySql the actual query string
10799
* @param batch True if you want to run the query as BATCH
108100
* @return a reference to the inserted query job
109101
* @throws IOException Thrown if there's a network exception
110102
*/
111-
public static Job asyncQuery(final Bigquery bigquery,
112-
final String projectId,
113-
final String querySql,
114-
final boolean batch) throws IOException {
103+
public static Job asyncQuery(
104+
final Bigquery bigquery, final String projectId, final String querySql, final boolean batch)
105+
throws IOException {
115106

116-
JobConfigurationQuery queryConfig = new JobConfigurationQuery()
117-
.setQuery(querySql);
107+
JobConfigurationQuery queryConfig = new JobConfigurationQuery().setQuery(querySql);
118108

119109
if (batch) {
120110
queryConfig.setPriority("BATCH");
121111
}
122112

123-
Job job = new Job().setConfiguration(
124-
new JobConfiguration().setQuery(queryConfig));
113+
Job job = new Job().setConfiguration(new JobConfiguration().setQuery(queryConfig));
125114

126115
return bigquery.jobs().insert(projectId, job).execute();
127116
}

bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryServiceFactory.java renamed to bigquery/src/main/java/com/google/cloud/bigquery/samples/BigQueryServiceFactory.java

+11-12
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,14 @@
3030
import java.util.Collection;
3131

3232
/**
33-
* This class creates our Service to connect to Bigquery including auth.
33+
* This class creates our Service to connect to BigQuery including auth.
3434
*/
35-
public final class BigqueryServiceFactory {
35+
public final class BigQueryServiceFactory {
3636

3737
/**
3838
* Private constructor to disable creation of this utility Factory class.
3939
*/
40-
private BigqueryServiceFactory() {
41-
42-
}
40+
private BigQueryServiceFactory() {}
4341

4442
/**
4543
* Singleton service used through the app.
@@ -52,9 +50,9 @@ private BigqueryServiceFactory() {
5250
private static Object serviceLock = new Object();
5351

5452
/**
55-
* Threadsafe Factory that provides an authorized Bigquery service.
56-
* @return The Bigquery service
57-
* @throws IOException Thronw if there is an error connecting to Bigquery.
53+
* Threadsafe Factory that provides an authorized BigQuery service.
54+
* @return The BigQuery service
55+
* @throws IOException Throw if there is an error connecting to BigQuery.
5856
*/
5957
public static Bigquery getService() throws IOException {
6058
if (service == null) {
@@ -68,7 +66,7 @@ public static Bigquery getService() throws IOException {
6866
}
6967

7068
/**
71-
* Creates an authorized client to Google Bigquery.
69+
* Creates an authorized client to Google BigQuery.
7270
*
7371
* @return The BigQuery Service
7472
* @throws IOException Thrown if there is an error connecting
@@ -78,18 +76,19 @@ private static Bigquery createAuthorizedClient() throws IOException {
7876
// Create the credential
7977
HttpTransport transport = new NetHttpTransport();
8078
JsonFactory jsonFactory = new JacksonFactory();
81-
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
79+
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
8280

8381
// Depending on the environment that provides the default credentials (e.g. Compute Engine, App
8482
// Engine), the credentials may require us to specify the scopes we need explicitly.
85-
// Check for this case, and inject the Bigquery scope if required.
83+
// Check for this case, and inject the BigQuery scope if required.
8684
if (credential.createScopedRequired()) {
8785
Collection<String> bigqueryScopes = BigqueryScopes.all();
8886
credential = credential.createScoped(bigqueryScopes);
8987
}
9088

9189
return new Bigquery.Builder(transport, jsonFactory, credential)
92-
.setApplicationName("BigQuery Samples").build();
90+
.setApplicationName("BigQuery Samples")
91+
.build();
9392
}
9493
// [END get_service]
9594

bigquery/src/main/java/com/google/cloud/bigquery/samples/BigqueryUtils.java renamed to bigquery/src/main/java/com/google/cloud/bigquery/samples/BigQueryUtils.java

+9-10
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,13 @@
3838
/**
3939
* Helper functions for the other classes.
4040
*/
41-
public class BigqueryUtils {
41+
public class BigQueryUtils {
4242

4343
/**
44-
* Private contructor to prevent creation of this class, which is just all
44+
* Private constructor to prevent creation of this class, which is just all
4545
* static helper methods.
4646
*/
47-
protected BigqueryUtils() {
48-
}
47+
private BigQueryUtils() {}
4948

5049
/**
5150
* Print rows to the output stream in a formatted way.
@@ -76,9 +75,8 @@ public static Job pollJob(final Bigquery.Jobs.Get request, final long interval)
7675
throws IOException, InterruptedException {
7776
Job job = request.execute();
7877
while (!job.getStatus().getState().equals("DONE")) {
79-
System.out.println("Job is "
80-
+ job.getStatus().getState()
81-
+ " waiting " + interval + " milliseconds...");
78+
System.out.println(
79+
"Job is " + job.getStatus().getState() + " waiting " + interval + " milliseconds...");
8280
Thread.sleep(interval);
8381
job = request.execute();
8482
}
@@ -165,9 +163,10 @@ public void remove() {
165163
public static TableSchema loadSchema(final Reader schemaSource) {
166164
TableSchema sourceSchema = new TableSchema();
167165

168-
List<TableFieldSchema> fields = (new Gson())
169-
.<List<TableFieldSchema>>fromJson(schemaSource,
170-
(new ArrayList<TableFieldSchema>()).getClass());
166+
List<TableFieldSchema> fields =
167+
(new Gson())
168+
.<List<TableFieldSchema>>fromJson(
169+
schemaSource, (new ArrayList<TableFieldSchema>()).getClass());
171170

172171
sourceSchema.setFields(fields);
173172

bigquery/src/main/java/com/google/cloud/bigquery/samples/ExportDataCloudStorageSample.java

+31-30
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
/**
2727
* Sample of how to Export Cloud Data.
2828
*/
29-
public class ExportDataCloudStorageSample {
29+
public class ExportDataCloudStorageSample {
3030
/**
3131
* Protected constructor since this is a collection of static functions.
3232
*/
@@ -42,20 +42,17 @@ protected ExportDataCloudStorageSample() {
4242
* @throws InterruptedException Should never be thrown.
4343
*/
4444
// [START main]
45-
public static void main(final String[] args)
46-
throws IOException, InterruptedException {
45+
public static void main(final String[] args) throws IOException, InterruptedException {
4746
Scanner scanner = new Scanner(System.in);
4847
System.out.println("Enter your project id: ");
4948
String projectId = scanner.nextLine();
5049
System.out.println("Enter your dataset id: ");
5150
String datasetId = scanner.nextLine();
5251
System.out.println("Enter your table id: ");
5352
String tableId = scanner.nextLine();
54-
System.out.println("Enter the Google Cloud Storage Path to which you'd "
55-
+ "like to export: ");
53+
System.out.println("Enter the Google Cloud Storage Path to which you'd " + "like to export: ");
5654
String cloudStoragePath = scanner.nextLine();
57-
System.out.println("Enter how often to check if your job is complete "
58-
+ "(milliseconds): ");
55+
System.out.println("Enter how often to check if your job is complete " + "(milliseconds): ");
5956
long interval = scanner.nextLong();
6057
scanner.close();
6158

@@ -79,30 +76,33 @@ public static void run(
7976
final String projectId,
8077
final String datasetId,
8178
final String tableId,
82-
final long interval) throws IOException, InterruptedException {
79+
final long interval)
80+
throws IOException, InterruptedException {
8381

84-
Bigquery bigquery = BigqueryServiceFactory.getService();
82+
Bigquery bigquery = BigQueryServiceFactory.getService();
8583

86-
Job extractJob = extractJob(
87-
bigquery,
88-
cloudStoragePath,
89-
new TableReference()
90-
.setProjectId(projectId)
91-
.setDatasetId(datasetId)
92-
.setTableId(tableId));
84+
Job extractJob =
85+
extractJob(
86+
bigquery,
87+
cloudStoragePath,
88+
new TableReference()
89+
.setProjectId(projectId)
90+
.setDatasetId(datasetId)
91+
.setTableId(tableId));
9392

94-
Bigquery.Jobs.Get getJob = bigquery.jobs().get(
95-
extractJob.getJobReference().getProjectId(),
96-
extractJob.getJobReference().getJobId());
93+
Bigquery.Jobs.Get getJob =
94+
bigquery
95+
.jobs()
96+
.get(
97+
extractJob.getJobReference().getProjectId(),
98+
extractJob.getJobReference().getJobId());
9799

98-
BigqueryUtils.pollJob(getJob, interval);
100+
BigQueryUtils.pollJob(getJob, interval);
99101

100102
System.out.println("Export is Done!");
101-
102103
}
103104
// [END run]
104105

105-
106106
/**
107107
* A job that extracts data from a table.
108108
* @param bigquery Bigquery service to use
@@ -113,16 +113,17 @@ public static void run(
113113
*/
114114
// [START extract_job]
115115
public static Job extractJob(
116-
final Bigquery bigquery,
117-
final String cloudStoragePath,
118-
final TableReference table) throws IOException {
116+
final Bigquery bigquery, final String cloudStoragePath, final TableReference table)
117+
throws IOException {
119118

120-
JobConfigurationExtract extract = new JobConfigurationExtract()
121-
.setSourceTable(table)
122-
.setDestinationUri(cloudStoragePath);
119+
JobConfigurationExtract extract =
120+
new JobConfigurationExtract().setSourceTable(table).setDestinationUri(cloudStoragePath);
123121

124-
return bigquery.jobs().insert(table.getProjectId(),
125-
new Job().setConfiguration(new JobConfiguration().setExtract(extract)))
122+
return bigquery
123+
.jobs()
124+
.insert(
125+
table.getProjectId(),
126+
new Job().setConfiguration(new JobConfiguration().setExtract(extract)))
126127
.execute();
127128
}
128129
// [END extract_job]

0 commit comments

Comments
 (0)