Example usage for java.lang Character isWhitespace

List of usage examples for java.lang Character isWhitespace

Introduction

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

Prototype

public static boolean isWhitespace(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is white space according to Java.

Usage

From source file:com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForInitializerPadCheck.java

@Override
public void visitToken(DetailAST ast) {
    if (ast.getChildCount() == 0) {
        //empty for initializer. test pad before semi.
        final DetailAST semi = ast.getNextSibling();
        final int semiLineIdx = semi.getLineNo() - 1;
        final String line = getLines()[semiLineIdx];
        final int before = semi.getColumnNo() - 1;
        //don't check if semi at beginning of line
        if (!CommonUtils.hasWhitespaceBefore(before, line)) {
            if (option == PadOption.NOSPACE && Character.isWhitespace(line.charAt(before))) {
                log(semi.getLineNo(), before, MSG_PRECEDED, SEMICOLON);
            } else if (option == PadOption.SPACE && !Character.isWhitespace(line.charAt(before))) {
                log(semi.getLineNo(), before, MSG_NOT_PRECEDED, SEMICOLON);
            }//from w w  w .  j a  va  2s. co  m
        }
    }
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.PennTreesToCsvWriter.java

/**
 * Taken from commons-lang:2.6// www  .  j  a va2  s. c  o  m
 */
private String normalizeSpace(String str) {
    str = StringUtils.strip(str);
    if (str == null || str.length() <= 2) {
        return str;
    }
    StrBuilder b = new StrBuilder(str.length());
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (Character.isWhitespace(c)) {
            if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {
                b.append(' ');
            }
        } else {
            b.append(c);
        }
    }
    return b.toString();
}

From source file:jshm.sh.scraper.wiki.ActionsScraper.java

public static Map<String, List<Action>> scrape(final Reader reader, final Map<String, List<Action>> ret)
        throws IOException, ScraperException {
    if (null == ret)
        throw new NullPointerException("ret");

    BufferedReader in = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);

    StringBuilder sb = null;//from  w  w w.jav  a  2 s  .co m
    String lastKey = null;
    Action action = null;

    int c = -1, leftBraceCount = 0, rightBraceCount = 0;
    boolean isQuotedString = false;
    Expect expect = Expect.LEFT_BRACE;

    while (-1 != (c = in.read())) {
        switch (expect) {
        case LEFT_BRACE:
            if ('{' == c) {
                leftBraceCount++;

                if (2 == leftBraceCount) {
                    LOG.finer("got 2 left braces, expecting name");
                    expect = Expect.NAME;
                    action = new Action();
                    sb = new StringBuilder();
                    isQuotedString = false;
                }
            }

            // skipping non action block
            continue;

        case NAME:
            if (Character.isLetter(c)) {
                sb.append((char) c);
                continue;
            } else if ('}' == c) {
                // no key/value pairs
                rightBraceCount++;
                action.name = sb.toString();
                if (null == ret.get(action.name))
                    ret.put(action.name, new ArrayList<Action>());
                ret.get(action.name).add(action);
                expect = Expect.RIGHT_BRACE;

                LOG.finer("got right brace after name (" + action.name + "), action has no args");
                continue;
            } else if (Character.isWhitespace(c)) {
                // we've read some characters for the name
                if (0 != sb.length()) {
                    action.name = sb.toString();
                    if (null == ret.get(action.name))
                        ret.put(action.name, new ArrayList<Action>());
                    ret.get(action.name).add(action);
                    expect = Expect.KEY;
                    sb = new StringBuilder();
                    isQuotedString = false;

                    LOG.finer("got whitespace after name (" + action.name + ")");
                }

                // else there's whitespace before the name

                continue;
            }

            throw new ScraperException("expecting next letter in name or whitespace after, got: " + (char) c);

        case KEY:
            if (Character.isLetter(c)) {
                sb.append((char) c);
                continue;
            } else if (Character.isWhitespace(c) && 0 == sb.length()) {
                // extra whitespace between last thing and this key 
                continue;
            } else if ('}' == c) {
                if (0 != sb.length())
                    throw new ScraperException("expecting next letter in key but got right brace");

                LOG.finer("got right brace after last value");

                rightBraceCount++;
                expect = Expect.RIGHT_BRACE;
                continue;
            } else if ('=' == c) {
                lastKey = sb.toString();

                LOG.finer("got equals sign after key (" + lastKey + ")");

                expect = Expect.VALUE;
                sb = new StringBuilder();
                isQuotedString = false;
                continue;
            }

            throw new ScraperException("expecting next letter in key or equals sign, got: " + (char) c);

        case VALUE:
            if (isQuotedString && '"' != c && '}' != c) {
                sb.append((char) c);
                continue;
            } else if ('"' == c || (isQuotedString && '}' == c)) {
                if ('}' == c) {
                    // malformed, no end quote
                    isQuotedString = false;
                } else {
                    isQuotedString = !isQuotedString;
                }

                if (isQuotedString) {
                    LOG.finest("got opening quote for value of key (" + lastKey + ")");
                } else {
                    String value = org.htmlparser.util.Translate.decode(sb.toString().trim());

                    LOG.finer("got closing quote for value (" + value + ")");

                    action.args.put(lastKey, value);

                    if ('}' == c) {
                        expect = Expect.RIGHT_BRACE;
                        rightBraceCount++;
                    } else {
                        expect = Expect.KEY;
                    }

                    lastKey = null;
                    sb = new StringBuilder();
                    isQuotedString = false;
                }

                continue;
            } else if (Character.isWhitespace(c)) {
                LOG.finer("got whitespace before value for key (" + lastKey + ")");
                expect = Expect.KEY;
                lastKey = null;
                sb = new StringBuilder();
                isQuotedString = false;

                continue;
            }

            throw new ScraperException("expecting quote or next letter in value, got: " + (char) c);

        case RIGHT_BRACE:
            if ('}' == c) {
                rightBraceCount++;

                if (2 == rightBraceCount) {
                    LOG.finer("got 2nd right brace");
                    leftBraceCount = rightBraceCount = 0;
                    expect = Expect.LEFT_BRACE;
                    continue;
                }
            }

            throw new ScraperException("expecting 2nd right brace, got " + (char) c);
        }
    }

    return ret;
}

