use of org.apache.pivot.serialization.SerializationException in project pivot by apache.
the class TableView method setTableData.
/**
* Sets the table data.
*
* @param tableData A URL referring to a JSON file containing the data to be
* presented by the table view.
*/
public void setTableData(URL tableData) {
Utils.checkNull(tableData, "URL for table data");
JSONSerializer jsonSerializer = new JSONSerializer();
try {
setTableData((List<?>) jsonSerializer.readObject(tableData.openStream()));
} catch (SerializationException exception) {
throw new IllegalArgumentException(exception);
} catch (IOException exception) {
throw new IllegalArgumentException(exception);
}
}
use of org.apache.pivot.serialization.SerializationException 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.serialization.SerializationException 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;
}
use of org.apache.pivot.serialization.SerializationException in project pivot by apache.
the class JSONSerializer method readObject.
/**
* Reads data from a JSON stream.
* <p> Processes macros at this level using {@link MacroReader}.
*
* @param reader The reader from which data will be read.
* @return One of the following types, depending on the content of the stream
* and the value of {@link #getType()}:
* <ul>
* <li>pivot.collections.Dictionary</li>
* <li>pivot.collections.Sequence</li>
* <li>java.lang.String</li>
* <li>java.lang.Number</li>
* <li>java.lang.Boolean</li>
* <li><tt>null</tt></li>
* <li>A JavaBean object</li>
* </ul>
* @throws IOException for any I/O related errors while reading.
* @throws SerializationException for any formatting errors in the data.
*/
public Object readObject(Reader reader) throws IOException, SerializationException {
Utils.checkNull(reader, "reader");
// Move to the first character
LineNumberReader lineNumberReader = new LineNumberReader(reader);
MacroReader macroReader = new MacroReader(lineNumberReader);
c = macroReader.read();
// Ignore BOM (if present)
if (c == 0xFEFF) {
c = macroReader.read();
}
// Read the root value
Object object;
try {
object = readValue(macroReader, type, type.getTypeName());
} catch (SerializationException exception) {
System.err.println("An error occurred while processing input at line number " + (lineNumberReader.getLineNumber() + 1));
throw exception;
}
return object;
}
use of org.apache.pivot.serialization.SerializationException in project pivot by apache.
the class JSONSerializer method skipWhitespaceAndComments.
private void skipWhitespaceAndComments(Reader reader) throws IOException, SerializationException {
while (c != -1 && (Character.isWhitespace(c) || c == '/')) {
boolean comment = (c == '/');
// Read the next character
c = reader.read();
if (comment) {
if (c == '/') {
// Single-line comment
while (c != -1 && c != '\n' && c != '\r') {
c = reader.read();
}
} else if (c == '*') {
// Multi-line comment
boolean closed = false;
while (c != -1 && !closed) {
c = reader.read();
if (c == '*') {
c = reader.read();
closed = (c == '/');
}
}
if (!closed) {
throw new SerializationException("Unexpected end of input stream.");
}
if (c != -1) {
c = reader.read();
}
} else {
throw new SerializationException("Unexpected character in input stream: '" + (char) c + "'");
}
}
}
}
Aggregations