Example usage for com.google.api.client.googleapis.media MediaHttpUploader setProgressListener

List of usage examples for com.google.api.client.googleapis.media MediaHttpUploader setProgressListener

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.media MediaHttpUploader setProgressListener.

Prototype

public MediaHttpUploader setProgressListener(MediaHttpUploaderProgressListener progressListener) 

Source Link

Document

Sets the progress listener to send progress notifications to or null for none.

Usage

From source file:GoogleDriveAPI.java

License:Apache License

/** Uploads a file using either resumable or direct media upload. */
public static String upload(String email, String filepath) throws IOException {
    setup(email);/*from   w  w  w .  ja  v a 2s  .c om*/
    FileContent mediaContent = new FileContent("application/octet-stream", new java.io.File(filepath));
    Drive.Files.Insert insert = drive.files().insert(new File().setTitle(filepath), mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    // uploader.setDirectUploadEnabled(useDirectUpload);
    uploader.setProgressListener(new FileUploadProgressListener());
    return insert.execute().getId();
}

From source file:DriveSample.java

License:Apache License

/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload, java.io.File UPLOAD_FILE, String ContentType)
        throws IOException {
    File fileMetadata = new File();
    fileMetadata.setTitle(UPLOAD_FILE.getName());

    FileContent mediaContent = new FileContent(ContentType, UPLOAD_FILE);

    Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    uploader.setDirectUploadEnabled(useDirectUpload);
    uploader.setProgressListener(new FileUploadProgressListener());
    return insert.execute();
}

From source file:UploadThumbnail.java

License:Apache License

/**
 * Prompt the user to specify a video ID and the path for a thumbnail
 * image. Then call the API to set the image as the thumbnail for the video.
 *
 * @param videoId id of YouTube video//  w  w w  .ja v a2s.c o m
 * @param filePath String path to jpeg file to upload
 */
