Example usage for java.lang Character toChars

List of usage examples for java.lang Character toChars

Introduction

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

Prototype

public static char[] toChars(int codePoint) 

Source Link

Document

Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array.

Usage

From source file:org.openrdf.rio.turtle.TurtleParser.java

protected IRI parseURI() throws IOException, RDFParseException {
    StringBuilder uriBuf = new StringBuilder(100);

    // First character should be '<'
    int c = readCodePoint();
    verifyCharacterOrFail(c, "<");

    // Read up to the next '>' character
    while (true) {
        c = readCodePoint();//from w  ww.  ja va 2s .  c  om

        if (c == '>') {
            break;
        } else if (c == -1) {
            throwEOFException();
        }

        if (c == ' ') {
            reportFatalError("IRI included an unencoded space: '" + c + "'");
        }

        uriBuf.append(Character.toChars(c));

        if (c == '\\') {
            // This escapes the next character, which might be a '>'
            c = readCodePoint();
            if (c == -1) {
                throwEOFException();
            }
            if (c != 'u' && c != 'U') {
                reportFatalError("IRI includes string escapes: '\\" + c + "'");
            }
            uriBuf.append(Character.toChars(c));
        }
    }

    if (c == '.') {
        reportFatalError("IRI must not end in a '.'");
    }

    String uri = uriBuf.toString();

    // Unescape any escape sequences
    try {
        // FIXME: The following decodes \n and similar in URIs, which should be
        // invalid according to test <turtle-syntax-bad-uri-04.ttl>
        uri = TurtleUtil.decodeString(uri);
    } catch (IllegalArgumentException e) {
        reportError(e.getMessage(), BasicParserSettings.VERIFY_DATATYPE_VALUES);
    }

    return super.resolveURI(uri);
}

From source file:io.realm.RealmTest.java

public void rarely_run_testUTF8() {
    testRealm.beginTransaction();//from w  w  w .ja  va  2 s. c  o  m
    testRealm.clear(AllTypes.class);
    testRealm.commitTransaction();

    String file = "assets/unicode_codepoints.csv";
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(file));
    int i = 0;
    String currentUnicode = null;
    try {
        testRealm.beginTransaction();
        while (scanner.hasNextLine()) {
            currentUnicode = scanner.nextLine();
            char[] chars = Character.toChars(Integer.parseInt(currentUnicode, 16));
            String codePoint = new String(chars);
            AllTypes o = testRealm.createObject(AllTypes.class);
            o.setColumnLong(i);
            o.setColumnString(codePoint);

            AllTypes realmType = testRealm.where(AllTypes.class).equalTo("columnLong", i).findFirst();
            if (i > 1) {
                assertEquals("Codepoint: " + i + " / " + currentUnicode, codePoint,
                        realmType.getColumnString()); // codepoint 0 is NULL, ignore for now.
            }
            i++;
        }
        testRealm.commitTransaction();
    } catch (Exception e) {
        fail("Failure, Codepoint: " + i + " / " + currentUnicode + " " + e.getMessage());
    }
}

From source file:weave.servlets.WeaveServlet.java

/**
 * Tries to convert value to the given type.
 * @param value The value to cast to a new type.
 * @param type The desired type.//from w w  w . j a  v  a2s . c om
 * @return The value, which may have been cast as the new type.
 */
