Example usage for java.util Collections binarySearch

List of usage examples for java.util Collections binarySearch

Introduction

In this page you can find the example usage for java.util Collections binarySearch.

Prototype

@SuppressWarnings("unchecked")
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 

Source Link

Document

Searches the specified list for the specified object using the binary search algorithm.

Usage

From source file:com.urbantamil.projmadurai.MaduraiBookCoverFragment.java

private String getGenreAnimalCode(String genre) {
    int pos = Collections.binarySearch(genre_list, genre, utf8.comparator);
    pos = Math.max(pos, 0);//from   w w w .j  a  va2  s.  c  o  m
    // 0-based
    return String.valueOf(pos % MAX_ANIMALS);
}

From source file:org.orekit.utils.ImmutableTimeStampedCache.java

/**
 * Find the index, i, to {@link #data} such that {@code data[i] <= t} and
 * {@code data[i+1] > t} if {@code data[i+1]} exists.
 *
 * @param t the time/* ww  w . j  av  a2s .co m*/
 * @return the index of the data at or just before {@code t}, {@code -1} if
 *         {@code t} is before the first entry, or {@code data.size()} if
 *         {@code t} is after the last entry.
 */
private int findIndex(final AbsoluteDate t) {
    // Guaranteed log(n) time
    int i = Collections.binarySearch(this.data, t, CMP);
    if (i == -this.data.size() - 1) {
        // beyond last entry
        i = this.data.size();
    } else if (i < 0) {
        // did not find exact match, but contained in data interval
        i = -i - 2;
    }
    return i;
}

From source file:edu.scripps.fl.collections.FuzzyMap.java

@SuppressWarnings("unchecked")
protected int getIndex(K key) {
    int idx = Collections.binarySearch((List) list, key, comparator);
    if (idx < 0) {
        idx = -1 * idx - 2;//from  www  .j  a  v  a  2 s .c om
        if (idx < 0)
            idx = 0;
    }
    return idx;
}

From source file:org.openvpms.web.workspace.workflow.scheduling.Schedule.java

/**
 * Returns the event starting at the specified time.
 *
 * @param time     the time/* www .  ja v a  2 s . c om*/
 * @param slotSize the slot size
 * @return the corresponding event, or {@code null} if none is found
 */
public PropertySet getEvent(Date time, int slotSize) {
    PropertySet set = new ObjectSet();
    set.set(ScheduleEvent.ACT_START_TIME, time);
    set.set(ScheduleEvent.ACT_END_TIME, time);
    int index = Collections.binarySearch(events, set, new StartTimeComparator(slotSize));
    return (index < 0) ? null : events.get(index);
}

From source file:org.openhab.binding.plugwise.internal.Stick.java

protected PlugwiseDevice getDeviceByMAC(String MAC) {

    PlugwiseDevice queryDevice = new PlugwiseDevice(MAC, null, "");
    Collections.sort(plugwiseDeviceCache, plugComparator);
    int index = Collections.binarySearch(plugwiseDeviceCache, queryDevice, plugComparator);
    if (index >= 0) {
        return plugwiseDeviceCache.get(index);
    } else {/*  w w w  . j a  va2  s.com*/
        return null;
    }
}

From source file:org.apache.hadoop.hdfs.notifier.server.ServerHistory.java

/**
 * Checks if there are notifications in our tree which are older than
 * historyLength. It removes does which are older.
 *//*from   w ww .j  a v  a  2  s  .  com*/
