Example usage for com.google.common.collect Sets newTreeSet

List of usage examples for com.google.common.collect Sets newTreeSet

Introduction

In this page you can find the example usage for com.google.common.collect Sets newTreeSet.

Prototype

public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) 

Source Link

Document

Creates a mutable, empty TreeSet instance with the given comparator.

Usage

From source file:de.tu_berlin.dima.oligos.stat.distribution.histogram.StringHistogram.java

@Override
public SortedSet<String> getUpperBounds() {
    return Sets.newTreeSet(exactValues.keySet());
}

From source file:fr.inria.maestro.lga.clustering.impl.ClusteringUtils.java

private static void printPropeprtyHolder(final IPropertiesHolder holder, final PrintWriter pw)
        throws IOException {
    for (final String str : Sets.newTreeSet(holder.getKeys())) {
        final String value = holder.getStringValue(str);
        pw.print(str);/*from  w w  w .  jav a  2s  .co  m*/
        pw.print("\t");
        pw.print((value != null) ? value : "");
        pw.print("\t");
    }

}

From source file:brooklyn.location.cloud.CloudLocation.java

@Override
public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    synchronized (mutex) {
        // Check context for entity being deployed
        Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName());
        if (context != null && !(context instanceof Entity)) {
            throw new IllegalStateException("Invalid location context: " + context);
        }/*from  ww w. j  ava2s. c  o m*/
        Entity entity = (Entity) context;

        // Look for idle CloudMachine first
        Set<Entity> idle = Sets.newTreeSet(new Ordering<Entity>() {
            @Override
            public int compare(@Nullable Entity left, @Nullable Entity right) {
                return ComparisonChain.start().compare(left.getAttribute(MachineEntity.CPU_USAGE),
                        right.getAttribute(MachineEntity.CPU_USAGE)).result();
            }
        });
        for (Entity e : getOwner().getCloudMachineList()) {
            if (Boolean.TRUE.equals(e.getAttribute(CloudMachine.SERVICE_UP))
                    && e.getAttribute(CloudMachine.ENTITY) == null) {
                idle.add(e);
            }
        }
        if (idle.size() > 0) {
            CloudMachineLocation machine = (CloudMachineLocation) Iterables.getLast(idle);
            machine.setEntity(entity);
            return machine;
        }

        // Obtain a new machine location
        MachineLocation machine = provisioner.obtain(flags);
        obtained.add(machine);

        return machine;
    }
}

From source file:com.google.api.tools.framework.importers.swagger.aspects.ApiFromSwagger.java

public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) {
    Map<String, String> duplicateOperationIdLookup = Maps.newHashMap();
    TreeSet<String> urlPaths = Sets.newTreeSet(swagger.getPaths().keySet());
    for (String urlPath : urlPaths) {
        Path pathObj = swagger.getPath(urlPath);
        createServiceMethodsFromPath(serviceBuilder, urlPath, pathObj, duplicateOperationIdLookup);
    }/* w  ww  .  j a v a  2s  . c  o m*/

    if (isAllowAllMethodsConfigured(swagger, diagCollector)) {
        Path userDefinedWildCardPathObject = new Path();
        if (urlPaths.contains(SwaggerUtils.WILDCARD_URL_PATH)) {
            userDefinedWildCardPathObject = swagger.getPath(SwaggerUtils.WILDCARD_URL_PATH);
        }
        createServiceMethodsFromPath(serviceBuilder, SwaggerUtils.WILDCARD_URL_PATH,
                getNewWildCardPathObject(userDefinedWildCardPathObject), duplicateOperationIdLookup);
    }
    coreApiBuilder.setVersion(swagger.getInfo().getVersion());
    serviceBuilder.addApis(coreApiBuilder);
}

From source file:ru.codeinside.adm.parser.EmployeeFixtureParser.java

private Set<String> parseGroups(ArrayList<String> props, int propertyGroupIndex) {
    final Set<String> groups;
    if (props.size() > propertyGroupIndex) {
        groups = Sets.newTreeSet(groupSplitter.split(props.get(propertyGroupIndex)));
    } else {/*  w  w  w.java  2 s.  co  m*/
        groups = Collections.emptySet();
    }
    return groups;
}

From source file:org.eclipse.xtext.xtext.generator.parser.antlr.KeywordHelper.java

private BiMap<CharSequence, String> createKeywordMap(Grammar grammar) {
    List<ParserRule> parserRules = GrammarUtil.allParserRules(grammar);
    List<EnumRule> enumRules = GrammarUtil.allEnumRules(grammar);
    Iterator<EObject> iter = Iterators.concat(EcoreUtil.<EObject>getAllContents(parserRules),
            EcoreUtil.<EObject>getAllContents(enumRules));
    Iterator<Keyword> filtered = Iterators.filter(iter, Keyword.class);
    Iterator<String> transformed = Iterators.transform(filtered, new Function<Keyword, String>() {
        @Override/*from  w  w  w . j  a v  a  2 s.c o  m*/
        public String apply(Keyword from) {
            return from.getValue();
        }
    });
    TreeSet<String> treeSet = Sets.newTreeSet(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1.length() == o2.length())
                return o1.compareTo(o2);
            return Integer.valueOf(o1.length()).compareTo(Integer.valueOf(o2.length()));
        }
    });
    Iterators.addAll(treeSet, transformed);
    BiMap<CharSequence, String> result = HashBiMap.create();
    for (String s : treeSet) {
        CharSequence key = createKey(s);
        String readableName = toAntlrTokenIdentifier(s);
        if (result.containsValue(readableName)) {
            int i = 1;
            String next = readableName + "_" + i;
            while (result.containsValue(next)) {
                i++;
                next = readableName + "_" + i;
            }
            readableName = next;
        }
        result.put(key, readableName);
    }
    return result;
}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.cnw.CNWConverter.java

