Inital commit
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
Google YouTube Data API Java Samples - README.txt
|
||||
-------------------------------------------------
|
||||
|
||||
The Java YouTube samples are simple applications that show sample usage
|
||||
of the various feeds that comprise the YouTube Data API. One of the samples
|
||||
is a readonly sample that allows anonymous searching of the feeds. The other
|
||||
sample is an authenticated sample that performs write or upload operations
|
||||
on behalf of a user.
|
||||
|
||||
The application can be built and run using the provided Ant build file found at
|
||||
gdata/java/build-samples.xml. The sample can be run in the following manner:
|
||||
|
||||
1. Invoke the samples using the appropriate commandline:
|
||||
|
||||
ant -f gdata/java/build-samples.xml sample.youtube.read.run
|
||||
|
||||
or
|
||||
|
||||
ant -f gdata/java/build-samples.xml sample.youtube.write.run
|
||||
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/* Copyright (c) 2008 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 sample.youtube;
|
||||
|
||||
import com.google.gdata.client.Query;
|
||||
import sample.util.SimpleCommandLineParser;
|
||||
import com.google.gdata.client.youtube.YouTubeService;
|
||||
import com.google.gdata.data.youtube.VideoEntry;
|
||||
import com.google.gdata.data.youtube.VideoFeed;
|
||||
import com.google.gdata.util.AuthenticationException;
|
||||
import com.google.gdata.util.ServiceException;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintStream;
|
||||
import java.net.URL;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Demo of partial response and partial patch to change keywords on uploaded
|
||||
* videos.
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class YouTubePartialDemo {
|
||||
|
||||
/**
|
||||
* Feed url for user uploaded videos.
|
||||
*/
|
||||
public static final String UPLOADS_URL =
|
||||
"http://gdata.youtube.com/feeds/api/users/default/uploads";
|
||||
|
||||
/**
|
||||
* Input stream for reading user input.
|
||||
*/
|
||||
private static final BufferedReader bufferedReader = new BufferedReader(
|
||||
new InputStreamReader(System.in));
|
||||
|
||||
/** Steam to print status messages to. */
|
||||
private final PrintStream output;
|
||||
|
||||
/** Constructor */
|
||||
private YouTubePartialDemo(PrintStream out) {
|
||||
this.output = out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the usage of how to run the sample from the command-line.
|
||||
*/
|
||||
private static void printUsage() {
|
||||
System.out.println("Usage: java YouTubePartialDemo.jar "
|
||||
+ " --username <user@gmail.com> " + " --password <pass> "
|
||||
+ " --key <developer key>");
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a menu of the main activities a user can perform.
|
||||
*/
|
||||
private void printMenu() {
|
||||
System.out.println("\n");
|
||||
System.out.println("Choose one of the following demo options:");
|
||||
System.out.println("\t1) Retrieve My uploaded videos with keywords");
|
||||
System.out.println("\t2) Update keywords for an uploaded video");
|
||||
System.out.println("\t0) Exit");
|
||||
System.out.println("\nEnter Number (0-2): ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input.
|
||||
*
|
||||
* @throws IOException If unable to read a line from the standard input.
|
||||
* @return A line of text read from the standard input.
|
||||
*/
|
||||
private static String readLine() throws IOException {
|
||||
return bufferedReader.readLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input and returns the parsed
|
||||
* integer representation.
|
||||
*
|
||||
* @throws IOException If unable to read a line from the standard input.
|
||||
* @return An integer read from the standard input.
|
||||
*/
|
||||
private static int readInt() throws IOException {
|
||||
String input = readLine();
|
||||
|
||||
try {
|
||||
return Integer.parseInt(input);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Print title, url of user's videos.
|
||||
*/
|
||||
private void printVideos(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
|
||||
Query query = new Query(new URL(UPLOADS_URL));
|
||||
query.setFields("title,entry(title, media:group/media:player)");
|
||||
VideoFeed videoFeed = service.query(query, VideoFeed.class);
|
||||
|
||||
output.println(videoFeed.getTitle() + ":");
|
||||
int count = 1;
|
||||
for (VideoEntry entry : videoFeed.getEntries()) {
|
||||
output.println(count + ") "
|
||||
+ entry.getTitle().getPlainText() + ": "
|
||||
+ entry.getMediaGroup().getPlayer().getUrl());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Solicits the user for a video ID (hash) or tries to figure one out
|
||||
* from the video's watch URL.
|
||||
*
|
||||
* @return String containing a video ID.
|
||||
* @throws IOException If there are problems reading user input.
|
||||
*/
|
||||
private static String readVideoID() throws IOException {
|
||||
System.out.println(
|
||||
"Input a valid video ID or a watch URL :");
|
||||
|
||||
String input = readLine();
|
||||
if (input.equals("")) {
|
||||
throw new IOException("Invalid video id");
|
||||
}
|
||||
|
||||
Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
|
||||
Matcher m = p.matcher(input);
|
||||
|
||||
if (m.matches()) {
|
||||
input = m.group(1);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates keywords associated with a selected video.
|
||||
*/
|
||||
private void updateVideoKeywords(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
// Identify video to update
|
||||
output.println("First choose a video to update:");
|
||||
String videoID = readVideoID();
|
||||
URL entryUrl = new URL(UPLOADS_URL + "/" + videoID);
|
||||
|
||||
// Select fields to update
|
||||
String fields = "@gd:etag,media:group/media:keywords";
|
||||
Query query = new Query(entryUrl);
|
||||
query.setFields(fields);
|
||||
|
||||
// Get representation for the interested fields
|
||||
VideoEntry videoEntry = null;
|
||||
try {
|
||||
videoEntry = service.getEntry(query.getUrl(), VideoEntry.class);
|
||||
} catch (ServiceException se) {
|
||||
// an invalid video ID was used.
|
||||
}
|
||||
if (videoEntry == null) {
|
||||
output.println("Sorry, the video ID you entered was not valid.\n");
|
||||
return;
|
||||
}
|
||||
output.println("Current Keywords: "
|
||||
+ videoEntry.getMediaGroup().getKeywords().getKeywords());
|
||||
|
||||
// add a new keyword
|
||||
output.println("Specify a keyword to add: ");
|
||||
String keyword = readLine();
|
||||
videoEntry.getMediaGroup().getKeywords().addKeyword(keyword);
|
||||
VideoEntry updatedEntry = service.patch(entryUrl, fields, videoEntry);
|
||||
output.println("Keywords after update: "
|
||||
+ updatedEntry.getMediaGroup().getKeywords().getKeywords());
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException, ServiceException {
|
||||
SimpleCommandLineParser parser = new SimpleCommandLineParser(args);
|
||||
String username = parser.getValue("username", "user", "u");
|
||||
String password = parser.getValue("password", "pass", "p");
|
||||
String developerKey = parser.getValue("key", "k");
|
||||
boolean help = parser.containsKey("help", "h");
|
||||
|
||||
if (help || username == null || password == null || developerKey == null) {
|
||||
printUsage();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
YouTubeService service = new YouTubeService("gdata-YTPartialDemo-1",
|
||||
developerKey);
|
||||
|
||||
try {
|
||||
service.setUserCredentials(username, password);
|
||||
} catch (AuthenticationException e) {
|
||||
System.out.println("Invalid login credentials.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
YouTubePartialDemo demo = new YouTubePartialDemo(System.out);
|
||||
while (true) {
|
||||
try {
|
||||
demo.printMenu();
|
||||
int choice = readInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
// Prints out the user's uploaded videos
|
||||
demo.printVideos(service);
|
||||
break;
|
||||
case 2:
|
||||
demo.updateVideoKeywords(service);
|
||||
break;
|
||||
case 0:
|
||||
System.exit(1);
|
||||
break;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Communications error
|
||||
System.err.println(
|
||||
"There was a problem communicating with the service.");
|
||||
e.printStackTrace();
|
||||
} catch (ServiceException e) {
|
||||
// Server side error
|
||||
System.err.println("The server had a problem handling your request.");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,782 @@
|
||||
/* Copyright (c) 2008 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 sample.youtube;
|
||||
|
||||
import com.google.gdata.client.Query;
|
||||
import com.google.gdata.client.Service;
|
||||
import com.google.gdata.client.youtube.YouTubeQuery;
|
||||
import com.google.gdata.client.youtube.YouTubeService;
|
||||
import com.google.gdata.data.Category;
|
||||
import com.google.gdata.data.Entry;
|
||||
import com.google.gdata.data.Feed;
|
||||
import com.google.gdata.data.TextContent;
|
||||
import com.google.gdata.data.extensions.Comments;
|
||||
import com.google.gdata.data.extensions.FeedLink;
|
||||
import com.google.gdata.data.media.mediarss.MediaKeywords;
|
||||
import com.google.gdata.data.media.mediarss.MediaPlayer;
|
||||
import com.google.gdata.data.media.mediarss.MediaThumbnail;
|
||||
import com.google.gdata.data.youtube.FeedLinkEntry;
|
||||
import com.google.gdata.data.youtube.PlaylistEntry;
|
||||
import com.google.gdata.data.youtube.PlaylistFeed;
|
||||
import com.google.gdata.data.youtube.PlaylistLinkEntry;
|
||||
import com.google.gdata.data.youtube.PlaylistLinkFeed;
|
||||
import com.google.gdata.data.youtube.SubscriptionEntry;
|
||||
import com.google.gdata.data.youtube.SubscriptionFeed;
|
||||
import com.google.gdata.data.youtube.UserProfileEntry;
|
||||
import com.google.gdata.data.youtube.VideoEntry;
|
||||
import com.google.gdata.data.youtube.VideoFeed;
|
||||
import com.google.gdata.data.youtube.YouTubeMediaContent;
|
||||
import com.google.gdata.data.youtube.YouTubeMediaGroup;
|
||||
import com.google.gdata.data.youtube.YouTubeNamespace;
|
||||
import com.google.gdata.util.ServiceException;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Demonstrates basic Youtube Data API operations using the Java client library:
|
||||
* <ol>
|
||||
* <li> Retrieving standard Youtube feeds
|
||||
* <li> Searching a feed
|
||||
* <li> Searching a feed using categories and keywords
|
||||
* <li> Retrieving a user's uploaded videos
|
||||
* <li> Retrieve a user's favorite videos
|
||||
* <li> Retrieve responses for a video
|
||||
* <li> Retrieve comments for a video
|
||||
* <li> Retrieve a list of a user's playlists
|
||||
* <li> Retrieve a playlist
|
||||
* <li> Retrieve a list of a user's subscriptions
|
||||
* <li> Retrieve a user's profile
|
||||
* </ol>
|
||||
*/
|
||||
public class YouTubeReadonlyClient {
|
||||
|
||||
/**
|
||||
* Input stream for reading user input.
|
||||
*/
|
||||
private static final BufferedReader bufferedReader = new BufferedReader(
|
||||
new InputStreamReader(System.in));
|
||||
|
||||
/**
|
||||
* The name of the server hosting the YouTube GDATA feeds
|
||||
*/
|
||||
public static final String YOUTUBE_GDATA_SERVER = "http://gdata.youtube.com";
|
||||
|
||||
/**
|
||||
* The prefix common to all standard feeds
|
||||
*/
|
||||
public static final String STANDARD_FEED_PREFIX = YOUTUBE_GDATA_SERVER
|
||||
+ "/feeds/api/standardfeeds/";
|
||||
|
||||
/**
|
||||
* The URL of the "Most Recent" feed
|
||||
*/
|
||||
public static final String MOST_RECENT_FEED = STANDARD_FEED_PREFIX
|
||||
+ "most_recent";
|
||||
|
||||
/**
|
||||
* The URL of the "Top Rated" feed
|
||||
*/
|
||||
public static final String TOP_RATED_FEED = STANDARD_FEED_PREFIX
|
||||
+ "top_rated";
|
||||
|
||||
/**
|
||||
* The URL of the "Most Viewed" feed
|
||||
*/
|
||||
public static final String MOST_VIEWED_FEED = STANDARD_FEED_PREFIX
|
||||
+ "most_viewed";
|
||||
|
||||
/**
|
||||
* The URL of the "Recently Featured" feed
|
||||
*/
|
||||
public static final String RECENTLY_FEATURED_FEED = STANDARD_FEED_PREFIX
|
||||
+ "recently_featured";
|
||||
|
||||
/**
|
||||
* The URL of the "Watch On Mobile" feed
|
||||
*/
|
||||
public static final String WATCH_ON_MOBILE_FEED = STANDARD_FEED_PREFIX
|
||||
+ "watch_on_mobile";
|
||||
|
||||
/**
|
||||
* The URL of the "Videos" feed
|
||||
*/
|
||||
public static final String VIDEOS_FEED = YOUTUBE_GDATA_SERVER
|
||||
+ "/feeds/api/videos";
|
||||
|
||||
/**
|
||||
* The prefix of the User Feeds
|
||||
*/
|
||||
public static final String USER_FEED_PREFIX = YOUTUBE_GDATA_SERVER
|
||||
+ "/feeds/api/users/";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's uploads feed
|
||||
*/
|
||||
public static final String UPLOADS_FEED_SUFFIX = "/uploads";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's favorites feed
|
||||
*/
|
||||
public static final String FAVORITES_FEED_SUFFIX = "/favorites";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's subscriptions feed
|
||||
*/
|
||||
public static final String SUBSCRIPTIONS_FEED_SUFFIX = "/subscriptions";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's playlists feed
|
||||
*/
|
||||
public static final String PLAYLISTS_FEED_SUFFIX = "/playlists";
|
||||
|
||||
/**
|
||||
* The default user if the user does not enter one.
|
||||
*/
|
||||
private static String defaultTestUser = "YTdebates";
|
||||
|
||||
/**
|
||||
* Prints a list of all standard feeds.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printStandardFeeds(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
printVideoFeed(service, MOST_VIEWED_FEED, false);
|
||||
printVideoFeed(service, TOP_RATED_FEED, false);
|
||||
printVideoFeed(service, RECENTLY_FEATURED_FEED, false);
|
||||
printVideoFeed(service, WATCH_ON_MOBILE_FEED, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a String, a newline, and a number of '-' characters equal to the
|
||||
* String's length.
|
||||
*
|
||||
* @param feedTitle - the title to print underlined
|
||||
*/
|
||||
private static void printUnderlined(String feedTitle) {
|
||||
System.out.println(feedTitle);
|
||||
for (int i = 0; i < feedTitle.length(); ++i) {
|
||||
System.out.print("-");
|
||||
}
|
||||
System.out.println("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a VideoEntry, optionally showing its responses and comment feeds.
|
||||
*
|
||||
* @param prefix a string to be shown before each entry
|
||||
* @param videoEntry the VideoEntry to be printed
|
||||
* @param showCommentsAndResponses true if the comments and responses feeds
|
||||
* should be printed
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the
|
||||
* request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printVideoEntry(String prefix, VideoEntry videoEntry,
|
||||
boolean showCommentsAndResponses) throws IOException, ServiceException {
|
||||
System.out.println(prefix);
|
||||
if (videoEntry.getTitle() != null) {
|
||||
System.out.printf("Title: %s\n", videoEntry.getTitle().getPlainText());
|
||||
}
|
||||
if (videoEntry.getSummary() != null) {
|
||||
System.out.printf("Summary: %s\n",
|
||||
videoEntry.getSummary().getPlainText());
|
||||
}
|
||||
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
|
||||
if(mediaGroup != null) {
|
||||
MediaPlayer mediaPlayer = mediaGroup.getPlayer();
|
||||
System.out.println("Web Player URL: " + mediaPlayer.getUrl());
|
||||
MediaKeywords keywords = mediaGroup.getKeywords();
|
||||
System.out.print("Keywords: ");
|
||||
for(String keyword : keywords.getKeywords()) {
|
||||
System.out.print(keyword + ",");
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("\tThumbnails:");
|
||||
for(MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
|
||||
System.out.println("\t\tThumbnail URL: " + mediaThumbnail.getUrl());
|
||||
System.out.println("\t\tThumbnail Time Index: " +
|
||||
mediaThumbnail.getTime());
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println("\tMedia:");
|
||||
for(YouTubeMediaContent mediaContent : mediaGroup.getYouTubeContents()) {
|
||||
System.out.println("\t\tMedia Location: "+mediaContent.getUrl());
|
||||
System.out.println("\t\tMedia Type: "+mediaContent.getType());
|
||||
System.out.println("\t\tDuration: " + mediaContent.getDuration());
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
if (showCommentsAndResponses) {
|
||||
printResponsesFeed(videoEntry);
|
||||
System.out.println("");
|
||||
printCommentsFeed(videoEntry);
|
||||
System.out.println("");
|
||||
System.out.println("");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the responses feed of a VideoEntry.
|
||||
*
|
||||
* @param videoEntry the VideoEntry whose responses are to be printed
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printResponsesFeed(VideoEntry videoEntry)
|
||||
throws IOException, ServiceException {
|
||||
if (videoEntry.getVideoResponsesLink() != null) {
|
||||
String videoResponsesFeedUrl =
|
||||
videoEntry.getVideoResponsesLink().getHref();
|
||||
System.out.println();
|
||||
printVideoFeed((YouTubeService) videoEntry.getService(),
|
||||
videoResponsesFeedUrl, false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the comments feed of a VideoEntry.
|
||||
*
|
||||
* @param videoEntry the VideoEntry whose comments are to be printed
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printCommentsFeed(VideoEntry videoEntry)
|
||||
throws IOException, ServiceException {
|
||||
Comments comments = videoEntry.getComments();
|
||||
if (comments != null && comments.getFeedLink() != null) {
|
||||
System.out.println("\tComments:");
|
||||
printFeed(videoEntry.getService(), comments.getFeedLink().getHref(),
|
||||
"Comment");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a basic feed, such as the comments or responses feed, retrieved from
|
||||
* a feedUrl.
|
||||
*
|
||||
* @param service a YouTubeService object
|
||||
* @param feedUrl the url of the feed
|
||||
* @param prefix a prefix string to be printed in front of each entry field
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printFeed(Service service, String feedUrl, String prefix)
|
||||
throws IOException, ServiceException {
|
||||
Feed feed = service.getFeed(new URL(feedUrl), Feed.class);
|
||||
|
||||
for (Entry e : feed.getEntries()) {
|
||||
printEntry(e, prefix);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a basic Entry, usually from a comments or responses feed.
|
||||
*
|
||||
* @param entry the entry to be printed
|
||||
* @param prefix a prefix to be printed before each entry attribute
|
||||
*/
|
||||
private static void printEntry(Entry entry, String prefix) {
|
||||
System.out.println("\t\t" + prefix + " Title: "
|
||||
+ entry.getTitle().getPlainText());
|
||||
if (entry.getContent() != null) {
|
||||
TextContent content = (TextContent) entry.getContent();
|
||||
System.out.println("\t\t" + prefix + " Content: "
|
||||
+ content.getContent().getPlainText());
|
||||
}
|
||||
System.out.println("\t\tURL: " + entry.getHtmlLink().getHref());
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a PlaylistEntry by retrieving the Description of the PlayList,
|
||||
* followed by the Titles and URLs of each entry in the feed.
|
||||
*
|
||||
* @param prefix a string to be printed before each entry
|
||||
* @param playlistLinkEntry the PlaylistEntry to be printed
|
||||
* @param showPlaylistContents if true, show the list of videos in the
|
||||
* playlist
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the
|
||||
* request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printPlaylistEntry(String prefix,
|
||||
PlaylistLinkEntry playlistLinkEntry, boolean showPlaylistContents)
|
||||
throws IOException, ServiceException {
|
||||
|
||||
System.out.println(prefix);
|
||||
System.out.printf("Description: %s\n", playlistLinkEntry.getSummary().getPlainText());
|
||||
if (showPlaylistContents) {
|
||||
printPlaylist(playlistLinkEntry.getService(), playlistLinkEntry.getFeedUrl());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a playlist feed as a series of Titles and URLs.
|
||||
*
|
||||
* @param service a YouTubeService object
|
||||
* @param playlistUrl the url of the playlist
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printPlaylist(Service service, String playlistUrl)
|
||||
throws IOException, ServiceException {
|
||||
PlaylistFeed playlistFeed = service.getFeed(new URL(playlistUrl),
|
||||
PlaylistFeed.class);
|
||||
if (playlistFeed != null) {
|
||||
for (PlaylistEntry e : playlistFeed.getEntries()) {
|
||||
System.out.println("\tPlaylist Entry: " + e.getTitle().getPlainText());
|
||||
System.out.println("\tPlaylist URL: " + e.getHtmlLink().getHref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a FeedLinkEntry as a Title and URL String.
|
||||
*
|
||||
* @param feedLinkEntry the FeedLinkEntry to be printed
|
||||
*/
|
||||
private static void printFeedLinkEntry(FeedLinkEntry feedLinkEntry) {
|
||||
if (feedLinkEntry.getTitle() != null) {
|
||||
System.out.printf("Title: %s\n", feedLinkEntry.getTitle().getPlainText());
|
||||
}
|
||||
System.out.println("FeedLink: " + feedLinkEntry.getFeedUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a SubscriptionEntry, which is a FeedLink entry.
|
||||
*
|
||||
* @param subEntry the SubscriptionEntry to be printed
|
||||
*/
|
||||
private static void printSubscriptionEntry(SubscriptionEntry subEntry) {
|
||||
printFeedLinkEntry(subEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input.
|
||||
* @throws IOException if unable to read a line from the standard input
|
||||
* @return a line of text read from the standard input
|
||||
*/
|
||||
private static String readLine() throws IOException {
|
||||
return bufferedReader.readLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input, and returns the parsed
|
||||
* integer representation.
|
||||
* @throws IOException if unable to read a line from the standard input
|
||||
* @return an integer read from the standard input
|
||||
*/
|
||||
private static int readInt() throws IOException {
|
||||
String input = readLine();
|
||||
return Integer.parseInt(input);
|
||||
}
|
||||
|
||||
private static void printUsage() {
|
||||
System.out.println("Choose one of the following demo options:");
|
||||
System.out.println("\t1) Print Standard Feeds");
|
||||
System.out.println("\t2) Print Search Feed");
|
||||
System.out.println("\t3) Print Keyword Search Feed");
|
||||
System.out.println("\t4) Print Uploads Feed");
|
||||
System.out.println("\t5) Print Favorites Feed");
|
||||
System.out
|
||||
.println("\t6) Show Comments and Responses Feed for a single Video");
|
||||
System.out.println("\t7) Print Playlists Feed");
|
||||
System.out.println("\t8) Display a playlist");
|
||||
System.out.println("\t9) Print Subscriptions Feed");
|
||||
System.out.println("\t10) Print User Profile Feed");
|
||||
System.out.println("\t0) Exit");
|
||||
System.out.println("\nEnter Number (0-10): ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetchs a user's profile feed and prints out most of the attributes.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printUserProfile(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
String testUser = promptForUser();
|
||||
printUnderlined("User Profile for '" + testUser + "'");
|
||||
UserProfileEntry userProfileEntry = service.getEntry(new URL(
|
||||
USER_FEED_PREFIX + testUser), UserProfileEntry.class);
|
||||
System.out.println("Username: " + userProfileEntry.getUsername());
|
||||
System.out.println("Age : " + userProfileEntry.getAge());
|
||||
System.out.println("Gender : " + userProfileEntry.getGender());
|
||||
System.out.println("Single? : " + userProfileEntry.getRelationship());
|
||||
System.out.println("Books : " + userProfileEntry.getBooks());
|
||||
System.out.println("Company : " + userProfileEntry.getCompany());
|
||||
System.out.println("Describe: " + userProfileEntry.getAboutMe());
|
||||
System.out.println("Hobbies : " + userProfileEntry.getHobbies());
|
||||
System.out.println("Hometown: " + userProfileEntry.getHometown());
|
||||
System.out.println("Location: " + userProfileEntry.getLocation());
|
||||
System.out.println("Movies : " + userProfileEntry.getMovies());
|
||||
System.out.println("Music : " + userProfileEntry.getMusic());
|
||||
System.out.println("Job : " + userProfileEntry.getOccupation());
|
||||
System.out.println("School : " + userProfileEntry.getSchool());
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a user's playlists feed.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @param showPlaylistContents if true, print only the first playlist,
|
||||
* followed by all of its contained entries
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printPlaylists(YouTubeService service,
|
||||
boolean showPlaylistContents) throws IOException, ServiceException {
|
||||
String testUser = promptForUser();
|
||||
printPlaylistsFeed(service, USER_FEED_PREFIX + testUser
|
||||
+ PLAYLISTS_FEED_SUFFIX, showPlaylistContents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a user's subscriptions feed.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printSubscriptions(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
String testUser = promptForUser();
|
||||
printSubscriptionsFeed(service, USER_FEED_PREFIX + testUser
|
||||
+ SUBSCRIPTIONS_FEED_SUFFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a user's favorites feed.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printFavorites(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
String testUser = promptForUser();
|
||||
printVideoFeed(service, USER_FEED_PREFIX + testUser + FAVORITES_FEED_SUFFIX,
|
||||
false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a user's uploads feed.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @param showCommentsAndResponses whether or not to just print the first
|
||||
* entry, followed by comments and responses
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printUploads(YouTubeService service,
|
||||
boolean showCommentsAndResponses) throws IOException, ServiceException {
|
||||
String testUser = promptForUser();
|
||||
printVideoFeed(service, USER_FEED_PREFIX + testUser + UPLOADS_FEED_SUFFIX,
|
||||
showCommentsAndResponses);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompts the user to enter his user name on the standard input.
|
||||
* @return a username entered by the user
|
||||
* @throws java.io.IOException if unable to read a line from standard input
|
||||
*/
|
||||
private static String promptForUser() throws IOException {
|
||||
System.out.println("\nEnter YouTube username [default " + defaultTestUser
|
||||
+ "]: ");
|
||||
String line = readLine();
|
||||
if (line == null || "".equals(line.trim())) {
|
||||
line = defaultTestUser;
|
||||
} else {
|
||||
defaultTestUser = line;
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a feed known to be a VideoFeed, printing each VideoEntry with in
|
||||
* a numbered list, optionally prompting the user for the number of a video
|
||||
* entry which should have its comments and responses printed.
|
||||
*
|
||||
* @param service a YouTubeService object
|
||||
* @param feedUrl the url of the video feed to print
|
||||
* @param showCommentsAndResponses true if the user should be prompted for
|
||||
* a video whose comments and responses should
|
||||
* printed
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printVideoFeed(YouTubeService service, String feedUrl,
|
||||
boolean showCommentsAndResponses) throws IOException, ServiceException {
|
||||
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
|
||||
String title = videoFeed.getTitle().getPlainText();
|
||||
if (showCommentsAndResponses) {
|
||||
title += " with comments and responses";
|
||||
}
|
||||
printUnderlined(title);
|
||||
List<VideoEntry> videoEntries = videoFeed.getEntries();
|
||||
if (videoEntries.size() == 0) {
|
||||
System.out.println("This feed contains no entries.");
|
||||
return;
|
||||
}
|
||||
int count = 1;
|
||||
for (VideoEntry ve : videoEntries) {
|
||||
printVideoEntry("(Video #" + String.valueOf(count) + ")", ve, false);
|
||||
count++;
|
||||
}
|
||||
|
||||
if (showCommentsAndResponses) {
|
||||
System.out.printf(
|
||||
"\nWhich video to show comments and responses for? (1-%d): \n",
|
||||
count - 1);
|
||||
int whichVideo = readInt();
|
||||
printVideoEntry("", videoEntries.get(whichVideo - 1), true);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a user's playlists feed.
|
||||
*
|
||||
* @param service a YouTubeService object
|
||||
* @param feedUrl the url of the feed
|
||||
* @param showPlaylistContents true if only one entry should be shown,
|
||||
* followed by the contents of the playlist
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printPlaylistsFeed(YouTubeService service, String feedUrl,
|
||||
boolean showPlaylistContents) throws IOException, ServiceException {
|
||||
PlaylistLinkFeed playlistLinkFeed = service.getFeed(new URL(feedUrl),
|
||||
PlaylistLinkFeed.class);
|
||||
String title = playlistLinkFeed.getTitle().getPlainText();
|
||||
if (showPlaylistContents) {
|
||||
title += " with playlist content.";
|
||||
}
|
||||
printUnderlined(title);
|
||||
List<PlaylistLinkEntry> playlistEntries = playlistLinkFeed.getEntries();
|
||||
int count = 1;
|
||||
for (PlaylistLinkEntry pe : playlistEntries) {
|
||||
printPlaylistEntry("(Playlist #" + count + ")", pe, false);
|
||||
count++;
|
||||
}
|
||||
if (showPlaylistContents) {
|
||||
System.out.printf("\nWhich playlist do you want to see? (1-%d): \n",
|
||||
count - 1);
|
||||
int whichVideo = readInt();
|
||||
printPlaylistEntry("", playlistEntries.get(whichVideo - 1), true);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a user's subscriptions feed.
|
||||
*
|
||||
* @param service a YouTubeService object
|
||||
* @param feedUrl the url of the feed
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void printSubscriptionsFeed(YouTubeService service,
|
||||
String feedUrl) throws IOException, ServiceException {
|
||||
SubscriptionFeed subscriptionFeed = service.getFeed(new URL(feedUrl),
|
||||
SubscriptionFeed.class);
|
||||
printUnderlined(subscriptionFeed.getTitle().getPlainText());
|
||||
for (SubscriptionEntry se : subscriptionFeed.getEntries()) {
|
||||
printSubscriptionEntry(se);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the VIDEOS_FEED for search terms and print each resulting
|
||||
* VideoEntry.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void searchFeed(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));
|
||||
// order results by the number of views (most viewed first)
|
||||
query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);
|
||||
|
||||
// do not exclude restricted content from the search results
|
||||
// (by default, it is excluded)
|
||||
query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
|
||||
|
||||
System.out.println("\nEnter search terms: ");
|
||||
String searchTerms = readLine();
|
||||
|
||||
query.setFullTextQuery(searchTerms);
|
||||
|
||||
printUnderlined("Running Search for '" + searchTerms + "'");
|
||||
VideoFeed videoFeed = service.query(query, VideoFeed.class);
|
||||
for (VideoEntry ve : videoFeed.getEntries()) {
|
||||
printVideoEntry("", ve, false);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the VIDEOS_FEED for category keywords and prints each resulting
|
||||
* VideoEntry.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws ServiceException
|
||||
* If the service is unable to handle the request.
|
||||
* @throws IOException error sending request or reading the feed.
|
||||
*/
|
||||
private static void searchFeedWithKeywords(YouTubeService service)
|
||||
throws IOException, ServiceException {
|
||||
YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));
|
||||
// order the results by the number of views
|
||||
query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);
|
||||
|
||||
// include restricted content in the search results
|
||||
query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
|
||||
|
||||
// a category filter holds a collection of categories to limit the search
|
||||
Query.CategoryFilter categoryFilter = new Query.CategoryFilter();
|
||||
|
||||
String keywordTerm = null;
|
||||
String allKeywords = "";
|
||||
|
||||
do {
|
||||
System.out.println("\nEnter keyword or empty line when done: ");
|
||||
keywordTerm = readLine();
|
||||
// creates categories whose scheme is KEYWORD_SCHEME
|
||||
Category category = new Category(YouTubeNamespace.KEYWORD_SCHEME,
|
||||
keywordTerm);
|
||||
categoryFilter.addCategory(category);
|
||||
// keeps track of concatenated list of keywords entered so far
|
||||
if(!"".equals(keywordTerm))
|
||||
allKeywords += keywordTerm + ", ";
|
||||
} while(keywordTerm != null && !"".equals(keywordTerm));
|
||||
|
||||
// adds the collection of keyword categories to the query
|
||||
query.addCategoryFilter(categoryFilter);
|
||||
|
||||
printUnderlined("Running Search for '" + allKeywords + "'");
|
||||
VideoFeed videoFeed = service.query(query, VideoFeed.class);
|
||||
for (VideoEntry ve : videoFeed.getEntries()) {
|
||||
printVideoEntry("", ve, false);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* YouTubeReadonlyClient is a sample command line application that
|
||||
* demonstrates many features of the YouTube data API using
|
||||
* the Java Client library.
|
||||
*
|
||||
* @param args not used
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
YouTubeService myService = new YouTubeService("gdataSample-YouTube-1");
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
printUsage();
|
||||
int choice = readInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
// Fetches and prints the standard feeds.
|
||||
printStandardFeeds(myService);
|
||||
break;
|
||||
case 2:
|
||||
// Searches the VIDEO_FEED for user supplied search terms.
|
||||
searchFeed(myService);
|
||||
break;
|
||||
case 3:
|
||||
// Searches the VIDEO_FEED for user supplied category keyword terms.
|
||||
searchFeedWithKeywords(myService);
|
||||
break;
|
||||
case 4:
|
||||
// Fetches and prints a user's uploads feed.
|
||||
printUploads(myService, false);
|
||||
break;
|
||||
case 5:
|
||||
// Fetches and prints a user's favorites feed.
|
||||
printFavorites(myService);
|
||||
break;
|
||||
case 6:
|
||||
// Prompts the user for a username and displays the uploads feed
|
||||
// for that username as a numbered list. The user is asked to choose
|
||||
// the number of a video entry for which the comments and responses
|
||||
// feeds should be displayed.
|
||||
printUploads(myService, true);
|
||||
break;
|
||||
case 7:
|
||||
// Fetches and prints a list of a user's playlists feed.
|
||||
printPlaylists(myService, false);
|
||||
break;
|
||||
case 8:
|
||||
// Fetches and prints a numbered list of entries in a user's
|
||||
// playlists feed. The user is then asked to choose the number of
|
||||
// a playlist he wishes to see the contents of.
|
||||
printPlaylists(myService, true);
|
||||
break;
|
||||
case 9:
|
||||
// Fetches and prints a user's subscriptions feed.
|
||||
printSubscriptions(myService);
|
||||
break;
|
||||
case 10:
|
||||
// Fetches and prints a user's profile feed.
|
||||
printUserProfile(myService);
|
||||
break;
|
||||
case 0:
|
||||
default:
|
||||
System.exit(0);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Communications error
|
||||
System.err.
|
||||
println("There was a problem communicating with the service.");
|
||||
e.printStackTrace();
|
||||
} catch (ServiceException e) {
|
||||
// Server side error
|
||||
System.err.println("The server had a problem handling your request.");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
/* Copyright (c) 2008 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 sample.youtube;
|
||||
|
||||
import com.google.gdata.client.media.ResumableGDataFileUploader;
|
||||
import sample.util.SimpleCommandLineParser;
|
||||
import com.google.gdata.client.youtube.YouTubeService;
|
||||
import com.google.gdata.data.media.MediaFileSource;
|
||||
import com.google.gdata.data.media.mediarss.MediaCategory;
|
||||
import com.google.gdata.data.media.mediarss.MediaDescription;
|
||||
import com.google.gdata.data.media.mediarss.MediaKeywords;
|
||||
import com.google.gdata.data.media.mediarss.MediaTitle;
|
||||
import com.google.gdata.data.youtube.VideoEntry;
|
||||
import com.google.gdata.data.youtube.YouTubeMediaGroup;
|
||||
import com.google.gdata.data.youtube.YouTubeNamespace;
|
||||
import com.google.gdata.util.AuthenticationException;
|
||||
import com.google.gdata.util.ServiceException;
|
||||
import com.google.gdata.client.uploader.ProgressListener;
|
||||
import com.google.gdata.client.uploader.ResumableHttpFileUploader;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintStream;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Demonstrates YouTube Data API operation to upload large media files.
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class YouTubeUploadClient {
|
||||
|
||||
/**
|
||||
* The URL used to resumable upload
|
||||
*/
|
||||
public static final String RESUMABLE_UPLOAD_URL =
|
||||
"http://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads";
|
||||
|
||||
/** Time interval at which upload task will notify about the progress */
|
||||
private static final int PROGRESS_UPDATE_INTERVAL = 1000;
|
||||
|
||||
/** Max size for each upload chunk */
|
||||
private static final int DEFAULT_CHUNK_SIZE = 10000000;
|
||||
|
||||
/** Steam to print status messages to. */
|
||||
PrintStream output;
|
||||
|
||||
/**
|
||||
* Input stream for reading user input.
|
||||
*/
|
||||
private static final BufferedReader bufferedReader = new BufferedReader(
|
||||
new InputStreamReader(System.in));
|
||||
|
||||
|
||||
/**
|
||||
* A {@link ProgressListener} implementation to track upload progress.
|
||||
* The listener can track multiple uploads at the same time.
|
||||
*/
|
||||
private class FileUploadProgressListener implements ProgressListener {
|
||||
public synchronized void progressChanged(ResumableHttpFileUploader uploader)
|
||||
{
|
||||
switch(uploader.getUploadState()) {
|
||||
case COMPLETE:
|
||||
output.println("Upload Completed");
|
||||
break;
|
||||
case CLIENT_ERROR:
|
||||
output.println("Upload Failed");
|
||||
break;
|
||||
case IN_PROGRESS:
|
||||
output.println(
|
||||
String.format("%3.0f", uploader.getProgress() * 100) + "%");
|
||||
break;
|
||||
case NOT_STARTED:
|
||||
output.println("Upload Not Started");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private YouTubeUploadClient(PrintStream out) {
|
||||
this.output = out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a new video to YouTube.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object.
|
||||
* @throws IOException Problems reading user input.
|
||||
*/
|
||||
private void uploadVideo(YouTubeService service)
|
||||
throws IOException, ServiceException, InterruptedException {
|
||||
|
||||
output.println("First, type in the path to the movie file:");
|
||||
File videoFile = new File(readLine());
|
||||
if (!videoFile.exists()) {
|
||||
output.println("Sorry, that video doesn't exist.");
|
||||
return;
|
||||
}
|
||||
|
||||
output.println(
|
||||
"What is the MIME type of this file? (ex. 'video/quicktime' for .mov)");
|
||||
MediaFileSource ms = new MediaFileSource(videoFile, readLine());
|
||||
|
||||
output.println("What should I call this video?");
|
||||
String videoTitle = readLine();
|
||||
|
||||
VideoEntry newEntry = new VideoEntry();
|
||||
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
|
||||
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
|
||||
mg.setTitle(new MediaTitle());
|
||||
mg.getTitle().setPlainTextContent(videoTitle);
|
||||
mg.setKeywords(new MediaKeywords());
|
||||
mg.getKeywords().addKeyword("gdata-test");
|
||||
mg.setDescription(new MediaDescription());
|
||||
mg.getDescription().setPlainTextContent(videoTitle);
|
||||
|
||||
FileUploadProgressListener listener = new FileUploadProgressListener();
|
||||
ResumableGDataFileUploader uploader =
|
||||
new ResumableGDataFileUploader.Builder(
|
||||
service, new URL(RESUMABLE_UPLOAD_URL), ms, newEntry)
|
||||
.title(videoTitle)
|
||||
.trackProgress(listener, PROGRESS_UPDATE_INTERVAL)
|
||||
.chunkSize(DEFAULT_CHUNK_SIZE)
|
||||
.build();
|
||||
|
||||
uploader.start();
|
||||
while (!uploader.isDone()) {
|
||||
Thread.sleep(PROGRESS_UPDATE_INTERVAL);
|
||||
}
|
||||
|
||||
switch(uploader.getUploadState()) {
|
||||
case COMPLETE:
|
||||
output.println("Uploaded successfully");
|
||||
break;
|
||||
case CLIENT_ERROR:
|
||||
output.println("Upload Failed");
|
||||
break;
|
||||
default:
|
||||
output.println("Unexpected upload status");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* YouTubeUploadClient is a sample command line application that
|
||||
* demonstrates how to upload large media files to youtube. This sample
|
||||
* uses resumable upload feature to upload large media.
|
||||
*
|
||||
* @param args Used to pass the username and password of a test account.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
SimpleCommandLineParser parser = new SimpleCommandLineParser(args);
|
||||
String username = parser.getValue("username", "user", "u");
|
||||
String password = parser.getValue("password", "pass", "p");
|
||||
String developerKey = parser.getValue("key", "k");
|
||||
boolean help = parser.containsKey("help", "h");
|
||||
|
||||
if (help || username == null || password == null || developerKey == null) {
|
||||
printUsage();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
YouTubeService service = new YouTubeService("gdataSample-YouTubeAuth-1",
|
||||
developerKey);
|
||||
|
||||
try {
|
||||
service.setUserCredentials(username, password);
|
||||
} catch (AuthenticationException e) {
|
||||
System.out.println("Invalid login credentials.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
YouTubeUploadClient client = new YouTubeUploadClient(System.out);
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
printMenu();
|
||||
int choice = readInt();
|
||||
|
||||
switch(choice) {
|
||||
case 1:
|
||||
client.uploadVideo(service);
|
||||
break;
|
||||
case 0:
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
// Communications error
|
||||
System.err.println(
|
||||
"There was a problem communicating with the service.");
|
||||
e.printStackTrace();
|
||||
} catch (ServiceException se) {
|
||||
System.out.println("Sorry, your upload was invalid:");
|
||||
System.out.println(se.getResponseBody());
|
||||
se.printStackTrace();
|
||||
} catch (InterruptedException ie) {
|
||||
System.out.println("Upload interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the usage of how to run the sample from the command-line.
|
||||
*/
|
||||
private static void printUsage() {
|
||||
System.out.println("Usage: java YouTubeUploadClient.jar "
|
||||
+ " --username <user@gmail.com> " + " --password <pass> "
|
||||
+ " --key <developer key>");
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a menu of the main activities a user can perform.
|
||||
*/
|
||||
private static void printMenu() {
|
||||
System.out.println("\n");
|
||||
System.out.println("Choose one of the following demo options:");
|
||||
System.out.println("\t1) Upload new video");
|
||||
System.out.println("\t0) Exit");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input.
|
||||
*
|
||||
* @throws IOException If unable to read a line from the standard input.
|
||||
* @return A line of text read from the standard input.
|
||||
*/
|
||||
private static String readLine() throws IOException {
|
||||
return bufferedReader.readLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input and returns the parsed
|
||||
* integer representation.
|
||||
*
|
||||
* @throws IOException If unable to read a line from the standard input.
|
||||
* @return An integer read from the standard input.
|
||||
*/
|
||||
private static int readInt() throws IOException {
|
||||
String input = readLine();
|
||||
|
||||
try {
|
||||
return Integer.parseInt(input);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,846 @@
|
||||
/* Copyright (c) 2008 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 sample.youtube;
|
||||
|
||||
import com.google.gdata.client.Service;
|
||||
import sample.util.SimpleCommandLineParser;
|
||||
import com.google.gdata.client.youtube.YouTubeService;
|
||||
import com.google.gdata.data.PlainTextConstruct;
|
||||
import com.google.gdata.data.TextConstruct;
|
||||
import com.google.gdata.data.media.MediaFileSource;
|
||||
import com.google.gdata.data.media.mediarss.MediaCategory;
|
||||
import com.google.gdata.data.media.mediarss.MediaDescription;
|
||||
import com.google.gdata.data.media.mediarss.MediaKeywords;
|
||||
import com.google.gdata.data.media.mediarss.MediaPlayer;
|
||||
import com.google.gdata.data.media.mediarss.MediaTitle;
|
||||
import com.google.gdata.data.youtube.CommentEntry;
|
||||
import com.google.gdata.data.youtube.PlaylistEntry;
|
||||
import com.google.gdata.data.youtube.PlaylistFeed;
|
||||
import com.google.gdata.data.youtube.PlaylistLinkEntry;
|
||||
import com.google.gdata.data.youtube.PlaylistLinkFeed;
|
||||
import com.google.gdata.data.youtube.UserEventEntry;
|
||||
import com.google.gdata.data.youtube.UserEventFeed;
|
||||
import com.google.gdata.data.youtube.VideoEntry;
|
||||
import com.google.gdata.data.youtube.VideoFeed;
|
||||
import com.google.gdata.data.youtube.YouTubeMediaGroup;
|
||||
import com.google.gdata.data.youtube.YouTubeNamespace;
|
||||
import com.google.gdata.data.youtube.YtPublicationState;
|
||||
import com.google.gdata.util.AuthenticationException;
|
||||
import com.google.gdata.util.ServiceException;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Demonstrates authenticated YouTube Data API operations using the Java client
|
||||
* library.
|
||||
*/
|
||||
public class YouTubeWriteClient {
|
||||
|
||||
/**
|
||||
* Input stream for reading user input.
|
||||
*/
|
||||
private static final BufferedReader bufferedReader = new BufferedReader(
|
||||
new InputStreamReader(System.in));
|
||||
|
||||
/**
|
||||
* The name of the server hosting the YouTube GDATA feeds.
|
||||
*/
|
||||
public static final String YOUTUBE_GDATA_SERVER = "http://gdata.youtube.com";
|
||||
|
||||
|
||||
/**
|
||||
* The URL of the videos feed
|
||||
*/
|
||||
public static final String VIDEOS_FEED = YOUTUBE_GDATA_SERVER
|
||||
+ "/feeds/api/videos";
|
||||
|
||||
/**
|
||||
* The prefix of the user feeds
|
||||
*/
|
||||
public static final String USER_FEED_PREFIX = YOUTUBE_GDATA_SERVER
|
||||
+ "/feeds/api/users/";
|
||||
|
||||
/**
|
||||
* The prefix of recent activity feeds
|
||||
*/
|
||||
public static final String ACTIVITY_FEED_PREFIX = YOUTUBE_GDATA_SERVER
|
||||
+ "/feeds/api/events";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's uploads feed
|
||||
*/
|
||||
public static final String UPLOADS_FEED_SUFFIX = "/uploads";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's favorites feed
|
||||
*/
|
||||
public static final String FAVORITES_FEED_SUFFIX = "/favorites";
|
||||
|
||||
/**
|
||||
* The URL suffix of the test user's playlists feed
|
||||
*/
|
||||
public static final String PLAYLISTS_FEED_SUFFIX = "/playlists";
|
||||
|
||||
/**
|
||||
* The URL suffix of the friends activity feed
|
||||
*/
|
||||
public static final String FRIENDS_ACTIVITY_FEED_SUFFIX = "/friendsactivity";
|
||||
|
||||
/**
|
||||
* The default username.
|
||||
*/
|
||||
public static final String DEFAULT_USER = "default";
|
||||
|
||||
/**
|
||||
* The default video to use for examples.
|
||||
*/
|
||||
public static final String DEFAULT_VIDEO_ID = "scoMN8DYkCw";
|
||||
|
||||
/**
|
||||
* The URL used to upload video
|
||||
*/
|
||||
public static final String VIDEO_UPLOAD_FEED =
|
||||
"http://uploads.gdata.youtube.com/feeds/api/users/"
|
||||
+ DEFAULT_USER + "/uploads";
|
||||
|
||||
/**
|
||||
* Enum to deal with various playlist operations:
|
||||
* VIEW = print user's playlists
|
||||
* LIST = print contents of a playlist
|
||||
* CREATE = create new playlist
|
||||
* ADD = add video to playlist
|
||||
*/
|
||||
private enum PlaylistOperation {
|
||||
VIEW, LIST, CREATE, ADD
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a String, a newline, and a number of '-' characters equal to the
|
||||
* String's length.
|
||||
*
|
||||
* @param stringToUnderline - the string to print underlined
|
||||
*/
|
||||
private static void printUnderlined(String stringToUnderline) {
|
||||
System.out.println(stringToUnderline);
|
||||
for (int i = 0; i < stringToUnderline.length(); ++i) {
|
||||
System.out.print("-");
|
||||
}
|
||||
System.out.println("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a VideoEntry, optionally showing its responses and comment feeds.
|
||||
*
|
||||
* @param entry The VideoEntry to be printed
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void printVideoEntry(VideoEntry entry) throws IOException,
|
||||
ServiceException {
|
||||
System.out.println("Title:" + entry.getTitle().getPlainText());
|
||||
|
||||
YouTubeMediaGroup mediaGroup = entry.getMediaGroup();
|
||||
|
||||
if (mediaGroup != null) {
|
||||
if (mediaGroup.isPrivate()) {
|
||||
System.out.println("Video is private");
|
||||
}
|
||||
MediaPlayer player = mediaGroup.getPlayer();
|
||||
if (player != null) {
|
||||
System.out.println("Video URL: " + player.getUrl());
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.isDraft()) {
|
||||
System.out.println("Video is not live");
|
||||
YtPublicationState pubState = entry.getPublicationState();
|
||||
if (pubState.getState() == YtPublicationState.State.PROCESSING) {
|
||||
System.out.println("Video is still being processed.");
|
||||
} else if (pubState.getState() == YtPublicationState.State.REJECTED) {
|
||||
System.out.print("Video has been rejected because: ");
|
||||
System.out.println(pubState.getDescription());
|
||||
System.out.print("For help visit: ");
|
||||
System.out.println(pubState.getHelpUrl());
|
||||
} else if (pubState.getState() == YtPublicationState.State.FAILED) {
|
||||
System.out.print("Video failed uploading because: ");
|
||||
System.out.println(pubState.getDescription());
|
||||
System.out.print("For help visit: ");
|
||||
System.out.println(pubState.getHelpUrl());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prints a PlaylistEntry by retrieving the description of the playlist,
|
||||
* followed by the titles and URLs of each entry in the feed.
|
||||
*
|
||||
* @param prefix A string to be printed before each entry.
|
||||
* @param playlistLinkEntry The PlaylistEntry to be printed
|
||||
* @param showPlaylistContents If true, show the list of videos in the
|
||||
* playlist.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void printPlaylistEntry(String prefix,
|
||||
PlaylistLinkEntry playlistLinkEntry, boolean showPlaylistContents)
|
||||
throws IOException, ServiceException {
|
||||
System.out.println(prefix);
|
||||
System.out.printf("Description: %s\n",
|
||||
playlistLinkEntry.getSummary().getPlainText());
|
||||
if (showPlaylistContents) {
|
||||
printPlaylist(
|
||||
playlistLinkEntry.getService(), playlistLinkEntry.getFeedUrl());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a playlist feed as a series of titles and URLs.
|
||||
*
|
||||
* @param service A YouTubeService object.
|
||||
* @param playlistUrl The url of the playlist.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void printPlaylist(Service service, String playlistUrl)
|
||||
throws IOException, ServiceException {
|
||||
PlaylistFeed playlistFeed = service.getFeed(new URL(playlistUrl),
|
||||
PlaylistFeed.class);
|
||||
if (playlistFeed != null) {
|
||||
for (PlaylistEntry e : playlistFeed.getEntries()) {
|
||||
System.out.println("\tPlaylist Entry: " + e.getTitle().getPlainText());
|
||||
System.out.println("\tPlaylist URL: " + e.getHtmlLink().getHref());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input.
|
||||
*
|
||||
* @throws IOException If unable to read a line from the standard input.
|
||||
* @return A line of text read from the standard input.
|
||||
*/
|
||||
private static String readLine() throws IOException {
|
||||
return bufferedReader.readLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a line of text from the standard input and returns the parsed
|
||||
* integer representation.
|
||||
*
|
||||
* @throws IOException If unable to read a line from the standard input.
|
||||
* @return An integer read from the standard input.
|
||||
*/
|
||||
private static int readInt() throws IOException {
|
||||
String input = readLine();
|
||||
|
||||
try {
|
||||
return Integer.parseInt(input);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Solicits the user for a video ID (hash) or tries to figure one out
|
||||
* from the video's watch URL.
|
||||
*
|
||||
* @return String containing a video ID.
|
||||
* @throws IOException If there are problems reading user input.
|
||||
*/
|
||||
private static String readVideoID() throws IOException {
|
||||
System.out.println(
|
||||
"Input a valid video ID or a watch URL (default: " + DEFAULT_VIDEO_ID
|
||||
+ "):");
|
||||
|
||||
String input = readLine();
|
||||
if (input.equals("")) {
|
||||
return DEFAULT_VIDEO_ID;
|
||||
}
|
||||
|
||||
Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
|
||||
Matcher m = p.matcher(input);
|
||||
|
||||
if (m.matches()) {
|
||||
input = m.group(1);
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Displays a menu of the main activities a user can perform.
|
||||
*/
|
||||
private static void printMenu() {
|
||||
System.out.println("\n");
|
||||
System.out.println("Choose one of the following demo options:");
|
||||
System.out.println("\t1) My Uploads");
|
||||
System.out.println("\t2) My Playlists");
|
||||
System.out.println("\t3) My Favorites");
|
||||
System.out.println("\t4) Comment on a video");
|
||||
System.out.println("\t5) Upload a new video");
|
||||
System.out.println("\t6) Add a favorite");
|
||||
System.out.println("\t7) Print user activity");
|
||||
System.out.println("\t8) Print my friends' activity");
|
||||
System.out.println("\t0) Exit");
|
||||
System.out.println("\nEnter Number (0-8): ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the usage of how to run the sample from the command-line.
|
||||
*/
|
||||
private static void printUsage() {
|
||||
System.out.println("Usage: java YouTubeWriteClient.jar "
|
||||
+ " --username <user@gmail.com> " + " --password <pass> "
|
||||
+ " --key <developer key>");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Displays a user's playlists and lets the user manipulate them.
|
||||
*
|
||||
* @param service A YouTubeService object.
|
||||
* @throws IOExcep
|
||||
* tion Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void showPlaylists(YouTubeService service) throws IOException,
|
||||
ServiceException {
|
||||
doPlaylistFeedOperation(service, PlaylistOperation.VIEW);
|
||||
|
||||
while (true) {
|
||||
System.out.println("\nWhat would you like to do?");
|
||||
System.out.println("\t1) Create a new playlist");
|
||||
System.out.println("\t2) Add a video to a playlist");
|
||||
System.out.println("\t3) Print playlists");
|
||||
System.out.println("\t4) Print playlist contents");
|
||||
System.out.println("\t0) Back to main menu");
|
||||
System.out.println("\nEnter Number (0-5): ");
|
||||
|
||||
int choice = readInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
doPlaylistFeedOperation(service, PlaylistOperation.CREATE);
|
||||
break;
|
||||
case 2:
|
||||
doPlaylistFeedOperation(service, PlaylistOperation.ADD);
|
||||
break;
|
||||
case 3:
|
||||
doPlaylistFeedOperation(service, PlaylistOperation.VIEW);
|
||||
break;
|
||||
case 4:
|
||||
doPlaylistFeedOperation(service, PlaylistOperation.LIST);
|
||||
break;
|
||||
case 0:
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a user's favorites and lets the user manipulate them.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void showFavorites(YouTubeService service) throws IOException,
|
||||
ServiceException {
|
||||
printVideoFeed(service, USER_FEED_PREFIX + DEFAULT_USER
|
||||
+ FRIENDS_ACTIVITY_FEED_SUFFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a user's activity feed.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void showActivity(YouTubeService service) throws IOException,
|
||||
ServiceException {
|
||||
|
||||
System.out.println("Type in a comma separated list of YouTube usernames:");
|
||||
|
||||
String users = readLine();
|
||||
printActivityFeed(service, ACTIVITY_FEED_PREFIX + "?author=" + users);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a user's friends' activity feed.
|
||||
*
|
||||
* @param service a YouTubeService object.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void showFriendsActivity(YouTubeService service) throws IOException,
|
||||
ServiceException {
|
||||
printActivityFeed(service, USER_FEED_PREFIX + DEFAULT_USER
|
||||
+ FRIENDS_ACTIVITY_FEED_SUFFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Demonstrates adding a comment to a video.
|
||||
*
|
||||
* @param service The YouTubeService object controlling the connection to the
|
||||
* server.
|
||||
* @throws IOException Error sending request or reading the response.
|
||||
*/
|
||||
|
||||
private static void addComment(YouTubeService service) throws IOException {
|
||||
System.out.println("First, choose a video you want to comment on.");
|
||||
String videoID = readVideoID();
|
||||
|
||||
System.out.println("Okay, adding a comment to: " + videoID);
|
||||
|
||||
URL entryUrl = new URL("http://gdata.youtube.com/feeds/api/videos/"
|
||||
+ videoID);
|
||||
|
||||
VideoEntry videoEntry = null;
|
||||
try {
|
||||
videoEntry = service.getEntry(entryUrl, VideoEntry.class);
|
||||
} catch (ServiceException se) {
|
||||
// an invalid video ID was used.
|
||||
}
|
||||
|
||||
if (videoEntry == null) {
|
||||
System.out.println("Sorry, the video ID you entered was not valid.\n");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("Enter your comment: ");
|
||||
|
||||
String input = readLine();
|
||||
|
||||
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
|
||||
|
||||
CommentEntry newComment = new CommentEntry();
|
||||
newComment.setContent(new PlainTextConstruct(input));
|
||||
|
||||
try {
|
||||
service.insert(new URL(commentUrl), newComment);
|
||||
} catch (ServiceException se) {
|
||||
System.out.println("There was an error adding your comment.\n");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("Comment added successfully!\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a new video to YouTube.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object.
|
||||
* @throws IOException Problems reading user input.
|
||||
*/
|
||||
private static void uploadVideo(YouTubeService service) throws IOException {
|
||||
System.out.println("First, type in the path to the movie file:");
|
||||
|
||||
|
||||
File videoFile = new File(readLine());
|
||||
|
||||
if (!videoFile.exists()) {
|
||||
System.out.println("Sorry, that video doesn't exist.");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println(
|
||||
"What is the MIME type of this file? (ex. 'video/quicktime' for .mov)");
|
||||
|
||||
String mimeType = readLine();
|
||||
|
||||
System.out.println("What should I call this video?");
|
||||
String videoTitle = readLine();
|
||||
|
||||
VideoEntry newEntry = new VideoEntry();
|
||||
|
||||
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
|
||||
|
||||
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
|
||||
mg.setTitle(new MediaTitle());
|
||||
mg.getTitle().setPlainTextContent(videoTitle);
|
||||
mg.setKeywords(new MediaKeywords());
|
||||
mg.getKeywords().addKeyword("gdata-test");
|
||||
mg.setDescription(new MediaDescription());
|
||||
mg.getDescription().setPlainTextContent(videoTitle);
|
||||
MediaFileSource ms = new MediaFileSource(videoFile, mimeType);
|
||||
newEntry.setMediaSource(ms);
|
||||
|
||||
try {
|
||||
service.insert(new URL(VIDEO_UPLOAD_FEED), newEntry);
|
||||
} catch (ServiceException se) {
|
||||
System.out.println("Sorry, your upload was invalid:");
|
||||
System.out.println(se.getResponseBody());
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("Video uploaded successfully!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a video as a favorite.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object.
|
||||
* @throws IOException Problems reading user input.
|
||||
*/
|
||||
private static void addFavorite(YouTubeService service) throws IOException {
|
||||
System.out.println("First, choose a video to favorite.");
|
||||
String videoID = readVideoID();
|
||||
|
||||
System.out.println("Okay, favoriting: " + videoID);
|
||||
|
||||
URL entryUrl = new URL("http://gdata.youtube.com/feeds/api/videos/"
|
||||
+ videoID);
|
||||
|
||||
VideoEntry videoEntry = null;
|
||||
try {
|
||||
videoEntry = service.getEntry(entryUrl, VideoEntry.class);
|
||||
} catch (ServiceException se) {
|
||||
// an invalid video ID was used.
|
||||
}
|
||||
|
||||
if (videoEntry == null) {
|
||||
System.out.println("Sorry, the video ID you entered was not valid.\n");
|
||||
return;
|
||||
}
|
||||
|
||||
URL feedUrl = new URL(USER_FEED_PREFIX + DEFAULT_USER
|
||||
+ FAVORITES_FEED_SUFFIX);
|
||||
|
||||
try {
|
||||
service.insert(feedUrl, videoEntry);
|
||||
} catch (ServiceException e) {
|
||||
System.out.println("Error adding favorite.");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("Video favorited.");
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Adds a video to a particular playlist.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object.
|
||||
* @param entry The PlaylistLinkEntry describing the playlist
|
||||
* to add the video to.
|
||||
* @throws IOException Error reading user input.
|
||||
*/
|
||||
private static void addPlaylistVideo(YouTubeService service,
|
||||
PlaylistLinkEntry entry) throws IOException {
|
||||
System.out.println("Choose a video to add to this playlist.");
|
||||
|
||||
String videoID = readVideoID();
|
||||
|
||||
System.out.println("Okay, adding this video: " + videoID);
|
||||
|
||||
URL entryUrl = new URL("http://gdata.youtube.com/feeds/api/videos/"
|
||||
+ videoID);
|
||||
|
||||
VideoEntry videoEntry = null;
|
||||
try {
|
||||
videoEntry = service.getEntry(entryUrl, VideoEntry.class);
|
||||
} catch (ServiceException se) {
|
||||
// an invalid video ID was used.
|
||||
}
|
||||
|
||||
if (videoEntry == null) {
|
||||
System.out.println("Sorry, the video ID you entered was not valid.\n");
|
||||
return;
|
||||
}
|
||||
|
||||
String playlistUrl = entry.getFeedUrl();
|
||||
PlaylistEntry playlistEntry = new PlaylistEntry(videoEntry);
|
||||
|
||||
try {
|
||||
service.insert(new URL(playlistUrl), playlistEntry);
|
||||
} catch (ServiceException e) {
|
||||
System.out.println("Error adding vide to playlist");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("Video added to the playlist!");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Prints the user's uploaded videos.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void printUploads(YouTubeService service) throws IOException,
|
||||
ServiceException {
|
||||
|
||||
printVideoFeed(service, USER_FEED_PREFIX + DEFAULT_USER
|
||||
+ UPLOADS_FEED_SUFFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a feed known to be a VideoFeed, printing each VideoEntry with in a
|
||||
* numbered list, optionally prompting the user for the number of a video
|
||||
* entry which should have its comments and responses printed.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object
|
||||
* @param feedUrl The url of the video feed to print.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void printVideoFeed(YouTubeService service, String feedUrl)
|
||||
throws IOException, ServiceException {
|
||||
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
|
||||
String title = videoFeed.getTitle().getPlainText();
|
||||
|
||||
printUnderlined(title);
|
||||
List<VideoEntry> videoEntries = videoFeed.getEntries();
|
||||
if (videoEntries.size() == 0) {
|
||||
System.out.println("This feed contains no entries.");
|
||||
return;
|
||||
}
|
||||
int count = 1;
|
||||
for (VideoEntry entry : videoEntries) {
|
||||
System.out.println("(Video #" + String.valueOf(count) + ")");
|
||||
printVideoEntry(entry);
|
||||
count++;
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a feed of activities and prints information about them.
|
||||
*
|
||||
* @param service An authenticated YouTubeService object
|
||||
* @param feedUrl The url of the video feed to print.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void printActivityFeed(YouTubeService service, String feedUrl)
|
||||
throws IOException, ServiceException {
|
||||
UserEventFeed activityFeed = service.getFeed(new URL(feedUrl),
|
||||
UserEventFeed.class);
|
||||
String title = activityFeed.getTitle().getPlainText();
|
||||
|
||||
printUnderlined(title);
|
||||
if (activityFeed.getEntries().size() == 0) {
|
||||
System.out.println("This feed contains no entries.");
|
||||
return;
|
||||
}
|
||||
for (UserEventEntry entry : activityFeed.getEntries()) {
|
||||
String user = entry.getAuthors().get(0).getName();
|
||||
if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_UPLOADED) {
|
||||
System.out.println(user + " uploaded a video " + entry.getVideoId());
|
||||
}
|
||||
else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_RATED) {
|
||||
System.out.println(user + " rated a video " + entry.getVideoId() +
|
||||
" " + entry.getRating().getValue() + " stars");
|
||||
}
|
||||
else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_FAVORITED) {
|
||||
System.out.println(user + " favorited a video " + entry.getVideoId());
|
||||
}
|
||||
else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_SHARED) {
|
||||
System.out.println(user + " shared a video " + entry.getVideoId());
|
||||
}
|
||||
else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_COMMENTED) {
|
||||
System.out.println(user + " commented on video " + entry.getVideoId());
|
||||
}
|
||||
else if(entry.getUserEventType()
|
||||
== UserEventEntry.Type.USER_SUBSCRIPTION_ADDED) {
|
||||
System.out.println(user + " subscribed to the channel of " +
|
||||
entry.getUsername());
|
||||
}
|
||||
else if(entry.getUserEventType() == UserEventEntry.Type.FRIEND_ADDED) {
|
||||
System.out.println(user + " friended " + entry.getUsername());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a given operation on the user's playlists feed
|
||||
*
|
||||
* @param service An authenticated YouTubeService object.
|
||||
* @param op The operation to perform on the playlists feed.
|
||||
* @throws IOException Error sending request or reading the feed.
|
||||
* @throws ServiceException If the service is unable to handle the request.
|
||||
*/
|
||||
private static void doPlaylistFeedOperation(YouTubeService service,
|
||||
PlaylistOperation op) throws IOException, ServiceException {
|
||||
String feedUrl = USER_FEED_PREFIX + DEFAULT_USER + PLAYLISTS_FEED_SUFFIX;
|
||||
|
||||
|
||||
if (op == PlaylistOperation.CREATE) {
|
||||
System.out.println("Creating new playlist!");
|
||||
System.out.println("Enter a title: ");
|
||||
String title = readLine();
|
||||
System.out.println("Enter a description: ");
|
||||
String description = readLine();
|
||||
|
||||
PlaylistLinkEntry newEntry = new PlaylistLinkEntry();
|
||||
newEntry.setTitle(new PlainTextConstruct(title));
|
||||
newEntry.setSummary(
|
||||
TextConstruct.create(TextConstruct.Type.TEXT, description, null));
|
||||
|
||||
service.insert(new URL(feedUrl), newEntry);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
PlaylistLinkFeed playlistLinkFeed = service.getFeed(new URL(feedUrl),
|
||||
PlaylistLinkFeed.class);
|
||||
String title = playlistLinkFeed.getTitle().getPlainText();
|
||||
|
||||
printUnderlined(title);
|
||||
List<PlaylistLinkEntry> playlistEntries = playlistLinkFeed.getEntries();
|
||||
int count = 1;
|
||||
for (PlaylistLinkEntry pe : playlistEntries) {
|
||||
printPlaylistEntry("(Playlist #" + count + ")", pe, false);
|
||||
count++;
|
||||
}
|
||||
|
||||
if (op == PlaylistOperation.LIST) {
|
||||
System.out.printf("\nWhich playlist do you want to see? (1-%d): \n",
|
||||
count - 1);
|
||||
int whichVideo = readInt();
|
||||
if (whichVideo < 1 || whichVideo > count - 1) {
|
||||
System.out.println("Invalid choice.");
|
||||
} else {
|
||||
printPlaylistEntry("", playlistEntries.get(whichVideo - 1), true);
|
||||
}
|
||||
}
|
||||
|
||||
if (op == PlaylistOperation.ADD) {
|
||||
System.out.printf("\nWhich playlist do you want to add to? (1-%d): \n",
|
||||
count - 1);
|
||||
int whichVideo = readInt();
|
||||
if (whichVideo < 1 || whichVideo > count - 1) {
|
||||
System.out.println("Invalid choice.");
|
||||
} else {
|
||||
addPlaylistVideo(service, playlistEntries.get(whichVideo - 1));
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* YouTubeWriteClient is a sample command line application that
|
||||
* demonstrates many features of the YouTube Data API using the Java Client
|
||||
* library.
|
||||
*
|
||||
* This sample demonstrates both upload and write activities in the API.
|
||||
*
|
||||
* @param args Used to pass the username and password of a test account.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
SimpleCommandLineParser parser = new SimpleCommandLineParser(args);
|
||||
String username = parser.getValue("username", "user", "u");
|
||||
String password = parser.getValue("password", "pass", "p");
|
||||
String developerKey = parser.getValue("key", "k");
|
||||
boolean help = parser.containsKey("help", "h");
|
||||
|
||||
if (help || username == null || password == null || developerKey == null) {
|
||||
printUsage();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
YouTubeService service = new YouTubeService("gdataSample-YouTubeAuth-1",
|
||||
developerKey);
|
||||
|
||||
try {
|
||||
service.setUserCredentials(username, password);
|
||||
} catch (AuthenticationException e) {
|
||||
System.out.println("Invalid login credentials.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
|
||||
printMenu();
|
||||
int choice = readInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
// Prints out the user's uploaded videos
|
||||
printUploads(service);
|
||||
break;
|
||||
case 2:
|
||||
// Accesses the user's playlists
|
||||
showPlaylists(service);
|
||||
break;
|
||||
case 3:
|
||||
// Accesses the user's favorites
|
||||
showFavorites(service);
|
||||
break;
|
||||
case 4:
|
||||
// Adds a comment to a video
|
||||
addComment(service);
|
||||
break;
|
||||
case 5:
|
||||
// Uploads a new video to YouTube
|
||||
uploadVideo(service);
|
||||
break;
|
||||
case 6:
|
||||
// adds a new favorite video
|
||||
addFavorite(service);
|
||||
break;
|
||||
case 7:
|
||||
// print the user's activities
|
||||
showActivity(service);
|
||||
break;
|
||||
case 8:
|
||||
// print the user's friends' activities
|
||||
showFriendsActivity(service);
|
||||
break;
|
||||
case 0:
|
||||
default:
|
||||
System.out.println("Bye!");
|
||||
System.exit(0);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Communications error
|
||||
System.err.println(
|
||||
"There was a problem communicating with the service.");
|
||||
e.printStackTrace();
|
||||
} catch (ServiceException e) {
|
||||
// Server side error
|
||||
System.err.println("The server had a problem handling your request.");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user