Search in sources :

Example 1 with Resources

use of org.apache.pivot.util.Resources in project pivot by apache.

the class ParentResourcesTest method testConstructors.

@Test
public void testConstructors() throws Exception {
    main = new Resources(parent, getClass().getName(), Charset.defaultCharset());
    testString();
    main = new Resources(parent, getClass().getName(), Charset.defaultCharset());
    testString();
    main = new Resources(parent, getClass().getName(), Locale.ENGLISH);
    testString();
    main = new Resources(parent, getClass().getName(), Locale.ENGLISH, Charset.defaultCharset());
    testString();
    main = new Resources(parent, getClass().getName(), Locale.ENGLISH, Charset.defaultCharset());
    testString();
}
Also used : Resources(org.apache.pivot.util.Resources) Test(org.junit.Test)

Example 2 with Resources

use of org.apache.pivot.util.Resources in project pivot by apache.

the class BXMLSerializer method readObject.

/**
 * Deserializes an object hierarchy from a BXML resource. <p> The location
 * of the resource is determined by a call to
 * {@link Class#getResource(String)} on the given base type, passing the
 * given resource name as an argument. If the resources is localized, the
 * base type is also used as the base name of the resource bundle.
 *
 * @param baseType The base type.
 * @param resourceName The name of the BXML resource.
 * @param localize If <tt>true</tt>, the deserialized resource will be
 * localized using the resource bundle specified by the base type.
 * Otherwise, it will not be localized, and any use of the resource
 * resolution operator will result in a serialization exception.
 * @return the top-level deserialized object.
 * @throws IllegalArgumentException for <tt>null</tt> type or resource name or if
 * the resource could not be found.
 * @throws IOException for any error reading the BXML resource.
 * @throws SerializationException for any other errors encountered deserializing the resource.
 * @see #readObject(URL, Resources)
 */
public final Object readObject(Class<?> baseType, String resourceName, boolean localize) throws IOException, SerializationException {
    Utils.checkNull(baseType, "baseType");
    Utils.checkNull(resourceName, "resourceName");
    // throw a nice error so the user knows which resource did not load
    URL locationLocal = baseType.getResource(resourceName);
    if (locationLocal == null) {
        throw new IllegalArgumentException("Could not find resource \"" + resourceName + "\".");
    }
    return readObject(locationLocal, localize ? new Resources(baseType.getName()) : null);
}
Also used : Resources(org.apache.pivot.util.Resources) URL(java.net.URL)

Example 3 with Resources

use of org.apache.pivot.util.Resources in project pivot by apache.

the class BXMLSerializer method processStartElement.

