Search in sources :

Example 36 with SerializationException

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

the class BXMLSerializer method processEndElement.

@SuppressWarnings("unchecked")
private void processEndElement() throws SerializationException {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    switch(element.type) {
        case INSTANCE:
        case INCLUDE:
        case REFERENCE:
            {
                // Apply attributes
                for (Attribute attribute : element.attributes) {
                    if (attribute.propertyClass == null) {
                        Dictionary<String, Object> dictionary;
                        if (element.value instanceof Dictionary<?, ?>) {
                            dictionary = (Dictionary<String, Object>) element.value;
                        } else {
                            dictionary = new BeanAdapter(element.value);
                        }
                        dictionary.put(attribute.name, attribute.value);
                    } else {
                        if (attribute.propertyClass.isInterface()) {
                            // The attribute represents an event listener
                            String listenerClassName = attribute.propertyClass.getName();
                            listenerClassName = listenerClassName.substring(listenerClassName.lastIndexOf('.') + 1);
                            String getListenerListMethodName = "get" + Character.toUpperCase(listenerClassName.charAt(0)) + listenerClassName.substring(1) + "s";
                            // Get the listener list
                            Method getListenerListMethod;
                            try {
                                Class<?> type = element.value.getClass();
                                getListenerListMethod = type.getMethod(getListenerListMethodName);
                            } catch (NoSuchMethodException exception) {
                                throw new SerializationException(exception);
                            }
                            Object listenerList;
                            try {
                                listenerList = getListenerListMethod.invoke(element.value);
                            } catch (InvocationTargetException exception) {
                                throw new SerializationException(exception);
                            } catch (IllegalAccessException exception) {
                                throw new SerializationException(exception);
                            }
                            // Create an invocation handler for this listener
                            AttributeInvocationHandler handler = new AttributeInvocationHandler(getEngineByName(language), attribute.name, (String) attribute.value);
                            Object listener = Proxy.newProxyInstance(classLoader, new Class<?>[] { attribute.propertyClass }, handler);
                            // Add the listener
                            Class<?> listenerListClass = listenerList.getClass();
                            Method addMethod;
                            try {
                                addMethod = listenerListClass.getMethod("add", Object.class);
                            } catch (NoSuchMethodException exception) {
                                throw new RuntimeException(exception);
                            }
                            try {
                                addMethod.invoke(listenerList, listener);
                            } catch (IllegalAccessException exception) {
                                throw new SerializationException(exception);
                            } catch (InvocationTargetException exception) {
                                throw new SerializationException(exception);
                            }
                        } else {
                            // The attribute represents a static setter
                            setStaticProperty(element.value, attribute.propertyClass, attribute.name, attribute.value);
                        }
                    }
                }
                if (element.parent != null) {
                    if (element.parent.type == Element.Type.WRITABLE_PROPERTY) {
                        // Set this as the property value; it will be applied
                        // later in the parent's closing tag
                        element.parent.value = element.value;
                    } else if (element.parent.value != null) {
                        // If the parent element has a default property, use it;
                        // otherwise, if the parent is a sequence, add the element to it.
                        Class<?> parentType = element.parent.value.getClass();
                        DefaultProperty defaultProperty = parentType.getAnnotation(DefaultProperty.class);
                        if (defaultProperty == null) {
                            if (element.parent.value instanceof Sequence<?>) {
                                Sequence<Object> sequence = (Sequence<Object>) element.parent.value;
                                sequence.add(element.value);
                            } else {
                                throw new SerializationException(element.parent.value.getClass() + " is not a sequence.");
                            }
                        } else {
                            String defaultPropertyName = defaultProperty.value();
                            BeanAdapter beanAdapter = new BeanAdapter(element.parent.value);
                            Object defaultPropertyValue = beanAdapter.get(defaultPropertyName);
                            if (defaultPropertyValue instanceof Sequence<?>) {
                                Sequence<Object> sequence = (Sequence<Object>) defaultPropertyValue;
                                try {
                                    sequence.add(element.value);
                                } catch (UnsupportedOperationException uoe) {
                                    beanAdapter.put(defaultPropertyName, element.value);
                                }
                            } else {
                                beanAdapter.put(defaultPropertyName, element.value);
                            }
                        }
                    }
                }
                break;
            }
        case READ_ONLY_PROPERTY:
            {
                Dictionary<String, Object> dictionary;
                if (element.value instanceof Dictionary<?, ?>) {
                    dictionary = (Dictionary<String, Object>) element.value;
                } else {
                    dictionary = new BeanAdapter(element.value);
                }
                // Process attributes looking for instance property setters
                for (Attribute attribute : element.attributes) {
                    if (attribute.propertyClass != null) {
                        throw new SerializationException("Static setters are not supported" + " for read-only properties.");
                    }
                    dictionary.put(attribute.name, attribute.value);
                }
                break;
            }
        case WRITABLE_PROPERTY:
            {
                if (element.propertyClass == null) {
                    Dictionary<String, Object> dictionary;
                    if (element.parent.value instanceof Dictionary) {
                        dictionary = (Dictionary<String, Object>) element.parent.value;
                    } else {
                        dictionary = new BeanAdapter(element.parent.value);
                    }
                    dictionary.put(element.name, element.value);
                } else {
                    if (element.parent == null) {
                        throw new SerializationException("Element does not have a parent.");
                    }
                    if (element.parent.value == null) {
                        throw new SerializationException("Parent value is null.");
                    }
                    setStaticProperty(element.parent.value, element.propertyClass, element.name, element.value);
                }
                break;
            }
        case LISTENER_LIST_PROPERTY:
            {
                // Evaluate the script
                String script = (String) element.value;
                // Get a new engine here in order to make the script function private to this object
                ScriptEngine scriptEngine = newEngineByName(language);
                try {
                    scriptEngine.eval(script);
                } catch (ScriptException exception) {
                    reportException(exception, script);
                    break;
                }
                // Create the listener and add it to the list
                BeanAdapter beanAdapter = new BeanAdapter(element.parent.value);
                ListenerList<?> listenerList = (ListenerList<?>) beanAdapter.get(element.name);
                Class<?> listenerListClass = listenerList.getClass();
                java.lang.reflect.Type[] genericInterfaces = listenerListClass.getGenericInterfaces();
                Class<?> listenerClass = (Class<?>) genericInterfaces[0];
                ElementInvocationHandler handler = new ElementInvocationHandler(scriptEngine);
                Method addMethod;
                try {
                    addMethod = listenerListClass.getMethod("add", Object.class);
                } catch (NoSuchMethodException exception) {
                    throw new RuntimeException(exception);
                }
                Object listener = Proxy.newProxyInstance(classLoader, new Class<?>[] { listenerClass }, handler);
                try {
                    addMethod.invoke(listenerList, listener);
                } catch (IllegalAccessException exception) {
                    throw new SerializationException(exception);
                } catch (InvocationTargetException exception) {
                    throw new SerializationException(exception);
                }
                break;
            }
        case SCRIPT:
            {
                String src = null;
                if (element.properties.containsKey(SCRIPT_SRC_ATTRIBUTE)) {
                    src = element.properties.get(SCRIPT_SRC_ATTRIBUTE);
                }
                if (src != null && src.charAt(0) == OBJECT_REFERENCE_PREFIX) {
                    src = src.substring(1);
                    if (src.length() > 0) {
                        if (!JSON.containsKey(namespace, src)) {
                            throw new SerializationException("Value \"" + src + "\" is not defined.");
                        }
                        String variableValue = JSON.get(namespace, src);
                        src = variableValue;
                    }
                }
                if (src != null) {
                    int i = src.lastIndexOf(".");
                    if (i == -1) {
                        throw new SerializationException("Cannot determine type of script \"" + src + "\".");
                    }
                    String extension = src.substring(i + 1);
                    ScriptEngine scriptEngine = getEngineByExtension(extension);
                    scriptEngine.setBindings(scriptEngineManager.getBindings(), ScriptContext.ENGINE_SCOPE);
                    try {
                        URL scriptLocation;
                        if (src.charAt(0) == SLASH_PREFIX) {
                            scriptLocation = classLoader.getResource(src.substring(1));
                            if (scriptLocation == null) {
                                // add a fallback
                                scriptLocation = new URL(location, src.substring(1));
                            }
                        } else {
                            scriptLocation = new URL(location, src);
                        }
                        BufferedReader scriptReader = null;
                        try {
                            scriptReader = new BufferedReader(new InputStreamReader(scriptLocation.openStream()));
                            scriptEngine.eval(NASHORN_COMPAT_SCRIPT);
                            scriptEngine.eval(scriptReader);
                        } catch (ScriptException exception) {
                            reportException(exception);
                        } finally {
                            if (scriptReader != null) {
                                scriptReader.close();
                            }
                        }
                    } catch (IOException exception) {
                        throw new SerializationException(exception);
                    }
                }
                if (element.value != null) {
                    // Evaluate the script
                    String script = (String) element.value;
                    ScriptEngine scriptEngine = getEngineByName(language);
                    scriptEngine.setBindings(scriptEngineManager.getBindings(), ScriptContext.ENGINE_SCOPE);
                    try {
                        scriptEngine.eval(NASHORN_COMPAT_SCRIPT);
                        scriptEngine.eval(script);
                    } catch (ScriptException exception) {
                        reportException(exception, script);
                    }
                }
                break;
            }
        case DEFINE:
            {
                // No-op
                break;
            }
        default:
            {
                break;
            }
    }
    // Move up the stack
    if (element.parent == null) {
        root = element.value;
    }
    element = element.parent;
}
Also used : ListenerList(org.apache.pivot.util.ListenerList) Dictionary(org.apache.pivot.collections.Dictionary) URL(java.net.URL) ScriptException(javax.script.ScriptException) SerializationException(org.apache.pivot.serialization.SerializationException) InputStreamReader(java.io.InputStreamReader) Method(java.lang.reflect.Method) Sequence(org.apache.pivot.collections.Sequence) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ScriptEngine(javax.script.ScriptEngine) BufferedReader(java.io.BufferedReader)

