尝试保存凭据时,使用Google Drive API库和Play with Java会冻结/锁定应用程序

问题描述 投票:1回答:1

我在使用Java的Play Framework应用程序中使用Google Drive API库/代码。我在API部分的GCP项目中正确设置了凭据。我还在学习这些Google库以及我使用的代码是如何从我找到的一些帖子中学习的,所以我不明白为什么它会冻结而不确定如何修复它。

我有代码在本地运行应用程序时工作正常(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());

如果您能通过示例或修复上面的代码向我展示我所缺少的内容,感谢您。提前致谢。

java playframework google-drive-sdk playframework-2.0
1个回答
2
投票

我对此的回答是使用服务帐户而不是OAuth2。

我在Google Cloud Platform项目中创建了一个服务帐户:

https://console.cloud.google.com/iam-admin/serviceaccounts/

我使用了Compute Engine实例的默认帐户,并创建了所需的密钥,并将文件下载到我的机器上,并在上面的代码中引用。

上传文件没有问题。

这是我的最终代码:

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;
    }


}

我希望这有助于下一个人。

© www.soinside.com 2019 - 2024. All rights reserved.