/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.bigquerydatatransfer;

import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.datatransfer.v1.CreateTransferConfigRequest;
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;
import com.google.cloud.bigquery.datatransfer.v1.ProjectName;
import com.google.cloud.bigquery.datatransfer.v1.TransferConfig;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class RunHistoryIT {

  private static final Logger LOG = Logger.getLogger(GetTransferConfigInfoIT.class.getName());
  private static final String ID = UUID.randomUUID().toString().substring(0, 8);
  private BigQuery bigquery;
  private ByteArrayOutputStream bout;
  private String name;
  private String displayName;
  private String datasetName;
  private PrintStream out;
  private PrintStream originalPrintStream;

  private static final String PROJECT_ID = requireEnvVar("GOOGLE_CLOUD_PROJECT");

  private static String requireEnvVar(String varName) {
    String value = System.getenv(varName);
    assertNotNull(
        "Environment variable " + varName + " is required to perform these tests.",
        System.getenv(varName));
    return value;
  }

  @BeforeClass
  public static void checkRequirements() {
    requireEnvVar("GOOGLE_CLOUD_PROJECT");
  }

  @Before
  public void setUp() throws IOException {
    bout = new ByteArrayOutputStream();
    out = new PrintStream(bout);
    originalPrintStream = System.out;
    System.setOut(out);

    displayName = "MY_SCHEDULE_NAME_TEST_" + ID;
    datasetName = "MY_DATASET_NAME_TEST_" + ID;
    // create a temporary dataset
    bigquery = BigQueryOptions.getDefaultInstance().getService();
    bigquery.create(DatasetInfo.of(datasetName));
    // create a scheduled query
    String query =
        "SELECT CURRENT_TIMESTAMP() as current_time, @run_time as intended_run_time, "
            + "@run_date as intended_run_date, 17 as some_integer";
    String destinationTableName =
        "MY_DESTINATION_TABLE_" + UUID.randomUUID().toString().substring(0, 8) + "_{run_date}";
    Map<String, Value> params = new HashMap<>();
    params.put("query", Value.newBuilder().setStringValue(query).build());
    params.put(
        "destination_table_name_template",
        Value.newBuilder().setStringValue(destinationTableName).build());
    params.put("write_disposition", Value.newBuilder().setStringValue("WRITE_TRUNCATE").build());
    params.put("partitioning_field", Value.newBuilder().setStringValue("").build());
    TransferConfig transferConfig =
        TransferConfig.newBuilder()
            .setDestinationDatasetId(datasetName)
            .setDisplayName(displayName)
            .setDataSourceId("scheduled_query")
            .setParams(Struct.newBuilder().putAllFields(params).build())
            .setSchedule("every 24 hours")
            .build();
    try (DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.create()) {
      ProjectName parent = ProjectName.of(PROJECT_ID);
      CreateTransferConfigRequest request =
          CreateTransferConfigRequest.newBuilder()
              .setParent(parent.toString())
              .setTransferConfig(transferConfig)
              .build();
      name = dataTransferServiceClient.createTransferConfig(request).getName();
      System.out.println("\nScheduled query created successfully :" + name);
    }
  }

  @After
  public void tearDown() throws IOException {
    // delete scheduled query that was just created
    DeleteScheduledQuery.deleteScheduledQuery(name);
    // delete a temporary dataset
    bigquery.delete(datasetName, BigQuery.DatasetDeleteOption.deleteContents());

    // restores print statements in the original method
    System.out.flush();
    System.setOut(originalPrintStream);
    LOG.log(Level.INFO, bout.toString());
  }

  @Test
  public void testRunHistory() throws IOException {
    RunHistory.runHistory(name);
    assertThat(bout.toString()).contains("Success! Run ID :");
  }
}

@@ -742,497 +742,8 @@
 l;%0A%0A
-import com.google.cloud.bigquery.BigQuery;%0Aimport com.google.cloud.bigquery.BigQueryOptions;%0Aimport com.google.cloud.bigquery.DatasetInfo;%0Aimport com.google.cloud.bigquery.datatransfer.v1.CreateTransferConfigRequest;%0Aimport com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;%0Aimport com.google.cloud.bigquery.datatransfer.v1.ProjectName;%0Aimport com.google.cloud.bigquery.datatransfer.v1.TransferConfig;%0Aimport com.google.protobuf.Struct;%0Aimport com.google.protobuf.Value;%0A
 impo
