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:stargate.commons.recipe.Recipe.java

@JsonIgnore
public RecipeChunk getChunk(long offset) throws IOException {
    if (this.chunkSize != 0) {
        int index = (int) (offset / this.chunkSize);
        RecipeChunk chunk = this.chunk.get(index);

        if (chunk.getOffset() <= offset && chunk.getOffset() + chunk.getLength() > offset) {
            return chunk;
        } else {//from w  w w.  j a va  2 s.co  m
            throw new IOException("unable to find chunk at " + offset);
        }
    }

    RecipeChunk searchKey = new RecipeChunk();
    searchKey.setOffset(offset);
    searchKey.setLength(0);
    int location = Collections.binarySearch(this.chunk, searchKey, new Comparator<RecipeChunk>() {

        @Override
        public int compare(RecipeChunk t, RecipeChunk t1) {
            return (int) (t.getOffset() - t1.getOffset());
        }
    });

    if (location >= 0) {
        return this.chunk.get(location);
    } else {
        RecipeChunk chunk = this.chunk.get(Math.abs(location + 1));
        if (chunk.getOffset() <= offset && chunk.getOffset() + chunk.getLength() > offset) {
            return chunk;
        } else {
            throw new IOException("unable to find chunk at " + offset);
        }
    }
}

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

protected PlugwiseDevice getDeviceByName(String name) {

    PlugwiseDevice queryDevice = new PlugwiseDevice(null, null, name);
    Collections.sort(plugwiseDeviceCache, friendlyPlugComparator);
    int index = Collections.binarySearch(plugwiseDeviceCache, queryDevice, friendlyPlugComparator);
    if (index >= 0) {
        return plugwiseDeviceCache.get(index);
    } else {//from   w w  w . j  a  v  a  2 s. c om
        return null;
    }
}

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

/**
 * Returns the event intersecting the specified time.
 *
 * @param time the time/*w  w  w.  j a  v  a  2  s .c  o  m*/
 * @return the corresponding event, or {@code null} if none is found
 */
public PropertySet getIntersectingEvent(Date time) {
    PropertySet set = new ObjectSet();
    set.set(ScheduleEvent.ACT_START_TIME, time);
    set.set(ScheduleEvent.ACT_END_TIME, time);
    int index = Collections.binarySearch(events, set, intersectComparator);
    return (index < 0) ? null : events.get(index);
}

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

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

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

@Override
@SuppressWarnings("unchecked")
public V put(K key, V value) {
    Entry<K, V> entry = new Entry<K, V>(key, value);
    int idx = Collections.binarySearch((List) list, key, comparator);
    if (idx >= 0) {
        Map.Entry<K, V> oldEntry = list.set(idx, entry);
        return oldEntry.getValue();
    } else {/*from ww  w  . j a  va  2s .c o m*/
        idx = -1 * idx - 1;
        list.add(idx, entry);
        return null;
    }
}

From source file:org.tinymediamanager.core.movie.entities.MovieSet.java

/**
 * Inserts the movie into the right position of the list
 * //from  w  ww  .j a v a  2  s . c  o  m
 * @param movie
 *          the movie to insert into the movie set
 */
public void insertMovie(Movie movie) {
    synchronized (movies) {
        if (movies.contains(movie)) {
            return;
        }

        int index = Collections.binarySearch(movies, movie, MOVIE_SET_COMPARATOR);
        if (index < 0) {
            movies.add(-index - 1, movie);
            movieIds.add(-index - 1, movie.getDbId());
        } else if (index >= 0) {
            movies.add(index, movie);
            movieIds.add(index, movie.getDbId());
        }

        // update artwork
        MovieSetArtworkHelper.updateArtwork(this);

        saveToDb();
    }

    // write images
    List<Movie> movies = new ArrayList<>(1);
    movies.add(movie);
    if (MovieModuleManager.MOVIE_SETTINGS.isEnableMovieSetArtworkMovieFolder()) {
        MovieSetArtworkHelper.writeImagesToMovieFolder(this, movies);
    }

    firePropertyChange("addedMovie", null, movie);
    firePropertyChange("movies", null, movies);
}

From source file:com.webcohesion.enunciate.modules.php_xml_client.PHPXMLClientModule.java

