Search in sources :

Example 1 with BeanAdapter

use of org.apache.pivot.beans.BeanAdapter in project pivot by apache.

the class BXMLExplorerDocument method analyseObjectTree.

@SuppressWarnings("unchecked")
private TreeNode analyseObjectTree(Object container) {
    // doesn't look neat
    if (container instanceof TablePane) {
        TreeBranch branch = new TreeBranch(nameForObject(container));
        TablePane table = (TablePane) container;
        for (TablePane.Row row : table.getRows()) {
            TreeNode childBranch = analyseObjectTree(row);
            branch.add(childBranch);
        }
        setComponentIconOnTreeNode(container, branch);
        return branch;
    }
    // We don't want to analyse the components that are added as part of the
    // skin, so use similar logic to BXMLSerializer
    DefaultProperty defaultProperty = container.getClass().getAnnotation(DefaultProperty.class);
    if (defaultProperty != null) {
        TreeBranch branch = new TreeBranch(nameForObject(container));
        String defaultPropertyName = defaultProperty.value();
        BeanAdapter beanAdapter = new BeanAdapter(container);
        if (!beanAdapter.containsKey(defaultPropertyName)) {
            throw new IllegalStateException("default property " + defaultPropertyName + " not found on " + container);
        }
        Object defaultPropertyValue = beanAdapter.get(defaultPropertyName);
        if (defaultPropertyValue != null) {
            if (defaultPropertyValue instanceof Component) {
                TreeNode childBranch = analyseObjectTree(defaultPropertyValue);
                branch.add(childBranch);
            }
        }
        // so make empty branches into nodes.
        if (branch.isEmpty()) {
            TreeNode node = new TreeNode(branch.getText());
            setComponentIconOnTreeNode(container, node);
            return node;
        }
        setComponentIconOnTreeNode(container, branch);
        return branch;
    }
    if (container instanceof Sequence<?>) {
        TreeBranch branch = new TreeBranch(nameForObject(container));
        Iterable<Object> sequence = (Iterable<Object>) container;
        for (Object child : sequence) {
            TreeNode childBranch = analyseObjectTree(child);
            branch.add(childBranch);
        }
        setComponentIconOnTreeNode(container, branch);
        return branch;
    }
    TreeNode node = new TreeNode(nameForObject(container));
    setComponentIconOnTreeNode(container, node);
    return node;
}
Also used : Sequence(org.apache.pivot.collections.Sequence) DefaultProperty(org.apache.pivot.beans.DefaultProperty) TreeBranch(org.apache.pivot.wtk.content.TreeBranch) TreeNode(org.apache.pivot.wtk.content.TreeNode) BeanAdapter(org.apache.pivot.beans.BeanAdapter) Component(org.apache.pivot.wtk.Component) TablePane(org.apache.pivot.wtk.TablePane)

Example 2 with BeanAdapter

use of org.apache.pivot.beans.BeanAdapter in project pivot by apache.

the class JSON method put.

/**
 * Sets the value at the given path.
 *
 * @param <T> The type of value we're dealing with.
 * @param root The root object.
 * @param path The path to the desired location from the root.
 * @param value The new value to set at the given path.
 * @return The value previously associated with the path.
 */
@SuppressWarnings("unchecked")
public static <T> T put(Object root, String path, T value) {
    Utils.checkNull(root, "root");
    Sequence<String> keys = parse(path);
    if (keys.getLength() == 0) {
        throw new IllegalArgumentException("Path is empty.");
    }
    String key = keys.remove(keys.getLength() - 1, 1).get(0);
    Object parent = get(root, keys);
    if (parent == null) {
        throw new IllegalArgumentException("Invalid path.");
    }
    Map<String, T> adapter = (Map<String, T>) (parent instanceof java.util.Map ? new MapAdapter<>((java.util.Map<String, T>) parent) : (parent instanceof Map ? ((Map<String, T>) parent) : new BeanAdapter(parent)));
    Object previousValue;
    if (adapter.containsKey(key)) {
        previousValue = adapter.put(key, value);
    } else if (parent instanceof Sequence<?>) {
        Sequence<Object> sequence = (Sequence<Object>) parent;
        previousValue = sequence.update(Integer.parseInt(key), value);
    } else if (parent instanceof Dictionary<?, ?>) {
        Dictionary<String, Object> dictionary = (Dictionary<String, Object>) parent;
        previousValue = dictionary.put(key, value);
    } else {
        throw new IllegalArgumentException("Property \"" + key + "\" not found.");
    }
    return (T) previousValue;
}
Also used : Dictionary(org.apache.pivot.collections.Dictionary) Sequence(org.apache.pivot.collections.Sequence) BeanAdapter(org.apache.pivot.beans.BeanAdapter) Map(org.apache.pivot.collections.Map)

