Example usage for com.google.common.collect Lists newArrayList

List of usage examples for com.google.common.collect Lists newArrayList

Introduction

In this page you can find the example usage for com.google.common.collect Lists newArrayList.

Prototype

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) 

Source Link

Document

Creates a mutable ArrayList instance containing the given elements; a very thin shortcut for creating an empty list and then calling Iterators#addAll .

Usage

From source file:com.mrmq.uyoutube.data.ChannelLocalizations.java

/**
 * Set and retrieve localized metadata for a channel.
 *
 * @param args command line args (not used).
 *///from   ww  w .ja  v a 2  s.com
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:
            setChannelLocalization(getId("channel"), getDefaultLanguage(), getLanguage(),
                    getMetadata("description"));
            break;
        case GET:
            getChannelLocalization(getId("channel"), getLanguage());
            break;
        case LIST:
            listChannelLocalizations(getId("channel"));
            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();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.reporting.RetrieveReports.java

/**
 * Retrieve reports./*from  www  .  j  av a 2 s. co  m*/
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    /*
     * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
     * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
     * use this scope.
     */
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");

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

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

        if (listReportingJobs()) {
            if (retrieveReports(getJobIdFromUser())) {
                downloadReport(getReportUrlFromUser());
            }
        }
    } 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:edu.harvard.med.screensaver.io.libraries.LibraryCreator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    CommandLineApplication app = new CommandLineApplication(args);
    try {//from   w  w  w . j ava  2s  .  c  om
        DateTimeFormatter dateFormat = DateTimeFormat.forPattern(CommandLineApplication.DEFAULT_DATE_PATTERN);

        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("library name")
                .withLongOpt("name").withDescription("full, official name for the library").create("n"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("short name").withLongOpt("short-name")
                        .withDescription("a short name for identifying the library").create("s"));
        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("library type")
                .withLongOpt("library-type").withDescription(StringUtils.makeListString(Lists.transform(
                        Lists.newArrayList(LibraryType.values()), new Function<LibraryType, String>() {
                            @Override
                            public String apply(LibraryType arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .create("lt"));
        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("screen type")
                .withLongOpt("screen-type").withDescription(StringUtils.makeListString(Lists
                        .transform(Lists.newArrayList(ScreenType.values()), new Function<ScreenType, String>() {
                            @Override
                            public String apply(ScreenType arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .create("st"));
        app.addCommandLineOption(OptionBuilder.hasArg(false).withLongOpt("is-pool")
                .withDescription("well contents are pools of reagents (only valid when library-type=RNAI)")
                .create("ip"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("start-plate").create("sp"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("end-plate").create("ep"));

        app.addCommandLineOption(
                OptionBuilder.hasArg().withArgName("name").withLongOpt("provider").create("lp"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().withArgName("text").withLongOpt("description").create("d"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName(CommandLineApplication.DEFAULT_DATE_PATTERN)
                .withLongOpt("date-received").create("dr"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName(CommandLineApplication.DEFAULT_DATE_PATTERN)
                .withLongOpt("date-screenable").create("ds"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName("plate size")
                .withDescription(StringUtils.makeListString(Lists
                        .transform(Lists.newArrayList(PlateSize.values()), new Function<PlateSize, String>() {
                            @Override
                            public String apply(PlateSize arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .withLongOpt("plate-size").create("ps"));

        app.processOptions(true, true);

        String libraryName = app.getCommandLineOptionValue("n");
        String shortName = app.getCommandLineOptionValue("s");
        LibraryType libraryType = app.getCommandLineOptionEnumValue("lt", LibraryType.class);
        boolean isPool = app.isCommandLineFlagSet("ip");
        ScreenType screenType = app.getCommandLineOptionEnumValue("st", ScreenType.class);
        int startPlate = app.getCommandLineOptionValue("sp", Integer.class);
        int endPlate = app.getCommandLineOptionValue("ep", Integer.class);
        String vendor = app.isCommandLineFlagSet("lp") ? app.getCommandLineOptionValue("lp") : null;
        String description = app.isCommandLineFlagSet("d") ? app.getCommandLineOptionValue("d") : null;
        LocalDate dateReceived = app.isCommandLineFlagSet("dr")
                ? app.getCommandLineOptionValue("dr", dateFormat).toLocalDate()
                : null;
        LocalDate dateScreenable = app.isCommandLineFlagSet("ds")
                ? app.getCommandLineOptionValue("ds", dateFormat).toLocalDate()
                : null;
        PlateSize plateSize = app.isCommandLineFlagSet("ps")
                ? app.getCommandLineOptionEnumValue("ps", PlateSize.class)
                : ScreensaverConstants.DEFAULT_PLATE_SIZE;

        Library library = new Library(app.findAdministratorUser(), libraryName, shortName, screenType,
                libraryType, startPlate, endPlate, plateSize);
        library.setPool(isPool);
        library.setDescription(description);
        library.setProvider(vendor);
        library.setDateReceived(dateReceived);
        library.setDateScreenable(dateScreenable);

        edu.harvard.med.screensaver.service.libraries.LibraryCreator libraryCreator = (edu.harvard.med.screensaver.service.libraries.LibraryCreator) app
                .getSpringBean("libraryCreator");
        libraryCreator.createLibrary(library);
        log.info("library succesfully added to database");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.toString());
        System.err.println("error: " + e.getMessage());
        System.exit(1);
    }
}

From source file:com.mrmq.uyoutube.data.PlaylistLocalizations.java

/**
 * Set and retrieve localized metadata for a playlist.
 *
 * @param args command line args (not used).
 *///from  w  w w .java  2s  .co  m
public static void main(String[] args) {

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

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "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:
            setPlaylistLocalization(getId("playlist"), getDefaultLanguage(), getLanguage(),
                    getMetadata("title"), getMetadata("description"));
            break;
        case GET:
            getPlaylistLocalization(getId("playlist"), getLanguage());
            break;
        case LIST:
            listPlaylistLocalizations(getId("playlist"));
            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();
    }
}

From source file:org.carrot2.examples.core.LoadingAttributeValuesFromXml.java

public static void main(String[] args) throws Exception {
    InputStream xmlStream = null;
    try {/*from w ww .ja  v a  2  s  .  c o m*/
        xmlStream = LoadingAttributeValuesFromXml.class.getResourceAsStream("algorithm-lingo-attributes.xml");

        // Load attribute value sets from the XML stream
        final AttributeValueSets attributeValueSets = AttributeValueSets.deserialize(xmlStream);

        // Get the desired set of attribute values for use with further processing
        final Map<String, Object> defaultAttributes = attributeValueSets.getDefaultAttributeValueSet()
                .getAttributeValues();

        final Map<String, Object> fasterClusteringAttributes = attributeValueSets
                .getAttributeValueSet("faster-clustering").getAttributeValues();

        // Perform processing using the attribute values
        final Controller controller = ControllerFactory.createSimple();

        // Initialize the controller with one attribute set
        controller.init(fasterClusteringAttributes);

        // Perform clustering using the attribute set provided at initialization time
        Map<String, Object> requestAttributes = Maps.newHashMap();
        CommonAttributesDescriptor.attributeBuilder(requestAttributes)
                .documents(Lists.newArrayList(SampleDocumentData.DOCUMENTS_DATA_MINING)).query("data mining");
        ProcessingResult results = controller.process(requestAttributes, LingoClusteringAlgorithm.class);
        ConsoleFormatter.displayClusters(results.getClusters());

        // Perform clustering using some other attribute set, in this case the
        // one that is the default in the XML file.
        requestAttributes = CommonAttributesDescriptor.attributeBuilder(Maps.newHashMap(defaultAttributes))
                .documents(Lists.newArrayList(SampleDocumentData.DOCUMENTS_DATA_MINING))
                .query("data mining").map;

        results = controller.process(requestAttributes, LingoClusteringAlgorithm.class);
        ConsoleFormatter.displayClusters(results.getClusters());
    } finally {
        CloseableUtils.close(xmlStream);
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.data.CommentThreads.java

/**
 * Create, list and update top-level channel and video comments.
 *
 * @param args command line args (not used).
 */// ww  w  .j  a va  2 s. co m
public static void main(String[] args) {

    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account and requires requests to use an SSL connection.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");

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

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

        // Prompt the user for the ID of a channel to comment on.
        // Retrieve the channel ID that the user is commenting to.
        String channelId = getChannelId();
        System.out.println("You chose " + channelId + " to subscribe.");

        // Prompt the user for the ID of a video to comment on.
        // Retrieve the video ID that the user is commenting to.
        String videoId = getVideoId();
        System.out.println("You chose " + videoId + " to subscribe.");

        // Prompt the user for the comment text.
        // Retrieve the text that the user is commenting.
        String text = getText();
        System.out.println("You chose " + text + " to subscribe.");

        // Insert channel comment by omitting videoId.
        // Create a comment snippet with text.
        CommentSnippet commentSnippet = new CommentSnippet();
        commentSnippet.setTextOriginal(text);

        // Create a top-level comment with snippet.
        Comment topLevelComment = new Comment();
        topLevelComment.setSnippet(commentSnippet);

        // Create a comment thread snippet with channelId and top-level
        // comment.
        CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
        commentThreadSnippet.setChannelId(channelId);
        commentThreadSnippet.setTopLevelComment(topLevelComment);

        // Create a comment thread with snippet.
        CommentThread commentThread = new CommentThread();
        commentThread.setSnippet(commentThreadSnippet);

        // Call the YouTube Data API's commentThreads.insert method to
        // create a comment.
        CommentThread channelCommentInsertResponse = youtube.commentThreads().insert("snippet", commentThread)
                .execute();
        // Print information from the API response.
        System.out.println("\n================== Created Channel Comment ==================\n");
        CommentSnippet snippet = channelCommentInsertResponse.getSnippet().getTopLevelComment().getSnippet();
        System.out.println("  - Author: " + snippet.getAuthorDisplayName());
        System.out.println("  - Comment: " + snippet.getTextDisplay());
        System.out.println("\n-------------------------------------------------------------\n");

        // Insert video comment
        commentThreadSnippet.setVideoId(videoId);
        // Call the YouTube Data API's commentThreads.insert method to
        // create a comment.
        CommentThread videoCommentInsertResponse = youtube.commentThreads().insert("snippet", commentThread)
                .execute();
        // Print information from the API response.
        System.out.println("\n================== Created Video Comment ==================\n");
        snippet = videoCommentInsertResponse.getSnippet().getTopLevelComment().getSnippet();
        System.out.println("  - Author: " + snippet.getAuthorDisplayName());
        System.out.println("  - Comment: " + snippet.getTextDisplay());
        System.out.println("\n-------------------------------------------------------------\n");

        // Call the YouTube Data API's commentThreads.list method to
        // retrieve video comment threads.
        V3CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads().list("snippet")
                .setVideoId(videoId).setTextFormat("plainText").execute();
        List<CommentThread> videoComments = videoCommentsListResponse.getItems();

        if (videoComments.isEmpty()) {
            System.out.println("Can't get video comments.");
        } else {
            // Print information from the API response.
            System.out.println("\n================== Returned Video Comments ==================\n");
            for (CommentThread videoComment : videoComments) {
                snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
                System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                System.out.println("  - Comment: " + snippet.getTextDisplay());
                System.out.println("\n-------------------------------------------------------------\n");
            }
            CommentThread firstComment = videoComments.get(0);
            firstComment.getSnippet().getTopLevelComment().getSnippet().setTextOriginal("updated");
            CommentThread videoCommentUpdateResponse = youtube.commentThreads().update("snippet", firstComment)
                    .execute();
            // Print information from the API response.
            System.out.println("\n================== Updated Video Comment ==================\n");
            snippet = videoCommentUpdateResponse.getSnippet().getTopLevelComment().getSnippet();
            System.out.println("  - Author: " + snippet.getAuthorDisplayName());
            System.out.println("  - Comment: " + snippet.getTextDisplay());
            System.out.println("\n-------------------------------------------------------------\n");

        }

        // Call the YouTube Data API's commentThreads.list method to
        // retrieve channel comment threads.
        V3CommentThreadListResponse channelCommentsListResponse = youtube.commentThreads().list("snippet")
                .setChannelId(channelId).setTextFormat("plainText").execute();
        List<CommentThread> channelComments = channelCommentsListResponse.getItems();

        if (channelComments.isEmpty()) {
            System.out.println("Can't get channel comments.");
        } else {
            // Print information from the API response.
            System.out.println("\n================== Returned Channel Comments ==================\n");
            for (CommentThread channelComment : channelComments) {
                snippet = channelComment.getSnippet().getTopLevelComment().getSnippet();
                System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                System.out.println("  - Comment: " + snippet.getTextDisplay());
                System.out.println("\n-------------------------------------------------------------\n");
            }
            CommentThread firstComment = channelComments.get(0);
            firstComment.getSnippet().getTopLevelComment().getSnippet().setTextOriginal("updated");
            CommentThread channelCommentUpdateResponse = youtube.commentThreads()
                    .update("snippet", firstComment).execute();
            // Print information from the API response.
            System.out.println("\n================== Updated Channel Comment ==================\n");
            snippet = channelCommentUpdateResponse.getSnippet().getTopLevelComment().getSnippet();
            System.out.println("  - Author: " + snippet.getAuthorDisplayName());
            System.out.println("  - Comment: " + snippet.getTextDisplay());
            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();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.data.PlaylistLocalizations.java

/**
 * Set and retrieve localized metadata for a playlist.
 *
 * @param args command line args (not used).
 *//* w  ww .  j  a  v a 2s  .  c  o m*/
public static void main(String[] args) {

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

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "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:
        //                    setPlaylistLocalization(getId("playlist"), getDefaultLanguage(),
        //                            getLanguage(), getMetadata("title"), getMetadata("description"));
        //                    break
        case GET:
            getPlaylistLocalization(getId("playlist"), getLanguage());
            break;
        case LIST:
            listPlaylistLocalizations(getId("playlist"));
            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();
    }
}

From source file:at.molindo.esi4j.integration.DummyIntegration.java

public static void main(String[] args) {

    Esi4J esi4j = new DefaultEsi4J(ImmutableSettings.settingsBuilder().put("esi4j.client.type", "node")
            .put("index.store.type", "ram").put("index.refresh_interval", "-1").put("node.data", true)
            .put("node.local", true).put("gateway.type", "none").build());

    Esi4JIndex index = esi4j.getIndex();

    ((InternalIndex) index).addTypeMapping(new TweetTypeMapping("tweet"));

    Tweet t1 = new Tweet(1, "sfussenegger", "esi4j rocks #elasticsearch");
    Tweet t4 = new Tweet(3, "msparer", "esi4j really rocks");

    Integer id = (Integer) index.index(t1).actionGet().getId();
    System.out.println("indexed: " + id);
    index.index(t4).actionGet().getId();

    index.refresh();/* w  ww . j ava  2s  .  c o m*/

    Tweet t2 = (Tweet) index.get(Tweet.class, id).actionGet().getObject();
    System.out.println(t1.equals(t2));

    Tweet none = (Tweet) index.get(Tweet.class, 4711).actionGet().getObject();
    System.out.println(none == null);

    List<Tweet> tweets = index.multiGet(Tweet.class, Arrays.asList(new Integer[] { 1, 2, 3 })).actionGet()
            .getObjects(Tweet.class);
    System.out.println("multi: " + tweets.contains(t1));
    System.out.println("multi: " + tweets.contains(t4));

    t1.setUser("dummy");

    Esi4JDummyModule module = new Esi4JDummyModule().setData(Tweet.class, Lists.newArrayList(t1));
    new SimpleRebuildProcessor().rebuild((InternalIndex) index, module.startRebuildSession(Tweet.class));

    Tweet t3 = (Tweet) index.get(Tweet.class, id).actionGet().getObject();
    System.out.println(t1.equals(t3));
}

From source file:com.google.api.services.samples.youtube.cmdline.data.VideoLocalizations.java

/**
 * Set and retrieve localized metadata for a video.
 *
 * @param args command line args (not used).
 *///w  w  w. j  a v a2  s  . com
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();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.live.InsertLiveChatMessage.java

/**
 * 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.//from  w w w  .jav a2 s .c om
 */
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();
    }
}