Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

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

Prototype

public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) 

Source Link

Document

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

Usage

From source file:org.archive.wayback.resourceindex.distributed.AlphaPartitionedIndex.java

protected RangeGroup getRangeGroupForRequest(WaybackRequest wbRequest)
        throws BadQueryException, ResourceIndexNotAvailableException {

    String keyUrl;/*from  www . j  ava2s  . com*/
    try {
        checkMapFile();
    } catch (IOException e) {
        // TODO: this is too much error info if we're repeatedly failing..
        e.printStackTrace();
        throw new ResourceIndexNotAvailableException(e.getMessage());
    }

    if (groups == null || groups.length == 0) {
        throw new ResourceIndexNotAvailableException("empty map file");
    }

    String searchUrl = wbRequest.getRequestUrl();
    if (searchUrl == null) {
        throw new BadQueryException("No " + WaybackRequest.REQUEST_URL + " specified");
    }

    try {
        keyUrl = canonicalizer.urlStringToKey(searchUrl);
    } catch (URIException e) {
        throw new BadQueryException("invalid " + WaybackRequest.REQUEST_URL + " " + searchUrl);
    }
    RangeGroup dummy = new RangeGroup("", keyUrl, "");
    int loc = Arrays.binarySearch(groups, dummy, comparator);
    if (loc < 0) {
        loc = (loc * -1) - 2;
    }
    LOGGER.info("Using group(" + groups[loc].getName() + ") for url (" + keyUrl + ")");
    return groups[loc];
}

From source file:com.bigdata.dastor.db.Memtable.java

/**
 * obtain an iterator of columns in this memtable in the specified order starting from a given column.
 *//*  w ww  . j  a v  a 2  s . com*/
public ColumnIterator getSliceIterator(ColumnFamily cf, SliceQueryFilter filter, AbstractType typeComparator) {
    final ColumnFamily columnFamily = cf == null
            ? ColumnFamily.create(getTableName(), filter.getColumnFamilyName())
            : cf.cloneMeShallow();

    final IColumn columns[] = (cf == null ? columnFamily : cf).getSortedColumns()
            .toArray(new IColumn[columnFamily.getSortedColumns().size()]);
    // TODO if we are dealing with supercolumns, we need to clone them while we have the read lock since they can be modified later
    if (filter.reversed)
        ArrayUtils.reverse(columns);
    IColumn startIColumn;
    final boolean isStandard = DatabaseDescriptor
            .getColumnFamilyType(getTableName(), filter.getColumnFamilyName()).equals("Standard");
    if (isStandard)
        startIColumn = new Column(filter.start);
    else
        startIColumn = new SuperColumn(filter.start, null); // ok to not have subcolumnComparator since we won't be adding columns to this object

    // can't use a ColumnComparatorFactory comparator since those compare on both name and time (and thus will fail to match
    // our dummy column, since the time there is arbitrary).
    Comparator<IColumn> comparator = filter.getColumnComparator(typeComparator);
    int index;
    if (filter.start.length == 0 && filter.reversed) {
        /* scan from the largest column in descending order */
        index = 0;
    } else {
        index = Arrays.binarySearch(columns, startIColumn, comparator);
    }
    final int startIndex = index < 0 ? -(index + 1) : index;

    return new AbstractColumnIterator() {
        private int curIndex_ = startIndex;

        public ColumnFamily getColumnFamily() {
            return columnFamily;
        }

        public boolean hasNext() {
            return curIndex_ < columns.length;
        }

        public IColumn next() {
            // clone supercolumns so caller can freely removeDeleted or otherwise mutate it
            return isStandard ? columns[curIndex_++] : ((SuperColumn) columns[curIndex_++]).cloneMe();
        }
    };
}

From source file:com.github.sdbg.debug.core.internal.sourcemaps.SourceMap.java

private int findIndexForLine(int line) {
    // TODO(devoncarew): test this binary search

    int location = Arrays.binarySearch(entries, SourceMapInfoEntry.forLine(line),
            SourceMapInfoEntry.lineComparator());

    if (location < 0) {
        return -1;
    }/*from  ww w  .j  av a2s .c om*/

    while (location > 0 && entries[location - 1].line == line) {
        location--;
    }

    return location;

    //    for (int i = 0; i < entries.length; i++) {
    //      SourceMapInfoEntry entry = entries[i];
    //
    //      if (entry.line == line) {
    //        return i;
    //      } else if (entry.line > line) {
    //        return -1;
    //      }
    //    }
    //
    //    return -1;
}

From source file:name.ikysil.beanpathdsl.codegen.CodeGen.java