private void cleanUpHistory() {
    long oldestAllowedTimestamp = System.currentTimeMillis() - historyLength;
    int trashedNotifications = 0;

    if (LOG.isDebugEnabled()) {
        LOG.debug("History cleanup: Checking old notifications to remove from history list ...");
    }

    HistoryTreeEntry key = new HistoryTreeEntry(oldestAllowedTimestamp, 0, (byte) 0);
    int notificationsCount = 0;
    historyLock.writeLock().lock();
    try {
        notificationsCount = orderedHistoryList.size();
        LOG.warn("History cleanup: size of the history before cleanup: " + notificationsCount);

        if (!historyLimitDisabled && notificationsCount > historyLimit) {
            LOG.warn("History cleanup: Reached physical limit. Number of stored notifications: "
                    + notificationsCount + ". Clearing ...");
        }

        int index = Collections.binarySearch(orderedHistoryList, key, comparatorByTS);
        int toDeleteByTS = index >= 0 ? index : -(index + 1);
        int toDeleteByLimit = historyLimitDisabled ? 0 : notificationsCount - (int) historyLimit;
        toDeleteByLimit = toDeleteByLimit > 0 ? toDeleteByLimit : 0;

        int toDelete = Math.max(toDeleteByTS, toDeleteByLimit);

        // Delete items which are too old
        if (toDelete > 0) {
            LOG.warn("History cleanup: number of the history to cleanup: " + toDelete);
            for (int i = 0; i < toDelete; i++) {
                orderedHistoryList.get(i).removeFromTree();
            }

            orderedHistoryList.subList(0, toDelete).clear();

            if (toDeleteByLimit > toDeleteByTS) {
                // If we delete a notification because we don't have space left
                trashedNotifications++;
            }
            notificationsCount = orderedHistoryList.size();
            LOG.warn("History cleanup: size of the history after cleanup: " + notificationsCount);

            // clean up history tree, remove the node that has no children and
            // no notifications associated with them.
            cleanUpHistoryTree(historyTree);
        }

    } finally {
        historyLock.writeLock().unlock();
    }

    core.getMetrics().trashedHistoryNotifications.inc(trashedNotifications);
    core.getMetrics().historySize.set(notificationsCount);
    core.getMetrics().historyQueues.set(historyQueuesCount);
}

From source file:com.webcohesion.enunciate.modules.ruby_json_client.RubyJSONClientModule.java

@Override
public void call(EnunciateContext context) {
    if ((this.jacksonModule == null || this.jacksonModule.getJacksonContext() == null
            || this.jacksonModule.getJacksonContext().getTypeDefinitions().isEmpty())
            && (this.jackson1Module == null || this.jackson1Module.getJacksonContext() == null
                    || this.jackson1Module.getJacksonContext().getTypeDefinitions().isEmpty())) {
        info("No Jackson JSON data types: Ruby JSON client will not be generated.");
        return;/*from  w w w  .j  a v  a  2 s  .  com*/
    }

    if (usesUnmappableElements()) {
        warn("Web service API makes use of elements that cannot be handled by the Ruby JSON client. Ruby JSON client will not be generated.");
        return;
    }

    Map<String, String> packageToModuleConversions = getPackageToModuleConversions();
    List<DecoratedTypeElement> schemaTypes = new ArrayList<DecoratedTypeElement>();
    ExtensionDepthComparator comparator = new ExtensionDepthComparator();
    EnunciateJacksonContext jacksonContext = null;
    EnunciateJackson1Context jackson1Context = null;

    if (this.jacksonModule != null) {
        jacksonContext = this.jacksonModule.getJacksonContext();
        for (TypeDefinition typeDefinition : jacksonContext.getTypeDefinitions()) {
            String pckg = typeDefinition.getPackage().getQualifiedName().toString();
            if (!packageToModuleConversions.containsKey(pckg)) {
                packageToModuleConversions.put(pckg, packageToModule(pckg));
            }

            int position = Collections.binarySearch(schemaTypes, typeDefinition, comparator);
            if (position < 0) {
                position = -position - 1;
            }
            schemaTypes.add(position, typeDefinition);
        }
    }

    if (this.jackson1Module != null) {
        jackson1Context = this.jackson1Module.getJacksonContext();
        for (com.webcohesion.enunciate.modules.jackson1.model.TypeDefinition typeDefinition : jackson1Context
                .getTypeDefinitions()) {
            String pckg = typeDefinition.getPackage().getQualifiedName().toString();
            if (!packageToModuleConversions.containsKey(pckg)) {
                packageToModuleConversions.put(pckg, packageToModule(pckg));
            }
            schemaTypes.add(typeDefinition);
        }
    }

    File srcDir = getSourceDir();
    Map<String, Object> model = new HashMap<String, Object>();

    model.put("schemaTypes", schemaTypes);

    model.put("schemaTypes", schemaTypes);
    model.put("packages2modules", packageToModuleConversions);
    model.put("moduleFor", new ClientPackageForMethod(packageToModuleConversions, this.context));
    ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(packageToModuleConversions,
            jacksonContext, jackson1Context);
    model.put("classnameFor", classnameFor);
    SimpleNameWithParamsMethod simpleNameFor = new SimpleNameWithParamsMethod(classnameFor);
    model.put("simpleNameFor", simpleNameFor);
    model.put("rubyFileName", getSourceFileName());
    model.put("file", new FileDirective(srcDir, this.enunciate.getLogger()));
    model.put("generatedCodeLicense", this.enunciate.getConfiguration().readGeneratedCodeLicenseFile());

    Set<String> facetIncludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetIncludes());
    facetIncludes.addAll(getFacetIncludes());
    Set<String> facetExcludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetExcludes());
    facetExcludes.addAll(getFacetExcludes());
    FacetFilter facetFilter = new FacetFilter(facetIncludes, facetExcludes);

    model.put("isFacetExcluded", new IsFacetExcludedMethod(facetFilter));

    if (!isUpToDateWithSources(srcDir)) {
        debug("Generating the Ruby JSON data classes...");
        URL apiTemplate = getTemplateURL("api.fmt");
        try {
            processTemplate(apiTemplate, model);
        } catch (IOException e) {
            throw new EnunciateException(e);
        } catch (TemplateException e) {
            throw new EnunciateException(e);
        }
    } else {
        info("Skipping Ruby code generation because everything appears up-to-date.");
    }

    ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "ruby.json.client.library",
            "Ruby JSON Client Library");
    artifactBundle.setPlatform("Ruby");
    FileArtifact sourceScript = new FileArtifact(getName(), "ruby.json.client",
            new File(srcDir, getSourceFileName()));
    sourceScript.setArtifactType(ArtifactType.binaries); //binaries and sources are the same thing in ruby
    sourceScript.setPublic(false);
    String description = readResource("library_description.fmt", model); //read in the description from file
    artifactBundle.setDescription(description);
    artifactBundle.addArtifact(sourceScript);
    this.enunciate.addArtifact(artifactBundle);
}

