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

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

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (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 {//from ww w .  ja  va2s .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.publictransitanalytics.scoregenerator.Main.java

public static void main(String[] args) throws FileNotFoundException, IOException, ArgumentParserException,
        InterruptedException, ExecutionException, InEnvironmentDetectorException {
    final Gson serializer = new GsonBuilder().setPrettyPrinting().create();

    final ArgumentParser parser = ArgumentParsers.newArgumentParser("ScoreGenerator").defaultHelp(true)
            .description("Generate isochrone map data.");

    parser.addArgument("-l", "--tripLengths").action(Arguments.append());
    parser.addArgument("-i", "--samplingInterval");
    parser.addArgument("-s", "--span");
    parser.addArgument("-d", "--baseDirectory");
    parser.addArgument("-k", "--backward").action(Arguments.storeTrue());
    parser.addArgument("-n", "--inMemCache").action(Arguments.storeTrue());
    parser.addArgument("-t", "--interactive").action(Arguments.storeTrue());
    parser.addArgument("-b", "--baseFile");
    parser.addArgument("-u", "--bounds");
    parser.addArgument("-c", "--comparisonFile");
    parser.addArgument("-o", "--outputName");

    final Subparsers subparsers = parser.addSubparsers().dest("command");

    subparsers.addParser("generateNetworkAccessibility");
    final Subparser generateSampledNetworkAccessibilityParser = subparsers
            .addParser("generateSampledNetworkAccessibility");
    generateSampledNetworkAccessibilityParser.addArgument("-m", "--samples");

    final Subparser generatePointAccessibilityParser = subparsers.addParser("generatePointAccessibility");
    generatePointAccessibilityParser.addArgument("-c", "--coordinate");

    final Namespace namespace = parser.parseArgs(args);

    final List<String> durationMinuteStrings = namespace.getList("tripLengths");
    final NavigableSet<Duration> durations = new TreeSet<>();
    for (String durationMinuteString : durationMinuteStrings) {
        final Duration duration = Duration.ofMinutes(Integer.valueOf(durationMinuteString));
        durations.add(duration);// w  w  w .  j av  a 2s.  com
    }

    final String baseDirectoryString = namespace.get("baseDirectory");
    final Path root = Paths.get(baseDirectoryString);

    final String baseFile = namespace.get("baseFile");
    final OperationDescription baseDescription = serializer.fromJson(
            new String(Files.readAllBytes(Paths.get(baseFile)), StandardCharsets.UTF_8),
            OperationDescription.class);

    final String comparisonFile = namespace.get("comparisonFile");
    final OperationDescription comparisonDescription = (comparisonFile == null) ? null
            : serializer.fromJson(
                    new String(Files.readAllBytes(Paths.get(comparisonFile)), StandardCharsets.UTF_8),
                    OperationDescription.class);

    final Boolean backwardObject = namespace.getBoolean("backward");
    final boolean backward = (backwardObject == null) ? false : backwardObject;

    final Boolean interactiveObject = namespace.getBoolean("interactive");
    final boolean interactive = (interactiveObject == null) ? false : interactiveObject;

    final NetworkConsoleFactory consoleFactory;
    if (interactive) {
        consoleFactory = (network, stopIdMap) -> new InteractiveNetworkConsole(network, stopIdMap);
    } else {
        consoleFactory = (network, stopIdMap) -> new DummyNetworkConsole();
    }

    final String samplingIntervalString = namespace.get("samplingInterval");
    final Duration samplingInterval = (samplingIntervalString != null)
            ? Duration.ofMinutes(Long.valueOf(samplingIntervalString))
            : null;

    final String spanString = namespace.get("span");
    final Duration span = (spanString != null) ? Duration.parse(spanString) : null;

    final String outputName = namespace.get("outputName");

    final String command = namespace.get("command");

    final LocalFilePublisher publisher = new LocalFilePublisher();

    final ImmutableSet.Builder<String> fileNamesBuilder = ImmutableSet.builder();
    fileNamesBuilder.add(baseDescription.getFiles());
    if (comparisonDescription != null) {
        fileNamesBuilder.add(comparisonDescription.getFiles());
    }
    final Set<String> fileNames = fileNamesBuilder.build();

    final Boolean inMemCacheObject = namespace.getBoolean("inMemCache");
    final StoreFactory storeFactory = (inMemCacheObject == null || inMemCacheObject == false)
            ? new NoCacheStoreFactory()
            : new UnboundedCacheStoreFactory();

    final Map<String, ServiceDataDirectory> serviceDirectoriesMap = new HashMap<>();
    for (final String fileName : fileNames) {
        if (!serviceDirectoriesMap.containsKey(fileName)) {
            final ServiceDataDirectory directory = new ServiceDataDirectory(root, fileName, storeFactory);
            serviceDirectoriesMap.put(fileName, directory);
        }
    }

    final String boundsString = namespace.get("bounds");
    final GeoBounds bounds = parseBounds(boundsString);
    final Grid grid = getGrid(root, bounds, storeFactory);

    final MapGenerator mapGenerator = new MapGenerator();

    final TimeTracker timeTracker;
    if (!backward) {
        timeTracker = new ForwardTimeTracker();
    } else {
        timeTracker = new BackwardTimeTracker();
    }

    if ("generatePointAccessibility".equals(command)) {

        generatePointAccessibility(namespace, baseDescription, backward, samplingInterval, span, durations,
                grid, serviceDirectoriesMap, comparisonDescription, publisher, serializer, mapGenerator,
                outputName, consoleFactory);
    } else if ("generateNetworkAccessibility".equals(command)) {
        final ScoreCardFactory scoreCardFactory = new CountScoreCardFactory();
        final Set<Center> centers = getAllCenters(grid);

        final BiMap<OperationDescription, Calculation<ScoreCard>> result = Main.<ScoreCard>runComparison(
                baseDescription, scoreCardFactory, centers, samplingInterval, span, backward, timeTracker, grid,
                serviceDirectoriesMap, durations.last(), comparisonDescription, consoleFactory);

        final Set<Sector> sectors = grid.getReachableSectors();
        publishNetworkAccessibility(baseDescription, comparisonDescription, result, grid, sectors, false,
                durations, span, samplingInterval, backward, publisher, serializer, mapGenerator, outputName);
    } else if ("generateSampledNetworkAccessibility".equals(command)) {

        final ScoreCardFactory scoreCardFactory = new CountScoreCardFactory();

        final int samples = Integer.valueOf(namespace.get("samples"));

        final Set<Sector> allReachableSectors = grid.getReachableSectors();
        final List<Sector> sectorList = new ArrayList<>(allReachableSectors);
        Collections.shuffle(sectorList);
        final Set<Sector> sampleSectors = ImmutableSet.copyOf(sectorList.subList(0, samples));
        final Set<Center> centers = getSampleCenters(sampleSectors, grid);

        final BiMap<OperationDescription, Calculation<ScoreCard>> result = Main.<ScoreCard>runComparison(
                baseDescription, scoreCardFactory, centers, samplingInterval, span, backward, timeTracker, grid,
                serviceDirectoriesMap, durations.last(), comparisonDescription, consoleFactory);
        publishNetworkAccessibility(baseDescription, comparisonDescription, result, grid, sampleSectors, true,
                durations, span, samplingInterval, backward, publisher, serializer, mapGenerator, outputName);
    }

}

From source file:org.zanata.rest.service.MockResourcesApplication.java

@SuppressWarnings("deprecation")
//TODO: replace with MockProjectVersionResource
private static void addDeprecatedResource(ImmutableSet.Builder<Class<?>> builder) {
    builder.add(MockProjectIterationResource.class);
}

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

/**
 * Combines a single value and array into an immutable set. Iteration of the set maintains the order of the items.
 * 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/*from  w  ww .  j a  v  a2s .c  o m*/
 */
@SafeVarargs
public static <T> ImmutableSet<T> combineToSet(T first, T... additional) {
    ImmutableSet.Builder<T> builder = ImmutableSet.builder();
    builder.add(first);
    builder.addAll(Arrays.asList(additional));
    return builder.build();
}

From source file:org.gradle.internal.component.external.model.LazyToRealisedModuleComponentResolveMetadataHelper.java

private static void populateHierarchy(Configuration metadata,
        ImmutableMap<String, Configuration> configurationDefinitions,
        ImmutableSet.Builder<String> accumulator) {
    accumulator.add(metadata.getName());
    for (String parentName : metadata.getExtendsFrom()) {
        Configuration parent = configurationDefinitions.get(parentName);
        populateHierarchy(parent, configurationDefinitions, accumulator);
    }//  w w  w . j ava 2  s  .  c  om
}

From source file:com.facebook.buck.util.autosparse.AbstractAutoSparseConfig.java

public static AutoSparseConfig of(boolean enabled, List<String> ignore) {
    ImmutableSet.Builder<Path> ignoredPaths = ImmutableSet.builder();
    for (String path : ignore) {
        ignoredPaths.add(Paths.get(path));
    }/*  w w  w .j a v a  2s. c o  m*/
    return AutoSparseConfig.of(enabled, ignoredPaths.build());
}

From source file:ca.cutterslade.match.scheduler.Time.java

static ImmutableSet<Time> forNames(Set<String> names) {
    ImmutableSet.Builder<Time> b = ImmutableSet.builder();
    for (String name : names)
        b.add(new Time(name));
    return b.build();
}

From source file:com.google.caliper.runner.target.TargetModule.java

@Provides
static ImmutableSet<VmType> vmTypes(ImmutableSet<Target> targets) {
    ImmutableSet.Builder<VmType> builder = ImmutableSet.builder();
    for (Target target : targets) {
        builder.add(target.vm().type());
    }//from   ww  w . ja  v a2 s.  c  om
    return builder.build();
}

From source file:com.google.caliper.runner.target.TargetModule.java

@Singleton
@Provides//from ww w.  jav a 2 s.  co  m
static ImmutableSet<Target> provideTargets(Device device, CaliperOptions options, CaliperConfig config) {
    ImmutableSet<String> vmNames = options.vmNames();
    if (vmNames.isEmpty()) {
        return ImmutableSet.of(device.createDefaultTarget());
    }

    ImmutableSet.Builder<Target> builder = ImmutableSet.builder();
    for (String vmName : vmNames) {
        builder.add(device.createTarget(config.getVmConfig(vmName)));
    }
    return builder.build();
}

From source file:org.apache.shindig.social.opensocial.model.EnumUtil.java

/**
 *
 * @param vals array of enums/* w  ww .  j a  v  a2s .  c o m*/
 * @return a set of the names for a list of Enum values defined by toString
 */
// TODO: Because we have a Enum interface in this package we have to explicitly state the java.lang.Enum (bad ?)
public static Set<String> getEnumStrings(java.lang.Enum<?>... vals) {
    ImmutableSet.Builder<String> builder = ImmutableSet.builder();
    for (java.lang.Enum<?> v : vals) {
        builder.add(v.toString());
    }
    Set<String> result = builder.build();

    Preconditions.checkArgument(result.size() == vals.length, "Enum names are not disjoint set");
    return result;
}