Example usage for com.google.common.collect ImmutableList builder

List of usage examples for com.google.common.collect ImmutableList builder

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList builder.

Prototype

public static <E> Builder<E> builder() 

Source Link

Usage

From source file:com.acme.scramble.ScrambleScorerMain.java

public static void main(String[] args) throws IOException, URISyntaxException {
    ScrambleScorerMain scorerMain = new ScrambleScorerMain(new ScrambleScorer(), new ImmutableList.Builder<>());

    if (args == null || args.length == 1) {
        File file = new File(args[0]);
        if (file.exists()) {
            Files.readLines(file, UTF_8, scorerMain);
            return;
        }//  w w w  . ja v  a  2s  .c  om

        System.err.println("Input file '" + file + "' not found.");
    } else {
        URL resource = Resources.getResource("sample_input.txt");
        CharSource charSource = Resources.asCharSource(resource, UTF_8);
        charSource.readLines(scorerMain);
    }

}

From source file:com.github.hilcode.versionator.Main.java

public static final void main(final String[] args) throws Exception {
    final PomParser pomParser = new DefaultPomParser();
    final PomFinder pomFinder = new DefaultPomFinder(pomParser);
    final CommandLineInterface.Basics basics = new CommandLineInterface.Basics();
    final JCommander commander = new JCommander(basics);
    final CommandLineInterface.CommandList commandList = new CommandLineInterface.CommandList();
    commander.addCommand(CommandLineInterface.CommandList.COMMAND, commandList);
    final CommandSetVersion commandSetVersion = new CommandSetVersion();
    commander.addCommand(CommandSetVersion.COMMAND, commandSetVersion);
    final CommandRelease commandRelease = new CommandRelease();
    commander.addCommand(CommandRelease.COMMAND, commandRelease);
    try {/*from   w  w w . j  av  a2  s .  co  m*/
        commander.parse(args);
        if (basics.help != null || basics.version != null) {
            if (basics.version != null) {
                System.out.println(
                        String.format("Versionator %s\n%s", Versionator.VERSION, Versionator.RELEASE_DATE));
            }
            if (basics.help != null) {
                commander.usage();
            }
            return;
        }
        if (CommandLineInterface.CommandList.COMMAND.equals(commander.getParsedCommand())) {
            final Command.List list = new Command.List(new File(commandList.rootDir),
                    ImmutableList.copyOf(commandList.patterns),
                    commandList.verbose ? Command.Verbosity.VERBOSE : Command.Verbosity.NORMAL,
                    commandList.groupByPom ? Command.Grouping.BY_POM : Command.Grouping.BY_GAV);
            new ListExecutor(pomParser, pomFinder, list).execute();
        } else if (CommandSetVersion.COMMAND.equals(commander.getParsedCommand())) {
            final Command.SetVersion setVersion = new Command.SetVersion(new File(commandSetVersion.rootDir),
                    commandSetVersion.dryRun ? Command.RunType.DRY_RUN : Command.RunType.ACTUAL,
                    commandSetVersion.interactive ? Command.Interactivity.INTERACTIVE
                            : Command.Interactivity.NOT_INTERACTIVE,
                    commandSetVersion.colourless ? Command.Colour.NO_COLOUR : Command.Colour.COLOUR,
                    ImmutableList.<String>copyOf(commandSetVersion.gavs));
            final Model model = Model.BUILDER.build(pomFinder.findAllPoms(setVersion.rootDir));
            final ImmutableList.Builder<Gav> changedGavsBuilder = ImmutableList.builder();
            for (final String gavAsText : setVersion.gavs) {
                changedGavsBuilder.add(Gav.BUILDER.build(gavAsText));
            }
            final Model result = model.apply(changedGavsBuilder.build());
            final ModelWriter modelWriter = new ModelWriter(new VersionSetter(), new PropertySetter());
            modelWriter.write(model, result);
        } else if (CommandRelease.COMMAND.equals(commander.getParsedCommand())) {
            final Command.Release release = new Command.Release(new File(commandRelease.rootDir),
                    commandRelease.dryRun ? Command.RunType.DRY_RUN : Command.RunType.ACTUAL,
                    commandRelease.interactive ? Command.Interactivity.INTERACTIVE
                            : Command.Interactivity.NOT_INTERACTIVE,
                    commandRelease.colourless ? Command.Colour.NO_COLOUR : Command.Colour.COLOUR,
                    ImmutableList.<String>copyOf(commandRelease.exclusions));
            final ImmutableSet.Builder<GroupArtifact> exclusionsBuilder = ImmutableSet.builder();
            for (final String exclusionAsText : release.exclusions) {
                exclusionsBuilder.add(GroupArtifact.BUILDER.build(exclusionAsText));
            }
            final ImmutableSet<GroupArtifact> exclusions = exclusionsBuilder.build();
            final Model model = Model.BUILDER.build(pomFinder.findAllPoms(release.rootDir));
            final Model result = model.release(exclusions);
            final ModelWriter modelWriter = new ModelWriter(new VersionSetter(), new PropertySetter());
            modelWriter.write(model, result);
        } else {
            System.err.println("No command provided. Perhaps try --help?");
        }
    } catch (final ParameterException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.google.devtools.build.skydoc.SkydocMain.java

public static void main(String[] args) throws IOException, InterruptedException {
    if (args.length != 2) {
        throw new IllegalArgumentException(
                "Expected two arguments. Usage:\n" + "{skydoc_bin} {target_skylark_file} {output_file}");
    }//from  w w w .  j  ava  2 s  .c om

    String bzlPath = args[0];
    String outputPath = args[1];

    Path path = Paths.get(bzlPath);
    byte[] content = Files.readAllBytes(path);

    ParserInputSource parserInputSource = ParserInputSource.create(content,
            PathFragment.create(path.toString()));

    ImmutableMap.Builder<String, RuleInfo> ruleInfoMap = ImmutableMap.builder();
    ImmutableList.Builder<RuleInfo> unexportedRuleInfos = ImmutableList.builder();

    new SkydocMain().eval(parserInputSource, ruleInfoMap, unexportedRuleInfos);

    try (PrintWriter printWriter = new PrintWriter(outputPath, "UTF-8")) {
        printRuleInfos(printWriter, ruleInfoMap.build(), unexportedRuleInfos.build());
    }
}

From source file:org.apache.jclouds.examples.chef.basics.MainApp.java

public static void main(final String[] args) {
    if (args.length < PARAMETERS) {
        throw new IllegalArgumentException(INVALID_SYNTAX);
    }//from  www .  jav a 2 s . com

    String provider = args[0];
    String identity = args[1];
    String credential = args[2];
    String groupName = args[3];
    Action action = Action.valueOf(args[4].toUpperCase());
    if ((action == Action.CHEF || action == Action.SOLO) && args.length < PARAMETERS + 1) {
        throw new IllegalArgumentException(
                "please provide the list of recipes to install, separated by commas");
    }
    String recipes = action == Action.CHEF || action == Action.SOLO ? args[5] : "apache2";

    String minRam = System.getProperty("minRam");

    // note that you can check if a provider is present ahead of time
    checkArgument(contains(allKeys, provider), "provider %s not in supported list: %s", provider, allKeys);

    LoginCredentials login = action != Action.DESTROY ? getLoginForCommandExecution(action) : null;

    ComputeService compute = initComputeService(provider, identity, credential);

    try {
        switch (action) {
        case ADD:
            System.out.printf(">> adding node to group %s%n", groupName);

            // Default template chooses the smallest size on an operating
            // system that tested to work with java
            TemplateBuilder templateBuilder = compute.templateBuilder();
            templateBuilder.osFamily(OsFamily.UBUNTU);

            // If you want to up the ram and leave everything default, you
            // can just tweak minRam
            if (minRam != null) {
                templateBuilder.minRam(Integer.parseInt(minRam));
            }

            // note this will create a user with the same name as you on the
            // node. ex. you can connect via ssh publicip
            Statement bootInstructions = AdminAccess.standard();

            // to run commands as root, we use the runScript option in the
            // template.
            templateBuilder.options(runScript(bootInstructions));

            NodeMetadata node = getOnlyElement(
                    compute.createNodesInGroup(groupName, 1, templateBuilder.build()));
            System.out.printf("<< node %s: %s%n", node.getId(),
                    concat(node.getPrivateAddresses(), node.getPublicAddresses()));

        case SOLO:
            System.out.printf(">> installing [%s] on group %s as %s%n", recipes, groupName, login.identity);

            Iterable<String> recipeList = Splitter.on(',').split(recipes);
            ImmutableList.Builder<Statement> bootstrapBuilder = ImmutableList.builder();
            bootstrapBuilder.add(new InstallGit());

            // Clone community cookbooks into the node
            for (String recipe : recipeList) {
                bootstrapBuilder.add(CloneGitRepo.builder()
                        .repository("git://github.com/opscode-cookbooks/" + recipe + ".git")
                        .directory("/var/chef/cookbooks/" + recipe) //
                        .build());
            }

            // Configure Chef Solo to bootstrap the selected recipes
            bootstrapBuilder.add(new InstallChefUsingOmnibus());
            bootstrapBuilder.add(ChefSolo.builder() //
                    .cookbookPath("/var/chef/cookbooks") //
                    .runlist(RunList.builder().recipes(recipeList).build()) //
                    .build());

            // Build the statement that will perform all the operations above
            StatementList bootstrap = new StatementList(bootstrapBuilder.build());

            // Run the script in the nodes of the group
            runScriptOnGroup(compute, login, groupName, bootstrap);
            break;
        case CHEF:
            // Create the connection to the Chef server
            ChefService chef = initChefService(System.getProperty("chef.client"),
                    System.getProperty("chef.validator"));

            // Build the runlist for the deployed nodes
            System.out.println("Configuring node runlist in the Chef server...");
            List<String> runlist = new RunListBuilder().addRecipes(recipes.split(",")).build();
            BootstrapConfig config = BootstrapConfig.builder().runList(runlist).build();
            chef.updateBootstrapConfigForGroup(groupName, config);
            Statement chefServerBootstrap = chef.createBootstrapScriptForGroup(groupName);

            // Run the script in the nodes of the group
            System.out.printf(">> installing [%s] on group %s as %s%n", recipes, groupName, login.identity);
            runScriptOnGroup(compute, login, groupName, chefServerBootstrap);
            break;
        case DESTROY:
            System.out.printf(">> destroying nodes in group %s%n", groupName);
            // you can use predicates to select which nodes you wish to
            // destroy.
            Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(//
                    Predicates.<NodeMetadata>and(not(TERMINATED), inGroup(groupName)));
            System.out.printf("<< destroyed nodes %s%n", destroyed);
            break;
        }
    } catch (RunNodesException e) {
        System.err.println("error adding node to group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (RunScriptOnNodesException e) {
        System.err.println("error installing " + recipes + " on group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (Exception e) {
        System.err.println("error: " + e.getMessage());
        error = 1;
    } finally {
        compute.getContext().close();
        System.exit(error);
    }
}

From source file:org.jclouds.examples.chef.basics.MainApp.java

public static void main(String[] args) {
    if (args.length < PARAMETERS) {
        throw new IllegalArgumentException(INVALID_SYNTAX);
    }//w w w  . j  a v  a2s .  co  m

    String provider = args[0];
    String identity = args[1];
    String credential = args[2];
    String groupName = args[3];
    Action action = Action.valueOf(args[4].toUpperCase());
    if ((action == Action.CHEF || action == Action.SOLO) && args.length < PARAMETERS + 1) {
        throw new IllegalArgumentException(
                "please provide the list of recipes to install, separated by commas");
    }
    String recipes = action == Action.CHEF || action == Action.SOLO ? args[5] : "apache2";

    String minRam = System.getProperty("minRam");

    // note that you can check if a provider is present ahead of time
    checkArgument(contains(allKeys, provider), "provider %s not in supported list: %s", provider, allKeys);

    LoginCredentials login = action != Action.DESTROY ? getLoginForCommandExecution(action) : null;

    ComputeService compute = initComputeService(provider, identity, credential);

    try {
        switch (action) {
        case ADD:
            System.out.printf(">> adding node to group %s%n", groupName);

            // Default template chooses the smallest size on an operating
            // system that tested to work with java, which tends to be Ubuntu
            // or CentOS
            TemplateBuilder templateBuilder = compute.templateBuilder();

            // If you want to up the ram and leave everything default, you
            // can just tweak minRam
            if (minRam != null) {
                templateBuilder.minRam(Integer.parseInt(minRam));
            }

            // note this will create a user with the same name as you on the
            // node. ex. you can connect via ssh publicip
            Statement bootInstructions = AdminAccess.standard();

            // to run commands as root, we use the runScript option in the
            // template.
            templateBuilder.options(runScript(bootInstructions));

            NodeMetadata node = getOnlyElement(
                    compute.createNodesInGroup(groupName, 1, templateBuilder.build()));
            System.out.printf("<< node %s: %s%n", node.getId(),
                    concat(node.getPrivateAddresses(), node.getPublicAddresses()));

        case SOLO:
            System.out.printf(">> installing [%s] on group %s as %s%n", recipes, groupName, login.identity);

            Iterable<String> recipeList = Splitter.on(',').split(recipes);
            ImmutableList.Builder<Statement> bootstrapBuilder = ImmutableList.builder();
            bootstrapBuilder.add(new InstallGit());

            // Clone community cookbooks into the node
            for (String recipe : recipeList) {
                bootstrapBuilder.add(CloneGitRepo.builder()
                        .repository("git://github.com/opscode-cookbooks/" + recipe + ".git")
                        .directory("/var/chef/cookbooks/" + recipe) //
                        .build());
            }

            // Configure Chef Solo to bootstrap the selected recipes
            bootstrapBuilder.add(InstallRuby.builder().build());
            bootstrapBuilder.add(InstallRubyGems.builder().build());
            bootstrapBuilder.add(ChefSolo.builder() //
                    .cookbookPath("/var/chef/cookbooks") //
                    .runlist(RunList.builder().recipes(recipeList).build()) //
                    .build());

            // Build the statement that will perform all the operations above
            StatementList bootstrap = new StatementList(bootstrapBuilder.build());

            // Run the script in the nodes of the group
            runScriptOnGroup(compute, login, groupName, bootstrap);
            break;
        case CHEF:
            // Create the connection to the Chef server
            ChefService chef = initChefService(System.getProperty("chef.client"),
                    System.getProperty("chef.validator"));

            // Build the runlist for the deployed nodes
            System.out.println("Configuring node runlist in the Chef server...");
            List<String> runlist = new RunListBuilder().addRecipes(recipes.split(",")).build();
            chef.updateRunListForGroup(runlist, groupName);
            Statement chefServerBootstrap = chef.createBootstrapScriptForGroup(groupName);

            // Run the script in the nodes of the group
            System.out.printf(">> installing [%s] on group %s as %s%n", recipes, groupName, login.identity);
            runScriptOnGroup(compute, login, groupName, chefServerBootstrap);
            break;
        case DESTROY:
            System.out.printf(">> destroying nodes in group %s%n", groupName);
            // you can use predicates to select which nodes you wish to
            // destroy.
            Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(//
                    Predicates.<NodeMetadata>and(not(TERMINATED), inGroup(groupName)));
            System.out.printf("<< destroyed nodes %s%n", destroyed);
            break;
        }
    } catch (RunNodesException e) {
        System.err.println("error adding node to group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (RunScriptOnNodesException e) {
        System.err.println("error installing " + recipes + " on group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (Exception e) {
        System.err.println("error: " + e.getMessage());
        error = 1;
    } finally {
        compute.getContext().close();
        System.exit(error);
    }
}

From source file:org.quickgeo.generate.Dataset.java

public static Dataset generate() throws IOException {

    ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();

    Settings settings = Settings.getSettings();

    String pom = FileUtils.readFileToString(settings.getParentPomFile(), "UTF-8");
    Matcher m = settings.getModulePattern().matcher(pom);
    while (m.find()) {
        String artifact = m.group(1);
        if (!settings.getBlacklist().contains(artifact)) {
            builder.add(artifact);/*ww  w .j  ava 2  s.c om*/
        }
    }

    return new Dataset(builder.build());
}

From source file:org.eclipse.buildship.ui.wizard.project.WelcomePageContentFactory.java

public static WelcomePageContent createImportWizardWelcomePageContent() {
    Builder<PageParagraph> paragraphs = ImmutableList.builder();
    paragraphs.add(new PageParagraph(ProjectWizardMessages.Import_Wizard_Paragraph_Title_Smart_Project_Import,
            ProjectWizardMessages.Import_Wizard_Paragraph_Content_Smart_Project_Import));
    paragraphs.add(new PageParagraph(ProjectWizardMessages.Import_Wizard_Paragraph_Title_Gradle_Wrapper,
            ProjectWizardMessages.Import_Wizard_Paragraph_Content_Gradle_Wrapper));
    paragraphs.add(new PageParagraph(ProjectWizardMessages.Import_Wizard_Paragraph_Title_Advanced_Options,
            ProjectWizardMessages.Import_Wizard_Paragraph_Content_Advanced_Options));

    return new WelcomePageContent(ProjectWizardMessages.Import_Wizard_Welcome_Page_Name,
            ProjectWizardMessages.Title_GradleWelcomeWizardPage,
            ProjectWizardMessages.InfoMessage_GradleWelcomeWizardPageDefault,
            ProjectWizardMessages.InfoMessage_GradleWelcomeWizardPageContext,
            ProjectWizardMessages.Import_Wizard_Paragraph_Main_Title, paragraphs.build());
}

From source file:io.prometheus.client.metrics.histogram.buckets.Distributions.java

public static List<Float> equallySizedBucketsFor(final float lower, final float upper, final int count) {
    final ImmutableList.Builder<Float> builder = ImmutableList.builder();

    final float partitionSize = (upper - lower) / count;

    for (int i = 0; i < count; i++) {
        builder.add(lower + ((float) i * partitionSize));
    }//w  w w .  java 2  s  . c  om

    return builder.build();
}

From source file:ninja.leaping.permissionsex.util.GuavaCollectors.java

public static <T> Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> toImmutableList() {
    return Collector.of(ImmutableList::builder, ImmutableList.Builder::add, (a, b) -> a.addAll(b.build()),
            ImmutableList.Builder::build);
}

From source file:io.prestosql.plugin.raptor.legacy.util.ArrayUtil.java

/**
 * Unpack an array of big endian ints./*w w  w. ja va2  s  .c  o  m*/
 */
public static List<Integer> intArrayFromBytes(byte[] bytes) {
    ImmutableList.Builder<Integer> list = ImmutableList.builder();
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    while (buffer.hasRemaining()) {
        list.add(buffer.getInt());
    }
    return list.build();
}