Skip to content

fix: add runtime hints for storage #2001

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@
<profile>
<id>spring-native</id>
<modules>
<module>spring-cloud-gcp-storage</module>
<module>spring-cloud-gcp-vision</module>
</modules>

Expand Down Expand Up @@ -380,6 +381,7 @@
<classesDirectory>${project.build.outputDirectory}</classesDirectory>
<systemPropertyVariables>
<!--integration tests are not invoked unless the relevant system property is set to true here. -->
<it.storage>true</it.storage>
<it.vision>true</it.vision>
</systemPropertyVariables>
</configuration>
Expand Down
9 changes: 8 additions & 1 deletion spring-cloud-gcp-samples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@
<id>native-sample-config</id>
<modules>
<module>spring-cloud-gcp-logging-sample</module>
<module>spring-cloud-gcp-storage-resource-sample</module>
<module>spring-cloud-gcp-integration-storage-sample</module>
<module>spring-cloud-gcp-vision-api-sample</module>
</modules>
<build>
Expand Down Expand Up @@ -133,7 +135,12 @@
</includes>
<systemPropertyVariables>
<it.logging>true</it.logging>
<it.vision>true</it.vision>
<it.storage>true</it.storage>
<it.vision>true</it.vision>
<gcs-resource-test-bucket>gcp-storage-resource-bucket-sample</gcs-resource-test-bucket>
<gcs-read-bucket>gcp-storage-bucket-sample-input</gcs-read-bucket>
<gcs-write-bucket>gcp-storage-bucket-sample-output</gcs-write-bucket>
<gcs-local-directory>/tmp/gcp_integration_tests/integration_storage_sample</gcs-local-directory>
</systemPropertyVariables>
</configuration>
</plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.awaitility.Awaitility;
Expand Down Expand Up @@ -57,8 +58,6 @@
@SpringBootTest(classes = {GcsSpringIntegrationApplication.class})
class GcsSpringIntegrationTests {

private static final String TEST_FILE_NAME = "test_file";

@Autowired private Storage storage;

@Value("${gcs-read-bucket}")
Expand All @@ -83,15 +82,16 @@ void teardownTestEnvironment() throws IOException {

@Test
void testFilePropagatedToLocalDirectory() {
BlobId blobId = BlobId.of(this.cloudInputBucket, TEST_FILE_NAME);
String testFileName = String.format("test_file_%s", UUID.randomUUID());
BlobId blobId = BlobId.of(this.cloudInputBucket, testFileName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
this.storage.create(blobInfo, "Hello World!".getBytes(StandardCharsets.UTF_8));

Awaitility.await()
.atMost(15, TimeUnit.SECONDS)
.untilAsserted(
() -> {
Path outputFile = Paths.get(this.outputFolder + "/" + TEST_FILE_NAME);
Path outputFile = Paths.get(this.outputFolder + "/" + testFileName);
assertThat(Files.exists(outputFile)).isTrue();
assertThat(Files.isRegularFile(outputFile)).isTrue();

Expand All @@ -104,7 +104,7 @@ void testFilePropagatedToLocalDirectory() {
.iterateAll()
.forEach(b -> blobNamesInOutputBucket.add(b.getName()));

assertThat(blobNamesInOutputBucket).contains(TEST_FILE_NAME);
assertThat(blobNamesInOutputBucket).contains(testFileName);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/**
* An example Spring Boot application that reads and writes files stored in Google Cloud Storage
* (GCS) using the Spring Resource abstraction and the gs: protocol prefix.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,20 @@

package com.example;

import com.google.cloud.spring.storage.GoogleStorageResource;
import com.google.cloud.storage.Storage;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
Expand All @@ -35,17 +39,45 @@
@RestController
public class WebController {

@Value("${gcs-resource-test-bucket}")
private String bucketName;

@Value("gs://${gcs-resource-test-bucket}/my-file.txt")
private Resource gcsFile;

@GetMapping("/")
public String readGcsFile() throws IOException {
private Storage storage;

private WebController(Storage storage) {
this.storage = storage;
}

@GetMapping(value = "/")
public String readGcsFile(@RequestParam("filename") Optional<String> fileName)
throws IOException {
if (fileName.isPresent()) {
GoogleStorageResource resource =
new GoogleStorageResource(
this.storage, String.format("gs://%s/%s", bucketName, fileName.get()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider a private Resource getResource(Optional<String> filename) function to reduce the duplication in this method and writeGcs.

  @GetMapping(value = "/")
  public String readGcsFile(@RequestParam("filename") Optional<String> fileName)
      throws IOException {
    Resource resource = getResource(fileName);
    return StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()) + "\n";
  }

return StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()) + "\n";
}
return StreamUtils.copyToString(this.gcsFile.getInputStream(), Charset.defaultCharset()) + "\n";
}

@PostMapping("/")
public String writeGcs(@RequestBody String data) throws IOException {
try (OutputStream os = ((WritableResource) this.gcsFile).getOutputStream()) {
@PostMapping(value = "/")
public String writeGcs(
@RequestBody String data, @RequestParam("filename") Optional<String> fileName)
throws IOException {
if (fileName.isPresent()) {
GoogleStorageResource resource =
new GoogleStorageResource(
this.storage, String.format("gs://%s/%s", bucketName, fileName.get()));
return updateResource(resource, data);
}
return updateResource(this.gcsFile, data);
}

private String updateResource(Resource resource, String data) throws IOException {
try (OutputStream os = ((WritableResource) resource).getOutputStream()) {
os.write(data.getBytes());
}
return "file was updated\n";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
Expand All @@ -36,7 +37,9 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.util.UriComponentsBuilder;

/**
* This verifies the sample application for using GCP Storage with Spring Resource abstractions.
Expand All @@ -58,6 +61,15 @@ class GcsSampleApplicationIntegrationTests {
@Value("${gcs-resource-test-bucket}")
private String bucketName;

@LocalServerPort private int port;

private String appUrl;

@BeforeEach
void initializeAppUrl() {
this.appUrl = "http://localhost:" + this.port;
}

@BeforeEach
@AfterEach
void cleanupCloudStorage() {
Expand All @@ -69,24 +81,35 @@ void cleanupCloudStorage() {

@Test
void testGcsResourceIsLoaded() {
BlobId blobId = BlobId.of(this.bucketName, "my-file.txt");
String fileName = String.format("file-%s.txt", UUID.randomUUID());
BlobId blobId = BlobId.of(this.bucketName, fileName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
this.storage.create(blobInfo, "Good Morning!".getBytes(StandardCharsets.UTF_8));

// Verify contents of uploaded file .
String getUrl =
UriComponentsBuilder.fromHttpUrl(this.appUrl + "/")
.queryParam("filename", fileName)
.toUriString();
Awaitility.await()
.atMost(15, TimeUnit.SECONDS)
.untilAsserted(
() -> {
String result = this.testRestTemplate.getForObject("/", String.class);
String result = this.testRestTemplate.getForObject(getUrl, String.class);
assertThat(result).isEqualTo("Good Morning!\n");
});

this.testRestTemplate.postForObject("/", "Good Night!", String.class);
// Update contents of uploaded file and verify.
String postUrl =
UriComponentsBuilder.fromHttpUrl(this.appUrl + "/")
.queryParam("filename", fileName)
.toUriString();
this.testRestTemplate.postForObject(postUrl, "Good Night!", String.class);
Awaitility.await()
.atMost(15, TimeUnit.SECONDS)
.untilAsserted(
() -> {
String result = this.testRestTemplate.getForObject("/", String.class);
String result = this.testRestTemplate.getForObject(getUrl, String.class);
assertThat(result).isEqualTo("Good Night!\n");
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2023 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
*
* https://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 com.google.cloud.spring.storage.integration.aot;

import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;

public class StorageIntegrationRuntimeHint implements RuntimeHintsRegistrar {

@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(TypeReference.of("com.google.cloud.storage.Blob[]"),
MemberCategory.DECLARED_CLASSES);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
org.springframework.aot.hint.RuntimeHintsRegistrar=\
com.google.cloud.spring.storage.integration.aot.StorageIntegrationRuntimeHint
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.google.cloud.spring.storage.integration.aot;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.aot.hint.predicate.RuntimeHintsPredicates.reflection;

import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;


class StorageIntegrationRuntimeHintTest {
@Test
void shouldRegisterHints() {
RuntimeHints hints = new RuntimeHints();
new StorageIntegrationRuntimeHint().registerHints(hints, getClass().getClassLoader());

assertThat(hints)
.matches(reflection().onType(TypeReference.of("com.google.cloud.storage.Blob[]")));
}
}