/**
 * checks if the input string is a valid Java keyword.
 *
 * @return boolean true/false//from   w  ww.java 2  s. c  o m
 */
public static boolean isJavaKeyword(String name) {
    return (Arrays.binarySearch(JAVA_KEYWORDS, name, ENGLISH_COLLATOR) >= 0);
}

From source file:org.gvnix.service.roo.addon.addon.util.WsdlParserUtils.java

/**
 * Checks if the input string is a valid java keyword.
 * //from   w  w w.  ja  va  2  s  . c o  m
 * @return boolean true/false
 */
public static boolean isJavaKeyword(String keyword) {
    return (Arrays.binarySearch(keywords, keyword, englishCollator) >= 0);
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.MergeManager.java

private void setHandlers(Properties props)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    ArrayList<MergeHandler> handlers = new ArrayList<MergeHandler>();
    for (String key : props.stringPropertyNames()) {
        if (key.startsWith("handler.")) {
            MergeHandler temp = (MergeHandler) Class.forName(props.getProperty(key)).newInstance();
            String name = key.substring(8, key.length());
            temp.setName(name);//  w w  w  . j  a v a  2s .c o m
            String priority = props.getProperty("priority." + name);
            if (priority != null) {
                temp.setPriority(Integer.parseInt(priority));
            }
            String xpath = props.getProperty("xpath." + name);
            if (priority != null) {
                temp.setXPath(xpath);
            }
            handlers.add(temp);
        }
    }
    MergeHandler[] explodedView = {};
    explodedView = handlers.toArray(explodedView);
    Comparator<Object> nameCompare = new Comparator<Object>() {
        @Override
        public int compare(Object arg0, Object arg1) {
            return ((MergeHandler) arg0).getName().compareTo(((MergeHandler) arg1).getName());
        }
    };
    Arrays.sort(explodedView, nameCompare);
    ArrayList<MergeHandler> finalHandlers = new ArrayList<MergeHandler>();
    for (MergeHandler temp : explodedView) {
        if (temp.getName().contains(".")) {
            final String parentName = temp.getName().substring(0, temp.getName().lastIndexOf("."));
            int pos = Arrays.binarySearch(explodedView, new MergeHandlerAdapter() {
                @Override
                public String getName() {
                    return parentName;
                }
            }, nameCompare);
            if (pos >= 0) {
                MergeHandler[] parentHandlers = explodedView[pos].getChildren();
                MergeHandler[] newHandlers = new MergeHandler[parentHandlers.length + 1];
                System.arraycopy(parentHandlers, 0, newHandlers, 0, parentHandlers.length);
                newHandlers[newHandlers.length - 1] = temp;
                Arrays.sort(newHandlers);
                explodedView[pos].setChildren(newHandlers);
            }
        } else {
            finalHandlers.add(temp);
        }
    }

    this.handlers = new MergeHandler[0];
    this.handlers = finalHandlers.toArray(this.handlers);
    Arrays.sort(this.handlers);
}

From source file:org.broadleafcommerce.vendor.cybersource.service.tax.CyberSourceTaxServiceImpl.java

