簡體   English   中英

春季:如何從JAR加載“文件”資源

[英]Spring: How do I load a “File” resource from a JAR

我正在嘗試從文件系統加載.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)方法。

忠告。

//糟糕的駭客,但行得通! 加載輸入流,從中創建一個臨時文件,然后將其引用傳遞給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();

UPD:嘗試使用:setServiceAccountPrivateKeyFromP12File(new File(getClass()。getResource(“ google-auth.p12”)。getFile()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM