Example usage for java.util LinkedHashSet size

List of usage examples for java.util LinkedHashSet size

Introduction

In this page you can find the example usage for java.util LinkedHashSet size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.gnucash.android.ui.report.BarChartFragment.java

/**
 * Sets custom legend. Disable legend if its items count greater than {@code COLORS} array size.
 */// w  w  w  .  j a  v a 2  s  .  com
private void setCustomLegend() {
    Legend legend = mChart.getLegend();
    BarDataSet dataSet = mChart.getData().getDataSetByIndex(0);

    LinkedHashSet<String> labels = new LinkedHashSet<>(Arrays.asList(dataSet.getStackLabels()));
    LinkedHashSet<Integer> colors = new LinkedHashSet<>(dataSet.getColors());

    if (COLORS.length >= labels.size()) {
        legend.setCustom(new ArrayList<>(colors), new ArrayList<>(labels));
        return;
    }
    legend.setEnabled(false);
}

From source file:org.fusesource.meshkeeper.distribution.remoting.AbstractRemotingClient.java

private final <T> T exportInternal(T obj, String multicastAddress, Class<?>... serviceInterfaces)
        throws Exception {
    LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
    if (serviceInterfaces == null || serviceInterfaces.length == 0) {
        collectDistributableInterfaces(obj.getClass(), interfaces);
    } else {//w  w  w.j a va  2  s  . co  m
        for (Class<?> serviceInterface : serviceInterfaces) {
            validateInterface(serviceInterface);
            interfaces.add(serviceInterface);
        }
    }

    //If the only interfaces is the Distributable interface itself, then we're
    //just trying to export the class:
    if (interfaces.size() == 0 || (interfaces.size() == 1 && interfaces.contains(Distributable.class))) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Exporting " + obj.getClass() + " with no service interfaces");
        }
        return (T) exportInterfaces(obj, multicastAddress, (Class<?>[]) null);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Exporting " + obj.getClass() + " as: " + interfaces);
    }

    Class<?>[] distributable = null;
    //System.out.println("Found distributable interfaces for: " + obj + ": " + interfaces);
    distributable = new Class<?>[interfaces.size()];
    interfaces.toArray(distributable);
    return (T) exportInterfaces(obj, multicastAddress, distributable);
}

From source file:net.heroicefforts.viable.android.rep.it.GIssueTrackerRepository.java

public SearchResults search(SearchParams params) throws ServiceException {
    final int startIdx = (params.getPage() - 1) * params.getPageSize();
    final int pageSize = params.getPageSize();

    LinkedHashSet<Issue> issues = new LinkedHashSet<Issue>();
    for (int i = startIdx; i < params.getIds().size() && i < startIdx + pageSize + i; i++)
        issues.add(findById(params.getIds().get(i)));

    if (issues.size() <= pageSize) {
        Issue issue = findByHash(params.getHash());
        if (issue != null)
            issues.add(issue);//from w w w.  ja  v  a2 s  .  co m
    }

    if (issues.size() <= pageSize) {
        long skip = startIdx;
        long skipped = params.getIds().size() + (params.getHash() != null ? 1 : 0);
        for (int i = 0; i < params.getAffectedVersions().size() && issues.size() <= pageSize; i++) {
            long count = countIssuesByVersion(params.getAffectedVersions().get(i));
            if (skipped + count > skip) {
                int needed = pageSize - issues.size() + 1;
                long startAt = skip - skipped;
                if (startAt < 0)
                    startAt = 0;
                issues.addAll(findIssuesByVersion(params.getAffectedVersions().get(i), startAt, needed));
                skipped = skip;
            } else {
                skipped += count;
            }
        }
    }

    setAppName(issues);

    if (issues.size() > pageSize)
        return new SearchResults(new ArrayList<Issue>(issues).subList(0, pageSize), true);
    else
        return new SearchResults(new ArrayList<Issue>(issues), false);
}

From source file:solidbase.core.UpgradeProcessor.java

/**
 * Perform upgrade to the given target version. The target version can end with an '*', indicating whatever tip version that
 * matches the target prefix.// w  w  w. jav  a  2 s . c o  m
 *
 * @param target The target requested.
 * @param downgradeable Indicates that downgrade paths are allowed to reach the given target.
 * @throws SQLExecutionException When the execution of a command throws an {@link SQLException}.
 */
protected void upgrade(String target, boolean downgradeable) throws SQLExecutionException {
    setupControlTables();

    String version = this.dbVersion.getVersion();

    if (target == null) {
        LinkedHashSet<String> targets = getTargets(true, null, downgradeable);
        if (targets.size() > 1)
            throw new FatalException("More than one possible target found, you should specify a target.");
        Assert.notEmpty(targets);

        target = targets.iterator().next();
    } else if (target.endsWith("*")) {
        String targetPrefix = target.substring(0, target.length() - 1);
        LinkedHashSet<String> targets = getTargets(true, targetPrefix, downgradeable);
        if (targets.size() > 1)
            throw new FatalException("More than one possible target found for " + target);
        if (targets.isEmpty())
            throw new FatalException("Target " + target + " is not reachable from version "
                    + StringUtils.defaultString(version, "<no version>"));

        target = targets.iterator().next();
    } else {
        LinkedHashSet<String> targets = getTargets(false, null, downgradeable);
        Assert.notEmpty(targets);

        // TODO Refactor this, put this in getTargets()
        boolean found = false;
        for (String t : targets)
            if (ObjectUtils.equals(t, target)) {
                found = true;
                break;
            }

        if (!found)
            throw new FatalException("Target " + target + " is not reachable from version "
                    + StringUtils.defaultString(version, "<no version>"));
    }

    if (ObjectUtils.equals(target, version)) {
        this.progress.noUpgradeNeeded();
        return;
    }

    upgrade(version, target, downgradeable);
}

From source file:org.opencb.opencga.storage.core.variant.VariantStoragePipeline.java

public static void checkAndUpdateStudyConfiguration(StudyConfiguration studyConfiguration, int fileId,
        VariantSource source, ObjectMap options) throws StorageEngineException {
    if (options.containsKey(Options.SAMPLE_IDS.key())
            && !options.getAsStringList(Options.SAMPLE_IDS.key()).isEmpty()) {
        for (String sampleEntry : options.getAsStringList(Options.SAMPLE_IDS.key())) {
            String[] split = sampleEntry.split(":");
            if (split.length != 2) {
                throw new StorageEngineException("Param " + sampleEntry + " is malformed");
            }/* ww w. j av  a  2 s . co m*/
            String sampleName = split[0];
            int sampleId;
            try {
                sampleId = Integer.parseInt(split[1]);
            } catch (NumberFormatException e) {
                throw new StorageEngineException("SampleId " + split[1] + " is not an integer", e);
            }

            if (!source.getSamplesPosition().containsKey(sampleName)) {
                //ERROR
                throw new StorageEngineException(
                        "Given sampleName '" + sampleName + "' is not in the input file");
            } else {
                if (!studyConfiguration.getSampleIds().containsKey(sampleName)) {
                    //Add sample to StudyConfiguration
                    studyConfiguration.getSampleIds().put(sampleName, sampleId);
                } else {
                    if (studyConfiguration.getSampleIds().get(sampleName) != sampleId) {
                        throw new StorageEngineException("Sample " + sampleName + ":" + sampleId
                                + " was already present. It was in the StudyConfiguration with a different sampleId: "
                                + studyConfiguration.getSampleIds().get(sampleName));
                    }
                }
            }
        }

        //Check that all samples has a sampleId
        List<String> missingSamples = new LinkedList<>();
        for (String sampleName : source.getSamples()) {
            if (!studyConfiguration.getSampleIds().containsKey(sampleName)) {
                missingSamples.add(sampleName);
            } /*else {
              Integer sampleId = studyConfiguration.getSampleIds().get(sampleName);
              if (studyConfiguration.getIndexedSamples().contains(sampleId)) {
                  logger.warn("Sample " + sampleName + ":" + sampleId + " was already loaded.
                  It was in the StudyConfiguration.indexedSamples");
              }
              }*/
        }
        if (!missingSamples.isEmpty()) {
            throw new StorageEngineException(
                    "Samples " + missingSamples.toString() + " has not assigned sampleId");
        }

    } else {
        //Find the grader sample Id in the studyConfiguration, in order to add more sampleIds if necessary.
        int maxId = 0;
        for (Integer i : studyConfiguration.getSampleIds().values()) {
            if (i > maxId) {
                maxId = i;
            }
        }
        //Assign new sampleIds
        for (String sample : source.getSamples()) {
            if (!studyConfiguration.getSampleIds().containsKey(sample)) {
                //If the sample was not in the original studyId, a new SampleId is assigned.

                int sampleId;
                int samplesSize = studyConfiguration.getSampleIds().size();
                Integer samplePosition = source.getSamplesPosition().get(sample);
                if (!studyConfiguration.getSampleIds().containsValue(samplePosition)) {
                    //1- Use with the SamplePosition
                    sampleId = samplePosition;
                } else if (!studyConfiguration.getSampleIds().containsValue(samplesSize)) {
                    //2- Use the number of samples in the StudyConfiguration.
                    sampleId = samplesSize;
                } else {
                    //3- Use the maxId
                    sampleId = maxId + 1;
                }
                studyConfiguration.getSampleIds().put(sample, sampleId);
                if (sampleId > maxId) {
                    maxId = sampleId;
                }
            }
        }
    }

    if (studyConfiguration.getSamplesInFiles().containsKey(fileId)) {
        LinkedHashSet<Integer> sampleIds = studyConfiguration.getSamplesInFiles().get(fileId);
        List<String> missingSamples = new LinkedList<>();
        for (String sampleName : source.getSamples()) {
            if (!sampleIds.contains(studyConfiguration.getSampleIds().get(sampleName))) {
                missingSamples.add(sampleName);
            }
        }
        if (!missingSamples.isEmpty()) {
            throw new StorageEngineException(
                    "Samples " + missingSamples.toString() + " were not in file " + fileId);
        }
        if (sampleIds.size() != source.getSamples().size()) {
            throw new StorageEngineException("Incorrect number of samples in file " + fileId);
        }
    } else {
        LinkedHashSet<Integer> sampleIdsInFile = new LinkedHashSet<>(source.getSamples().size());
        for (String sample : source.getSamples()) {
            sampleIdsInFile.add(studyConfiguration.getSampleIds().get(sample));
        }
        studyConfiguration.getSamplesInFiles().put(fileId, sampleIdsInFile);
    }
}

From source file:com.soulgalore.crawler.core.impl.DefaultCrawler.java

/**
 * Get the urls./* www.  j a  va  2s  .c  o  m*/
 * 
 * @param configuration how to perform the crawl
 * @return the result of the crawl
 */
public CrawlerResult getUrls(CrawlerConfiguration configuration) {

    final Map<String, String> requestHeaders = configuration.getRequestHeadersMap();
    final HTMLPageResponse resp = verifyInput(configuration.getStartUrl(), configuration.getOnlyOnPath(),
            requestHeaders);

    int level = 0;

    final Set<CrawlerURL> allUrls = new LinkedHashSet<CrawlerURL>();
    final Set<HTMLPageResponse> verifiedUrls = new LinkedHashSet<HTMLPageResponse>();
    final Set<HTMLPageResponse> nonWorkingResponses = new LinkedHashSet<HTMLPageResponse>();

    verifiedUrls.add(resp);

    final String host = resp.getPageUrl().getHost();

    if (configuration.getMaxLevels() > 0) {

        // set the start url
        Set<CrawlerURL> nextToFetch = new LinkedHashSet<CrawlerURL>();
        nextToFetch.add(resp.getPageUrl());

        while (level < configuration.getMaxLevels()) {

            final Map<Future<HTMLPageResponse>, CrawlerURL> futures = new HashMap<Future<HTMLPageResponse>, CrawlerURL>(
                    nextToFetch.size());

            for (CrawlerURL testURL : nextToFetch) {
                futures.put(service.submit(
                        new HTMLPageResponseCallable(testURL, responseFetcher, true, requestHeaders, false)),
                        testURL);
            }

            nextToFetch = fetchNextLevelLinks(futures, allUrls, nonWorkingResponses, verifiedUrls, host,
                    configuration.getOnlyOnPath(), configuration.getNotOnPath());
            level++;
        }
    } else {
        allUrls.add(resp.getPageUrl());
    }

    if (configuration.isVerifyUrls())
        verifyUrls(allUrls, verifiedUrls, nonWorkingResponses, requestHeaders);

    LinkedHashSet<CrawlerURL> workingUrls = new LinkedHashSet<CrawlerURL>();
    for (HTMLPageResponse workingResponses : verifiedUrls) {
        workingUrls.add(workingResponses.getPageUrl());
    }

    // TODO find a better fix for this
    // wow, this is a hack to fix if the first URL is redirected,
    // then we want to keep that original start url
    if (workingUrls.size() >= 1) {
        List<CrawlerURL> list = new ArrayList<CrawlerURL>(workingUrls);
        list.add(0, new CrawlerURL(configuration.getStartUrl()));
        list.remove(1);
        workingUrls.clear();
        workingUrls.addAll(list);
    }

    return new CrawlerResult(configuration.getStartUrl(), configuration.isVerifyUrls() ? workingUrls : allUrls,
            verifiedUrls, nonWorkingResponses);

}

From source file:cz.incad.kramerius.pdf.impl.FirstPagePDFServiceImpl.java

String templateParent(PreparedDocument rdoc, ObjectPidsPath path) throws IOException,
        ParserConfigurationException, SAXException, XPathExpressionException, JAXBException {
    ResourceBundle resourceBundle = resourceBundleService.getResourceBundle("base", localesProvider.get());

    StringTemplate template = new StringTemplate(IOUtils.readAsString(
            this.getClass().getResourceAsStream("templates/_first_page.st"), Charset.forName("UTF-8"), true));
    FirstPageViewObject fpvo = prepareViewObject(resourceBundle);

    // tistena polozka
    GeneratedItem itm = new GeneratedItem();

    // detaily/*w  w  w  .  ja  v  a2  s .co  m*/
    Map<String, LinkedHashSet<String>> detailItemValues = new HashMap<String, LinkedHashSet<String>>();
    Map<String, Map<String, List<String>>> mods = processModsFromPath(path, null);

    // Hlavni nazev
    String rootPid = path.getRoot();
    if (mods.get(rootPid).containsKey(TitleBuilder.MODS_TITLE)) {
        List<String> list = mods.get(rootPid).get(TitleBuilder.MODS_TITLE);
        if (!list.isEmpty()) {
            String key = TitleBuilder.MODS_TITLE;
            itemVals(detailItemValues, list, key);
        }
    }

    // pouze jeden root
    String[] rProps = renderedProperties(true);
    String[] fromRootToLeaf = path.getPathFromRootToLeaf();
    for (int i = 0; i < fromRootToLeaf.length; i++) {
        String pidPath = fromRootToLeaf[i];
        for (String prop : rProps) {

            if (mods.get(pidPath).containsKey(prop)) {
                List<String> list = mods.get(pidPath).get(prop);
                itemVals(detailItemValues, list, prop);
            }
        }
    }

    // hlavni nazev
    List<DetailItem> details = new ArrayList<FirstPagePDFServiceImpl.DetailItem>();
    LinkedHashSet<String> maintitles = detailItemValues.get(TitleBuilder.MODS_TITLE);
    String key = maintitles != null && maintitles.size() > 1 ? resourceBundle.getString("pdf.fp.titles")
            : resourceBundle.getString("pdf.fp.title");
    if (maintitles != null && (!maintitles.isEmpty())) {
        details.add(new DetailItem(key, vals(maintitles).toString()));
    }

    String[] props = renderedProperties(true);
    for (String prop : props) {
        LinkedHashSet<String> vals = detailItemValues.get(prop);
        key = vals != null && vals.size() > 1 ? resourceBundle.getString(i18nKey(prop) + "s")
                : resourceBundle.getString(i18nKey(prop));
        if (vals != null && (!vals.isEmpty())) {
            details.add(new DetailItem(key, vals(vals).toString()));
        }
    }

    pagesInParentPdf(rdoc, resourceBundle, details);

    itm.setDetailItems((DetailItem[]) details.toArray(new DetailItem[details.size()]));

    fpvo.setGeneratedItems(new GeneratedItem[] { itm });
    template.setAttribute("viewinfo", fpvo);
    String templateText = template.toString();
    return templateText;
}

