Skip to content

Commit 2e24257

Browse files
ouitavonkurtisvg
authored andcommitted
Add list recommendations code sample (GoogleCloudPlatform#1789)
* Add list recommendations code sample * Update recommender/beta/cloud-client/pom.xml Co-Authored-By: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> * Update recommender/beta/cloud-client/pom.xml Co-Authored-By: Kurtis Van Gent <31518063+kurtisvg@users.noreply.github.com> * Address review comments * Add additional comments for location and recommender * Address CL comments
1 parent 78dd559 commit 2e24257

File tree

4 files changed

+279
-0
lines changed

4 files changed

+279
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Getting Started with Recommender and the Google Java API Client library
2+
3+
<a href="https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/java-docs-samples&page=editor&open_in_editor=README.md&cloudshell_working_dir=recommender/beta/cloud-client/">
4+
<img alt="Open in Cloud Shell" src ="http://gstatic.com/cloudssh/images/open-btn.png"></a>
5+
6+
[Cloud Recommender](https://cloud.google.com/recommender/) is a service on Google Cloud that provides
7+
usage recommendations for Cloud products and services. This sample Java
8+
application demonstrates how to access the Recommender API using the
9+
[Google Cloud Client Library for Java](https://github.com/GoogleCloudPlatform/google-cloud-java).
10+
11+
## Quickstart
12+
13+
### Setup
14+
- [Set up a Java Development Environment for Maven](https://cloud.google.com/java/docs/setup).
15+
- [Enable Recommender API](https://cloud.google.com/recommender/docs/enabling) for your project.
16+
- [Authenticate using a service account](https://cloud.google.com/docs/authentication/getting-started).
17+
Create a service account, download a JSON key file, and set the
18+
`GOOGLE_APPLICATION_CREDENTIALS` environment variable.
19+
- Set the `GOOGLE_CLOUD_PROJECT` environment variable to your project ID.
20+
21+
### Build
22+
Build your project with:
23+
```
24+
mvn clean package -DskipTests
25+
```
26+
27+
## Testing
28+
To run the unit tests:
29+
```
30+
mvn clean verify
31+
```

recommender/beta/cloud-client/pom.xml

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
<!--
2+
Copyright 2019 Google LLC
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
-->
13+
<project>
14+
<modelVersion>4.0.0</modelVersion>
15+
<groupId>com.example.recommender</groupId>
16+
<artifactId>recommender-samples</artifactId>
17+
<packaging>jar</packaging>
18+
19+
<!--
20+
The parent pom defines common style checks and testing strategies for our samples.
21+
Removing or replacing it should not affect the execution of the samples in anyway.
22+
-->
23+
<parent>
24+
<groupId>com.google.cloud.samples</groupId>
25+
<artifactId>shared-configuration</artifactId>
26+
<version>1.0.11</version>
27+
</parent>
28+
29+
<properties>
30+
<maven.compiler.target>1.8</maven.compiler.target>
31+
<maven.compiler.source>1.8</maven.compiler.source>
32+
</properties>
33+
34+
<!-- [START recommender_java_dependencies] -->
35+
<!-- Using libraries-bom to manage versions.
36+
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
37+
<dependencyManagement>
38+
<dependencies>
39+
<dependency>
40+
<groupId>com.google.cloud</groupId>
41+
<artifactId>libraries-bom</artifactId>
42+
<version>3.0.0</version>
43+
<type>pom</type>
44+
<scope>import</scope>
45+
</dependency>
46+
</dependencies>
47+
</dependencyManagement>
48+
49+
<dependencies>
50+
<dependency>
51+
<groupId>com.google.cloud</groupId>
52+
<artifactId>google-cloud-recommender</artifactId>
53+
<version>0.1.2</version>
54+
</dependency>
55+
<!-- [END recommender_java_dependencies] -->
56+
57+
<!-- Test dependencies -->
58+
<dependency>
59+
<groupId>junit</groupId>
60+
<artifactId>junit</artifactId>
61+
<version>4.12</version>
62+
<scope>test</scope>
63+
</dependency>
64+
<dependency>
65+
<groupId>com.google.truth</groupId>
66+
<artifactId>truth</artifactId>
67+
<version>1.0</version>
68+
<scope>test</scope>
69+
</dependency>
70+
<!-- [START recommender_java_dependencies] -->
71+
</dependencies>
72+
<!-- [END recommender_java_dependencies] -->
73+
74+
<build>
75+
<plugins>
76+
<plugin>
77+
<groupId>org.codehaus.mojo</groupId>
78+
<artifactId>exec-maven-plugin</artifactId>
79+
<version>1.6.0</version>
80+
<configuration>
81+
<cleanupDaemonThreads>false</cleanupDaemonThreads>
82+
</configuration>
83+
</plugin>
84+
</plugins>
85+
</build>
86+
</project>
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/*
2+
* Copyright 2019 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.recommender;
18+
19+
// [START recommender_list_recommendations]
20+
21+
import com.google.api.gax.rpc.InvalidArgumentException;
22+
import com.google.api.gax.rpc.PermissionDeniedException;
23+
import com.google.cloud.recommender.v1beta1.ListRecommendationsRequest;
24+
import com.google.cloud.recommender.v1beta1.Recommendation;
25+
import com.google.cloud.recommender.v1beta1.RecommenderClient;
26+
import com.google.cloud.recommender.v1beta1.RecommenderClient.ListRecommendationsPagedResponse;
27+
import java.io.IOException;
28+
29+
public class ListRecommendations {
30+
31+
// List IAM recommendations for GOOGLE_CLOUD_PROJECT environment variable
32+
public static void listRecommendations() throws IOException {
33+
// TODO(developer): Replace the projectId variable before running the sample.
34+
String projectId = "my-project-id";
35+
36+
// Google Cloud location where resources associated with the recommendations are located (for
37+
// example, "global" or "us-central1-a"). For a full list of supported regions, visit
38+
// https://cloud.google.com/compute/docs/regions-zones/
39+
String location = "global";
40+
41+
// Fully-qualified recommender ID (for example, "google.iam.policy.Recommender" or
42+
// "google.compute.instance.MachineTypeRecommender"). For a full list of supported recommenders
43+
// visit https://cloud.google.com/recommender/docs/recommenders#recommenders
44+
String recommender = "google.iam.policy.Recommender";
45+
46+
listRecommendations(projectId, location, recommender);
47+
}
48+
49+
// List recommendations for a specified project, location, and recommender
50+
public static void listRecommendations(String projectId, String location, String recommender)
51+
throws IOException {
52+
// Initialize client that will be used to send requests. This client only needs to be created
53+
// once, and can be reused for multiple requests. After completing all of your requests, call
54+
// the "close" method on the client to safely clean up any remaining background resources.
55+
try (RecommenderClient recommenderClient = RecommenderClient.create()) {
56+
/// Build the request
57+
String parent =
58+
String.format(
59+
"projects/%s/locations/%s/recommenders/%s", projectId, location, recommender);
60+
ListRecommendationsRequest request =
61+
ListRecommendationsRequest.newBuilder().setParent(parent).build();
62+
63+
try {
64+
// Send the request
65+
ListRecommendationsPagedResponse response = recommenderClient.listRecommendations(request);
66+
67+
// Print out each recommendation
68+
for (Recommendation responseItem : response.iterateAll()) {
69+
Recommendation recommendation = responseItem;
70+
System.out.println("Recommendation name: " + recommendation.getName());
71+
System.out.println("- description: " + recommendation.getDescription());
72+
System.out.println(
73+
"- primary_impact.category: " + recommendation.getPrimaryImpact().getCategory());
74+
System.out.println("- state_info.state: " + recommendation.getStateInfo().getState());
75+
System.out.println();
76+
}
77+
78+
// Indicate the request was successful
79+
System.out.println("List recommendations successful");
80+
} catch (PermissionDeniedException e) {
81+
System.out.println("Permission denied for project '" + projectId
82+
+ "'. Ensure you have the appropriate permissions to list recommendations: \n" + e
83+
.toString());
84+
} catch (InvalidArgumentException e) {
85+
System.out.println(
86+
("Invalid argument for projectId. Ensure you have 'GOOGLE_CLOUD_PROJECT' set: \n"
87+
+ e.toString()));
88+
}
89+
}
90+
}
91+
}
92+
// [END recommender_list_recommendations]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* Copyright 2019 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.recommender;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
21+
22+
import java.io.ByteArrayOutputStream;
23+
import java.io.IOException;
24+
import java.io.PrintStream;
25+
import org.junit.After;
26+
import org.junit.Before;
27+
import org.junit.BeforeClass;
28+
import org.junit.Test;
29+
30+
public class ListRecommendationsTest {
31+
32+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
33+
private static final String LOCATION = "global";
34+
private static final String RECOMMENDER = "google.iam.policy.Recommender";
35+
36+
private ByteArrayOutputStream bout;
37+
private PrintStream out;
38+
39+
private static void requireEnvVar(String varName) {
40+
assertNotNull(
41+
System.getenv(varName),
42+
"Environment variable '%s' is required to perform these tests.".format(varName)
43+
);
44+
}
45+
46+
@BeforeClass
47+
public static void checkRequirements() {
48+
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
49+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
50+
}
51+
52+
@Before
53+
public void setUp() throws Exception {
54+
bout = new ByteArrayOutputStream();
55+
out = new PrintStream(bout);
56+
System.setOut(out);
57+
}
58+
59+
@After
60+
public void tearDown() {
61+
System.setOut(null);
62+
}
63+
64+
@Test
65+
public void listRecommendations() throws IOException {
66+
ListRecommendations.listRecommendations(PROJECT_ID, LOCATION, RECOMMENDER);
67+
68+
assertThat(bout.toString()).contains("List recommendations successful");
69+
}
70+
}

0 commit comments

Comments
 (0)