protected Object cast(Object value, Class<?> type) throws RemoteException {
    if (type.isInstance(value))
        return value;

    try {
        if (value == null) // null -> NaN
        {
            if (type == double.class || type == Double.class)
                value = Double.NaN;
            else if (type == float.class || type == Float.class)
                value = Float.NaN;
            return value;
        }

        if (value instanceof Map) // Map -> Java Bean
        {
            Object bean = type.newInstance();
            for (Field field : type.getFields()) {
                Object fieldValue = ((Map<?, ?>) value).get(field.getName());
                fieldValue = cast(fieldValue, field.getType());
                field.set(bean, fieldValue);
            }
            return bean;
        }

        if (type.isArray()) // ? -> T[]
        {
            if (value instanceof String) // String -> String[]
                value = CSVParser.defaultParser.parseCSVRow((String) value, true);

            if (value instanceof List) // List -> Object[]
                value = ((List<?>) value).toArray();

            if (value.getClass().isArray()) // T1[] -> T2[]
            {
                int n = Array.getLength(value);
                Class<?> itemType = type.getComponentType();
                Object output = Array.newInstance(itemType, n);
                while (n-- > 0)
                    Array.set(output, n, cast(Array.get(value, n), itemType));
                return output;
            }
        }

        if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection>
        {
            value = cast(value, Object[].class); // ? -> Object[]

            if (value.getClass().isArray()) // T1[] -> Vector<T2>
            {
                int n = Array.getLength(value);
                List<Object> output = new Vector<Object>(n);
                TypeVariable<?>[] itemTypes = type.getTypeParameters();
                Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null;
                while (n-- > 0) {
                    Object item = Array.get(value, n);
                    if (itemType != null)
                        item = cast(item, itemType); // T1 -> T2
                    output.set(n, item);
                }
                return output;
            }
        }

        if (value instanceof String) // String -> ?
        {
            String string = (String) value;

            // String -> primitive
            if (type == char.class || type == Character.class)
                return string.charAt(0);
            if (type == byte.class || type == Byte.class)
                return Byte.parseByte(string);
            if (type == long.class || type == Long.class)
                return Long.parseLong(string);
            if (type == int.class || type == Integer.class)
                return Integer.parseInt(string);
            if (type == short.class || type == Short.class)
                return Short.parseShort(string);
            if (type == float.class || type == Float.class)
                return Float.parseFloat(string);
            if (type == double.class || type == Double.class)
                return Double.parseDouble(string);
            if (type == boolean.class || type == Boolean.class)
                return string.equalsIgnoreCase("true");

            if (type == InputStream.class) // String -> InputStream
            {
                try {
                    return new ByteArrayInputStream(string.getBytes("UTF-8"));
                } catch (Exception e) {
                    return null;
                }
            }
        }

        if (value instanceof Number) // Number -> primitive
        {
            Number number = (Number) value;
            if (type == byte.class || type == Byte.class)
                return number.byteValue();
            if (type == long.class || type == Long.class)
                return number.longValue();
            if (type == int.class || type == Integer.class)
                return number.intValue();
            if (type == short.class || type == Short.class)
                return number.shortValue();
            if (type == float.class || type == Float.class)
                return number.floatValue();
            if (type == double.class || type == Double.class)
                return number.doubleValue();
            if (type == char.class || type == Character.class)
                return Character.toChars(number.intValue())[0];
            if (type == boolean.class || type == Boolean.class)
                return !Double.isNaN(number.doubleValue()) && number.intValue() != 0;
        }
    } catch (Exception e) {
        throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(),
                type.getSimpleName()), e);
    }

    // Return original value if not handled above.
    // Primitives and their Object equivalents will cast automatically.
    return value;
}

From source file:org.openrdf.rio.turtle.TurtleParser.java

/**
 * Parses qnames and boolean values, which have equivalent starting
 * characters./*  w  w  w .ja  v a  2 s  .  c o m*/
 */
protected Value parseQNameOrBoolean() throws IOException, RDFParseException {
    // First character should be a ':' or a letter
    int c = readCodePoint();
    if (c == -1) {
        throwEOFException();
    }
    if (c != ':' && !TurtleUtil.isPrefixStartChar(c)) {
        reportError("Expected a ':' or a letter, found '" + new String(Character.toChars(c)) + "'",
                BasicParserSettings.VERIFY_RELATIVE_URIS);
    }

    String namespace = null;

    if (c == ':') {
        // qname using default namespace
        namespace = getNamespace("");
    } else {
        // c is the first letter of the prefix
        StringBuilder prefix = new StringBuilder(8);
        prefix.append(Character.toChars(c));

        int previousChar = c;
        c = readCodePoint();
        while (TurtleUtil.isPrefixChar(c)) {
            prefix.append(Character.toChars(c));
            previousChar = c;
            c = readCodePoint();
        }

        if (c != ':') {
            // prefix may actually be a boolean value
            String value = prefix.toString();

            if (value.equals("true") || value.equals("false")) {
                unread(c);
                return createLiteral(value, null, XMLSchema.BOOLEAN, getLineNumber(), -1);
            }
        } else {
            if (previousChar == '.') {
                // '.' is a legal prefix name char, but can not appear at the end
                reportFatalError("prefix can not end with with '.'");
            }
        }

        verifyCharacterOrFail(c, ":");

        namespace = getNamespace(prefix.toString());
    }

    // c == ':', read optional local name
    StringBuilder localName = new StringBuilder(16);
    c = readCodePoint();
    if (TurtleUtil.isNameStartChar(c)) {
        if (c == '\\') {
            localName.append(readLocalEscapedChar());
        } else {
            localName.append(Character.toChars(c));
        }

        int previousChar = c;
        c = readCodePoint();
        while (TurtleUtil.isNameChar(c)) {
            if (c == '\\') {
                localName.append(readLocalEscapedChar());
            } else {
                localName.append(Character.toChars(c));
            }
            previousChar = c;
            c = readCodePoint();
        }

        // Unread last character
        unread(c);

        if (previousChar == '.') {
            // '.' is a legal name char, but can not appear at the end, so is
            // not actually part of the name
            unread(previousChar);
            localName.deleteCharAt(localName.length() - 1);
        }
    } else {
        // Unread last character
        unread(c);
    }

    String localNameString = localName.toString();

    for (int i = 0; i < localNameString.length(); i++) {
        if (localNameString.charAt(i) == '%') {
            if (i > localNameString.length() - 3 || !ASCIIUtil.isHex(localNameString.charAt(i + 1))
                    || !ASCIIUtil.isHex(localNameString.charAt(i + 2))) {
                reportFatalError("Found incomplete percent-encoded sequence: " + localNameString);
            }
        }
    }

    // if (c == '.') {
    // reportFatalError("Blank node identifier must not end in a '.'");
    // }

    // Note: namespace has already been resolved
    return createURI(namespace + localNameString);
}

