gpt4 book ai didi

java - Spring:如何从 JAR 加载 "File"资源

转载 作者:行者123 更新时间:2023-11-30 03:17:47 25 4
gpt4 key购买 nike

我正在尝试从文件系统加载 .p12 文件(Google 证书),以验证我的 Google Cloud Storage 应用程序。

 Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("157264856793-sl14obknv58bi73m2co92oabrara9l8c@developer.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(resourceLoader.getResource("classpath:google-auth.p12").getFile())
.setServiceAccountScopes(scopes).build();

不幸的是,当尝试部署应用程序(作为 JAR 到 Heroku 上)时,我收到一条错误,指出无法从 JAR 加载"file"。

java.io.FileNotFoundException: class path resource [google-auth.p12] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app/build/libs/Nitro.jar!/google-auth.p12

有人建议我将文件作为 inputstream 加载,而不是文件,但 GoogleCredential 似乎没有合适的方法,只有:

setServiceAccountPrivateKeyFromP12File(File file) 方法。

感谢建议。

最佳答案

//糟糕的黑客,但它有效!加载输入流,从中创建一个临时文件,然后将其引用传递给 Google API。我希望 Google 尽快实现一种接受 InputStream 的方法。

    InputStream stream = resourceLoader.getResource("classpath:google-auth.p12").getInputStream();

// Here is the juicy stuff...

File tempFile = File.createTempFile("temp", "temp");
IOUtils.copy(stream, new FileOutputStream(tempFile));

// And the rest...

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();

List<String> scopes = new ArrayList<>();
scopes.add(StorageScopes.CLOUD_PLATFORM);

Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("157264856793-sl14obknv58bi73m2co92oabrara9l8c@developer.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(tempFile)
.setServiceAccountScopes(scopes).build();

关于java - Spring:如何从 JAR 加载 "File"资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32155274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com