Example 37 with SerializationException

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

the class BXMLSerializer method readObject.

/**
 * Deserializes an object hierarchy from a BXML resource. <p> This is the
 * base version of the method. It does not set the "location" or "resources"
 * properties. Callers that wish to use this version of the method to load
 * BXML that uses location or resource resolution must manually set these
 * properties via a call to {@link #setLocation(URL)} or
 * {@link #setResources(Resources)}, respectively, before calling this
 * method.
 *
 * @return The deserialized object hierarchy.
 */
@Override
public Object readObject(InputStream inputStream) throws IOException, SerializationException {
    Utils.checkNull(inputStream, "inputStream");
    root = null;
    language = null;
    // Parse the XML stream
    try {
        try {
            xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
            while (xmlStreamReader.hasNext()) {
                int event = xmlStreamReader.next();
                switch(event) {
                    case XMLStreamConstants.PROCESSING_INSTRUCTION:
                        {
                            processProcessingInstruction();
                            break;
                        }
                    case XMLStreamConstants.CHARACTERS:
                        {
                            processCharacters();
                            break;
                        }
                    case XMLStreamConstants.START_ELEMENT:
                        {
                            processStartElement();
                            break;
                        }
                    case XMLStreamConstants.END_ELEMENT:
                        {
                            processEndElement();
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
        } catch (XMLStreamException exception) {
            throw new SerializationException(exception);
        }
    } catch (IOException exception) {
        logException(exception);
        throw exception;
    } catch (SerializationException exception) {
        logException(exception);
        throw exception;
    } catch (RuntimeException exception) {
        logException(exception);
        throw exception;
    }
    xmlStreamReader = null;
    // Apply the namespace bindings
    for (Attribute attribute : namespaceBindingAttributes) {
        Element elementLocal = attribute.element;
        String sourcePath = (String) attribute.value;
        NamespaceBinding.BindMapping bindMapping;
        int i = sourcePath.indexOf(BIND_MAPPING_DELIMITER);
        if (i == -1) {
            bindMapping = null;
        } else {
            String bindFunction = sourcePath.substring(0, i);
            sourcePath = sourcePath.substring(i + 1);
            bindMapping = new ScriptBindMapping(getEngineByName(language), bindFunction);
        }
        switch(elementLocal.type) {
            case INSTANCE:
            case INCLUDE:
                {
                    // Bind to <element ID>.<attribute name>
                    if (elementLocal.id == null) {
                        elementLocal.id = INTERNAL_ID_PREFIX + Integer.toString(nextID++);
                        namespace.put(elementLocal.id, elementLocal.value);
                    }
                    String targetPath = elementLocal.id + "." + attribute.name;
                    NamespaceBinding namespaceBinding = new NamespaceBinding(namespace, sourcePath, targetPath, bindMapping);
                    namespaceBinding.bind();
                    break;
                }
            case READ_ONLY_PROPERTY:
                {
                    // Bind to <parent element ID>.<element name>.<attribute name>
                    if (elementLocal.parent.id == null) {
                        elementLocal.parent.id = INTERNAL_ID_PREFIX + Integer.toString(nextID++);
                        namespace.put(elementLocal.parent.id, elementLocal.parent.value);
                    }
                    String targetPath = elementLocal.parent.id + "." + elementLocal.name + "." + attribute.name;
                    NamespaceBinding namespaceBinding = new NamespaceBinding(namespace, sourcePath, targetPath, bindMapping);
                    namespaceBinding.bind();
                    break;
                }
            default:
                {
                    break;
                }
        }
    }
    namespaceBindingAttributes.clear();
    // Bind the root to the namespace
    if (root instanceof Bindable) {
        Class<?> type = root.getClass();
        while (Bindable.class.isAssignableFrom(type)) {
            bind(root, type);
            type = type.getSuperclass();
        }
        Bindable bindable = (Bindable) root;
        bindable.initialize(namespace, location, resources);
    }
    return root;
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 38 with SerializationException

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

the class XMLSerializer method writeObject.

public void writeObject(Element element, Writer writer) throws SerializationException {
    Utils.checkNull(writer, "writer");
    Utils.checkNull(element, "element");
    XMLOutputFactory output = XMLOutputFactory.newInstance();
    try {
        XMLStreamWriter xmlStreamWriter = output.createXMLStreamWriter(writer);
        xmlStreamWriter.writeStartDocument();
        writeElement(element, xmlStreamWriter);
        xmlStreamWriter.writeEndDocument();
    } catch (XMLStreamException exception) {
        throw new SerializationException(exception);
    }
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) SerializationException(org.apache.pivot.serialization.SerializationException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter)

Example 39 with SerializationException

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

the class XMLSerializer method writeElement.

private void writeElement(Element element, XMLStreamWriter xmlStreamWriter) throws XMLStreamException, SerializationException {
    String namespacePrefix = element.getNamespacePrefix();
    String localName = element.getLocalName();
    if (namespacePrefix == null) {
        if (element.getLength() == 0) {
            xmlStreamWriter.writeEmptyElement(localName);
        } else {
            xmlStreamWriter.writeStartElement(localName);
        }
    } else {
        String namespaceURI = element.getNamespaceURI(namespacePrefix);
        if (element.getLength() == 0) {
            xmlStreamWriter.writeEmptyElement(namespacePrefix, localName, namespaceURI);
        } else {
            xmlStreamWriter.writeStartElement(namespacePrefix, localName, namespaceURI);
        }
    }
    // Write out the declared namespaces
    String defaultNamespaceURI = element.getDefaultNamespaceURI();
    if (defaultNamespaceURI != null) {
        xmlStreamWriter.writeDefaultNamespace(defaultNamespaceURI);
    }
    Element.NamespaceDictionary namespaces = element.getNamespaces();
    for (String declaredNamespacePrefix : namespaces) {
        String declaredNamespaceURI = namespaces.get(declaredNamespacePrefix);
        xmlStreamWriter.writeNamespace(declaredNamespacePrefix, declaredNamespaceURI);
    }
    // Write out the attributes
    for (Element.Attribute attribute : element.getAttributes()) {
        String attributeNamespacePrefix = attribute.getNamespacePrefix();
        String attributeLocalName = attribute.getLocalName();
        String attributeValue = attribute.getValue();
        if (attributeNamespacePrefix == null) {
            xmlStreamWriter.writeAttribute(attributeLocalName, attributeValue);
        } else {
            String attributeNamespaceURI = element.getNamespaceURI(attributeNamespacePrefix);
            xmlStreamWriter.writeAttribute(attributeNamespacePrefix, attributeNamespaceURI, attributeLocalName, attributeValue);
        }
    }
    // Write out the child nodes
    for (Node node : element) {
        if (node instanceof Element) {
            writeElement((Element) node, xmlStreamWriter);
        } else if (node instanceof TextNode) {
            writeTextNode((TextNode) node, xmlStreamWriter);
        } else {
            throw new SerializationException("Unsupported node type: " + node.getClass().getName());
        }
    }
    if (element.getLength() > 0) {
        xmlStreamWriter.writeEndElement();
    }
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException)

Example 40 with SerializationException

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

the class GraphicsUtilities method decodePaint.

/**
 * Interpret a string as a {@link Paint} value
 *
 * @param value Either (a) One of the
 * {@linkplain GraphicsUtilities#decodeColor color values recognized by
 * Pivot} or (b) A {@linkplain GraphicsUtilities#decodePaint(Dictionary)
 * JSON dictionary describing a Paint value}.
 * @return The decoded paint value.
 * @throws IllegalArgumentException if the given value is {@code null} or
 * empty or there is a problem decoding the value.
 */
public static Paint decodePaint(String value) {
    Utils.checkNullOrEmpty(value, "paint");
    Paint paint;
    if (value.startsWith("#") || value.startsWith("0x") || value.startsWith("0X")) {
        paint = decodeColor(value);
    } else {
        try {
            paint = decodePaint(JSONSerializer.parseMap(value));
        } catch (SerializationException exception) {
            throw new IllegalArgumentException(exception);
        }
    }
    return paint;
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) LinearGradientPaint(java.awt.LinearGradientPaint) RadialGradientPaint(java.awt.RadialGradientPaint) Paint(java.awt.Paint) GradientPaint(java.awt.GradientPaint)

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