Search in sources :

Example 26 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class UploadVideo method main.

/**
 * Upload the user-selected video to the user's YouTube channel. The code
 * looks for the video in the application's project folder and uses OAuth
 * 2.0 to authorize the API request.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();
        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);
        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();
        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);
        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4"));
        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();
        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) Credential(com.google.api.client.auth.oauth2.Credential) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) VideoStatus(com.google.api.services.youtube.model.VideoStatus) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 27 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class VideoLocalizations method main.

/**
 * Set and retrieve localized metadata for a video.
 *
 * @param args command line args (not used).
 */
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, "localizations");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-localizations-sample").build();
        // Prompt the user to specify the action of the be achieved.
        String actionString = getActionFromUser();
        System.out.println("You chose " + actionString + ".");
        // Map the user input to the enum values.
        Action action = Action.valueOf(actionString.toUpperCase());
        switch(action) {
            case SET:
                setVideoLocalization(getId("video"), getDefaultLanguage(), getLanguage(), getMetadata("title"), getMetadata("description"));
                break;
            case GET:
                getVideoLocalization(getId("video"), getLanguage());
                break;
            case LIST:
                listVideoLocalizations(getId("video"));
                break;
        }
    } 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();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube)

Example 28 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class ListBroadcasts method main.

/**
 * List broadcasts for the user's channel.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows for read-only access to the
    // authenticated user's account, but not other types of account access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "listbroadcasts");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-listbroadcasts-sample").build();
        // Create a request to list broadcasts.
        YouTube.LiveBroadcasts.List liveBroadcastRequest = youtube.liveBroadcasts().list("id,snippet");
        // Indicate that the API response should not filter broadcasts
        // based on their type or status.
        liveBroadcastRequest.setBroadcastType("all").setBroadcastStatus("all");
        // Execute the API request and return the list of broadcasts.
        LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
        List<LiveBroadcast> returnedList = returnedListResponse.getItems();
        // Print information from the API response.
        System.out.println("\n================== Returned Broadcasts ==================\n");
        for (LiveBroadcast broadcast : returnedList) {
            System.out.println("  - Id: " + broadcast.getId());
            System.out.println("  - Title: " + broadcast.getSnippet().getTitle());
            System.out.println("  - Description: " + broadcast.getSnippet().getDescription());
            System.out.println("  - Published At: " + broadcast.getSnippet().getPublishedAt());
            System.out.println("  - Scheduled Start Time: " + broadcast.getSnippet().getScheduledStartTime());
            System.out.println("  - Scheduled End Time: " + broadcast.getSnippet().getScheduledEndTime());
            System.out.println("\n-------------------------------------------------------------\n");
        }
    } 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();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) LiveBroadcast(com.google.api.services.youtube.model.LiveBroadcast) LiveBroadcastListResponse(com.google.api.services.youtube.model.LiveBroadcastListResponse) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException)

Example 29 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class DeleteLiveChatMessage method main.

/**
 * Deletes a message from a live broadcast.
 *
 * @param args The message id to delete (required) followed by the videoId (optional). If the
 * videoId is given, live chat messages will be retrieved from the chat associated with this
 * video. If the videoId is not specified, the signed in user's current live broadcast will be
 * used instead.
 */
public static void main(String[] args) {
    // Get the message id to delete
    if (args.length == 0) {
        System.err.println("No message id specified");
        System.exit(1);
    }
    String messageId = args[0];
    // This OAuth 2.0 access scope allows for write access to the authenticated user's account.
    List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_FORCE_SSL);
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "deletelivechatmessage");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-deletechatmessages-sample").build();
        // Delete the message from live chat
        YouTube.LiveChatMessages.Delete liveChatDelete = youtube.liveChatMessages().delete(messageId);
        liveChatDelete.execute();
        System.out.println("Deleted message id " + messageId);
    } 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();
    }
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube)

Example 30 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project api-samples by youtube.

the class InsertLiveChatMessage method main.

/**
 * Inserts a message into a live broadcast.
 *
 * @param args The message to insert (required) followed by the videoId (optional).
 * If the videoId is given, live chat messages will be retrieved from the chat associated with
 * this video. If the videoId is not specified, the signed in user's current live broadcast will
 * be used instead.
 */
public static void main(String[] args) {
    // Get the chat message to insert
    if (args.length == 0) {
        System.err.println("No message specified");
        System.exit(1);
    }
    String message = args[0];
    // This OAuth 2.0 access scope allows for write access to the authenticated user's account.
    List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_FORCE_SSL);
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "insertlivechatmessage");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-insertchatmessage-sample").build();
        // Get the liveChatId
        String liveChatId = args.length == 2 ? GetLiveChatId.getLiveChatId(youtube, args[1]) : GetLiveChatId.getLiveChatId(youtube);
        if (liveChatId != null) {
            System.out.println("Live chat id: " + liveChatId);
        } else {
            System.err.println("Unable to find a live chat id");
            System.exit(1);
        }
        // Insert the message into live chat
        LiveChatMessage liveChatMessage = new LiveChatMessage();
        LiveChatMessageSnippet snippet = new LiveChatMessageSnippet();
        snippet.setType("textMessageEvent");
        snippet.setLiveChatId(liveChatId);
        LiveChatTextMessageDetails details = new LiveChatTextMessageDetails();
        details.setMessageText(message);
        snippet.setTextMessageDetails(details);
        liveChatMessage.setSnippet(snippet);
        YouTube.LiveChatMessages.Insert liveChatInsert = youtube.liveChatMessages().insert("snippet", liveChatMessage);
        LiveChatMessage response = liveChatInsert.execute();
        System.out.println("Inserted message id " + response.getId());
    } 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();
    }
}
Also used : LiveChatTextMessageDetails(com.google.api.services.youtube.model.LiveChatTextMessageDetails) Credential(com.google.api.client.auth.oauth2.Credential) LiveChatMessage(com.google.api.services.youtube.model.LiveChatMessage) LiveChatMessageSnippet(com.google.api.services.youtube.model.LiveChatMessageSnippet) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException)

Aggregations

GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)90 IOException (java.io.IOException)45 YouTube (com.google.api.services.youtube.YouTube)26 Credential (com.google.api.client.auth.oauth2.Credential)25 Operation (com.google.api.services.compute.model.Operation)12 ArrayList (java.util.ArrayList)12 Test (org.junit.Test)12 Compute (com.google.api.services.compute.Compute)11 Storage (com.google.api.services.storage.Storage)10 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)8 GcsOptions (org.apache.beam.sdk.extensions.gcp.options.GcsOptions)7 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)5 InputStreamContent (com.google.api.client.http.InputStreamContent)5 BackOff (com.google.api.client.util.BackOff)5 HashMap (java.util.HashMap)5 Objects (com.google.api.services.storage.model.Objects)4 GoogleCloudStorage (com.google.cloud.hadoop.gcsio.GoogleCloudStorage)4 HalException (com.netflix.spinnaker.halyard.core.error.v1.HalException)4 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3