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:org.nira.wso2.nexus.ComponentVersion.java

/**
 * Loads the List of all the Dependencies in the DependencyManagement from  the root
 * pom.xml//  w w  w  .  j  av  a  2  s  .  co  m
 *
 * @param pomFilePath : The path to the root pom.xml
 * @throws ComponentException
 */
private static void getDependencyManagement(String pomFilePath) throws ComponentException {
    String nodeName, nodeValue;
    DependencyComponent dependencyComponent;
    NodeList dependenciesList = Utils.getNodeListFromXPath(pomFilePath, Constants.DEPENDENCY_MANAGEMENT_XPATH);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        for (int i = 0; i < dependenciesList.getLength(); ++i) {

            Node dependency = dependenciesList.item(i);
            if (dependency != null && dependency.getNodeType() == Node.ELEMENT_NODE) {
                NodeList nodes = (NodeList) xpath.evaluate(Constants.SELECT_ALL, dependency,
                        XPathConstants.NODESET);
                dependencyComponent = new DependencyComponent();
                for (int j = 0; j < nodes.getLength(); ++j) {
                    nodeName = nodes.item(j).getNodeName();
                    nodeValue = nodes.item(j).getTextContent();
                    if (nodeValue == null) {
                        throw new ComponentException("Dependency value is NULL for " + nodeName + "!");
                    }
                    switch (nodeName) {
                    case Constants.GROUPID:
                        dependencyComponent.setGroupId(nodeValue);
                        break;
                    case Constants.ARTIFACTID:
                        dependencyComponent.setArtifactId(nodeValue);
                        break;
                    case Constants.VERSION:
                        if (Constants.PROJECT_VERSION.equalsIgnoreCase(nodeValue)) {
                            break;
                        }
                        //ToDo: Check for values like the one below:
                        //<version.tomcat>7.0.59</version.tomcat>
                        //<orbit.version.tomcat>${version.tomcat}.wso2v3</orbit.version.tomcat>
                        while (!Character.isDigit(nodeValue.charAt(0))) {
                            nodeValue = nodeValue.substring(2, nodeValue.length() - 1);
                            nodeValue = dependencyComponentVersions.get(nodeValue);
                            if (nodeValue == null) {
                                throw new ComponentException("Dependency Version cannot be NULL!");
                            }
                        }
                        dependencyComponent.setVersion(nodeValue);
                        break;
                    }
                }
                if (dependencyComponent.getGroupId() != null && dependencyComponent.getArtifactId() != null
                        && dependencyComponent.getVersion() != null) {
                    getLatestComponentVersion(dependencyComponent);
                    dependencyComponentList.add(dependencyComponent);
                }
            }
        }
    } catch (XPathExpressionException e) {
        throw new ComponentException("XPath Exception when retrieving Dependency Components!", e);
    }
    Collections.sort(dependencyComponentList, DependencyComponent.GroupIdArifactIdComparator);
}

From source file:br.com.bropenmaps.util.Util.java

/**
 * Desfaz as alteraes feitas quando um termo precisa ser modificado ao ser utilizado como parmetro em requisies HTTP (decoder para o {@link URLEncoder})
 * @param s - termo a ser modificado //  w  w w . j  a va 2 s  .c o m
 * @return Retorna o termo com as modificaes realizadas
 */
public static String decoder(String s) {
    if (s == null) {
        return s;
    }

    StringBuffer sbuf = new StringBuffer();
    int l = s.length();
    int ch = -1;
    int b, sumb = 0;
    for (int i = 0, more = -1; i < l; i++) {
        /* Get next byte b from URL segment s */
        switch (ch = s.charAt(i)) {
        case '%':
            ch = s.charAt(++i);
            int hb = (Character.isDigit((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a')
                    & 0xF;
            ch = s.charAt(++i);
            int lb = (Character.isDigit((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a')
                    & 0xF;
            b = (hb << 4) | lb;
            break;
        default:
            b = ch;
        }
        /* Decode byte b as UTF-8, sumb collects incomplete chars */
        if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte)
            sumb = (sumb << 6) | (b & 0x3f); // Add 6 bits to sumb
            if (--more == 0)
                sbuf.append((char) sumb); // Aarg0dd char to sbuf
        } else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits)
            sbuf.append((char) b); // Store in sbuf
        } else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits)
            sumb = b & 0x1f;
            more = 1; // Expect 1 more byte
        } else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits)
            sumb = b & 0x0f;
            more = 2; // Expect 2 more bytes
        } else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits)
            sumb = b & 0x07;
            more = 3; // Expect 3 more bytes
        } else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits)
            sumb = b & 0x03;
            more = 4; // Expect 4 more bytes
        } else /*if ((b & 0xfe) == 0xfc)*/ { // 1111110x (yields 1 bit)
            sumb = b & 0x01;
            more = 5; // Expect 5 more bytes
        }
        /* We don't test if the UTF-8 encoding is well-formed */
    }
    return sbuf.toString();
}

