Warm tip: This article is reproduced from serverfault.com, please click

java-结合使用Google Drive APis和Scala Play项目

(java - Using Google Drive APis with a scala play project)

发布于 2020-12-12 22:12:04

我一直在尝试改编Java快速入门指南,以便与Scala Play项目的Google驱动器API进行交互,但是我在读取凭证文件时遇到了麻烦,它说它不存在,但是我已经尝试过:

  • 绝对路径
  • 内容根的路径
  • 源根的路径

但是这些都不起作用。

这是我的项目结构: 项目结构

这是错误: 错误

这是我用来尝试读取文件的代码:

import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
import com.google.api.client.googleapis.auth.oauth2.{GoogleAuthorizationCodeFlow, GoogleClientSecrets}
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.JsonFactory
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.client.util.store.FileDataStoreFactory
import com.google.api.services.sheets.v4.SheetsScopes

import java.io.{File, FileNotFoundException, IOException, InputStreamReader}
import java.security.GeneralSecurityException
import java.util
import java.util.Collections

class GoogleService {
 private val applicationName: String = "Google Sheets API Java Quickstart"
 private val jsonFactory: JsonFactory = JacksonFactory.getDefaultInstance()
 private val tokenDirectoryPath: String = "tokens"

 private val scopes: util.List[String] = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY)
 private val credentialsFilePath: String = "app/assets/credentials.json"

 @throws[IOException]
 private def getCredentials(HTTP_TRANSPORT: NetHttpTransport) = { // Load client secrets.
   val in = classOf[GoogleService].getResourceAsStream(credentialsFilePath)
   if (in == null) {
     System.out.printf(credentialsFilePath)
     throw new FileNotFoundException(s"Resource not found: $credentialsFilePath")
   }
   val clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(in))
   // Build flow and trigger user authorization request.
   val flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, jsonFactory, clientSecrets, scopes).setDataStoreFactory(new FileDataStoreFactory(new File(tokenDirectoryPath))).setAccessType("offline").build
   val receiver = new LocalServerReceiver.Builder().setPort(8888).build
   new AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
 }

 @throws[IOException]
 @throws[GeneralSecurityException]
 def main(args: String*
         ) {
   val httpTransport = GoogleNetHttpTransport.newTrustedTransport
   getCredentials(httpTransport)
 }
}
Questioner
DevyDev
Viewed
1
Tomer Shetah 2020-12-14 01:59:46

尝试更换:

val in = classOf[GoogleService].getResourceAsStream(credentialsFilePath)

和:

val in = getClass.getResourceAsStream(credentialsFilePath)

请注意,资源通常位于conf文件夹中,而这正是它们的所在。请尝试将文件夹assetsapp文件夹重新定位conf然后upadte:

private val credentialsFilePath: String = "assets/credentials.json"