Java Examples for com.google.api.services.youtube.model.Video

The following java examples will help you to understand the usage of com.google.api.services.youtube.model.Video. These source code samples are taken from different open source projects.

Example 1
Project: kmf-content-demo-master  File: Videos.java View source code
public static Video upload(String url, String playListToken, List<String> tags) {
    Video uploadedVideo;
    try {
        VideoSnippet snippet = new VideoSnippet();
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("FI-WARE project. Kurento Demo on Campus Party Brazil " + cal.getTime());
        snippet.setDescription("Kurento demo  on " + cal.getTime());
        snippet.setTags(tags);
        Video video = new Video();
        video.setSnippet(snippet);
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        String tmpFileName = "tmp";
        FileOutputStream fos = new FileOutputStream(tmpFileName);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        final File videoFile = new File(tmpFileName);
        InputStreamContent mediaContent = new InputStreamContent("video/*", new BufferedInputStream(new FileInputStream(videoFile)));
        /*
			 * 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", video, mediaContent);
        // Set the upload type and add event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        log.debug("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        log.debug("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        log.debug("Upload in progress");
                        log.debug("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        log.debug("Upload Completed!");
                        log.debug("Deleting local file...  " + videoFile.delete());
                        break;
                    case NOT_STARTED:
                        log.debug("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        uploadedVideo = videoInsert.execute();
        String playListItemId = Playlists.insertItem(playListToken, uploadedVideo.getId());
        // Print out returned results.
        log.info("\n================== Returned Video ==================\n");
        log.info(" -Id: " + uploadedVideo.getId());
        log.info(" -PlayList Item Id: " + playListItemId);
        log.info(" -Title: " + uploadedVideo.getSnippet().getTitle());
        log.info(" -Tags: " + uploadedVideo.getSnippet().getTags());
        log.info(" -Privacy Status: " + uploadedVideo.getStatus().getPrivacyStatus());
        log.info(" -Video Count: " + uploadedVideo.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        log.error("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        throw new KurentoMediaFrameworkException(e);
    } catch (IOException e) {
        log.error("IOException: " + e.getMessage());
        throw new KurentoMediaFrameworkException(e);
    } catch (Throwable t) {
        log.error("Throwable: " + t.getMessage());
        throw new KurentoMediaFrameworkException(t);
    }
    return uploadedVideo;
}
Example 2
Project: simplejavayoutubeuploader-master  File: ScheduleServiceImpl.java View source code
@Override
public void schedule(final DateTime dateTime, final String videoid, final Account account) throws ScheduleIOException {
    try {
        final YouTube youTube = youTubeProvider.setAccount(account).get();
        final YouTube.Videos.List listVideosRequest = youTube.videos().list("status").setId(videoid);
        final VideoListResponse listResponse = listVideosRequest.execute();
        final List<Video> videoList = listResponse.getItems();
        if (videoList.isEmpty()) {
            LOGGER.info("Can't find a video with ID: " + videoid);
            return;
        }
        final Video video = videoList.get(0);
        final VideoStatus status = video.getStatus();
        status.setPublishAt(dateTime);
        youTube.videos().update("status", video).execute();
    } catch (final Exception e) {
        throw new ScheduleIOException(e);
    }
}
Example 3
Project: incubator-streams-master  File: YoutubeUserActivityCollectorTest.java View source code
private static VideoListResponse createMockVideoListResponse(int numBefore, int numAfter, int numInRange, DateTime after, DateTime before, boolean page) {
    VideoListResponse feed = new VideoListResponse();
    List<Video> list = new LinkedList<>();
    for (int i = 0; i < numAfter; ++i) {
        com.google.api.client.util.DateTime published = new com.google.api.client.util.DateTime(after.getMillis() + 1000000);
        Video video = new Video();
        video.setSnippet(new VideoSnippet());
        video.getSnippet().setPublishedAt(published);
        list.add(video);
    }
    for (int i = 0; i < numInRange; ++i) {
        DateTime published;
        if ((before == null && after == null) || before == null) {
            // no date range or end time date range so just make the time now.
            published = DateTime.now();
        } else if (after == null) {
            //no beginning to range
            published = before.minusMillis(100000);
        } else {
            // has to be in range
            long range = before.getMillis() - after.getMillis();
            //in the middle
            published = after.plus(range / 2);
        }
        com.google.api.client.util.DateTime ytPublished = new com.google.api.client.util.DateTime(published.getMillis());
        Video video = new Video();
        video.setSnippet(new VideoSnippet());
        video.getSnippet().setPublishedAt(ytPublished);
        video.getSnippet().setTitle(IN_RANGE_IDENTIFIER);
        list.add(video);
    }
    for (int i = 0; i < numBefore; ++i) {
        com.google.api.client.util.DateTime published = new com.google.api.client.util.DateTime((after.minusMillis(100000)).getMillis());
        Video video = new Video();
        video.setSnippet(new VideoSnippet());
        video.getSnippet().setPublishedAt(published);
        list.add(video);
    }
    if (page) {
        feed.setNextPageToken("A");
    } else {
        feed.setNextPageToken(null);
    }
    feed.setItems(list);
    return feed;
}
Example 4
Project: RavenBot-master  File: YouTubeHandler.java View source code
@Override
public void onMessage(final MessageEvent event) {
    super.onMessage(event);
    PircBotX bot = event.getBot();
    String[] splitMessage = event.getMessage().split(" ");
    for (String aSplitMessage : splitMessage) {
        if (aSplitMessage.contains("youtube.com") && aSplitMessage.contains("v=")) {
            int index = aSplitMessage.lastIndexOf("v=") + 2;
            String videoId = (aSplitMessage.indexOf("&", index) > -1 ? aSplitMessage.substring(index, aSplitMessage.indexOf("&", index)) : aSplitMessage.substring(index));
            System.out.println(videoId);
            try {
                YouTube.Videos.List videos = youtube.videos().list("id,snippet,contentDetails");
                videos.setKey(SettingsManager.getInstance().getSettings().getYoutubeKey());
                videos.setId(videoId);
                VideoListResponse videoListResponse = videos.execute();
                List<Video> videoList = videoListResponse.getItems();
                if (videoList != null) {
                    Video firstResult = videoList.get(0);
                    bot.sendIRC().message(event.getChannel().getName(), formatResult(firstResult));
                } else {
                    bot.sendIRC().message(event.getChannel().getName(), "Could not find information about that video");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Example 5
Project: api-samples-master  File: VideoLocalizations.java View source code
/**
     * Updates a video's default language and sets its localized metadata.
     *
     * @param videoId The id parameter specifies the video ID for the resource
     * that is being updated.
     * @param defaultLanguage The language of the video's default metadata
     * @param language The language of the localized metadata
     * @param title The localized title to be set
     * @param description The localized description to be set
     * @throws IOException
     */
private static void setVideoLocalization(String videoId, String defaultLanguage, String language, String title, String description) throws IOException {
    // Call the YouTube Data API's videos.list method to retrieve videos.
    VideoListResponse videoListResponse = youtube.videos().list("snippet,localizations").setId(videoId).execute();
    // Since the API request specified a unique video ID, the API
    // response should return exactly one video. If the response does
    // not contain a video, then the specified video ID was not found.
    List<Video> videoList = videoListResponse.getItems();
    if (videoList.isEmpty()) {
        System.out.println("Can't find a video with ID: " + videoId);
        return;
    }
    Video video = videoList.get(0);
    // Modify video's default language and localizations properties.
    // Ensure that a value is set for the resource's snippet.defaultLanguage property.
    video.getSnippet().setDefaultLanguage(defaultLanguage);
    // Preserve any localizations already associated with the video. If the
    // video does not have any localizations, create a new array. Append the
    // provided localization to the list of localizations associated with the video.
    Map<String, VideoLocalization> localizations = video.getLocalizations();
    if (localizations == null) {
        localizations = new ArrayMap<String, VideoLocalization>();
        video.setLocalizations(localizations);
    }
    VideoLocalization videoLocalization = new VideoLocalization();
    videoLocalization.setTitle(title);
    videoLocalization.setDescription(description);
    localizations.put(language, videoLocalization);
    // Update the video resource by calling the videos.update() method.
    Video videoResponse = youtube.videos().update("snippet,localizations", video).execute();
    // Print information from the API response.
    System.out.println("\n================== Updated Video ==================\n");
    System.out.println("  - ID: " + videoResponse.getId());
    System.out.println("  - Default Language: " + videoResponse.getSnippet().getDefaultLanguage());
    System.out.println("  - Title(" + language + "): " + videoResponse.getLocalizations().get(language).getTitle());
    System.out.println("  - Description(" + language + "): " + videoResponse.getLocalizations().get(language).getDescription());
    System.out.println("\n-------------------------------------------------------------\n");
}
Example 6
Project: opencast-master  File: YouTubeV3PublicationServiceImpl.java View source code
/**
   * Publishes the element to the publication channel and returns a reference to the published version of the element.
   *
   * @param job
   *          the associated job
   * @param mediaPackage
   *          the mediapackage
   * @param elementId
   *          the mediapackage element id to publish
   * @return the published element
   * @throws PublicationException
   *           if publication fails
   */
private Publication publish(final Job job, final MediaPackage mediaPackage, final String elementId) throws PublicationException {
    if (mediaPackage == null) {
        throw new IllegalArgumentException("Mediapackage must be specified");
    } else if (elementId == null) {
        throw new IllegalArgumentException("Mediapackage ID must be specified");
    }
    final MediaPackageElement element = mediaPackage.getElementById(elementId);
    if (element == null) {
        throw new IllegalArgumentException("Mediapackage element must be specified");
    }
    if (element.getIdentifier() == null) {
        throw new IllegalArgumentException("Mediapackage element must have an identifier");
    }
    if (element.getMimeType().toString().matches("text/xml")) {
        throw new IllegalArgumentException("Mediapackage element cannot be XML");
    }
    try {
        // create context strategy for publication
        final YouTubePublicationAdapter c = new YouTubePublicationAdapter(mediaPackage, workspace);
        final File file = workspace.get(element.getURI());
        final String episodeName = c.getEpisodeName();
        final UploadProgressListener operationProgressListener = new UploadProgressListener(mediaPackage, file);
        final String privacyStatus = makeVideosPrivate ? "private" : "public";
        final VideoUpload videoUpload = new VideoUpload(truncateTitleToMaxFieldLength(episodeName, false), c.getEpisodeDescription(), privacyStatus, file, operationProgressListener, tags);
        final Video video = youTubeService.addVideoToMyChannel(videoUpload);
        final int timeoutMinutes = 60;
        final long startUploadMilliseconds = new Date().getTime();
        while (!operationProgressListener.isComplete()) {
            Thread.sleep(POLL_MILLISECONDS);
            final long howLongWaitingMinutes = (new Date().getTime() - startUploadMilliseconds) / 60000;
            if (howLongWaitingMinutes > timeoutMinutes) {
                throw new PublicationException("Upload to YouTube exceeded " + timeoutMinutes + " minutes for episode " + episodeName);
            }
        }
        String playlistName = StringUtils.trimToNull(truncateTitleToMaxFieldLength(mediaPackage.getSeriesTitle(), true));
        playlistName = (playlistName == null) ? this.defaultPlaylist : playlistName;
        final Playlist playlist;
        final Playlist existingPlaylist = youTubeService.getMyPlaylistByTitle(playlistName);
        if (existingPlaylist == null) {
            playlist = youTubeService.createPlaylist(playlistName, c.getContextDescription(), mediaPackage.getSeries());
        } else {
            playlist = existingPlaylist;
        }
        youTubeService.addPlaylistItem(playlist.getId(), video.getId());
        // Create new publication element
        final URL url = new URL("http://www.youtube.com/watch?v=" + video.getId());
        return PublicationImpl.publication(UUID.randomUUID().toString(), CHANNEL_NAME, url.toURI(), MimeTypes.parseMimeType(MIME_TYPE));
    } catch (Exception e) {
        logger.error("failed publishing to Youtube", e);
        logger.warn("Error publishing {}, {}", element, e.getMessage());
        if (e instanceof PublicationException) {
            throw (PublicationException) e;
        } else {
            throw new PublicationException("YouTube publish failed on job: " + ToStringBuilder.reflectionToString(job, ToStringStyle.MULTI_LINE_STYLE), e);
        }
    }
}
Example 7
Project: SecureShareLib-master  File: YoutubeSiteController.java View source code
public YouTube.Videos.Insert prepareUpload(String title, String body, File mediaFile) {
    try {
        if (!super.isVideoFile(mediaFile)) {
            jobFailed(null, 1231291, mContext.getString(R.string.invalid_file_format));
            return null;
        }
        Video videoObjectDefiningMetadata = new Video();
        //set the video to private by default
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("unlisted");
        videoObjectDefiningMetadata.setStatus(status);
        //we set a majority of the metadata with the VideoSnippet object
        VideoSnippet snippet = new VideoSnippet();
        //video file name.
        snippet.setTitle(title);
        snippet.setDescription(body);
        //set keywords.
        List<String> tags = new ArrayList<String>();
        tags.add("storymaker");
        snippet.setTags(tags);
        //set completed snippet to the video object
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, new BufferedInputStream(new FileInputStream(mediaFile)));
        mediaContent.setLength(mediaFile.length());
        YouTube.Videos.Insert requestInsert = mYoutube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        //set the upload type and add event listener.
        MediaHttpUploader uploader = requestInsert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        Timber.d("Upload file: Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        Timber.d("Upload file: Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        Timber.d("YouTube Upload: Upload in progress");
                        float uploadPercent = (float) (uploader.getProgress());
                        jobProgress(uploadPercent, mContext.getString(R.string.youtube_uploading));
                        break;
                    case MEDIA_COMPLETE:
                        Timber.d("Upload file: Upload Completed!");
                        break;
                    case NOT_STARTED:
                        Timber.d("Upload file: Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        return requestInsert;
    } catch (FileNotFoundException e) {
        String msg = e.getMessage() != null ? e.getMessage() + ", " : "";
        String errorMessage = e.getCause() + msg;
        Timber.e("File not found: " + errorMessage);
        return null;
    } catch (IOException e) {
        String msg = e.getMessage() != null ? e.getMessage() + ", " : "";
        String errorMessage = e.getCause() + msg;
        Timber.e("Progress IOException: " + errorMessage);
        return null;
    }
}
Example 8
Project: yt-direct-lite-android-master  File: MainActivity.java View source code
private void directTag(final VideoData video) {
    final Video updateVideo = new Video();
    VideoSnippet snippet = video.addTags(Arrays.asList(Constants.DEFAULT_KEYWORD, Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST)));
    updateVideo.setSnippet(snippet);
    updateVideo.setId(video.getYouTubeId());
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... voids) {
            YouTube youtube = new YouTube.Builder(transport, jsonFactory, credential).setApplicationName(Constants.APP_NAME).build();
            try {
                youtube.videos().update("snippet", updateVideo).execute();
            } catch (UserRecoverableAuthIOException e) {
                startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
            return null;
        }
    }.execute((Void) null);
    Toast.makeText(this, R.string.video_submitted_to_ytdl, Toast.LENGTH_LONG).show();
}
Example 9
Project: UTubeTV-master  File: YouTubeAPI.java View source code
protected List<YouTubeData> itemsForNextToken(String token, long maxResults) {
    List<Video> result = new ArrayList<Video>();
    VideoListResponse searchListResponse;
    try {
        YouTube.Videos.List listRequest = youTube().videos().list(mPart);
        listRequest.setKey(Auth.devKey());
        listRequest.setFields(mFields);
        listRequest.setMyRating("like");
        listRequest.setMaxResults(maxResults);
        listRequest.setPageToken(token);
        searchListResponse = listRequest.execute();
        // nasty double cast?
        response = searchListResponse;
        result.addAll(searchListResponse.getItems());
    } catch (UserRecoverableAuthIOException e) {
        handleResultsException(e);
    } catch (Exception e) {
        handleResultsException(e);
    }
    return itemsToMap(result);
}
Example 10
Project: kurento-media-framework-master  File: Videos.java View source code
public static Video upload(String url, String playListToken, List<String> tags) {
    Video uploadedVideo;
    try {
        VideoSnippet snippet = new VideoSnippet();
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("FI-WARE project. Kurento Demo on Campus Party Brazil " + cal.getTime());
        snippet.setDescription("Kurento demo  on " + cal.getTime());
        snippet.setTags(tags);
        Video video = new Video();
        video.setSnippet(snippet);
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        String tmpFileName = "tmp";
        FileOutputStream fos = new FileOutputStream(tmpFileName);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        final File videoFile = new File(tmpFileName);
        InputStreamContent mediaContent = new InputStreamContent("video/*", new BufferedInputStream(new FileInputStream(videoFile)));
        /*
			 * 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", video, mediaContent);
        // Set the upload type and add event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        log.debug("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        log.debug("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        log.debug("Upload in progress");
                        log.debug("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        log.debug("Upload Completed!");
                        log.debug("Deleting local file...  " + videoFile.delete());
                        break;
                    case NOT_STARTED:
                        log.debug("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        uploadedVideo = videoInsert.execute();
        String playListItemId = Playlists.insertItem(playListToken, uploadedVideo.getId());
        // Print out returned results.
        log.info("\n================== Returned Video ==================\n");
        log.info(" -Id: " + uploadedVideo.getId());
        log.info(" -PlayList Item Id: " + playListItemId);
        log.info(" -Title: " + uploadedVideo.getSnippet().getTitle());
        log.info(" -Tags: " + uploadedVideo.getSnippet().getTags());
        log.info(" -Privacy Status: " + uploadedVideo.getStatus().getPrivacyStatus());
        log.info(" -Video Count: " + uploadedVideo.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        log.error("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        throw new KurentoException(e);
    } catch (IOException e) {
        log.error("IOException: " + e.getMessage());
        throw new KurentoException(e);
    } catch (Throwable t) {
        log.error("Throwable: " + t.getMessage());
        throw new KurentoException(t);
    }
    return uploadedVideo;
}
Example 11
Project: HearthStats.net-Uploader-master  File: UploadVideo.java View source code
/**
     * Upload the user-selected video to the user's YouTube channel. The code
     * looks for the video in the application's project folder and uses OAuth
     * 2.0 to authorize the API request.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();
        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);
        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();
        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        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 the keyword tags that you want to associate with the video.
        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);
        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4"));
        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        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);
        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();
        // Print data about the newly inserted video from the API response.
        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();
    }
}