在试图保存凭据时,使用Google Drive API库并使用Java冻结/锁定应用程序

在试图保存凭据时,使用Google Drive API库并使用Java冻结/锁定应用程序,java,playframework,google-drive-api,playframework-2.0,Java,Playframework,Google Drive Api,Playframework 2.0,我正在使用Java的Play Framework应用程序中使用Google Drive API库/代码。我在API部分的GCP项目中正确设置了凭据。我仍然在学习这些谷歌库和我使用的代码是如何从我找到的一些帖子中获得的,所以我不明白为什么它会冻结,也不知道如何修复它 我的代码在本地运行应用程序时运行良好(http://localhost:9000)。但是,当我在服务器上运行时,当它试图保存凭据时,它会冻结/锁定-它从不返回错误或消息。我已经等了15分钟没有回应。以下是代码行: credential

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

我的代码在本地运行应用程序时运行良好(
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;
    }

}
如您所见,它永远不会到达下一个日志输出:

Logger.info("GoogleDrive: authorize: Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());

如果你能给我一个样本或修复上面的代码,让我看看我缺少了什么,我将不胜感激。提前感谢。

我的答案是使用服务帐户而不是OAuth2

我在我的Google云平台项目中创建了一个服务帐户:

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

文件上传没有问题

这是我的最终代码:

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


}
package-google;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.array;
导入java.util.Collections;
导入java.util.List;
导入com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
导入com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
导入com.google.api.client.http.FileContent;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.json.jackson2.JacksonFactory;
导入com.google.api.client.util.store.FileDataStoreFactory;
导入com.google.api.services.drive.drive;
导入com.google.api.services.drive.DriveScopes;
导入com.google.api.services.drive.model.File;
导入com.google.api.services.drive.model.FileList;
导入controllers.GlobalUtilities.StringControl;
导入播放配置;
导入play.Logger;
公共级谷歌硬盘{
/**应用程序名称*/
私有静态最终字符串应用程序\u NAME=“PTP”;
/**用于存储此应用程序的用户凭据的目录*/
private static final java.io.File DATA_STORE_DIR=new java.io.File(System.getProperty(“user.home”),
“.credentials/ptpgoogledrive”);
/**{@link FileDataStoreFactory}的全局实例*/
私有静态文件数据存储工厂数据存储工厂;
/**JSON工厂的全局实例*/
私有静态最终JsonFactory JSON_FACTORY=JacksonFactory.getDefaultInstance();
/**HTTP传输的全局实例*/
专用静态HttpTransport HTTP_传输;
/**
*此快速启动所需作用域的全局实例。
*
*如果修改这些作用域,请删除以前保存的凭据
*~/.credentials/驱动器java快速启动
*/
私有静态最终列表范围=Arrays.asList(DriveScopes.DRIVE);
静止的{
试一试{
HTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
DATA\u STORE\u FACTORY=新文件datastorefactory(DATA\u STORE\u DIR);
}捕获(可丢弃的t){
t、 printStackTrace();
系统出口(1);
}
}
/**
*创建授权凭据对象。
* 
*@返回授权凭证对象。
*@抛出异常
*/
@抑制警告(“弃用”)
公共静态GoogleCredential Authorization()引发IOException{
GoogleCredential凭证=null;
字符串credentialsFileName=“”;
试一试{
Logger.info(“谷歌硬盘:授权:启动…”);
Logger.info(“GoogleDrive:authorize:GettingCredentialsFileName路径…”);
credentialsFileName=Configuration.root().getString(“google.drive.credentials.file”);
Logger.info(“GoogleDrive:authorize:credentialsFileName=“+credentialsFileName”);
Logger.info(“GoogleDrive:authorize:settinginputstream…”);
InputStream in=GoogleDrive.class.getClassLoader().getResourceAsStream(credentialsFileName);
if(in==null){
info(“GoogleDrive:authorize:InputStream为空”);
}
Logger.info(“GoogleDrive:authorize:InputStream set…”);
Logger.info(“谷歌硬盘:授权:设置凭证…”);
credential=GoogleCredential.fromStream(在HTTP\u传输、JSON\u工厂中)
.createScope(Collections.singleton(DriveScopes.DRIVE));
}捕获(IOEX异常){
System.out.println(例如toString());
System.out.println(“找不到文件”+凭证文件名);
例如printStackTrace();
}
Logger.info(“谷歌硬盘:授权:结束…”);
返回凭证;
}
/**
*生成并返回授权驱动器客户端服务。
* 
*@返回授权驱动器客户端服务
*@抛出异常
*/
公共静态驱动器getDriveService()引发IOException{
Logger.info(“GoogleDrive:getDriveService:Starting…”);
GoogleCredential凭证=null;
驱动器googleDrive=null;
试一试{
凭证=授权();
Logger.info(“GoogleDrive:getDriveService:Credentials set…”);
googleDrive=new Drive.Builder(HTTP_传输、JSON_工厂、凭证)
.setApplicationName(应用程序名称).build();
}捕获(IOEX异常){
System.out.println(例如toString(
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;
    }


}