private void processStartElement() throws IOException, SerializationException {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // Initialize the page language
    if (language == null) {
        language = getDefaultLanguage();
    }
    // Get element properties
    String namespaceURI = xmlStreamReader.getNamespaceURI();
    String prefix = xmlStreamReader.getPrefix();
    // for the default namespace
    if (prefix != null && prefix.length() == 0) {
        prefix = null;
    }
    String localName = xmlStreamReader.getLocalName();
    // Determine the type and value of this element
    Element.Type elementType;
    String name;
    Class<?> propertyClass = null;
    Object value = null;
    if (prefix != null && prefix.equals(BXML_PREFIX)) {
        // The element represents a BXML operation
        if (element == null) {
            throw new SerializationException("Invalid root element.");
        }
        if (localName.equals(INCLUDE_TAG)) {
            elementType = Element.Type.INCLUDE;
        } else if (localName.equals(SCRIPT_TAG)) {
            elementType = Element.Type.SCRIPT;
        } else if (localName.equals(DEFINE_TAG)) {
            elementType = Element.Type.DEFINE;
        } else if (localName.equals(REFERENCE_TAG)) {
            elementType = Element.Type.REFERENCE;
        } else {
            throw new SerializationException("Invalid element.");
        }
        name = "<" + prefix + ":" + localName + ">";
    } else {
        if (Character.isUpperCase(localName.charAt(0))) {
            int i = localName.indexOf('.');
            if (i != -1 && Character.isLowerCase(localName.charAt(i + 1))) {
                // The element represents an attached property
                elementType = Element.Type.WRITABLE_PROPERTY;
                name = localName.substring(i + 1);
                String propertyClassName = namespaceURI + "." + localName.substring(0, i);
                try {
                    propertyClass = Class.forName(propertyClassName, true, classLoader);
                } catch (Throwable exception) {
                    throw new SerializationException(exception);
                }
            } else {
                // The element represents a typed object
                if (namespaceURI == null) {
                    throw new SerializationException("No XML namespace specified for " + localName + " tag.");
                }
                elementType = Element.Type.INSTANCE;
                name = "<" + ((prefix == null) ? "" : prefix + ":") + localName + ">";
                String className = namespaceURI + "." + localName.replace('.', '$');
                try {
                    Class<?> type = Class.forName(className, true, classLoader);
                    value = newTypedObject(type);
                } catch (Throwable exception) {
                    throw new SerializationException("Error creating a new '" + className + "' object", exception);
                }
            }
        } else {
            // The element represents a property
            if (prefix != null) {
                throw new SerializationException("Property elements cannot have a namespace prefix.");
            }
            if (element.value instanceof Dictionary<?, ?>) {
                elementType = Element.Type.WRITABLE_PROPERTY;
            } else {
                BeanAdapter beanAdapter = new BeanAdapter(element.value);
                if (beanAdapter.isReadOnly(localName)) {
                    Class<?> propertyType = beanAdapter.getType(localName);
                    if (propertyType == null) {
                        throw new SerializationException("\"" + localName + "\" is not a valid property of element " + element.name + ".");
                    }
                    if (ListenerList.class.isAssignableFrom(propertyType)) {
                        elementType = Element.Type.LISTENER_LIST_PROPERTY;
                    } else {
                        elementType = Element.Type.READ_ONLY_PROPERTY;
                        value = beanAdapter.get(localName);
                        assert (value != null) : "Read-only properties cannot be null.";
                    }
                } else {
                    elementType = Element.Type.WRITABLE_PROPERTY;
                }
            }
            name = localName;
        }
    }
    // Create the element and process the attributes
    element = new Element(element, elementType, name, propertyClass, value);
    processAttributes();
    if (elementType == Element.Type.INCLUDE) {
        // Load the include
        if (!element.properties.containsKey(INCLUDE_SRC_ATTRIBUTE)) {
            throw new SerializationException(INCLUDE_SRC_ATTRIBUTE + " attribute is required for " + BXML_PREFIX + ":" + INCLUDE_TAG + " tag.");
        }
        String src = element.properties.get(INCLUDE_SRC_ATTRIBUTE);
        if (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;
            }
        }
        Resources resourcesLocal = this.resources;
        if (element.properties.containsKey(INCLUDE_RESOURCES_ATTRIBUTE)) {
            resourcesLocal = new Resources(resourcesLocal, element.properties.get(INCLUDE_RESOURCES_ATTRIBUTE));
        }
        String mimeType = null;
        if (element.properties.containsKey(INCLUDE_MIME_TYPE_ATTRIBUTE)) {
            mimeType = element.properties.get(INCLUDE_MIME_TYPE_ATTRIBUTE);
        }
        if (mimeType == null) {
            // Get the file extension
            int i = src.lastIndexOf(".");
            if (i != -1) {
                String extension = src.substring(i + 1);
                mimeType = fileExtensions.get(extension);
            }
        }
        if (mimeType == null) {
            throw new SerializationException("Cannot determine MIME type of include \"" + src + "\".");
        }
        boolean inline = false;
        if (element.properties.containsKey(INCLUDE_INLINE_ATTRIBUTE)) {
            inline = Boolean.parseBoolean(element.properties.get(INCLUDE_INLINE_ATTRIBUTE));
        }
        // Determine an appropriate serializer to use for the include
        Class<? extends Serializer<?>> serializerClass = mimeTypes.get(mimeType);
        if (serializerClass == null) {
            throw new SerializationException("No serializer associated with MIME type " + mimeType + ".");
        }
        Serializer<?> serializer;
        try {
            serializer = newIncludeSerializer(serializerClass);
        } catch (InstantiationException exception) {
            throw new SerializationException(exception);
        } catch (IllegalAccessException exception) {
            throw new SerializationException(exception);
        }
        // Determine location from src attribute
        URL locationLocal;
        if (src.charAt(0) == SLASH_PREFIX) {
            locationLocal = classLoader.getResource(src.substring(1));
        } else {
            locationLocal = new URL(this.location, src);
        }
        // Set optional resolution properties
        if (serializer instanceof Resolvable) {
            Resolvable resolvable = (Resolvable) serializer;
            if (inline) {
                resolvable.setNamespace(namespace);
            }
            resolvable.setLocation(locationLocal);
            resolvable.setResources(resourcesLocal);
        }
        // Read the object
        try (InputStream inputStream = new BufferedInputStream(locationLocal.openStream())) {
            element.value = serializer.readObject(inputStream);
        }
    } else if (element.type == Element.Type.REFERENCE) {
        // Dereference the value
        if (!element.properties.containsKey(REFERENCE_ID_ATTRIBUTE)) {
            throw new SerializationException(REFERENCE_ID_ATTRIBUTE + " attribute is required for " + BXML_PREFIX + ":" + REFERENCE_TAG + " tag.");
        }
        String id = element.properties.get(REFERENCE_ID_ATTRIBUTE);
        if (!namespace.containsKey(id)) {
            throw new SerializationException("A value with ID \"" + id + "\" does not exist.");
        }
        element.value = namespace.get(id);
    }
    // If the element has an ID, add the value to the namespace
    if (element.id != null) {
        namespace.put(element.id, element.value);
        // If the type has an ID property, use it
        Class<?> type = element.value.getClass();
        IDProperty idProperty = type.getAnnotation(IDProperty.class);
        if (idProperty != null) {
            BeanAdapter beanAdapter = new BeanAdapter(element.value);
            beanAdapter.put(idProperty.value(), element.id);
        }
    }
}
Also used : Dictionary(org.apache.pivot.collections.Dictionary) SerializationException(org.apache.pivot.serialization.SerializationException) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) URL(java.net.URL) BufferedInputStream(java.io.BufferedInputStream) Resources(org.apache.pivot.util.Resources)