@@ -836,79 +836,8 @@
 am;%0A
-import java.util.HashMap;%0Aimport java.util.Map;%0Aimport java.util.UUID;%0A
 impo
@@ -1138,227 +1138,34 @@
 ate 
-static final String ID = UUID.randomUUID().toString().substring(0, 8);%0A  private BigQuery bigquery;%0A  private ByteArrayOutputStream bout;%0A  private String name;%0A  private String displayName;%0A  private String datasetName
+ByteArrayOutputStream bout
 ;%0A  
@@ -1263,26 +1263,27 @@
  String 
-PROJECT_ID
+CONFIG_NAME
  = requi
@@ -1292,36 +1292,40 @@
 EnvVar(%22
-GOOGLE_CLOUD_PROJECT
+DTS_TRANSFER_CONFIG_NAME
 %22);%0A%0A  p
@@ -1660,28 +1660,32 @@
 ar(%22
-GOOGLE_CLOUD_PROJECT
+DTS_TRANSFER_CONFIG_NAME
 %22);%0A
@@ -1720,35 +1720,16 @@
  setUp()
- throws IOException
  %7B%0A    b
@@ -1862,2192 +1862,48 @@
 t);%0A
-%0A    displayName = %22MY_SCHEDULE_NAME_TEST_%22 + ID;%0A    datasetName = %22MY_DATASET_NAME_TEST_%22 + ID;%0A    // create a temporary dataset%0A    bigquery = BigQueryOptions.getDefaultInstance().getService();%0A    bigquery.create(DatasetInfo.of(datasetName));%0A    // create a scheduled query%0A    String query =%0A        %22SELECT CURRENT_TIMESTAMP() as current_time, @run_time as intended_run_time, %22%0A            + %22@run_date as intended_run_date, 17 as some_integer%22;%0A    String destinationTableName =%0A        %22MY_DESTINATION_TABLE_%22 + UUID.randomUUID().toString().substring(0, 8) + %22_%7Brun_date%7D%22;%0A    Map%3CString, Value%3E params = new HashMap%3C%3E();%0A    params.put(%22query%22, Value.newBuilder().setStringValue(query).build());%0A    params.put(%0A        %22destination_table_name_template%22,%0A        Value.newBuilder().setStringValue(destinationTableName).build());%0A    params.put(%22write_disposition%22, Value.newBuilder().setStringValue(%22WRITE_TRUNCATE%22).build());%0A    params.put(%22partitioning_field%22, Value.newBuilder().setStringValue(%22%22).build());%0A    TransferConfig transferConfig =%0A        TransferConfig.newBuilder()%0A            .setDestinationDatasetId(datasetName)%0A            .setDisplayName(displayName)%0A            .setDataSourceId(%22scheduled_query%22)%0A            .setParams(Struct.newBuilder().putAllFields(params).build())%0A            .setSchedule(%22every 24 hours%22)%0A            .build();%0A    try (DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.create()) %7B%0A      ProjectName parent = ProjectName.of(PROJECT_ID);%0A      CreateTransferConfigRequest request =%0A          CreateTransferConfigRequest.newBuilder()%0A              .setParent(parent.toString())%0A              .setTransferConfig(transferConfig)%0A              .build();%0A      name = dataTransferServiceClient.createTransferConfig(request).getName();%0A      System.out.println(%22%5CnScheduled query created successfully :%22 + name);%0A    %7D%0A  %7D%0A%0A  @After%0A  public void tearDown() throws IOException %7B%0A    // delete scheduled query that was just created%0A    DeleteScheduledQuery.deleteScheduledQuery(name);%0A    // delete a temporary dataset%0A    bigquery.delete(datasetName, BigQuery.DatasetDeleteOption.deleteContents());%0A
+  %7D%0A%0A  @After%0A  public void tearDown() %7B
 %0A   
@@ -2156,12 +2156,19 @@
 ory(
-name
+CONFIG_NAME
 );%0A 

update run history it (#348)