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

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

Introduction

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

Prototype

public long getNumBytesUploaded() 

Source Link

Document

Gets the total number of bytes the server received so far or 0 for direct uploads when the content length is not known.

Usage

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

License:Apache License

/**
 * Uploads {@link #setArchive(File) specified file} to Google Drive.
 */// ww  w .  j a va  2 s. c om
@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.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.//from w w w  .  j  a v a2 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.example.aakas.signuptest.UploadVideo.java

License:Apache License

@Override
protected Void doInBackground(Context... params) {
    this.context = params[0];
    Log.v("UploadVideo.java", "Here************");
    try {//from  w ww . j  a  v a  2s . c om

        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new GsonFactory();
        Log.d("UploadVideo.java", credential.getSelectedAccountName() + "!!!!!!!!!!");
        //             YouTube client

        youtube = new YouTube.Builder(transport, jsonFactory, credential).setApplicationName("Umeed 1.0")
                .build();
        Log.d("UploadVideo.java", credential.getSelectedAccountName() + "|||||||||||||||||");

        Log.v("UploadVideo.java", "0************");

        System.out.println("Uploading video");

        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(video.getStatus());
        videoObjectDefiningMetadata.setStatus(status);

        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        snippet.setTitle(video.getTitle());
        snippet.setDescription(video.getDescription());
        Log.v("UploadVideo.java", "1************");
        List<String> tags = new ArrayList<String>();
        snippet.setTags(video.getTags());

        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new BufferedInputStream(new FileInputStream(video.getUri())));
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();

        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();
        Log.v("UploadVideo.java", "3************");

        uploader.setDirectUploadEnabled(true);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    Log.v("UploadVideo.java", "Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    Log.v("UploadVideo.java", "Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    Log.v("UploadVideo.java", "Upload in progress");
                    Log.v("UploadVideo.java", "Upload percentage: " + uploader.getNumBytesUploaded());
                    break;
                case MEDIA_COMPLETE:
                    Log.v("UploadVideo.java", "Upload Completed!");
                    break;
                case NOT_STARTED:
                    Log.v("UploadVideo.java", "Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        Log.v("UploadVideo.java", "4************");

        // Call the API and upload the video.
        Log.d("UploadVideo.java", "*****" + credential.getSelectedAccountName() + "*****");
        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());
        Log.v("UploadVideo.java", "Success************");
        this.returnVideoId = returnedVideo.getId();
        activity.doSomething(this.returnVideoId);

    } catch (UserRecoverableAuthIOException userRecoverableException) {
        Log.i(TAG, String.format("UserRecoverableAuthIOException: %s",
                userRecoverableException.getMessage() + "........"));
        ((SignUpChoosingActivity) context).startActivityForResult(userRecoverableException.getIntent(),
                REQUEST_AUTHORIZATION);
        //            requestAuth(context, userRecoverableException);
    } catch (GoogleJsonResponseException e) {
        Log.v("UploadVideo.java", "5************");

        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.v("UploadVideo.java", "6************");
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        Log.v("UploadVideo.java", "7************");

        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
    return null;
}

From source file:com.google.cloud.dataflow.sdk.util.gcsio.LoggingMediaHttpUploaderProgressListener.java

License:Open Source License

@Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
    progressChanged(LOG, uploader.getUploadState(), uploader.getNumBytesUploaded(), System.currentTimeMillis());
}

From source file:com.google.ytdl.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
 *
 * @param args command line args (not used).
 */

