Skip to content

Commit 49c241d

Browse files
committed
Merge pull request #487 from ajkannan/example-app
Create ResourceManagerExample
2 parents 2650901 + 741b106 commit 49c241d

File tree

4 files changed

+255
-9
lines changed

4 files changed

+255
-9
lines changed

gcloud-java-examples/README.md

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ To run examples from your command line:
3333

3434
1. Login using gcloud SDK (`gcloud auth login` in command line)
3535

36-
2. Set your current project using `gcloud config set project PROJECT_ID`
36+
2. Set your current project using `gcloud config set project PROJECT_ID`. This step is not necessary for `ResourceManagerExample`.
3737

3838
3. Compile using Maven (`mvn compile` in command line from your base project directory)
3939

@@ -56,7 +56,16 @@ To run examples from your command line:
5656
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="list <bucket_name>"
5757
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="download <bucket_name> test.txt"
5858
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="delete <bucket_name> test.txt"
59-
```
59+
```
60+
61+
Here's an example run of `ResourceManagerExample`.
62+
63+
Be sure to change the placeholder project ID "my-project-id" with your own globally unique project ID.
64+
```
65+
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="create my-project-id"
66+
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="list"
67+
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="get my-project-id"
68+
```
6069

6170
Troubleshooting
6271
---------------
Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
/*
2+
* Copyright 2015 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.gcloud.examples;
18+
19+
import com.google.common.base.Joiner;
20+
import com.google.gcloud.resourcemanager.ProjectInfo;
21+
import com.google.gcloud.resourcemanager.ResourceManager;
22+
import com.google.gcloud.resourcemanager.ResourceManagerOptions;
23+
24+
import java.util.Arrays;
25+
import java.util.HashMap;
26+
import java.util.Map;
27+
import java.util.Scanner;
28+
29+
/**
30+
* An example of using the Google Cloud Resource Manager.
31+
*
32+
* <p>This example creates, deletes, gets, and lists projects.
33+
*
34+
* <p> Steps needed for running the example:<ol>
35+
* <li>login using gcloud SDK - {@code gcloud auth login}.</li>
36+
* <li>compile using maven - {@code mvn compile}</li>
37+
* <li>run using maven - {@code mvn exec:java
38+
* -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample"
39+
* -Dexec.args="[list | [create | delete | get] projectId]"}</li>
40+
* </ol>
41+
*/
42+
public class ResourceManagerExample {
43+
44+
private static final String DEFAULT_ACTION = "list";
45+
private static final Map<String, ResourceManagerAction> ACTIONS = new HashMap<>();
46+
47+
private interface ResourceManagerAction {
48+
void run(ResourceManager resourceManager, String... args);
49+
50+
String[] getRequiredParams();
51+
52+
String[] getOptionalParams();
53+
}
54+
55+
private static class CreateAction implements ResourceManagerAction {
56+
@Override
57+
public void run(ResourceManager resourceManager, String... args) {
58+
String projectId = args[0];
59+
Map<String, String> labels = new HashMap<>();
60+
for (int i = 1; i < args.length; i += 2) {
61+
if (i + 1 < args.length) {
62+
labels.put(args[i], args[i + 1]);
63+
} else {
64+
labels.put(args[i], "");
65+
}
66+
}
67+
ProjectInfo project =
68+
resourceManager.create(ProjectInfo.builder(projectId).labels(labels).build());
69+
System.out.printf(
70+
"Successfully created project '%s': %s.%n", projectId, projectDetails(project));
71+
}
72+
73+
@Override
74+
public String[] getRequiredParams() {
75+
return new String[] {"project-id"};
76+
}
77+
78+
@Override
79+
public String[] getOptionalParams() {
80+
return new String[] {"label-key-1", "label-value-1", "label-key-2", "label-value-2", "..."};
81+
}
82+
}
83+
84+
private static class DeleteAction implements ResourceManagerAction {
85+
@Override
86+
public void run(ResourceManager resourceManager, String... args) {
87+
String projectId = args[0];
88+
System.out.printf("Going to delete project \"%s\". Are you sure [y/N]: ", projectId);
89+
Scanner scanner = new Scanner(System.in);
90+
if (scanner.nextLine().toLowerCase().equals("y")) {
91+
resourceManager.delete(projectId);
92+
System.out.println("Successfully deleted project " + projectId + ".");
93+
} else {
94+
System.out.println("Will not delete project " + projectId + ".");
95+
}
96+
scanner.close();
97+
}
98+
99+
@Override
100+
public String[] getRequiredParams() {
101+
return new String[] {"project-id"};
102+
}
103+
104+
@Override
105+
public String[] getOptionalParams() {
106+
return new String[] {};
107+
}
108+
}
109+
110+
private static class GetAction implements ResourceManagerAction {
111+
@Override
112+
public void run(ResourceManager resourceManager, String... args) {
113+
String projectId = args[0];
114+
ProjectInfo project = resourceManager.get(projectId);
115+
if (project != null) {
116+
System.out.printf(
117+
"Successfully got project '%s': %s.%n", projectId, projectDetails(project));
118+
} else {
119+
System.out.printf("Could not find project '%s'.%n", projectId);
120+
}
121+
}
122+
123+
@Override
124+
public String[] getRequiredParams() {
125+
return new String[] {"project-id"};
126+
}
127+
128+
@Override
129+
public String[] getOptionalParams() {
130+
return new String[] {};
131+
}
132+
}
133+
134+
private static class ListAction implements ResourceManagerAction {
135+
@Override
136+
public void run(ResourceManager resourceManager, String... args) {
137+
System.out.println("Projects you can view:");
138+
for (ProjectInfo project : resourceManager.list().values()) {
139+
System.out.println(projectDetails(project));
140+
}
141+
}
142+
143+
@Override
144+
public String[] getRequiredParams() {
145+
return new String[] {};
146+
}
147+
148+
@Override
149+
public String[] getOptionalParams() {
150+
return new String[] {};
151+
}
152+
}
153+
154+
static {
155+
ACTIONS.put("create", new CreateAction());
156+
ACTIONS.put("delete", new DeleteAction());
157+
ACTIONS.put("get", new GetAction());
158+
ACTIONS.put("list", new ListAction());
159+
}
160+
161+
private static String projectDetails(ProjectInfo project) {
162+
return new StringBuilder()
163+
.append("{projectId:")
164+
.append(project.projectId())
165+
.append(", projectNumber:")
166+
.append(project.projectNumber())
167+
.append(", createTimeMillis:")
168+
.append(project.createTimeMillis())
169+
.append(", state:")
170+
.append(project.state())
171+
.append(", labels:")
172+
.append(project.labels())
173+
.append("}")
174+
.toString();
175+
}
176+
177+
private static void addUsage(
178+
String actionName, ResourceManagerAction action, StringBuilder usage) {
179+
usage.append(actionName);
180+
Joiner joiner = Joiner.on(" ");
181+
String[] requiredParams = action.getRequiredParams();
182+
String[] optionalParams = action.getOptionalParams();
183+
if (requiredParams.length > 0) {
184+
usage.append(' ');
185+
joiner.appendTo(usage, requiredParams);
186+
}
187+
if (optionalParams.length > 0) {
188+
usage.append(" [");
189+
joiner.appendTo(usage, optionalParams);
190+
usage.append(']');
191+
}
192+
}
193+
194+
public static void main(String... args) {
195+
String actionName = args.length > 0 ? args[0].toLowerCase() : DEFAULT_ACTION;
196+
ResourceManagerAction action = ACTIONS.get(actionName);
197+
if (action == null) {
198+
StringBuilder actionAndParams = new StringBuilder();
199+
for (Map.Entry<String, ResourceManagerAction> entry : ACTIONS.entrySet()) {
200+
addUsage(entry.getKey(), entry.getValue(), actionAndParams);
201+
actionAndParams.append('|');
202+
}
203+
actionAndParams.setLength(actionAndParams.length() - 1);
204+
System.out.printf(
205+
"Usage: %s [%s]%n", ResourceManagerExample.class.getSimpleName(), actionAndParams);
206+
return;
207+
}
208+
209+
// If you want to access a local Resource Manager emulator (after creating and starting the
210+
// LocalResourceManagerHelper), use the following code instead:
211+
// ResourceManager resourceManager = LocalResourceManagerHelper.options().service();
212+
ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
213+
args = args.length > 1 ? Arrays.copyOfRange(args, 1, args.length) : new String[] {};
214+
if (args.length < action.getRequiredParams().length) {
215+
StringBuilder usage = new StringBuilder();
216+
addUsage(actionName, action, usage);
217+
System.out.println("Usage: " + usage);
218+
} else {
219+
action.run(resourceManager, args);
220+
}
221+
}
222+
}

