use of org.apache.pivot.collections.Dictionary 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);
}
}
}
use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class JSONSerializerTest method testEquals.
@Test
public void testEquals() throws IOException, SerializationException {
JSONSerializer jsonSerializer = new JSONSerializer();
JSONSerializerListener jsonSerializerListener = new JSONSerializerListener() {
@Override
public void beginDictionary(JSONSerializer jsonSerializerArgument, Dictionary<String, ?> value) {
System.out.println("Begin dictionary: " + value);
}
@Override
public void endDictionary(JSONSerializer jsonSerializerArgument) {
System.out.println("End dictionary");
}
@Override
public void readKey(JSONSerializer jsonSerializerArgument, String key) {
System.out.println("Read key: " + key);
}
@Override
public void beginSequence(JSONSerializer jsonSerializerArgument, Sequence<?> value) {
System.out.println("Begin sequence: " + value);
}
@Override
public void endSequence(JSONSerializer jsonSerializerArgument) {
System.out.println("End sequence");
}
@Override
public void readString(JSONSerializer jsonSerializerArgument, String value) {
System.out.println("Read string: " + value);
}
@Override
public void readNumber(JSONSerializer jsonSerializerArgument, Number value) {
System.out.println("Read number: " + value);
}
@Override
public void readBoolean(JSONSerializer jsonSerializerArgument, Boolean value) {
System.out.println("Read boolean: " + value);
}
@Override
public void readNull(JSONSerializer jsonSerializerArgument) {
System.out.println("Read null");
}
};
jsonSerializer.getJSONSerializerListeners().add(jsonSerializerListener);
Object o1 = jsonSerializer.readObject(getClass().getResourceAsStream("map.json"));
assertEquals((Integer) JSON.get(o1, "a"), (Integer) 100);
assertEquals(JSON.get(o1, "b"), "Hello");
assertEquals(JSON.get(o1, "c"), false);
assertEquals((Integer) JSON.get(o1, "e.g"), (Integer) 5);
assertEquals((Integer) JSON.get(o1, "i.a"), (Integer) 200);
assertEquals(JSON.get(o1, "i.c"), true);
assertEquals(JSON.get(o1, "m"), "Hello\r\n\tWorld!");
jsonSerializer.getJSONSerializerListeners().remove(jsonSerializerListener);
Object o2 = jsonSerializer.readObject(getClass().getResourceAsStream("map.json"));
assertEquals((Integer) JSON.get(o2, "k[1].a"), (Integer) 10);
assertEquals((Integer) JSON.get(o2, "k[2].a"), (Integer) 100);
assertEquals((Integer) JSON.get(o2, "k[2].b"), (Integer) 200);
assertEquals(JSON.get(o2, "k[2].c"), "300");
assertEquals((Integer) JSON.get(o2, "j"), (Integer) 200);
assertEquals(JSON.get(o2, "n"), "This is a \"test\" of the 'quoting' in \\JSON\\");
assertTrue(o1.equals(o2));
List<?> d = JSON.get(o1, "d");
d.remove(0, 1);
assertFalse(o1.equals(o2));
}
use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class CSVSerializerTest method testQuotedNewlineReadObject.
@Test
public void testQuotedNewlineReadObject() throws IOException, SerializationException {
StringBuilder buf = new StringBuilder();
buf.append("a,\"b\nb \",c\r\n");
StringReader reader = new StringReader(buf.toString());
CSVSerializer serializer = new CSVSerializer();
serializer.setKeys("A", "B", "C");
List<?> result = serializer.readObject(reader);
@SuppressWarnings("unchecked") Dictionary<String, Object> row = (Dictionary<String, Object>) result.get(0);
assertEquals("a", row.get("A"));
assertEquals("b\nb", row.get("B"));
assertEquals("c", row.get("C"));
}
use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class JSON method get.
/**
* Returns the value at a given path.
*
* @param <T> The type of value to expect.
* @param root The root object.
* @param keys The path to the value as a sequence of keys.
* @return The value at the given path.
*/
@SuppressWarnings("unchecked")
public static <T> T get(Object root, Sequence<String> keys) {
Utils.checkNull(keys, "keys");
Object value = root;
for (int i = 0, n = keys.getLength(); i < n; i++) {
if (value == null) {
break;
}
String key = keys.get(i);
Map<String, T> adapter = (Map<String, T>) (value instanceof java.util.Map ? new MapAdapter<>((java.util.Map<String, T>) value) : (value instanceof Map ? ((Map<String, T>) value) : new BeanAdapter(value)));
if (adapter.containsKey(key)) {
value = adapter.get(key);
} else if (value instanceof Sequence<?>) {
Sequence<Object> sequence = (Sequence<Object>) value;
value = sequence.get(Integer.parseInt(key));
} else if (value instanceof Dictionary<?, ?>) {
Dictionary<String, Object> dictionary = (Dictionary<String, Object>) value;
value = dictionary.get(key);
} else {
throw new IllegalArgumentException("Property \"" + key + "\" not found.");
}
}
return (T) value;
}
use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class CSVSerializer method readItem.
@SuppressWarnings("unchecked")
private Object readItem(Reader reader) throws IOException, SerializationException {
Object item = null;
if (c != -1) {
// Instantiate the item
Dictionary<String, Object> itemDictionary;
try {
if (itemType instanceof ParameterizedType) {
ParameterizedType parameterizedItemType = (ParameterizedType) itemType;
Class<?> rawItemType = (Class<?>) parameterizedItemType.getRawType();
item = rawItemType.newInstance();
} else {
Class<?> classItemType = (Class<?>) itemType;
item = classItemType.newInstance();
}
if (item instanceof Dictionary<?, ?>) {
itemDictionary = (Dictionary<String, Object>) item;
} else {
itemDictionary = new BeanAdapter(item);
}
} catch (IllegalAccessException exception) {
throw new SerializationException(exception);
} catch (InstantiationException exception) {
throw new SerializationException(exception);
}
// Add values to the item
for (int i = 0, n = keys.getLength(); i < n; i++) {
String key = keys.get(i);
String value = readValue(reader);
if (value == null) {
throw new SerializationException("Error reading value for " + key + " from input stream.");
}
if (c == '\r' || c == '\n') {
if (i < n - 1) {
throw new SerializationException("Line data is incomplete.");
}
// Move to next char; if LF, move again
c = reader.read();
if (c == '\n') {
c = reader.read();
}
}
itemDictionary.put(key, value);
}
// Notify the listeners
if (csvSerializerListeners != null) {
csvSerializerListeners.readItem(this, item);
}
}
return item;
}
Aggregations