diff --git a/README.md b/README.md index b15c777bf88d..fcceb4d43cea 100644 --- a/README.md +++ b/README.md @@ -42,17 +42,17 @@ libraryDependencies += "com.google.gcloud" % "gcloud-java" % "0.1.3" Example Applications -------------------- -- [`BigQueryExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/BigQueryExample.java) - A simple command line interface providing some of Cloud BigQuery's functionality +- [`BigQueryExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/BigQueryExample.java) - A simple command line interface providing some of Cloud BigQuery's functionality - Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/BigQueryExample.html). - [`Bookshelf`](https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/bookshelf) - An App Engine app that manages a virtual bookshelf. - This app uses `gcloud-java` to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service. -- [`DatastoreExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DatastoreExample.java) - A simple command line interface for the Cloud Datastore +- [`DatastoreExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) - A simple command line interface for the Cloud Datastore - Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/DatastoreExample.html). -- [`ResourceManagerExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/ResourceManagerExample.java) - A simple command line interface providing some of Cloud Resource Manager's functionality +- [`ResourceManagerExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/ResourceManagerExample.java) - A simple command line interface providing some of Cloud Resource Manager's functionality - Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/ResourceManagerExample.html). - [`SparkDemo`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/managed_vms/sparkjava) - An example of using gcloud-java-datastore from within the SparkJava and App Engine Managed VM frameworks. - Read about how it works on the example's [README page](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/managed_vms/sparkjava#how-does-it-work). -- [`StorageExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java) - A simple command line interface providing some of Cloud Storage's functionality +- [`StorageExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/StorageExample.java) - A simple command line interface providing some of Cloud Storage's functionality - Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/StorageExample.html). Specifying a Project ID @@ -123,15 +123,15 @@ Google Cloud BigQuery (Alpha) Here is a code snippet showing a simple usage example from within Compute/App Engine. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. +Complete source code can be found at +[CreateTableAndLoadData.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/CreateTableAndLoadData.java). ```java import com.google.gcloud.bigquery.BigQuery; import com.google.gcloud.bigquery.BigQueryOptions; import com.google.gcloud.bigquery.Field; +import com.google.gcloud.bigquery.FormatOptions; import com.google.gcloud.bigquery.Job; -import com.google.gcloud.bigquery.JobStatus; -import com.google.gcloud.bigquery.JobInfo; -import com.google.gcloud.bigquery.LoadJobConfiguration; import com.google.gcloud.bigquery.Schema; import com.google.gcloud.bigquery.StandardTableDefinition; import com.google.gcloud.bigquery.Table; @@ -145,19 +145,17 @@ if (table == null) { System.out.println("Creating table " + tableId); Field integerField = Field.of("fieldName", Field.Type.integer()); Schema schema = Schema.of(integerField); - bigquery.create(TableInfo.of(tableId, StandardTableDefinition.of(schema))); + table = bigquery.create(TableInfo.of(tableId, StandardTableDefinition.of(schema))); +} +System.out.println("Loading data into table " + tableId); +Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path"); +while (!loadJob.isDone()) { + Thread.sleep(1000L); +} +if (loadJob.status().error() != null) { + System.out.println("Job completed with errors"); } else { - System.out.println("Loading data into table " + tableId); - LoadJobConfiguration configuration = LoadJobConfiguration.of(tableId, "gs://bucket/path"); - Job loadJob = bigquery.create(JobInfo.of(configuration)); - while (!loadJob.isDone()) { - Thread.sleep(1000L); - } - if (loadJob.status().error() != null) { - System.out.println("Job completed with errors"); - } else { - System.out.println("Job succeeded"); - } + System.out.println("Job succeeded"); } ``` @@ -171,8 +169,32 @@ Google Cloud Datastore #### Preview -Here is a code snippet showing a simple usage example from within Compute/App Engine. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. +Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. + +The first snippet shows how to create a Datastore entity. Complete source code can be found at +[CreateEntity.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/CreateEntity.java). + +```java +import com.google.gcloud.datastore.Datastore; +import com.google.gcloud.datastore.DatastoreOptions; +import com.google.gcloud.datastore.DateTime; +import com.google.gcloud.datastore.Entity; +import com.google.gcloud.datastore.Key; +import com.google.gcloud.datastore.KeyFactory; +Datastore datastore = DatastoreOptions.defaultInstance().service(); +KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); +Key key = keyFactory.newKey("keyName"); +Entity entity = Entity.builder(key) + .set("name", "John Doe") + .set("age", 30) + .set("access_time", DateTime.now()) + .build(); +datastore.put(entity); +``` +The second snippet shows how to update a Datastore entity if it exists. Complete source code can be +found at +[UpdateEntity.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/UpdateEntity.java). ```java import com.google.gcloud.datastore.Datastore; import com.google.gcloud.datastore.DatastoreOptions; @@ -182,17 +204,10 @@ import com.google.gcloud.datastore.Key; import com.google.gcloud.datastore.KeyFactory; Datastore datastore = DatastoreOptions.defaultInstance().service(); -KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND); -Key key = keyFactory.newKey(keyName); +KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); +Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); -if (entity == null) { - entity = Entity.builder(key) - .set("name", "John Do") - .set("age", 30) - .set("access_time", DateTime.now()) - .build(); - datastore.put(entity); -} else { +if (entity != null) { System.out.println("Updating access_time for " + entity.getString("name")); entity = Entity.builder(entity) .set("access_time", DateTime.now()) @@ -210,7 +225,8 @@ Google Cloud Resource Manager (Alpha) #### Preview Here is a code snippet showing a simple usage example. Note that you must supply Google SDK credentials for this service, not other forms of authentication listed in the [Authentication section](#authentication). - +Complete source code can be found at +[UpdateAndListProjects.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/UpdateAndListProjects.java). ```java import com.google.gcloud.resourcemanager.Project; import com.google.gcloud.resourcemanager.ResourceManager; @@ -219,14 +235,15 @@ import com.google.gcloud.resourcemanager.ResourceManagerOptions; import java.util.Iterator; ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); -Project myProject = resourceManager.get("some-project-id"); // Use an existing project's ID -Project newProject = myProject.toBuilder() - .addLabel("launch-status", "in-development") - .build() - .replace(); -System.out.println("Updated the labels of project " + newProject.projectId() - + " to be " + newProject.labels()); -// List all the projects you have permission to view. +Project project = resourceManager.get("some-project-id"); // Use an existing project's ID +if (project != null) { + Project newProject = project.toBuilder() + .addLabel("launch-status", "in-development") + .build() + .replace(); + System.out.println("Updated the labels of project " + newProject.projectId() + + " to be " + newProject.labels()); +} Iterator projectIterator = resourceManager.list().iterateAll(); System.out.println("Projects I can view:"); while (projectIterator.hasNext()) { @@ -244,13 +261,32 @@ Google Cloud Storage #### Preview -Here is a code snippet showing a simple usage example from within Compute/App Engine. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. +Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. + +The first snippet shows how to create a Storage blob. Complete source code can be found at +[CreateBlob.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateBlob.java). ```java import static java.nio.charset.StandardCharsets.UTF_8; import com.google.gcloud.storage.Blob; +import com.google.gcloud.storage.BlobId; import com.google.gcloud.storage.BlobInfo; +import com.google.gcloud.storage.Storage; +import com.google.gcloud.storage.StorageOptions; + +Storage storage = StorageOptions.defaultInstance().service(); +BlobId blobId = BlobId.of("bucket", "blob_name"); +BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); +Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8)); +``` +The second snippet shows how to update a Storage blob if it exists. Complete source code can be +found at +[UpdateBlob.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/UpdateBlob.java). +```java +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.gcloud.storage.Blob; import com.google.gcloud.storage.BlobId; import com.google.gcloud.storage.Storage; import com.google.gcloud.storage.StorageOptions; @@ -261,11 +297,7 @@ import java.nio.channels.WritableByteChannel; Storage storage = StorageOptions.defaultInstance().service(); BlobId blobId = BlobId.of("bucket", "blob_name"); Blob blob = storage.get(blobId); -if (blob == null) { - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); - storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8)); -} else { - System.out.println("Updating content for " + blobId.name()); +if (blob != null) { byte[] prevContent = blob.content(); System.out.println(new String(prevContent, UTF_8)); WritableByteChannel channel = blob.writer(); diff --git a/gcloud-java-bigquery/README.md b/gcloud-java-bigquery/README.md index 1a4e48dfd4fd..f65d57fd6e47 100644 --- a/gcloud-java-bigquery/README.md +++ b/gcloud-java-bigquery/README.md @@ -34,7 +34,7 @@ libraryDependencies += "com.google.gcloud" % "gcloud-java-bigquery" % "0.1.3" Example Application ------------------- -- [`BigQueryExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/BigQueryExample.java) - A simple command line interface providing some of Cloud BigQuery's functionality. +- [`BigQueryExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/BigQueryExample.java) - A simple command line interface providing some of Cloud BigQuery's functionality. Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/BigQueryExample.html). Authentication @@ -200,91 +200,13 @@ while (rowIterator.hasNext()) { ``` #### Complete source code -Here we put together all the code shown above into one program. This program assumes that you are -running on Compute Engine or from your own desktop. To run this example on App Engine, simply move +In +[InsertDataAndQueryTable.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/InsertDataAndQueryTable.java) +we put together all the code shown above into one program. The program assumes that you are +running on Compute Engine or from your own desktop. To run the example on App Engine, simply move the code from the main method to your application's servlet class and change the print statements to display on your webpage. -```java -import com.google.gcloud.bigquery.BigQuery; -import com.google.gcloud.bigquery.BigQueryOptions; -import com.google.gcloud.bigquery.DatasetInfo; -import com.google.gcloud.bigquery.Field; -import com.google.gcloud.bigquery.FieldValue; -import com.google.gcloud.bigquery.InsertAllRequest; -import com.google.gcloud.bigquery.InsertAllResponse; -import com.google.gcloud.bigquery.QueryRequest; -import com.google.gcloud.bigquery.QueryResponse; -import com.google.gcloud.bigquery.Schema; -import com.google.gcloud.bigquery.StandardTableDefinition; -import com.google.gcloud.bigquery.Table; -import com.google.gcloud.bigquery.TableId; -import com.google.gcloud.bigquery.TableInfo; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class GcloudBigQueryExample { - - public static void main(String[] args) throws InterruptedException { - - // Create a service instance - BigQuery bigquery = BigQueryOptions.defaultInstance().service(); - - // Create a dataset - String datasetId = "my_dataset_id"; - bigquery.create(DatasetInfo.builder(datasetId).build()); - - TableId tableId = TableId.of(datasetId, "my_table_id"); - // Table field definition - Field stringField = Field.of("StringField", Field.Type.string()); - // Table schema definition - Schema schema = Schema.of(stringField); - // Create a table - StandardTableDefinition tableDefinition = StandardTableDefinition.of(schema); - Table createdTable = bigquery.create(TableInfo.of(tableId, tableDefinition)); - - // Define rows to insert - Map firstRow = new HashMap<>(); - Map secondRow = new HashMap<>(); - firstRow.put("StringField", "value1"); - secondRow.put("StringField", "value2"); - // Create an insert request - InsertAllRequest insertRequest = InsertAllRequest.builder(tableId) - .addRow(firstRow) - .addRow(secondRow) - .build(); - // Insert rows - InsertAllResponse insertResponse = bigquery.insertAll(insertRequest); - // Check if errors occurred - if (insertResponse.hasErrors()) { - System.out.println("Errors occurred while inserting rows"); - } - - // Create a query request - QueryRequest queryRequest = - QueryRequest.builder("SELECT * FROM my_dataset_id.my_table_id") - .maxWaitTime(60000L) - .maxResults(1000L) - .build(); - // Request query to be executed and wait for results - QueryResponse queryResponse = bigquery.query(queryRequest); - while (!queryResponse.jobCompleted()) { - Thread.sleep(1000L); - queryResponse = bigquery.getQueryResults(queryResponse.jobId()); - } - // Read rows - Iterator> rowIterator = queryResponse.result().iterateAll(); - System.out.println("Table rows:"); - while (rowIterator.hasNext()) { - System.out.println(rowIterator.next()); - } - } -} -``` - Troubleshooting --------------- diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java index 6a54a183eaec..db5e956e0a12 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/package-info.java @@ -17,7 +17,10 @@ /** * A client to Google Cloud BigQuery. * - *

