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

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

Introduction

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

Prototype

public MediaHttpUploader setChunkSize(int chunkSize) 

Source Link

Document

Sets the maximum size of individual chunks that will get uploaded by single HTTP requests.

Usage

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

License:Apache License

/**
 * Uploads {@link #setArchive(File) specified file} to Google Drive.
 *//*from w ww  . jav a 2s  .  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.example.youtubeuploadv3.AsyncLoadYoutube.java

License:Apache License

@Override
protected Video doInBackground() throws IOException {
    /*     //from   w  ww .  j a  v a 2 s. c  o m
        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.wiwit.eplweb.util.youtube.api.VideoService.java

License:Apache License

public static void doChangeThumbnail(String videoId, InputStream imageStream) {
    // 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 {/*from  w  w  w . j  a  va  2  s .  c  om*/
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "youtube");

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

        // Create an object that contains the thumbnail image file's
        // contents.
        InputStreamContent mediaContent = new InputStreamContent(IMAGE_FILE_FORMAT, imageStream);

        // 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);
        uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);

        // Set the upload state for the thumbnail image.
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            @Override
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    logger.info("INITIATION_STARTED");
                    break;
                case INITIATION_COMPLETE:
                    logger.info("INITIATION_COMPLETE");
                    break;
                case MEDIA_IN_PROGRESS:
                    logger.info("MEDIA_IN_PROGRESS : " + uploader.getProgress());
                    break;
                case MEDIA_COMPLETE:
                    logger.info("MEDIA_COMPLETE");
                    break;
                case NOT_STARTED:
                    logger.info("NOT_STARTED");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

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

    } catch (GoogleJsonResponseException e) {
        logger.info("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.info("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        logger.error("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:com.yt.uploader.services.YouTubeService.java

public Video uploadVideo(VideoVO inVideoInfo, ApplicationOptionsVO inOpts) throws IOException {
    System.out.println("Uploading: " + inVideoInfo.getTitle());

    // Execute upload with retries
    int remainingRetries = inOpts.getFailedUploadNumOfRetries();
    while (remainingRetries > 0) {
        try {//from   www.ja  v  a 2  s  .c o m
            // Add extra information to the video before uploading.
            Video videoObjectDefiningMetadata = new Video();

            VideoStatus status = new VideoStatus();
            status.setPrivacyStatus(inVideoInfo.getPrivacySetting().getCode());
            status.setEmbeddable(Boolean.TRUE);
            status.setLicense(inVideoInfo.getLicenseType().getCode());
            videoObjectDefiningMetadata.setStatus(status);

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

            snippet.setTitle(inVideoInfo.getTitle());
            snippet.setDescription(inVideoInfo.getDescription());

            snippet.setTags(inVideoInfo.getTagList());

            snippet.setCategoryId(inVideoInfo.getCategoryType().getCode());

            videoObjectDefiningMetadata.setSnippet(snippet);

            InputStreamContent mediaContent = new InputStreamContent(Constants.VIDEO_FILE_FORMAT,
                    new BufferedInputStream(new FileInputStream(inVideoInfo.getVideoFile())));

            mediaContent.setLength(inVideoInfo.getVideoFile().length());

            YouTube.Videos.Insert videoInsert = getYouTubeInstance(true).videos()
                    .insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);

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

            uploader.setDirectUploadEnabled(inOpts.getForceDirectUpload());
            uploader.setChunkSize(inOpts.getUploadChunkSize());
            uploader.setProgressListener(new MediaUploadProgressListener());

            Video returnedVideo = videoInsert.execute();
            return returnedVideo;
        } catch (Exception e) {
            remainingRetries--;
            System.out.println(
                    "ERROR while uploading the video " + inVideoInfo.getTitle() + ": " + e.getMessage());
            System.out.println("Remaining attempts: " + remainingRetries);
        }
    }
    throw new IOException("Failed all attempts to upload the video " + inVideoInfo.getTitle()
            + ". The service might be down.");
}

From source file:fiuba.challenge.youtube.AsyncLoadYoutube.java

License:Apache License

@Override
protected Video doInBackground() throws IOException {

    String VIDEO_FILE_FORMAT = "video/*";

    Uri videoUri = activity.videoUri;/*from ww  w.ja  v a2  s . co  m*/
    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("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("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 = null;
        try {
            returnedVideo = videoInsert.execute();
            String videoId = returnedVideo.getId();

            Log.d(TAG, String.format("videoId = [%s]", videoId));
            context.endSubmit(videoId);
        } catch (UserRecoverableAuthIOException e) {

            ((Activity) context).startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
        }

        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:org.blom.martin.stream2gdrive.Stream2GDrive.java

License:Apache License

public static void upload(Drive client, String local, String root, String remote, String mime, boolean progress,
        float chunkSize) throws IOException {

    com.google.api.services.drive.model.File meta = new com.google.api.services.drive.model.File();
    meta.setTitle(remote);//from  w  ww .j  a va2  s  . co  m
    meta.setMimeType(mime);

    if (root != null) {
        meta.setParents(Arrays.asList(new ParentReference().setId(root)));
    }

    AbstractInputStreamContent isc = local.equals("-") ? new StreamContent(meta.getMimeType(), System.in)
            : new FileContent(meta.getMimeType(), new File(local));

    Drive.Files.Insert insert = client.files().insert(meta, isc);

    MediaHttpUploader ul = insert.getMediaHttpUploader();
    ul.setDirectUploadEnabled(false);
    ul.setChunkSize(calcChunkSize(chunkSize));

    if (progress) {
        ul.setProgressListener(new ProgressListener());
    }

    // Streaming upload with GZip encoding has horrible performance!
    insert.setDisableGZipContent(isc instanceof StreamContent);

    insert.execute();
}

From source file:org.mrpdaemon.android.encdroid.GoogleDriveOutputStream.java

License:Open Source License

public GoogleDriveOutputStream(final GoogleDriveFileProvider fileProvider, final String dstPath,
        final long length) throws IOException {
    this.failed = false;

    Log.d(TAG, "Creating output stream for path " + dstPath);

    // Create pipes
    pipeDrive = new PipedInputStream();
    pipeToWrite = new PipedOutputStream(pipeDrive);

    // Delete file touched by encfs-java
    if (fileProvider.exists(dstPath)) {
        fileProvider.delete(dstPath);/*from w w w .j a v a 2 s.  co  m*/
    }

    final File newFile = fileProvider.prepareFileForCreation(dstPath);

    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                InputStreamContent streamContent = new InputStreamContent("application/octet-stream",
                        pipeDrive);
                streamContent.setLength(length);

                Drive.Files.Insert insert = fileProvider.getDriveService().files().insert(newFile,
                        streamContent);

                // Use resumable upload to not time out for larger files
                MediaHttpUploader uploader = insert.getMediaHttpUploader();
                uploader.setDirectUploadEnabled(false);
                uploader.setChunkSize(MediaHttpUploader.DEFAULT_CHUNK_SIZE);

                insert.execute();

            } catch (IOException e) {
                if (e.getMessage() != null) {
                    GoogleDriveOutputStream.this.fail(e.getMessage());
                } else {
                    GoogleDriveOutputStream.this.fail(e.toString());
                }
            }
        }
    });

    thread.start();
}