From source file:org.pentaho.di.ui.trans.steps.annotation.OptionsResolver.java

public String[] resolveOrdinalFieldOptions(final TransMeta transMeta, final String stepName,
        ModelAnnotation modelAnnotation) {
    LinkedHashSet<String> names = new LinkedHashSet<String>();
    try {//from   w ww .j a v a2s.c o m
        RowMetaInterface prevStepFields = transMeta.getPrevStepFields(stepName);
        for (ValueMetaInterface valueMetaInterface : prevStepFields.getValueMetaList()) {
            if (!StringUtils.equals(modelAnnotation.getAnnotation().getField(), valueMetaInterface.getName())) {
                names.add(valueMetaInterface.getName());
            }
        }
    } catch (Exception e) {
        logger.warning(e.getMessage());
    }
    return names.toArray(new String[names.size()]);
}

From source file:ch.unibas.fittingwizard.presentation.fitting.FittingParameterPage.java

private File getInitalCharges(MoleculeQueryService queryService) {
    LinkedHashSet<ChargeValue> userCharges = new LinkedHashSet<>();
    LinkedHashSet<AtomTypeId> atomTypesRequiringUserInput = new LinkedHashSet<>();

    List<Molecule> moleculesWithMissingUserCharges = queryService.findMoleculesWithMissingUserCharges();
    atomTypesRequiringUserInput.addAll(getAllAtomTypeIds(moleculesWithMissingUserCharges));

    boolean multipleMoleculesDefined = queryService.getNumberOfMolecules() > 1;
    if (multipleMoleculesDefined) {
        List<AtomTypeId> duplicates = queryService.findUnequalAndDuplicateAtomTypes();
        atomTypesRequiringUserInput.addAll(duplicates);
    }/*w w  w  .  j  a  v a  2  s .co  m*/

    if (atomTypesRequiringUserInput.size() > 0) {
        LinkedHashSet<ChargeValue> editedValues = editAtomTypeChargesDialog
                .editAtomTypes(atomTypesRequiringUserInput);
        if (editedValues == null) {
            // TODO ... no nested return
            return null;
        }
        userCharges.addAll(editedValues);
    }

    // fill up with all other values in order to generate a correct charges file.
    // due to the set, the already edited values will not be replaced.
    LinkedHashSet<ChargeValue> allCharges = queryService.getUserChargesFromMoleculesWithCharges();
    for (ChargeValue charge : allCharges) {
        if (!userCharges.contains(charge)) {
            userCharges.add(charge);
        }
    }

    File initalChargesFile = generateInitialChargesFileFromUserCharges(userCharges);
    return initalChargesFile;
}

From source file:org.chromium.content_shell.Shell.java

private void updateHistory(String url) {
    String json = mPref.getString("history", null);
    JSONArray array = new JSONArray();
    if (json != null) {
        try {//from  w ww.jav  a 2 s. c  o m
            array = new JSONArray(json);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    LinkedHashSet<String> history = new LinkedHashSet<String>();
    for (int i = 0; i < array.length(); i++) {
        try {
            history.add(array.getString(i));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (history.contains(url)) {
        history.remove(url);
    }
    history.add(url);
    if (history.size() > 100) {
        String f = history.iterator().next();
        history.remove(f);
    }
    array = new JSONArray();
    for (String u : history) {
        array.put(u);
    }

    mPref.edit().putString("history", array.toString()).commit();
}