Java コード サンプル

次のコード サンプルは Java用のGoogle APIのクライアントライブラリ を使用しており、YouTube Data API で利用できます。これらのコードサンプルは GithubのYouTube APIコードサンプルレポジトリ 内にあるjavaのフォルダからダウンロードできます。

チャンネルのお知らせメッセージの投稿

次のコード サンプルでは、API の activities.insert メソッドを呼び出し、リクエストに関連付けられているチャンネルにお知らせメッセージを投稿します。

  • ChannelBulletin.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample;
    
    import java.io.File;
    import java.util.Calendar;
    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.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Activity;
    import com.google.api.services.youtube.model.ActivityContentDetails;
    import com.google.api.services.youtube.model.ActivityContentDetails.Bulletin;
    import com.google.api.services.youtube.model.ActivitySnippet;
    import com.google.api.services.youtube.model.Channel;
    import com.google.api.services.youtube.model.ChannelListResponse;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.common.collect.Lists;
    
    /**
     * Creates a video bulletin that is posted to the user's channel feed.
     *
     * @author Jeremy Walker
     */
    public class ChannelBulletin {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /*
       * Global instance of the video id we want to post as a bulletin into our channel feed. You will
       * probably pull this from a search or your app.
       */
      private static String VIDEO_ID = "L-oNKK1CrnU";
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json"));
    
        // 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://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .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");
      }
    
      /**
       * Authorizes user, runs Youtube.Channnels.List to get the default channel, and posts a bulletin
       * with a video id to the user's default channel.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // Scope required to upload to YouTube.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-channelbulletin-sample").build();
    
          /*
           * Now that the user is authenticated, the app makes a channel list request to get the
           * authenticated user's channel. https://developers.google.com/youtube/v3/docs/channels/list
           */
          YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
          channelRequest.setMine("true");
          /*
           * Limits the results to only the data we need making your app more efficient.
           */
          channelRequest.setFields("items/contentDetails");
          ChannelListResponse channelResult = channelRequest.execute();
    
          /*
           * Gets the list of channels associated with the user.
           */
          List<Channel> channelsList = channelResult.getItems();
    
          if (channelsList != null) {
            // Gets user's default channel id (first channel in list).
            String channelId = channelsList.get(0).getId();
    
            /*
             * We create the snippet to set the channel we will post to and the description that goes
             * along with our bulletin.
             */
            ActivitySnippet snippet = new ActivitySnippet();
            snippet.setChannelId(channelId);
            Calendar cal = Calendar.getInstance();
            snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());
    
            /*
             * We set the kind of the ResourceId to video (youtube#video). Please note, you could set
             * the type to a playlist (youtube#playlist) and use a playlist id instead of a video id.
             */
            ResourceId resource = new ResourceId();
            resource.setKind("youtube#video");
            resource.setVideoId(VIDEO_ID);
    
            Bulletin bulletin = new Bulletin();
            bulletin.setResourceId(resource);
    
            // We construct the ActivityContentDetails now that we have the Bulletin.
            ActivityContentDetails contentDetails = new ActivityContentDetails();
            contentDetails.setBulletin(bulletin);
    
            /*
             * Finally, we construct the activity we will write to YouTube via the API. We set the
             * snippet (covers description and channel we are posting to) and the content details
             * (covers video id and type).
             */
            Activity activity = new Activity();
            activity.setSnippet(snippet);
            activity.setContentDetails(contentDetails);
    
            /*
             * We specify the parts (contentDetails and snippet) we will write to YouTube. Those also
             * cover the parts that are returned.
             */
            YouTube.Activities.Insert insertActivities =
                youtube.activities().insert("contentDetails,snippet", activity);
            // This returns the Activity that was added to the user's YouTube channel.
            Activity newActivityInserted = insertActivities.execute();
    
            if (newActivityInserted != null) {
              System.out.println(
                  "New Activity inserted of type " + newActivityInserted.getSnippet().getType());
              System.out.println(" - Video id "
                  + newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
              System.out.println(
                  " - Description: " + newActivityInserted.getSnippet().getDescription());
              System.out.println(" - Posted on " + newActivityInserted.getSnippet().getPublishedAt());
            } else {
              System.out.println("Activity failed.");
            }
    
          } else {
            System.out.println("No channels are assigned to this user.");
          }
        } catch (GoogleJsonResponseException e) {
          e.printStackTrace();
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
    
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-channelbulletin-sample</artifactId>
      <version>1.0</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-channelbulletin-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.oauth.version>1.12.0-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample.ChannelBulletin</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter your client id here",
        "client_secret": "Enter your client secret here"
      }
    }
    

次のコード サンプルでは、API の channels.update メソッドを呼び出し、チャンネルの invideoPromotion プロパティを設定します。

  • AddFeaturedVideo.java

    /*
     * Copyright (c) 2013 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addfeaturedvideo_sample;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.*;
    import com.google.common.collect.Lists;
    
    import java.io.File;
    import java.io.IOException;
    import java.math.BigInteger;
    import java.util.List;
    
    /**
     * This program adds a featured video to a channel via the Invideo Programming API.
     *
     * @author Ikai Lan <ikai@google.com>
     */
    public class AddFeaturedVideo {
    
        /**
         * Global instance of the HTTP transport.
         */
        private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
        /**
         * Global instance of the JSON factory.
         */
        private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
        /**
         * Global instance of Youtube object to make all API requests.
         */
        private static YouTube youtube;
    
    
        /**
         * Authorizes the installed application to access user's protected data.
         *
         * @param scopes list of scopes needed to run youtube upload.
         */
        private static Credential authorize(List<String> scopes) throws IOException {
    
            // Load client secrets.
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
                    JSON_FACTORY, AddFeaturedVideo.class.getResourceAsStream("/client_secrets.json"));
    
            // 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://code.google.com/apis/console/?api=youtube"
                                + "into youtube-cmdline-addfeaturedvideo-sample/src/main/resources/client_secrets.json");
                System.exit(1);
            }
    
            // Set up file credential store.
            FileCredentialStore credentialStore = new FileCredentialStore(
                    new File(System.getProperty("user.home"), ".credentials/youtube-api-addfeaturedvideo.json"),
                    JSON_FACTORY);
    
            // Set up authorization code flow.
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
                    .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");
        }
    
        /**
         * This is a very simple code sample that looks up a user's channel, then features the most recently
         * uploaded video in the bottom left hand corner of every single video in the channel.
         *
         * @param args command line args (not used).
         */
        public static void main(String[] args) {
    
            // An OAuth 2 access scope that allows for full read/write access.
            List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
            try {
                // Authorization.
                Credential credential = authorize(scopes);
    
                // YouTube object used to make all API requests.
                youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
                        "youtube-cmdline-addfeaturedvideo-sample").build();
    
                // Fetch the user's channel. We also fetch the uploads playlist so we can use this later
                // to find the most recently uploaded video
                ChannelListResponse channelListResponse = youtube.channels().list("id,contentDetails")
                        .setMine(true)
                        .setFields("items(contentDetails/relatedPlaylists/uploads,id)")
                        .execute();
    
                // This assumes the user has a channel already. If the user does not have a channel, this should
                // throw a GoogleJsonResponseException explaining the issue
                Channel myChannel = channelListResponse.getItems().get(0);
                String channelId = myChannel.getId();
                String uploadsPlaylistId = myChannel.getContentDetails().getRelatedPlaylists().getUploads();
    
                // Fetch the most recently uploaded video
                PlaylistItemListResponse playlistItemListResponse = youtube.playlistItems().list("snippet")
                        .setPlaylistId(uploadsPlaylistId)
                        .setFields("items/snippet")
                        .execute();
    
                String featuredVideoId;
                if (playlistItemListResponse.getItems().isEmpty()) {
                    // There are no videos on the channel. Therefore, we cannot feature a video. Exit.
                    System.out.println("Channel contains no videos. Featuring a default video instead from the Google Developers channel.");
                    featuredVideoId = "w4eiUiauo2w";
                } else {
                    // The latest video should be the first video in the playlist response
                    PlaylistItem featuredVideo = playlistItemListResponse.getItems().get(0);
                    featuredVideoId = featuredVideo.getSnippet()
                            .getResourceId()
                            .getVideoId();
    
                    System.out.println("Featuring video: " + featuredVideo.getSnippet().getTitle());
                }
    
                // Feature this video on the channel via the Invideo programming API
                // This describes the position of the video. Valid positions are bottomLeft, bottomRight, topLeft and
                // topRight
                InvideoPosition invideoPosition = new InvideoPosition();
                invideoPosition.setCornerPosition("bottomLeft");
                invideoPosition.setType("corner");
    
                // The allowed offsets are offsetFromEnd and offsetFromStart, with offsetMs being an offset in milliseconds
                InvideoTiming invideoTiming = new InvideoTiming();
                invideoTiming.setOffsetMs(BigInteger.valueOf(15000l));
                invideoTiming.setType("offsetFromEnd");
    
                // Represents the type of promotion. In this case, a video with a video ID
                PromotedItemId promotedItemId = new PromotedItemId();
                promotedItemId.setType("video");
                promotedItemId.setVideoId(featuredVideoId);
    
                // Construct the Invidideo promotion
                InvideoPromotion invideoPromotion = new InvideoPromotion();
                invideoPromotion.setPosition(invideoPosition);
                invideoPromotion.setTiming(invideoTiming);
                invideoPromotion.setItems(Lists.newArrayList(promotedItemId));
    
                // Now let's add the invideo promotion to the channel
                Channel channel = new Channel();
                channel.setId(channelId);
                channel.setInvideoPromotion(invideoPromotion);
    
                // Make the API call
                Channel updateChannelResponse = youtube.channels()
                        .update("invideoPromotion", channel)
                        .execute();
    
                // Print out returned results.
                System.out.println("\n================== Updated Channel Information ==================\n");
                System.out.println("\t- Channel ID: " + updateChannelResponse.getId());
    
                InvideoPromotion promotion = updateChannelResponse.getInvideoPromotion();
                System.out.println("\t- Invideo promotion video ID: " + promotion.getItems()
                        .get(0)
                        .getVideoId());
                System.out.println("\t- Promotion position: " + promotion.getPosition().getCornerPosition());
                System.out.println("\t- Promotion timing: " + promotion.getTiming().getOffsetMs()
                        + " Offset: " + promotion.getTiming().getType());
            } catch (GoogleJsonResponseException e) {
                System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                        + e.getDetails().getMessage());
                e.printStackTrace();
    
            } catch (IOException e) {
                System.err.println("IOException: " + e.getMessage());
                e.printStackTrace();
            }
        }
    
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-addfeaturedvideo-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-addfeaturedvideo-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev56-1.15.0-rc</project.youtube.version>
        <project.http.version>1.15.0-rc</project.http.version>
        <project.oauth.version>1.15.0-rc</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
    
        <dependency>
            <groupId>com.google.collections</groupId>
            <artifactId>google-collections</artifactId>
            <version>1.0</version>
        </dependency>
    
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addfeaturedvideo_sample.AddFeaturedVideo</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter Client ID",
        "client_secret": "Enter Client Secret"
      }
    }
    

マイ アップロード動画の取得

