Search in sources :

Example 1 with Map

use of org.apache.pivot.collections.Map 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 2 with Map

use of org.apache.pivot.collections.Map 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 3 with Map

use of org.apache.pivot.collections.Map 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 4 with Map

use of org.apache.pivot.collections.Map in project pivot by apache.

the class PropertiesSerializerTest method readValues.

@Test
public // run writeValues before readValues, important
void readValues() throws IOException, SerializationException {
    log("readValues()");
    assertNotNull(testMap);
    // prepare test data, but without using a static variable
    byte[] testBytes = mapToPropertiesToBytes(testMap);
    assertNotNull(testBytes);
    Serializer<Map<?, ?>> serializer = new PropertiesSerializer();
    log("serializer instance created: " + serializer);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(testBytes);
    @SuppressWarnings("unchecked") Map<String, Object> readData = (Map<String, Object>) serializer.readObject(inputStream);
    assertNotNull(readData);
    log("Succesfully Read");
    for (String key : readData) {
        log(key + "=" + readData.get(key));
    }
    inputStream.close();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) PropertiesSerializer(org.apache.pivot.serialization.PropertiesSerializer) HashMap(org.apache.pivot.collections.HashMap) Map(org.apache.pivot.collections.Map) Test(org.junit.Test)

Example 5 with Map

use of org.apache.pivot.collections.Map in project pivot by apache.

the class PropertiesSerializerTest method mapToPropertiesToBytes.

// utility method to transform the given Map to Properties,
// and then to byte array
protected byte[] mapToPropertiesToBytes(Map<String, Object> testMap2) throws IOException, SerializationException {
    Serializer<Map<?, ?>> serializer = new PropertiesSerializer();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    serializer.writeObject(testMap2, outputStream);
    outputStream.flush();
    outputStream.close();
    String result = outputStream.toString();
    return result.getBytes();
}
Also used : PropertiesSerializer(org.apache.pivot.serialization.PropertiesSerializer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(org.apache.pivot.collections.HashMap) Map(org.apache.pivot.collections.Map)

Aggregations

Map (org.apache.pivot.collections.Map)16 HashMap (org.apache.pivot.collections.HashMap)7 List (org.apache.pivot.collections.List)5 BeanAdapter (org.apache.pivot.beans.BeanAdapter)4 Dictionary (org.apache.pivot.collections.Dictionary)3 Sequence (org.apache.pivot.collections.Sequence)3 JSONSerializer (org.apache.pivot.json.JSONSerializer)3 SerializationException (org.apache.pivot.serialization.SerializationException)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 URL (java.net.URL)2 ArrayList (org.apache.pivot.collections.ArrayList)2 FileList (org.apache.pivot.io.FileList)2 PropertiesSerializer (org.apache.pivot.serialization.PropertiesSerializer)2 Task (org.apache.pivot.util.concurrent.Task)2 TaskListener (org.apache.pivot.util.concurrent.TaskListener)2 TreeBranch (org.apache.pivot.wtk.content.TreeBranch)2 Test (org.junit.Test)2 Color (java.awt.Color)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1