From source file:io.realm.RealmTest.java

private List<String> getCharacterArray() {
    List<String> chars_array = new ArrayList<String>();
    String file = "assets/unicode_codepoints.csv";
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(file));
    int i = 0;/* www.java  2  s  . c  o m*/
    String currentUnicode = null;
    try {
        while (scanner.hasNextLine()) {
            currentUnicode = scanner.nextLine();
            char[] chars = Character.toChars(Integer.parseInt(currentUnicode, 16));
            String codePoint = new String(chars);
            chars_array.add(codePoint);
            i++;
        }
    } catch (Exception e) {
        fail("Failure, Codepoint: " + i + " / " + currentUnicode + " " + e.getMessage());
    }
    return chars_array;
}

From source file:org.eclipse.rdf4j.rio.turtle.TurtleParser.java

/**
 * Parses qnames and boolean values, which have equivalent starting
 * characters.//  w  w  w . j a va 2s.  co m
 */
protected Value parseQNameOrBoolean() throws IOException, RDFParseException {
    // First character should be a ':' or a letter
    int c = readCodePoint();
    if (c == -1) {
        throwEOFException();
    }
    if (c != ':' && !TurtleUtil.isPrefixStartChar(c)) {
        reportError("Expected a ':' or a letter, found '" + new String(Character.toChars(c)) + "'",
                BasicParserSettings.VERIFY_RELATIVE_URIS);
    }

    String namespace = null;

    if (c == ':') {
        // qname using default namespace
        namespace = getNamespace("");
    } else {
        // c is the first letter of the prefix
        StringBuilder prefix = new StringBuilder(8);
        appendCodepoint(prefix, c);

        int previousChar = c;
        c = readCodePoint();
        while (TurtleUtil.isPrefixChar(c)) {
            appendCodepoint(prefix, c);
            previousChar = c;
            c = readCodePoint();
        }
        while (previousChar == '.' && prefix.length() > 0) {
            // '.' is a legal prefix name char, but can not appear at the end
            unread(c);
            c = previousChar;
            prefix.setLength(prefix.length() - 1);
            previousChar = prefix.codePointAt(prefix.codePointCount(0, prefix.length()) - 1);
        }

        if (c != ':') {
            // prefix may actually be a boolean value
            String value = prefix.toString();

            if (value.equals("true")) {
                unread(c);
                return createLiteral("true", null, XMLSchema.BOOLEAN, getLineNumber(), -1);
            } else if (value.equals("false")) {
                unread(c);
                return createLiteral("false", null, XMLSchema.BOOLEAN, getLineNumber(), -1);
            }
        }

        verifyCharacterOrFail(c, ":");

        namespace = getNamespace(prefix.toString());
    }

    // c == ':', read optional local name
    StringBuilder localName = new StringBuilder(16);
    c = readCodePoint();
    if (TurtleUtil.isNameStartChar(c)) {
        if (c == '\\') {
            localName.append(readLocalEscapedChar());
        } else {
            appendCodepoint(localName, c);
        }

        int previousChar = c;
        c = readCodePoint();
        while (TurtleUtil.isNameChar(c)) {
            if (c == '\\') {
                localName.append(readLocalEscapedChar());
            } else {
                appendCodepoint(localName, c);
            }
            previousChar = c;
            c = readCodePoint();
        }

        // Unread last character
        unread(c);

        if (previousChar == '.') {
            // '.' is a legal name char, but can not appear at the end, so
            // is
            // not actually part of the name
            unread(previousChar);
            localName.deleteCharAt(localName.length() - 1);
        }
    } else {
        // Unread last character
        unread(c);
    }

    String localNameString = localName.toString();

    for (int i = 0; i < localNameString.length(); i++) {
        if (localNameString.charAt(i) == '%') {
            if (i > localNameString.length() - 3 || !ASCIIUtil.isHex(localNameString.charAt(i + 1))
                    || !ASCIIUtil.isHex(localNameString.charAt(i + 2))) {
                reportFatalError("Found incomplete percent-encoded sequence: " + localNameString);
            }
        }
    }

    // if (c == '.') {
    // reportFatalError("Blank node identifier must not end in a '.'");
    // }

    // Note: namespace has already been resolved
    return createURI(namespace + localNameString);
}