A simple usage example: + *

A simple usage example showing how to create a table if it does not exist and load data into + * it. For the complete source code see + * + * CreateTableAndLoadData.java. *

 {@code
  * BigQuery bigquery = BigQueryOptions.defaultInstance().service();
  * TableId tableId = TableId.of("dataset", "table");
@@ -26,19 +29,17 @@
  *   System.out.println("Creating table " + tableId);
  *   Field integerField = Field.of("fieldName", Field.Type.integer());
  *   Schema schema = Schema.of(integerField);
- *   bigquery.create(TableInfo.of(tableId, StandardTableDefinition.of(schema)));
+ *   table = bigquery.create(TableInfo.of(tableId, StandardTableDefinition.of(schema)));
+ * }
+ * System.out.println("Loading data into table " + tableId);
+ * Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path");
+ * while (!loadJob.isDone()) {
+ *   Thread.sleep(1000L);
+ * }
+ * if (loadJob.status().error() != null) {
+ *   System.out.println("Job completed with errors");
  * } else {
- *   System.out.println("Loading data into table " + tableId);
- *   LoadJobConfiguration configuration = LoadJobConfiguration.of(tableId, "gs://bucket/path");
- *   Job loadJob = bigquery.create(JobInfo.of(configuration));
- *   while (!loadJob.isDone()) {
- *     Thread.sleep(1000L);
- *   }
- *   if (loadJob.status().error() != null) {
- *     System.out.println("Job completed with errors");
- *   } else {
- *     System.out.println("Job succeeded");
- *   }
+ *   System.out.println("Job succeeded");
  * }}
