Search in sources :

Example 6 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class TableView method setTableData.

/**
 * Sets the table data.
 *
 * @param tableData A URL referring to a JSON file containing the data to be
 * presented by the table view.
 */
public void setTableData(URL tableData) {
    Utils.checkNull(tableData, "URL for table data");
    JSONSerializer jsonSerializer = new JSONSerializer();
    try {
        setTableData((List<?>) jsonSerializer.readObject(tableData.openStream()));
    } catch (SerializationException exception) {
        throw new IllegalArgumentException(exception);
    } catch (IOException exception) {
        throw new IllegalArgumentException(exception);
    }
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) IOException(java.io.IOException) JSONSerializer(org.apache.pivot.json.JSONSerializer)

Example 7 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class JSONSerializer method writeObject.

/**
 * Writes data to a JSON stream.
 *
 * @param object The object to serialize. Must be one of the following
 * types: <ul> <li>pivot.collections.Map</li>
 * <li>pivot.collections.List</li> <li>java.lang.String</li>
 * <li>java.lang.Number</li> <li>java.lang.Boolean</li>
 * <li><tt>null</tt></li> </ul>
 * @param writer The writer to which data will be written.
 * @throws IOException for any errors during the writing process.
 * @throws SerializationException for any formatting errors in the data.
 */
@SuppressWarnings("unchecked")
public void writeObject(Object object, Writer writer) throws IOException, SerializationException {
    Utils.checkNull(writer, "writer");
    if (object == null) {
        writer.append("null");
    } else if (object instanceof String) {
        String string = (String) object;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0, n = string.length(); i < n; i++) {
            char ci = string.charAt(i);
            switch(ci) {
                case '\t':
                    {
                        stringBuilder.append("\\t");
                        break;
                    }
                case '\n':
                    {
                        stringBuilder.append("\\n");
                        break;
                    }
                case '\r':
                    {
                        stringBuilder.append("\\r");
                        break;
                    }
                case '\f':
                    {
                        stringBuilder.append("\\f");
                        break;
                    }
                case '\b':
                    {
                        stringBuilder.append("\\b");
                        break;
                    }
                case '\\':
                case '\"':
                case '\'':
                    {
                        stringBuilder.append("\\" + ci);
                        break;
                    }
                default:
                    {
                        // and for other character sets if the value is an ASCII control character.
                        if ((charset.name().startsWith("UTF") && !Character.isISOControl(ci)) || (ci > 0x1F && ci != 0x7F && ci <= 0xFF)) {
                            stringBuilder.append(ci);
                        } else {
                            stringBuilder.append("\\u");
                            stringBuilder.append(String.format("%04x", (short) ci));
                        }
                    }
            }
        }
        writer.append("\"" + stringBuilder.toString() + "\"");
    } else if (object instanceof Number) {
        Number number = (Number) object;
        if (number instanceof Float) {
            Float f = (Float) number;
            if (f.isNaN() || f.isInfinite()) {
                throw new SerializationException(number + " is not a valid value.");
            }
        } else if (number instanceof Double) {
            Double d = (Double) number;
            if (d.isNaN() || d.isInfinite()) {
                throw new SerializationException(number + " is not a valid value.");
            }
        }
        writer.append(number.toString());
    } else if (object instanceof Boolean) {
        writer.append(object.toString());
    } else if (object instanceof List<?>) {
        List<Object> list = (List<Object>) object;
        writer.append("[");
        int i = 0;
        for (Object item : list) {
            if (i > 0) {
                writer.append(", ");
            }
            writeObject(item, writer);
            i++;
        }
        writer.append("]");
    } else {
        Map<String, Object> map;
        if (object instanceof Map<?, ?>) {
            map = (Map<String, Object>) object;
        } else if (object instanceof java.util.Map<?, ?>) {
            map = new MapAdapter<>((java.util.Map<String, Object>) object);
        } else {
            map = new BeanAdapter(object, true);
        }
        writer.append("{");
        int i = 0;
        for (String key : map) {
            Object value = map.get(key);
            boolean identifier = true;
            StringBuilder keyStringBuilder = new StringBuilder();
            for (int j = 0, n = key.length(); j < n; j++) {
                char cj = key.charAt(j);
                identifier &= Character.isJavaIdentifierPart(cj);
                if (cj == '"') {
                    keyStringBuilder.append('\\');
                }
                keyStringBuilder.append(cj);
            }
            key = keyStringBuilder.toString();
            if (i > 0) {
                writer.append(", ");
            }
            // Write the key
            if (!identifier || alwaysDelimitMapKeys) {
                writer.append('"');
            }
            writer.append(key);
            if (!identifier || alwaysDelimitMapKeys) {
                writer.append('"');
            }
            writer.append(": ");
            // Write the value
            writeObject(value, writer);
            i++;
        }
        writer.append("}");
    }
    writer.flush();
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) ListenerList(org.apache.pivot.util.ListenerList) ArrayList(org.apache.pivot.collections.ArrayList) List(org.apache.pivot.collections.List) BeanAdapter(org.apache.pivot.beans.BeanAdapter) Map(org.apache.pivot.collections.Map) HashMap(org.apache.pivot.collections.HashMap) MapAdapter(org.apache.pivot.collections.adapter.MapAdapter)

