2727import java .io .PrintStream ;
2828import java .util .Iterator ;
2929import java .util .List ;
30- import java .util .stream .Collectors ;
3130
3231/**
3332 * Runs a synchronous query against BigQuery.
@@ -40,7 +39,7 @@ public class SyncQuerySample {
4039 /**
4140 * Prompts the user for the required parameters to perform a query.
4241 */
43- public static void main (final String [] args ) throws IOException {
42+ public static void main (final String [] args ) throws IOException , InterruptedException {
4443 String queryString = System .getProperty ("query" );
4544 if (queryString == null || queryString .isEmpty ()) {
4645 System .out .println ("The query property was not set, using default." );
@@ -82,7 +81,7 @@ public static void run(
8281 final PrintStream out ,
8382 final String queryString ,
8483 final long waitTime ,
85- final boolean useLegacySql ) throws IOException {
84+ final boolean useLegacySql ) throws IOException , InterruptedException {
8685 BigQuery bigquery =
8786 new BigQueryOptions .DefaultBigqueryFactory ().create (BigQueryOptions .getDefaultInstance ());
8887
@@ -95,20 +94,28 @@ public static void run(
9594 .build ();
9695 QueryResponse response = bigquery .query (queryRequest );
9796
97+ // Wait for the job to finish (if the query takes more than 10 seconds to complete).
98+ while (!response .jobCompleted ()) {
99+ Thread .sleep (1000 );
100+ response = bigquery .getQueryResults (response .getJobId ());
101+ }
102+
98103 if (response .hasErrors ()) {
99- throw new RuntimeException (
100- response
101- .getExecutionErrors ()
102- .stream ()
103- .<String >map (err -> err .getMessage ())
104- .collect (Collectors .joining ("\n " )));
104+ String firstError = "" ;
105+ if (response .getExecutionErrors ().size () != 0 ) {
106+ firstError = response .getExecutionErrors ().get (0 ).getMessage ();
107+ }
108+ throw new RuntimeException (firstError );
105109 }
106110
107111 QueryResult result = response .getResult ();
108112 Iterator <List <FieldValue >> iter = result .iterateAll ();
109113 while (iter .hasNext ()) {
110114 List <FieldValue > row = iter .next ();
111- out .println (row .stream ().map (val -> val .toString ()).collect (Collectors .joining ("," )));
115+ for (FieldValue val : row ) {
116+ out .printf ("%s," , val .toString ());
117+ }
118+ out .printf ("\n " );
112119 }
113120 }
114121 // [END run]
0 commit comments