@Override
public void call(EnunciateContext context) {
    if (this.jaxbModule == null || this.jaxbModule.getJaxbContext() == null
            || this.jaxbModule.getJaxbContext().getSchemas().isEmpty()) {
        info("No JAXB XML data types: PHP XML client will not be generated.");
        return;//  w  w  w .  j  a  v  a2 s .  co m
    }

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

    List<String> namingConflicts = JAXBErrors
            .findConflictingAccessorNamingErrors(this.jaxbModule.getJaxbContext());
    if (namingConflicts != null && !namingConflicts.isEmpty()) {
        error("JAXB naming conflicts have been found:");
        for (String namingConflict : namingConflicts) {
            error(namingConflict);
        }
        error("These naming conflicts are often between the field and it's associated property, in which case you need to use one or two of the following strategies to avoid the conflicts:");
        error("1. Explicitly exclude one or the other.");
        error("2. Put the annotations on the property instead of the field.");
        error("3. Tell JAXB to use a different process for detecting accessors using the @XmlAccessorType annotation.");
        throw new EnunciateException("JAXB naming conflicts detected.");
    }

    Map<String, String> packageToNamespaceConversions = getPackageToNamespaceConversions();
    List<TypeDefinition> schemaTypes = new ArrayList<TypeDefinition>();
    ExtensionDepthComparator comparator = new ExtensionDepthComparator();

    EnunciateJaxbContext jaxbContext = this.jaxbModule.getJaxbContext();

    for (SchemaInfo schemaInfo : jaxbContext.getSchemas().values()) {
        for (TypeDefinition typeDefinition : schemaInfo.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);
        }
    }

    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,
            jaxbContext);
    model.put("classnameFor", classnameFor);
    model.put("typeNameFor", new TypeNameForMethod(packageToNamespaceConversions, jaxbContext));
    model.put("simpleNameFor", new SimpleNameWithParamsMethod(classnameFor));
    model.put("phpFileName", getSourceFileName());
    model.put("findRootElement", new FindRootElementMethod(jaxbContext));
    model.put("referencedNamespaces", new ReferencedNamespacesMethod(jaxbContext));
    model.put("prefix", new PrefixMethod(jaxbContext.getNamespacePrefixes()));
    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 XML 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 XML 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.xml.client.library",
                "PHP XML Client Library");
        artifactBundle.setPlatform("PHP");
        FileArtifact sourceScript = new FileArtifact(getName(), "php.xml.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:io.druid.server.coordinator.cost.SegmentsCostCache.java

public double cost(DataSegment segment) {
    double cost = 0.0;
    int index = Collections.binarySearch(intervals, segment.getInterval(),
            Comparators.intervalsByStartThenEnd());
    index = (index >= 0) ? index : -index - 1;

    for (ListIterator<Bucket> it = sortedBuckets.listIterator(index); it.hasNext();) {
        Bucket bucket = it.next();/*from w ww . j  a v a 2 s  . c  om*/
        if (!bucket.inCalculationInterval(segment)) {
            break;
        }
        cost += bucket.cost(segment);
    }

    for (ListIterator<Bucket> it = sortedBuckets.listIterator(index); it.hasPrevious();) {
        Bucket bucket = it.previous();
        if (!bucket.inCalculationInterval(segment)) {
            break;
        }
        cost += bucket.cost(segment);
    }

    return cost;
}

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

@Override
@SuppressWarnings("unchecked")
public V remove(Object key) {
    if (list.isEmpty())
        return null;
    int idx = Collections.binarySearch((List) list, key, comparator);
    if (idx >= 0) {
        Map.Entry<K, V> entry = list.remove(idx);
        return entry.getValue();
    }/* www. jav  a 2s .c  o  m*/
    return null;
}

From source file:de.mrapp.android.util.view.AttachedViewRecycler.java

@SafeVarargs
@NonNull/*  w  w  w.  j  a v a 2  s  .c  o  m*/
@Override
public final Pair<View, Boolean> inflate(@NonNull final ItemType item, final boolean useCache,
        @NonNull final ParamType... params) {
    ensureNotNull(params, "The array may not be null");
    ensureNotNull(getAdapter(), "No adapter has been set", IllegalStateException.class);

    View view = getView(item);
    boolean inflated = false;

    if (view == null) {
        int viewType = getAdapter().getViewType(item);

        if (useCache) {
            view = pollUnusedView(viewType);
        }

        if (view == null) {
            view = getAdapter().onInflateView(getLayoutInflater(), parent, item, viewType, params);
            inflated = true;
            getLogger().logInfo(getClass(),
                    "Inflated view to visualize item " + item + " using view type " + viewType);
        } else {
            getLogger().logInfo(getClass(),
                    "Reusing view to visualize item " + item + " using view type " + viewType);
        }

        getActiveViews().put(item, view);
        int index;

        if (comparator != null) {
            index = Collections.binarySearch(items, item, comparator);

            if (index < 0) {
                index = ~index;
            }
        } else {
            index = items.size();
        }

        items.add(index, item);
        parent.addView(view, index);
        getLogger().logDebug(getClass(), "Added view of item " + item + " at index " + index);
    }

    getAdapter().onShowView(getContext(), view, item, inflated, params);
    getLogger().logDebug(getClass(), "Updated view of item " + item);
    return Pair.create(view, inflated);
}