Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions functions/http/http-form-data/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
<?xml version="1.0" encoding="UTF-8"?>

<!--
Copyright 2020 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example.cloud.functions</groupId>
<artifactId>functions-http-form-data</artifactId>

<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.0.17</version>
</parent>

<properties>
<powermock.version>2.0.7</powermock.version>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<!-- Disable tests during GCF builds (from parent POM) -->
<!-- You can remove this profile to run tests -->
<!-- when deploying, but we recommend creating -->
<!-- a CI/CD pipeline via Cloud Build instead -->
<profiles>
<profile>
<id>skip_tests_on_gcf</id>
<activation>
<property>
<name>env.NEW_BUILD</name>
</property>
</activation>
<properties>
<skipTests>true</skipTests>
</properties>
</profile>
</profiles>

<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.cloud.functions</groupId>
<artifactId>functions-framework-api</artifactId>
<version>1.0.1</version>
</dependency>

<!-- The following dependencies are only required for testing -->
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>29.0-jre</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>29.0-jre</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<!--
Google Cloud Functions Framework Maven plugin

This plugin allows you to run Cloud Functions Java code
locally. Use the following terminal command to run a
given function locally:

mvn function:run -Drun.functionTarget=your.package.yourFunction
-->
<groupId>com.google.cloud.functions</groupId>
<artifactId>function-maven-plugin</artifactId>
<version>0.9.2</version>
<configuration>
<functionTarget>functions.HttpFormData</functionTarget>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M4</version>
<configuration>
<skipTests>${skipTests}</skipTests>
<reportNameSuffix>sponge_log</reportNameSuffix>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
<plugin> <!-- Required for Java 8 (Alpha) functions in the inline editor -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<excludes>
<exclude>.google/</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package functions;

// [START functions_http_form_data]

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;
import javax.servlet.annotation.MultipartConfig;

@MultipartConfig
public class HttpFormData implements HttpFunction {
private static final Logger LOGGER = Logger.getLogger(HttpFormData.class.getName());

@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {

if (!"POST".equals(request.getMethod())) {
response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
return;
}

// This code will process each file uploaded.
String tempDirectory = System.getProperty("java.io.tmpdir");
for (HttpRequest.HttpPart httpPart : request.getParts().values()) {
String filename = httpPart.getFileName().orElse(null);
if (filename == null) {
continue;
}

LOGGER.info("Processed file: " + filename);

// Note: GCF's temp directory is an in-memory file system
// Thus, any files in it must fit in the instance's memory.
Path filePath = Paths.get(tempDirectory, filename).toAbsolutePath();

// Note: files saved to a GCF instance itself may not persist across executions.
// Persistent files should be stored elsewhere, e.g. a Cloud Storage bucket.
Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

// TODO(developer): process saved files here
Files.delete(filePath);
}

// This code will process other form fields.
for (String fieldName : request.getQueryParameters().keySet()) {
String firstFieldValue = request.getFirstQueryParameter(fieldName).get();

// TODO(developer): process field values here
LOGGER.info(String.format(
"Processed field: %s (value: %s)", fieldName, firstFieldValue));
}
}
}
// [END functions_http_form_data]
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package functions;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.common.testing.TestLogHandler;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;

@RunWith(JUnit4.class)
public class HttpFormDataTest {
@Mock private HttpRequest request;
@Mock private HttpResponse response;

private BufferedWriter writerOut;
private StringWriter responseOut;

private static final Logger LOGGER = Logger.getLogger(HttpFormData.class.getName());
private static final TestLogHandler logHandler = new TestLogHandler();

@BeforeClass
public static void setUp() {
LOGGER.addHandler(logHandler);
}

@Before
public void beforeTest() throws IOException {
Mockito.mockitoSession().initMocks(this);

request = mock(HttpRequest.class);
response = mock(HttpResponse.class);

responseOut = new StringWriter();
writerOut = new BufferedWriter(responseOut);
PowerMockito.when(response.getWriter()).thenReturn(writerOut);

logHandler.clear();
}

@Test
public void functionsHttpMethod_shouldErrorOnGet() throws IOException {
when(request.getMethod()).thenReturn("GET");

new HttpFormData().service(request, response);

writerOut.flush();
verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
}

@Test
public void functionsHttpFormData_shouldSaveFiles() throws IOException {
when(request.getMethod()).thenReturn("POST");

ArrayList<HttpRequest.HttpPart> partsList = new ArrayList<>();

InputStream stream = new ByteArrayInputStream("foo text%n".getBytes(StandardCharsets.UTF_8));

MockHttpPart mockHttpPart = new MockHttpPart();
mockHttpPart.setFileName("foo.txt");
mockHttpPart.setInputStream(stream);
partsList.add(mockHttpPart);

HashMap<String, HttpRequest.HttpPart> httpParts = new HashMap<>();
httpParts.put("mock", mockHttpPart);
when(request.getParts()).thenReturn(httpParts);

new HttpFormData().service(request, response);

assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo(
"Processed file: foo.txt");
}

@Test
public void functionsHttpFormData_shouldProcessFields() throws IOException {
when(request.getMethod()).thenReturn("POST");
when(request.getParts()).thenReturn(new HashMap<>());

HashMap<String, List<String>> queryParams = new HashMap<>();
queryParams.put("foo", Arrays.asList(new String[]{"bar"}));

when(request.getQueryParameters()).thenReturn(queryParams);
when(request.getFirstQueryParameter("foo")).thenReturn(Optional.of("bar"));

new HttpFormData().service(request, response);

assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo(
"Processed field: foo (value: bar)");
}
}
Loading