2017-11-21 1 views
1

私は基本的にはサーブレットを介して私はYouTubeのビデオのコメントを取得しようとしている動的WEB-APPを持っています。外部ディレクトリjavaからclient_secrets.jsonを呼び出す方法は?

ウェブ上でそれについての記事がたくさんありますが、なぜ私のために働いたのかわかりません。

最初の試行:Credential credential = Auth.authorize(scopes, "commentthreads");

あなたが喜ばできる場合scopeで、どこからそれを得る何をすべきかを説明します。私はラインでNullPointerExceptionが取得しています。これにより

private static int counter = 0; 
private static YouTube youtube; 

public static void getYoutubeOauth() throws Exception { 
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl"); 

    Credential credential = Auth.authorize(scopes, "commentthreads"); 
    youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build(); 

    String videoId = "KIgxmV9xXBQ"; 

    // Get video comments threads 
    CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute(); 

    while (true) { 
     handleCommentsThreads(commentsPage.getItems()); 

     String nextPageToken = commentsPage.getNextPageToken(); 
     if (nextPageToken == null) 
      break; 

     // Get next page of video comments threads 
     commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute(); 
    } 

    System.out.println("Total: " + counter); 
} 

2回目の試行資格情報を取得するための別の機能を作成しようとしました。

二回目:私は、ファイルにアクセスすることができ、私の端末でnano /home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.jsonをしようとする場合がここで

public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 
public static final JsonFactory JSON_FACTORY = new JacksonFactory(); 
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials"; 

public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException { 

    // Load client secrets. 
    Reader clientSecretReader = new InputStreamReader(
      Auth.class.getResourceAsStream("/home/hazrat/Documents/eclipse-jee-neon-3-linux-gtk-x86_64/eclipse/client_secrets.json")); 
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader); 

    // Checks that the defaults have been replaced (Default = "Enter X here"). 
    if (clientSecrets.getDetails().getClientId().startsWith("Enter") 
      || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { 
     System.out.println(
       "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential " 
         + "into src/main/resources/client_secrets.json"); 
     return null; 
    } 

    // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore} 
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY)); 
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore); 

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore) 
      .build(); 

    // Build the local server and bind it to port 8080 
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); 

    // Authorize. 
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); 
} 

もイムラインReader clientSecretReader = new InputStreamReader(...でNullPointerExceptionが取得。

質問:私のweb-appを認証して、client_secrets.jsonを外部ディレクトリから読み取る方法。

答えて

0

少し痛いですが、2番目の解決策を働かせました。

Auth.class.getResourceAsStream私はclassLoaderにデータを利用する必要がありますが、classLoaderにはそうではありませんでした。

私がしなければならなかったのは、getResourceAsStream以外のFileInputStreamを使用しなければならない外部ディレクトリからclient_secrets.jsonを要求することでした。

FileInputStreamgetResourceAsStreamはどちらも問題なく動作しますが、状況やコードによって異なります。

public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 
public static final JsonFactory JSON_FACTORY = new JacksonFactory(); 
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials"; 

public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException { 
    Reader clientSecretReader = new InputStreamReader(
      new FileInputStream("/client_secrets.json")); 
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader); 
    System.out.println(clientSecretReader.toString()); 
    if (clientSecrets.getDetails().getClientId().startsWith("Enter") 
      || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { 
     System.out.println(
       "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential " 
         + "into src/main/resources/client_secrets.json"); 
     return null; 
    } 
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY)); 
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore); 

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore) 
      .build(); 
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8081).build(); 

    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); 
} 

private static int counter = 0; 
private static YouTube youtube; 

public static void getYoutubeOauth() throws Exception { 
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl"); 
    Credential credential = authorize(scopes, "commentthreads"); 
    youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build(); 

    String videoId = "KIgxmV9xXBQ"; 

    // Get video comments threads 
    CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute(); 

    while (true) { 
     handleCommentsThreads(commentsPage.getItems()); 

     String nextPageToken = commentsPage.getNextPageToken(); 
     if (nextPageToken == null) 
      break; 

     commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute(); 
    } 

    System.out.println("Total: " + counter); 
} 

private static YouTube.CommentThreads.List prepareListRequest(String videoId) throws Exception { 

    return youtube.commentThreads() 
        .list("snippet,replies") 
        .setVideoId(videoId) 
        .setMaxResults(100L) 
        .setModerationStatus("published") 
        .setTextFormat("plainText"); 
} 

private static void handleCommentsThreads(List<CommentThread> commentThreads) { 

    for (CommentThread commentThread : commentThreads) { 
     List<Comment> comments = Lists.newArrayList(); 
     comments.add(commentThread.getSnippet().getTopLevelComment()); 

     CommentThreadReplies replies = commentThread.getReplies(); 
     if (replies != null) 
      comments.addAll(replies.getComments()); 

     System.out.println("Found " + comments.size() + " comments."); 

     // Do your comments logic here 
     counter += comments.size(); 
    } 
} 

注:自分の場所に変更FileInputStream場所を。

次に、getYoutubeOauthに電話して、動作している応答を得ることができます。

関連する問題