public static String upload(YouTube youtube, final InputStream fileInputStream, final long fileSize,
        Context context) {
    final NotificationManager mNotifyManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setContentTitle(context.getString(R.string.youtube_upload))
            .setContentText(context.getString(R.string.youtube_direct_lite_upload_started))
            .setSmallIcon(R.drawable.icon);
    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.
        List<String> tags = new ArrayList<String>();
        tags.add(Constants.DEFAULT_KEYWORD);
        tags.add(Upload.generateKeywordFromPlaylistId(Constants.UPLOAD_PLAYLIST));
        snippet.setTags(tags);

        // 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:
                    mBuilder.setContentText("Initiation Started").setProgress((int) fileSize,
                            (int) uploader.getNumBytesUploaded(), false);
                    mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
                    break;
                case INITIATION_COMPLETE:
                    mBuilder.setContentText("Initiation Completed").setProgress((int) fileSize,
                            (int) uploader.getNumBytesUploaded(), false);
                    mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
                    break;
                case MEDIA_IN_PROGRESS:
                    mBuilder.setContentTitle("YouTube Upload " + (int) (uploader.getProgress() * 100) + "%")
                            .setContentText("Direct Lite upload in progress")
                            .setProgress((int) fileSize, (int) uploader.getNumBytesUploaded(), false);
                    mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
                    break;
                case MEDIA_COMPLETE:
                    mBuilder.setContentTitle("YouTube Upload Completed").setContentText("Upload complete")
                            // Removes the progress bar
                            .setProgress(0, 0, false);
                    mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
                case NOT_STARTED:
                    Log.d(this.getClass().getSimpleName(), "Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

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

    } catch (final GoogleJsonResponseException e) {
        if (401 == e.getDetails().getCode()) {
            Log.e(ResumableUpload.class.getSimpleName(), e.getMessage());
            LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
            manager.sendBroadcast(new Intent(MainActivity.INVALIDATE_TOKEN_INTENT));
        }
    } catch (IOException e) {
        Log.e("IOException", e.getMessage());
    } catch (Throwable t) {
        Log.e("Throwable", t.getMessage());
    }
    return videoId;
}

From source file:com.mrmq.uyoutube.data.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. c  o  m
 *
 */
