Skip to content

Commit 8da84f4

Browse files
authored
Add samples for Google Cloud Functions. (GoogleCloudPlatform#1477)
1 parent 25b3c92 commit 8da84f4

7 files changed

Lines changed: 490 additions & 0 deletions

File tree

‎functions/snippets/pom.xml‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.google.cloud.functions</groupId>
8+
<artifactId>functions-snippets</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<!--
12+
The parent pom defines common style checks and testing strategies for our samples.
13+
Removing or replacing it should not affect the execution of the samples in anyway.
14+
-->
15+
<parent>
16+
<groupId>com.google.cloud.samples</groupId>
17+
<artifactId>shared-configuration</artifactId>
18+
<version>1.0.11</version>
19+
</parent>
20+
21+
<properties>
22+
<maven.compiler.target>11</maven.compiler.target>
23+
<maven.compiler.source>11</maven.compiler.source>
24+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
25+
</properties>
26+
27+
<dependencies>
28+
<dependency>
29+
<groupId>javax.servlet</groupId>
30+
<artifactId>javax.servlet-api</artifactId>
31+
<version>4.0.1</version>
32+
<scope>provided</scope>
33+
</dependency>
34+
35+
<!-- Required to for ParseContentType -->
36+
<dependency>
37+
<groupId>com.google.code.gson</groupId>
38+
<artifactId>gson</artifactId>
39+
<version>2.8.5</version>
40+
</dependency>
41+
42+
<!-- Required to for RetrieveLogs -->
43+
<dependency>
44+
<groupId>com.google.cloud</groupId>
45+
<artifactId>google-cloud-logging</artifactId>
46+
<version>1.78.0</version>
47+
</dependency>
48+
49+
<!-- The following dependencies are only required for testing -->
50+
<dependency>
51+
<groupId>junit</groupId>
52+
<artifactId>junit</artifactId>
53+
<version>4.13-beta-2</version>
54+
<scope>test</scope>
55+
</dependency>
56+
<dependency>
57+
<groupId>org.mockito</groupId>
58+
<artifactId>mockito-core</artifactId>
59+
<version>2.28.2</version>
60+
<scope>test</scope>
61+
</dependency>
62+
63+
</dependencies>
64+
65+
<!-- Required for Java 8 (Alpha) functions in the inline editor -->
66+
<build>
67+
<plugins>
68+
<plugin>
69+
<groupId>org.apache.maven.plugins</groupId>
70+
<artifactId>maven-compiler-plugin</artifactId>
71+
<configuration>
72+
<excludes>
73+
<exclude>.google/</exclude>
74+
</excludes>
75+
</configuration>
76+
</plugin>
77+
</plugins>
78+
</build>
79+
</project>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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_http_cors]
18+
import java.io.IOException;
19+
import java.io.PrintWriter;
20+
import javax.servlet.http.HttpServletRequest;
21+
import javax.servlet.http.HttpServletResponse;
22+
23+
public class CorsEnabled {
24+
// corsEnabled is an example of setting CORS headers.
25+
// For more information about CORS and CORS preflight requests, see
26+
// https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.
27+
public void corsEnabled(HttpServletRequest request, HttpServletResponse response)
28+
throws IOException {
29+
// Set CORS headers for preflight requests
30+
if (request.getMethod().equals("OPTIONS")) {
31+
response.setHeader("Access-Control-Allow-Origin", "*");
32+
response.setHeader("Access-Control-Allow-Methods", "POST");
33+
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
34+
response.setHeader("Access-Control-Max-Age", "3600");
35+
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
36+
return;
37+
}
38+
39+
// Set CORS headers for the main request.
40+
response.setHeader("Access-Control-Allow-Origin", "*");
41+
PrintWriter writer = response.getWriter();
42+
writer.write("CORS headers set successfully!");
43+
}
44+
}
45+
46+
// [END functions_http_cors]
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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_log_helloworld]
18+
import java.io.IOException;
19+
import java.io.PrintWriter;
20+
import java.util.logging.Logger;
21+
import javax.servlet.http.HttpServletRequest;
22+
import javax.servlet.http.HttpServletResponse;
23+
24+
public class LogHelloWorld {
25+
26+
private static final Logger LOGGER = Logger.getLogger(LogHelloWorld.class.getName());
27+
28+
public void logHelloWorld(HttpServletRequest request, HttpServletResponse response)
29+
throws IOException {
30+
LOGGER.info("I am an info log!");
31+
LOGGER.warning("I am a warning log!");
32+
33+
PrintWriter writer = response.getWriter();
34+
writer.write("Messages successfully logged!");
35+
}
36+
}
37+
38+
// [END functions_log_helloworld]
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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_http_content]
18+
19+
import com.google.gson.Gson;
20+
import com.google.gson.JsonObject;
21+
import java.io.IOException;
22+
import java.io.PrintWriter;
23+
import java.util.Base64;
24+
import javax.servlet.http.HttpServletRequest;
25+
import javax.servlet.http.HttpServletResponse;
26+
27+
public class ParseContentType {
28+
29+
// Use GSON (https://github.com/google/gson) to parse JSON content.
30+
private Gson gsonParser = new Gson();
31+
32+
// Responds to an HTTP request using data from the request body parsed according to the
33+
// "content-type" header.
34+
public void parseContentType(HttpServletRequest request, HttpServletResponse response)
35+
throws IOException {
36+
String name;
37+
String contentType = request.getContentType();
38+
if (contentType.equals("application/json")) {
39+
// '{"name":"John"}'
40+
JsonObject body = gsonParser.fromJson(request.getReader(), JsonObject.class);
41+
name = body.get("name").getAsString();
42+
} else if (contentType.equals("application/octet-stream")) {
43+
// 'John', stored in a Buffer
44+
name = new String(Base64.getDecoder().decode(request.getInputStream().readAllBytes()));
45+
} else if (contentType.equals("text/plain")) {
46+
// 'John'
47+
name = request.getReader().readLine();
48+
} else if (contentType.equals("application/x-www-form-urlencoded")) {
49+
// 'name=John' in the body of a POST request (not the URL)
50+
name = request.getParameter("name");
51+
} else {
52+
// Invalid or missing header "Content-Type"
53+
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
54+
return;
55+
}
56+
PrintWriter writer = response.getWriter();
57+
writer.write(String.format("Hello %s!", name));
58+
}
59+
}
60+
61+
// [END functions_http_content]
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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_log_retrieve]
18+
19+
import com.google.cloud.logging.v2.LoggingClient;
20+
import com.google.cloud.logging.v2.LoggingClient.ListLogEntriesPagedResponse;
21+
import com.google.logging.v2.ListLogEntriesRequest;
22+
import com.google.logging.v2.LogEntry;
23+
import java.io.IOException;
24+
import java.io.PrintWriter;
25+
import javax.servlet.http.HttpServletRequest;
26+
import javax.servlet.http.HttpServletResponse;
27+
28+
public class RetrieveLogs {
29+
30+
private LoggingClient client;
31+
32+
// Retrieve the latest Cloud Function log entries
33+
public void retrieveLogs(HttpServletRequest request, HttpServletResponse response)
34+
throws IOException {
35+
// Get the LoggingClient for the function.
36+
client = getClient();
37+
38+
// Construct the request
39+
ListLogEntriesRequest entriesRequest =
40+
ListLogEntriesRequest.newBuilder()
41+
.setPageSize(10)
42+
.setFilter("resource.type=\"cloud_function\"")
43+
.build();
44+
45+
ListLogEntriesPagedResponse entriesResponse = client.listLogEntries(entriesRequest);
46+
47+
PrintWriter writer = response.getWriter();
48+
for (LogEntry entry : entriesResponse.getPage().getValues()) {
49+
writer.println(String.format("%s: %s", entry.getLogName(), entry.getTextPayload()));
50+
}
51+
writer.println("\n\nLogs retrieved successfully.");
52+
}
53+
54+
// Returns a client for interacting with the Logging API. The client is stored in the global scope
55+
// and reused by all requests.
56+
private LoggingClient getClient() throws IOException {
57+
if (client == null) {
58+
client = LoggingClient.create();
59+
}
60+
return client;
61+
}
62+
}
63+
64+
// [END functions_log_retrieve]
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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_concepts_requests]
18+
import java.io.IOException;
19+
import java.io.PrintWriter;
20+
import java.net.URI;
21+
import java.net.http.HttpClient;
22+
import java.net.http.HttpRequest;
23+
import java.net.http.HttpResponse;
24+
import java.net.http.HttpResponse.BodyHandlers;
25+
import java.time.Duration;
26+
import javax.servlet.http.HttpServletRequest;
27+
import javax.servlet.http.HttpServletResponse;
28+
29+
public class SendHttpRequest {
30+
31+
// Create a client with some reasonable defaults. This client can be reused for multiple requests.
32+
private static HttpClient client =
33+
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
34+
35+
public void sendHttpRequest(HttpServletRequest request, HttpServletResponse response)
36+
throws IOException, InterruptedException {
37+
// Create a GET sendHttpRequest to "http://example.com"
38+
String url = "http://example.com";
39+
HttpRequest getRequest = HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
40+
41+
// Send the sendHttpRequest using the client
42+
HttpResponse<String> getResponse = client.send(getRequest, BodyHandlers.ofString());
43+
44+
// Write the results to the output:
45+
PrintWriter writer = response.getWriter();
46+
writer.write(String.format("Received code '%s' from url '%s'.", getResponse.statusCode(), url));
47+
}
48+
}
49+
50+
// [END functions_concepts_requests]

0 commit comments

Comments
 (0)