From source file:net.sf.jabref.bst.BibtexCaseChanger.java

private String doChangeCase(String s, FORMAT_MODE format) {
    char[] c = s.toCharArray();

    StringBuilder sb = new StringBuilder();

    int i = 0;// w  ww. j  a v  a2  s . c  o m
    int n = s.length();

    while (i < n) {
        if (c[i] == '{') {
            braceLevel++;
            if ((braceLevel != 1) || ((i + 4) > n) || (c[i + 1] != '\\')) {
                prevColon = false;
                sb.append(c[i]);
                i++;
                continue;
            }
            if ((format == FORMAT_MODE.TITLE_LOWERS)
                    && ((i == 0) || (prevColon && Character.isWhitespace(c[i - 1])))) {
                sb.append('{');
                i++;
                prevColon = false;
                continue;
            }
            i = convertSpecialChar(sb, c, i, format);
            continue;
        }
        if (c[i] == '}') {
            sb.append(c[i]);
            i++;
            if (braceLevel == 0) {
                LOGGER.warn("Too many closing braces in string: " + s);
            } else {
                braceLevel--;
            }
            prevColon = false;
            continue;
        }
        if (braceLevel == 0) {
            i = convertCharIfBraceLevelIsZero(c, i, sb, format);
            continue;
        }
        sb.append(c[i]);
        i++;
    }
    if (braceLevel > 0) {
        LOGGER.warn("No enough closing braces in string: " + s);
    }
    return sb.toString();
}

From source file:Strings.java

/**
 * Returns true if specified character is a whitespace character.
 * The definition in {@link/*from  ww w  .  ja  v  a  2  s .co m*/
 * java.lang.Character#isWhitespace(char)} is extended to include
 * the unicode non-breakable space character (unicode 160).
 *
 * @param c Character to test.
 * @return <code>true</code> if specified character is a
 * whitespace.
 * @see java.lang.Character#isWhitespace(char)
 */
