- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Java 的 Play Framework 应用程序中使用 Google Drive API 库/代码。我在 API 部分的 GCP 项目中正确设置了凭据。我仍在学习这些 Google 库和我使用的代码是如何来 self 发现的一些帖子,所以我不明白为什么它会卡住,也不知道如何修复它。
我的代码在本地运行应用程序时可以正常工作(http://localhost:9000
)。但是,当我在服务器上运行时,它在尝试保存凭据时卡住/锁定 - 它永远不会返回错误或消息。我已经等了 15 分钟,没有任何回应。这是代码行:
credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
这是我正在使用的类:
package google;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
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;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
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.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import controllers.GlobalUtilities.StringControl;
import play.Configuration;
import play.Logger;
public class GoogleDrive {
/** Application name. */
private static final String APPLICATION_NAME = "PTP";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/ptpgoogledrive");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials at
* ~/.credentials/drive-java-quickstart
*/
// private static final List<String> SCOPES =
// Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static Credential authorize() throws IOException {
Credential credential = null;
String credentialsFileName = "";
try {
Logger.info("GoogleDrive: authorize: Starting...");
// Set up the credentials...
String clientID = Configuration.root().getString("google.drive.credentials.clientID");
String clientSecret = Configuration.root().getString("google.drive.credentials.clientSecret");
String authURI = Configuration.root().getString("google.drive.credentials.authURI");
String tokenURI = Configuration.root().getString("google.drive.credentials.tokenURI");
Logger.info("GoogleDrive: authorize: clientID = " + clientID);
Logger.info("GoogleDrive: authorize: clientSecret = " + clientSecret);
Logger.info("GoogleDrive: authorize: authURI = " + authURI);
Logger.info("GoogleDrive: authorize: tokenURI = " + tokenURI);
GoogleClientSecrets.Details details = new Details();
details.setClientId(clientID);
details.setClientSecret(clientSecret);
details.setAuthUri(authURI);
details.setTokenUri(tokenURI);
GoogleClientSecrets clientSecrets = new GoogleClientSecrets().setInstalled(details);
Logger.info("GoogleDrive: authorize: Found client secrets...");
if (clientSecrets == null) {
Logger.info("GoogleDrive: authorize: GoogleClientSecrets is null...");
}
// Build flow and trigger user authorization request...
Logger.info("GoogleDrive: authorize: Setting GoogleAuthorizationCodeFlow...");
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Logger.info("GoogleDrive: authorize: GoogleAuthorizationCodeFlow has been set...");
Logger.info("GoogleDrive: authorize: Setting credenital...");
credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
Logger.info("GoogleDrive: authorize: Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + credentialsFileName);
ex.printStackTrace();
}
Logger.info("GoogleDrive: authorize: Ending...");
return credential;
}
/**
* Build and return an authorized Drive client service.
*
* @return an authorized Drive client service
* @throws IOException
*/
public static Drive getDriveService() throws IOException {
Logger.info("GoogleDrive: getDriveService: Starting...");
Credential credential = null;
Drive googleDrive = null;
try {
credential = authorize();
googleDrive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
} catch (IOException ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return googleDrive;
}
public static String getPath() {
String s = GoogleDrive.class.getName();
int i = s.lastIndexOf(".");
if (i > -1)
s = s.substring(i + 1);
s = s + ".class";
System.out.println("Class Name: " + s);
Object testPath = GoogleDrive.class.getResource(s);
System.out.println("Current Path: " + testPath);
return "";
}
public static String uploadFile(java.io.File file) throws IOException {
String fileID = "";
try {
Logger.info("GoogleDrive: uploadFile: Starting File Upload...");
// Build a new authorized API client service.
Drive service = getDriveService();
Logger.info("GoogleDrive: uploadFile: Completed Drive Service...");
String fullFilePath = file.getAbsolutePath();
Logger.info("GoogleDrive: uploadFile: Full File Path: " + fullFilePath);
File fileMetadata = new File();
String fileName = StringControl.rightBack(fullFilePath, "\\");
String fileContentType = getContentType(fileName);
Logger.info("GoogleDrive: uploadFile: File Content Type: " + fileContentType);
fileMetadata.setName(fileName);
Logger.info("GoogleDrive: uploadFile: File Name = " + fileName);
// Set the folder...
String folderID = Configuration.root().getString("google.drive.folderid");
Logger.info("GoogleDrive: uploadFile: Folder ID = " + folderID);
fileMetadata.setParents(Collections.singletonList(folderID));
java.io.File filePath = new java.io.File(fullFilePath);
FileContent mediaContent = new FileContent(fileContentType, filePath);
File fileToUpload = service.files().create(fileMetadata, mediaContent).setFields("id, parents").execute();
fileID = fileToUpload.getId();
Logger.info("GoogleDrive: uploadFile: File ID: " + fileID);
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
Logger.info("GoogleDrive: uploadFile: Ending File Upload...");
return fileID;
}
public static String getContentType(String filePath) throws Exception {
String type = "";
try {
Path path = Paths.get(filePath);
type = Files.probeContentType(path);
System.out.println(type);
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return type;
}
}
我有一堆日志记录来确定代码卡住的位置,这是输出:
GoogleDrive: uploadFile: Starting File Upload...
GoogleDrive: getDriveService: Starting...
GoogleDrive: authorize: Starting...
GoogleDrive: authorize: clientID = (my client ID)
GoogleDrive: authorize: clientSecret = (my client secret)
GoogleDrive: authorize: authURI = https://accounts.google.com/o/oauth2/auth
GoogleDrive: authorize: tokenURI = https://accounts.google.com/o/oauth2/token
GoogleDrive: authorize: Found client secrets...
GoogleDrive: authorize: Setting GoogleAuthorizationCodeFlow...
GoogleDrive: authorize: GoogleAuthorizationCodeFlow has been set...
GoogleDrive: authorize: Setting credenital...
如您所见,它永远不会到达下一个日志输出:
Logger.info("GoogleDrive: authorize: Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
如果您能向我展示示例中缺少的内容或修复上面的代码,我将不胜感激。提前致谢。
最佳答案
我对此的回答是使用服务帐户而不是 OAuth2。
我在 Google Cloud Platform 项目中创建了一个服务帐号:
https://console.cloud.google.com/iam-admin/serviceaccounts/
我使用了 Compute Engine 实例的默认帐户并创建了所需的 key ,并将文件下载到我的计算机并在上面的代码中引用。
文件上传没有问题。
这是我的最终代码:
package google;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
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.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import controllers.GlobalUtilities.StringControl;
import play.Configuration;
import play.Logger;
public class GoogleDrive {
/** Application name. */
private static final String APPLICATION_NAME = "PTP";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/ptpgoogledrive");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials at
* ~/.credentials/drive-java-quickstart
*/
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static GoogleCredential authorize() throws IOException {
GoogleCredential credential = null;
String credentialsFileName = "";
try {
Logger.info("GoogleDrive: authorize: Starting...");
Logger.info("GoogleDrive: authorize: Getting credentialsFileName path...");
credentialsFileName = Configuration.root().getString("google.drive.credentials.file");
Logger.info("GoogleDrive: authorize: credentialsFileName = " + credentialsFileName);
Logger.info("GoogleDrive: authorize: Setting InputStream...");
InputStream in = GoogleDrive.class.getClassLoader().getResourceAsStream(credentialsFileName);
if (in == null) {
Logger.info("GoogleDrive: authorize: InputStream is null");
}
Logger.info("GoogleDrive: authorize: InputStream set...");
Logger.info("GoogleDrive: authorize: Setting credential...");
credential = GoogleCredential.fromStream(in, HTTP_TRANSPORT, JSON_FACTORY)
.createScoped(Collections.singleton(DriveScopes.DRIVE));
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + credentialsFileName);
ex.printStackTrace();
}
Logger.info("GoogleDrive: authorize: Ending...");
return credential;
}
/**
* Build and return an authorized Drive client service.
*
* @return an authorized Drive client service
* @throws IOException
*/
public static Drive getDriveService() throws IOException {
Logger.info("GoogleDrive: getDriveService: Starting...");
GoogleCredential credential = null;
Drive googleDrive = null;
try {
credential = authorize();
Logger.info("GoogleDrive: getDriveService: Credentials set...");
googleDrive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
} catch (IOException ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return googleDrive;
}
public static String getPath() {
String s = GoogleDrive.class.getName();
int i = s.lastIndexOf(".");
if (i > -1)
s = s.substring(i + 1);
s = s + ".class";
System.out.println("Class Name: " + s);
Object testPath = GoogleDrive.class.getResource(s);
System.out.println("Current Path: " + testPath);
return "";
}
public static String uploadFile(java.io.File file, String folderIDToFind) throws IOException {
String fileID = "";
String fileName = "";
try {
Logger.info("GoogleDrive: uploadFile: Starting File Upload...");
// Build a new authorized API client service.
Drive service = getDriveService();
Logger.info("GoogleDrive: uploadFile: Completed Drive Service...");
// Set the folder...
String folderID = Configuration.root().getString("google.drive.folderid");
Logger.info("GoogleDrive: uploadFile: Folder ID = " + folderID);
String folderIDToUse = getSubfolderID(service, folderID, folderIDToFind);
String fullFilePath = file.getAbsolutePath();
Logger.info("GoogleDrive: uploadFile: Full File Path: " + fullFilePath);
File fileMetadata = new File();
// Let's see what slashes exist to get the correct file name...
if (fullFilePath.contains("/")) {
fileName = StringControl.rightBack(fullFilePath, "/");
} else {
fileName = StringControl.rightBack(fullFilePath, "\\");
}
String fileContentType = getContentType(fileName);
Logger.info("GoogleDrive: uploadFile: File Content Type: " + fileContentType);
fileMetadata.setName(fileName);
Logger.info("GoogleDrive: uploadFile: File Name = " + fileName);
Logger.info("GoogleDrive: uploadFile: Setting the folder...");
fileMetadata.setParents(Collections.singletonList(folderIDToUse));
Logger.info("GoogleDrive: uploadFile: Folder set...");
// Team Drive settings...
fileMetadata.set("supportsTeamDrives", true);
java.io.File filePath = new java.io.File(fullFilePath);
FileContent mediaContent = new FileContent(fileContentType, filePath);
File fileToUpload = service.files().create(fileMetadata, mediaContent).setSupportsTeamDrives(true)
.setFields("id, parents").execute();
fileID = fileToUpload.getId();
Logger.info("GoogleDrive: uploadFile: File ID: " + fileID);
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
Logger.info("GoogleDrive: uploadFile: Ending File Upload...");
return fileID;
}
public static String getContentType(String filePath) throws Exception {
String type = "";
try {
Path path = Paths.get(filePath);
type = Files.probeContentType(path);
System.out.println(type);
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
return type;
}
public static String getSubfolderID(Drive service, String parentFolderID, String folderKeyToGet) {
// We need to see if the folder exists based on the ID...
String folderID = "";
Boolean foundFolder = false;
FileList result = null;
File newFolder = null;
// Set the drive query...
String driveQuery = "mimeType='application/vnd.google-apps.folder' and '" + parentFolderID
+ "' in parents and name contains '" + folderKeyToGet + "' and trashed=false";
try {
result = service.files().list().setQ(driveQuery).execute();
} catch (IOException e) {
e.printStackTrace();
}
for (File folder : result.getFiles()) {
System.out.printf("Found folder: %s (%s)\n", folder.getName(), folder.getId());
foundFolder = true;
folderID = folder.getId();
}
if (foundFolder != true) {
// Need to create the folder...
File fileMetadata = new File();
fileMetadata.setName(folderKeyToGet);
fileMetadata.setTeamDriveId(parentFolderID);
fileMetadata.set("supportsTeamDrives", true);
fileMetadata.setMimeType("application/vnd.google-apps.folder");
fileMetadata.setParents(Collections.singletonList(parentFolderID));
try {
newFolder = service.files().create(fileMetadata).setSupportsTeamDrives(true).setFields("id, parents")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
// Send back the folder ID...
folderID = newFolder.getId();
System.out.println("Folder ID: " + newFolder.getId());
}
return folderID;
}
}
我希望这对下一个人有帮助。
关于java - 尝试保存凭据时,使用 Google Drive API 库和 Play with Java 会卡住/锁定应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951874/
所以我的应用程序的评论显示在我的游戏控制台中,但是由于某种原因,当我在 google Play 商店上访问我的应用程序链接并以普通用户的身份查看它时,我没有收到新评论的通知,我的显示了 13 条评论,
一旦我在 2.3 play 项目上运行 'sbt compile',我就不能再使用 'sbt compile' 来编译任何 Play 2.2.x 项目。这是我运行 sbt 命令时的错误。 [info]
我有点困惑,想得到一个解释。 我正在使用 Java Play 2 和 Akka Actor 。我使用 play run 启动系统。 不过,我刚刚看到一个视频,使用了命令: play akka star
当我玩游戏时,我遇到两个选择play.api.mvc和 play.mvc包裹 有什么不同? 最佳答案 从戏! 2 文档: The API available in the play.api packa
从 2.3 迁移到 2.4 后,我收到此错误。我应该使用的正确导入语句是什么? error: value routesImport is not a member of object play.Pla
所以我在 google play 上有一个应用程序已经将近 6 个月了,最近两个月我更新了我的应用程序屏幕截图,从那时起,每次我更新我的应用程序时,我都开始收到应用程序拒绝。 上次我提出上诉并被接受,
我有以下代码: Snapshots.OpenSnapshotResult result; result = Games.Snapshots.open(googleApiClient, "save",
在过去 72 小时内,我为 Google Play 开发者计划支付的 Google 电子钱包付款显示为“您的购买正在处理中”。我知道这可能需要长达 48 小时,但这是他们处理时间最坏情况之后的一整天。
我在 Play 商店发布了应用程序,我不知道为什么应用程序显示预注册,我想为我的用户提供直接下载选项。伸出援手将不胜感激。 最佳答案 instructions for pre-registration
我有一个 PHP 后端,它与 Google Play 服务集成以验证从 APP 进行的购买。购买信息返回收据和签名,我需要验证购买是否正确。 我收到: { ...rest of the data
我在 Google Play Developer Console 上创建了我的 Android 应用程序的草稿。我已经填写了所有需要的信息。必需的步骤之一是“内容评级”。我已填写表格以自动分配 Goo
我已经设置好了 com.typesafe.play play_2.13 2.7.4 在项目 pom.xml 中。但是,当我尝试遵循this tutorial时,语句 pla
我在 Play 商店上发布了一个应用程序,并收到了一些评论。在Google Play开发者控制台中,我在一些评论中看不到应用程序的版本。这是我在“应用程序”标题下找到的内容。 版本代码 — 版本名称
假设 A 是所有者。我希望我们团队的 B、C 和 D 用户能够上传我们应用程序的新版本。这可能吗?来自 this我不太清楚用户有什么样的权限。如果有人对这部分有任何经验,欢迎。 最佳答案 您需要 go
我正在尝试将应用重新提交到 Google Play,但我似乎可以找到一种技术上的方法来实现此目的。 我对“您的应用主要针对 COPPA 定义的 13 岁以下 child 吗?”的回答是肯定的,然后在不
我想分享一下我在分析 Google Play 控制台的新功能时遇到的情况,并尝试找到解决方案。 正如你们许多人可能已经知道的那样,Google 已在 Google Play 控制台上发布了更新并引入了
我有两个用 playframework 编写的应用程序。我想加入另一个。我有一个数据库,我想在它们之间共享我的登录类。应用程序对类、方法、变量使用不同的名称。 我怎样才能实现它?我应该创建 jar 版
对于我的硕士论文,我需要自动将来自 Google Play 的不同 Android 应用程序的信息写入一个文本文件。所以我使用 perl 脚本语言来实现这种自动化。我的 perl 脚本可以在 Goog
我想测试子项目是如何工作的,尤其是 routes在主项目 ( this was not visible before ) 中考虑了子项目的数量。 我在这里阅读了文档: https://github.c
我正在使用 Play 框架 2.1.2,我有一个 handlere 方法返回一个 Promise,如 Play 的 2.1.2 documentation 中所述 但是 Play 抛出编译错误说: C
我是一名优秀的程序员,十分优秀!