8000 Add missing helloworld samples + delete excess logging code (#2531) · doinotlikeit/java-docs-samples@6af8668 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6af8668

Browse files
author
Ace Nassri
authored
Add missing helloworld samples + delete excess logging code (GoogleCloudPlatform#2531)
* Add missing helloworld (GCS generic, error) samples * Add functions_helloworld_method + rename tests to match DRIFT spec
1 parent 5477a7e commit 6af8668

File tree

5 files changed

+211
-8
lines changed

5 files changed

+211
-8
lines changed

functions/snippets/src/main/java/com/example/functions/GcsEvent.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package com.example.functions;
1818

19+
import java.util.Date;
20+
1921
// [START functions_helloworld_gcs_event]
2022
class GcsEvent {
2123
// Cloud Functions uses GSON to populate this object.
@@ -24,6 +26,8 @@ class GcsEvent {
2426
String bucket;
2527
String name;
2628
String metageneration;
29+
Date timeCreated;
30+
Date updated;
2731

2832
public String getBucket() {
2933
return bucket;
@@ -48,5 +52,21 @@ public String getMetageneration() {
4852
public void setMetageneration(String metageneration) {
4953
this.metageneration = metageneration;
5054
}
55+
56+
public Date getTimeCreated() {
57+
return timeCreated;
58+
}
59+
60+
public void setTimeCreated(Date timeCreated) {
61+
this.timeCreated = timeCreated;
62+
}
63+
64+
public Date getUpdated() {
65+
return updated;
66+
}
67+
68+
public void setUpdated(Date updated) {
69+
this.updated = updated;
70+
}
5171
}
5272
// [END functions_helloworld_gcs_event]
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Copyright 2020 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.functions;
18+
19+
// [START functions_helloworld_error]
20+
21+
import com.google.cloud.functions.HttpFunction;
22+
import com.google.cloud.functions.HttpRequest;
23+
import com.google.cloud.functions.HttpResponse;
24+
import java.io.IOException;
25+
import java.util.logging.Logger;
26+
27+
public class HelloError implements HttpFunction {
28+
29+
private static final Logger LOGGER = Logger.getLogger(HelloError.class.getName());
30+
31+
@Override
32+
public void service(HttpRequest request, HttpResponse response)
33+
throws IOException {
34+
// These will NOT be reported to Stackdriver error reporting
35+
System.err.println("I failed you");
36+
LOGGER.severe("I failed you");
37+
38+
// This WILL be reported to Stackdriver error reporting
39+
throw new RuntimeException("I failed you");
40+
}
41+
}
42+
// [END functions_helloworld_error]
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright 2020 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.functions;
18+
19+
// [START functions_helloworld_storage_generic]
20+
import com.google.cloud.functions.BackgroundFunction;
21+
import com.google.cloud.functions.Context;
22+
import java.util.logging.Logger;
23+
24+
public class HelloGcsGeneric implements BackgroundFunction<GcsEvent> {
25+
private static final Logger LOGGER = Logger.getLogger(HelloGcs.class.getName());
26+
27+
@Override
28+
public void accept(GcsEvent event, Context context) {
29+
LOGGER.info("Event: " + context.eventId());
30+
LOGGER.info("Event Type: " + context.eventType());
31+
LOGGER.info("Bucket: " + event.getBucket());
32+
LOGGER.info("File: " + event.getName());
33+
LOGGER.info("Metageneration: " + event.getMetageneration());
34+
LOGGER.info("Created: " + event.getTimeCreated());
35+
LOGGER.info("Updated: " + event.getUpdated());
36+
}
37+
}
38+
// [END functions_helloworld_storage_generic]
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* Copyright 2020 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.functions;
18+
19+
// [START functions_helloworld_method]
20+
21+
import com.google.cloud.functions.HttpFunction;
22+
import com.google.cloud.functions.HttpRequest;
23+
import com.google.cloud.functions.HttpResponse;
24+
import java.io.BufferedWriter;
25+
import java.io.IOException;
26+
import java.net.HttpURLConnection;
27+
28+
public class HelloMethod implements HttpFunction {
29+
@Override
30+
public void service(HttpRequest request, HttpResponse response)
31+
throws IOException {
32+
33+
BufferedWriter writer = response.getWriter();
34+
35+
switch (request.getMethod()) {
36+
case "GET":
37+
response.setStatusCode(HttpURLConnection.HTTP_OK);
38+
writer.write("Hello world!");
39+
break;
40+
case "PUT":
41+
response.setStatusCode(HttpURLConnection.HTTP_FORBIDDEN);
42+
writer.write("Forbidden!");
43+
break;
44+
default:
45+
response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
46+
writer.write("Something blew up!");
47+
break;
48+
}
49+
}
50+
}
51+
// [END functions_helloworld_method]

functions/snippets/src/test/java/com/example/functions/SnippetsTests.java

Lines changed: 60 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
import static com.google.common.truth.Truth.assertThat;
2020
import static org.mockito.ArgumentMatchers.any;
2121
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
22+
import static org.mockito.Mockito.times;
23+
import static org.mockito.Mockito.verify;
2224
import static org.powermock.api.mockito.PowerMockito.mock;
2325
import static org.powermock.api.mockito.PowerMockito.when;
2426

@@ -35,11 +37,13 @@
3537
import java.io.InputStream;
3638
import java.io.StringReader;
3739
import java.io.StringWriter;
40+
import java.net.HttpURLConnection;
3841
import java.nio.charset.StandardCharsets;
3942
import java.time.Instant;
4043
import java.time.ZoneOffset;
4144
import java.time.ZonedDateTime;
4245
import java.util.Base64;
46+
import java.util.Date;
4347
import java.util.List;
4448
import java.util.Optional;
4549
import java.util.logging.LogRecord;
@@ -74,6 +78,8 @@ public class SnippetsTests {
7478
private static final Logger BACKGROUND_LOGGER = Logger.getLogger(HelloBackground.class.getName());
7579
private static final Logger PUBSUB_LOGGER = Logger.getLogger(HelloPubSub.class.getName());
7680
private static final Logger GCS_LOGGER = Logger.getLogger(HelloGcs.class.getName());
81+
private static final Logger GCS_GENERIC_LOGGER = Logger.getLogger(
82+
HelloGcsGeneric.class.getName());
7783
private static final Logger STACKDRIVER_LOGGER = Logger.getLogger(
7884
StackdriverLogging.class.getName());
7985
private static final Logger RETRY_LOGGER = Logger.getLogger(RetryPubSub.class.getName());
@@ -109,6 +115,7 @@ public static void beforeClass() {
109115
REMOTE_CONFIG_LOGGER.addHandler(logHandler);
110116
AUTH_LOGGER.addHandler(logHandler);
111117
REACTIVE_LOGGER.addHandler(logHandler);
118+
GCS_GENERIC_LOGGER.addHandler(logHandler);
112119
}
113120

114121
@Before
@@ -131,14 +138,6 @@ public void beforeTest() throws IOException {
131138
firestoreMock = mock(Firestore.class);
132139
when(firestoreMock.document(any())).thenReturn(referenceMock);
133140

134-
// Use the same logging handler for all tests
135-
Logger.getLogger(HelloBackground.class.getName()).addHandler(logHandler);
136-
Logger.getLogger(HelloPubSub.class.getName()).addHandler(logHandler);
137-
Logger.getLogger(HelloGcs.class.getName()).addHandler(logHandler);
138-
Logger.getLogger(StackdriverLogging.class.getName()).addHandler(logHandler);
139-
Logger.getLogger(RetryPubSub.class.getName()).addHandler(logHandler);
140-
Logger.getLogger(InfiniteRetryPubSub.class.getName()).addHandler(logHandler);
141-
142141
logHandler.clear();
143142
}
144143

@@ -156,6 +155,26 @@ public void helloWorldTest() throws IOException {
156155
assertThat(responseOut.toString()).contains("Hello World!");
157156
}
158157

158+
@Test
159+
public void functionsHelloworldStorageGeneric_shouldPrintEvent() throws IOException {
160+
GcsEvent event = new GcsEvent();
161+
event.bucket = "some-bucket";
162+
event.name = "some-file.txt";
163+
event.timeCreated = new Date();
164+
event.updated = new Date();
165+
166+
MockContext context = new MockContext();
167+
context.eventType = "google.storage.object.metadataUpdate";
168+
169+
new HelloGcsGeneric().accept(event, context);
170+
171+
List<LogRecord> logs = logHandler.getStoredLogRecords();
172+
assertThat(logs.get(1).getMessage()).isEqualTo(
173+
"Event Type: google.storage.object.metadataUpdate");
174+
assertThat(logs.get(2).getMessage()).isEqualTo("Bucket: some-bucket");
175+
assertThat(logs.get(3).getMessage()).isEqualTo("File: some-file.txt");
176+
}
177+
159178
@Test
160179
public void logHelloWorldTest() throws IOException {
161180
new LogHelloWorld().service(request, response);
@@ -329,6 +348,39 @@ public void helloHttp_bodyParamsPost() throws IOException {
329348
assertThat(responseOut.toString()).isEqualTo("Hello Jane!");
330349
}
331350

351+
@Test
352+
public void functionsHelloworldMethod_shouldAcceptGet() throws IOException {
353+
when(request.getMethod()).thenReturn("GET");
354+
355+
new HelloMethod().service(request, response);
356+
357+
writerOut.flush();
358+
verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_OK);
359+
assertThat(responseOut.toString()).isEqualTo("Hello world!");
360+
}
361+
362+
@Test
363+
public void functionsHelloworldMethod_shouldForbidPut() throws IOException {
364+
when(request.getMethod()).thenReturn("PUT");
365+
366+
new HelloMethod().service(request, response);
367+
368+
writerOut.flush();
369+
verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_FORBIDDEN);
370+
assertThat(responseOut.toString()).isEqualTo("Forbidden!");
371+
}
372+
373+
@Test
374+
public void functionsHelloworldMethod_shouldErrorOnPost() throws IOException {
375+
when(request.getMethod()).thenReturn("POST");
376+
377+
new HelloMethod().service(request, response);
378+
379+
writerOut.flush();
380+
verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
381+
assertThat(responseOut.toString()).isEqualTo("Something blew up!");
382+
}
383+
332384
@Test(expected = RuntimeException.class)
333385
public void retryPubsub_handlesRetryMsg() throws IOException {
334386
String data = "{\"retry\": true}";

0 commit comments

Comments
 (0)
0