Example 3 with BeanAdapter

use of org.apache.pivot.beans.BeanAdapter in project pivot by apache.

the class JSON method containsKey.

/**
 * Tests the existence of a path in a given object.
 *
 * @param <T> The type of value we're dealing with.
 * @param root The root object.
 * @param path The path to test (from the root).
 * @return <tt>true</tt> if the path exists; <tt>false</tt>, otherwise.
 */
@SuppressWarnings("unchecked")
public static <T> boolean containsKey(Object root, String path) {
    Utils.checkNull(root, "root");
    Sequence<String> keys = parse(path);
    if (keys.getLength() == 0) {
        throw new IllegalArgumentException("Path is empty.");
    }
    String key = keys.remove(keys.getLength() - 1, 1).get(0);
    Object parent = get(root, keys);
    boolean containsKey;
    if (parent == null) {
        containsKey = false;
    } else {
        Map<String, T> adapter = (Map<String, T>) (parent instanceof java.util.Map ? new MapAdapter<>((java.util.Map<String, T>) parent) : (parent instanceof Map ? ((Map<String, T>) parent) : new BeanAdapter(parent)));
        containsKey = adapter.containsKey(key);
        if (!containsKey) {
            if (parent instanceof Sequence<?>) {
                Sequence<Object> sequence = (Sequence<Object>) parent;
                containsKey = (sequence.getLength() > Integer.parseInt(key));
            } else if (parent instanceof Dictionary<?, ?>) {
                Dictionary<String, Object> dictionary = (Dictionary<String, Object>) parent;
                containsKey = dictionary.containsKey(key);
            } else {
                throw new IllegalArgumentException("Property \"" + key + "\" not found.");
            }
        }
    }
    return containsKey;
}
Also used : Dictionary(org.apache.pivot.collections.Dictionary) Sequence(org.apache.pivot.collections.Sequence) BeanAdapter(org.apache.pivot.beans.BeanAdapter) Map(org.apache.pivot.collections.Map)

Example 4 with BeanAdapter

use of org.apache.pivot.beans.BeanAdapter 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 5 with BeanAdapter

use of org.apache.pivot.beans.BeanAdapter 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)

Aggregations

BeanAdapter (org.apache.pivot.beans.BeanAdapter)14 Dictionary (org.apache.pivot.collections.Dictionary)6 Map (org.apache.pivot.collections.Map)4 Sequence (org.apache.pivot.collections.Sequence)4 ArrayList (org.apache.pivot.collections.ArrayList)3 List (org.apache.pivot.collections.List)3 SerializationException (org.apache.pivot.serialization.SerializationException)3 ParameterizedType (java.lang.reflect.ParameterizedType)2 HashMap (org.apache.pivot.collections.HashMap)2 Component (org.apache.pivot.wtk.Component)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Method (java.lang.reflect.Method)1 Type (java.lang.reflect.Type)1 TypeVariable (java.lang.reflect.TypeVariable)1 BXMLSerializer (org.apache.pivot.beans.BXMLSerializer)1 BeanMonitor (org.apache.pivot.beans.BeanMonitor)1 DefaultProperty (org.apache.pivot.beans.DefaultProperty)1 LinkedList (org.apache.pivot.collections.LinkedList)1 MapAdapter (org.apache.pivot.collections.adapter.MapAdapter)1