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 int binarySearch(Object[] a, Object key) 

Source Link

Document

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

Usage

From source file:com.krawler.esp.servlets.importProjectPlanCSV.java

public String getActualDuration(Date stdate, Date enddate, int[] NonWorkDays, String[] holidays) {
    int noofdays = 0;
    java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
    try {//  ww w.j a  va 2s . c o  m
        Calendar c1 = Calendar.getInstance();
        while (stdate.compareTo(enddate) < 0) {
            if (Arrays.binarySearch(NonWorkDays, stdate.getDay()) < 0
                    && Arrays.binarySearch(holidays, sdf1.format(stdate)) < 0) {
                noofdays++;
            }
            c1.set(stdate.getYear() + 1900, stdate.getMonth(), stdate.getDate());
            c1.add(Calendar.DATE, 1);
            stdate = sdf1.parse(sdf1.format(c1.getTime()));
        }
        if (stdate.compareTo(enddate) == 0) {
            if (Arrays.binarySearch(NonWorkDays, stdate.getDay()) < 0
                    && Arrays.binarySearch(holidays, sdf1.format(stdate)) < 0) {
                noofdays++;
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
    }
    return noofdays + "d";
}

From source file:com.enonic.esl.xml.XMLTool.java

private static Document domparse(InputSource inputSource, String[] rootNames) {
    Document doc;//from   w ww  . jav a 2s . co  m

    try {
        doc = getDocumentBuilder().parse(inputSource);
    } catch (IOException e) {
        throw new XMLToolException("Failed to retrieve XML source document on the given URL", e);
    } catch (SAXException e) {
        throw new XMLToolException("Failed to parse xml document", e);
    }

    if (rootNames != null) {
        Element root = doc.getDocumentElement();
        if (root == null) {
            throw new XMLToolException("No root element in XML document");
        }

        Arrays.sort(rootNames);
        if (Arrays.binarySearch(rootNames, root.getTagName()) < 0) {
            throw new XMLToolException("Wrong root element name: " + root.getTagName());
        }
    }

    return doc;
}

From source file:com.feigdev.webcom.PersistentCookieStore.java

/**
 * parseCookie() parses the cookieString which is a comma-separated list of
 * one or more cookies in the format of "NAME=VALUE; expires=DATE;
 * path=PATH; domain=DOMAIN_NAME; secure httponly" to a list of Cookies.
 * Here is a sample: IGDND=1, IGPC=ET=UB8TSNwtDmQ:AF=0; expires=Sun,
 * 17-Jan-2038 19:14:07 GMT; path=/ig; domain=.google.com, =,
 * PREF=ID=408909b1b304593d:TM=1156459854:LM=1156459854:S=V-vCAU6Sh-gobCfO;
 * expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com which
 * contains 3 cookies IGDND, IGPC, PREF and an empty cookie
 * @param host The default host//from   w  w  w  . j  a v  a  2 s.co  m
 * @param path The default path
 * @param cookieString The string coming from "Set-Cookie:"
 * @return A list of Cookies
 */
private ArrayList<BasicClientCookie> parseCookie(String host, String path, String cookieString) {
    ArrayList<BasicClientCookie> ret = new ArrayList<BasicClientCookie>();

    int index = 0;
    int length = cookieString.length();
    while (true) {
        BasicClientCookie cookie = null;

        // done
        if (index < 0 || index >= length) {
            break;
        }

        // skip white space
        if (cookieString.charAt(index) == WHITE_SPACE) {
            index++;
            continue;
        }

        /*
         * get NAME=VALUE; pair. detecting the end of a pair is tricky, it
         * can be the end of a string, like "foo=bluh", it can be semicolon
         * like "foo=bluh;path=/"; or it can be enclosed by \", like
         * "foo=\"bluh bluh\";path=/"
         *
         * Note: in the case of "foo=bluh, bar=bluh;path=/", we interpret
         * it as one cookie instead of two cookies.
         */
        int semicolonIndex = cookieString.indexOf(SEMICOLON, index);
        int equalIndex = cookieString.indexOf(EQUAL, index);

        // Cookies like "testcookie; path=/;" are valid and used
        // (lovefilm.se).
        // Look for 2 cases:
        // 1. "foo" or "foo;" where equalIndex is -1
        // 2. "foo; path=..." where the first semicolon is before an equal
        //    and a semicolon exists.
        if ((semicolonIndex != -1 && (semicolonIndex < equalIndex)) || equalIndex == -1) {
            // Fix up the index in case we have a string like "testcookie"
            if (semicolonIndex == -1) {
                semicolonIndex = length;
            }
            cookie = new BasicClientCookie(cookieString.substring(index, semicolonIndex), null);
            cookie.setDomain(host);
            cookie.setPath(path);
        } else {
            cookie = new BasicClientCookie(cookieString.substring(index, equalIndex), null);
            cookie.setDomain(host);
            cookie.setPath(path);
            // Make sure we do not throw an exception if the cookie is like
            // "foo="
            if ((equalIndex < length - 1) && (cookieString.charAt(equalIndex + 1) == QUOTATION)) {
                index = cookieString.indexOf(QUOTATION, equalIndex + 2);
                if (index == -1) {
                    // bad format, force return
                    break;
                }
            }
            // Get the semicolon index again in case it was contained within
            // the quotations.
            semicolonIndex = cookieString.indexOf(SEMICOLON, index);
            if (semicolonIndex == -1) {
                semicolonIndex = length;
            }
            if (semicolonIndex - equalIndex > MAX_COOKIE_LENGTH) {
                // cookie is too big, trim it
                cookie.setValue(cookieString.substring(equalIndex + 1, equalIndex + 1 + MAX_COOKIE_LENGTH));
            } else if (equalIndex + 1 == semicolonIndex || semicolonIndex < equalIndex) {
                // this is an unusual case like "foo=;" or "foo="
                cookie.setValue("");
            } else {
                cookie.setValue(cookieString.substring(equalIndex + 1, semicolonIndex));
            }
        }
        // get attributes
        index = semicolonIndex;
        while (true) {
            // done
            if (index < 0 || index >= length) {
                break;
            }

            // skip white space and semicolon
            if (cookieString.charAt(index) == WHITE_SPACE || cookieString.charAt(index) == SEMICOLON) {
                index++;
                continue;
            }

            // comma means next cookie
            if (cookieString.charAt(index) == COMMA) {
                index++;
                break;
            }

            // "secure" is a known attribute doesn't use "=";
            // while sites like live.com uses "secure="
            if (length - index >= SECURE_LENGTH
                    && cookieString.substring(index, index + SECURE_LENGTH).equalsIgnoreCase(SECURE)) {
                index += SECURE_LENGTH;
                cookie.setSecure(true);
                if (index == length)
                    break;
                if (cookieString.charAt(index) == EQUAL)
                    index++;
                continue;
            }

            // "httponly" is a known attribute doesn't use "=";
            // while sites like live.com uses "httponly="
            if (length - index >= HTTP_ONLY_LENGTH
                    && cookieString.substring(index, index + HTTP_ONLY_LENGTH).equalsIgnoreCase(HTTP_ONLY)) {
                index += HTTP_ONLY_LENGTH;
                if (index == length)
                    break;
                if (cookieString.charAt(index) == EQUAL)
                    index++;
                // FIXME: currently only parse the attribute
                continue;
            }
            equalIndex = cookieString.indexOf(EQUAL, index);
            if (equalIndex > 0) {
                String name = cookieString.substring(index, equalIndex).toLowerCase();
                if (name.equals(EXPIRES)) {
                    int comaIndex = cookieString.indexOf(COMMA, equalIndex);

                    // skip ',' in (Wdy, DD-Mon-YYYY HH:MM:SS GMT) or
                    // (Weekday, DD-Mon-YY HH:MM:SS GMT) if it applies.
                    // "Wednesday" is the longest Weekday which has length 9
                    if ((comaIndex != -1) && (comaIndex - equalIndex <= 10)) {
                        index = comaIndex + 1;
                    }
                }
                semicolonIndex = cookieString.indexOf(SEMICOLON, index);
                int commaIndex = cookieString.indexOf(COMMA, index);
                if (semicolonIndex == -1 && commaIndex == -1) {
                    index = length;
                } else if (semicolonIndex == -1) {
                    index = commaIndex;
                } else if (commaIndex == -1) {
                    index = semicolonIndex;
                } else {
                    index = Math.min(semicolonIndex, commaIndex);
                }
                String value = cookieString.substring(equalIndex + 1, index);

                // Strip quotes if they exist
                if (value.length() > 2 && value.charAt(0) == QUOTATION) {
                    int endQuote = value.indexOf(QUOTATION, 1);
                    if (endQuote > 0) {
                        value = value.substring(1, endQuote);
                    }
                }
                if (name.equals(EXPIRES)) {
                    try {
                        cookie.setExpiryDate(new Date(AndroidHttpClient.parseDate(value)));
                    } catch (IllegalArgumentException ex) {
                        Log.e(LOGTAG, "illegal format for expires: " + value);
                    }
                } else if (name.equals(MAX_AGE)) {
                    try {
                        cookie.setExpiryDate(
                                new Date(System.currentTimeMillis() + 1000 * Long.parseLong(value)));
                    } catch (NumberFormatException ex) {
                        Log.e(LOGTAG, "illegal format for max-age: " + value);
                    }
                } else if (name.equals(PATH)) {
                    // only allow non-empty path value
                    if (value.length() > 0) {
                        cookie.setPath(value);
                    }
                } else if (name.equals(DOMAIN)) {
                    int lastPeriod = value.lastIndexOf(PERIOD);
                    if (lastPeriod == 0) {
                        // disallow cookies set for TLDs like [.com]
                        cookie.setDomain(null);
                        continue;
                    }
                    try {
                        Integer.parseInt(value.substring(lastPeriod + 1));
                        // no wildcard for ip address match
                        if (!value.equals(host)) {
                            // no cross-site cookie
                            cookie.setDomain(null);
                        }
                        continue;
                    } catch (NumberFormatException ex) {
                        // ignore the exception, value is a host name
                    }
                    value = value.toLowerCase();
                    if (value.charAt(0) != PERIOD) {
                        // pre-pended dot to make it as a domain cookie
                        value = PERIOD + value;
                        lastPeriod++;
                    }
                    if (host.endsWith(value.substring(1))) {
                        int len = value.length();
                        int hostLen = host.length();
                        if (hostLen > (len - 1) && host.charAt(hostLen - len) != PERIOD) {
                            // make sure the bar.com doesn't match .ar.com
                            cookie.setDomain(null);
                            continue;
                        }
                        // disallow cookies set on ccTLDs like [.co.uk]
                        if ((len == lastPeriod + 3) && (len >= 6 && len <= 8)) {
                            String s = value.substring(1, lastPeriod);
                            if (Arrays.binarySearch(BAD_COUNTRY_2LDS, s) >= 0) {
                                cookie.setDomain(null);
                                continue;
                            }
                        }
                        cookie.setDomain(value);
                    } else {
                        // no cross-site or more specific sub-domain cookie
                        cookie.setDomain(null);
                    }
                }
            } else {
                // bad format, force return
                index = length;
            }
        }
        if (cookie != null && cookie.getDomain() != null) {
            ret.add(cookie);
        }
    }
    return ret;
}

From source file:com.krawler.esp.servlets.importProjectPlanCSV.java

public static String getActualDuration_importCSV(Date stdate, Date enddate, int[] NonWorkDays,
        String[] holidays, String duration) {
    Double noofdays = 0.0;//from   www.j av a  2  s  .c  o  m
    java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
    try {
        Calendar c1 = Calendar.getInstance();
        while (stdate.compareTo(enddate) < 0) {
            if (Arrays.binarySearch(NonWorkDays, stdate.getDay()) < 0
                    && Arrays.binarySearch(holidays, sdf1.format(stdate)) < 0) {
                noofdays++;
            }
            c1.setTime(stdate);
            c1.add(Calendar.DATE, 1);
            stdate = sdf1.parse(sdf1.format(c1.getTime()));
        }
        if (stdate.compareTo(enddate) == 0) {
            if (Arrays.binarySearch(NonWorkDays, stdate.getDay()) < 0
                    && Arrays.binarySearch(holidays, sdf1.format(stdate)) < 0) {
                if (duration.equals("")) {
                    noofdays++;
                } else {
                    int dur1 = Integer.parseInt(duration.substring(0, 1));
                    if (dur1 == 0) {
                        noofdays = 0.0;
                    } else {
                        noofdays++;
                    }
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
    }
    return String.valueOf(noofdays);
}

From source file:com.projity.pm.calendar.CalendarDefinition.java

public final WorkDay getWorkDay(long date) {
    WorkDay workDay = null;/*from  w  ww  .  j a v  a 2 s .  c  o  m*/
    int i = Arrays.binarySearch(getConcreteInstance().exceptions, new Date(date));
    if (i >= 0) {
        workDay = exceptions[i];
    } else {
        workDay = week.getWeekDay(getDayOfWeek(date));
    }
    return workDay;
}

From source file:aldenjava.opticalmapping.data.data.DataNode.java

public void removeSignal(long pos) {
    int index = Arrays.binarySearch(refp, pos);
    if (index < 0)
        System.err.println("Warning: Signal does not exist at " + Long.toString(pos));
    else {// w w  w  .j a  v  a  2  s.c  o  m
        long[] newrefp = new long[refp.length - 1];
        System.arraycopy(refp, 0, newrefp, 0, index);
        System.arraycopy(refp, index + 1, newrefp, index, refp.length - index - 1);
        refp = newrefp;
        // this.rebuildRefl();
    }
}

From source file:de.tap.easy_xkcd.fragments.comics.ComicFragment.java

@Override
public void onPrepareOptionsMenu(Menu menu) {
    //Update the favorites icon
    MenuItem fav = menu.findItem(R.id.action_favorite);
    if (databaseManager.checkFavorite(lastComicNumber)) {
        fav.setIcon(R.drawable.ic_action_favorite);
        fav.setTitle(R.string.action_favorite_remove);
    } else {/*  ww  w .j a  v  a2 s .co  m*/
        fav.setIcon(R.drawable.ic_favorite_outline);
        fav.setTitle(R.string.action_favorite);
    }
    //If the FAB is visible, hide the random comic menu item
    if (((MainActivity) getActivity()).getFab().getVisibility() == View.GONE) {
        menu.findItem(R.id.action_random).setVisible(true);
    } else {
        menu.findItem(R.id.action_random).setVisible(false);
    }
    menu.findItem(R.id.action_alt).setVisible(prefHelper.showAltTip());
    if (Arrays.binarySearch(getResources().getIntArray(R.array.interactive_comics), lastComicNumber) >= 0)
        menu.findItem(R.id.action_browser).setVisible(true);
}

From source file:eu.eidas.auth.engine.core.impl.SignSW.java

private Set<String> getAlgorithmList(String whiteList) {
    String listAlgo = "";
    Set<String> configuredAlgorithms = EIDASUtil.parseSemicolonSeparatedList(whiteList);
    Set<String> algorithms = new HashSet<String>();
    for (String algorithm : configuredAlgorithms) {
        if (Arrays.binarySearch(KNOWN_OPENSAML_ALGORITMS, algorithm) >= 0) {
            algorithms.add(algorithm);/*www.  j  a  v  a  2s.  c o  m*/
            listAlgo += algorithm + ";";
            continue;
        }
    }
    LOG.debug("Liste algo autorise=" + listAlgo);
    return algorithms;
}

From source file:org.alfresco.repo.search.impl.lucene.query.LeafScorer.java

private boolean check() throws IOException {
    if (matchAllLeaves) {
        this.counter = 0;
        int position;

        StructuredFieldPosition last = sfps[sfps.length - 1];

        if (last.linkSelf()) {
            if ((self != null) && sfps[1].linkSelf() && ((position = Arrays.binarySearch(self, max)) >= 0)) {
                if (!selfDocs.get(max)) {
                    selfDocs.set(max);//w  ww.  ja  va  2  s .co m
                    while (position > -1 && self[position] == max) {
                        position--;
                    }
                    for (int i = position + 1, l = self.length; ((i < l) && (self[i] == max)); i++) {
                        this.counter++;
                    }
                }
            }
        }
        if (!selfDocs.get(max) && last.linkParent()) {
            if ((parents != null) && ((position = Arrays.binarySearch(parents, max)) >= 0)) {
                while (position > -1 && parents[position] == max) {
                    position--;
                }
                for (int i = position + 1, l = parents.length; ((i < l) && (parents[i] == max)); i++) {
                    this.counter++;
                }
            }

            if ((cats != null) && ((position = Arrays.binarySearch(cats, max)) >= 0)) {
                while (position > -1 && cats[position] == max) {
                    position--;
                }
                for (int i = position + 1, l = cats.length; ((i < l) && (cats[i] == max)); i++) {
                    this.counter++;
                }
            }
        }
        return counter > 0;
    }

    // String name = reader.document(doc()).getField("QNAME").stringValue();
    // We have duplicate entries
    // The match must be in a known term range
    int count = root.freq();
    int start = 0;
    int end = -1;
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            // First starts at zero
            start = 0;
            end = root.nextPosition();
        } else {
            start = end + 1;
            end = root.nextPosition();
        }

        check(start, end, i);

    }
    // We had checks to do and they all failed.
    return this.counter > 0;
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * This method encodes URI string into a percent encoded string. If a URI string
 * or part of it is already percent encoded, that part of URI string is skipped.
 * This method is implemented as per specifications in RFC 1738 (section 2).
 *
 * I also had a look at//from   www.  ja v  a2  s .  c o  m
 * {@link java.net.URLEncoder} does not meet out requirements
 * {@link java.net.URI} also does not meet our requirements
 *
 *
 *  TODO There is one issue in this implementation, RFC 1738 section 2.2,
 *  states that a reserved character in a URI must be encoded if it is used
 *  for a purpose other than its reserved purpose. (For example :- If a
 *  reserved character is used in the name of file in a URI, then that reserved
 *  character must be encoded). As of now in the current implementation we are
 *  not encoding any reserved characters. For us it is difficult to determine
 *  whether a reserved character is used for its reserved purpose of some other
 *  purpose.
 *
 *  One possible (but costly) solution to above limitation could be,
 *  to start encoding all the possible combinations of reserved characters
 *  in the URI one at a time and see if URI starts working.
 *
 * @param input URI string which needs to be percent encoded
 * @return percent encoded string
 * {@linkplain http://java.sun.com/javaee/6/docs/api/javax/ws/rs/core/UriBuilder.html},
 * probably URIBuilder does the same work we want to do below. But no of
 * dependencies(maven) on URI are huge. So it does not look worth the effort
 * to use URIBuilder
 * {@linkplain http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars}
 * {@linkplain http://www.ietf.org/rfc/rfc1738.txt} (section 2.2)
 */
public static String percentEncoding(String input) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c == '%') {
            boolean inputHasAtleastTwoMoreChars = i + 2 < input.length();
            if (inputHasAtleastTwoMoreChars) {
                String twoCharsAfterPercent = input.substring(i + 1, i + 3);
                if (isHexAfterPercent(twoCharsAfterPercent)) {
                    i = i + 2;
                    sb.append("%").append(twoCharsAfterPercent);
                    continue;
                }
            }
        }
        boolean isLetterOrDigit = Character.isLetterOrDigit(c);
        boolean isSafe = Arrays.binarySearch(safe, c) >= 0;
        boolean isReserved = Arrays.binarySearch(reserved, c) >= 0;
        if (isLetterOrDigit || isSafe || isReserved) {
            sb.append(c);
        } else if (c <= 0x007F) { // convert all other ASCII to percent encoding
            sb.append("%").append(Integer.toHexString(c));
        } else if (c <= 0x07FF) { // non-ASCII <= 0x7FF (UTF 2 byte)
            sb.append("%").append(Integer.toHexString(0xc0 | (c >> 6)));
            sb.append("%").append(Integer.toHexString(0x80 | (c & 0x3F)));
        } else { // 0x7FF < ch <= 0xFFFF (UTF 3 bytes)
            sb.append("%").append(Integer.toHexString(0xe0 | (c >> 12)));
            sb.append("%").append(Integer.toHexString(0x80 | ((c >> 6) & 0x3F)));
            sb.append("%").append(Integer.toHexString(0x80 | (c & 0x3F)));
        }
    }
    return sb.toString();
}