From source file:org.openrdf.rio.turtle.TurtleParser.java

/**
 * Parses a blank node ID, e.g. <tt>_:node1</tt>.
 *///w  w  w.  j  ava 2 s .com
protected BNode parseNodeID() throws IOException, RDFParseException {
    // Node ID should start with "_:"
    verifyCharacterOrFail(readCodePoint(), "_");
    verifyCharacterOrFail(readCodePoint(), ":");

    // Read the node ID
    int c = readCodePoint();
    if (c == -1) {
        throwEOFException();
    } else if (!TurtleUtil.isBLANK_NODE_LABEL_StartChar(c)) {
        reportError("Expected a letter, found '" + (char) c + "'", BasicParserSettings.PRESERVE_BNODE_IDS);
    }

    StringBuilder name = new StringBuilder(32);
    name.append(Character.toChars(c));

    // Read all following letter and numbers, they are part of the name
    c = readCodePoint();

    // If we would never go into the loop we must unread now
    if (!TurtleUtil.isBLANK_NODE_LABEL_Char(c)) {
        unread(c);
    }

    while (TurtleUtil.isBLANK_NODE_LABEL_Char(c)) {
        int previous = c;
        c = readCodePoint();

        if (previous == '.' && (c == -1 || TurtleUtil.isWhitespace(c) || c == '<' || c == '_')) {
            unread(c);
            unread(previous);
            break;
        }
        name.append((char) previous);
        if (!TurtleUtil.isBLANK_NODE_LABEL_Char(c)) {
            unread(c);
        }
    }

    return createBNode(name.toString());
}

From source file:org.eclipse.rdf4j.rio.turtle.TurtleParser.java

private char readLocalEscapedChar() throws RDFParseException, IOException {
    int c = readCodePoint();

    if (TurtleUtil.isLocalEscapedChar(c)) {
        return (char) c;
    } else {//  w w w .  j av  a 2  s .c o m
        throw new RDFParseException("found '" + new String(Character.toChars(c)) + "', expected one of: "
                + Arrays.toString(TurtleUtil.LOCAL_ESCAPED_CHARS));
    }
}

From source file:io.realm.RealmTests.java

@Test
public void utf8Tests() {
    realm.beginTransaction();//  w ww.  j  a va2s . c o  m
    realm.delete(AllTypes.class);
    realm.commitTransaction();

    String file = "assets/unicode_codepoints.csv";
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(file), "UTF-8");
    int i = 0;
    String currentUnicode = null;
    try {
        realm.beginTransaction();
        while (scanner.hasNextLine()) {
            currentUnicode = scanner.nextLine();
            char[] chars = Character.toChars(Integer.parseInt(currentUnicode, 16));
            String codePoint = new String(chars);
            AllTypes o = realm.createObject(AllTypes.class);
            o.setColumnLong(i);
            o.setColumnString(codePoint);

            AllTypes realmType = realm.where(AllTypes.class).equalTo("columnLong", i).findFirst();
            if (i > 1) {
                assertEquals("Codepoint: " + i + " / " + currentUnicode, codePoint,
                        realmType.getColumnString()); // codepoint 0 is NULL, ignore for now.
            }
            i++;
        }
        realm.commitTransaction();
    } catch (Exception e) {
        fail("Failure, Codepoint: " + i + " / " + currentUnicode + " " + e.getMessage());
    }
}

From source file:io.realm.RealmTests.java

private List<String> getCharacterArray() {
    List<String> chars_array = new ArrayList<String>();
    String file = "assets/unicode_codepoints.csv";
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(file), "UTF-8");
    int i = 0;//from  w  w w. j  a v  a  2s.co m
    String currentUnicode = null;
    try {
        while (scanner.hasNextLine()) {
            currentUnicode = scanner.nextLine();
            char[] chars = Character.toChars(Integer.parseInt(currentUnicode, 16));
            String codePoint = new String(chars);
            chars_array.add(codePoint);
            i++;
        }
    } catch (Exception e) {
        fail("Failure, Codepoint: " + i + " / " + currentUnicode + " " + e.getMessage());
    }
    return chars_array;
}