use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class CSVSerializer method writeObject.
/**
* Writes values to a comma-separated value stream.
*
* @param items A list containing the data to write to the CSV file. List
* items must be instances of <tt>Dictionary<String, Objecti></tt>. The dictionary
* values will be written out in the order specified by the key sequence.
* @param writer The writer to which data will be written.
* @throws IOException for any errors during writing.
* @throws IllegalArgumentException for {@code null} input arguments.
*/
@SuppressWarnings("unchecked")
public void writeObject(List<?> items, Writer writer) throws IOException {
Utils.checkNull(items, "items");
Utils.checkNull(writer, "writer");
if (writeKeys) {
// Write keys as first line
for (int i = 0, n = keys.getLength(); i < n; i++) {
String key = keys.get(i);
if (i > 0) {
writer.append(",");
}
writer.append(key);
}
}
for (Object item : items) {
Dictionary<String, Object> itemDictionary;
if (item instanceof Dictionary<?, ?>) {
itemDictionary = (Dictionary<String, Object>) item;
} else {
itemDictionary = new BeanAdapter(item);
}
for (int i = 0, n = keys.getLength(); i < n; i++) {
String key = keys.get(i);
if (i > 0) {
writer.append(",");
}
Object value = itemDictionary.get(key);
if (value != null) {
String string = value.toString();
if (string.indexOf(',') >= 0 || string.indexOf('"') >= 0 || string.indexOf('\r') >= 0 || string.indexOf('\n') >= 0) {
writer.append('"');
if (string.indexOf('"') == -1) {
writer.append(string);
} else {
writer.append(string.replace("\"", "\"\""));
}
writer.append('"');
} else {
writer.append(string);
}
}
}
writer.append("\r\n");
}
writer.flush();
}
use of org.apache.pivot.collections.Dictionary 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;
}
use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class TableViewRowComparator method compare.
/**
* Compares two rows in a table view. If the column values implement
* {@link Comparable}, the {@link Comparable#compareTo(Object)} method will
* be used to compare the values. Otherwise, the values will be compared as
* strings using {@link Object#toString()}. If either value is
* <tt>null</tt>, it will be considered as less than the other value. If
* both values are <tt>null</tt>, they will be considered equal.
*/
@Override
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
int result;
TableView.SortDictionary sort = tableView.getSort();
if (sort.getLength() > 0) {
Dictionary<String, ?> row1;
if (o1 instanceof Dictionary<?, ?>) {
row1 = (Dictionary<String, ?>) o1;
} else {
row1 = new BeanAdapter(o1);
}
Dictionary<String, ?> row2;
if (o2 instanceof Dictionary<?, ?>) {
row2 = (Dictionary<String, ?>) o2;
} else {
row2 = new BeanAdapter(o2);
}
result = 0;
int n = sort.getLength();
int i = 0;
while (i < n && result == 0) {
Dictionary.Pair<String, SortDirection> pair = sort.get(i);
String columnName = pair.key;
SortDirection sortDirection = sort.get(columnName);
Object value1 = row1.get(columnName);
Object value2 = row2.get(columnName);
if (value1 == null && value2 == null) {
result = 0;
} else if (value1 == null) {
result = -1;
} else if (value2 == null) {
result = 1;
} else {
if (value1 instanceof Comparable<?>) {
result = ((Comparable<Object>) value1).compareTo(value2);
} else {
String s1 = value1.toString();
String s2 = value2.toString();
result = s1.compareTo(s2);
}
}
result *= (sortDirection == SortDirection.ASCENDING ? 1 : -1);
i++;
}
} else {
result = 0;
}
return result;
}
use of org.apache.pivot.collections.Dictionary in project pivot by apache.
the class GraphicsUtilities method decodePaint.
/**
* Interpret a dictionary as a {@link Paint} value
*
* @param dictionary A dictionary containing a key {@value #PAINT_TYPE_KEY}
* and further elements according to its value: <ul> <li><b>solid_color</b>
* - key {@value #COLOR_KEY} with value being any of the
* {@linkplain GraphicsUtilities#decodeColor color values recognized by
* Pivot}</li> <li><b>gradient</b> - keys {@value #START_X_KEY},
* {@value #START_Y_KEY}, {@value #END_X_KEY}, {@value #END_Y_KEY} (values
* are coordinates), {@value #START_COLOR_KEY}, {@value #END_COLOR_KEY}
* (values are {@linkplain GraphicsUtilities#decodeColor colors})</li>
* <li><b>linear_gradient</b> - keys {@value #START_X_KEY},
* {@value #START_Y_KEY}, {@value #END_X_KEY}, {@value #END_Y_KEY}
* (coordinates), {@value #STOPS_KEY} (a list of dictionaries with keys
* {@value #OFFSET_KEY} (a number in [0,1]) and {@value #COLOR_KEY})</li>
* <li><b>radial_gradient</b> - keys {@value #CENTER_X_KEY},
* {@value #CENTER_Y_KEY} (coordinates), {@value #RADIUS_KEY} (a number),
* {@value #STOPS_KEY} (a list of dictionaries with keys
* {@value #OFFSET_KEY} and {@value #COLOR_KEY})</li> </ul>
* @return The fully decoded paint value.
* @throws IllegalArgumentException if there is no paint type key found.
*/
public static Paint decodePaint(Dictionary<String, ?> dictionary) {
Utils.checkNull(dictionary, "paint dictionary");
String paintType = JSON.get(dictionary, PAINT_TYPE_KEY);
if (paintType == null) {
throw new IllegalArgumentException(PAINT_TYPE_KEY + " is required.");
}
Paint paint;
switch(PaintType.valueOf(paintType.toUpperCase(Locale.ENGLISH))) {
case SOLID_COLOR:
{
String color = JSON.get(dictionary, COLOR_KEY);
paint = decodeColor(color);
break;
}
case GRADIENT:
{
float startX = JSON.getFloat(dictionary, START_X_KEY);
float startY = JSON.getFloat(dictionary, START_Y_KEY);
float endX = JSON.getFloat(dictionary, END_X_KEY);
float endY = JSON.getFloat(dictionary, END_Y_KEY);
Color startColor = decodeColor((String) JSON.get(dictionary, START_COLOR_KEY));
Color endColor = decodeColor((String) JSON.get(dictionary, END_COLOR_KEY));
paint = new GradientPaint(startX, startY, startColor, endX, endY, endColor);
break;
}
case LINEAR_GRADIENT:
{
float startX = JSON.getFloat(dictionary, START_X_KEY);
float startY = JSON.getFloat(dictionary, START_Y_KEY);
float endX = JSON.getFloat(dictionary, END_X_KEY);
float endY = JSON.getFloat(dictionary, END_Y_KEY);
@SuppressWarnings("unchecked") List<Dictionary<String, ?>> stops = (List<Dictionary<String, ?>>) JSON.get(dictionary, STOPS_KEY);
int n = stops.getLength();
float[] fractions = new float[n];
Color[] colors = new Color[n];
for (int i = 0; i < n; i++) {
Dictionary<String, ?> stop = stops.get(i);
float offset = JSON.getFloat(stop, OFFSET_KEY);
fractions[i] = offset;
Color color = decodeColor((String) JSON.get(stop, COLOR_KEY));
colors[i] = color;
}
paint = new LinearGradientPaint(startX, startY, endX, endY, fractions, colors);
break;
}
case RADIAL_GRADIENT:
{
float centerX = JSON.getFloat(dictionary, CENTER_X_KEY);
float centerY = JSON.getFloat(dictionary, CENTER_Y_KEY);
float radius = JSON.getFloat(dictionary, RADIUS_KEY);
@SuppressWarnings("unchecked") List<Dictionary<String, ?>> stops = (List<Dictionary<String, ?>>) JSON.get(dictionary, STOPS_KEY);
int n = stops.getLength();
float[] fractions = new float[n];
Color[] colors = new Color[n];
for (int i = 0; i < n; i++) {
Dictionary<String, ?> stop = stops.get(i);
float offset = JSON.getFloat(stop, OFFSET_KEY);
fractions[i] = offset;
Color color = decodeColor((String) JSON.get(stop, COLOR_KEY));
colors[i] = color;
}
paint = new RadialGradientPaint(centerX, centerY, radius, fractions, colors);
break;
}
default:
{
throw new UnsupportedOperationException();
}
}
return paint;
}
Aggregations