Example 4 with Resources

use of org.apache.pivot.util.Resources in project pivot by apache.

the class Localization method startup.

@Override
public void startup(Display display, Map<String, String> properties) throws Exception {
    String language = properties.get(LANGUAGE_KEY);
    Locale locale = (language == null) ? Locale.getDefault() : new Locale(language);
    Resources resources = new Resources(getClass().getName(), locale);
    Theme theme = Theme.getTheme();
    Font font = theme.getFont();
    // Search for a font that can support the sample string
    String sampleResource = (String) resources.get("firstName");
    if (font.canDisplayUpTo(sampleResource) != -1) {
        Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
        for (int i = 0; i < fonts.length; i++) {
            if (fonts[i].canDisplayUpTo(sampleResource) == -1) {
                theme.setFont(fonts[i].deriveFont(Font.PLAIN, 12));
                break;
            }
        }
    }
    BXMLSerializer bxmlSerializer = new BXMLSerializer();
    window = (Window) bxmlSerializer.readObject(Localization.class.getResource("localization.bxml"), resources);
    window.open(display);
}
Also used : Locale(java.util.Locale) Theme(org.apache.pivot.wtk.Theme) Resources(org.apache.pivot.util.Resources) Font(java.awt.Font) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer)

Example 5 with Resources

use of org.apache.pivot.util.Resources in project pivot by apache.

the class JavascriptConsoleTest method loadResources.

/**
 * Load resource files for the given classname, or if null a default will be used.
 *
 * @param className The full class name (to use as a base name), for loading resources.
 */
private void loadResources(String className) {
    try {
        // but only if not already loaded ...
        if (resources == null) {
            resources = new Resources(MAIN_CLASS_NAME, locale);
            logObject("buildResources, load resources from " + "\"" + // set a useful default
            ((className != null && className.length() > 0) ? className : MAIN_CLASS_NAME) + "\", with locale " + locale);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Resources(org.apache.pivot.util.Resources) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SerializationException(org.apache.pivot.serialization.SerializationException)

Aggregations

Resources (org.apache.pivot.util.Resources)9 BXMLSerializer (org.apache.pivot.beans.BXMLSerializer)4 URL (java.net.URL)3 Locale (java.util.Locale)3 MalformedURLException (java.net.MalformedURLException)2 SerializationException (org.apache.pivot.serialization.SerializationException)2 Font (java.awt.Font)1 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Dictionary (org.apache.pivot.collections.Dictionary)1 Theme (org.apache.pivot.wtk.Theme)1 Before (org.junit.Before)1 Test (org.junit.Test)1