public static boolean isWhitespace(char c) {
    return Character.isWhitespace(c) || c == NBSP_CHAR;
}

From source file:HTMLParser.java

private int skipSpace(int c) {
    while (c != EOF && Character.isWhitespace((char) c)) {
        c = getC();//from   w  w w  .  ja v  a  2  s.  c o  m
    }
    return c;
}

From source file:de.jcup.egradle.sdk.builder.action.javadoc.ReplaceJavaDocPartsAction.java

License:asdf

String removeWhitespacesAndStars(String text) {
    StringBuilder sb = new StringBuilder();

    boolean firstNonWhitespaceWorked = false;
    for (char c : text.toCharArray()) {
        if (!firstNonWhitespaceWorked) {
            if (Character.isWhitespace(c)) {
                continue;
            }/*from w w  w  . j  a v a2  s. c  o  m*/
            firstNonWhitespaceWorked = true;
            if (c == '*') {
                continue;
            }
            /* other first char will be appended */
        }
        sb.append(c);
    }
    String result = sb.toString();
    return result;
}

From source file:com.streamsets.pipeline.lib.parser.log.ExtendedFormatParser.java

@Override
public Map<String, Field> parseLogLine(StringBuilder logLine) throws DataParserException {
    Map<String, Field> map = new HashMap<>();

    // Parse headers
    Matcher m = HEADER_PATTERN.matcher(logLine);
    int counter = 0;
    int index = 0;
    int headerCount = 1;
    while (counter < headerCount && m.find()) {
        String val = logLine.substring(index, m.start());

        if (counter == 0) {
            Field formatVersion = getExtFormatVersion(val);
            map.put(formatType.label + "Version", formatVersion);
            headerCount = getNumHeaderFields(formatType, formatVersion);
        } else {//from  w  ww.  jav a  2 s.co  m
            map.put(getHeaderFieldName(counter), Field.create(val));
        }

        index = m.end();
        counter++;
    }

    if (counter < headerCount) {
        throw new DataParserException(Errors.LOG_PARSER_12, formatName, headerCount, counter);
    }

    // For LEEF 2.0, there is an optional field in the header, so we check for it, and
    // advance the index, if necessary, to get to the start of the extensions
    char attrSeparator = getExtensionAttrSeparator(m, index, logLine);
    if (!m.hitEnd()) {
        index = m.end();
    }

    // Calls to trim() will strip off whitespace, but if format is LEEF 2.0 and a custom
    // delimiter is being used, we need to offset the start index of extension keys
    int offset = 0;
    if (!Character.isWhitespace(attrSeparator)) {
        offset = 1;
    }

    // Process extensions
    Map<String, Field> extMap = new HashMap<>();
    Map<String, String> labelMap = new HashMap<>();
    String ext = logLine.substring(index);
    m = EXT_PATTERN.matcher(ext);
    index = 0;
    String key = null;
    String value;

    while (m.find()) {
        if (key == null) {
            key = ext.substring(index, m.start());
            index = m.end();
            if (!m.find()) {
                break;
            }
        }
        // Regex will search for unescaped '=' character to find the split between keys
        // and values. We'll need to figure out where the separator is to determine the
        // end of the value, and then go back for the next KV pair
        value = ext.substring(index, m.start());
        index = m.end();
        int lastSepIndex = value.lastIndexOf(attrSeparator);
        if (lastSepIndex > 0) {
            String temp = value.substring(0, lastSepIndex).trim();
            putLabelIntoAppropriateMap(labelMap, extMap, key, temp);
            key = value.substring(lastSepIndex + offset).trim();
        }
    }
    value = ext.substring(index);

    // Build a map of Label extensions to apply later
    putLabelIntoAppropriateMap(labelMap, extMap, key, value);

    // Apply the labels to custom fields
    for (Map.Entry<String, String> label : labelMap.entrySet()) {
        if (extMap.containsKey(label.getKey())) {
            Field field = extMap.remove(label.getKey());
            extMap.put(label.getValue(), field);
        }
    }

    map.put("extensions", Field.create(extMap));

    return map;
}

From source file:blue.soundObject.Note.java