次のコード サンプルでは、API の playlistItems.list メソッドを呼び出し、リクエストに関連付けられているチャンネルにアップロードされた動画のリストを取得します。また、mine パラメータを true に設定して channels.list メソッドを呼び出し、チャンネルのアップロード済み動画を識別する再生リスト ID を取得します。

  • MyUploads.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_myuploads_sample;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Iterator;
    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.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Channel;
    import com.google.api.services.youtube.model.ChannelListResponse;
    import com.google.api.services.youtube.model.PlaylistItem;
    import com.google.api.services.youtube.model.PlaylistItemListResponse;
    import com.google.common.collect.Lists;
    
    /**
     * Prints a list of videos uploaded to the user's YouTube account using OAuth2 for authentication.
     *
     *  Details: The app uses Youtube.Channnels.List to get the playlist id associated with all the
     * videos ever uploaded to the user's account. It then gets all the video info using
     * YouTube.PlaylistItems.List. Finally, it prints all the information to the screen.
     *
     * @author Jeremy Walker
     */
    public class MyUploads {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, MyUploads.class.getResourceAsStream("/client_secrets.json"));
    
        // 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://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-myuploads-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-myuploads.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .build();
    
        // Build the local server and bind it to port 9000
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Authorizes user, runs Youtube.Channnels.List get the playlist id associated with uploaded
       * videos, runs YouTube.PlaylistItems.List to get information on each video, and prints out the
       * results.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // Scope required to upload to YouTube.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-myuploads-sample").build();
    
          /*
           * Now that the user is authenticated, the app makes a channel list request to get the
           * authenticated user's channel. Returned with that data is the playlist id for the uploaded
           * videos. https://developers.google.com/youtube/v3/docs/channels/list
           */
          YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
          channelRequest.setMine("true");
          /*
           * Limits the results to only the data we needo which makes things more efficient.
           */
          channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
          ChannelListResponse channelResult = channelRequest.execute();
    
          /*
           * Gets the list of channels associated with the user. This sample only pulls the uploaded
           * videos for the first channel (default channel for user).
           */
          List<Channel> channelsList = channelResult.getItems();
    
          if (channelsList != null) {
            // Gets user's default channel id (first channel in list).
            String uploadPlaylistId =
                channelsList.get(0).getContentDetails().getRelatedPlaylists().getUploads();
    
            // List to store all PlaylistItem items associated with the uploadPlaylistId.
            List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
    
            /*
             * Now that we have the playlist id for your uploads, we will request the playlistItems
             * associated with that playlist id, so we can get information on each video uploaded. This
             * is the template for the list call. We call it multiple times in the do while loop below
             * (only changing the nextToken to get all the videos).
             * https://developers.google.com/youtube/v3/docs/playlistitems/list
             */
            YouTube.PlaylistItems.List playlistItemRequest =
                youtube.playlistItems().list("id,contentDetails,snippet");
            playlistItemRequest.setPlaylistId(uploadPlaylistId);
    
            // This limits the results to only the data we need and makes things more efficient.
            playlistItemRequest.setFields(
                "items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo");
    
            String nextToken = "";
    
            // Loops over all search page results returned for the uploadPlaylistId.
            do {
              playlistItemRequest.setPageToken(nextToken);
              PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
    
              playlistItemList.addAll(playlistItemResult.getItems());
    
              nextToken = playlistItemResult.getNextPageToken();
            } while (nextToken != null);
    
            // Prints results.
            prettyPrint(playlistItemList.size(), playlistItemList.iterator());
          }
    
        } catch (GoogleJsonResponseException e) {
          e.printStackTrace();
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
    
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    
      /*
       * Method that prints all the PlaylistItems in an Iterator.
       *
       * @param size size of list
       *
       * @param iterator of Playlist Items from uploaded Playlist
       */
      private static void prettyPrint(int size, Iterator<PlaylistItem> playlistEntries) {
        System.out.println("=============================================================");
        System.out.println("\t\tTotal Videos Uploaded: " + size);
        System.out.println("=============================================================\n");
    
        while (playlistEntries.hasNext()) {
          PlaylistItem playlistItem = playlistEntries.next();
          System.out.println(" video name  = " + playlistItem.getSnippet().getTitle());
          System.out.println(" video id    = " + playlistItem.getContentDetails().getVideoId());
          System.out.println(" upload date = " + playlistItem.getSnippet().getPublishedAt());
          System.out.println("\n-------------------------------------------------------------\n");
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-myuploads-sample</artifactId>
      <version>1.0</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-myuploads-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.oauth.version>1.12.0-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_myuploads_sample.MyUploads</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter your client id here",
        "client_secret": "Enter your client secret here"
      }
    }
    

再生リストの作成

次のコード サンプルでは、API の playlists.insert メソッドを呼び出し、リクエストを承認するチャンネルが所有する非公開の再生リストを作成します。

  • PlaylistUpdates.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the
     * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
     * express or implied. See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_playlistupdates_sample;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Calendar;
    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.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Playlist;
    import com.google.api.services.youtube.model.PlaylistItem;
    import com.google.api.services.youtube.model.PlaylistItemSnippet;
    import com.google.api.services.youtube.model.PlaylistSnippet;
    import com.google.api.services.youtube.model.PlaylistStatus;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.common.collect.Lists;
    
    /**
     * Creates a new, private playlist in the authorized user's channel and adds a playlistitem
     * containing a video to that new playlist.
     *
     * @author Jeremy Walker
     */
    public class PlaylistUpdates {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /*
       * Global instance of the video id we want to post as the first PlaylistItem in our new playlist.
       */
      private static String VIDEO_ID = "SZj6rAYkYOg";
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(
                JSON_FACTORY,
                PlaylistUpdates.class.getResourceAsStream("/client_secrets.json"));
    
        // 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://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-playlistupdates-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore =
            new FileCredentialStore(
                new File(System.getProperty("user.home"),
                         ".credentials/youtube-api-playlistupdates.json"),
                         JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = 
            new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, 
                                                    JSON_FACTORY,
                                                    clientSecrets,
                                                    scopes)
          .setCredentialStore(credentialStore).build();
    
        // Build the local server and bind it to port 9000
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Authorizes user, creates a playlist, adds a playlistitem with a video to that new playlist.
       *
       * @param args command line args (not used).
       */
      public static void main( String[] args ) {
    
        // General read/write scope for YouTube APIs.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("youtube-cmdline-playlistupdates-sample")
            .build();
    
          // Creates a new playlist in the authorized user's channel.
          String playlistId = insertPlaylist();
    
          // If a valid playlist was created, adds a new playlistitem with a video to that playlist.
          insertPlaylistItem(playlistId, VIDEO_ID);
    
        } catch (GoogleJsonResponseException e) {
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          System.err.println("IOException: " + e.getMessage());
          e.printStackTrace();
        } catch (Throwable t) {
          System.err.println("Throwable: " + t.getMessage());
          t.printStackTrace();
        }
      }
    
      /**
       * Creates YouTube Playlist and adds it to the authorized account.
       */
      private static String insertPlaylist() throws IOException {
    
        /*
         * We need to first create the parts of the Playlist before the playlist itself.  Here we are
         * creating the PlaylistSnippet and adding the required data.
         */
        PlaylistSnippet playlistSnippet = new PlaylistSnippet();
        playlistSnippet.setTitle("Test Playlist " + Calendar.getInstance().getTime());
        playlistSnippet.setDescription("A private playlist created with the YouTube API v3");
    
        // Here we set the privacy status (required).
        PlaylistStatus playlistStatus = new PlaylistStatus();
        playlistStatus.setPrivacyStatus("private");
    
        /*
         * Now that we have all the required objects, we can create the Playlist itself and assign the
         * snippet and status objects from above.
         */
        Playlist youTubePlaylist = new Playlist();
        youTubePlaylist.setSnippet(playlistSnippet);
        youTubePlaylist.setStatus(playlistStatus);
    
        /*
         * This is the object that will actually do the insert request and return the result.  The
         * first argument tells the API what to return when a successful insert has been executed.  In
         * this case, we want the snippet and contentDetails info.  The second argument is the playlist
         * we wish to insert.
         */
        YouTube.Playlists.Insert playlistInsertCommand =
            youtube.playlists().insert("snippet,status", youTubePlaylist);
        Playlist playlistInserted = playlistInsertCommand.execute();
    
        // Pretty print results.
    
        System.out.println("New Playlist name: " + playlistInserted.getSnippet().getTitle());
        System.out.println(" - Privacy: " + playlistInserted.getStatus().getPrivacyStatus());
        System.out.println(" - Description: " + playlistInserted.getSnippet().getDescription());
        System.out.println(" - Posted: " + playlistInserted.getSnippet().getPublishedAt());
        System.out.println(" - Channel: " + playlistInserted.getSnippet().getChannelId() + "\n");
        return playlistInserted.getId();
    
      }
    
      /**
       * Creates YouTube PlaylistItem with specified video id and adds it to the specified playlist id
       * for the authorized account.
       *
       * @param playlistId assign to newly created playlistitem
       * @param videoId YouTube video id to add to playlistitem
       */
      private static String insertPlaylistItem(String playlistId, String videoId) throws IOException {
    
        /*
         * The Resource type (video,playlist,channel) needs to be set along with the resource id. In
         * this case, we are setting the resource to a video id, since that makes sense for this
         * playlist.
         */
        ResourceId resourceId = new ResourceId();
        resourceId.setKind("youtube#video");
        resourceId.setVideoId(videoId);
    
        /*
         * Here we set all the information required for the snippet section.  We also assign the
         * resource id from above to the snippet object.
         */
        PlaylistItemSnippet playlistItemSnippet = new PlaylistItemSnippet();
        playlistItemSnippet.setTitle("First video in the test playlist");
        playlistItemSnippet.setPlaylistId(playlistId);
        playlistItemSnippet.setResourceId(resourceId);
    
        /*
         * Now that we have all the required objects, we can create the PlaylistItem itself and assign
         * the snippet object from above.
         */
        PlaylistItem playlistItem = new PlaylistItem();
        playlistItem.setSnippet(playlistItemSnippet);
    
        /*
         * This is the object that will actually do the insert request and return the result.  The
         * first argument tells the API what to return when a successful insert has been executed.  In
         * this case, we want the snippet and contentDetails info.  The second argument is the
         * playlistitem we wish to insert.
         */
        YouTube.PlaylistItems.Insert playlistItemsInsertCommand =
            youtube.playlistItems().insert("snippet,contentDetails", playlistItem);
        PlaylistItem returnedPlaylistItem = playlistItemsInsertCommand.execute();
    
        // Pretty print results.
    
        System.out.println("New PlaylistItem name: " + returnedPlaylistItem.getSnippet().getTitle());
        System.out.println(" - Video id: " + returnedPlaylistItem.getSnippet().getResourceId().getVideoId());
        System.out.println(" - Posted: " + returnedPlaylistItem.getSnippet().getPublishedAt());
        System.out.println(" - Channel: " + returnedPlaylistItem.getSnippet().getChannelId());
        return returnedPlaylistItem.getId();
    
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-playlistupdates-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-playlistupdates-sample</name>
      <url>http://maven.apache.org</url>
    
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.oauth.version>1.12.0-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_playlistupdates_sample.PlaylistUpdates</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    
    </project>
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter Client ID",
        "client_secret": "Enter Client Secret"
      }
    }
    

キーワードで検索

次のコード サンプルでは、API の search.list メソッドを呼び出し、特定のキーワードに関連する検索結果を取得します。

  • Search.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_search_sample;
    
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpRequest;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.api.services.youtube.model.SearchListResponse;
    import com.google.api.services.youtube.model.SearchResult;
    import com.google.api.services.youtube.model.Thumbnail;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Properties;
    
    /**
     * Prints a list of videos based on a search term.
     *
     * @author Jeremy Walker
     */
    public class Search {
    
      /** Global instance properties filename. */
      private static String PROPERTIES_FILENAME = "youtube.properties";
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of the max number of videos we want returned (50 = upper limit per page). */
      private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
    
      /** Global instance of Youtube object to make all API requests. */
      private static YouTube youtube;
    
    
      /**
       * Initializes YouTube object to search for videos on YouTube (Youtube.Search.List). The program
       * then prints the names and thumbnails of each of the videos (only first 50 videos).
       *
       * @param args command line args.
       */
      public static void main(String[] args) {
        // Read the developer key from youtube.properties
        Properties properties = new Properties();
        try {
          InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
          properties.load(in);
    
        } catch (IOException e) {
          System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
              + " : " + e.getMessage());
          System.exit(1);
        }
    
        try {
          /*
           * The YouTube object is used to make all API requests. The last argument is required, but
           * because we don't need anything initialized when the HttpRequest is initialized, we override
           * the interface and provide a no-op function.
           */
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {}
          }).setApplicationName("youtube-cmdline-search-sample").build();
    
          // Get query term from user.
          String queryTerm = getInputQuery();
    
          YouTube.Search.List search = youtube.search().list("id,snippet");
          /*
           * It is important to set your developer key from the Google Developer Console for
           * non-authenticated requests (found under the API Access tab at this link:
           * code.google.com/apis/). This is good practice and increased your quota.
           */
          String apiKey = properties.getProperty("youtube.apikey");
          search.setKey(apiKey);
          search.setQ(queryTerm);
          /*
           * We are only searching for videos (not playlists or channels). If we were searching for
           * more, we would add them as a string like this: "video,playlist,channel".
           */
          search.setType("video");
          /*
           * This method reduces the info returned to only the fields we need and makes calls more
           * efficient.
           */
          search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
          search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
          SearchListResponse searchResponse = search.execute();
    
          List<SearchResult> searchResultList = searchResponse.getItems();
    
          if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm);
          }
        } catch (GoogleJsonResponseException e) {
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
        } catch (IOException e) {
          System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    
      /*
       * Returns a query term (String) from user via the terminal.
       */
      private static String getInputQuery() throws IOException {
    
        String inputQuery = "";
    
        System.out.print("Please enter a search term: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        inputQuery = bReader.readLine();
    
        if (inputQuery.length() < 1) {
          // If nothing is entered, defaults to "YouTube Developers Live."
          inputQuery = "YouTube Developers Live";
        }
        return inputQuery;
      }
    
      /*
       * Prints out all SearchResults in the Iterator. Each printed line includes title, id, and
       * thumbnail.
       *
       * @param iteratorSearchResults Iterator of SearchResults to print
       *
       * @param query Search query (String)
       */
      private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
    
        System.out.println("\n=============================================================");
        System.out.println(
            "   First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
        System.out.println("=============================================================\n");
    
        if (!iteratorSearchResults.hasNext()) {
          System.out.println(" There aren't any results for your query.");
        }
    
        while (iteratorSearchResults.hasNext()) {
    
          SearchResult singleVideo = iteratorSearchResults.next();
          ResourceId rId = singleVideo.getId();
    
          // Double checks the kind is video.
          if (rId.getKind().equals("youtube#video")) {
            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
    
            System.out.println(" Video Id" + rId.getVideoId());
            System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
            System.out.println(" Thumbnail: " + thumbnail.getUrl());
            System.out.println("\n-------------------------------------------------------------\n");
          }
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-search-sample</artifactId>
      <version>1.0</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-search-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_search_sample.Search</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

トピックで検索

次のコード サンプルでは、Freebase API と YouTube Data API を使用して検索結果を取得します。コードは最初に Freebase API を使用してユーザーが入力したクエリに一致するトピックのリストを取得します。続いてユーザーがトピックを選択します。コードは API の search.list メソッドを呼び出し、そのトピックに関連する YouTube 動画を取得します。

  • Topics.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the
     * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
     * express or implied. See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample;
    
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpRequest;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.api.services.youtube.model.SearchListResponse;
    import com.google.api.services.youtube.model.SearchResult;
    import com.google.api.services.youtube.model.Thumbnail;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.codehaus.jackson.JsonNode;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.node.ArrayNode;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Properties;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * Demo of a semantic YouTube search getting a topic and search term from the user.  The class
     * calls the Freebase API to get a topics id based on user input, then passes that id along with
     * another user query term to the YouTube APIs.  The result is a list of videos based on a
     * semantic search.
     *
     * @author Jeremy Walker
     */
    public class Topics {
    
      /** Global instance properties filename. */
      private static String PROPERTIES_FILENAME = "youtube.properties";
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of the max number of videos we want returned. */
      private static final long NUMBER_OF_VIDEOS_RETURNED = 5;
    
      /** Global instance of the max number of topics we want returned. */
      private static final long NUMBER_OF_TOPICS_RETURNED = 5;
    
      /** Global instance of Youtube object to make all API requests. */
      private static YouTube youtube;
    
      /**
       * Method kicks off a search via the Freebase API for a topics id.  It initializes a YouTube
       * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the
       * search more specific.  The program then prints the names and thumbnails of each of the videos
       * (only first 5 videos).  Please note, user input is taken for both search on Freebase and on
       * YouTube.
       *
       * @param args command line args not used.
      */
      public static void main( String[] args ) {
        // Read the developer key from youtube.properties
        Properties properties = new Properties();
        try {
          InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
          properties.load(in);
    
        } catch (IOException e) {
          System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
              + " : " + e.getMessage());
          System.exit(1);
        }
    
    
        try {
          // Gets a topic id via the Freebase API based on user input.
          String topicsId = getTopicId();
          if(topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
          }
    
          /*
           * Get query term from user.  The "search" parameter is just used as output to clarify that
           * we want a "search" term (vs. a "topics" term).
           */
          String queryTerm = getInputQuery("search");
    
          /*
           * The YouTube object is used to make all API requests.  The last argument is required, but
           * because we don't need anything initialized when the HttpRequest is initialized, we
           * override the interface and provide a no-op function.
           */
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
              public void initialize(HttpRequest request) throws IOException {}})
            .setApplicationName("youtube-cmdline-search-sample")
            .build();
    
          YouTube.Search.List search = youtube.search().list("id,snippet");
          /*
           * It is important to set your developer key from the Google Developer Console for
           * non-authenticated requests (found under the API Access tab at this link:
           * code.google.com/apis/). This is good practice and increases your quota.
           */
          String apiKey = properties.getProperty("youtube.apikey");
          search.setKey(apiKey);
          search.setQ(queryTerm);
          if(topicsId.length() > 0) {
            search.setTopicId(topicsId);
          }
    
          /*
           * We are only searching for videos (not playlists or channels).  If we were searching for
           * more, we would add them as a string like this: "video,playlist,channel".
           */
          search.setType("video");
          /*
           * This method reduces the info returned to only the fields we need.  It makes things more
           * efficient, because we are transmitting less data.
           */
          search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
          search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
          SearchListResponse searchResponse = search.execute();
    
          List<SearchResult> searchResultList = searchResponse.getItems();
    
          if(searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
          } else {
            System.out.println("There were no results for your query.");
          }
        } catch (GoogleJsonResponseException e) {
          System.err.println("There was a service error: " + e.getDetails().getCode() +
              " : " + e.getDetails().getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
          e.printStackTrace();
        }
      }
    
      /*
       * Returns a query term (String) from user via the terminal.
       *
       * @param searchCategory This is for output to the user to clariy what info we need from them.
       */
      private static String getInputQuery(String searchCategory) throws IOException {
    
        String inputQuery = "";
    
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
    
        do {
          System.out.print("Please enter a " + searchCategory + " term: ");
          inputQuery = bReader.readLine();
        } while(inputQuery.length() < 1);
    
        return inputQuery;
      }
    
      /**
       * The Java Freebase client library does not include search functionality, so we created a call
       * directly via URL.  We use jackson functionality to put the JSON response into a POJO (Plain
       * Old Java Object).  The additional classes to create the object from JSON were created based on
       * the JSON response to make it easier to get the values we need.  For more info on jackson
       * classes, please search on the term.
       */
      private static String getTopicId() throws IOException {
    
        /*
         * Returned as an empty string if we can't find a matching topicsId or there aren't any
         * results available.
         */
        String topicsId = "";
    
        /*
         * Get query term from user.  The "topics" parameter is just used as output to clarify that
         * we want a "topics" term (vs. a general "search" term).
         */
        String topicQuery = getInputQuery("topics");
    
        /*
         * Again, there isn't search functionality in the Freebase Java Library, so we have to call
         * directly against the URL.  Below we construct the proper URL, then use jackson classes to
         * convert the JSON into an object for reading.  You can find out more about the search calls
         * here: http://wiki.freebase.com/wiki/ApiSearch.
         */
        HttpClient httpclient = new DefaultHttpClient();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("query", topicQuery));
        params.add(new BasicNameValuePair("limit", Long.toString(NUMBER_OF_TOPICS_RETURNED)));
    
        String serviceURL = "https://www.googleapis.com/freebase/v1/search";
        String url = serviceURL + "?" + URLEncodedUtils.format(params, "UTF-8");
    
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        HttpEntity entity = httpResponse.getEntity();
    
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
              /*
               * Converts JSON to a Tree.  I could have specified extra classes and done an exact map
               * from JSON to POJO, but I was trying to keep the sample within one Java file.  If the
               * .get() function calls here and in getUserChoice() aren't your cup of tea, feel free
               * to create those classes and use them with the mapper.readValue() function.
               */
              ObjectMapper mapper = new ObjectMapper();
              JsonNode rootNode = mapper.readValue(instream, JsonNode.class);
    
              // Check that the response is valid.
              if(rootNode.get("status").asText().equals("200 OK")) {
                // I know the "result" field contains the list of results I need.
                ArrayNode arrayNodeResults = (ArrayNode) rootNode.get("result");
                // Only place we set the topicsId for a valid selection in this function.
                topicsId = getUserChoice(arrayNodeResults);
              }
            } finally {
              instream.close();
            }
        }
        return topicsId;
      }
    
      /**
       * Outputs topic search results to the user, records user selection, and returns topic id.
       *
       * @param freebaseResults ArrayNode object representing results of search.
       */
      private static String getUserChoice(ArrayNode freebaseResults) throws IOException {
    
        String freebaseId = "";
    
        if(freebaseResults.size() < 1) {
          return freebaseId;
        }
    
        for(int i = 0; i < freebaseResults.size(); i++) {
          JsonNode node = freebaseResults.get(i);
          System.out.print(" " + i + " = " + node.get("name").asText());
          if(node.get("notable") != null) {
            System.out.print(" (" + node.get("notable").get("name").asText() + ")");
          }
          System.out.println("");
        }
    
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        String inputChoice;
    
        do {
          System.out.print("Choose the number of the Freebase Node: ");
          inputChoice = bReader.readLine();
        } while (!isValidIntegerSelection(inputChoice, freebaseResults.size()));
    
        // Returns Topic id needed for YouTube Search.
        JsonNode node = freebaseResults.get(Integer.parseInt(inputChoice));
        freebaseId = node.get("mid").asText();
        return freebaseId;
      }
    
      /**
       * Checks if string contains a valid, positive integer that is less than max.  Please note, I am
       * not testing the upper limit of an integer (2,147,483,647).  I just go up to 999,999,999.
       *
       * @param input String to test.
       * @param max Integer must be less then this Maximum number.
       */
      public static boolean isValidIntegerSelection(String input, int max) {
        if (input.length() > 9)
          return false;
    
        boolean validNumber = false;
        // Only accepts positive numbers of up to 9 numbers.
        Pattern intsOnly = Pattern.compile("^\\d{1,9}$");
        Matcher makeMatch = intsOnly.matcher(input);
    
        if(makeMatch.find()){
          int number = Integer.parseInt(makeMatch.group());
          if((number >= 0) && (number < max)) {
            validNumber = true;
          }
        }
        return validNumber;
      }
    
      /*
       * Prints out all SearchResults in the Iterator.  Each printed line includes title, id, and
       * thumbnail.
       *
       * @param iteratorSearchResults Iterator of SearchResults to print
       * @param query Search query (String)
       */
      private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query, String topicsId) {
    
        System.out.println("\n=============================================================");
        System.out.println("   First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\" with Topics id: " + topicsId + ".");
        System.out.println("=============================================================\n");
    
        if(!iteratorSearchResults.hasNext()) {
          System.out.println(" There aren't any results for your query.");
        }
    
        while(iteratorSearchResults.hasNext()) {
    
          SearchResult singleVideo = iteratorSearchResults.next();
          ResourceId rId = singleVideo.getId();
    
          // Double checks the kind is video.
          if(rId.getKind().equals("youtube#video")) {
            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
    
            System.out.println(" Video Id" + rId.getVideoId());
            System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
            System.out.println(" Thumbnail: " + thumbnail.getUrl());
            System.out.println("\n-------------------------------------------------------------\n");
          }
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-topics-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-topics-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
        <repository>
          <id>codehaus</id>
          <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
      </repositories>
    
      <dependencies>
        <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
          <version>1.9.4</version>
        </dependency>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
      </dependencies>
    
        <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

チャンネル登録の追加

次のコード サンプルでは、API の subscriptions.insert メソッドを呼び出し、指定したチャンネルに登録を追加します。

  • AddSubscription.java

    /*
     * Copyright (c) 2013 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addsubscription_sample;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    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.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.api.services.youtube.model.Subscription;
    import com.google.api.services.youtube.model.SubscriptionSnippet;
    import com.google.common.collect.Lists;
    
    /**
     * Demo of subscribing user to a channel using the YouTube Data API (V3) with OAuth2 for
     * authorization.
     *
     * @author Ibrahim Ulukaya
     */
    public class AddSubscription {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of Youtube object to make all API requests. */
      private static YouTube youtube;
    
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run youtube upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, AddSubscription.class.getResourceAsStream("/client_secrets.json"));
    
        // 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://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-uploadvideo-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-uploadvideo.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .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");
      }
    
      /**
       * Subscribes user's YouTube account to a user selected channel using OAuth2 for authentication.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // An OAuth 2 access scope that allows for full read/write access.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-addsubscription-sample").build();
    
          // We get the user selected channel to subscribe.
          String channelId = getChannelId();
          System.out.println("You chose " + channelId + " to subscribe.");
    
          // We create a resourceId with channel id.
          ResourceId resourceId = new ResourceId();
          resourceId.setChannelId(channelId);
          resourceId.setKind("youtube#channel");
    
          // We create a snippet with ResourceId.
          SubscriptionSnippet snippet = new SubscriptionSnippet();
          snippet.setResourceId(resourceId);
    
          // We create a subscription request with snippet.
          Subscription subscription = new Subscription();
          subscription.setSnippet(snippet);
    
          /*
           * The subscription insert command includes: 1. Information we want returned after file is
           * successfully uploaded. 2. Subscription metadata we want to insert.
           */
          YouTube.Subscriptions.Insert subscriptionInsert =
              youtube.subscriptions().insert("snippet,contentDetails", subscription);
    
          // Execute subscription.
          Subscription returnedSubscription = subscriptionInsert.execute();
    
          // Print out returned results.
          System.out.println("\n================== Returned Subscription ==================\n");
          System.out.println("  - Id: " + returnedSubscription.getId());
          System.out.println("  - Title: " + returnedSubscription.getSnippet().getTitle());
    
        } catch (GoogleJsonResponseException e) {
          System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
          e.printStackTrace();
    
        } catch (IOException e) {
          System.err.println("IOException: " + e.getMessage());
          e.printStackTrace();
        } catch (Throwable t) {
          System.err.println("Throwable: " + t.getMessage());
          t.printStackTrace();
        }
      }
    
      /*
       * Returns a channel id (String) from user via the terminal.
       */
      private static String getChannelId() throws IOException {
    
        String channelId = "";
    
        System.out.print("Please enter a channel id: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        channelId = bReader.readLine();
    
        if (channelId.length() < 1) {
          // If nothing is entered, defaults to "YouTube For Developers."
          channelId = "UCtVd0c0tGXuTSbU5d8cSBUg";
        }
        return channelId;
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-addsubscription-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-addsubscription-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev16-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.oauth.version>1.12.0-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addsubscription_sample.AddSubscription</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter Client ID",
        "client_secret": "Enter Client Secret"
      }
    }
    

