Skip to content

Commit c2bc743

Browse files
authored
Feat: Adds functions_helloworld_background (GoogleCloudPlatform#1549)
1 parent 60e3495 commit c2bc743

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
// [START functions_helloworld_background]
18+
import com.google.gson.Gson;
19+
import com.google.gson.JsonObject;
20+
import java.io.IOException;
21+
import java.io.PrintWriter;
22+
import java.util.logging.Logger;
23+
import javax.servlet.http.HttpServletRequest;
24+
import javax.servlet.http.HttpServletResponse;
25+
26+
public class HelloBackground {
27+
28+
// Use GSON (https://github.com/google/gson) to parse JSON content.
29+
private Gson gsonParser = new Gson();
30+
31+
// Background Cloud Function.
32+
public void helloBackground(HttpServletRequest request, HttpServletResponse response)
33+
throws IOException {
34+
String contentType = request.getContentType();
35+
String name = "World";
36+
JsonObject body = gsonParser.fromJson(request.getReader(), JsonObject.class);
37+
if (body.has("name")) {
38+
name = body.get("name").getAsString();
39+
}
40+
PrintWriter writer = response.getWriter();
41+
writer.write(String.format("Hello %s!", name));
42+
}
43+
}
44+
45+
// [END functions_helloworld_background]

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,4 +149,14 @@ public void retrieveLogsTest() throws IOException {
149149

150150
assertThat(responseOut.toString(), containsString("Logs retrieved successfully."));
151151
}
152+
153+
@Test
154+
public void helloBackgroundTest() throws IOException {
155+
when(request.getContentType()).thenReturn("application/json");
156+
BufferedReader bodyReader = new BufferedReader(new StringReader("{\"name\":\"John\"}"));
157+
when(request.getReader()).thenReturn(bodyReader);
158+
159+
new HelloBackground().helloBackground(request, response);
160+
assertThat(responseOut.toString(), containsString("Hello John!"));
161+
}
152162
}

0 commit comments

Comments
 (0)