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

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

Introduction

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

Prototype

public double getProgress() throws IOException 

Source Link

Document

Gets the upload progress denoting the percentage of bytes that have been uploaded, represented between 0.0 (0%) and 1.0 (100%).

Usage

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  ww .  j  ava2s  .co  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.  jav a  2 s  .c om*/
 */

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.//www  . ja  va 2  s . c om
 *
 * @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);//  w w  w  .ja  va2  s.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.FileUploadProgressListener.java

License:Apache License

@Override
public void progressChanged(final MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
    case INITIATION_STARTED:
        View.header2("Upload Initiation has started.");
        break;/*from ww w .  j a v a 2 s  .c o m*/
    case INITIATION_COMPLETE:
        View.header2("Upload Initiation is Complete.");
        break;
    case MEDIA_IN_PROGRESS:
        View.header2(
                "Upload is In Progress: " + NumberFormat.getPercentInstance().format(uploader.getProgress()));
        break;
    case MEDIA_COMPLETE:
        View.header2("Upload is Complete!");
        break;
    }
}

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  w  w  .  j av a  2  s. c  om
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();
    }
}

From source file:com.example.android.mediarecorder.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  ava 2 s  .c om
 *
 */
public static void uploadVideo(String videoFile) {

    // 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.

        final String REFRESH_TOKEN = "1/7xBoioFqdbCgThf4NmDGUxrq34lX6PHEnrKJaqZAleI";
        final String ACCESS_TOKEN = "ya29.bgFtAuzEw4zJkzzuBIbHX-3UoIqooDOSqp-LhQASBXBIqZyOoePumoeLU3t9aw4MXS4BdigJOwmy7Q";

        GoogleCredential credential = new GoogleCredential.Builder()
                .setClientSecrets("538179399027-agbtmkj35iggo6ksb5mcgkg7acjs5j4o.apps.googleusercontent.com",
                        "ETC6y4uDXbgpQPVHre6qiBRv")
                .setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).build()
                .setRefreshToken(REFRESH_TOKEN).setAccessToken(ACCESS_TOKEN);

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

        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("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("A driver being a jerk " + cal.getTime());
        snippet.setDescription("Someone was abusing the bike lane at this time: " + cal.getTime());

        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("jerk driver");
        snippet.setTags(tags);

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

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(new FileInputStream(videoFile)));

        // 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.example.youtubeuploadv3.AsyncLoadYoutube.java

License:Apache License

@Override
protected Video doInBackground() throws IOException {
    /*     /*from w  w w  .  j av  a2  s  .  com*/
        List<String> result = new ArrayList<String>();
        List<Task> tasks =
            client.tasks().list("@default").setFields("items/title").execute().getItems();
        if (tasks != null) {
          for (Task task : tasks) {
            result.add(task.getTitle());
          }
        } else {
          result.add("No tasks.");
        }
        activity.tasksList = result;
    */
    String VIDEO_FILE_FORMAT = "video/*";
    Uri videoUri = activity.videoUri;

    try {

        // We get the user selected local video file to upload.

        File videoFile = getFileFromUri(videoUri);
        Log.d(TAG, "You chose " + videoFile + " to upload.");

        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        /*
         * Set the video to unlisted, so only someone with the link can see it.  You will probably
         * want to remove this in your code.  The default is public, which is what most people want.
         */
        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();

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

        // Set your keywords.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("android");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);

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

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(new FileInputStream(videoFile)));
        mediaContent.setLength(videoFile.length());
        Log.d(TAG, "videoFile.length()=" + videoFile.length());
        /*
         * The upload command includes:
         *   1. Information we want returned after file is successfully uploaded.
         *   2. Metadata we want associated with the uploaded video.
         *   3. Video file itself.
         */
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

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

        /*
         * Sets whether direct media upload is enabled or disabled.
         * True = whole media content is uploaded in a single request.
         * False (default) = resumable media upload protocol to upload in data chunks.
         */
        uploader.setDirectUploadEnabled(false);
        uploader.setChunkSize(1024 * 1024);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    Log.d(TAG, "Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    Log.d(TAG, "Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    Log.d(TAG, "Upload in progress");
                    Log.d(TAG, "Upload percentage: " + uploader.getProgress());
                    publishProgress((int) (uploader.getProgress() * 100));
                    break;
                case MEDIA_COMPLETE:
                    Log.d(TAG, "Upload Completed!");
                    break;
                case NOT_STARTED:
                    Log.d(TAG, "Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Execute upload.
        Video returnedVideo = videoInsert.execute();

        return returnedVideo;
        // Print out returned results.

    } catch (GoogleJsonResponseException e) {
        Log.e(TAG, "GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        Log.e(TAG, "Throwable: " + t.getMessage());
        t.printStackTrace();
    }
    return null;

}

From source file:com.gemmystar.api.youtube.UploadProgressListener.java

License:Open Source License

@Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
    case INITIATION_STARTED:
        LOGGER.info("Initiation Started");
        break;// w  w w  . j  a  v  a2  s . co m
    case INITIATION_COMPLETE:
        LOGGER.info("Initiation Completed");
        break;
    case MEDIA_IN_PROGRESS:
        //LOGGER.debug("Upload in progress");
        LOGGER.debug("Uploading percentage: {}", uploader.getProgress());
        break;
    case MEDIA_COMPLETE:
        LOGGER.info("Upload Completed!");
        break;
    case NOT_STARTED:
        LOGGER.info("Upload Not Started!");
        break;
    }

}

From source file:com.github.valentin.fedoskin.fb2me.desktop.drive.FileUploadProgressListener.java

License:Apache License

@Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
    case INITIATION_STARTED:
        DriveView.header2("Upload Initiation has started.");
        break;//from ww w .  ja  v  a2s  .  c  om
    case INITIATION_COMPLETE:
        DriveView.header2("Upload Initiation is Complete.");
        break;
    case MEDIA_IN_PROGRESS:
        DriveView.header2("Upload is In Progress: " + uploader.getProgress());
        break;
    case MEDIA_COMPLETE:
        DriveView.header2("Upload is Complete!");
        break;
    }
}