* * @see Google Cloud BigQuery diff --git a/gcloud-java-datastore/README.md b/gcloud-java-datastore/README.md index 7eae00f2ad3f..0f8ca7321fcb 100644 --- a/gcloud-java-datastore/README.md +++ b/gcloud-java-datastore/README.md @@ -34,7 +34,7 @@ libraryDependencies += "com.google.gcloud" % "gcloud-java-datastore" % "0.1.3" Example Application -------------------- -[`DatastoreExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DatastoreExample.java) is a simple command line interface for the Cloud Datastore. Read more about using the application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/DatastoreExample.html). +[`DatastoreExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) is a simple command line interface for the Cloud Datastore. Read more about using the application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/DatastoreExample.html). Authentication -------------- @@ -134,67 +134,12 @@ Cloud Datastore relies on indexing to run queries. Indexing is turned on by defa #### Complete source code -Here we put together all the code shown above into one program. This program assumes that you are running on Compute Engine or from your own desktop. To run this example on App Engine, move this code to your application's servlet class and print the query output to the webpage instead of `System.out`. - -```java -import com.google.gcloud.datastore.Datastore; -import com.google.gcloud.datastore.DatastoreOptions; -import com.google.gcloud.datastore.Entity; -import com.google.gcloud.datastore.Key; -import com.google.gcloud.datastore.KeyFactory; -import com.google.gcloud.datastore.Query; -import com.google.gcloud.datastore.QueryResults; -import com.google.gcloud.datastore.StructuredQuery; -import com.google.gcloud.datastore.StructuredQuery.PropertyFilter; - -public class GcloudDatastoreExample { - - public static void main(String[] args) { - // Create datastore service object. - // By default, credentials are inferred from the runtime environment. - Datastore datastore = DatastoreOptions.defaultInstance().service(); - - // Add an entity to Datastore - KeyFactory keyFactory = datastore.newKeyFactory().kind("Person"); - Key key = keyFactory.newKey("john.doe@gmail.com"); - Entity entity = Entity.builder(key) - .set("name", "John Doe") - .set("age", 51) - .set("favorite_food", "pizza") - .build(); - datastore.put(entity); - - // Get an entity from Datastore - Entity johnEntity = datastore.get(key); - - // Add a couple more entities to make the query results more interesting - Key janeKey = keyFactory.newKey("jane.doe@gmail.com"); - Entity janeEntity = Entity.builder(janeKey) - .set("name", "Jane Doe") - .set("age", 44) - .set("favorite_food", "pizza") - .build(); - Key joeKey = keyFactory.newKey("joe.shmoe@gmail.com"); - Entity joeEntity = Entity.builder(joeKey) - .set("name", "Joe Shmoe") - .set("age", 27) - .set("favorite_food", "sushi") - .build(); - datastore.put(janeEntity, joeEntity); - - // Run a query - Query query = Query.entityQueryBuilder() - .kind("Person") - .filter(PropertyFilter.eq("favorite_food", "pizza")) - .build(); - QueryResults results = datastore.run(query); - while (results.hasNext()) { - Entity currentEntity = results.next(); - System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!"); - } - } -} -``` +In +[AddEntitiesAndRunQuery.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java) +we put together all the code shown above into one program. The program assumes that you are +running on Compute Engine or from your own desktop. To run the example on App Engine, simply move +the code from the main method to your application's servlet class and change the print statements to +display on your webpage. Troubleshooting --------------- diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java index 1404b2817802..fbf468d6458d 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java @@ -17,35 +17,38 @@ /** * A client to the Google Cloud Datastore. * - *

Here's a simple usage example for using gcloud-java from App/Compute Engine: + *

Here's a simple usage example for using gcloud-java from App/Compute Engine. This example + * shows how to create a Datastore entity. For the complete source code see + * + * CreateEntity.java. *

 {@code
  * Datastore datastore = DatastoreOptions.defaultInstance().service();
- * KeyFactory keyFactory = datastore.newKeyFactory().kind(kind);
- * Key key = keyFactory.newKey(keyName);
+ * KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind");
+ * Key key = keyFactory.newKey("keyName");
+ * Entity entity = Entity.builder(key)
+ *     .set("name", "John Doe")
+ *     .set("age", 30)
+ *     .set("access_time", DateTime.now())
+ *     .build();
+ * datastore.put(entity);
+ * } 
+ *

+ * This second example shows how to get and update a Datastore entity if it exists. For the complete + * source code see + * + * UpdateEntity.java. + *

 {@code
+ * Datastore datastore = DatastoreOptions.defaultInstance().service();
+ * KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind");
+ * Key key = keyFactory.newKey("keyName");
  * Entity entity = datastore.get(key);
- * if (entity == null) {
- *   entity = Entity.builder(key)
- *       .set("name", "John Do")
- *       .set("age", LongValue.builder(100).indexed(false).build())
- *       .set("updated", false)
+ * if (entity != null) {
+ *   System.out.println("Updating access_time for " + entity.getString("name"));
+ *   entity = Entity.builder(entity)
+ *       .set("access_time", DateTime.now())
  *       .build();
- *   datastore.put(entity);
- * } else {
- *   boolean updated = entity.getBoolean("updated");
- *   if (!updated) {
- *     String[] name = entity.getString("name").split(" ");
- *     entity = Entity.builder(entity)
- *         .set("name", name[0])
- *         .set("last_name", StringValue.builder(name[1]).indexed(false).build())
- *         .set("updated", true)
- *         .remove("old_property")
- *         .set("new_property", 1.1)
- *         .build();
- *     datastore.update(entity);
- *   }
- * }
- * } 
- * + * datastore.update(entity); + * }} *