private void noteInit(String input, Note previousNote) throws Exception {
    // If for any reason there should be an exception
    // let it bubble up and the note factory method will
    // return null

    int i = 0;//from   ww  w .jav  a  2s  .c  om
    ArrayList buffer = new ArrayList();
    int size = input.length();

    int start = 0;

    // the following code might be better off using
    // regular expressions, but should wait until
    // Java 1.4 is available on all platforms

    // PARSES PFIELDS FROM STRING
    while (i < size) {
        if (input.charAt(i) == '\"') {
            start = i++;

            while (i < size && input.charAt(i) != '\"') {
                i++;
            }

            buffer.add(input.substring(start, ++i));
            // i++;
        } else if (input.charAt(i) == '[') {
            start = ++i;
            while (i < size && input.charAt(i) != ']') {
                i++;
            }

            float val = ScoreExpressionParser.eval(input.substring(start, i));

            i++;

            buffer.add(Float.toString(val));
        } else if (Character.isWhitespace(input.charAt(i))) {
            while (i < size && Character.isWhitespace(input.charAt(i))) {
                i++; // eat up empty spaces or tabs
            }
        } else {
            start = i;
            while (i < size && !(Character.isWhitespace(input.charAt(i)))) {
                i++;
            }
            buffer.add(input.substring(start, i));
        }
    }

    if (previousNote != null) {
        boolean performCarry = buffer.get(0).equals(previousNote.getPField(1));

        if (!performCarry) {
            try {
                int instr1 = (int) (Float.parseFloat((String) buffer.get(0)));
                int instr2 = (int) (Float.parseFloat(previousNote.getPField(1)));

                if (instr1 == instr2) {
                    performCarry = true;
                }
            } catch (NumberFormatException nfe) {
                performCarry = false;
            }
        }

        if (performCarry) {
            int numFieldsToCopy = previousNote.getPCount() - buffer.size();
            if (numFieldsToCopy > 0) {
                for (i = previousNote.getPCount() - numFieldsToCopy; i < previousNote.getPCount(); i++) {
                    buffer.add(previousNote.getPField(i + 1));
                }
            }
        }
    }

    // INITIALIZES PFIELD ARRAY
    fields = (String[]) buffer.toArray(new String[buffer.size()]);

    if (previousNote != null) {

        // SWAP PERIODS WITH VALUE FROM PREVIOUS NOTE
        for (i = 0; i < fields.length; i++) {
            if (fields[i].equals(".")) {
                fields[i] = previousNote.getPField(i + 1);
            }
        }
    }

    float dur = Float.parseFloat(fields[2]);

    setSubjectiveDuration(dur);
    setTied(dur < 0.0f);
}

From source file:de.jcup.egradle.codeassist.SourceCodeInsertionSupport.java

/**
 * Transform text before column to indent string. Purpose for this method is
 * to have exact same column as on code completion before. Because text
 * before can also contain parts of the code proposal itself the text before
 * last whitespace will not be used for indention.<br>
 * <br>/*from ww  w.ja v a  2 s .  c o m*/
 * 
 * An example:
 * 
 * <pre>
 *    "123 cod" will be transformed to "    "
 *  "  3 cod" will be transformed to "    "
 *  "  3 co " will be transformed to "       "
 * 
 * </pre>
 * 
 * @param textBeforeColumn
 * @return transformed string never <code>null</code>
 */
String transformTextBeforeToIndentString(String textBeforeColumn) {
    if (textBeforeColumn == null) {
        return "";
    }
    StringBuilder indentSb = new StringBuilder();
    int lastOriginWhitespacePos = -1;
    for (int i = 0; i < textBeforeColumn.length(); i++) {
        char c = textBeforeColumn.charAt(i);
        if (Character.isWhitespace(c)) {
            indentSb.append(c);
            lastOriginWhitespacePos = i + 1;
        } else {
            indentSb.append(" ");
        }
    }
    if (lastOriginWhitespacePos == -1) {
        return ""; // there were no origin whitespaces so do not indent
    }
    String indent = indentSb.substring(0, lastOriginWhitespacePos);
    return indent;
}