public static void run(String videoName, String videoId, String filePath) {
    try {

        File imageFile = new File(filePath);

        // Create an object that contains the thumbnail image file's
        // contents.
        InputStreamContent mediaContent = new InputStreamContent(IMAGE_FILE_FORMAT,
                new BufferedInputStream(new FileInputStream(imageFile)));
        mediaContent.setLength(imageFile.length());

        // Create an API request that specifies that the mediaContent
        // object is the thumbnail of the specified video.
        Set thumbnailSet = Main.youtube.thumbnails().set(videoId, mediaContent);

        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = thumbnailSet.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);

        // Set the upload state for the thumbnail image.
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
            }
        };
        uploader.setProgressListener(progressListener);

        // Upload the image and set it as the specified video's thumbnail.
        ThumbnailSetResponse setResponse = thumbnailSet.execute();

        // Print the URL for the updated video's thumbnail image.
        System.out.println("Upload Completed: " + videoName);

    } catch (GoogleJsonResponseException e) {
        System.out.println("Fail");
        System.err.println(e);
        e.printStackTrace();

    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:by.dev.madhead.gbp.tasks.gdrive.GoogleDriveUploadTask.java

License:Apache License

/**
 * Uploads {@link #setArchive(File) specified file} to Google Drive.
 *///from www .j ava2 s  .com
@TaskAction
public void run() {
    try {
        Preconditions.checkNotNull(this.clientId, "Google Drive client ID must not be null");
        Preconditions.checkNotNull(this.clientSecret, "Google Drive client secret must not be null");
        Preconditions.checkNotNull(this.accessToken, "Google Drive access token must not be null");
        Preconditions.checkNotNull(this.refreshToken, "Google Drive refresh token must not be null");
        Preconditions.checkNotNull(this.archive, "Archive must not be null");
        Preconditions.checkArgument(this.archive.exists(), "Archive must exist");
        Preconditions.checkArgument(this.archive.isFile(), "Archive must be a file");

        final Drive drive = constructDrive();

        final com.google.api.services.drive.model.File parent = locateParent(drive);

        final com.google.api.services.drive.model.File descriptor = new com.google.api.services.drive.model.File();
        final FileContent content = new FileContent(mimeType, archive);

        if (null != parent) {
            descriptor.setParents(Arrays.<ParentReference>asList(new ParentReference().setId(parent.getId())));
        }
        descriptor.setMimeType(content.getType());
        descriptor.setTitle(content.getFile().getName());

        final Drive.Files.Insert insert = drive.files().insert(descriptor, content);
        final MediaHttpUploader uploader = insert.getMediaHttpUploader();

        uploader.setChunkSize(1 * 1024 * 1024 /* bytes */);

        if (listenForUpload) {
            uploader.setProgressListener(new MediaHttpUploaderProgressListener() {
                @Override
                public void progressChanged(MediaHttpUploader u) throws IOException {
                    final double progress = (double) u.getNumBytesUploaded() / content.getLength();

                    System.out.printf("\r[%-50.50s] %.2f%%", Strings.repeat("#", (int) (progress * 50)),
                            progress * 100);
                    System.out.flush();
                }
            });
        }

        insert.execute();
    } catch (Exception e) {
        throw new TaskExecutionException(this, e);
    }
}

From source file:com.acceleratedio.pac_n_zoom.UploadVideo.java

License:Apache License

/**
 * 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.//from w  w w.j av  a2  s.c  o  m
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    MakePostRequest get_video = new MakePostRequest();
    get_video.execute();

    // 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");

    String vidFileName = PickAnmActivity.fil_nams[position].replace('/', '?') + ".mp4";
    String httpAddrs = "http://www.pnzanimate.me/Droid/db_rd.php?";
    httpAddrs += vidFileName;

    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("mp4",
                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();
    }
}

From source file:com.afrozaar.jazzfestreporting.ResumableUpload.java

License:Apache License

/**
 * Uploads user selected video in the project folder to the user's YouTube account using OAuth2
 * for authentication.//  w  w  w  . j av a  2 s. c  o m
 */

public static String upload(YouTube youtube, final InputStream fileInputStream, final long fileSize,
        final Uri mFileUri, final String path, final Context context) {
    final NotificationManager notifyManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent notificationIntent = new Intent(context, ReviewActivity.class);
    notificationIntent.setData(mFileUri);
    notificationIntent.setAction(Intent.ACTION_VIEW);
    Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.MICRO_KIND);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentTitle(context.getString(R.string.youtube_upload))
            .setContentText(context.getString(R.string.youtube_upload_started))
            .setSmallIcon(R.drawable.ic_stat_device_access_video).setContentIntent(contentIntent)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(thumbnail));
    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());

    String videoId = null;
    try {
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        /*
         * Set the video to public, so it is available to everyone (what most people want). This is
         * actually the default, but I wanted you to see what it looked like in case you need to set
         * it to "unlisted" or "private" via API.
         */
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        // We set a majority of the metadata with the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        /*
         * The Calendar instance is used to create a unique name and description for test purposes, so
         * you can see multiple files being uploaded. You will want to remove this from your project
         * and use your own standard names.
         */
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

        // Set your keywords.
        snippet.setTags(Arrays.asList(Constants.DEFAULT_KEYWORD,
                Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST)));

        // Set completed snippet to the video object.
        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(fileInputStream));
        mediaContent.setLength(fileSize);

        /*
         * The upload command includes: 1. Information we want returned after file is successfully
         * uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself.
         */
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

        // Set the upload type and add event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        /*
         * Sets whether direct media upload is enabled or disabled. True = whole media content is
         * uploaded in a single request. False (default) = resumable media upload protocol to upload
         * in data chunks.
         */
        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    builder.setContentText(context.getString(R.string.initiation_started))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case INITIATION_COMPLETE:
                    builder.setContentText(context.getString(R.string.initiation_completed))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case MEDIA_IN_PROGRESS:
                    builder.setContentTitle(context.getString(R.string.youtube_upload)
                            + (int) (uploader.getProgress() * 100) + "%")
                            .setContentText(context.getString(R.string.upload_in_progress))
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                    break;
                case MEDIA_COMPLETE:
                    builder.setContentTitle(context.getString(R.string.yt_upload_completed))
                            .setContentText(context.getString(R.string.upload_completed))
                            // Removes the progress bar
                            .setProgress(0, 0, false);
                    notifyManager.notify(UPLOAD_NOTIFICATION_ID, builder.build());
                case NOT_STARTED:
                    Log.d(this.getClass().getSimpleName(), context.getString(R.string.upload_not_started));
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Execute upload.
        Video returnedVideo = videoInsert.execute();
        Log.d(TAG, "Video upload completed");
        videoId = returnedVideo.getId();
        Log.d(TAG, String.format("videoId = [%s]", videoId));
    } catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
        Log.e(TAG, "GooglePlayServicesAvailabilityIOException", availabilityException);
        notifyFailedUpload(context, context.getString(R.string.cant_access_play), notifyManager, builder);
    } catch (UserRecoverableAuthIOException userRecoverableException) {
        Log.i(TAG, String.format("UserRecoverableAuthIOException: %s", userRecoverableException.getMessage()));
        requestAuth(context, userRecoverableException);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        notifyFailedUpload(context, context.getString(R.string.please_try_again), notifyManager, builder);
    }
    return videoId;
}