From source file:com.webcohesion.enunciate.modules.php_json_client.PHPJSONClientModule.java

@Override
public void call(EnunciateContext context) {
    if ((this.jacksonModule == null || this.jacksonModule.getJacksonContext() == null
            || this.jacksonModule.getJacksonContext().getTypeDefinitions().isEmpty())
            && (this.jackson1Module == null || this.jackson1Module.getJacksonContext() == null
                    || this.jackson1Module.getJacksonContext().getTypeDefinitions().isEmpty())) {
        info("No Jackson JSON data types: PHP JSON client will not be generated.");
        return;/* w  w w .  j a  v  a2 s.  c o  m*/
    }

    if (usesUnmappableElements()) {
        warn("Web service API makes use of elements that cannot be handled by the PHP JSON client. PHP JSON client will not be generated.");
        return;
    }

    Map<String, String> packageToNamespaceConversions = getPackageToNamespaceConversions();
    List<DecoratedTypeElement> schemaTypes = new ArrayList<DecoratedTypeElement>();
    ExtensionDepthComparator comparator = new ExtensionDepthComparator();
    EnunciateJacksonContext jacksonContext = null;
    EnunciateJackson1Context jackson1Context = null;

    if (this.jacksonModule != null) {
        jacksonContext = this.jacksonModule.getJacksonContext();
        for (TypeDefinition typeDefinition : jacksonContext.getTypeDefinitions()) {
            String pckg = typeDefinition.getPackage().getQualifiedName().toString();
            if (!packageToNamespaceConversions.containsKey(pckg)) {
                packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
            }

            int position = Collections.binarySearch(schemaTypes, typeDefinition, comparator);
            if (position < 0) {
                position = -position - 1;
            }
            schemaTypes.add(position, typeDefinition);
        }
    }

    if (this.jackson1Module != null) {
        jackson1Context = this.jackson1Module.getJacksonContext();
        for (com.webcohesion.enunciate.modules.jackson1.model.TypeDefinition typeDefinition : jackson1Context
                .getTypeDefinitions()) {
            String pckg = typeDefinition.getPackage().getQualifiedName().toString();
            if (!packageToNamespaceConversions.containsKey(pckg)) {
                packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
            }
            schemaTypes.add(typeDefinition);
        }
    }

    File srcDir = getSourceDir();
    Map<String, Object> model = new HashMap<String, Object>();

    model.put("schemaTypes", schemaTypes);
    model.put("namespaceFor", new ClientPackageForMethod(packageToNamespaceConversions, this.context));
    ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(packageToNamespaceConversions,
            jacksonContext, jackson1Context);
    model.put("classnameFor", classnameFor);
    model.put("typeNameFor",
            new TypeNameForMethod(packageToNamespaceConversions, jacksonContext, jackson1Context));
    model.put("simpleNameFor", new SimpleNameWithParamsMethod(classnameFor));
    model.put("phpFileName", getSourceFileName());
    model.put("file", new FileDirective(srcDir, this.enunciate.getLogger()));
    model.put("generatedCodeLicense", this.enunciate.getConfiguration().readGeneratedCodeLicenseFile());

    Set<String> facetIncludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetIncludes());
    facetIncludes.addAll(getFacetIncludes());
    Set<String> facetExcludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetExcludes());
    facetExcludes.addAll(getFacetExcludes());
    FacetFilter facetFilter = new FacetFilter(facetIncludes, facetExcludes);

    model.put("isFacetExcluded", new IsFacetExcludedMethod(facetFilter));

    if (!isUpToDateWithSources(srcDir)) {
        debug("Generating the PHP data classes...");
        URL apiTemplate = isSingleFilePerClass() ? getTemplateURL("api-multiple-files.fmt")
                : getTemplateURL("api.fmt");
        try {
            processTemplate(apiTemplate, model);
        } catch (IOException e) {
            throw new EnunciateException(e);
        } catch (TemplateException e) {
            throw new EnunciateException(e);
        }
    } else {
        info("Skipping PHP code generation because everything appears up-to-date.");
    }

    File packageDir = getPackageDir();
    packageDir.mkdirs();

    File bundle = new File(packageDir, getBundleFileName());
    boolean anyFiles = bundle.exists();
    if (!isUpToDateWithSources(packageDir)) {
        try {
            anyFiles = enunciate.zip(bundle, srcDir);
        } catch (IOException e) {
            throw new EnunciateException(e);
        }
    }

    if (anyFiles) {
        ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "php.json.client.library",
                "PHP JSON Client Library");
        artifactBundle.setPlatform("PHP");
        FileArtifact sourceScript = new FileArtifact(getName(), "php.json.client", bundle);
        sourceScript.setArtifactType(ArtifactType.binaries); //binaries and sources are the same thing in php
        sourceScript.setPublic(false);
        String description = readResource("library_description.fmt", model); //read in the description from file
        artifactBundle.setDescription(description);
        artifactBundle.addArtifact(sourceScript);
        this.enunciate.addArtifact(artifactBundle);
    }
}