gcloud-java-resourcemanager/README.md

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,10 @@ Java idiomatic client for [Google Cloud Resource Manager] (https://cloud.google.
55

66
[![Build Status](https://travis-ci.org/GoogleCloudPlatform/gcloud-java.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/gcloud-java)
77
[![Coverage Status](https://coveralls.io/repos/GoogleCloudPlatform/gcloud-java/badge.svg?branch=master)](https://coveralls.io/r/GoogleCloudPlatform/gcloud-java?branch=master)
8-
9-
<!-- TODO(ajaykannan): add in the maven shield once the artifact is pushed to maven -->
8+
[![Maven](https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-resourcemanager.svg)]( https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-resourcemanager.svg)
109

1110
- [Homepage] (https://googlecloudplatform.github.io/gcloud-java/)
12-
13-
<!-- TODO(ajaykannan): add in a link to javadocs once the site has been generated with resource manager docs included -->
11+
- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/resourcemanager/package-summary.html)
1412

1513
> Note: This client is a work-in-progress, and may occasionally
1614
> make backwards-incompatible changes.
@@ -34,9 +32,9 @@ If you are using SBT, add this to your dependencies
3432
libraryDependencies += "com.google.gcloud" % "gcloud-java-resourcemanager" % "0.1.0"
3533
```
3634

37-
<!-- TODO(ajaykannan): once the API becomes usable, make an example application
3835
Example Application
39-
-------------------- -->
36+
--------------------
37+
[`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).
4038

4139
Authentication
4240
--------------

gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/package-info.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,24 @@
1616

1717
/**
1818
* A client to Google Cloud Resource Manager.
19-
* //TODO(ajaykannan): add code example
19+
*
20+
* <p>Here's a simple usage example for using gcloud-java-resourcemanager:
21+
* <pre>{@code
22+
* ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
23+
* String myProjectId = "my-globally-unique-project-id"; // Change to a unique project ID.
24+
* ProjectInfo myProject = resourceManager.create(ProjectInfo.builder(myProjectId).build());
25+
* ProjectInfo newProjectInfo = resourceManager.replace(myProject.toBuilder()
26+
* .addLabel("launch-status", "in-development").build());
27+
* Iterator<ProjectInfo> projectIterator = resourceManager.list().iterateAll();
28+
* System.out.println("Projects I can view:");
29+
* while (projectIterator.hasNext()) {
30+
* System.out.println(projectIterator.next().projectId());
31+
* }}</pre>
32+
*
33+
* <p>Remember that you must authenticate using the Google Cloud SDK. See more about
34+
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java#specifying-a-project-id">providing
35+
* credentials here</a>.
36+
*
2037
* @see <a href="https://cloud.google.com/resource-manager/">Google Cloud Resource Manager</a>
2138
*/
2239

0 commit comments

Comments
 (0)