When using gcloud-java from outside of App/Compute Engine, you have to specify a * project ID and diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md index 8030d14d09e7..cdd677e8368a 100644 --- a/gcloud-java-examples/README.md +++ b/gcloud-java-examples/README.md @@ -53,39 +53,39 @@ To run examples from your command line: ``` Then you are ready to run the following example: ``` - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.BigQueryExample" -Dexec.args="create dataset new_dataset_id" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.BigQueryExample" -Dexec.args="create table new_dataset_id new_table_id field_name:string" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.BigQueryExample" -Dexec.args="list tables new_dataset_id" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.BigQueryExample" -Dexec.args="load new_dataset_id new_table_id CSV gs://my_bucket/my_csv_file" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.BigQueryExample" -Dexec.args="query 'select * from new_dataset_id.new_table_id'" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="create dataset new_dataset_id" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="create table new_dataset_id new_table_id field_name:string" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="list tables new_dataset_id" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="load new_dataset_id new_table_id CSV gs://my_bucket/my_csv_file" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="query 'select * from new_dataset_id.new_table_id'" ``` * Here's an example run of `DatastoreExample`. Be sure to change the placeholder project ID "your-project-id" with your own project ID. Also note that you have to enable the Google Cloud Datastore API on the [Google Developers Console][developers-console] before running the following commands. ``` - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DatastoreExample" -Dexec.args="your-project-id my_name add my\ comment" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DatastoreExample" -Dexec.args="your-project-id my_name display" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DatastoreExample" -Dexec.args="your-project-id my_name delete" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.datastore.DatastoreExample" -Dexec.args="your-project-id my_name add my\ comment" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.datastore.DatastoreExample" -Dexec.args="your-project-id my_name display" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.datastore.DatastoreExample" -Dexec.args="your-project-id my_name delete" ``` * Here's an example run of `ResourceManagerExample`. Be sure to change the placeholder project ID "your-project-id" with your own globally unique project ID. ``` - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="create your-project-id" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="list" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="get your-project-id" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.resourcemanager.ResourceManagerExample" -Dexec.args="create your-project-id" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.resourcemanager.ResourceManagerExample" -Dexec.args="list" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.resourcemanager.ResourceManagerExample" -Dexec.args="get your-project-id" ``` * Here's an example run of `StorageExample`. Before running the example, go to the [Google Developers Console][developers-console] to ensure that Google Cloud Storage API is enabled and that you have a bucket. Also ensure that you have a test file (`test.txt` is chosen here) to upload to Cloud Storage stored locally on your machine. ``` - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="upload /path/to/test.txt " - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="list " - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="download test.txt" - mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="delete test.txt" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample" -Dexec.args="upload /path/to/test.txt " + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample" -Dexec.args="list " + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample" -Dexec.args="download test.txt" + mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample" -Dexec.args="delete test.txt" ``` Troubleshooting diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/BigQueryExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/BigQueryExample.java similarity index 99% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/BigQueryExample.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/BigQueryExample.java index 7fb7e056d8cc..c8fbe7289f9c 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/BigQueryExample.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/BigQueryExample.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.examples; +package com.google.gcloud.examples.bigquery; import com.google.common.collect.ImmutableMap; import com.google.gcloud.WriteChannel; @@ -63,7 +63,7 @@ *

  • login using gcloud SDK - {@code gcloud auth login}.
  • *
  • compile using maven - {@code mvn compile}
  • *
  • run using maven - - *
    {@code mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.BigQueryExample"
    + * 
    {@code mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample"
      *  -Dexec.args="[]
      *  list datasets |
      *  list tables  |
    diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/CreateTableAndLoadData.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/CreateTableAndLoadData.java
    new file mode 100644
    index 000000000000..857f6b43d013
    --- /dev/null
    +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/CreateTableAndLoadData.java
    @@ -0,0 +1,64 @@
    +/*
    + * Copyright 2016 Google Inc. All Rights Reserved.
    + *
    + * 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.
    + */
    +
    +/*
    + * EDITING INSTRUCTIONS
    + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
    + * the project's READMEs and package-info.java.
    + */
    +
    +package com.google.gcloud.examples.bigquery.snippets;
    +
    +import com.google.gcloud.bigquery.BigQuery;
    +import com.google.gcloud.bigquery.BigQueryOptions;
    +import com.google.gcloud.bigquery.Field;
    +import com.google.gcloud.bigquery.FormatOptions;
    +import com.google.gcloud.bigquery.Job;
    +import com.google.gcloud.bigquery.Schema;
    +import com.google.gcloud.bigquery.StandardTableDefinition;
    +import com.google.gcloud.bigquery.Table;
    +import com.google.gcloud.bigquery.TableId;
    +import com.google.gcloud.bigquery.TableInfo;
    +
    +/**
    + * A snippet for Google Cloud BigQuery showing how to get a BigQuery table or create it if it does
    + * not exist. The snippet also starts a BigQuery job to load data into the table from a Cloud
    + * Storage blob and wait until the job completes.
    + */
    +public class CreateTableAndLoadData {
    +
    +  public static void main(String... args) throws InterruptedException {
    +    BigQuery bigquery = BigQueryOptions.defaultInstance().service();
    +    TableId tableId = TableId.of("dataset", "table");
    +    Table table = bigquery.getTable(tableId);
    +    if (table == null) {
    +      System.out.println("Creating table " + tableId);
    +      Field integerField = Field.of("fieldName", Field.Type.integer());
    +      Schema schema = Schema.of(integerField);
    +      table = bigquery.create(TableInfo.of(tableId, StandardTableDefinition.of(schema)));
    +    }
    +    System.out.println("Loading data into table " + tableId);
    +    Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path");
    +    while (!loadJob.isDone()) {
    +      Thread.sleep(1000L);
    +    }
    +    if (loadJob.status().error() != null) {
    +      System.out.println("Job completed with errors");
    +    } else {
    +      System.out.println("Job succeeded");
    +    }
    +  }
    +}
    diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/InsertDataAndQueryTable.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/InsertDataAndQueryTable.java
    new file mode 100644
    index 000000000000..f421bc832441
    --- /dev/null
    +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/snippets/InsertDataAndQueryTable.java
    @@ -0,0 +1,102 @@
    +/*
    + * Copyright 2016 Google Inc. All Rights Reserved.
    + *
    + * 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.
    + */
    +
    +/*
    + * EDITING INSTRUCTIONS
    + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
    + * the project's READMEs and package-info.java.
    + */
    +
    +package com.google.gcloud.examples.bigquery.snippets;
    +
    +import com.google.gcloud.bigquery.BigQuery;
    +import com.google.gcloud.bigquery.BigQueryOptions;
    +import com.google.gcloud.bigquery.DatasetInfo;
    +import com.google.gcloud.bigquery.Field;
    +import com.google.gcloud.bigquery.FieldValue;
    +import com.google.gcloud.bigquery.InsertAllRequest;
    +import com.google.gcloud.bigquery.InsertAllResponse;
    +import com.google.gcloud.bigquery.QueryRequest;
    +import com.google.gcloud.bigquery.QueryResponse;
    +import com.google.gcloud.bigquery.Schema;
    +import com.google.gcloud.bigquery.StandardTableDefinition;
    +import com.google.gcloud.bigquery.TableId;
    +import com.google.gcloud.bigquery.TableInfo;
    +
    +import java.util.HashMap;
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +/**
    + * A snippet for Google Cloud BigQuery showing how to create a BigQuery dataset and table. Once
    + * created, the snippet streams data into the table and then queries it.
    + */
    +public class InsertDataAndQueryTable {
    +
    +  public static void main(String... args) throws InterruptedException {
    +    // Create a service instance
    +    BigQuery bigquery = BigQueryOptions.defaultInstance().service();
    +
    +    // Create a dataset
    +    String datasetId = "my_dataset_id";
    +    bigquery.create(DatasetInfo.builder(datasetId).build());
    +
    +    TableId tableId = TableId.of(datasetId, "my_table_id");
    +    // Table field definition
    +    Field stringField = Field.of("StringField", Field.Type.string());
    +    // Table schema definition
    +    Schema schema = Schema.of(stringField);
    +    // Create a table
    +    StandardTableDefinition tableDefinition = StandardTableDefinition.of(schema);
    +    bigquery.create(TableInfo.of(tableId, tableDefinition));
    +
    +    // Define rows to insert
    +    Map firstRow = new HashMap<>();
    +    Map secondRow = new HashMap<>();
    +    firstRow.put("StringField", "value1");
    +    secondRow.put("StringField", "value2");
    +    // Create an insert request
    +    InsertAllRequest insertRequest = InsertAllRequest.builder(tableId)
    +        .addRow(firstRow)
    +        .addRow(secondRow)
    +        .build();
    +    // Insert rows
    +    InsertAllResponse insertResponse = bigquery.insertAll(insertRequest);
    +    // Check if errors occurred
    +    if (insertResponse.hasErrors()) {
    +      System.out.println("Errors occurred while inserting rows");
    +    }
    +
    +    // Create a query request
    +    QueryRequest queryRequest = QueryRequest.builder("SELECT * FROM my_dataset_id.my_table_id")
    +        .maxWaitTime(60000L)
    +        .maxResults(1000L)
    +        .build();
    +    // Request query to be executed and wait for results
    +    QueryResponse queryResponse = bigquery.query(queryRequest);
    +    while (!queryResponse.jobCompleted()) {
    +      Thread.sleep(1000L);
    +      queryResponse = bigquery.getQueryResults(queryResponse.jobId());
    +    }
    +    // Read rows
    +    Iterator> rowIterator = queryResponse.result().iterateAll();
    +    System.out.println("Table rows:");
    +    while (rowIterator.hasNext()) {
    +      System.out.println(rowIterator.next());
    +    }
    +  }
    +}
    diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DatastoreExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java
    similarity index 98%
    rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/DatastoreExample.java
    rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java
    index 1e65a018a1fb..cc4331734200 100644
    --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DatastoreExample.java
    +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java
    @@ -14,7 +14,7 @@
      * limitations under the License.
      */
     
    -package com.google.gcloud.examples;
    +package com.google.gcloud.examples.datastore;
     
     import com.google.gcloud.datastore.Datastore;
     import com.google.gcloud.datastore.DatastoreOptions;
    @@ -44,7 +44,7 @@
      * 
  • login using gcloud SDK - {@code gcloud auth login}.
  • *
  • compile using maven - {@code mvn compile}
  • *
  • run using maven - {@code mvn exec:java - * -Dexec.mainClass="com.google.gcloud.examples.DatastoreExample" + * -Dexec.mainClass="com.google.gcloud.examples.datastore.DatastoreExample" * -Dexec.args="[projectId] [user] [delete|display|add comment]"}
  • * */ @@ -67,7 +67,7 @@ private static class DeleteAction implements DatastoreAction { public void run(Transaction tx, Key userKey, String... args) { Entity user = tx.get(userKey); if (user == null) { - System.out.println("Nothing to delete, user does not exists."); + System.out.println("Nothing to delete, user does not exist."); return; } Query query = Query.keyQueryBuilder() diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java new file mode 100644 index 000000000000..f1e844c79b24 --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java @@ -0,0 +1,84 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* + * EDITING INSTRUCTIONS + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in + * the project's READMEs and package-info.java. + */ + +package com.google.gcloud.examples.datastore.snippets; + +import com.google.gcloud.datastore.Datastore; +import com.google.gcloud.datastore.DatastoreOptions; +import com.google.gcloud.datastore.Entity; +import com.google.gcloud.datastore.Key; +import com.google.gcloud.datastore.KeyFactory; +import com.google.gcloud.datastore.Query; +import com.google.gcloud.datastore.QueryResults; +import com.google.gcloud.datastore.StructuredQuery.PropertyFilter; + +/** + * A snippet for Google Cloud Datastore showing how to create and get entities. The snippet also + * shows how to run a query against Datastore. + */ +public class AddEntitiesAndRunQuery { + + public static void main(String... args) { + // Create datastore service object. + // By default, credentials are inferred from the runtime environment. + Datastore datastore = DatastoreOptions.defaultInstance().service(); + + // Add an entity to Datastore + KeyFactory keyFactory = datastore.newKeyFactory().kind("Person"); + Key key = keyFactory.newKey("john.doe@gmail.com"); + Entity entity = Entity.builder(key) + .set("name", "John Doe") + .set("age", 51) + .set("favorite_food", "pizza") + .build(); + datastore.put(entity); + + // Get an entity from Datastore + Entity johnEntity = datastore.get(key); + + // Add a couple more entities to make the query results more interesting + Key janeKey = keyFactory.newKey("jane.doe@gmail.com"); + Entity janeEntity = Entity.builder(janeKey) + .set("name", "Jane Doe") + .set("age", 44) + .set("favorite_food", "pizza") + .build(); + Key joeKey = keyFactory.newKey("joe.shmoe@gmail.com"); + Entity joeEntity = Entity.builder(joeKey) + .set("name", "Joe Shmoe") + .set("age", 27) + .set("favorite_food", "sushi") + .build(); + datastore.put(janeEntity, joeEntity); + + // Run a query + Query query = Query.entityQueryBuilder() + .kind("Person") + .filter(PropertyFilter.eq("favorite_food", "pizza")) + .build(); + QueryResults results = datastore.run(query); + while (results.hasNext()) { + Entity currentEntity = results.next(); + System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!"); + } + } +} diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/CreateEntity.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/CreateEntity.java new file mode 100644 index 000000000000..3981162a2943 --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/CreateEntity.java @@ -0,0 +1,48 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* + * EDITING INSTRUCTIONS + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in + * the project's READMEs and package-info.java. + */ + +package com.google.gcloud.examples.datastore.snippets; + +import com.google.gcloud.datastore.Datastore; +import com.google.gcloud.datastore.DatastoreOptions; +import com.google.gcloud.datastore.DateTime; +import com.google.gcloud.datastore.Entity; +import com.google.gcloud.datastore.Key; +import com.google.gcloud.datastore.KeyFactory; + +/** + * A snippet for Google Cloud Datastore showing how to create an entity. + */ +public class CreateEntity { + + public static void main(String... args) { + Datastore datastore = DatastoreOptions.defaultInstance().service(); + KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); + Key key = keyFactory.newKey("keyName"); + Entity entity = Entity.builder(key) + .set("name", "John Doe") + .set("age", 30) + .set("access_time", DateTime.now()) + .build(); + datastore.put(entity); + } +} diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/UpdateEntity.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/UpdateEntity.java new file mode 100644 index 000000000000..cbc97f0784dd --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/snippets/UpdateEntity.java @@ -0,0 +1,50 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* + * EDITING INSTRUCTIONS + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in + * the project's READMEs and package-info.java. + */ + +package com.google.gcloud.examples.datastore.snippets; + +import com.google.gcloud.datastore.Datastore; +import com.google.gcloud.datastore.DatastoreOptions; +import com.google.gcloud.datastore.DateTime; +import com.google.gcloud.datastore.Entity; +import com.google.gcloud.datastore.Key; +import com.google.gcloud.datastore.KeyFactory; + +/** + * A snippet for Google Cloud Datastore showing how to get an entity and update it if it exists. + */ +public class UpdateEntity { + + public static void main(String... args) { + Datastore datastore = DatastoreOptions.defaultInstance().service(); + KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); + Key key = keyFactory.newKey("keyName"); + Entity entity = datastore.get(key); + if (entity != null) { + System.out.println("Updating access_time for " + entity.getString("name")); + entity = Entity.builder(entity) + .set("access_time", DateTime.now()) + .build(); + datastore.update(entity); + } + } +} diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/ResourceManagerExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/ResourceManagerExample.java similarity index 98% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/ResourceManagerExample.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/ResourceManagerExample.java index 46ff82bfaf12..349c0eebe73d 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/ResourceManagerExample.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/ResourceManagerExample.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.examples; +package com.google.gcloud.examples.resourcemanager; import com.google.common.base.Joiner; import com.google.gcloud.resourcemanager.Project; @@ -36,7 +36,7 @@ *
  • login using gcloud SDK - {@code gcloud auth login}.
  • *
  • compile using maven - {@code mvn compile}
  • *
  • run using maven - {@code mvn exec:java - * -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" + * -Dexec.mainClass="com.google.gcloud.examples.resourcemanager.ResourceManagerExample" * -Dexec.args="[list | [create | delete | get] projectId]"}
  • * */ diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/GetOrCreateProject.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/GetOrCreateProject.java new file mode 100644 index 000000000000..5a298107cc60 --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/GetOrCreateProject.java @@ -0,0 +1,49 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* + * EDITING INSTRUCTIONS + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in + * the project's READMEs and package-info.java. + */ + +package com.google.gcloud.examples.resourcemanager.snippets; + +import com.google.gcloud.resourcemanager.Project; +import com.google.gcloud.resourcemanager.ProjectInfo; +import com.google.gcloud.resourcemanager.ResourceManager; +import com.google.gcloud.resourcemanager.ResourceManagerOptions; + +/** + * A snippet for Google Cloud Resource Manager showing how to create a project if it does not exist. + */ +public class GetOrCreateProject { + + public static void main(String... args) { + // Create Resource Manager service object. + // By default, credentials are inferred from the runtime environment. + ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); + + String projectId = "my-globally-unique-project-id"; // Change to a unique project ID. + // Get a project from the server. + Project project = resourceManager.get(projectId); + if (project == null) { + // Create a project. + project = resourceManager.create(ProjectInfo.builder(projectId).build()); + } + System.out.println("Got project " + project.projectId() + " from the server."); + } +} diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/UpdateAndListProjects.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/UpdateAndListProjects.java new file mode 100644 index 000000000000..b194de0815d5 --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/UpdateAndListProjects.java @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* + * EDITING INSTRUCTIONS + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in + * the project's READMEs and package-info.java. + */ + +package com.google.gcloud.examples.resourcemanager.snippets; + +import com.google.gcloud.resourcemanager.Project; +import com.google.gcloud.resourcemanager.ResourceManager; +import com.google.gcloud.resourcemanager.ResourceManagerOptions; + +import java.util.Iterator; + +/** + * A snippet for Google Cloud Resource Manager showing how to update a project and list all projects + * the user has permission to view. + */ +public class UpdateAndListProjects { + + public static void main(String... args) { + // Create Resource Manager service object + // By default, credentials are inferred from the runtime environment. + ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); + + // Get a project from the server + Project project = resourceManager.get("some-project-id"); // Use an existing project's ID + + // Update a project + if (project != null) { + Project newProject = project.toBuilder() + .addLabel("launch-status", "in-development") + .build() + .replace(); + System.out.println("Updated the labels of project " + newProject.projectId() + + " to be " + newProject.labels()); + } + + // List all the projects you have permission to view. + Iterator projectIterator = resourceManager.list().iterateAll(); + System.out.println("Projects I can view:"); + while (projectIterator.hasNext()) { + System.out.println(projectIterator.next().projectId()); + } + } +} diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/StorageExample.java similarity index 99% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/StorageExample.java index a331543af001..e73cfc427129 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/StorageExample.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.examples; +package com.google.gcloud.examples.storage; import com.google.gcloud.AuthCredentials; import com.google.gcloud.AuthCredentials.ServiceAccountAuthCredentials; @@ -65,7 +65,7 @@ *
  • login using gcloud SDK - {@code gcloud auth login}.
  • *
  • compile using maven - {@code mvn compile}
  • *
  • run using maven - - *
    {@code mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample"
    + * 
    {@code mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample"
      *  -Dexec.args="[]
      *  list [] |
      *  info [ []] |
    diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java
    new file mode 100644
    index 000000000000..435cc90b03d8
    --- /dev/null
    +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java
    @@ -0,0 +1,70 @@
    +/*
    + * Copyright 2016 Google Inc. All Rights Reserved.
    + *
    + * 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.
    + */
    +
    +/*
    + * EDITING INSTRUCTIONS
    + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
    + * the project's READMEs and package-info.java.
    + */
    +
    +package com.google.gcloud.examples.storage.snippets;
    +
    +import static java.nio.charset.StandardCharsets.UTF_8;
    +
    +import com.google.gcloud.storage.Blob;
    +import com.google.gcloud.storage.Bucket;
    +import com.google.gcloud.storage.BucketInfo;
    +import com.google.gcloud.storage.Storage;
    +import com.google.gcloud.storage.StorageOptions;
    +
    +import java.util.Iterator;
    +
    +/**
    + * A snippet for Google Cloud Storage showing how to create a bucket and a blob in it. The snippet
    + * also shows how to get a blob's content, list buckets and list blobs.
    + */
    +public class CreateAndListBucketsAndBlobs {
    +
    +  public static void main(String... args) {
    +    // Create a service object
    +    // Credentials are inferred from the environment.
    +    Storage storage = StorageOptions.defaultInstance().service();
    +
    +    // Create a bucket
    +    String bucketName = "my_unique_bucket"; // Change this to something unique
    +    Bucket bucket = storage.create(BucketInfo.of(bucketName));
    +
    +    // Upload a blob to the newly created bucket
    +    Blob blob = bucket.create("my_blob_name", "a simple blob".getBytes(UTF_8), "text/plain");
    +
    +    // Read the blob content from the server
    +    String blobContent = new String(blob.content(), UTF_8);
    +
    +    // List all your buckets
    +    Iterator bucketIterator = storage.list().iterateAll();
    +    System.out.println("My buckets:");
    +    while (bucketIterator.hasNext()) {
    +      System.out.println(bucketIterator.next());
    +    }
    +
    +    // List the blobs in a particular bucket
    +    Iterator blobIterator = bucket.list().iterateAll();
    +    System.out.println("My blobs:");
    +    while (blobIterator.hasNext()) {
    +      System.out.println(blobIterator.next());
    +    }
    +  }
    +}
    diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateBlob.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateBlob.java
    new file mode 100644
    index 000000000000..2c1304a478ab
    --- /dev/null
    +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateBlob.java
    @@ -0,0 +1,44 @@
    +/*
    + * Copyright 2016 Google Inc. All Rights Reserved.
    + *
    + * 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.
    + */
    +
    +/*
    + * EDITING INSTRUCTIONS
    + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
    + * the project's READMEs and package-info.java.
    + */
    +
    +package com.google.gcloud.examples.storage.snippets;
    +
    +import static java.nio.charset.StandardCharsets.UTF_8;
    +
    +import com.google.gcloud.storage.Blob;
    +import com.google.gcloud.storage.BlobId;
    +import com.google.gcloud.storage.BlobInfo;
    +import com.google.gcloud.storage.Storage;
    +import com.google.gcloud.storage.StorageOptions;
    +
    +/**
    + * A snippet for Google Cloud Storage showing how to create a blob.
    + */
    +public class CreateBlob {
    +
    +  public static void main(String... args) {
    +    Storage storage = StorageOptions.defaultInstance().service();
    +    BlobId blobId = BlobId.of("bucket", "blob_name");
    +    BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build();
    +    Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
    +  }
    +}
    diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/UpdateBlob.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/UpdateBlob.java
    new file mode 100644
    index 000000000000..13290b201787
    --- /dev/null
    +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/UpdateBlob.java
    @@ -0,0 +1,53 @@
    +/*
    + * Copyright 2016 Google Inc. All Rights Reserved.
    + *
    + * 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.
    + */
    +
    +/*
    + * EDITING INSTRUCTIONS
    + * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
    + * the project's READMEs and package-info.java.
    + */
    +
    +package com.google.gcloud.examples.storage.snippets;
    +
    +import static java.nio.charset.StandardCharsets.UTF_8;
    +
    +import com.google.gcloud.storage.Blob;
    +import com.google.gcloud.storage.BlobId;
    +import com.google.gcloud.storage.Storage;
    +import com.google.gcloud.storage.StorageOptions;
    +
    +import java.io.IOException;
    +import java.nio.ByteBuffer;
    +import java.nio.channels.WritableByteChannel;
    +
    +/**
    + * A snippet for Google Cloud Storage showing how to update the blob's content if the blob exists.
    + */
    +public class UpdateBlob {
    +
    +  public static void main(String... args) throws IOException {
    +    Storage storage = StorageOptions.defaultInstance().service();
    +    BlobId blobId = BlobId.of("bucket", "blob_name");
    +    Blob blob = storage.get(blobId);
    +    if (blob != null) {
    +      byte[] prevContent = blob.content();
    +      System.out.println(new String(prevContent, UTF_8));
    +      WritableByteChannel channel = blob.writer();
    +      channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
    +      channel.close();
    +    }
    +  }
    +}
    diff --git a/gcloud-java-resourcemanager/README.md b/gcloud-java-resourcemanager/README.md
    index d9a99e12b7a5..c8db4892ef89 100644
    --- a/gcloud-java-resourcemanager/README.md
    +++ b/gcloud-java-resourcemanager/README.md
    @@ -34,7 +34,7 @@ libraryDependencies += "com.google.gcloud" % "gcloud-java-resourcemanager" % "0.
     
     Example Application
     --------------------
    -[`ResourceManagerExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/ResourceManagerExample.java) is a simple command line interface for the Cloud Resource Manager.  Read more about using the application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/ResourceManagerExample.html).
    +[`ResourceManagerExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/ResourceManagerExample.java) is a simple command line interface for the Cloud Resource Manager.  Read more about using the application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/ResourceManagerExample.html).
     
     Authentication
     --------------
    @@ -70,7 +70,12 @@ You will need to set up the local development environment by [installing the Goo
     You'll need to obtain the `gcloud-java-resourcemanager` library.  See the [Quickstart](#quickstart) section to add `gcloud-java-resourcemanager` as a dependency in your code.
     
     #### Creating an authorized service object
    -To make authenticated requests to Google Cloud Resource Manager, you must create a service object with Google Cloud SDK credentials. You can then make API calls by calling methods on the Resource Manager service object. The simplest way to authenticate is to use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials). These credentials are automatically inferred from your environment, so you only need the following code to create your service object:
    +To make authenticated requests to Google Cloud Resource Manager, you must create a service object
    +with Google Cloud SDK credentials. You can then make API calls by calling methods on the Resource
    +Manager service object. The simplest way to authenticate is to use
    +[Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials).
    +These credentials are automatically inferred from your environment, so you only need the following
    +code to create your service object:
     
     ```java
     import com.google.gcloud.resourcemanager.ResourceManager;
    @@ -79,46 +84,68 @@ import com.google.gcloud.resourcemanager.ResourceManagerOptions;
     ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
     ```
     
    -#### Creating a project
    -All you need to create a project is a globally unique project ID.  You can also optionally attach a non-unique name and labels to your project. Read more about naming guidelines for project IDs, names, and labels [here](https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects). To create a project, add the following import at the top of your file:
    +#### Getting a specific project
    +You can load a project if you know it's project ID and have read permissions to the project.
    +To get a project, add the following import at the top of your file:
     
     ```java
     import com.google.gcloud.resourcemanager.Project;
    -import com.google.gcloud.resourcemanager.ProjectInfo;
     ```
     
    -Then add the following code to create a project (be sure to change `myProjectId` to your own unique project ID).
    +Then use the following code to get the project:
     
     ```java
    -String myProjectId = "my-globally-unique-project-id"; // Change to a unique project ID.
    -Project myProject = resourceManager.create(ProjectInfo.builder(myProjectId).build());
    +String projectId = "my-globally-unique-project-id"; // Change to a unique project ID
    +Project project = resourceManager.get(projectId);
     ```
     
    -Note that the return value from `create` is a `Project` that includes additional read-only information, like creation time, project number, and lifecycle state. Read more about these fields on the [Projects page](https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects). `Project`, a subclass of `ProjectInfo`, adds a layer of service-related functionality over `ProjectInfo`.
    +#### Creating a project
    +All you need to create a project is a globally unique project ID. You can also optionally attach a
    +non-unique name and labels to your project. Read more about naming guidelines for project IDs,
    +names, and labels [here](https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects).
    +To create a project, add the following imports at the top of your file:
     
    -#### Getting a specific project
    -You can load a project if you know it's project ID and have read permissions to the project. For example, to get the project we just created we can do the following:
    +```java
    +import com.google.gcloud.resourcemanager.Project;
    +import com.google.gcloud.resourcemanager.ProjectInfo;
    +```
    +
    +Then add the following code to create a project (be sure to change `projectId` to your own unique
    +project ID).
     
     ```java
    -Project projectFromServer = resourceManager.get(myProjectId);
    +String projectId = "my-globally-unique-project-id"; // Change to a unique project ID
    +Project project = resourceManager.create(ProjectInfo.builder(projectId).build());
     ```
     
    +Note that the return value from `create` is a `Project` that includes additional read-only
    +information, like creation time, project number, and lifecycle state. Read more about these fields
    +on the [Projects page](https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects).
    +`Project`, a subclass of `ProjectInfo`, adds a layer of service-related functionality over
    +`ProjectInfo`.
    +
     #### Editing a project
     To edit a project, create a new `ProjectInfo` object and pass it in to the `Project.replace` method.
    -
    -For example, to add a label for the newly created project to denote that it's launch status is "in development", add the following code:
    +For example, to add a label to a project to denote that it's launch status is "in development", add
    +the following code:
     
     ```java
    -Project newProject = myProject.toBuilder()
    +Project newProject = project.toBuilder()
         .addLabel("launch-status", "in-development")
         .build()
         .replace();
     ```
     
    -Note that the values of the project you pass in to `replace` overwrite the server's values for non-read-only fields, namely `projectName` and `labels`. For example, if you create a project with `projectName` "some-project-name" and subsequently call replace using a `ProjectInfo` object that didn't set the `projectName`, then the server will unset the project's name. The server ignores any attempted changes to the read-only fields `projectNumber`, `lifecycleState`, and `createTime`. The `projectId` cannot change.
    +Note that the values of the project you pass in to `replace` overwrite the server's values for
    +non-read-only fields, namely `projectName` and `labels`. For example, if you create a project with
    +`projectName` "some-project-name" and subsequently call replace using a `ProjectInfo` object that
    +didn't set the `projectName`, then the server will unset the project's name. The server ignores any
    +attempted changes to the read-only fields `projectNumber`, `lifecycleState`, and `createTime`.
    +The `projectId` cannot change.
     
     #### Listing all projects
    -Suppose that we want a list of all projects for which we have read permissions. Add the following import:
    +Suppose that we want a list of all projects for which we have read permissions. Add the following
    +import:
     
     ```java
     import java.util.Iterator;
    @@ -136,48 +163,15 @@ while (projectIterator.hasNext()) {
     
     #### Complete source code
     
    -Here we put together all the code shown above into one program.  This program assumes that you are running from your own desktop and used the Google Cloud SDK to authenticate yourself.
    -
    -```java
    -import com.google.gcloud.resourcemanager.Project;
    -import com.google.gcloud.resourcemanager.ProjectInfo;
    -import com.google.gcloud.resourcemanager.ResourceManager;
    -import com.google.gcloud.resourcemanager.ResourceManagerOptions;
    +We put together all the code shown above into two programs. Both programs assume that you are
    +running from your own desktop and used the Google Cloud SDK to authenticate yourself.
     
    -import java.util.Iterator;
    +The first program creates a project if it does not exist. Complete source code can be found at
    +[GetOrCreateProject.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/GetOrCreateProject.java).
     
    -public class GcloudJavaResourceManagerExample {
    -
    -  public static void main(String[] args) {
    -    // Create Resource Manager service object.
    -    // By default, credentials are inferred from the runtime environment.
    -    ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
    -
    -    // Create a project.
    -    String myProjectId = "my-globally-unique-project-id"; // Change to a unique project ID.
    -    Project myProject = resourceManager.create(ProjectInfo.builder(myProjectId).build());
    -
    -    // Get a project from the server.
    -    Project projectFromServer = resourceManager.get(myProjectId);
    -    System.out.println("Got project " + projectFromServer.projectId() + " from the server.");
    -
    -    // Update a project
    -    Project newProject = myProject.toBuilder()
    -        .addLabel("launch-status", "in-development")
    -        .build()
    -        .replace();
    -    System.out.println("Updated the labels of project " + newProject.projectId()
    -        + " to be " + newProject.labels());
    -
    -    // List all the projects you have permission to view.
    -    Iterator projectIterator = resourceManager.list().iterateAll();
    -    System.out.println("Projects I can view:");
    -    while (projectIterator.hasNext()) {
    -      System.out.println(projectIterator.next().projectId());
    -    }
    -  }
    -}
    -```
    +The second program updates a project if it exists and lists all projects the user has permission to
    +view. Complete source code can be found at
    +[UpdateAndListProjects.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/snippets/UpdateAndListProjects.java).
     
     Java Versions
     -------------
    diff --git a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/package-info.java b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/package-info.java
    index 22a81499eb7a..d1794447e9fb 100644
    --- a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/package-info.java
    +++ b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/package-info.java
    @@ -17,21 +17,40 @@
     /**
      * A client to Google Cloud Resource Manager.
      *
    - * 

    Here's a simple usage example for using gcloud-java-resourcemanager: + *

    Here's a simple usage example for using gcloud-java from App/Compute Engine. This example + * creates a project if it does not exist. For the complete source code see + * + * GetOrCreateProject.java. *

     {@code
      * ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
    - * String myProjectId = "my-globally-unique-project-id"; // Change to a unique project ID.
    - * Project myProject = resourceManager.create(ProjectInfo.builder(myProjectId).build());
    - * Project newProject = myProject.toBuilder()
    - *     .addLabel("launch-status", "in-development")
    - *     .build()
    - *     .replace();
    + * String projectId = "my-globally-unique-project-id"; // Change to a unique project ID.
    + * Project project = resourceManager.get(projectId);
    + * if (project == null) {
    + *   project = resourceManager.create(ProjectInfo.builder(projectId).build());
    + * }
    + * System.out.println("Got project " + project.projectId() + " from the server.");
    + * }
    + *

    + * This second example shows how to update a project if it exists and list all projects the user has + * permission to view. For the complete source code see + * + * UpdateAndListProjects.java. + *

     {@code
    + * ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
    + * Project project = resourceManager.get("some-project-id"); // Use an existing project's ID
    + * if (project != null) {
    + *   Project newProject = project.toBuilder()
    + *       .addLabel("launch-status", "in-development")
    + *       .build()
    + *       .replace();
    + *   System.out.println("Updated the labels of project " + newProject.projectId()
    + *       + " to be " + newProject.labels());
    + * }
      * Iterator projectIterator = resourceManager.list().iterateAll();
      * System.out.println("Projects I can view:");
      * while (projectIterator.hasNext()) {
      *   System.out.println(projectIterator.next().projectId());
      * }}
    - * *

    Remember that you must authenticate using the Google Cloud SDK. See more about * providing * credentials here. diff --git a/gcloud-java-storage/README.md b/gcloud-java-storage/README.md index d1a389919558..71d5f1109577 100644 --- a/gcloud-java-storage/README.md +++ b/gcloud-java-storage/README.md @@ -35,7 +35,7 @@ libraryDependencies += "com.google.gcloud" % "gcloud-java-storage" % "0.1.3" Example Application ------------------- -[`StorageExample`](https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java) is a simple command line interface that provides some of Cloud Storage's functionality. Read more about using the application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/StorageExample.html). +[`StorageExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/StorageExample.java) is a simple command line interface that provides some of Cloud Storage's functionality. Read more about using the application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/StorageExample.html). Authentication -------------- @@ -85,8 +85,6 @@ Add the following imports at the top of your file: import static java.nio.charset.StandardCharsets.UTF_8; import com.google.gcloud.storage.Blob; -import com.google.gcloud.storage.BlobId; -import com.google.gcloud.storage.BlobInfo; import com.google.gcloud.storage.Bucket; import com.google.gcloud.storage.BucketInfo; ``` @@ -103,8 +101,7 @@ Bucket bucket = storage.create(BucketInfo.of(bucketName)); // Upload a blob to the newly created bucket BlobId blobId = BlobId.of(bucketName, "my_blob_name"); Blob blob = storage.create( - BlobInfo.builder(blobId).contentType("text/plain").build(), - "a simple blob".getBytes(UTF_8)); + "my_blob_name", "a simple blob".getBytes(UTF_8), "text/plain"); ``` At this point, you will be able to see your newly created bucket and blob on the Google Developers Console. @@ -113,7 +110,7 @@ At this point, you will be able to see your newly created bucket and blob on the Now that we have content uploaded to the server, we can see how to read data from the server. Add the following line to your program to get back the blob we uploaded. ```java -String blobContent = new String(storage.readAllBytes(blobId), UTF_8); +String blobContent = new String(blob.content(), UTF_8); ``` #### Listing buckets and contents of buckets @@ -134,7 +131,7 @@ while (bucketIterator.hasNext()) { } // List the blobs in a particular bucket -Iterator blobIterator = storage.list(bucketName).iterateAll(); +Iterator blobIterator = bucket.list().iterateAll(); System.out.println("My blobs:"); while (blobIterator.hasNext()) { System.out.println(blobIterator.next()); @@ -143,57 +140,12 @@ while (blobIterator.hasNext()) { #### Complete source code -Here we put together all the code shown above into one program. This program assumes that you are running on Compute Engine or from your own desktop. To run this example on App Engine, simply move the code from the main method to your application's servlet class and change the print statements to display on your webpage. - -```java -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.gcloud.storage.Blob; -import com.google.gcloud.storage.BlobId; -import com.google.gcloud.storage.BlobInfo; -import com.google.gcloud.storage.Bucket; -import com.google.gcloud.storage.BucketInfo; -import com.google.gcloud.storage.Storage; -import com.google.gcloud.storage.StorageOptions; - -import java.util.Iterator; - -public class GcloudStorageExample { - - public static void main(String[] args) { - // Create a service object - // Credentials are inferred from the environment. - Storage storage = StorageOptions.defaultInstance().service(); - - // Create a bucket - String bucketName = "my_unique_bucket"; // Change this to something unique - Bucket bucket = storage.create(BucketInfo.of(bucketName)); - - // Upload a blob to the newly created bucket - BlobId blobId = BlobId.of(bucketName, "my_blob_name"); - Blob blob = storage.create( - BlobInfo.builder(blobId).contentType("text/plain").build(), - "a simple blob".getBytes(UTF_8)); - - // Retrieve a blob from the server - String blobContent = new String(storage.readAllBytes(blobId), UTF_8); - - // List all your buckets - Iterator bucketIterator = storage.list().iterateAll(); - System.out.println("My buckets:"); - while (bucketIterator.hasNext()) { - System.out.println(bucketIterator.next()); - } - - // List the blobs in a particular bucket - Iterator blobIterator = storage.list(bucketName).iterateAll(); - System.out.println("My blobs:"); - while (blobIterator.hasNext()) { - System.out.println(blobIterator.next()); - } - } -} -``` +In +[CreateAndListBucketsAndBlobs.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java) +we put together all the code shown above into one program. The program assumes that you are +running on Compute Engine or from your own desktop. To run the example on App Engine, simply move +the code from the main method to your application's servlet class and change the print statements to +display on your webpage. Troubleshooting --------------- diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/package-info.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/package-info.java index 4609c7034693..181e63b08d0b 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/package-info.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/package-info.java @@ -17,23 +17,32 @@ /** * A client to Google Cloud Storage. * - *

    Here's a simple usage example for using gcloud-java from App/Compute Engine: + *

    Here's a simple usage example for using gcloud-java from App/Compute Engine. This example + * shows how to create a Storage blob. For the complete source code see + * + * CreateBlob.java. + *

     {@code
    + * Storage storage = StorageOptions.defaultInstance().service();
    + * BlobId blobId = BlobId.of("bucket", "blob_name");
    + * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build();
    + * Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
    + * }
    + *

    + * This second example shows how to update the blob's content if the blob exists. For the complete + * source code see + * + * UpdateBlob.java. *

     {@code
      * Storage storage = StorageOptions.defaultInstance().service();
      * BlobId blobId = BlobId.of("bucket", "blob_name");
      * Blob blob = storage.get(blobId);
    - * if (blob == null) {
    - *   BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build();
    - *   storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
    - * } else {
    - *   System.out.println("Updating content for " + blobId.name());
    + * if (blob != null) {
      *   byte[] prevContent = blob.content();
      *   System.out.println(new String(prevContent, UTF_8));
      *   WritableByteChannel channel = blob.writer();
      *   channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
      *   channel.close();
      * }}
    - * *

    When using gcloud-java from outside of App/Compute Engine, you have to specify a * project ID and