From source file:org.ala.dao.FulltextSearchDaoImplSolr.java

public SearchTaxonConceptDTO getPhylum(Integer left, Integer right) {
    SearchTaxonConceptDTO dto = null;//  w  w  w.j a  v  a2  s.c o m
    SearchTaxonConceptDTO input = new SearchTaxonConceptDTO();
    input.setLeft(left);
    input.setRight(right);
    if (pyhlumList != null && pyhlumList.size() > 0) {
        int i = Collections.binarySearch(pyhlumList, input, new SearchTaxonConceptComparator());
        if (i >= 0) {
            dto = pyhlumList.get(i);
        }
    }
    return dto;
}

From source file:com.webcohesion.enunciate.modules.javascript_client.JavaScriptClientModule.java

@Override
public void call(EnunciateContext context) {
    if ((this.jacksonModule == null || this.jacksonModule.getJacksonContext() == null
            || this.jacksonModule.getJacksonContext().getTypeDefinitions().isEmpty())
            && (this.jackson1Module == null || this.jackson1Module.getJacksonContext() == null
                    || this.jackson1Module.getJacksonContext().getTypeDefinitions().isEmpty())) {
        info("No Jackson JSON data types: JavaScript client will not be generated.");
        return;/*w w  w  . ja  va2s .co  m*/
    }

    detectAccessorNamingErrors();

    Map<String, String> packageToNamespaceConversions = getPackageToNamespaceConversions();
    List<DecoratedTypeElement> schemaTypes = new ArrayList<DecoratedTypeElement>();
    ExtensionDepthComparator comparator = new ExtensionDepthComparator();
    EnunciateJacksonContext jacksonContext = null;
    EnunciateJackson1Context jackson1Context = null;

    if (this.jacksonModule != null) {
        jacksonContext = this.jacksonModule.getJacksonContext();
        for (TypeDefinition typeDefinition : jacksonContext.getTypeDefinitions()) {
            String pckg = typeDefinition.getPackage().getQualifiedName().toString();
            if (!packageToNamespaceConversions.containsKey(pckg)) {
                packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
            }

            int position = Collections.binarySearch(schemaTypes, typeDefinition, comparator);
            if (position < 0) {
                position = -position - 1;
            }
            schemaTypes.add(position, typeDefinition);
        }
    }

    if (this.jackson1Module != null) {
        jackson1Context = this.jackson1Module.getJacksonContext();
        for (com.webcohesion.enunciate.modules.jackson1.model.TypeDefinition typeDefinition : jackson1Context
                .getTypeDefinitions()) {
            String pckg = typeDefinition.getPackage().getQualifiedName().toString();
            if (!packageToNamespaceConversions.containsKey(pckg)) {
                packageToNamespaceConversions.put(pckg, packageToNamespace(pckg));
            }
            schemaTypes.add(typeDefinition);
        }
    }

    File srcDir = getSourceDir();
    Map<String, Object> model = new HashMap<String, Object>();

    model.put("globalName", this.config.getString("[@global]", "javascriptClient"));
    model.put("schemaTypes", schemaTypes);
    model.put("namespaceFor", new ClientPackageForMethod(packageToNamespaceConversions, this.context));
    ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(packageToNamespaceConversions,
            jacksonContext, jackson1Context);
    model.put("classnameFor", classnameFor);
    model.put("typeNameFor",
            new TypeNameForMethod(packageToNamespaceConversions, jacksonContext, jackson1Context));
    model.put("simpleNameFor", new SimpleNameWithParamsMethod(classnameFor));
    model.put("jsFileName", getSourceFileName());
    model.put("file", new FileDirective(srcDir, this.enunciate.getLogger()));
    model.put("generatedCodeLicense", this.enunciate.getConfiguration().readGeneratedCodeLicenseFile());

    Set<String> facetIncludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetIncludes());
    facetIncludes.addAll(getFacetIncludes());
    Set<String> facetExcludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetExcludes());
    facetExcludes.addAll(getFacetExcludes());
    FacetFilter facetFilter = new FacetFilter(facetIncludes, facetExcludes);

    model.put("isFacetExcluded", new IsFacetExcludedMethod(facetFilter));

    if (!isUpToDateWithSources(srcDir)) {
        debug("Generating the JavaScript data classes...");
        URL apiTemplate = getTemplateURL("api.fmt");
        try {
            processTemplate(apiTemplate, model);
        } catch (IOException e) {
            throw new EnunciateException(e);
        } catch (TemplateException e) {
            throw new EnunciateException(e);
        }
    } else {
        info("Skipping JavaScript code generation because everything appears up-to-date.");
    }

    File packageDir = getPackageDir();
    packageDir.mkdirs();

    File bundle = new File(packageDir, getBundleFileName());
    boolean anyFiles = bundle.exists();
    if (!isUpToDateWithSources(packageDir)) {
        try {
            anyFiles = enunciate.zip(bundle, srcDir);
        } catch (IOException e) {
            throw new EnunciateException(e);
        }
    }

    if (anyFiles) {
        ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "js.client.library",
                "JavaScript Client Library");
        artifactBundle.setPlatform("JavaScript");
        FileArtifact sourceScript = new FileArtifact(getName(), "javascript.client", bundle);
        sourceScript.setArtifactType(ArtifactType.binaries); //binaries and sources are the same thing in js
        sourceScript.setPublic(false);
        String description = readResource("library_description.fmt", model); //read in the description from file
        artifactBundle.setDescription(description);
        artifactBundle.addArtifact(sourceScript);
        this.enunciate.addArtifact(artifactBundle);
    }
}