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;
}
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;
}
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;
}
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();
}
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;
}
Aggregations