Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge gcloud-java-resourcemanager into master #495

Merged
merged 35 commits into from
Dec 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
4899c27
Create packages for resource manager and outline spi layer.
Nov 2, 2015
3687cb1
Fixes to the ResourceManagerRpc layer, and also add resource manager …
Nov 3, 2015
3892eed
minor changes to ResourceManagerRpc
Nov 3, 2015
a60f7d1
Style updates to ResourceManagerRpc
Nov 3, 2015
c69af1a
add return values to delete, undelete, and setIamPolicy
Nov 3, 2015
249fae8
Remove spi result enums, change 'update/set' terminology to 'replace'
Nov 4, 2015
65a6240
Project, ProjectInfo, Policy, and ResourceId classes added.
Nov 12, 2015
9d6fbff
Fix style, simplify equals methods, fix tests, and add Project javadocs
Nov 17, 2015
e625c20
Add documentation and make resource ID type string
Nov 20, 2015
ebcac0b
Remove Policy and add docs
Nov 24, 2015
d800d1f
Added docs, removed policy-related methods from spi layer, fixed list…
Nov 25, 2015
a770e12
Remove parent and resource ID, add fields options
Nov 25, 2015
24edea2
Add exception handling, add back resource ID, and other cleanup
Nov 27, 2015
940aa92
Add list/get options serialization tests + other small fixes
Nov 30, 2015
57de95a
Add page size and page token options
Nov 30, 2015
e9359a0
fix paging docs
Nov 30, 2015
e6954ae
sync pom version to parent project
Nov 30, 2015
a50d770
Default spi layer implementation
Nov 30, 2015
918ab7b
Fix typo and remove non-retryable error code
Dec 1, 2015
3de4f8f
Initial commit of LocalResourceManagerHelper and tests
Dec 6, 2015
978fe27
Add filtering, make projects map a ConcurrentHashMap, and fix style i…
Dec 8, 2015
a670d21
Make error messages more informative, propagate all server exceptions…
Dec 10, 2015
19aa650
remove checkNotNull calls and minor fixes
Dec 10, 2015
4fdd477
minor fixes
Dec 11, 2015
937fe22
minor fix
Dec 11, 2015
ddf447f
ResourceManagerImpl + docs
Dec 2, 2015
8c12d67
Fix docs and return null if project not found by get.
Dec 16, 2015
a3bbbd2
Minor fixes
Dec 17, 2015
37b5efd
Adding ResourceManagerExample, update docs
Dec 17, 2015
b6bbf67
Include delete action + minor edits
Dec 18, 2015
1e7e152
Add retryable exceptions and fix checkstyle complaints
Dec 18, 2015
0eada88
minor fixes
Dec 18, 2015
ccbf4f4
more checkstyle fixes
Dec 19, 2015
bac6a07
minor fixes
Dec 19, 2015
b5d4bca
Update pom version in resource manager, remove noCredentials from Ser…
Dec 21, 2015
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This client supports the following Google Cloud Platform services:

- [Google Cloud Datastore] (#google-cloud-datastore)
- [Google Cloud Storage] (#google-cloud-storage)
- [Google Cloud Resource Manager] (#google-cloud-resource-manager)

> Note: This client is a work-in-progress, and may occasionally
> make backwards-incompatible changes.
Expand Down Expand Up @@ -182,6 +183,37 @@ if (blob == null) {
}
```

Google Cloud Resource Manager
----------------------

- [API Documentation][resourcemanager-api]
- [Official Documentation][cloud-resourcemanager-docs]

#### 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).

```java
import com.google.gcloud.resourcemanager.ProjectInfo;
import com.google.gcloud.resourcemanager.ResourceManager;
import com.google.gcloud.resourcemanager.ResourceManagerOptions;

import java.util.Iterator;

ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
ProjectInfo myProject = resourceManager.get("some-project-id"); // Use an existing project's ID
ProjectInfo newProjectInfo = resourceManager.replace(myProject.toBuilder()
.addLabel("launch-status", "in-development").build());
System.out.println("Updated the labels of project " + newProjectInfo.projectId()
+ " to be " + newProjectInfo.labels());
// List all the projects you have permission to view.
Iterator<ProjectInfo> projectIterator = resourceManager.list().iterateAll();
System.out.println("Projects I can view:");
while (projectIterator.hasNext()) {
System.out.println(projectIterator.next().projectId());
}
```

Troubleshooting
---------------

Expand Down Expand Up @@ -241,3 +273,6 @@ Apache 2.0 - See [LICENSE] for more information.
[cloud-storage-create-bucket]: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
[cloud-storage-activation]: https://cloud.google.com/storage/docs/signup
[storage-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/storage/package-summary.html

[resourcemanager-api]:http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/resourcemanager/package-summary.html
[cloud-resourcemanager-docs]:https://cloud.google.com/resource-manager/
39 changes: 38 additions & 1 deletion TESTING.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
## gcloud-java tools for testing

This library provides tools to help write tests for code that uses gcloud-java services.
This library provides tools to help write tests for code that uses the following gcloud-java services:

- [Datastore] (#testing-code-that-uses-datastore)
- [Storage] (#testing-code-that-uses-storage)
- [Resource Manager] (#testing-code-that-uses-resource-manager)

### Testing code that uses Datastore

Expand Down Expand Up @@ -65,5 +69,38 @@ Here is an example that clears the bucket created in Step 3 with a timeout of 5
RemoteGcsHelper.forceDelete(storage, bucket, 5, TimeUnit.SECONDS);
```

### Testing code that uses Resource Manager

#### On your machine

You can test against a temporary local Resource Manager by following these steps:

1. Before running your testing code, start the Resource Manager emulator `LocalResourceManagerHelper`. This can be done as follows:

```java
import com.google.gcloud.resourcemanager.testing.LocalResourceManagerHelper;

LocalResourceManagerHelper helper = LocalResourceManagerHelper.create();
helper.start();
```

This will spawn a server thread that listens to `localhost` at an ephemeral port for Resource Manager requests.

2. In your program, create and use a Resource Manager service object whose host is set to `localhost` at the appropriate port. For example:

```java
ResourceManager resourceManager = LocalResourceManagerHelper.options().service();
```

3. Run your tests.

4. Stop the Resource Manager emulator.

```java
helper.stop();
```

This method will block until the server thread has been terminated.


[cloud-platform-storage-authentication]:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts
13 changes: 11 additions & 2 deletions gcloud-java-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ To run examples from your command line:

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

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

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

Expand All @@ -56,7 +56,16 @@ To run examples from your command line:
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="list <bucket_name>"
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="download <bucket_name> test.txt"
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample" -Dexec.args="delete <bucket_name> test.txt"
```
```

Here's an example run of `ResourceManagerExample`.

Be sure to change the placeholder project ID "my-project-id" with your own globally unique project ID.
```
$mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample" -Dexec.args="create my-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 my-project-id"
```

Troubleshooting
---------------
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
/*
* Copyright 2015 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.
*/

package com.google.gcloud.examples;

import com.google.common.base.Joiner;
import com.google.gcloud.resourcemanager.ProjectInfo;
import com.google.gcloud.resourcemanager.ResourceManager;
import com.google.gcloud.resourcemanager.ResourceManagerOptions;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
* An example of using the Google Cloud Resource Manager.
*
* <p>This example creates, deletes, gets, and lists projects.
*
* <p> Steps needed for running the example:<ol>
* <li>login using gcloud SDK - {@code gcloud auth login}.</li>
* <li>compile using maven - {@code mvn compile}</li>
* <li>run using maven - {@code mvn exec:java
* -Dexec.mainClass="com.google.gcloud.examples.ResourceManagerExample"
* -Dexec.args="[list | [create | delete | get] projectId]"}</li>
* </ol>
*/
public class ResourceManagerExample {

private static final String DEFAULT_ACTION = "list";
private static final Map<String, ResourceManagerAction> ACTIONS = new HashMap<>();

private interface ResourceManagerAction {
void run(ResourceManager resourceManager, String... args);

String[] getRequiredParams();

String[] getOptionalParams();
}

private static class CreateAction implements ResourceManagerAction {
@Override
public void run(ResourceManager resourceManager, String... args) {
String projectId = args[0];
Map<String, String> labels = new HashMap<>();
for (int i = 1; i < args.length; i += 2) {
if (i + 1 < args.length) {
labels.put(args[i], args[i + 1]);
} else {
labels.put(args[i], "");
}
}
ProjectInfo project =
resourceManager.create(ProjectInfo.builder(projectId).labels(labels).build());
System.out.printf(
"Successfully created project '%s': %s.%n", projectId, projectDetails(project));
}

@Override
public String[] getRequiredParams() {
return new String[] {"project-id"};
}

@Override
public String[] getOptionalParams() {
return new String[] {"label-key-1", "label-value-1", "label-key-2", "label-value-2", "..."};
}
}

private static class DeleteAction implements ResourceManagerAction {
@Override
public void run(ResourceManager resourceManager, String... args) {
String projectId = args[0];
System.out.printf("Going to delete project \"%s\". Are you sure [y/N]: ", projectId);
Scanner scanner = new Scanner(System.in);
if (scanner.nextLine().toLowerCase().equals("y")) {
resourceManager.delete(projectId);
System.out.println("Successfully deleted project " + projectId + ".");
} else {
System.out.println("Will not delete project " + projectId + ".");
}
scanner.close();
}

@Override
public String[] getRequiredParams() {
return new String[] {"project-id"};
}

@Override
public String[] getOptionalParams() {
return new String[] {};
}
}

private static class GetAction implements ResourceManagerAction {
@Override
public void run(ResourceManager resourceManager, String... args) {
String projectId = args[0];
ProjectInfo project = resourceManager.get(projectId);
if (project != null) {
System.out.printf(
"Successfully got project '%s': %s.%n", projectId, projectDetails(project));
} else {
System.out.printf("Could not find project '%s'.%n", projectId);
}
}

@Override
public String[] getRequiredParams() {
return new String[] {"project-id"};
}

@Override
public String[] getOptionalParams() {
return new String[] {};
}
}

private static class ListAction implements ResourceManagerAction {
@Override
public void run(ResourceManager resourceManager, String... args) {
System.out.println("Projects you can view:");
for (ProjectInfo project : resourceManager.list().values()) {
System.out.println(projectDetails(project));
}
}

@Override
public String[] getRequiredParams() {
return new String[] {};
}

@Override
public String[] getOptionalParams() {
return new String[] {};
}
}

static {
ACTIONS.put("create", new CreateAction());
ACTIONS.put("delete", new DeleteAction());
ACTIONS.put("get", new GetAction());
ACTIONS.put("list", new ListAction());
}

private static String projectDetails(ProjectInfo project) {
return new StringBuilder()
.append("{projectId:")
.append(project.projectId())
.append(", projectNumber:")
.append(project.projectNumber())
.append(", createTimeMillis:")
.append(project.createTimeMillis())
.append(", state:")
.append(project.state())
.append(", labels:")
.append(project.labels())
.append("}")
.toString();
}

private static void addUsage(
String actionName, ResourceManagerAction action, StringBuilder usage) {
usage.append(actionName);
Joiner joiner = Joiner.on(" ");
String[] requiredParams = action.getRequiredParams();
if (requiredParams.length > 0) {
usage.append(' ');
joiner.appendTo(usage, requiredParams);
}
String[] optionalParams = action.getOptionalParams();
if (optionalParams.length > 0) {
usage.append(" [");
joiner.appendTo(usage, optionalParams);
usage.append(']');
}
}

public static void main(String... args) {
String actionName = args.length > 0 ? args[0].toLowerCase() : DEFAULT_ACTION;
ResourceManagerAction action = ACTIONS.get(actionName);
if (action == null) {
StringBuilder actionAndParams = new StringBuilder();
for (Map.Entry<String, ResourceManagerAction> entry : ACTIONS.entrySet()) {
addUsage(entry.getKey(), entry.getValue(), actionAndParams);
actionAndParams.append('|');
}
actionAndParams.setLength(actionAndParams.length() - 1);
System.out.printf(
"Usage: %s [%s]%n", ResourceManagerExample.class.getSimpleName(), actionAndParams);
return;
}

// If you want to access a local Resource Manager emulator (after creating and starting the
// LocalResourceManagerHelper), use the following code instead:
// ResourceManager resourceManager = LocalResourceManagerHelper.options().service();
ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
args = args.length > 1 ? Arrays.copyOfRange(args, 1, args.length) : new String[] {};
if (args.length < action.getRequiredParams().length) {
StringBuilder usage = new StringBuilder();
usage.append("Usage: ");
addUsage(actionName, action, usage);
System.out.println(usage);
} else {
action.run(resourceManager, args);
}
}
}
Loading