From source file:com.agroknow.cimmyt.utils.UploadVideo.java

License:Apache License

/**
 * 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.//from  w  w  w . ja va 2 s.  co  m
 *
 * @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();
    }
}

From source file:com.bdaum.zoom.video.youtube.internal.YouTubeUploadClient.java

License:Apache License

public String uploadVideo(IProgressMonitor monitor, Session session, URI uri, String mimeType,
        String videoTitle, Date creationDate, String[] keywords, String category, String copyright,
        double latitude, double longitude, String location, boolean makePrivate)
        throws IOException, InterruptedException {

    File videoFile = new File(uri);
    if (!videoFile.exists())
        throw new FileNotFoundException(videoFile.toString());

    System.out.println("Uploading: " + videoFile);

    // 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(makePrivate ? "private" : "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.
    snippet.setTitle(videoTitle);/*from  ww w .j a  va  2s.  com*/
    snippet.setDescription("Video uploaded by ZoRa PhotoDirector");

    // Set the keyword tags that you want to associate with the video.
    List<String> tags = Arrays.asList(keywords);
    snippet.setTags(tags);
    // Add the completed snippet object to the video resource.
    videoObjectDefiningMetadata.setSnippet(snippet);

    try (InputStream videoStream = new FileInputStream(videoFile)) {

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, videoStream);

        // 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());
    }
    return null;

    // videoId = null;
    // VideoEntry newEntry = new VideoEntry();
    // YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
    // mg.setTitle(new MediaTitle());
    // mg.getTitle().setPlainTextContent(videoTitle);
    // mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME,
    // category));
    // mg.setCopyright(new MediaCopyright());
    // mg.getCopyright().setContent(copyright == null ? "" : copyright);
    // //$NON-NLS-1$
    // mg.setPrivate(makePrivate);
    // MediaKeywords mediaKeywords = new MediaKeywords();
    // mg.setKeywords(mediaKeywords);
    // if (keywords != null)
    // for (String kw : keywords)
    // mediaKeywords.addKeyword(kw);
    // mg.setDescription(new MediaDescription());
    // mg.getDescription().setPlainTextContent(videoTitle);
    // mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME,
    // Constants.APPNAME));
    // if (!Double.isNaN(latitude) && !Double.isNaN(longitude))
    // newEntry.setGeoCoordinates(new GeoRssWhere(latitude, longitude));
    // else if (location != null && location.length() > 0)
    // newEntry.setLocation(location);
    // if (creationDate != null) {
    // DateTime dateTime = new DateTime(creationDate);
    // dateTime.setDateOnly(true);
    // newEntry.setRecorded(dateTime);
    // }
    // MediaFileSource ms = new MediaFileSource(videoFile, mimeType);
    // newEntry.setMediaSource(ms);

    // FileUploadProgressListener listener = new
    // FileUploadProgressListener(monitor);
    // ResumableGDataFileUploader uploader = new
    // ResumableGDataFileUploader.Builder(service,
    // new URL(YtConstants.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);
    // }
    // ResponseMessage response = uploader.getResponse();
    // try {
    // if (response != null) {
    // String receiveMessage = response.receiveMessage(3000);
    // if (receiveMessage != null) {
    // // <id>tag:youtube.com,2008:video:Zd_PLRmRNA0</id>
    // int p = receiveMessage.indexOf("<id>") + 4; //$NON-NLS-1$
    // if (p >= 4) {
    // int q = receiveMessage.indexOf("</id>", p); //$NON-NLS-1$
    // if (q > p) {
    // int r = receiveMessage.indexOf("video:", p); //$NON-NLS-1$
    // if (r >= p && r < q)
    // videoId = receiveMessage.substring(r + 6, q).trim();
    // }
    // }
    // }
    // }
    // } catch (ExecutionException e) {
    // return Messages.YouTubeUploadClient_execution_error;
    // } catch (TimeoutException e) {
    // return Messages.YouTubeUploadClient_timeout;
    // }
    // switch (uploader.getUploadState()) {
    // case COMPLETE:
    // return null;
    // case CLIENT_ERROR:
    // return Messages.YouTubeUploadClient_upload_failed;
    // default:
    // return Messages.YouTubeUploadClient_unexpected_upload_status;
    // }
}

