Skip to content

Commit 903a0f7

Browse files
authored
docs: Update SimpleApp to explicitly set project id (#3534)
* docs: Update SimpleApp to explicitly set project id When running in Google Cloud console, the default google cloud project might not be set leading to 404 errors. This update requires the reader to explicitly set the project value. * Removes the explicit use of UUID to set jobId as the library now internally generates the value. * Fix missing braces * Add try/catch for errors * Add missing import * Add more missing import * Add requireEnvVar check * Add missing test import * Add missing test import
1 parent e78e78c commit 903a0f7

File tree

2 files changed

+67
-41
lines changed

2 files changed

+67
-41
lines changed

samples/snippets/src/main/java/com/example/bigquery/SimpleApp.java

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,63 +20,73 @@
2020
// [START bigquery_simple_app_deps]
2121

2222
import com.google.cloud.bigquery.BigQuery;
23+
import com.google.cloud.bigquery.BigQueryException;
2324
import com.google.cloud.bigquery.BigQueryOptions;
2425
import com.google.cloud.bigquery.FieldValueList;
2526
import com.google.cloud.bigquery.Job;
2627
import com.google.cloud.bigquery.JobId;
2728
import com.google.cloud.bigquery.JobInfo;
2829
import com.google.cloud.bigquery.QueryJobConfiguration;
2930
import com.google.cloud.bigquery.TableResult;
30-
import java.util.UUID;
3131

3232
// [END bigquery_simple_app_deps]
3333

3434
public class SimpleApp {
35+
3536
public static void main(String... args) throws Exception {
36-
// [START bigquery_simple_app_client]
37-
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
38-
// [END bigquery_simple_app_client]
39-
// [START bigquery_simple_app_query]
40-
QueryJobConfiguration queryConfig =
41-
QueryJobConfiguration.newBuilder(
42-
"SELECT CONCAT('https://stackoverflow.com/questions/', "
43-
+ "CAST(id as STRING)) as url, view_count "
44-
+ "FROM `bigquery-public-data.stackoverflow.posts_questions` "
45-
+ "WHERE tags like '%google-bigquery%' "
46-
+ "ORDER BY view_count DESC "
47-
+ "LIMIT 10")
48-
// Use standard SQL syntax for queries.
49-
// See: https://cloud.google.com/bigquery/sql-reference/
50-
.setUseLegacySql(false)
51-
.build();
37+
// TODO(developer): Replace these variables before running the app.
38+
String projectId = "MY_PROJECT_ID";
39+
simpleApp(projectId);
40+
}
5241

53-
// Create a job ID so that we can safely retry.
54-
JobId jobId = JobId.of(UUID.randomUUID().toString());
55-
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
42+
public static void simpleApp(String projectId) {
43+
try {
44+
// [START bigquery_simple_app_client]
45+
BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
46+
// [END bigquery_simple_app_client]
47+
// [START bigquery_simple_app_query]
48+
QueryJobConfiguration queryConfig =
49+
QueryJobConfiguration.newBuilder(
50+
"SELECT CONCAT('https://stackoverflow.com/questions/', "
51+
+ "CAST(id as STRING)) as url, view_count "
52+
+ "FROM `bigquery-public-data.stackoverflow.posts_questions` "
53+
+ "WHERE tags like '%google-bigquery%' "
54+
+ "ORDER BY view_count DESC "
55+
+ "LIMIT 10")
56+
// Use standard SQL syntax for queries.
57+
// See: https://cloud.google.com/bigquery/sql-reference/
58+
.setUseLegacySql(false)
59+
.build();
5660

57-
// Wait for the query to complete.
58-
queryJob = queryJob.waitFor();
61+
JobId jobId = JobId.newBuilder().setProject(projectId).build();
62+
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
5963

60-
// Check for errors
61-
if (queryJob == null) {
62-
throw new RuntimeException("Job no longer exists");
63-
} else if (queryJob.getStatus().getError() != null) {
64-
// You can also look at queryJob.getStatus().getExecutionErrors() for all
65-
// errors, not just the latest one.
66-
throw new RuntimeException(queryJob.getStatus().getError().toString());
67-
}
68-
// [END bigquery_simple_app_query]
64+
// Wait for the query to complete.
65+
queryJob = queryJob.waitFor();
66+
67+
// Check for errors
68+
if (queryJob == null) {
69+
throw new RuntimeException("Job no longer exists");
70+
} else if (queryJob.getStatus().getError() != null) {
71+
// You can also look at queryJob.getStatus().getExecutionErrors() for all
72+
// errors, not just the latest one.
73+
throw new RuntimeException(queryJob.getStatus().getError().toString());
74+
}
75+
// [END bigquery_simple_app_query]
6976

70-
// [START bigquery_simple_app_print]
71-
// Get the results.
72-
TableResult result = queryJob.getQueryResults();
77+
// [START bigquery_simple_app_print]
78+
// Get the results.
79+
TableResult result = queryJob.getQueryResults();
7380

74-
// Print all pages of the results.
75-
for (FieldValueList row : result.iterateAll()) {
76-
// String type
77-
String url = row.get("url").getStringValue();
78-
String viewCount = row.get("view_count").getStringValue();
79-
System.out.printf("%s : %s views\n", url, viewCount);
81+
// Print all pages of the results.
82+
for (FieldValueList row : result.iterateAll()) {
83+
// String type
84+
String url = row.get("url").getStringValue();
85+
String viewCount = row.get("view_count").getStringValue();
86+
System.out.printf("%s : %s views\n", url, viewCount);
87+
}
88+
} catch (BigQueryException | InterruptedException e) {
89+
System.out.println("Simple App failed due to error: \n" + e.toString());
8090
}
8191
// [END bigquery_simple_app_print]
8292
}

samples/snippets/src/test/java/com/example/bigquery/SimpleAppIT.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@
1717
package com.example.bigquery;
1818

1919
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
2021

2122
import java.io.ByteArrayOutputStream;
2223
import java.io.PrintStream;
2324
import java.util.logging.Level;
2425
import java.util.logging.Logger;
2526
import org.junit.After;
2627
import org.junit.Before;
28+
import org.junit.BeforeClass;
2729
import org.junit.Test;
2830
import org.junit.runner.RunWith;
2931
import org.junit.runners.JUnit4;
@@ -37,6 +39,20 @@ public class SimpleAppIT {
3739
private ByteArrayOutputStream bout;
3840
private PrintStream out;
3941
private PrintStream originalPrintStream;
42+
private static final String PROJECT_ID = requireEnvVar("GOOGLE_CLOUD_PROJECT");
43+
44+
private static String requireEnvVar(String varName) {
45+
String value = System.getenv(varName);
46+
assertNotNull(
47+
"Environment variable " + varName + " is required to perform these tests.",
48+
System.getenv(varName));
49+
return value;
50+
}
51+
52+
@BeforeClass
53+
public static void checkRequirements() {
54+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
55+
}
4056

4157
@Before
4258
public void setUp() {
@@ -56,7 +72,7 @@ public void tearDown() {
5672

5773
@Test
5874
public void testQuickstart() throws Exception {
59-
SimpleApp.main();
75+
SimpleApp.simpleApp(PROJECT_ID);
6076
String got = bout.toString();
6177
assertThat(got).contains("https://stackoverflow.com/questions/");
6278
}

0 commit comments

Comments
 (0)