動画をアップロード

次のコード サンプルでは、API の videos.insert メソッドを呼び出し、リクエストに関連付けられているチャンネルに動画をアップロードします。

  • UploadVideo.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_uploadvideo_sample;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FilenameFilter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    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.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Video;
    import com.google.api.services.youtube.model.VideoSnippet;
    import com.google.api.services.youtube.model.VideoStatus;
    import com.google.common.collect.Lists;
    
    /**
     * Demo of uploading a video to a user's account using the YouTube Data API (V3) with OAuth2 for
     * authorization.
     *
     *  TODO: PLEASE NOTE, YOU MUST ADD YOUR VIDEO FILES TO THE PROJECT FOLDER TO UPLOAD THEM WITH THIS
     * APPLICATION!
     *
     * @author Jeremy Walker
     */
    public class UploadVideo {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of Youtube object to make all API requests. */
      private static YouTube youtube;
    
      /* Global instance of the format used for the video being uploaded (MIME type). */
      private static String VIDEO_FILE_FORMAT = "video/*";
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run youtube upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, UploadVideo.class.getResourceAsStream("/client_secrets.json"));
    
        // 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://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-uploadvideo-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-uploadvideo.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .build();
    
        // Build the local server and bind it to port 9000
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Uploads user selected video in the project folder to the user's YouTube account using OAuth2
       * for authentication.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // Scope required to upload to YouTube.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-uploadvideo-sample").build();
    
          // We get the user selected local video file to upload.
          File videoFile = getVideoFromUser();
          System.out.println("You chose " + videoFile + " to upload.");
    
          // Add extra information to the video before uploading.
          Video videoObjectDefiningMetadata = new Video();
    
          /*
           * Set the video to public, so it is available to everyone (what most people want). This is
           * actually the default, but I wanted you to see what it looked like in case you need to set
           * it to "unlisted" or "private" via API.
           */
          VideoStatus status = new VideoStatus();
          status.setPrivacyStatus("public");
          videoObjectDefiningMetadata.setStatus(status);
    
          // We set a majority of the metadata with the VideoSnippet object.
          VideoSnippet snippet = new VideoSnippet();
    
          /*
           * The Calendar instance is used to create a unique name and description for test purposes, so
           * you can see multiple files being uploaded. You will want to remove this from your project
           * and use your own standard names.
           */
          Calendar cal = Calendar.getInstance();
          snippet.setTitle("Test Upload via Java on " + cal.getTime());
          snippet.setDescription(
              "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
    
          // Set your keywords.
          List<String> tags = new ArrayList<String>();
          tags.add("test");
          tags.add("example");
          tags.add("java");
          tags.add("YouTube Data API V3");
          tags.add("erase me");
          snippet.setTags(tags);
    
          // Set completed snippet to the video object.
          videoObjectDefiningMetadata.setSnippet(snippet);
    
          InputStreamContent mediaContent = new InputStreamContent(
              VIDEO_FILE_FORMAT, new BufferedInputStream(new FileInputStream(videoFile)));
          mediaContent.setLength(videoFile.length());
    
          /*
           * The upload command includes: 1. Information we want returned after file is successfully
           * uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself.
           */
          YouTube.Videos.Insert videoInsert = youtube.videos()
              .insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
    
          // Set the upload type and add event listener.
          MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
    
          /*
           * Sets whether direct media upload is enabled or disabled. True = whole media content is
           * uploaded in a single request. False (default) = resumable media upload protocol to upload
           * in data chunks.
           */
          uploader.setDirectUploadEnabled(false);
    
          MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
              switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                  System.out.println("Initiation Started");
                  break;
                case INITIATION_COMPLETE:
                  System.out.println("Initiation Completed");
                  break;
                case MEDIA_IN_PROGRESS:
                  System.out.println("Upload in progress");
                  System.out.println("Upload percentage: " + uploader.getProgress());
                  break;
                case MEDIA_COMPLETE:
                  System.out.println("Upload Completed!");
                  break;
                case NOT_STARTED:
                  System.out.println("Upload Not Started!");
                  break;
              }
            }
          };
          uploader.setProgressListener(progressListener);
    
          // Execute upload.
          Video returnedVideo = videoInsert.execute();
    
          // Print out returned results.
          System.out.println("\n================== Returned Video ==================\n");
          System.out.println("  - Id: " + returnedVideo.getId());
          System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
          System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
          System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
          System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    
        } catch (GoogleJsonResponseException e) {
          System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          System.err.println("IOException: " + e.getMessage());
          e.printStackTrace();
        } catch (Throwable t) {
          System.err.println("Throwable: " + t.getMessage());
          t.printStackTrace();
        }
      }
    
      /**
       * Gets the user selected local video file to upload.
       */
      private static File getVideoFromUser() throws IOException {
        File[] listOfVideoFiles = getLocalVideoFiles();
        return getUserChoice(listOfVideoFiles);
      }
    
      /**
       * Gets an array of videos in the current directory.
       */
      private static File[] getLocalVideoFiles() throws IOException {
    
        File currentDirectory = new File(".");
        System.out.println("Video files from " + currentDirectory.getAbsolutePath() + ":");
    
        // Filters out video files. This list of video extensions is not comprehensive.
        FilenameFilter videoFilter = new FilenameFilter() {
          public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".webm") || lowercaseName.endsWith(".flv")
                || lowercaseName.endsWith(".f4v") || lowercaseName.endsWith(".mov")
                || lowercaseName.endsWith(".mp4")) {
              return true;
            } else {
              return false;
            }
          }
        };
        return currentDirectory.listFiles(videoFilter);
      }
    
      /**
       * Outputs video file options to the user, records user selection, and returns the video (File
       * object).
       *
       * @param videoFiles Array of video File objects
       */
      private static File getUserChoice(File videoFiles[]) throws IOException {
    
        if (videoFiles.length < 1) {
          throw new IllegalArgumentException("No video files in this directory.");
        }
    
        for (int i = 0; i < videoFiles.length; i++) {
          System.out.println(" " + i + " = " + videoFiles[i].getName());
        }
    
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        String inputChoice;
    
        do {
          System.out.print("Choose the number of the video file you want to upload: ");
          inputChoice = bReader.readLine();
        } while (!isValidIntegerSelection(inputChoice, videoFiles.length));
    
        return videoFiles[Integer.parseInt(inputChoice)];
      }
    
      /**
       * Checks if string contains a valid, positive integer that is less than max. Please note, I am
       * not testing the upper limit of an integer (2,147,483,647). I just go up to 999,999,999.
       *
       * @param input String to test.
       * @param max Integer must be less then this Maximum number.
       */
      public static boolean isValidIntegerSelection(String input, int max) {
        if (input.length() > 9) return false;
    
        boolean validNumber = false;
        // Only accepts positive numbers of up to 9 numbers.
        Pattern intsOnly = Pattern.compile("^\\d{1,9}$");
        Matcher makeMatch = intsOnly.matcher(input);
    
        if (makeMatch.find()) {
          int number = Integer.parseInt(makeMatch.group());
          if ((number >= 0) && (number < max)) {
            validNumber = true;
          }
        }
        return validNumber;
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-uploadvideo-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-uploadvideo-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev24-1.13.2-beta</project.youtube.version>
        <project.http.version>1.13.1-beta</project.http.version>
        <project.oauth.version>1.13.1-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_uploadvideo_sample.UploadVideo</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter Client ID",
        "client_secret": "Enter Client Secret"
      }
    }
    