protected void setTaxRates(CyberSourceTaxResponse taxResponse, CyberSourceTaxRequest taxRequest,
        TaxReplyItem[] replyItems) {//from  w w w . ja  v a2s . c  o m
    CyberSourceTaxItemRequest requestItem = (CyberSourceTaxItemRequest) taxRequest.getItemRequests().get(0);
    BigDecimal unitPrice = requestItem.getUnitPrice().getAmount();
    BigInteger requestId = new BigInteger(String.valueOf(requestItem.getId()));
    TaxReplyItem key = new TaxReplyItem();
    key.setId(requestId);
    int pos = Arrays.binarySearch(replyItems, key, new Comparator<TaxReplyItem>() {

        public int compare(TaxReplyItem one, TaxReplyItem two) {
            return one.getId().compareTo(two.getId());
        }

    });
    if (pos >= 0) {
        TaxReplyItem replyItem = replyItems[pos];
        if (replyItem.getCityTaxAmount() != null) {
            BigDecimal cityRate = new BigDecimal(replyItem.getCityTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setCityRate(cityRate);
        }
        if (replyItem.getCountyTaxAmount() != null) {
            BigDecimal countyRate = new BigDecimal(replyItem.getCountyTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setCountyRate(countyRate);
        }
        if (replyItem.getDistrictTaxAmount() != null) {
            BigDecimal districtRate = new BigDecimal(replyItem.getDistrictTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setDistrictRate(districtRate);
        }
        if (replyItem.getStateTaxAmount() != null) {
            BigDecimal stateRate = new BigDecimal(replyItem.getStateTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setStateRate(stateRate);
        }
        if (replyItem.getTotalTaxAmount() != null) {
            BigDecimal totalRate = new BigDecimal(replyItem.getTotalTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setTotalRate(totalRate);
        }
    }
}

From source file:com.limewoodmedia.nsdroid.activities.Region.java

private void doRMBSetup() {
    // Region name
    rmbRegion.setText(data.name);/*w w  w.ja  v  a 2s.c  o m*/

    rmbInner.setMessages(data.messages, 0, homeRegion);

    Comparator<String> comparator = new AlphabeticComparator();
    Arrays.sort(data.nations, comparator);
    String region = TagParser.nameToId(NationInfo.getInstance(this).getRegionId());
    boolean hasEmbassyWithYourRegion = false;
    for (Embassy e : data.embassies) {
        if (TagParser.nameToId(e.region).equals(region)) {
            hasEmbassyWithYourRegion = true;
            break;
        }
    }
    if (Arrays.binarySearch(data.nations, NationInfo.getInstance(this).getId(), comparator) > -1 // You are a resident in the region
            || hasEmbassyWithYourRegion) {
        allowPosting = true;
        supportInvalidateOptionsMenu();
    }
}

From source file:org.apache.hadoop.hbase.index.mapreduce.IndexLoadIncrementalHFile.java

/**
 * Attempt to assign the given load queue item into its target region group. If the hfile boundary
 * no longer fits into a region, physically splits the hfile such that the new bottom half will
 * fit and returns the list of LQI's corresponding to the resultant hfiles. protected for testing
 *///from  w ww  .j a v  a2  s  .com
protected List<LoadQueueItem> groupOrSplit(Multimap<ByteBuffer, LoadQueueItem> regionGroups,
        final LoadQueueItem item, final HTable table, final Pair<byte[][], byte[][]> startEndKeys)
        throws IOException {
    final Path hfilePath = item.hfilePath;
    final FileSystem fs = hfilePath.getFileSystem(getConf());
    HFile.Reader hfr = HFile.createReader(fs, hfilePath, new CacheConfig(getConf()));
    final byte[] first, last;
    try {
        hfr.loadFileInfo();
        first = hfr.getFirstRowKey();
        last = hfr.getLastRowKey();
    } finally {
        hfr.close();
    }

    LOG.info("Trying to load hfile=" + hfilePath + " first=" + Bytes.toStringBinary(first) + " last="
            + Bytes.toStringBinary(last));
    if (first == null || last == null) {
        assert first == null && last == null;
        // TODO what if this is due to a bad HFile?
        LOG.info("hfile " + hfilePath + " has no entries, skipping");
        return null;
    }
    if (Bytes.compareTo(first, last) > 0) {
        throw new IllegalArgumentException(
                "Invalid range: " + Bytes.toStringBinary(first) + " > " + Bytes.toStringBinary(last));
    }
    int idx = Arrays.binarySearch(startEndKeys.getFirst(), first, Bytes.BYTES_COMPARATOR);
    if (idx < 0) {
        // not on boundary, returns -(insertion index). Calculate region it
        // would be in.
        idx = -(idx + 1) - 1;
    }
    final int indexForCallable = idx;
    boolean lastKeyInRange = Bytes.compareTo(last, startEndKeys.getSecond()[idx]) < 0
            || Bytes.equals(startEndKeys.getSecond()[idx], HConstants.EMPTY_BYTE_ARRAY);
    if (!lastKeyInRange) {
        List<LoadQueueItem> lqis = splitStoreFile(item, table, startEndKeys.getFirst()[indexForCallable],
                startEndKeys.getSecond()[indexForCallable]);
        return lqis;
    }

    // group regions.
    regionGroups.put(ByteBuffer.wrap(startEndKeys.getFirst()[idx]), item);
    return null;
}

From source file:com.ecyrd.jspwiki.parser.JSPWikiMarkupParser.java

/**
 *  Figures out if a link is an off-site link.  This recognizes
 *  the most common protocols by checking how it starts.
 *
 *  @param link The link to check./*  ww w .j  av  a  2  s  .com*/
 *  @return true, if this is a link outside of this wiki.
 *  @since 2.4
 */

public static boolean isExternalLink(String link) {
    int idx = Arrays.binarySearch(EXTERNAL_LINKS, link, c_startingComparator);

    //
    //  We need to check here once again; otherwise we might
    //  get a match for something like "h".
    //
    if (idx >= 0 && link.startsWith(EXTERNAL_LINKS[idx]))
        return true;

    return false;
}