src.main.java.com.dd.plist.NSObject Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dd-plist Show documentation
Show all versions of dd-plist Show documentation
This library enables Java applications to work with property lists in various formats.
Supported formats for reading and writing are OS X/iOS binary and XML property lists.
ASCII property lists are also supported.
The library also provides access to basic functions of NeXTSTEP/Cocoa classes like
NSDictionary, NSArray, etc.
/*
* plist - An open source library to parse and generate property lists
* Copyright (C) 2014 Daniel Dreibrodt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dd.plist;
import java.io.IOException;
import java.lang.reflect.*;
import java.util.*;
/**
* Abstract interface for an object contained in a property list.
* The names and functions of the various objects orient themselves towards Apple's Cocoa API.
*
* @author Daniel Dreibrodt
*/
public abstract class NSObject {
/**
* The newline character used for generating the XML output.
* This constant will be different depending on the operating system on
* which you use this library.
*/
final static String NEWLINE = System.getProperty("line.separator");
/**
* The maximum length of the text lines to be used when generating
* ASCII property lists. But this number is only a guideline it is not
* guaranteed that it will not be overstepped.
*/
final static int ASCII_LINE_LENGTH = 80;
/**
* The indentation character used for generating the XML output. This is the
* tabulator character.
*/
private final static String INDENT = "\t";
/**
* Generates the XML representation of the object (without XML headers or enclosing plist-tags).
*
* @param xml The StringBuilder onto which the XML representation is appended.
* @param level The indentation level of the object.
*/
abstract void toXML(StringBuilder xml, int level);
/**
* Assigns IDs to all the objects in this NSObject subtree.
*
* @param out The writer object that handles the binary serialization.
*/
void assignIDs(BinaryPropertyListWriter out) {
out.assignID(this);
}
/**
* Generates the binary representation of the object.
*
* @param out The output stream to serialize the object to.
* @throws java.io.IOException If an IO error occurs while writing to the stream or the object structure contains
* data that cannot be saved.
*/
abstract void toBinary(BinaryPropertyListWriter out) throws IOException;
/**
* Generates a valid XML property list including headers using this object as root.
*
* @return The XML representation of the property list including XML header and doctype information.
*/
public String toXMLPropertyList() {
StringBuilder xml = new StringBuilder("")
.append(NSObject.NEWLINE)
.append("")
.append(NSObject.NEWLINE)
.append("")
.append(NSObject.NEWLINE);
toXML(xml, 0);
xml.append(NSObject.NEWLINE).append(" ");
return xml.toString();
}
/**
* Generates the ASCII representation of this object.
* The generated ASCII representation does not end with a newline.
* Complies with the Old-Style ASCII Property Lists definition.
*
* @param ascii The StringBuilder onto which the ASCII representation is appended.
* @param level The indentation level of the object.
*/
protected abstract void toASCII(StringBuilder ascii, int level);
/**
* Generates the ASCII representation of this object in the GnuStep format.
* The generated ASCII representation does not end with a newline.
*
* @param ascii The StringBuilder onto which the ASCII representation is appended.
* @param level The indentation level of the object.
*/
protected abstract void toASCIIGnuStep(StringBuilder ascii, int level);
/**
* Helper method that adds correct indentation to the xml output.
* Calling this method will add level
number of tab characters
* to the xml
string.
*
* @param xml The string builder for the XML document.
* @param level The level of indentation.
*/
void indent(StringBuilder xml, int level) {
for (int i = 0; i < level; i++)
xml.append(INDENT);
}
/**
* Converts this NSObject into an equivalent object of the Java Runtime Environment.
*
* - NSArray objects are converted to arrays.
* - NSDictionary objects are converted to objects extending the java.util.Map class.
* - NSSet objects are converted to objects extending the java.util.Set class.
* - NSNumber objects are converted to primitive number values (int, long, double or boolean).
* - NSString objects are converted to String objects.
* - NSData objects are converted to byte arrays.
* - NSDate objects are converted to java.util.Date objects.
* - UID objects are converted to byte arrays.
*
* @return A native java object representing this NSObject's value.
*/
public Object toJavaObject() {
if(this instanceof NSArray) {
return this.deserializeArray();
} else if (this instanceof NSDictionary) {
return this.deserializeMap();
} else if(this instanceof NSSet) {
return this.deserializeSet();
} else if(this instanceof NSNumber) {
return this.deserializeNumber();
} else if(this instanceof NSString) {
return ((NSString)this).getContent();
} else if(this instanceof NSData) {
return ((NSData)this).bytes();
} else if(this instanceof NSDate) {
return ((NSDate)this).getDate();
} else if(this instanceof UID) {
return ((UID)this).getBytes();
} else {
return this;
}
}
/**
* Converts this NSObject into an object of the specified class.
* @param The target object type.
* @param clazz The target class.
* @return A new instance of the specified class, deserialized from this NSObject.
* @throws IllegalArgumentException If the specified class cannot be deserialized from this NSObject.
*/
@SuppressWarnings("unchecked")
public T toJavaObject(Class clazz) {
return (T)toJavaObject(this, clazz, null);
}
/**
* Serializes the specified object into an NSObject.
* Objects which do not have a direct type correspondence to an NSObject type will be serialized as a NSDictionary.
* The dictionary will contain the values of all publicly accessible fields and properties.
* @param object The object to serialize.
* @return A NSObject instance.
* @throws IllegalArgumentException If the specified object throws an exception while getting its properties.
*/
public static NSObject fromJavaObject(Object object) {
if (object == null) {
return null;
}
if(object instanceof NSObject) {
return (NSObject)object;
}
Class> objClass = object.getClass();
if (objClass.isArray()) {
//process []
return fromArray(object, objClass);
}
if (isSimple(objClass)) {
//process simple types
return fromSimple(object, objClass);
}
if (Set.class.isAssignableFrom(objClass)) {
//process set
return fromSet((Set>) object);
}
if (Map.class.isAssignableFrom(objClass)) {
//process Map
return fromMap((Map, ?>) object);
}
if (Collection.class.isAssignableFrom(objClass)) {
//process collection
return fromCollection((Collection>) object);
}
//process pojo
return fromPojo(object, objClass);
}
private static boolean isSimple(Class> clazz) {
return clazz.isPrimitive() ||
Number.class.isAssignableFrom(clazz) ||
Boolean.class.isAssignableFrom(clazz) ||
clazz == String.class ||
Date.class.isAssignableFrom(clazz);
}
private static Object getInstance(Class> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
throw new IllegalArgumentException("Could not instantiate class " + clazz.getSimpleName());
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not instantiate class " + clazz.getSimpleName());
}
}
private static Class> getClassForName(String className) {
int spaceIndex = className.indexOf(' ');
if(spaceIndex != -1) {
className = className.substring(spaceIndex + 1);
}
if ("double".equals(className)) {
return double.class;
}
if ("float".equals(className)) {
return float.class;
}
if ("int".equals(className)) {
return int.class;
}
if ("long".equals(className)) {
return long.class;
}
if ("short".equals(className)) {
return short.class;
}
if ("boolean".equals(className)) {
return boolean.class;
}
if ("byte".equals(className)) {
return byte.class;
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not load class " + className, e);
}
}
private static String makeFirstCharLowercase(String input) {
char[] chars = input.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
private Object toJavaObject(NSObject payload, Class> clazz, Type[] types) {
if (clazz.isArray()) {
//generics and arrays do not mix
return deserializeArray(payload, clazz);
}
if (isSimple(clazz)) {
return deserializeSimple(payload, clazz);
}
if (clazz == Object.class && !(payload instanceof NSSet || payload instanceof NSArray)) {
return deserializeSimple(payload, clazz);
}
if (payload instanceof NSSet && Collection.class.isAssignableFrom(clazz)) {
return deserializeCollection(payload, clazz, types);
}
if (payload instanceof NSArray && Collection.class.isAssignableFrom(clazz)) {
return deserializeCollection(payload, clazz, types);
}
if (payload instanceof NSDictionary) {
return deserializeObject((NSDictionary) payload, clazz, types);
}
throw new IllegalArgumentException("Cannot process " + clazz.getSimpleName());
}
private Object deserializeObject(NSDictionary payload, Class> clazz, Type[] types) {
Map map = payload.getHashMap();
if (Map.class.isAssignableFrom(clazz)) {
return deserializeMap(clazz, types, map);
}
Object result = getInstance(clazz);
Map getters = new HashMap();
Map setters = new HashMap();
for (Method method : clazz.getMethods()) {
String name = method.getName();
if (name.startsWith("get")) {
getters.put(makeFirstCharLowercase(name.substring(3)), method);
} else if (name.startsWith("set")) {
setters.put(makeFirstCharLowercase(name.substring(3)), method);
} else if (name.startsWith("is")) {
getters.put(makeFirstCharLowercase(name.substring(2)), method);
}
}
for (Map.Entry entry : map.entrySet()) {
Method setter = setters.get(makeFirstCharLowercase(entry.getKey()));
Method getter = getters.get(makeFirstCharLowercase(entry.getKey()));
if (setter != null && getter != null) {
Class> elemClass = getter.getReturnType();
Type[] elemTypes = null;
Type type = getter.getGenericReturnType();
if (type instanceof ParameterizedType) {
elemTypes = ((ParameterizedType) type).getActualTypeArguments();
}
try {
setter.invoke(result, toJavaObject(entry.getValue(), elemClass, elemTypes));
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access setter " + setter);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Could not invoke setter " + setter);
}
}
}
return result;
}
private HashMap deserializeMap() {
HashMap originalMap = ((NSDictionary)this).getHashMap();
HashMap clonedMap = new HashMap(originalMap.size());
for(String key:originalMap.keySet()) {
clonedMap.put(key, originalMap.get(key).toJavaObject());
}
return clonedMap;
}
private Object deserializeMap(Class> clazz, Type[] types, Map map) {
final Map result;
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
//fallback
result = new HashMap();
} else {
@SuppressWarnings("unchecked")
Map temp = (Map) getInstance(clazz);
result = temp;
}
Class> elemClass = Object.class;
Type[] elemParams = null;
if (types != null && types.length > 1) {
Type elemType = types[1];
if (elemType instanceof ParameterizedType) {
elemClass = getClassForName(((ParameterizedType) elemType).getRawType().toString());
elemParams = ((ParameterizedType) elemType).getActualTypeArguments();
} else {
elemClass = getClassForName(elemType.toString());
}
}
for (Map.Entry entry : map.entrySet()) {
result.put(entry.getKey(), toJavaObject(entry.getValue(), elemClass, elemParams));
}
return result;
}
private Object deserializeCollection(NSObject payload, Class> clazz, Type[] types) {
final Collection