Example usage for java.lang Character isDigit

List of usage examples for java.lang Character isDigit

Introduction

In this page you can find the example usage for java.lang Character isDigit.

Prototype

public static boolean isDigit(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is a digit.

Usage

From source file:uk.ac.ebi.ep.controller.SearchController.java

private boolean startsWithDigit(String data) {
    return Character.isDigit(data.charAt(0));
}

From source file:com.dragoniade.deviantart.deviation.SearchStream.java

public List<Deviation> search(ProgressDialog progress, Collection collection) {
    if (user == null) {
        throw new IllegalStateException("You must set the user before searching.");
    }/*w w  w.j  a va 2 s.c  o m*/
    if (search == null) {
        throw new IllegalStateException("You must set the search type before searching.");
    }
    String searchQuery = search.getSearch().replace("%username%", user);
    String queryString = "http://www.deviantart.com/global/difi.php?c=Stream;thumbs;" + searchQuery + ","
            + offset + "," + OFFSET + "&t=xml";
    GetMethod method = new GetMethod(queryString);
    List<Deviation> results = new ArrayList<Deviation>(OFFSET);
    try {
        int sc = -1;
        do {
            sc = client.executeMethod(method);
            if (sc != 200) {
                int res = DialogHelper.showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    return null;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        } while (sc != 200);

        XmlToolkit toolkit = XmlToolkit.getInstance();

        StringBuilder stringBuilder = new StringBuilder();
        InputStream inputStream = method.getResponseBodyAsStream();
        int b;
        boolean isOpening = false;
        while ((b = inputStream.read()) > -1) {
            if (b > 127) {
                isOpening = false;
                continue;
            }
            char c = (char) b;
            if (isOpening && Character.isDigit(c)) {
                stringBuilder.append('_');
            }
            if (isOpening && c == '/') {
                stringBuilder.append(c);
                continue;
            }
            isOpening = (c == '<');
            stringBuilder.append(c);
        }

        Element responses = toolkit.parseDocument(stringBuilder.toString());
        method.releaseConnection();

        total = toolkit.getNodeAsInt(responses, "response/calls/response/content/total");
        List<?> deviations = toolkit.getMultipleNodes(responses, "response/calls/response/content/deviations");
        if (total == 0) {
            return results;
        }
        for (Object obj : deviations) {
            Element deviation = (Element) obj;

            Deviation da = new Deviation();
            da.setId(toolkit.getNodeAsLong(deviation, "id"));
            da.setArtist(toolkit.getNodeAsString(deviation, "artist"));
            da.setCategory(toolkit.getNodeAsString(deviation, "category"));
            da.setTitle(toolkit.getNodeAsString(deviation, "title"));
            da.setUrl(toolkit.getNodeAsString(deviation, "url"));
            da.setTimestamp(new Date(toolkit.getNodeAsLong(deviation, "ts") * 1000));
            da.setMature("1".equals(toolkit.getNodeAsString(deviation, "is_mature")));
            da.setCollection(collection);

            String filenameStr = toolkit.getNodeAsString(deviation, "filename");
            String imageUrl = toolkit.getNodeAsString(deviation, "image/url");

            String primaryFilename = Deviation.extractFilename(filenameStr);
            da.setDocumentDownloadUrl(DOWNLOAD_URL + da.getId() + "/");
            da.setDocumentFilename(primaryFilename);

            if (imageUrl != null) {
                String secondaryFilename = Deviation.extractFilename(imageUrl);
                da.setImageDownloadUrl(imageUrl);
                da.setImageFilename(secondaryFilename);
                da.setResolution(toolkit.getNodeAsString(deviation, "image/width") + "x"
                        + toolkit.getNodeAsString(deviation, "image/height"));
            }

            results.add(da);
        }
        offset = offset + deviations.size();
        return results;
    } catch (HttpException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    } catch (IOException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

From source file:org.shept.util.FileUtils.java

/**
 * List the file directory as specified by the name filter and path directory
 * The maps keys contain the parsed date from the filename.
 * The filename can be something like Backup_db_2008_12_01_1350.xyz
 * The first part is may begin with any character, the first number found
 * is treated as year followed by month followed by day.
 * All characters are separated by "_" (underscores).
 * The last 4-letter number represents hours & minutes
 * /*from w ww  .  java 2s  . c o  m*/
 * @param path
 * @param filePattern
 * @return
 */
public static SortedMap<Calendar, File> fileMapByFilenameDate(String path, String filePattern) {
    FileUtils fu = new FileUtils(); // needed for inner class
    SortedMap<Calendar, File> newFileMap = new TreeMap<Calendar, File>();
    File fileDir = new File(path);
    if (null != path && fileDir.isDirectory()) {
        FileFilter filter = fu.new Filter(path, filePattern);
        File[] files = fileDir.listFiles(filter);
        for (int i = 0; i < files.length; i++) {
            Calendar cal = Calendar.getInstance();
            String[] split = files[i].getName().split("_");
            int j = 0;
            // looking for the first digit
            while (!Character.isDigit(split[j].charAt(0))) {
                j++;
            }
            try {
                cal.set(Calendar.YEAR, Integer.valueOf(split[j++]));
                cal.set(Calendar.MONTH, Integer.valueOf(split[j++]) - 1);
                cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(split[j++]));
                cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(split[j].substring(0, 2)));
                cal.set(Calendar.MINUTE, Integer.valueOf(split[j].substring(2, 4)));
                newFileMap.put(cal, files[i]);
            } catch (Throwable t) {
                // if format doesn't fit ignore the file
            }
        }
    }
    return newFileMap;
}

From source file:com.docdoku.core.util.Tools.java

public static boolean validateMask(String mask, String str) {

    // '*' goes for any alpha-numeric char, '#' for numbers only
    if (mask == null || mask.length() == 0) {
        return true;
    }/*from   w ww  .  j  av a2 s . c om*/

    // Not same length
    if (mask.length() != str.length()) {
        return false;
    }

    Pattern alphaNum = Pattern.compile("[a-zA-Z0-9]");

    for (int i = 0; i < mask.length(); i++) {

        if ('*' == mask.charAt(i) && !alphaNum.matcher(str.charAt(i) + "").find()) {
            return false;
        }
        if ('#' == mask.charAt(i) && !Character.isDigit(str.charAt(i))) {
            return false;
        }
    }

    return true;

}

From source file:net.riezebos.thoth.renderers.util.CustomHtmlSerializer.java

protected void writeBookmarks(HeaderNode node) {
    // Headers might be tokenized; so we need to append them together.
    String combinedName = "";
    for (Node child : node.getChildren()) {
        if (child instanceof TextNode) {
            TextNode textNode = (TextNode) child;
            String text = textNode.getText();
            if (text != null && text.trim().length() > 0) {
                combinedName += text.trim();
            }//from w  ww  .j  a  v  a  2 s. c o m
        }
    }
    if (StringUtils.isNoneBlank(combinedName)) {
        String ref = ThothUtil.encodeBookmark(combinedName, false);
        writeBookmark(ref);

        // Also add a bookmark that excludes any (potentially) generated numbers as a prefix of the title
        int idx = 0;
        for (int i = 0; i < ref.length(); i++, idx++) {
            if (!Character.isDigit(ref.charAt(i)) && ref.charAt(i) != '.')
                break;
        }
        if (idx != 0) {
            String alternate = ref.substring(idx).trim();
            writeBookmark(alternate);
        }
    }
}

From source file:edu.umn.cs.spatialHadoop.nasa.HTTPFileSystem.java

private static long parseSize(String size) {
    char lastChar = size.charAt(size.length() - 1);
    if (!Character.isDigit(lastChar)) {
        size = size.substring(0, size.length() - 1);
    }/*w  ww . ja  v  a 2 s  . c  o  m*/
    double dsize = Double.parseDouble(size);
    switch (lastChar) {
    case 'G':
    case 'g':
        dsize *= 1024;
    case 'M':
    case 'm':
        dsize *= 1024;
    case 'K':
    case 'k':
        dsize *= 1024;
    }
    return (long) dsize;
}

From source file:com.textuality.keybase.lib.prover.Twitter.java

private boolean endsWithDigits(String path) {
    int i = path.length() - 1;
    while (i >= 0 && Character.isDigit(path.charAt(i))) {
        i--;//from  ww  w.ja  v a2s.c  om
    }
    return ('/' == path.charAt(i));
}

From source file:Main.java

/**
 * <p>Turns a string value into a java.lang.Number.</p>
 *
 * <p>First, the value is examined for a type qualifier on the end
 * (<code>'f','F','d','D','l','L'</code>).  If it is found, it starts 
 * trying to create successively larger types from the type specified
 * until one is found that can hold the value.</p>
 *
 * <p>If a type specifier is not found, it will check for a decimal point
 * and then try successively larger types from <code>Integer</code> to
 * <code>BigInteger</code> and from <code>Float</code> to
 * <code>BigDecimal</code>.</p>
 *
 * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it
 * will be interpreted as a hexadecimal integer.  Values with leading
 * <code>0</code>'s will not be interpreted as octal.</p>
 *
 * @param val String containing a number
 * @return Number created from the string
 * @throws NumberFormatException if the value cannot be converted
 */// www.  jav a 2s  .c om
public static Number createNumber(String val) throws NumberFormatException {
    if (val == null) {
        return null;
    }
    if (val.length() == 0) {
        throw new NumberFormatException("\"\" is not a valid number.");
    }
    if (val.startsWith("--")) {
        // this is protection for poorness in java.lang.BigDecimal.
        // it accepts this as a legal value, but it does not appear 
        // to be in specification of class. OS X Java parses it to 
        // a wrong value.
        return null;
    }
    if (val.startsWith("0x") || val.startsWith("-0x")) {
        return createInteger(val);
    }
    char lastChar = val.charAt(val.length() - 1);
    String mant;
    String dec;
    String exp;
    int decPos = val.indexOf('.');
    int expPos = val.indexOf('e') + val.indexOf('E') + 1;

    if (decPos > -1) {

        if (expPos > -1) {
            if (expPos < decPos) {
                throw new NumberFormatException(val + " is not a valid number.");
            }
            dec = val.substring(decPos + 1, expPos);
        } else {
            dec = val.substring(decPos + 1);
        }
        mant = val.substring(0, decPos);
    } else {
        if (expPos > -1) {
            mant = val.substring(0, expPos);
        } else {
            mant = val;
        }
        dec = null;
    }
    if (!Character.isDigit(lastChar)) {
        if (expPos > -1 && expPos < val.length() - 1) {
            exp = val.substring(expPos + 1, val.length() - 1);
        } else {
            exp = null;
        }
        //Requesting a specific type..
        String numeric = val.substring(0, val.length() - 1);
        boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
        switch (lastChar) {
        case 'l':
        case 'L':
            if (dec == null && exp == null
                    && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
                try {
                    return createLong(numeric);
                } catch (NumberFormatException nfe) {
                    //Too big for a long
                }
                return createBigInteger(numeric);

            }
            throw new NumberFormatException(val + " is not a valid number.");
        case 'f':
        case 'F':
            try {
                Float f = createFloat(numeric);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    //If it's too big for a float or the float value = 0 and the string
                    //has non-zeros in it, then float does not have the precision we want
                    return f;
                }

            } catch (NumberFormatException e) {
                // ignore the bad number
            }
            //Fall through
        case 'd':
        case 'D':
            try {
                Double d = createDouble(numeric);
                if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                return createBigDecimal(numeric);
            } catch (NumberFormatException e) {
                // empty catch
            }
            //Fall through
        default:
            throw new NumberFormatException(val + " is not a valid number.");

        }
    } else {
        //User doesn't have a preference on the return type, so let's start
        //small and go from there...
        if (expPos > -1 && expPos < val.length() - 1) {
            exp = val.substring(expPos + 1, val.length());
        } else {
            exp = null;
        }
        if (dec == null && exp == null) {
            //Must be an int,long,bigint
            try {
                return createInteger(val);
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                return createLong(val);
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            return createBigInteger(val);

        } else {
            //Must be a float,double,BigDec
            boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
            try {
                Float f = createFloat(val);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    return f;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                Double d = createDouble(val);
                if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }

            return createBigDecimal(val);

        }

    }
}

From source file:com.ning.maven.plugins.dependencyversionscheck.version.Version.java

public Version(final String rawVersion, final String selectedVersion) {
    if (StringUtils.isBlank(rawVersion) || StringUtils.isBlank(selectedVersion)) {
        throw new NullPointerException("Version cannot be null");
    }/*from   w ww. j  a va  2s.com*/

    this.selectedVersion = selectedVersion;
    this.rawVersion = rawVersion;

    rawElements = StringUtils.splitPreserveAllTokens(selectedVersion, "-._");
    versionElements = new VersionElement[rawElements.length];

    // Position of the next splitter to look at.
    int charPos = 0;

    // Position to store the result in.
    int resultPos = 0;

    for (int i = 0; i < rawElements.length; i++) {
        final String rawElement = rawElements[i];

        long divider = 0L;
        final char dividerChar;

        charPos += rawElement.length();
        if (charPos < selectedVersion.length()) {
            dividerChar = selectedVersion.charAt(charPos);
            charPos++;

            if (dividerChar == '.') {
                divider |= DOT_DIVIDER;
            } else if (dividerChar == '-') {
                divider |= MINUS_DIVIDER;
            } else if (dividerChar == '_') {
                divider |= UNDERSCORE_DIVIDER;
            } else {
                divider |= OTHER_DIVIDER;
            }

        } else {
            dividerChar = 0;
            divider |= END_OF_VERSION;
        }

        final String element = StringUtils.trimToEmpty(rawElement);

        if (!StringUtils.isBlank(element)) {
            long flags = ALL_NUMBERS | ALL_LETTERS | ALL_OTHER;
            final char firstChar = element.charAt(0);
            final char lastChar = element.charAt(element.length() - 1);

            if (Character.isDigit(firstChar)) {
                flags |= STARTS_WITH_NUMBERS;
            } else if (Character.isLetter(firstChar)) {
                flags |= STARTS_WITH_LETTERS;
            } else {
                flags |= STARTS_WITH_OTHER;
            }

            if (Character.isDigit(lastChar)) {
                flags |= ENDS_WITH_NUMBERS;
            } else if (Character.isLetter(lastChar)) {
                flags |= ENDS_WITH_LETTERS;
            } else {
                flags |= ENDS_WITH_OTHER;
            }

            for (int j = 0; j < element.length(); j++) {

                if (Character.isDigit(element.charAt(j))) {
                    flags &= ~(ALL_LETTERS | ALL_OTHER);
                    flags |= NUMBERS;
                } else if (Character.isLetter(element.charAt(j))) {
                    flags &= ~(ALL_NUMBERS | ALL_OTHER);
                    flags |= LETTERS;
                } else {
                    flags &= ~(ALL_LETTERS | ALL_NUMBERS);
                    flags |= OTHER;
                }
            }

            versionElements[resultPos++] = new VersionElement(element, flags, divider, dividerChar);
        }
    }

    this.elementCount = resultPos;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlAnchor.java

/**
 * Same as {@link #doClickStateUpdate()}, except that it accepts an href suffix, needed when a click is
 * performed on an image map to pass information on the click position.
 *
 * @param hrefSuffix the suffix to add to the anchor's href attribute (for instance coordinates from an image map)
 * @throws IOException if an IO error occurs
 *//*w ww.  j  a  v  a2  s .c om*/
protected void doClickStateUpdate(final String hrefSuffix) throws IOException {
    final String href = (getHrefAttribute() + hrefSuffix).trim();
    if (LOG.isDebugEnabled()) {
        final String w = getPage().getEnclosingWindow().getName();
        LOG.debug("do click action in window '" + w + "', using href '" + href + "'");
    }
    if (ATTRIBUTE_NOT_DEFINED == getHrefAttribute()) {
        return;
    }
    HtmlPage htmlPage = (HtmlPage) getPage();
    if (StringUtils.startsWithIgnoreCase(href, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        final StringBuilder builder = new StringBuilder(href.length());
        builder.append(JavaScriptURLConnection.JAVASCRIPT_PREFIX);
        for (int i = JavaScriptURLConnection.JAVASCRIPT_PREFIX.length(); i < href.length(); i++) {
            final char ch = href.charAt(i);
            if (ch == '%' && i + 2 < href.length()) {
                final char ch1 = Character.toUpperCase(href.charAt(i + 1));
                final char ch2 = Character.toUpperCase(href.charAt(i + 2));
                if ((Character.isDigit(ch1) || ch1 >= 'A' && ch1 <= 'F')
                        && (Character.isDigit(ch2) || ch2 >= 'A' && ch2 <= 'F')) {
                    builder.append((char) Integer.parseInt(href.substring(i + 1, i + 3), 16));
                    i += 2;
                    continue;
                }
            }
            builder.append(ch);
        }

        if (hasFeature(ANCHOR_IGNORE_TARGET_FOR_JS_HREF)) {
            htmlPage.executeJavaScriptIfPossible(builder.toString(), "javascript url", getStartLineNumber());
        } else {
            final WebWindow win = htmlPage.getWebClient().openTargetWindow(htmlPage.getEnclosingWindow(),
                    htmlPage.getResolvedTarget(getTargetAttribute()), "_self");
            final Page page = win.getEnclosedPage();
            if (page != null && page.isHtmlPage()) {
                htmlPage = (HtmlPage) page;
                htmlPage.executeJavaScriptIfPossible(builder.toString(), "javascript url",
                        getStartLineNumber());
            }
        }
        return;
    }

    final URL url = getTargetUrl(href, htmlPage);

    final BrowserVersion browser = htmlPage.getWebClient().getBrowserVersion();
    final WebRequest webRequest = new WebRequest(url, browser.getHtmlAcceptHeader());
    webRequest.setCharset(htmlPage.getPageEncoding());
    webRequest.setAdditionalHeader("Referer", htmlPage.getUrl().toExternalForm());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Getting page for " + url.toExternalForm() + ", derived from href '" + href
                + "', using the originating URL " + htmlPage.getUrl());
    }
    htmlPage.getWebClient().download(htmlPage.getEnclosingWindow(),
            htmlPage.getResolvedTarget(getTargetAttribute()), webRequest, true, false, "Link click");
}