Example 8 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class JSONSerializer method readMapValue.

@SuppressWarnings("unchecked")
private Object readMapValue(Reader reader, Type typeArgument) throws IOException, SerializationException {
    Dictionary<String, Object> dictionary = null;
    Type valueType = null;
    if (typeArgument == Object.class) {
        // Return the default dictionary and value types
        dictionary = new HashMap<>();
        valueType = Object.class;
    } else {
        // Determine the value type from generic parameters
        Type parentType = typeArgument;
        while (parentType != null) {
            if (parentType instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) parentType;
                Class<?> rawType = (Class<?>) parameterizedType.getRawType();
                if (Dictionary.class.isAssignableFrom(rawType)) {
                    valueType = parameterizedType.getActualTypeArguments()[1];
                }
                break;
            }
            Class<?> classType = (Class<?>) parentType;
            Type[] genericInterfaces = classType.getGenericInterfaces();
            for (int i = 0; i < genericInterfaces.length; i++) {
                Type genericInterface = genericInterfaces[i];
                if (genericInterface instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
                    Class<?> interfaceType = (Class<?>) parameterizedType.getRawType();
                    if (Dictionary.class.isAssignableFrom(interfaceType)) {
                        valueType = parameterizedType.getActualTypeArguments()[1];
                        if (valueType instanceof TypeVariable<?>) {
                            valueType = Object.class;
                        }
                        break;
                    }
                }
            }
            if (valueType != null) {
                break;
            }
            parentType = classType.getGenericSuperclass();
        }
        // Instantiate the dictionary or bean type
        if (valueType == null) {
            Class<?> beanType = (Class<?>) typeArgument;
            try {
                dictionary = new BeanAdapter(beanType.newInstance());
            } catch (InstantiationException exception) {
                throw new RuntimeException(exception);
            } catch (IllegalAccessException exception) {
                throw new RuntimeException(exception);
            }
        } else {
            Class<?> dictionaryType;
            if (typeArgument instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) typeArgument;
                dictionaryType = (Class<?>) parameterizedType.getRawType();
            } else {
                dictionaryType = (Class<?>) typeArgument;
            }
            try {
                dictionary = (Dictionary<String, Object>) dictionaryType.newInstance();
            } catch (InstantiationException exception) {
                throw new RuntimeException(exception);
            } catch (IllegalAccessException exception) {
                throw new RuntimeException(exception);
            }
        }
    }
    // Notify the listeners
    if (jsonSerializerListeners != null) {
        jsonSerializerListeners.beginDictionary(this, dictionary);
    }
    // Move to the next character after '{'
    c = reader.read();
    skipWhitespaceAndComments(reader);
    while (c != -1 && c != '}') {
        String key = null;
        if (c == '"' || c == '\'') {
            // The key is a delimited string
            key = readString(reader);
        } else {
            // The key is an undelimited string; it must adhere to Java
            // identifier syntax
            StringBuilder keyBuilder = new StringBuilder();
            if (!Character.isJavaIdentifierStart(c)) {
                throw new SerializationException("Illegal identifier start character.");
            }
            while (c != -1 && c != ':' && !Character.isWhitespace(c)) {
                if (!Character.isJavaIdentifierPart(c)) {
                    throw new SerializationException("Illegal identifier character.");
                }
                keyBuilder.append((char) c);
                c = reader.read();
            }
            if (c == -1) {
                throw new SerializationException("Unexpected end of input stream.");
            }
            key = keyBuilder.toString();
        }
        if (key == null || key.length() == 0) {
            throw new SerializationException("\"" + key + "\" is not a valid key.");
        }
        // Notify listeners
        if (jsonSerializerListeners != null) {
            jsonSerializerListeners.readKey(this, key);
        }
        skipWhitespaceAndComments(reader);
        if (c != ':') {
            throw new SerializationException("Unexpected character in input stream: '" + (char) c + "'");
        }
        // Move to the first character after ':'
        c = reader.read();
        if (valueType == null) {
            // The map is a bean instance; get the generic type of the property
            Type genericValueType = ((BeanAdapter) dictionary).getGenericType(key);
            if (genericValueType != null) {
                // Set the value in the bean
                dictionary.put(key, readValue(reader, genericValueType, key));
            } else {
                // The property does not exist; ignore this value
                readValue(reader, Object.class, key);
            }
        } else {
            dictionary.put(key, readValue(reader, valueType, key));
        }
        skipWhitespaceAndComments(reader);
        if (c == ',') {
            c = reader.read();
            skipWhitespaceAndComments(reader);
        } else if (c == -1) {
            throw new SerializationException("Unexpected end of input stream.");
        } else {
            if (c != '}') {
                throw new SerializationException("Unexpected character in input stream: '" + (char) c + "'");
            }
        }
    }
    // Move to the first character after '}'
    c = reader.read();
    // Notify the listeners
    if (jsonSerializerListeners != null) {
        jsonSerializerListeners.endDictionary(this);
    }
    return (dictionary instanceof BeanAdapter) ? ((BeanAdapter) dictionary).getBean() : dictionary;
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) TypeVariable(java.lang.reflect.TypeVariable) BeanAdapter(org.apache.pivot.beans.BeanAdapter)