From source file:com.moviejukebox.tools.FileTools.java

public static void initUnsafeChars() {
    if (!UNSAFE_CHARS.isEmpty()) {
        return;/* ww w  . j  a  v  a  2s .  com*/
    }

    // What to do if the user specifies a blank encodeEscapeChar? I guess disable encoding.
    String encodeEscapeCharString = PropertiesUtil.getProperty("mjb.charset.filenameEncodingEscapeChar", "$");
    if (encodeEscapeCharString.length() > 0) {
        // What to do if the user specifies a >1 character long string? I guess just use the first char.
        final Character ENCODE_ESCAPE_CHAR = encodeEscapeCharString.charAt(0);

        String repChars = PropertiesUtil.getProperty("mjb.charset.unsafeFilenameChars", "<>:\"/\\|?*");
        for (String repChar : repChars.split("")) {
            if (repChar.length() > 0) {
                char ch = repChar.charAt(0);
                // Don't encode characters that are hex digits
                // Also, don't encode the escape char -- it is safe by definition!
                if (!Character.isDigit(ch) && -1 == "AaBbCcDdEeFf".indexOf(ch)
                        && !ENCODE_ESCAPE_CHAR.equals(ch)) {
                    String hex = Integer.toHexString(ch).toUpperCase();
                    UNSAFE_CHARS.add(new ReplaceEntry(repChar, ENCODE_ESCAPE_CHAR + hex));
                }
            }
        }
    }

    // Parse transliteration map: (source_character [-] transliteration_sequence [,])+
    StringTokenizer st = new StringTokenizer(PropertiesUtil.getProperty("mjb.charset.filename.translate", ""),
            ",");
    while (st.hasMoreElements()) {
        final String token = st.nextToken();
        String beforeStr = substringBefore(token, "-");
        final String character = beforeStr.length() == 1 && ("\t".equals(beforeStr) || " ".equals(beforeStr))
                ? beforeStr
                : trimToNull(beforeStr);
        if (character == null) {
            // TODO Error message?
            continue;
        }
        String afterStr = substringAfter(token, "-");
        final String translation = afterStr.length() == 1 && ("\t".equals(afterStr) || " ".equals(afterStr))
                ? afterStr
                : trimToNull(afterStr);
        if (translation == null) {
            // TODO Error message?
            // TODO Allow empty transliteration?
            continue;
        }
        UNSAFE_CHARS.add(new ReplaceEntry(character.toUpperCase(), translation.toUpperCase()));
        UNSAFE_CHARS.add(new ReplaceEntry(character.toLowerCase(), translation.toLowerCase()));
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.SequenceNumberValidator.java

/**
 * Checks if the string is composed of only digits.
 * /*w  w  w.ja  v a 2  s . c o m*/
 * @param string
 * @return true for a string of all digits, false otherwise (including false for null and empty string)
 */
static boolean isDigits(String string) {
    if (string == null || string.length() == 0) {
        return false;
    }
    for (int i = 0; i < string.length(); i++) {
        if (!Character.isDigit(string.charAt(i))) {
            return false;
        }
    }
    return true;
}

From source file:com.yahoo.glimmer.web.QueryController.java

@RequestMapping(value = { "/query", "/v1/search" }, method = RequestMethod.GET)
public Map<String, ?> query(@ModelAttribute(INDEX_KEY) RDFIndex index, @Valid QueryCommand command,
        HttpServletRequest httpServletRequest)
        throws QueryParserException, QueryBuilderVisitorException, IOException {
    if (index == null) {
        throw new HttpMessageConversionException("No index given.");
    }/*  w w  w.j av  a2  s.  c  om*/

    String query = command.getQuery();
    if (query == null || query.isEmpty()) {
        throw new HttpMessageConversionException("No query given.");
    }

    QueryResult result;
    if (queryFilter != null && queryFilter.filter(query)) {
        LOGGER.info("Blocking query:" + query + " from address:" + httpServletRequest.getRemoteAddr());
        throw new HttpMessageConversionException("Bad query given.");
    }

    query = decodeEntities(command.getQuery()).trim();
    query = encodeResources(index, query);

    Query parsedQuery;
    switch (command.getType()) {
    case MG4J:
        parsedQuery = new SimpleParser().parse(query);
        result = querier.doQuery(index, parsedQuery, command.getPageStart(), command.getPageSize(),
                command.isDeref(), defaultObjectLengthLimit);
        break;
    case YAHOO:
        if (query.startsWith(DOC_PSEUDO_FIELD)) {
            String idOrSubject = query.substring(DOC_PSEUDO_FIELD.length());
            Long id;
            if (Character.isDigit(idOrSubject.charAt(0))) {
                try {
                    id = Long.parseLong(idOrSubject);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(
                            "Query " + query + " failed to parse as a numeric subject ID(int)");
                }
            } else {
                id = index.getSubjectId(idOrSubject);
                if (id == null) {
                    throw new IllegalArgumentException("subject " + idOrSubject + " is not in collection.");
                }
            }
            result = querier.doQueryForDocId(index, id, command.isDeref(), null);
        } else {
            try {
                parsedQuery = index.getParser().parse(query);
            } catch (QueryParserException e) {
                throw new IllegalArgumentException("Query failed to parse:" + query, e);
            }
            result = querier.doQuery(index, parsedQuery, command.getPageStart(), command.getPageSize(),
                    command.isDeref(), defaultObjectLengthLimit);
        }
        break;
    default:
        throw new IllegalArgumentException("No query type given.");
    }

    return Collections.singletonMap(OBJECT_KEY, result);
}

From source file:com.meyling.telnet.shell.ShellIo.java

/**
 * After getting an ESC this method handles the ESC sequence.
 * If the ESC sequence leads to several ints to read (for example
 * multiple backspace characters) these characters are put into the
 * buffer with {@link #putBuffer(int)} of {@link #putBuffer(int, int)}.
 *
 * This method extends the functionality of
 * {@link net.wimpi.telnetd.io.terminal.BasicTerminal#translateEscapeSequence(int[])}.
 *
 * @return    Read int.//from  w  w w.j  a v a 2  s .c  om
 * @throws     IOException    Read error.
 */
private int handleEscapeSequence() throws IOException {
    int c;
    if ((c = bufferedRead()) == Terminal.LSB) {
        int number = 0;
        do {
            c = bufferedRead();
            if (c >= 0 && c < 256 && Character.isDigit((char) c)) {
                number = number * 10 + c - '0';
            } else {
                break;
            }
        } while (true);
        if (number == 0) {
            number = 1;
        }
        if (trace.isDebugEnabled()) {
            trace.debug("number=" + number);
        }
        switch (c) {
        case Terminal.A:
            number--;
            putBuffer(TerminalIO.UP, number);
            return TerminalIO.UP;
        case Terminal.B:
            number--;
            putBuffer(TerminalIO.DOWN, number);
            return TerminalIO.DOWN;
        case Terminal.C:
            number--;
            putBuffer(TerminalIO.RIGHT, number);
            return TerminalIO.RIGHT;
        case Terminal.D:
            number--;
            putBuffer(TerminalIO.LEFT, number);
            return TerminalIO.LEFT;
        case 80: // new in comparison to the original
            // P (DELETE). The byte code of P, as used in escape sequences
            // for delete character. 
            number--;
            putBuffer(TerminalIO.DELETE, number);
            return TerminalIO.DELETE;
        case 126: // ~ new in comparison to the original
            if (number == 3) {
                putBuffer(TerminalIO.DELETE);
            }
        default:
            break;
        }
    }
    trace.error("Unrecognized ESC sequence with char " + c + " " + (char) c);
    return TerminalIO.UNRECOGNIZED;
}

From source file:BrowserDetect.java

/**
 * We've found the start of a sequence of numbers, what is it as an int?
 *///from   www.  j  ava2s  .c  o  m
private static int parseNumberAtStart(String numberString) {
    if (numberString == null || numberString.length() == 0) {
        return -1;
    }

    int endOfNumbers = 0;
    while (Character.isDigit(numberString.charAt(endOfNumbers))) {
        endOfNumbers++;
    }

    try {
        return Integer.parseInt(numberString.substring(0, endOfNumbers));
    } catch (NumberFormatException ex) {
        return -1;
    }
}

From source file:fi.uta.infim.usaproxylogparser.UsaProxyHTTPTrafficLogParser.java

/**
 * Converts a UsaProxy DOM path to an XPath expression
 * @param usaProxyPath usaproxy dom path
 * @return XPath expression as string/*from w ww . j  a va2  s  . c  om*/
 * @throws IOException
 * @throws XPathExpressionException
 */
static String usaProxyDOMPathToXPath(String usaProxyPath) throws IOException, XPathExpressionException {
    String path = "";
    StringReader reader = new StringReader(usaProxyPath);
    while (reader.ready()) {
        int depth = 0; // Index of the child element
        int currentChar;
        String prefix = "0";
        while (Character.isDigit(currentChar = reader.read())) {
            prefix += String.valueOf((char) currentChar);
        }
        if (currentChar == -1)
            break;
        depth += Integer.parseInt(prefix) * 26;
        depth += currentChar - ((int) 'a') + 1; // assuming ascii charset
        path += "/*[" + String.valueOf(depth) + "]";
    }

    return path;
}

From source file:Convert.java

/** 
 * Parses a number from a string.//from  w w  w  .  j  ava  2 s .c  o m
 * Finds the first recognizable base-10 number (integer or floating point)
 * in the string and returns it as a Number.
 * @param string String to parse
 * @return first recognizable number
 * @exception NumberFormatException if no recognizable number is found
 */
public static Number toNumber(String s) throws NumberFormatException {
    // parsing states
    int INT = 0;
    int FRAC = 1;
    int EXP = 2;
    int p = 0;
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (Character.isDigit(c)) {
            int start = i;
            int end = ++i;
            int state = INT;
            if (start > 0 && s.charAt(start - 1) == '.') {
                --start;
                state = FRAC;
            }
            if (start > 0 && s.charAt(start - 1) == '-')
                --start;
            boolean atEnd = false;
            while (!atEnd && i < s.length()) {
                switch (s.charAt(i)) {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    end = ++i;
                    break;
                case '.':
                    if (state == INT) {
                        state = FRAC;
                        ++i;
                    } else {
                        atEnd = true;
                    }
                    break;
                case 'e':
                case 'E':
                    state = EXP;
                    ++i;
                    if (i < s.length() && ((c = s.charAt(i)) == '+' || c == '-'))
                        ++i;
                    break;
                default:
                    atEnd = true;
                }
            }
            String num = s.substring(start, end);
            try {
                if (state == INT)
                    return new Integer(num);
                else
                    return new Double(num);
            } catch (NumberFormatException e) {
                throw new RuntimeException("internal error: " + e);
            }
        }
    }
    throw new NumberFormatException(s);
}

From source file:com.santhoshknn.sudoku.GridExtractor.java

/**
 * <p>//  www .  ja v a 2  s.  c o m
 * Parses the supplied file to extract a 9x9 grid of integers substituting
 * the supplied x with a 0
 * </p>
 * <b>Note:</b>Used internally for testing with various data. REST API uses
 * the operation above
 *
 * @param input
 * @return extracted grid if valid input, null otherwise
 */
public GridResponse parseFromFile(final String fileName) {
    int[][] grid = new int[9][9]; // default 0 vals
    GridResponse response = new GridResponse();
    Scanner scanner = null;
    String error = null;
    try {
        URL url = getClass().getResource(fileName);
        log.info("Reading input file [{}]", url.getFile());
        scanner = new Scanner(new File(url.getPath()));
        int row = 0;
        while (scanner.hasNext()) {
            int col = 0;
            String line = scanner.nextLine();
            // delete whitespaces added for cosmetic purpose
            line = StringUtils.deleteWhitespace(line);
            if (line.isEmpty())
                continue; // Sanitize input. Remove line added for
                          // readability
                          // fail if line's length!=9
            if (line.length() != 9) {
                error = INVALID_CHARS_IN_FILE + ":" + (row + 1);
                break;
            }

            for (int i = 0; i < line.length(); i++) {
                //log.info("Row [{}] Char is [{}]",row,line.charAt(i));
                if (Character.isDigit(line.charAt(i))) {
                    int number = Character.getNumericValue(line.charAt(i));
                    grid[row][col] = number;
                } else {
                    grid[row][col] = 0;
                }
                col++;
            }
            if (row == 9)
                break;
            row++;
        }
    } catch (FileNotFoundException e) {
        log.error("Error reading file [{}]", fileName, e);
    } finally {
        if (scanner != null)
            scanner.close();
    }
    if (null == error) {
        response.setGrid(grid);
    } else {
        response.setError(error);
        log.error(error);
    }
    return response;
}