diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000000..2f7896d1d136
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000000..d64569567334
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
diff --git a/checkstyle.xml b/checkstyle.xml
new file mode 100644
index 000000000000..08df965ae6bb
--- /dev/null
+++ b/checkstyle.xml
@@ -0,0 +1,385 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/pom.xml b/examples/pom.xml
new file mode 100644
index 000000000000..fcb52fcdbf8d
--- /dev/null
+++ b/examples/pom.xml
@@ -0,0 +1,223 @@
+
+
+
+ 4.0.0
+
+
+ com.google.cloud.dataflow
+ google-cloud-dataflow-java-sdk-parent
+ manual_build
+
+
+ com.google.cloud.dataflow
+ google-cloud-dataflow-java-examples-all
+ Google Cloud Dataflow Java Examples - All
+ Google Cloud Dataflow Java SDK provides a simple, Java-based
+ interface for processing virtually any size data using Google cloud
+ resources. This artifact includes all Dataflow Java SDK
+ examples.
+ http://cloud.google.com/dataflow
+
+ manual_build
+
+ jar
+
+
+
+ DataflowPipelineTests
+
+ true
+ com.google.cloud.dataflow.sdk.testing.RunnableOnService
+ both
+
+
+
+
+
+
+
+ maven-compiler-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 2.12
+
+ ../checkstyle.xml
+ true
+ true
+ true
+
+
+
+
+ check
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 2.4
+
+
+ attach-sources
+ compile
+
+ jar
+
+
+
+ attach-test-sources
+ test-compile
+
+ test-jar
+
+
+
+
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 2.4.0
+ true
+
+ ${project.artifactId}-bundled-${project.version}
+
+
+ *;scope=compile|runtime;artifactId=!google-cloud-dataflow-java-sdk-all;inline=true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+ dataflow-examples-compile
+ compile
+
+ jar
+
+
+
+ dataflow-examples-test-compile
+ test-compile
+
+ test-jar
+
+
+
+
+
+
+
+
+
+ com.google.cloud.dataflow
+ google-cloud-dataflow-java-sdk-all
+ ${project.version}
+
+
+
+ com.google.apis
+ google-api-services-storage
+ v1-rev11-1.19.0
+
+
+
+ com.google.apis
+ google-api-services-bigquery
+ v2-rev167-1.19.0
+
+
+
+ com.google.guava
+ guava-jdk5
+
+
+
+
+
+ com.google.http-client
+ google-http-client-jackson2
+ 1.19.0
+
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+ 2.4.2
+
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+ 2.4.2
+
+
+
+
+ org.slf4j
+ slf4j-api
+ 1.7.7
+
+
+
+ org.slf4j
+ slf4j-jdk14
+ 1.7.7
+
+
+
+
+ com.google.cloud.dataflow
+ google-cloud-dataflow-java-sdk-all
+ ${project.version}
+ test-jar
+ test
+
+
+
+ org.hamcrest
+ hamcrest-all
+ 1.3
+ test
+
+
+
+ junit
+ junit
+ 4.11
+ test
+
+
+
diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/BigQueryTornadoes.java b/examples/src/main/java/com/google/cloud/dataflow/examples/BigQueryTornadoes.java
new file mode 100644
index 000000000000..43e94c08633b
--- /dev/null
+++ b/examples/src/main/java/com/google/cloud/dataflow/examples/BigQueryTornadoes.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * 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.google.cloud.dataflow.examples;
+
+import com.google.api.services.bigquery.model.TableFieldSchema;
+import com.google.api.services.bigquery.model.TableRow;
+import com.google.api.services.bigquery.model.TableSchema;
+import com.google.cloud.dataflow.sdk.Pipeline;
+import com.google.cloud.dataflow.sdk.io.BigQueryIO;
+import com.google.cloud.dataflow.sdk.options.Default;
+import com.google.cloud.dataflow.sdk.options.Description;
+import com.google.cloud.dataflow.sdk.options.PipelineOptions;
+import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
+import com.google.cloud.dataflow.sdk.options.Validation;
+import com.google.cloud.dataflow.sdk.transforms.Count;
+import com.google.cloud.dataflow.sdk.transforms.DoFn;
+import com.google.cloud.dataflow.sdk.transforms.PTransform;
+import com.google.cloud.dataflow.sdk.transforms.ParDo;
+import com.google.cloud.dataflow.sdk.values.KV;
+import com.google.cloud.dataflow.sdk.values.PCollection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * An example that reads the public samples of weather data from BigQuery, counts the number of
+ * tornadoes that occur in each month, and writes the results to BigQuery.
+ */
+public class BigQueryTornadoes {
+ // Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod.
+ private static final String WEATHER_SAMPLES_TABLE =
+ "clouddataflow-readonly:samples.weather_stations";
+
+ /**
+ * Examines each row in the input table. If a tornado was recorded in that sample, the month in
+ * which it occurred is output.
+ */
+ static class ExtractTornadoesFn extends DoFn {
+ @Override
+ public void processElement(ProcessContext c){
+ TableRow row = c.element();
+ if ((Boolean) row.get("tornado")) {
+ c.output(Integer.parseInt((String) row.get("month")));
+ }
+ }
+ }
+
+ /**
+ * Prepares the data for writing to BigQuery by building a TableRow object containing an
+ * integer representation of month and the number of tornadoes that occurred in each month.
+ */
+ static class FormatCountsFn extends DoFn, TableRow> {
+ @Override
+ public void processElement(ProcessContext c) {
+ TableRow row = new TableRow()
+ .set("month", c.element().getKey().intValue())
+ .set("tornado_count", c.element().getValue().longValue());
+ c.output(row);
+ }
+ }
+
+ /**
+ * Takes rows from a table and generates a table of counts.
+ *
+ * The input schema is described by
+ * https://developers.google.com/bigquery/docs/dataset-gsod .
+ * The output contains the total number of tornadoes found in each month in
+ * the following schema:
+ *
+ * Inherits standard configuration options.
+ */
+ private static interface Options extends PipelineOptions {
+ @Description("Table to read from, specified as "
+ + ":.")
+ @Default.String(WEATHER_SAMPLES_TABLE)
+ String getInput();
+ void setInput(String value);
+
+ @Description("Table to write to, specified as "
+ + ":.")
+ @Validation.Required
+ String getOutput();
+ void setOutput(String value);
+ }
+
+ public static void main(String[] args) {
+ Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
+
+ Pipeline p = Pipeline.create(options);
+
+ // Build the table schema for the output table.
+ List fields = new ArrayList<>();
+ fields.add(new TableFieldSchema().setName("month").setType("INTEGER"));
+ fields.add(new TableFieldSchema().setName("tornado_count").setType("INTEGER"));
+ TableSchema schema = new TableSchema().setFields(fields);
+
+ p.apply(BigQueryIO.Read.from(options.getInput()))
+ .apply(new CountTornadoes())
+ .apply(BigQueryIO.Write
+ .to(options.getOutput())
+ .withSchema(schema)
+ .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
+ .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE));
+
+ p.run();
+ }
+}
diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/DatastoreWordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/DatastoreWordCount.java
new file mode 100644
index 000000000000..1e00589281aa
--- /dev/null
+++ b/examples/src/main/java/com/google/cloud/dataflow/examples/DatastoreWordCount.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * 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.google.cloud.dataflow.examples;
+
+import com.google.api.services.datastore.DatastoreV1.Entity;
+import com.google.api.services.datastore.DatastoreV1.Key;
+import com.google.api.services.datastore.DatastoreV1.Property;
+import com.google.api.services.datastore.DatastoreV1.Query;
+import com.google.api.services.datastore.DatastoreV1.Value;
+import com.google.api.services.datastore.client.DatastoreHelper;
+import com.google.cloud.dataflow.sdk.Pipeline;
+import com.google.cloud.dataflow.sdk.io.DatastoreIO;
+import com.google.cloud.dataflow.sdk.io.TextIO;
+import com.google.cloud.dataflow.sdk.options.Default;
+import com.google.cloud.dataflow.sdk.options.Description;
+import com.google.cloud.dataflow.sdk.options.PipelineOptions;
+import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
+import com.google.cloud.dataflow.sdk.options.Validation;
+import com.google.cloud.dataflow.sdk.transforms.DoFn;
+import com.google.cloud.dataflow.sdk.transforms.ParDo;
+
+import java.util.Map;
+
+/**
+ * A WordCount example using DatastoreIO.
+ *
+ *
This example shows how to use DatastoreIO to read from Datastore and
+ * write the results to Cloud Storage. Note that this example will write
+ * data to Datastore, which may incur charge for Datastore operations.
+ *
+ *
To run this example, users need to set up the environment and use gcloud
+ * to get credential for Datastore:
+ *
Note that the environment variable CLOUDSDK_EXTRA_SCOPES must be set
+ * to the same value when executing a Datastore pipeline, as the local auth
+ * cache is keyed by the requested scopes.
+ *
+ *
To run this pipeline locally, the following options must be provided:
+ *
To run this example using Dataflow service, you must additionally
+ * provide either {@literal --stagingLocation} or {@literal --tempLocation}, and
+ * select one of the Dataflow pipeline runners, eg
+ * {@literal --runner=BlockingDataflowPipelineRunner}.
+ */
+public class DatastoreWordCount {
+
+ /**
+ * A DoFn that gets the content of an entity (one line in a
+ * Shakespeare play) and converts it to a string.
+ */
+ static class GetContentFn extends DoFn {
+ @Override
+ public void processElement(ProcessContext c) {
+ Map props = DatastoreHelper.getPropertyMap(c.element());
+ c.output(DatastoreHelper.getString(props.get("content")));
+ }
+ }
+
+ /**
+ * A DoFn that creates entity for every line in Shakespeare.
+ */
+ static class CreateEntityFn extends DoFn {
+ private String kind;
+
+ CreateEntityFn(String kind) {
+ this.kind = kind;
+ }
+
+ public Entity makeEntity(String content) {
+ Entity.Builder entityBuilder = Entity.newBuilder();
+ // Create entities with same ancestor Key.
+ Key ancestorKey = DatastoreHelper.makeKey(kind, "root").build();
+ Key key = DatastoreHelper.makeKey(ancestorKey, kind).build();
+ entityBuilder.setKey(key);
+ entityBuilder.addProperty(Property.newBuilder()
+ .setName("content")
+ .setValue(Value.newBuilder().setStringValue(content)));
+ return entityBuilder.build();
+ }
+
+ @Override
+ public void processElement(ProcessContext c) {
+ c.output(makeEntity(c.element()));
+ }
+ }
+
+ /**
+ * Options supported by {@link DatastoreWordCount}.
+ *
+ * Inherits standard configuration options.
+ */
+ private static interface Options extends PipelineOptions {
+ @Description("Path of the file to read from and store to Datastore")
+ @Default.String("gs://dataflow-samples/shakespeare/kinglear.txt")
+ String getInput();
+ void setInput(String value);
+
+ @Description("Path of the file to write to")
+ @Validation.Required
+ String getOutput();
+ void setOutput(String value);
+
+ @Description("Dataset ID to read from datastore")
+ @Validation.Required
+ String getDataset();
+ void setDataset(String value);
+
+ @Description("Dataset entity kind")
+ @Default.String("shakespeare-demo")
+ String getKind();
+ void setKind(String value);
+
+ @Description("Read an existing dataset, do not write first")
+ boolean isReadOnly();
+ void setReadOnly(boolean value);
+ }
+
+ /**
+ * An example which creates a pipeline to populate DatastoreIO from a
+ * text input. Forces use of DirectPipelineRunner for local execution mode.
+ */
+ public static void writeDataToDatastore(Options options) {
+ // Runs locally via DirectPiplineRunner, as writing is not yet implemented
+ // for the other runners which is why we just create a PipelineOptions with defaults.
+ Pipeline p = Pipeline.create(PipelineOptionsFactory.create());
+ p.apply(TextIO.Read.named("ReadLines").from(options.getInput()))
+ .apply(ParDo.of(new CreateEntityFn(options.getKind())))
+ .apply(DatastoreIO.Write.to(options.getDataset()));
+
+ p.run();
+ }
+
+ /**
+ * An example which creates a pipeline to do DatastoreIO.Read from Datastore.
+ */
+ public static void readDataFromDatastore(Options options) {
+ // Build a query: read all entities of the specified kind.
+ Query.Builder q = Query.newBuilder();
+ q.addKindBuilder().setName(options.getKind());
+ Query query = q.build();
+
+ Pipeline p = Pipeline.create(options);
+ p.apply(DatastoreIO.Read.named("ReadShakespeareFromDatastore")
+ .from(options.getDataset(), query))
+ .apply(ParDo.of(new GetContentFn()))
+ .apply(new WordCount.CountWords())
+ .apply(TextIO.Write.named("WriteLines").to(options.getOutput()));
+
+ p.run();
+ }
+
+ /**
+ * Main function.
+ * An example to demo how to use DatastoreIO. The runner here is
+ * customizable, which means users could pass either DirectPipelineRunner
+ * or DataflowPipelineRunner in PipelineOptions.
+ */
+ public static void main(String args[]) {
+ // The options are used in two places, for Dataflow service, and
+ // building DatastoreIO.Read object
+ Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
+
+ if (!options.isReadOnly()) {
+ // First example: write data to Datastore for reading later.
+ // Note: this will insert new entries with the given kind. Existing entries
+ // should be cleared first, or the final counts will contain duplicates.
+ // The Datastore Admin tool in the AppEngine console can be used to erase
+ // all entries with a particular kind.
+ DatastoreWordCount.writeDataToDatastore(options);
+ }
+
+ // Second example: do parallel read from Datastore.
+ DatastoreWordCount.readDataFromDatastore(options);
+ }
+}
diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/TfIdf.java b/examples/src/main/java/com/google/cloud/dataflow/examples/TfIdf.java
new file mode 100644
index 000000000000..a6bd4f27fd61
--- /dev/null
+++ b/examples/src/main/java/com/google/cloud/dataflow/examples/TfIdf.java
@@ -0,0 +1,425 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * 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.google.cloud.dataflow.examples;
+
+import com.google.cloud.dataflow.sdk.Pipeline;
+import com.google.cloud.dataflow.sdk.coders.Coder;
+import com.google.cloud.dataflow.sdk.coders.KvCoder;
+import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder;
+import com.google.cloud.dataflow.sdk.coders.URICoder;
+import com.google.cloud.dataflow.sdk.io.TextIO;
+import com.google.cloud.dataflow.sdk.options.Default;
+import com.google.cloud.dataflow.sdk.options.Description;
+import com.google.cloud.dataflow.sdk.options.GcsOptions;
+import com.google.cloud.dataflow.sdk.options.PipelineOptions;
+import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
+import com.google.cloud.dataflow.sdk.options.Validation;
+import com.google.cloud.dataflow.sdk.transforms.Count;
+import com.google.cloud.dataflow.sdk.transforms.DoFn;
+import com.google.cloud.dataflow.sdk.transforms.Flatten;
+import com.google.cloud.dataflow.sdk.transforms.Keys;
+import com.google.cloud.dataflow.sdk.transforms.PTransform;
+import com.google.cloud.dataflow.sdk.transforms.ParDo;
+import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates;
+import com.google.cloud.dataflow.sdk.transforms.Values;
+import com.google.cloud.dataflow.sdk.transforms.View;
+import com.google.cloud.dataflow.sdk.transforms.WithKeys;
+import com.google.cloud.dataflow.sdk.transforms.join.CoGbkResult;
+import com.google.cloud.dataflow.sdk.transforms.join.CoGroupByKey;
+import com.google.cloud.dataflow.sdk.transforms.join.KeyedPCollectionTuple;
+import com.google.cloud.dataflow.sdk.util.GcsUtil;
+import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath;
+import com.google.cloud.dataflow.sdk.values.KV;
+import com.google.cloud.dataflow.sdk.values.PCollection;
+import com.google.cloud.dataflow.sdk.values.PCollectionList;
+import com.google.cloud.dataflow.sdk.values.PCollectionView;
+import com.google.cloud.dataflow.sdk.values.PDone;
+import com.google.cloud.dataflow.sdk.values.PInput;
+import com.google.cloud.dataflow.sdk.values.TupleTag;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * An example that computes a basic TF-IDF search table for a directory or GCS prefix.
+ *
+ *
To execute this pipeline using the Dataflow service
+ * to index the works of Shakespeare and write the results to a GCS bucket:
+ * (For execution via the Dataflow service, only GCS locations are supported)
+ *
+ *
The default input is gs://dataflow-samples/shakespeare/
+ */
+public class TfIdf {
+ /**
+ * Options supported by {@link TfIdf}.
+ *
+ * Inherits standard configuration options.
+ */
+ private static interface Options extends PipelineOptions {
+ @Description("Path to the directory or GCS prefix containing files to read from")
+ @Default.String("gs://dataflow-samples/shakespeare/")
+ String getInput();
+ void setInput(String value);
+
+ @Description("Prefix of output URI to write to")
+ @Validation.Required
+ String getOutput();
+ void setOutput(String value);
+ }
+
+ /**
+ * Lists documents contained beneath the {@code options.input} prefix/directory.
+ */
+ public static Set listInputDocuments(Options options)
+ throws URISyntaxException, IOException {
+ URI baseUri = new URI(options.getInput());
+
+ // List all documents in the directory or GCS prefix.
+ URI absoluteUri;
+ if (baseUri.getScheme() != null) {
+ absoluteUri = baseUri;
+ } else {
+ absoluteUri = new URI(
+ "file",
+ baseUri.getAuthority(),
+ baseUri.getPath(),
+ baseUri.getQuery(),
+ baseUri.getFragment());
+ }
+
+ Set uris = new HashSet<>();
+ if (absoluteUri.getScheme().equals("file")) {
+ File directory = new File(absoluteUri);
+ for (String entry : directory.list()) {
+ File path = new File(directory, entry);
+ uris.add(path.toURI());
+ }
+ } else if (absoluteUri.getScheme().equals("gs")) {
+ GcsUtil gcsUtil = options.as(GcsOptions.class).getGcsUtil();
+ URI gcsUriGlob = new URI(
+ absoluteUri.getScheme(),
+ absoluteUri.getAuthority(),
+ absoluteUri.getPath() + "*",
+ absoluteUri.getQuery(),
+ absoluteUri.getFragment());
+ for (GcsPath entry : gcsUtil.expand(GcsPath.fromUri(gcsUriGlob))) {
+ uris.add(entry.toUri());
+ }
+ }
+
+ return uris;
+ }
+
+ /**
+ * Reads the documents at the provided uris and returns all lines
+ * from the documents tagged with which document they are from.
+ */
+ public static class ReadDocuments
+ extends PTransform>> {
+
+ private Iterable uris;
+
+ public ReadDocuments(Iterable uris) {
+ this.uris = uris;
+ }
+
+ @Override
+ public Coder> getDefaultOutputCoder() {
+ return KvCoder.of(URICoder.of(), StringUtf8Coder.of());
+ }
+
+ @Override
+ public PCollection> apply(PInput input) {
+ Pipeline pipeline = getPipeline();
+
+ // Create one TextIO.Read transform for each document
+ // and add its output to a PCollectionList
+ PCollectionList> urisToLines =
+ PCollectionList.empty(pipeline);
+
+ // TextIO.Read supports:
+ // - file: URIs and paths locally
+ // - gs: URIs on the service
+ for (final URI uri : uris) {
+ String uriString;
+ if (uri.getScheme().equals("file")) {
+ uriString = new File(uri).getPath();
+ } else {
+ uriString = uri.toString();
+ }
+
+ PCollection> oneUriToLines = pipeline
+ .apply(TextIO.Read.from(uriString)
+ .named("TextIO.Read(" + uriString + ")"))
+ .apply(WithKeys.of(uri));
+
+ urisToLines = urisToLines.and(oneUriToLines);
+ }
+
+ return urisToLines.apply(Flatten.>create());
+ }
+ }
+
+ /**
+ * A transform containing a basic TF-IDF pipeline. The input consists of KV objects
+ * where the key is the document's URI and the value is a piece
+ * of the document's content. The output is mapping from terms to
+ * scores for each document URI.
+ */
+ public static class ComputeTfIdf
+ extends PTransform>, PCollection>>> {
+
+ public ComputeTfIdf() { }
+
+ @Override
+ public PCollection>> apply(
+ PCollection> uriToContent) {
+
+ // Compute the total number of documents, and
+ // prepare this singleton PCollectionView for
+ // use as a side input.
+ final PCollectionView totalDocuments =
+ uriToContent
+ .apply(Keys.create())
+ .apply(RemoveDuplicates.create())
+ .apply(Count.globally())
+ .apply(View.asSingleton());
+
+ // Create a collection of pairs mapping a URI to each
+ // of the words in the document associated with that that URI.
+ PCollection> uriToWords = uriToContent
+ .apply(ParDo.named("SplitWords").of(
+ new DoFn, KV>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ URI uri = c.element().getKey();
+ String line = c.element().getValue();
+ for (String word : line.split("\\W+")) {
+ if (!word.isEmpty()) {
+ c.output(KV.of(uri, word.toLowerCase()));
+ }
+ }
+ }
+ }));
+
+ // Compute a mapping from each word to the total
+ // number of documents in which it appears.
+ PCollection> wordToDocCount = uriToWords
+ .apply(RemoveDuplicates.>create())
+ .apply(Values.create())
+ .apply(Count.perElement());
+
+ // Compute a mapping from each URI to the total
+ // number of words in the document associated with that URI.
+ PCollection> uriToWordTotal = uriToWords
+ .apply(Keys.create())
+ .apply(Count.perElement());
+
+ // Count, for each (URI, word) pair, the number of
+ // occurrences of that word in the document associated
+ // with the URI.
+ PCollection, Long>> uriAndWordToCount = uriToWords
+ .apply(Count.>perElement());
+
+ // Adjust the above collection to a mapping from
+ // (URI, word) pairs to counts into an isomorphic mapping
+ // from URI to (word, count) pairs, to prepare for a join
+ // by the URI key.
+ PCollection>> uriToWordAndCount = uriAndWordToCount
+ .apply(ParDo.of(new DoFn, Long>, KV>>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ URI uri = c.element().getKey().getKey();
+ String word = c.element().getKey().getValue();
+ Long occurrences = c.element().getValue();
+ c.output(KV.of(uri, KV.of(word, occurrences)));
+ }
+ }));
+
+ // Prepare to join the mapping of URI to (word, count) pairs with
+ // the mapping of URI to total word counts, by associating
+ // each of the input PCollection> with
+ // a tuple tag. Each input must have the same key type, URI
+ // in this case. The type parameter of the tuple tag matches
+ // the types of the values for each collection.
+ final TupleTag wordTotalsTag = new TupleTag();
+ final TupleTag> wordCountsTag = new TupleTag>();
+ KeyedPCollectionTuple coGbkInput = KeyedPCollectionTuple
+ .of(wordTotalsTag, uriToWordTotal)
+ .and(wordCountsTag, uriToWordAndCount);
+
+ // Perform a CoGroupByKey (a sort of pre-join) on the prepared
+ // inputs. This yields a mapping from URI to a CoGbkResult
+ // (CoGroupByKey Result). The CoGbkResult is a mapping
+ // from the above tuple tags to the values in each input
+ // associated with a particular URI. In this case, each
+ // KV group a URI with the total number of
+ // words in that document as well as all the (word, count)
+ // pairs for particular words.
+ PCollection> uriToWordAndCountAndTotal = coGbkInput
+ .apply(CoGroupByKey.create().withName("CoGroupByURI"));
+
+ // Compute a mapping from each word to a (URI, term frequency)
+ // pair for each URI. A word's term frequency for a document
+ // is simply the number of times that word occurs in the document
+ // divided by the total number of words in the document.
+ PCollection>> wordToUriAndTf = uriToWordAndCountAndTotal
+ .apply(ParDo.of(new DoFn, KV>>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ URI uri = c.element().getKey();
+ Long wordTotal = c.element().getValue().getOnly(wordTotalsTag);
+
+ for (KV wordAndCount : c.element().getValue().getAll(wordCountsTag)) {
+ String word = wordAndCount.getKey();
+ Long wordCount = wordAndCount.getValue();
+ Double termFrequency = wordCount.doubleValue() / wordTotal.doubleValue();
+ c.output(KV.of(word, KV.of(uri, termFrequency)));
+ }
+ }
+ }));
+
+ // Compute a mapping from each word to its document frequency.
+ // A word's document frequency in a corpus is the number of
+ // documents in which the word appears divided by the total
+ // number of documents in the corpus. Note how the total number of
+ // documents is passed as a side input; the same value is
+ // presented to each invocation of the DoFn.
+ PCollection> wordToDf = wordToDocCount
+ .apply(ParDo
+ .withSideInputs(totalDocuments)
+ .of(new DoFn, KV>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ String word = c.element().getKey();
+ Long documentCount = c.element().getValue();
+ Long documentTotal = c.sideInput(totalDocuments);
+ Double documentFrequency = documentCount.doubleValue()
+ / documentTotal.doubleValue();
+
+ c.output(KV.of(word, documentFrequency));
+ }
+ }));
+
+ // Join the term frequency and document frequency
+ // collections, each keyed on the word.
+ final TupleTag> tfTag = new TupleTag>();
+ final TupleTag dfTag = new TupleTag();
+ PCollection> wordToUriAndTfAndDf = KeyedPCollectionTuple
+ .of(tfTag, wordToUriAndTf)
+ .and(dfTag, wordToDf)
+ .apply(CoGroupByKey.create());
+
+ // Compute a mapping from each word to a (URI, TF-IDF) score
+ // for each URI. There are a variety of definitions of TF-IDF
+ // ("term frequency - inverse document frequency") score;
+ // here we use a basic version which is the term frequency
+ // divided by the log of the document frequency.
+ PCollection>> wordToUriAndTfIdf = wordToUriAndTfAndDf
+ .apply(ParDo.of(new DoFn, KV>>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ String word = c.element().getKey();
+ Double df = c.element().getValue().getOnly(dfTag);
+
+ for (KV uriAndTf : c.element().getValue().getAll(tfTag)) {
+ URI uri = uriAndTf.getKey();
+ Double tf = uriAndTf.getValue();
+ Double tfIdf = tf * Math.log(1 / df);
+ c.output(KV.of(word, KV.of(uri, tfIdf)));
+ }
+ }
+ }));
+
+ return wordToUriAndTfIdf;
+ }
+ }
+
+ /**
+ * A {@link PTransform} to write, in CSV format, a mapping from term and URI
+ * to score.
+ */
+ public static class WriteTfIdf
+ extends PTransform>>, PDone> {
+
+ private String output;
+
+ public WriteTfIdf(String output) {
+ this.output = output;
+ }
+
+ @Override
+ public PDone apply(PCollection>> wordToUriAndTfIdf) {
+ return wordToUriAndTfIdf
+ .apply(ParDo.of(new DoFn>, String>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ c.output(String.format("%s,\t%s,\t%f",
+ c.element().getKey(),
+ c.element().getValue().getKey(),
+ c.element().getValue().getValue()));
+ }
+ }))
+ .apply(TextIO.Write
+ .to(output)
+ .withSuffix(".csv"));
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
+ Pipeline pipeline = Pipeline.create(options);
+
+ pipeline
+ .apply(new ReadDocuments(listInputDocuments(options)))
+ .apply(new ComputeTfIdf())
+ .apply(new WriteTfIdf(options.getOutput()));
+
+ pipeline.run();
+ }
+}
diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/TopWikipediaSessions.java b/examples/src/main/java/com/google/cloud/dataflow/examples/TopWikipediaSessions.java
new file mode 100644
index 000000000000..baa520ea0447
--- /dev/null
+++ b/examples/src/main/java/com/google/cloud/dataflow/examples/TopWikipediaSessions.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * 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.google.cloud.dataflow.examples;
+
+import com.google.api.services.bigquery.model.TableRow;
+import com.google.cloud.dataflow.sdk.Pipeline;
+import com.google.cloud.dataflow.sdk.coders.TableRowJsonCoder;
+import com.google.cloud.dataflow.sdk.io.TextIO;
+import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions;
+import com.google.cloud.dataflow.sdk.options.Default;
+import com.google.cloud.dataflow.sdk.options.Description;
+import com.google.cloud.dataflow.sdk.options.PipelineOptions;
+import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
+import com.google.cloud.dataflow.sdk.options.Validation;
+import com.google.cloud.dataflow.sdk.transforms.Count;
+import com.google.cloud.dataflow.sdk.transforms.DoFn;
+import com.google.cloud.dataflow.sdk.transforms.PTransform;
+import com.google.cloud.dataflow.sdk.transforms.ParDo;
+import com.google.cloud.dataflow.sdk.transforms.SerializableComparator;
+import com.google.cloud.dataflow.sdk.transforms.Top;
+import com.google.cloud.dataflow.sdk.transforms.windowing.CalendarWindows;
+import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow;
+import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions;
+import com.google.cloud.dataflow.sdk.transforms.windowing.Window;
+import com.google.cloud.dataflow.sdk.values.KV;
+import com.google.cloud.dataflow.sdk.values.PCollection;
+
+import org.joda.time.Duration;
+import org.joda.time.Instant;
+
+import java.util.List;
+
+/**
+ * Pipeline that reads Wikipedia edit data from BigQuery and computes the user with
+ * the longest string of edits separated by no more than an hour within each month.
+ *
+ *
This pipeline demonstrates how the Windowing API can be used to perform
+ * various time-based aggregations of data.
+ *
+ *
To run this pipeline, the following options must be provided:
+ *
{@code
+ * --project=
+ * --output=gs://
+ *
+ *
To run this example using Dataflow service, you must additionally
+ * provide either {@literal --stagingLocation} or {@literal --tempLocation}, and
+ * select one of the Dataflow pipeline runners, eg
+ * {@literal --runner=BlockingDataflowPipelineRunner}.
+ */
+public class TopWikipediaSessions {
+ private static final String EXPORTED_WIKI_TABLE = "gs://dataflow-samples/wikipedia_edits/*.json";
+
+ /**
+ * Extracts user and timestamp from a TableRow representing a Wikipedia edit
+ */
+ static class ExtractUserAndTimestamp extends DoFn {
+ @Override
+ public void processElement(ProcessContext c) {
+ TableRow row = c.element();
+ int timestamp = (Integer) row.get("timestamp");
+ String userName = (String) row.get("contributor_username");
+ if (userName != null) {
+ // Sets the implicit timestamp field to be used in windowing.
+ c.outputWithTimestamp(userName, new Instant(timestamp * 1000L));
+ }
+ }
+ }
+
+ /**
+ * Computes the number of edits in each user session. A session is defined as
+ * a string of edits where each is separated from the next by less than an hour.
+ */
+ static class ComputeSessions
+ extends PTransform, PCollection>> {
+ @Override
+ public PCollection> apply(PCollection actions) {
+ return actions
+ .apply(Window.into(Sessions.withGapDuration(Duration.standardHours(1))))
+
+ .apply(Count.perElement());
+ }
+ }
+
+ /**
+ * Computes the longest session ending in each month.
+ */
+ private static class TopPerMonth
+ extends PTransform>, PCollection>>> {
+ @Override
+ public PCollection>> apply(PCollection> sessions) {
+ return sessions
+ .apply(Window.>into(CalendarWindows.months(1)))
+
+ .apply(Top.of(1, new SerializableComparator>() {
+ @Override
+ public int compare(KV o1, KV o2) {
+ return Long.compare(o1.getValue(), o2.getValue());
+ }
+ }));
+ }
+ }
+
+ static class ComputeTopSessions extends PTransform, PCollection> {
+ private final double samplingThreshold;
+
+ public ComputeTopSessions(double samplingThreshold) {
+ this.samplingThreshold = samplingThreshold;
+ }
+
+ @Override
+ public PCollection apply(PCollection input) {
+ return input
+ .apply(ParDo.of(new ExtractUserAndTimestamp()))
+
+ .apply(ParDo.named("SampleUsers").of(
+ new DoFn() {
+ @Override
+ public void processElement(ProcessContext c) {
+ if (Math.abs(c.element().hashCode()) <= Integer.MAX_VALUE * samplingThreshold) {
+ c.output(c.element());
+ }
+ }
+ }))
+
+ .apply(new ComputeSessions())
+
+ .apply(ParDo.named("SessionsToStrings").of(
+ new DoFn, KV>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ c.output(KV.of(
+ c.element().getKey() + " : "
+ + c.windows().iterator().next(), c.element().getValue()));
+ }
+ }))
+
+ .apply(new TopPerMonth())
+
+ .apply(ParDo.named("FormatOutput").of(
+ new DoFn>, String>() {
+ @Override
+ public void processElement(ProcessContext c) {
+ for (KV item : c.element()) {
+ String session = item.getKey();
+ long count = item.getValue();
+ c.output(
+ session + " : " + count + " : "
+ + ((IntervalWindow) c.windows().iterator().next()).start());
+ }
+ }
+ }));
+ }
+ }
+
+ /**
+ * Options supported by this class.
+ *
+ *
Inherits standard Dataflow configuration options.
+ */
+ private static interface Options extends PipelineOptions {
+ @Description(
+ "Input specified as a GCS path containing a BigQuery table exported as json")
+ @Default.String(EXPORTED_WIKI_TABLE)
+ String getInput();
+ void setInput(String value);
+
+ @Description("File to output results to")
+ @Validation.Required
+ String getOutput();
+ void setOutput(String value);
+ }
+
+ public static void main(String[] args) {
+ Options options = PipelineOptionsFactory.fromArgs(args)
+ .withValidation()
+ .as(Options.class);
+ DataflowPipelineOptions dataflowOptions = options.as(DataflowPipelineOptions.class);
+
+ Pipeline p = Pipeline.create(dataflowOptions);
+
+ double samplingThreshold = 0.1;
+
+ p.apply(TextIO.Read
+ .from(options.getInput())
+ .withCoder(TableRowJsonCoder.of()))
+ .apply(new ComputeTopSessions(samplingThreshold))
+ .apply(TextIO.Write.named("Write").withoutSharding().to(options.getOutput()));
+
+ p.run();
+ }
+}
diff --git a/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java b/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java
new file mode 100644
index 000000000000..96893b909bc7
--- /dev/null
+++ b/examples/src/main/java/com/google/cloud/dataflow/examples/WordCount.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2014 Google Inc.
+ *
+ * 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.google.cloud.dataflow.examples;
+
+import com.google.cloud.dataflow.sdk.Pipeline;
+import com.google.cloud.dataflow.sdk.io.TextIO;
+import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions;
+import com.google.cloud.dataflow.sdk.options.Default;
+import com.google.cloud.dataflow.sdk.options.DefaultValueFactory;
+import com.google.cloud.dataflow.sdk.options.Description;
+import com.google.cloud.dataflow.sdk.options.PipelineOptions;
+import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
+import com.google.cloud.dataflow.sdk.transforms.Aggregator;
+import com.google.cloud.dataflow.sdk.transforms.Count;
+import com.google.cloud.dataflow.sdk.transforms.DoFn;
+import com.google.cloud.dataflow.sdk.transforms.PTransform;
+import com.google.cloud.dataflow.sdk.transforms.ParDo;
+import com.google.cloud.dataflow.sdk.transforms.Sum;
+import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath;
+import com.google.cloud.dataflow.sdk.values.KV;
+import com.google.cloud.dataflow.sdk.values.PCollection;
+
+/**
+ * An example that counts words in Shakespeare. For a detailed walkthrough of this
+ * example see:
+ * https://developers.google.com/cloud-dataflow/java-sdk/wordcount-example
+ *
+ * To execute this pipeline locally, specify general pipeline configuration:
+ * --project=
+ * and example configuration:
+ * --output=[ | gs://