Example 9 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class JSONSerializer method readObject.

/**
 * Reads data from a JSON stream.
 * <p> Processes macros at this level using {@link MacroReader}.
 *
 * @param reader The reader from which data will be read.
 * @return One of the following types, depending on the content of the stream
 * and the value of {@link #getType()}:
 * <ul>
 * <li>pivot.collections.Dictionary</li>
 * <li>pivot.collections.Sequence</li>
 * <li>java.lang.String</li>
 * <li>java.lang.Number</li>
 * <li>java.lang.Boolean</li>
 * <li><tt>null</tt></li>
 * <li>A JavaBean object</li>
 * </ul>
 * @throws IOException for any I/O related errors while reading.
 * @throws SerializationException for any formatting errors in the data.
 */
public Object readObject(Reader reader) throws IOException, SerializationException {
    Utils.checkNull(reader, "reader");
    // Move to the first character
    LineNumberReader lineNumberReader = new LineNumberReader(reader);
    MacroReader macroReader = new MacroReader(lineNumberReader);
    c = macroReader.read();
    // Ignore BOM (if present)
    if (c == 0xFEFF) {
        c = macroReader.read();
    }
    // Read the root value
    Object object;
    try {
        object = readValue(macroReader, type, type.getTypeName());
    } catch (SerializationException exception) {
        System.err.println("An error occurred while processing input at line number " + (lineNumberReader.getLineNumber() + 1));
        throw exception;
    }
    return object;
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) MacroReader(org.apache.pivot.serialization.MacroReader) LineNumberReader(java.io.LineNumberReader)

Example 10 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class JSONSerializer method skipWhitespaceAndComments.

private void skipWhitespaceAndComments(Reader reader) throws IOException, SerializationException {
    while (c != -1 && (Character.isWhitespace(c) || c == '/')) {
        boolean comment = (c == '/');
        // Read the next character
        c = reader.read();
        if (comment) {
            if (c == '/') {
                // Single-line comment
                while (c != -1 && c != '\n' && c != '\r') {
                    c = reader.read();
                }
            } else if (c == '*') {
                // Multi-line comment
                boolean closed = false;
                while (c != -1 && !closed) {
                    c = reader.read();
                    if (c == '*') {
                        c = reader.read();
                        closed = (c == '/');
                    }
                }
                if (!closed) {
                    throw new SerializationException("Unexpected end of input stream.");
                }
                if (c != -1) {
                    c = reader.read();
                }
            } else {
                throw new SerializationException("Unexpected character in input stream: '" + (char) c + "'");
            }
        }
    }
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException)

Aggregations

SerializationException (org.apache.pivot.serialization.SerializationException)49 IOException (java.io.IOException)28 BXMLSerializer (org.apache.pivot.beans.BXMLSerializer)14 URL (java.net.URL)9 JSONSerializer (org.apache.pivot.json.JSONSerializer)9 ArrayList (org.apache.pivot.collections.ArrayList)8 Component (org.apache.pivot.wtk.Component)7 File (java.io.File)6 List (org.apache.pivot.collections.List)6 QueryException (org.apache.pivot.web.QueryException)6 ComponentMouseButtonListener (org.apache.pivot.wtk.ComponentMouseButtonListener)6 InputStream (java.io.InputStream)5 Sequence (org.apache.pivot.collections.Sequence)5 Button (org.apache.pivot.wtk.Button)5 ButtonPressListener (org.apache.pivot.wtk.ButtonPressListener)5 Mouse (org.apache.pivot.wtk.Mouse)5 PushButton (org.apache.pivot.wtk.PushButton)5 MalformedURLException (java.net.MalformedURLException)4 ScriptException (javax.script.ScriptException)4 TextInput (org.apache.pivot.wtk.TextInput)4