Spring:如何加载"文件"来自JAR的资源

时间:2015-08-22 10:51:06

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

我尝试从文件系统加载.p12文件(Google证书),以便对我的Google云端存储应用程序进行身份验证。

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

建议很有意思。

2 个答案:

答案 0 :(得分:1)

//糟糕的黑客,但它有效!加载输入流,从中创建临时文件,然后将其引用传递给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();

答案 1 :(得分:0)

UPD: 尝试使用: setServiceAccountPrivateKeyFromP12File(new File(getClass()。getResource(&#34; google-auth.p12&#34;)。getFile()))