Skip to content

Commit 7c31b3a

Browse files
committed
Added a test and improved the main sample to handle paged API responses.
1 parent 77c33df commit 7c31b3a

File tree

2 files changed

+129
-39
lines changed

2 files changed

+129
-39
lines changed

logging/src/main/java/ListLogs.java

Lines changed: 68 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,24 @@
1313
* License for the specific language governing permissions and limitations under
1414
* the License.
1515
*/
16-
// [START all]
17-
import java.io.IOException;
18-
import java.io.UnsupportedEncodingException;
19-
import java.net.URLDecoder;
20-
import java.security.GeneralSecurityException;
21-
import java.util.ArrayList;
22-
import java.util.Collections;
23-
import java.util.List;
24-
16+
// [START imports]
2517
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
26-
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
18+
import com.google.api.client.http.HttpTransport;
19+
import com.google.api.client.http.javanet.NetHttpTransport;
20+
import com.google.api.client.json.JsonFactory;
2721
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.client.util.Strings;
2823
import com.google.api.services.logging.Logging;
24+
import com.google.api.services.logging.LoggingScopes;
2925
import com.google.api.services.logging.model.ListLogsResponse;
3026
import com.google.api.services.logging.model.Log;
3127

28+
import java.io.IOException;
29+
import java.net.URLDecoder;
30+
import java.util.Collections;
31+
import java.util.List;
32+
// [END imports]
33+
3234
/**
3335
* Cloud Logging Java API sample that lists the logs available to a project.
3436
* Uses the v1beta3 Cloud Logging API, version 1.20.0 or later.
@@ -37,36 +39,68 @@
3739
public class ListLogs {
3840

3941
private static final List<String> LOGGING_SCOPES = Collections.singletonList(
40-
"https://www.googleapis.com/auth/logging.read");
41-
42+
LoggingScopes.LOGGING_READ);
43+
4244
private static final String APPLICATION_NAME = "ListLogs sample";
4345

44-
/** Returns an authorized Cloud Logging API service client. */
45-
public static Logging getLoggingService() throws GeneralSecurityException,
46-
IOException {
47-
GoogleCredential credential = GoogleCredential.getApplicationDefault()
48-
.createScoped(LOGGING_SCOPES);
49-
Logging service = new Logging.Builder(
50-
GoogleNetHttpTransport.newTrustedTransport(),
51-
JacksonFactory.getDefaultInstance(),
52-
credential).setApplicationName(APPLICATION_NAME).build();
46+
/**
47+
* Returns an authorized Cloud Logging API service client that is usable
48+
* on Google App Engine, Google Compute Engine, workstations with the Google Cloud SDK,
49+
* and other computers if you install service account private credentials.
50+
* See https://cloud.google.com/logging/docs/api/tasks.
51+
*/
52+
// [START auth]
53+
public static Logging getLoggingService() throws IOException {
54+
HttpTransport transport = new NetHttpTransport();
55+
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
56+
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
57+
if (credential.createScopedRequired()) {
58+
credential = credential.createScoped(LOGGING_SCOPES);
59+
}
60+
Logging service = new Logging.Builder(transport, jsonFactory, credential)
61+
.setApplicationName(APPLICATION_NAME).build();
5362
return service;
5463
}
64+
// [END auth]
5565

56-
/** Extract simple log names from URL-encoded resource names. */
57-
public static List<String> getSimpleLogNames(List<Log> logs,
58-
String projectId) throws UnsupportedEncodingException {
59-
final int RESOURCE_PREFIX_LENGTH = ("/projects/" + projectId + "/logs/")
60-
.length();
61-
List<String> logNames = new ArrayList<String>();
62-
for (Log log: logs) {
63-
logNames.add(URLDecoder.decode(log.getName(), "utf-8").substring(
64-
RESOURCE_PREFIX_LENGTH));
65-
}
66-
return logNames;
66+
/**
67+
* Lists the names of the logs visible to a project, which may require fetching multiple
68+
* pages of results from the Cloud Logging API. This method converts log resource names
69+
* ("/projects/PROJECTID/logs/SERVICENAME%2FLOGNAME") to simple log names ("SERVICENAME/LOGNAME").
70+
*
71+
* @param service The logging service client returned by getLoggingService.
72+
* @param projectId The project whose logs are to be listed.
73+
* @throws IOException If the Cloud Logging API fails because, for example, the project ID
74+
* doesn't exist or authorization fails.
75+
* See https://cloud.google.com//logging/docs/api/tasks/#java_sample_code.
76+
*/
77+
// [START listlogs]
78+
private static void listLogs(Logging service, String projectId) throws IOException {
79+
final int pageSize = 3;
80+
final int resourcePrefixLength = ("/projects/" + projectId + "/logs/").length();
81+
String nextPageToken = "";
82+
83+
do {
84+
ListLogsResponse response = service.projects().logs().list(projectId)
85+
.setPageToken(nextPageToken).setPageSize(pageSize).execute();
86+
if (response.isEmpty()) break;
87+
for (Log log: response.getLogs()) {
88+
System.out.println(URLDecoder.decode(
89+
log.getName().substring(resourcePrefixLength), "utf-8"));
90+
}
91+
nextPageToken = response.getNextPageToken();
92+
} while (!Strings.isNullOrEmpty(nextPageToken));
93+
System.out.println("Done.");
6794
}
95+
// [END listlogs]
6896

69-
public static void main(String[] args) throws Exception {
97+
/**
98+
* Demonstrates the Cloud Logging API by listing the logs in a project.
99+
* @param args The project ID.
100+
* @throws IOException if a Cloud Logging API call fails because, say, the project ID is wrong
101+
* or authorization fails.
102+
*/
103+
public static void main(String[] args) throws IOException {
70104
if (args.length != 1) {
71105
System.err.println(String.format("Usage: %s <project-name>",
72106
ListLogs.class.getSimpleName()));
@@ -75,12 +109,7 @@ public static void main(String[] args) throws Exception {
75109

76110
String projectId = args[0];
77111
Logging service = getLoggingService();
78-
ListLogsResponse response = service.projects().logs().list(projectId)
79-
.execute();
80-
System.out.println("RAW: " + response.toPrettyString());
81-
System.out.println("SIMPLE: " +
82-
getSimpleLogNames(response.getLogs(), projectId));
83-
112+
listLogs(service, projectId);
84113
}
85114
}
86115
// [END all]
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
import static com.jcabi.matchers.RegexMatchers.containsPattern;
17+
import static org.junit.Assert.assertEquals;
18+
import static org.junit.Assert.assertThat;
19+
20+
import org.junit.After;
21+
import org.junit.Before;
22+
import org.junit.Test;
23+
24+
import java.io.ByteArrayOutputStream;
25+
import java.io.PrintStream;
26+
27+
/**
28+
* Tests the Cloud Logging sample.
29+
*/
30+
public class ListLogsTest {
31+
private final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
32+
private final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
33+
private static final PrintStream REAL_OUT = System.out;
34+
private static final PrintStream REAL_ERR = System.err;
35+
36+
@Before
37+
public void setUp() {
38+
System.setOut(new PrintStream(stdout));
39+
System.setErr(new PrintStream(stderr));
40+
}
41+
42+
@After
43+
public void tearDown() {
44+
System.setOut(ListLogsTest.REAL_OUT);
45+
System.setErr(ListLogsTest.REAL_ERR);
46+
}
47+
48+
@Test
49+
public void testUsage() throws Exception {
50+
ListLogs.main(new String[] {});
51+
assertEquals("Usage: ListLogs <project-name>\n", stderr.toString());
52+
}
53+
54+
@Test
55+
public void testListLogs() throws Exception {
56+
ListLogs.main(new String[] {"cloud-samples-tests"});
57+
String out = stdout.toString();
58+
// Don't know what logs the test project will have.
59+
assertThat(out, containsPattern("Done\\."));
60+
}
61+
}

0 commit comments

Comments
 (0)