From source file:com.datafrog.mms.bak.DriveSample.java

License:Apache License

/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(final boolean useDirectUpload) throws IOException {
    File fileMetadata = new File();
    fileMetadata.setTitle(UPLOAD_FILE.getName());

    FileContent mediaContent = new FileContent("image/jpeg", UPLOAD_FILE);

    Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    uploader.setDirectUploadEnabled(useDirectUpload);
    uploader.setProgressListener(new FileUploadProgressListener());
    return insert.execute();
}

From source file:com.example.aakas.signuptest.UploadThumbnail.java

License:Apache License

/**
 * Prompt the user to specify a video ID and the path for a thumbnail
 * image. Then call the API to set the image as the thumbnail for the video.
 *
 * @param args command line args (not used).
 *///  w ww  .jav a  2  s.co m
public static void main(String[] args) {

    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadthumbnail");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-uploadthumbnail-sample").build();

        // Prompt the user to enter the video ID of the video being updated.
        String videoId = getVideoIdFromUser();
        System.out.println("You chose " + videoId + " to upload a thumbnail.");

        // Prompt the user to specify the location of the thumbnail image.
        File imageFile = getImageFromUser();
        System.out.println("You chose " + imageFile + " to upload.");

        // Create an object that contains the thumbnail image file's
        // contents.
        InputStreamContent mediaContent = new InputStreamContent(IMAGE_FILE_FORMAT,
                new BufferedInputStream(new FileInputStream(imageFile)));
        mediaContent.setLength(imageFile.length());

        // Create an API request that specifies that the mediaContent
        // object is the thumbnail of the specified video.
        Set thumbnailSet = youtube.thumbnails().set(videoId, mediaContent);

        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = thumbnailSet.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);

        // Set the upload state for the thumbnail image.
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                // This value is set before the initiation request is
                // sent.
                case INITIATION_STARTED:
                    System.out.println("Initiation Started");
                    break;
                // This value is set after the initiation request
                //  completes.
                case INITIATION_COMPLETE:
                    System.out.println("Initiation Completed");
                    break;
                // This value is set after a media file chunk is
                // uploaded.
                case MEDIA_IN_PROGRESS:
                    System.out.println("Upload in progress");
                    System.out.println("Upload percentage: " + uploader.getProgress());
                    break;
                // This value is set after the entire media file has
                //  been successfully uploaded.
                case MEDIA_COMPLETE:
                    System.out.println("Upload Completed!");
                    break;
                // This value indicates that the upload process has
                //  not started yet.
                case NOT_STARTED:
                    System.out.println("Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Upload the image and set it as the specified video's thumbnail.
        ThumbnailSetResponse setResponse = thumbnailSet.execute();

        // Print the URL for the updated video's thumbnail image.
        System.out.println("\n================== Uploaded Thumbnail ==================\n");
        System.out.println("  - Url: " + setResponse.getItems().get(0).getDefault().getUrl());

    } 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();
    }
}