private void convertPersons(Map<String, Map<String, String>> listMaps) throws Exception {
    Progress progress = new Progress();
    PrintWriter out = createPrintWriter(CNWPerson.class);
    //    Set<RelationDTO> knownRelations = Sets.newHashSet();
    Map<String, String> shortDescriptionMap = Maps.newHashMap();
    try {//from  w  w w .j  av a  2s.  co  m
        Collection<File> files = FileUtils.listFiles(inputDir, TEI_EXTENSIONS, false);
        for (File file : Sets.newTreeSet(files)) {
            progress.step();
            String fileName = file.getName();
            log(".. %s%n", fileName);
            String xml = Files.readTextFromFile(file);
            //      LOG.info("xml={}", xml);
            String pid = "cnw:pers:" + fileName.replace(".xml", "");
            PersonContext personContext = new PersonContext(pid);
            Visitor visitor = new PersonVisitor(personContext, listMaps);
            Document.createFromXml(xml).accept(visitor);
            CNWPerson person = personContext.person;
            koppelnaam2pid.put(person.getKoppelnaam(), person.getId());
            jsonConverter.appendTo(out, person);
            shortDescriptionMap.put(person.getKoppelnaam(), person.getShortDescription());
        }
        out.close();

        File personDescription = new File("import/CNW/person-short_description.csv");
        FileUtils.write(personDescription, "koppelnaam;korte_omschrijving\n", false);
        shortDescriptionMap.forEach((koppelnaam, description) -> {
            CharSequence data = StringEscapeUtils.escapeCsv(koppelnaam) + ";"
                    + StringEscapeUtils.escapeCsv(description) + "\n";
            try {
                FileUtils.write(personDescription, data, true);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });

    } finally {
        out.close();
        progress.done();
    }
}

From source file:org.fenixedu.qubdocs.academic.documentRequests.providers.StandaloneCurriculumEntriesDataProvider.java

private void collectByEntries() {
    curriculumEntries = Sets.newTreeSet(CurriculumEntry.NAME_COMPARATOR(locale));
    for (Enrolment curriculumLine : sourceLines) {
        curriculumEntries.addAll(CurriculumEntry.transform(registration, Collections.singleton(curriculumLine),
                remarksDataProvider));//from   ww w.j a  v a 2  s . c o  m
    }
}

From source file:com.spotify.helios.cli.command.JobListCommand.java

@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json,
        final BufferedReader stdin) throws ExecutionException, InterruptedException {
    final boolean full = options.getBoolean(fullArg.getDest());
    final boolean quiet = options.getBoolean(quietArg.getDest());
    final String pattern = options.getString(patternArg.getDest());
    final boolean deployed = options.getBoolean(deployedArg.getDest());

    final Map<JobId, Job> jobs;
    if (pattern == null) {
        jobs = client.jobs().get();/*from www .ja  va 2  s  .com*/
    } else {
        jobs = client.jobs(pattern).get();
    }

    if (!Strings.isNullOrEmpty(pattern) && jobs.isEmpty()) {
        if (json) {
            out.println(Json.asPrettyStringUnchecked(jobs));
        } else if (!quiet) {
            out.printf("job pattern %s matched no jobs%n", pattern);
        }
        return 1;
    }

    final Map<JobId, ListenableFuture<JobStatus>> oldFutures = JobStatusFetcher.getJobsStatuses(client,
            jobs.keySet());

    final Map<JobId, ListenableFuture<JobStatus>> futures = Maps.newHashMap();

    // maybe filter on deployed jobs
    if (!deployed) {
        futures.putAll(oldFutures);
    } else {
        for (final Entry<JobId, ListenableFuture<JobStatus>> e : oldFutures.entrySet()) {
            if (!e.getValue().get().getDeployments().isEmpty()) {
                futures.put(e.getKey(), e.getValue());
            }
        }
    }

    final Set<JobId> sortedJobIds = Sets.newTreeSet(futures.keySet());

    if (json) {
        if (quiet) {
            out.println(Json.asPrettyStringUnchecked(sortedJobIds));
        } else {
            final Map<JobId, Job> filteredJobs = Maps.newHashMap();
            for (final Entry<JobId, Job> entry : jobs.entrySet()) {
                if (futures.containsKey(entry.getKey())) {
                    filteredJobs.put(entry.getKey(), entry.getValue());
                }
            }
            out.println(Json.asPrettyStringUnchecked(filteredJobs));
        }
    } else {
        if (quiet) {
            for (final JobId jobId : sortedJobIds) {
                out.println(jobId);
            }
        } else {
            final Table table = table(out);
            table.row("JOB ID", "NAME", "VERSION", "HOSTS", "COMMAND", "ENVIRONMENT");

            for (final JobId jobId : sortedJobIds) {
                final Job job = jobs.get(jobId);
                final String command = on(' ').join(escape(job.getCommand()));
                final String env = Joiner.on(" ").withKeyValueSeparator("=").join(job.getEnv());
                final JobStatus status = futures.get(jobId).get();
                table.row(full ? jobId : jobId.toShortString(), jobId.getName(), jobId.getVersion(),
                        status != null ? status.getDeployments().keySet().size() : 0, command, env);
            }
            table.print();
        }
    }

    return 0;
}

From source file:org.gradle.composite.internal.CompositeBuildDependencySubstitutions.java

private ProjectComponentIdentifier getReplacementFor(ModuleComponentSelector selector) {
    ModuleIdentifier candidateId = DefaultModuleIdentifier.newId(selector.getGroup(), selector.getModule());
    Collection<ProjectComponentIdentifier> providingProjects = replacementMap.get(candidateId);
    if (providingProjects.isEmpty()) {
        LOGGER.info("Found no composite build substitute for module '" + candidateId + "'.");
        return null;
    }/*from   w ww.  j ava 2s .  c  om*/
    if (providingProjects.size() == 1) {
        ProjectComponentIdentifier match = providingProjects.iterator().next();
        LOGGER.info("Found project '" + match + "' as substitute for module '" + candidateId + "'.");
        return match;
    }
    SortedSet<String> sortedProjects = Sets.newTreeSet(
            CollectionUtils.collect(providingProjects, new Transformer<String, ProjectComponentIdentifier>() {
                @Override
                public String transform(ProjectComponentIdentifier projectComponentIdentifier) {
                    return projectComponentIdentifier.getDisplayName();
                }
            }));
    String failureMessage = String.format(
            "Module version '%s' is not unique in composite: can be provided by %s.", selector.getDisplayName(),
            sortedProjects);
    throw new ModuleVersionResolveException(selector, failureMessage);
}