【问题标题】:Spring: How do I load a "File" resource from a JARSpring:如何从 JAR 加载“文件”资源
【发布时间】:2015-11-16 06:45:05
【问题描述】:

我正在尝试从文件系统加载一个 .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 加载“文件”。

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) 方法。

建议。

【问题讨论】:

  • 您可以使用this answer 创建一个标准的Java PrivateKey 对象,然后您可以使用接受PrivateKeyGoogleCredential.Builder.setServiceAccountPrivateKey() 方法。

标签: java spring heroku jar google-cloud-storage


【解决方案1】:

更新: 尝试使用: setServiceAccountPrivateKeyFromP12File(new File(getClass().getResource("google-auth.p12").getFile()))

【讨论】:

  • .getFile() 返回一个字符串。 .setServiceAccountPrivateKeyFromP12File(File file() 需要一个文件。
  • 哦,是的。所以应该是这样 setServiceAccountPrivateKeyFromP12File(new File(getClass().getResource("google-auth.p12").getFile()))
  • 没有这样的运气,似乎因为 .jar 的内部实际上并不是正常文件系统的一部分,所以 .getFile 将永远无法工作。幸运的是,我设法通过创建一个临时文件来破解它。
【解决方案2】:

// 可怕的 hack,但它成功了!加载输入流,从中创建一个临时文件,然后将其引用传递给 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();

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 2018-03-26
    • 2011-08-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多