動画の更新

次のコード サンプルでは、API の videos.update メソッドを呼び出し、リクエストを承認するチャンネルが所有する動画を更新します。

  • UpdateVideo.java

    /*
     * Copyright (c) 2013 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_updatevideo_sample;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
    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.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Video;
    import com.google.api.services.youtube.model.VideoListResponse;
    import com.google.api.services.youtube.model.VideoSnippet;
    import com.google.common.collect.Lists;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Demo of updating a video by adding a tag, using the YouTube Data API (V3) with OAuth2 for
     * authorization.
     *
     * @author Ibrahim Ulukaya
     */
    public class UpdateVideo {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run YouTube upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, UpdateVideo.class.getResourceAsStream("/client_secrets.json"));
    
        // 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://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-updatevideo-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-updatevideo.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .build();
    
        // Build the local server and bind it to port 9000
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Uploads user selected video in the project folder to the user's YouTube account using OAuth2
       * for authentication.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // An OAuth 2 access scope that allows for full read/write access.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-updatevideo-sample").build();
    
          // Get the user selected video Id.
          String videoId = getVideoIdFromUser();
          System.out.println("You chose " + videoId + " to update.");
    
          // Get the user selected tag for video.
          String tag = getTagFromUser();
          System.out.println("You chose " + tag + " as a tag.");
    
          // Create the video list request
          YouTube.Videos.List listVideosRequest = youtube.videos().list(videoId, "snippet");
    
          // Request is executed and video list response is returned
          VideoListResponse listResponse = listVideosRequest.execute();
    
          List<Video> videoList = listResponse.getItems();
          if (videoList.isEmpty()) {
            System.out.println("Can't find a video with video id: " + videoId);
            return;
          }
    
          // Since a unique video id is given, it will only return 1 video.
          Video video = videoList.get(0);
          VideoSnippet snippet = video.getSnippet();
    
          List<String> tags = snippet.getTags();
    
          // getTags() returns null if the video didn't have any tags, so we will check for this and
          // create a new list if needed
          if (tags == null) {
            tags = new ArrayList<String>(1);
            snippet.setTags(tags);
          }
          tags.add(tag);
    
          // Create the video update request
          YouTube.Videos.Update updateVideosRequest = youtube.videos().update("snippet", video);
    
          // Request is executed and updated video is returned
          Video videoResponse = updateVideosRequest.execute();
    
          // Print out returned results.
          System.out.println("\n================== Returned Video ==================\n");
          System.out.println("  - Title: " + videoResponse.getSnippet().getTitle());
          System.out.println("  - Tags: " + videoResponse.getSnippet().getTags());
    
        } catch (GoogleJsonResponseException e) {
          System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          System.err.println("IOException: " + e.getMessage());
          e.printStackTrace();
        } catch (Throwable t) {
          System.err.println("Throwable: " + t.getMessage());
          t.printStackTrace();
        }
      }
    
      /*
       * Prompts for a tag from standard input and returns it.
       */
      private static String getTagFromUser() throws IOException {
    
        String title = "";
    
        System.out.print("Please enter a tag for your video: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        title = bReader.readLine();
    
        if (title.length() < 1) {
          // If nothing is entered, defaults to "New Tag"
          title = "New Tag";
        }
        return title;
      }
    
      /*
       * Prompts for a video ID from standard input and returns it.
       */
      private static String getVideoIdFromUser() throws IOException {
    
        String title = "";
    
        System.out.print("Please enter a video Id to update: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        title = bReader.readLine();
    
        if (title.length() < 1) {
          // If nothing is entered, exits
          System.out.print("Video Id can't be empty!");
          System.exit(1);
        }
    
        return title;
      }
    
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-updatevideo-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-updatevideo-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev24-1.13.2-beta</project.youtube.version>
        <project.http.version>1.13.1-beta</project.http.version>
        <project.oauth.version>1.13.1-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_updatevideo_sample.UpdateVideo</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter Client ID",
        "client_secret": "Enter Client Secret"
      }
    }