Example usage for com.google.common.collect ImmutableList.Builder add

List of usage examples for com.google.common.collect ImmutableList.Builder add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Appends the specified element to the end of this list (optional operation).

Usage

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 {// w  ww.  j a v a2  s.c o 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: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 w w  w.j a  va2s. c o  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
            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.  java 2 s .  c o  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:com.android.dx.merge.DexMerger.java

public static void main(String[] args) throws IOException {
    if (args.length < 2) {
        printUsage();/*from   w  w w  .j a va2  s  .c  o m*/
        return;
    }

    ImmutableList.Builder<Dex> toMerge = ImmutableList.builder();
    for (int i = 2; i < args.length; i++) {
        toMerge.add(new Dex(new File(args[i])));
    }
    Dex merged = new DexMerger(toMerge.build(), CollisionPolicy.KEEP_FIRST).merge();
    merged.writeTo(new File(args[0]));
}

From source file:org.caleydo.core.util.impute.KNNImpute.java

public static void main(String[] args) throws IOException {
    ImmutableList.Builder<Gene> b = ImmutableList.builder();
    List<String> lines = CharStreams
            .readLines(new InputStreamReader(KNNImpute.class.getResourceAsStream("khan.csv")));
    lines = lines.subList(1, lines.size());
    int j = 0;//from  w  w w  .ja  v a 2s.  co m
    for (String line : lines) {
        String[] l = line.split(";");
        float[] d = new float[l.length];
        int nans = 0;
        for (int i = 0; i < l.length; ++i) {
            if ("NA".equals(l[i])) {
                nans++;
                d[i] = Float.NaN;
            } else {
                d[i] = Float.parseFloat(l[i]);
            }
        }
        b.add(new Gene(j++, nans, d));
    }
    final KNNImputeDescription desc2 = new KNNImputeDescription();
    desc2.setMaxp(100000);
    KNNImpute r = new KNNImpute(desc2, b.build());
    ForkJoinPool p = new ForkJoinPool();
    p.invoke(r);
    try (PrintWriter w = new PrintWriter("khan.imputed.csv")) {
        w.println(StringUtils.repeat("sample", ";", r.samples));
        for (Gene g : r.genes) {
            float[] d = g.data;
            int nan = 0;
            w.print(Float.isNaN(d[0]) ? g.nanReplacements[nan++] : d[0]);
            for (int i = 1; i < d.length; ++i)
                w.append(';').append(String.valueOf(Float.isNaN(d[i]) ? g.nanReplacements[nan++] : d[i]));
            w.println();
        }
    }
}

From source file:com.tibco.businessworks6.sonar.plugin.CommonExtensions.java

@SuppressWarnings("rawtypes")
public static List getExtensions() {
    ImmutableList.Builder<Object> builder = ImmutableList.builder();
    builder.add(BusinessWorksMetrics.class);
    builder.add(BusinessWorksMetricsWidget.class);
    //builder.add(BusinessWorksProcessColorizerFormat.class);
    return builder.build();
}

From source file:com.google.api.tools.framework.tools.configgen.ServiceConfigGeneratorTool.java

/**
 * Add all options that will be accepted on the command line.
 *///from  w  ww . java  2 s.c  om
private static ImmutableList<Option<?>> buildFrameworkOptions() {
    ImmutableList.Builder<Option<?>> frameworkOptions = new ImmutableList.Builder<Option<?>>();
    frameworkOptions.add(ToolOptions.DESCRIPTOR_SET);
    frameworkOptions.add(ToolOptions.CONFIG_FILES);
    frameworkOptions.add(ConfigGeneratorDriver.BIN_OUT);
    frameworkOptions.add(ConfigGeneratorDriver.TXT_OUT);
    frameworkOptions.add(ConfigGeneratorDriver.JSON_OUT);
    frameworkOptions.add(ConfigGeneratorFromProtoDescriptor.SUPPRESS_WARNINGS);
    frameworkOptions.add(SwaggerToolDriverBase.OPEN_API);
    frameworkOptions.add(SwaggerToolDriverBase.SERVICE_NAME);
    frameworkOptions.add(SwaggerToolDriverBase.TYPE_NAMESPACE);

    return frameworkOptions.build();
}

From source file:org.terasology.util.Varargs.java

/**
 * Combines a single value and array into an immutable list.
 * This is intended to aid methods using the mandatory-first optional-additional varargs trick.
 *
 * @param first      The first, single value
 * @param additional Any additional values
 * @param <T>        The type of the items
 * @return A set of the combined values// ww  w. ja v a 2 s. com
 */
@SafeVarargs
public static <T> ImmutableList<T> combineToList(T first, T... additional) {
    ImmutableList.Builder<T> builder = ImmutableList.builder();
    builder.add(first);
    builder.addAll(Arrays.asList(additional));
    return builder.build();
}

From source file:eu.arthepsy.sonar.plugins.scapegoat.ScapegoatConfiguration.java

public static List<PropertyDefinition> getPropertyDefinitions() {
    ImmutableList.Builder<PropertyDefinition> properties = ImmutableList.builder();
    properties.add(PropertyDefinition.builder(REPORT_PATH_PROPERTY_KEY).category(CATEGORY)
            .subCategory(SUBCATEGORY).index(0).name("Scapegoat report path")
            .description("Path to generated scapegoat xml report.").type(PropertyType.STRING)
            .defaultValue("target/scapegoat-report/scapegoat.xml").build());
    return properties.build();
}

From source file:com.tibco.businessworks6.sonar.plugin.ProcessExtensions.java

@SuppressWarnings("rawtypes")
public static List getExtensions() {
    ImmutableList.Builder<Object> builder = ImmutableList.builder();
    builder.add(ProcessLanguage.class);
    builder.add(ProcessSonarWayProfile.class);
    builder.add(ProcessRuleDefinition.class);
    builder.add(ProcessRuleSensor.class);
    //builder.add(ProcessMetricSensor.class);
    builder.add(PropertyDefinition.builder(ProcessLanguage.FILE_SUFFIXES_KEY)
            .defaultValue(StringUtils.join(ProcessLanguage.DEFAULT_FILE_SUFFIXES, ","))
            .name("Process file suffixes").description("Comma-separated list of suffixes for files to analyze.")
            .category(BusinessWorksPlugin.TIBCO_BUSINESSWORK_CATEGORY).subCategory(SUB_CATEGORY_NAME)
            .onQualifiers(Qualifiers.PROJECT).build());
    return builder.build();
}