0

Googleドライブにファイルをアップロードするには次のコードを使用します。これはJavaベースのウェブアプリケーションに使用されます。認証以外のすべてが正常に機能します。GoogleドライブAPI Java、認証は初回のみ有効

このコードの主な問題は、認証のために一度だけ質問し、後でプロジェクトを実行するときに認証を要求することがないことです。

クライアントが要求したすべての要求に対して認証が必要です。

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package myapp.util; 

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.GoogleCredential; 
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 
import com.google.api.client.googleapis.media.MediaHttpUploader; 
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.InputStreamContent; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.util.store.FileDataStoreFactory; 

import com.google.api.services.drive.DriveScopes; 
import com.google.api.services.drive.model.*; 
import com.google.api.services.drive.Drive; 
import java.io.BufferedInputStream; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URLDecoder; 
import java.security.GeneralSecurityException; 
import java.util.Arrays; 
import java.util.List; 
import javax.faces.context.FacesContext; 
import javax.servlet.ServletContext; 

public class GDrive { 

    /** 
    * Application name. 
    */ 
    private static final String APPLICATION_NAME 
      = "Drive API Java Quickstart"; 

    /** 
    * 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/drive-java-quickstart.json"); 

    /** 
    * 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_FILE); 

    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 
    */ 
    public static Credential authorize() throws IOException { 
     ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); 
     String basePath = servletContext.getRealPath(""); 
     basePath = URLDecoder.decode(basePath, "UTF-8"); 
     // Load client secrets. 
     InputStream in = new FileInputStream(
       new java.io.File(basePath + "/resources/client_secret.json")); 
     GoogleClientSecrets clientSecrets 
       = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); 

     // Build flow and trigger user authorization request. 
     GoogleAuthorizationCodeFlow flow 
       = new GoogleAuthorizationCodeFlow.Builder(
         HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) 
       .setDataStoreFactory(DATA_STORE_FACTORY) 
       .setAccessType("offline") 
       .setApprovalPrompt("auto") 
       .build(); 

     GoogleCredential credential = new GoogleCredential(); 
     System.out.println(
       "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); 
     return credential; 
    } 

    /** 
    * Build and return an authorized Drive client service. 
    * 
    * @return an authorized Drive client service 
    * @throws IOException 
    */ 
    public static Drive getDriveService() throws IOException { 
     Credential credential = authorize(); 
     System.out.println("getAccessToken" + credential.getAccessToken()); 

     System.out.println("setAccessToken" + credential.getAccessToken()); 
     System.out.println("setExpiresInSeconds" + credential.getExpiresInSeconds()); 

     System.out.println("setRefreshToken" + credential.getRefreshToken()); 
     return new Drive.Builder(
       HTTP_TRANSPORT, JSON_FACTORY, credential) 
       .setApplicationName(APPLICATION_NAME) 
       .build(); 
    } 

    public boolean uploadToDrive(String filePathUrl, String fileName) throws FileNotFoundException, IOException, GeneralSecurityException, Exception { 
     Drive service = GDrive.getDriveService(); 
     boolean status = false; 
     // TODO code application logic here 
     java.io.File mediaFile = new java.io.File(filePathUrl); 
     com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File(); 
     fileMetadata.setName(fileName); 
     InputStreamContent mediaContent = new InputStreamContent("application/octet-stream", new BufferedInputStream(new FileInputStream(mediaFile))); 
     mediaContent.setLength(mediaFile.length()); 

     HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 

     Drive.Files.Create request = service.files().create(fileMetadata, mediaContent); 
     request.getMediaHttpUploader().setProgressListener(new CustomProgressListener()); 
     request.execute(); 
     status = true; 
     return status; 
    } 

} 

class CustomProgressListener implements MediaHttpUploaderProgressListener { 

    public void progressChanged(MediaHttpUploader uploader) throws IOException { 
     switch (uploader.getUploadState()) { 
      case INITIATION_STARTED: 
       System.out.println("Initiation has started!"); 
       break; 
      case INITIATION_COMPLETE: 
       System.out.println("Initiation is complete!"); 
       break; 
      case MEDIA_IN_PROGRESS: 
       System.out.println(uploader.getProgress()); 
       break; 
      case MEDIA_COMPLETE: 
       System.out.println("Upload is complete!"); 
     } 
    } 
} 
+0

は、setDataStoreFactory(DATA_STORE_FACTORY)で回りました。私の推測はそれを制御しています。 – DaImTo

+0

コードで見ることができます。私はすでにGoogleAuthorizationCodeFlowのデータストアファクトリを設定しています –

+1

FileDataStoreFactoryはおそらく認証を保存しています。一旦認証されると、おそらくあなたのハードドライブに保存されています。あなたはそれを別のユーザーに伝える方法や、別のデータストアを使用する方法を理解する必要があります。 https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/store/FileDataStoreFactory – DaImTo

答えて

1

クライアントライブラリには認証情報が格納されているため、アプリケーションを実行するたびにプロンプ​​トが表示されません。クライアントライブラリは、指定したDataStoreインスタンスへの認証情報を保持します。特定のディレクトリにファイルを格納するFileDataStoreがあります。

複数のユーザーが同じデータストアを共有できますが、承認を行う際に一意のユーザー識別子を渡す必要があります。インストールされているアプリケーションの場合はAuthorizationCodeInstalledApp.authorizeで、Webアプリケーションの場合はAbstractAuthorizationCodeServlet.getUserIdAbstractAuthorizationCodeCallbackServlet.getUserIdを上書きします。詳細と例については、JavaクライアントライブラリのOAuth2 guideを参照してください。

関連する問題