public static Result upload(YouTube youtube, String videoUri, Video video, ChannelSetting setting) {
    Result result = new Result();

    try {
        Preconditions.checkNotNull(video, "Video can not be null");
        Preconditions.checkNotNull(video.getSnippet(), "Snippet can not be null");
        Preconditions.checkNotNull(video.getSnippet().getTitle(), "Video title can not be null");
        Preconditions.checkNotNull(video.getSnippet().getDescription(), "Video description can not be null");

        logger.info("Uploading, videoUri: {}, videos: ", videoUri, video);

        // 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(setting.getPrivacyStatus()); //public/private
        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(video.getSnippet().getTitle());
        snippet.setDescription(video.getSnippet().getDescription());

        // Set the keyword tags that you want to associate with the video
        if (video.getSnippet().getTags() != null)
            snippet.setTags(video.getSnippet().getTags());

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

        UploadVideo.class.getResourceAsStream(videoUri);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                new FileInputStream(new File(videoUri)));

        // 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:
                    logger.info("Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    logger.info("Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    logger.info("Upload in progress");
                    logger.info("Upload {} Kbs", (uploader.getNumBytesUploaded() / 1024));
                    break;
                case MEDIA_COMPLETE:
                    logger.info("Upload Completed!");
                    break;
                case NOT_STARTED:
                    logger.info("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.
        logger.info("\n================== Returned Video ==================\n");
        logger.info("  - Id: " + returnedVideo.getId());
        logger.info("  - Title: " + returnedVideo.getSnippet().getTitle());
        logger.info("  - Tags: " + returnedVideo.getSnippet().getTags());
        logger.info("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        logger.info("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
        result.setValue(returnedVideo);
        result.setErrorCode(ErrorCode.SUCCESS);
    } catch (GoogleJsonResponseException e) {
        result.setErrorCode(ErrorCode.FAIL);
        logger.error("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage(), e);
    } catch (IOException e) {
        result.setErrorCode(ErrorCode.FAIL);
        logger.error("IOException: " + e.getMessage(), e);
    } catch (Throwable t) {
        result.setErrorCode(ErrorCode.FAIL);
        logger.error("Throwable: " + t.getMessage(), t);
    }

    return result;
}

From source file:com.siblinks.ws.util.UploadVideo.java

License:Apache License

/**
*
*//* ww  w.j  av a  2  s. c om*/
public void upload(final String fileName, final InputStream inputStream, final String subject,
        final String topic, final String subTopic) {
    // 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.
        String title = fileName;
        title = title.substring(0, title.lastIndexOf(".mp4"));
        Calendar cal = Calendar.getInstance();
        snippet.setTitle(title);
        // snippet.setTitle("siblinks");
        snippet.setDescription(subTopic + title);

        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();

        snippet.setTags(tags);

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

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, inputStream);

        // 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() {
            @Override
            public void progressChanged(final 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.getNumBytesUploaded());
                    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());
        String titleVideo = returnedVideo.getSnippet().getTitle();
        titleVideo = titleVideo.replaceAll("'", "");

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("title", subTopic + "" + titleVideo);
        queryParams.put("subject", subject);
        queryParams.put("topic", topic);
        queryParams.put("subTopic", subTopic);
        //queryParams.put("description", titleVideo);

        queryParams.put("image", returnedVideo.getSnippet().getThumbnails().getDefault().getUrl());
        queryParams.put("url", "https://www.youtube.com/watch?v=" + returnedVideo.getId());
        String entityName = "VIDEO_DATA_INSERT";
        boolean msgs = dao.insertUpdateObject(entityName, queryParams);

        System.out.println("msgs====" + msgs);
        //`topic`,`subTopic`,`description

    } 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:de.jlo.talendcomp.google.analytics.uploads.UploadHelper.java

License:Apache License

public Upload startUpload(String filePath) throws Exception {
    if (accountId == null) {
        throw new IllegalStateException("Account-ID not set!");
    }// ww  w. jav a2 s. c  o  m
    if (webPropertyId == null) {
        throw new IllegalStateException("Web Property-ID not set!");
    }
    if (customDataSourceId == null) {
        throw new IllegalStateException("Custom Data Source ID not set!");
    }
    if (filePath == null || filePath.trim().isEmpty()) {
        throw new IllegalArgumentException("filePath cannot be null or empty");
    }
    File file = new File(filePath);
    if (file.canRead() == false) {
        throw new Exception("File:" + filePath + " cannot be read or does not exists!");
    }
    InputStreamContent mediaContent = new InputStreamContent("application/octet-stream",
            new FileInputStream(file));
    mediaContent.setLength(file.length());
    UploadData request = analyticsClient.management().uploads().uploadData(accountId, webPropertyId,
            customDataSourceId, mediaContent);
    MediaHttpUploader uploader = request.getMediaHttpUploader();
    uploader.setDirectUploadEnabled(false);
    uploader.setProgressListener(new MediaHttpUploaderProgressListener() {

        @Override
        public void progressChanged(MediaHttpUploader uploader) throws IOException {
            System.out.println("File status: " + uploader.getUploadState());
            System.out.println("Bytes uploaded:" + uploader.getNumBytesUploaded());
        }

    });
    return (Upload) execute(request);
}

From source file:de.jlo.talendcomp.google.drive.DriveHelper.java

License:Apache License

/**
 * Upload a file to the google drive//from  w  ww. jav  a2 s.  c  om
 * @param localFilePath local file path
 * @param title the alternate title, if null the file name will be used as title
 * @param driveFolderPath target folder
 * @param createDirIfNecessary if true create the target folder if not exists
 * @param overwrite overwrite an existing file with the same title, otherweise if a file already exists an exception will be thrown
 * @return the meta data of the new file
 * @throws Exception
 */
public com.google.api.services.drive.model.File upload(String localFilePath, String title,
        String driveFolderPath, boolean createDirIfNecessary, boolean overwrite) throws Exception {
    checkPrerequisits();
    if (localFilePath == null || localFilePath.trim().isEmpty()) {
        throw new IllegalArgumentException("localFilePath cannot be null or empty");
    }
    File localFile = new File(localFilePath);
    if (localFile.canRead() == false) {
        throw new Exception("Local upload file: " + localFile.getAbsolutePath() + " cannot be read.");
    }
    if (driveFolderPath != null && driveFolderPath.trim().isEmpty() == false) {
        driveFolderPath = driveFolderPath.trim();
        int pos = driveFolderPath.lastIndexOf("/");
        if (pos == driveFolderPath.length() - 1) {
            driveFolderPath = driveFolderPath.substring(0, pos); // cut up last /
        }
    }
    if (title != null) {
        title = title.trim();
    }
    if (title == null || title.isEmpty()) {
        title = localFile.getName();
    }
    String filePath = null;
    if (driveFolderPath != null) {
        filePath = driveFolderPath + "/" + title;
    } else {
        filePath = title;
    }
    com.google.api.services.drive.model.File existingFile = getByName(filePath);
    if (overwrite == false && existingFile != null) {
        throw new Exception("File " + existingFile.getTitle() + " already exists in the Drive. File-Id="
                + existingFile.getId());
    }
    if (existingFile == null) {
        info("Upload new file " + localFile.getAbsolutePath());
        String parentId = null;
        if (driveFolderPath != null && driveFolderPath.trim().isEmpty() == false) {
            com.google.api.services.drive.model.File parentFolder = getFolder(driveFolderPath,
                    createDirIfNecessary);
            if (parentFolder != null) {
                parentId = parentFolder.getId();
            } else {
                throw new Exception(
                        "Parent folder " + driveFolderPath + " does not exists or cannot be created.");
            }
        }
        com.google.api.services.drive.model.File uploadFile = new com.google.api.services.drive.model.File();
        uploadFile.setTitle(title);
        if (parentId != null) {
            ParentReference pr = new ParentReference();
            pr.setId(parentId);
            uploadFile.setParents(Arrays.asList(pr));
        }
        String mimeType = getMimeType(localFilePath);
        FileContent mediaContent = new FileContent(mimeType, localFile);
        Drive.Files.Insert insertRequest = driveService.files().insert(uploadFile, mediaContent);
        MediaHttpUploader uploader = insertRequest.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        uploader.setProgressListener(new MediaHttpUploaderProgressListener() {

            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                info("File status: " + uploader.getUploadState());
                info("Bytes uploaded:" + uploader.getNumBytesUploaded());
            }

        });
        return (com.google.api.services.drive.model.File) execute(insertRequest);
    } else {
        info("Upload existing file " + localFile.getAbsolutePath());
        String mimeType = getMimeType(localFilePath);
        FileContent mediaContent = new FileContent(mimeType, localFile);
        Drive.Files.Update updateRequest = driveService.files().update(existingFile.getId(), existingFile,
                mediaContent);
        MediaHttpUploader uploader = updateRequest.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);
        uploader.setProgressListener(new MediaHttpUploaderProgressListener() {

            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                info("File status: " + uploader.getUploadState());
                info("Bytes uploaded:" + uploader.getNumBytesUploaded());
            }

        });
        return (com.google.api.services.drive.model.File) execute(updateRequest);
    }
}

From source file:io.cloudex.cloud.impl.google.storage.UploadProgressListener.java

License:Apache License

@Override
public void progressChanged(MediaHttpUploader uploader) {
    switch (uploader.getUploadState()) {
    case INITIATION_STARTED:
        stopwatch.start();//ww w  .  ja v  a2s  .com
        log.info("Initiation has started!");
        break;
    case INITIATION_COMPLETE:
        log.info("Initiation is complete!");
        break;
    case MEDIA_IN_PROGRESS:
        // Progress works iff you have a content length specified.
        try {
            log.info("Progress: " + Math.round(uploader.getProgress() * 100.00) + "%");
        } catch (IOException e) {
            log.warn("Failed to get progress", e);
            log.info("Uploaded: " + uploader.getNumBytesUploaded());
        }

        break;
    case MEDIA_COMPLETE:
        if (stopwatch.isRunning()) {
            stopwatch.stop();
        }
        log.info(String.format("Upload is complete! (%s)", stopwatch));
        if (this.callback != null) {
            this.callback.execute();
        }
        break;
    case NOT_STARTED:
        break;
    }
}