Skip to content
This repository was archived by the owner on Sep 27, 2023. It is now read-only.

Commit 0938236

Browse files
author
Praful Makani
authored
docs(samples): add create cloud storage transfer (#431)
1 parent 9bc3eb9 commit 0938236

File tree

3 files changed

+219
-1
lines changed

3 files changed

+219
-1
lines changed

samples/snippets/src/main/java/com/example/bigquerydatatransfer/CreateAmazonS3Transfer.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,6 @@ public static void createAmazonS3Transfer(String projectId, TransferConfig trans
7777
} catch (ApiException ex) {
7878
System.out.print("Amazon s3 transfer was not created." + ex.toString());
7979
}
80-
;
8180
}
8281
}
8382
// [END bigquerydatatransfer_create_amazons3_transfer]
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.bigquerydatatransfer;
18+
19+
// [START bigquerydatatransfer_create_cloudstorage_transfer]
20+
import com.google.api.gax.rpc.ApiException;
21+
import com.google.cloud.bigquery.datatransfer.v1.CreateTransferConfigRequest;
22+
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;
23+
import com.google.cloud.bigquery.datatransfer.v1.ProjectName;
24+
import com.google.cloud.bigquery.datatransfer.v1.TransferConfig;
25+
import com.google.protobuf.Struct;
26+
import com.google.protobuf.Value;
27+
import java.io.IOException;
28+
import java.util.HashMap;
29+
import java.util.Map;
30+
31+
// Sample to create google cloud storage transfer config
32+
public class CreateCloudStorageTransfer {
33+
34+
public static void main(String[] args) throws IOException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
final String projectId = "MY_PROJECT_ID";
37+
String datasetId = "MY_DATASET_ID";
38+
String tableId = "MY_TABLE_ID";
39+
// GCS Uri
40+
String sourceUri = "gs://cloud-samples-data/bigquery/us-states/us-states.csv";
41+
String fileFormat = "CSV";
42+
String fieldDelimiter = ",";
43+
String skipLeadingRows = "1";
44+
Map<String, Value> params = new HashMap<>();
45+
params.put(
46+
"destination_table_name_template", Value.newBuilder().setStringValue(tableId).build());
47+
params.put("data_path_template", Value.newBuilder().setStringValue(sourceUri).build());
48+
params.put("write_disposition", Value.newBuilder().setStringValue("APPEND").build());
49+
params.put("file_format", Value.newBuilder().setStringValue(fileFormat).build());
50+
params.put("field_delimiter", Value.newBuilder().setStringValue(fieldDelimiter).build());
51+
params.put("skip_leading_rows", Value.newBuilder().setStringValue(skipLeadingRows).build());
52+
TransferConfig transferConfig =
53+
TransferConfig.newBuilder()
54+
.setDestinationDatasetId(datasetId)
55+
.setDisplayName("Your Google Cloud Storage Config Name")
56+
.setDataSourceId("google_cloud_storage")
57+
.setParams(Struct.newBuilder().putAllFields(params).build())
58+
.setSchedule("every 24 hours")
59+
.build();
60+
createCloudStorageTransfer(projectId, transferConfig);
61+
}
62+
63+
public static void createCloudStorageTransfer(String projectId, TransferConfig transferConfig)
64+
throws IOException {
65+
try (DataTransferServiceClient client = DataTransferServiceClient.create()) {
66+
ProjectName parent = ProjectName.of(projectId);
67+
CreateTransferConfigRequest request =
68+
CreateTransferConfigRequest.newBuilder()
69+
.setParent(parent.toString())
70+
.setTransferConfig(transferConfig)
71+
.build();
72+
TransferConfig config = client.createTransferConfig(request);
73+
System.out.println("Cloud storage transfer created successfully :" + config.getName());
74+
} catch (ApiException ex) {
75+
System.out.print("Cloud storage transfer was not created." + ex.toString());
76+
}
77+
}
78+
}
79+
// [END bigquerydatatransfer_create_cloudstorage_transfer]
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.bigquerydatatransfer;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
21+
22+
import com.google.cloud.bigquery.BigQuery;
23+
import com.google.cloud.bigquery.BigQueryOptions;
24+
import com.google.cloud.bigquery.DatasetInfo;
25+
import com.google.cloud.bigquery.Field;
26+
import com.google.cloud.bigquery.Schema;
27+
import com.google.cloud.bigquery.StandardSQLTypeName;
28+
import com.google.cloud.bigquery.StandardTableDefinition;
29+
import com.google.cloud.bigquery.TableDefinition;
30+
import com.google.cloud.bigquery.TableId;
31+
import com.google.cloud.bigquery.TableInfo;
32+
import com.google.cloud.bigquery.datatransfer.v1.TransferConfig;
33+
import com.google.protobuf.Struct;
34+
import com.google.protobuf.Value;
35+
import java.io.ByteArrayOutputStream;
36+
import java.io.IOException;
37+
import java.io.PrintStream;
38+
import java.util.HashMap;
39+
import java.util.Map;
40+
import java.util.UUID;
41+
import java.util.logging.Level;
42+
import java.util.logging.Logger;
43+
import org.junit.After;
44+
import org.junit.Before;
45+
import org.junit.BeforeClass;
46+
import org.junit.Test;
47+
48+
public class CreateCloudStorageTransferIT {
49+
50+
private static final Logger LOG = Logger.getLogger(CreateCloudStorageTransferIT.class.getName());
51+
private static final String ID = UUID.randomUUID().toString().substring(0, 8);
52+
private BigQuery bigquery;
53+
private ByteArrayOutputStream bout;
54+
private String name;
55+
private String displayName;
56+
private String datasetName;
57+
private String tableName;
58+
private PrintStream out;
59+
private PrintStream originalPrintStream;
60+
61+
private static final String PROJECT_ID = requireEnvVar("GOOGLE_CLOUD_PROJECT");
62+
63+
private static String requireEnvVar(String varName) {
64+
String value = System.getenv(varName);
65+
assertNotNull(
66+
"Environment variable " + varName + " is required to perform these tests.",
67+
System.getenv(varName));
68+
return value;
69+
}
70+
71+
@BeforeClass
72+
public static void checkRequirements() {
73+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
74+
}
75+
76+
@Before
77+
public void setUp() {
78+
displayName = "CLOUD_STORAGE_CONFIG_TEST_" + ID;
79+
datasetName = "CLOUD_STORAGE_DATASET_NAME_TEST_" + ID;
80+
tableName = "CLOUD_STORAGE_TABLE_NAME_TEST_" + ID;
81+
// create a temporary dataset
82+
bigquery = BigQueryOptions.getDefaultInstance().getService();
83+
bigquery.create(DatasetInfo.of(datasetName));
84+
// create a temporary table
85+
Schema schema =
86+
Schema.of(
87+
Field.of("name", StandardSQLTypeName.STRING),
88+
Field.of("post_abbr", StandardSQLTypeName.STRING));
89+
TableDefinition tableDefinition = StandardTableDefinition.of(schema);
90+
TableInfo tableInfo = TableInfo.of(TableId.of(datasetName, tableName), tableDefinition);
91+
bigquery.create(tableInfo);
92+
93+
bout = new ByteArrayOutputStream();
94+
out = new PrintStream(bout);
95+
originalPrintStream = System.out;
96+
System.setOut(out);
97+
}
98+
99+
@After
100+
public void tearDown() throws IOException {
101+
// Clean up
102+
DeleteTransferConfig.deleteTransferConfig(name);
103+
// delete a temporary table
104+
bigquery.delete(TableId.of(datasetName, tableName));
105+
// delete a temporary dataset
106+
bigquery.delete(datasetName, BigQuery.DatasetDeleteOption.deleteContents());
107+
// restores print statements in the original method
108+
System.out.flush();
109+
System.setOut(originalPrintStream);
110+
LOG.log(Level.INFO, bout.toString());
111+
}
112+
113+
@Test
114+
public void testCreateCloudStorageTransfer() throws IOException {
115+
String sourceUri = "gs://cloud-samples-data/bigquery/us-states/us-states.csv";
116+
String fileFormat = "CSV";
117+
String fieldDelimiter = ",";
118+
String skipLeadingRows = "1";
119+
Map<String, Value> params = new HashMap<>();
120+
params.put(
121+
"destination_table_name_template", Value.newBuilder().setStringValue(tableName).build());
122+
params.put("data_path_template", Value.newBuilder().setStringValue(sourceUri).build());
123+
params.put("write_disposition", Value.newBuilder().setStringValue("APPEND").build());
124+
params.put("file_format", Value.newBuilder().setStringValue(fileFormat).build());
125+
params.put("field_delimiter", Value.newBuilder().setStringValue(fieldDelimiter).build());
126+
params.put("skip_leading_rows", Value.newBuilder().setStringValue(skipLeadingRows).build());
127+
TransferConfig transferConfig =
128+
TransferConfig.newBuilder()
129+
.setDestinationDatasetId(datasetName)
130+
.setDisplayName(displayName)
131+
.setDataSourceId("google_cloud_storage")
132+
.setParams(Struct.newBuilder().putAllFields(params).build())
133+
.setSchedule("every 24 hours")
134+
.build();
135+
CreateCloudStorageTransfer.createCloudStorageTransfer(PROJECT_ID, transferConfig);
136+
String result = bout.toString();
137+
name = result.substring(result.indexOf(":") + 1, result.length() - 1);
138+
assertThat(result).contains("Cloud storage transfer created successfully :");
139+
}
140+
}

0 commit comments

Comments
 (0)