Exemplo n.º 1
0
 public void readFields(Object object, JsonValue jsonMap) {
   Type type = ReflectionCache.getType(object.getClass());
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   for (JsonValue child = jsonMap.child(); child != null; child = child.next()) {
     FieldMetadata metadata = fields.get(child.name());
     if (metadata == null) {
       if (ignoreUnknownFields) {
         if (debug)
           System.out.println(
               "Ignoring unknown field: " + child.name() + " (" + type.getName() + ")");
         continue;
       } else
         throw new SerializationException(
             "Field not found: " + child.name() + " (" + type.getName() + ")");
     }
     Field field = metadata.field;
     // if (entry.value == null) continue; // I don't remember what this did. :(
     try {
       field.set(object, readValue(field.getType().getClassOfType(), metadata.elementType, child));
     } catch (IllegalAccessException ex) {
       throw new SerializationException(
           "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
     } catch (SerializationException ex) {
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     } catch (RuntimeException runtimeEx) {
       SerializationException ex = new SerializationException(runtimeEx);
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     }
   }
 }
Exemplo n.º 2
0
 /** @param elementType May be null if the type is unknown. */
 public void readField(
     Object object, String fieldName, String jsonName, Class elementType, Object jsonData) {
   OrderedMap jsonMap = (OrderedMap) jsonData;
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   FieldMetadata metadata = fields.get(fieldName);
   if (metadata == null)
     throw new SerializationException(
         "Field not found: " + fieldName + " (" + type.getName() + ")");
   Field field = metadata.field;
   Object jsonValue = jsonMap.get(jsonName);
   if (jsonValue == null) return;
   if (elementType == null) elementType = metadata.elementType;
   try {
     field.set(object, readValue(field.getType(), elementType, jsonValue));
   } catch (IllegalAccessException ex) {
     throw new SerializationException(
         "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
   } catch (SerializationException ex) {
     ex.addTrace(field.getName() + " (" + type.getName() + ")");
     throw ex;
   } catch (RuntimeException runtimeEx) {
     SerializationException ex = new SerializationException(runtimeEx);
     ex.addTrace(field.getName() + " (" + type.getName() + ")");
     throw ex;
   }
 }
Exemplo n.º 3
0
 public void readFields(Object object, Object jsonData) {
   OrderedMap<String, Object> jsonMap = (OrderedMap) jsonData;
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   for (Entry<String, Object> entry : jsonMap.entries()) {
     FieldMetadata metadata = fields.get(entry.key);
     if (metadata == null) {
       if (ignoreUnknownFields) {
         if (debug)
           System.out.println(
               "Ignoring unknown field: " + entry.key + " (" + type.getName() + ")");
         continue;
       } else
         throw new SerializationException(
             "Field not found: " + entry.key + " (" + type.getName() + ")");
     }
     Field field = metadata.field;
     if (entry.value == null) continue;
     try {
       field.set(object, readValue(field.getType(), metadata.elementType, entry.value));
     } catch (IllegalAccessException ex) {
       throw new SerializationException(
           "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
     } catch (SerializationException ex) {
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     } catch (RuntimeException runtimeEx) {
       SerializationException ex = new SerializationException(runtimeEx);
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     }
   }
 }
Exemplo n.º 4
0
 /** @param elementType May be null if the type is unknown. */
 public void writeField(Object object, String fieldName, String jsonName, Class elementType) {
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   FieldMetadata metadata = fields.get(fieldName);
   if (metadata == null)
     throw new SerializationException(
         "Field not found: " + fieldName + " (" + type.getName() + ")");
   Field field = metadata.field;
   if (elementType == null) elementType = metadata.elementType;
   try {
     if (debug)
       System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
     writer.name(jsonName);
     writeValue(field.get(object), field.getType(), elementType);
   } catch (IllegalAccessException ex) {
     throw new SerializationException(
         "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
   } catch (SerializationException ex) {
     ex.addTrace(field + " (" + type.getName() + ")");
     throw ex;
   } catch (Exception runtimeEx) {
     SerializationException ex = new SerializationException(runtimeEx);
     ex.addTrace(field + " (" + type.getName() + ")");
     throw ex;
   }
 }
Exemplo n.º 5
0
 /** @throws GdxRuntimeException if the attribute was not found. */
 public String getAttribute(String name) {
   if (attributes == null)
     throw new GdxRuntimeException("Element " + this.name + " doesn't have attribute: " + name);
   String value = attributes.get(name);
   if (value == null)
     throw new GdxRuntimeException("Element " + this.name + " doesn't have attribute: " + name);
   return value;
 }
Exemplo n.º 6
0
 /**
  * Returns a new or existing pool for the specified type, stored in a a Class to {@link
  * ReflectionPool} map. The max size of the pool used is 100.
  */
 public <T> Pool<T> get(Class<T> type) {
   ReflectionPool pool = typePools.get(type);
   if (pool == null) {
     pool = new ReflectionPool(type, 4, 100);
     typePools.put(type, pool);
   }
   return pool;
 }
Exemplo n.º 7
0
 public Type getClass(String tag) {
   Type type = tagToClass.get(tag);
   if (type != null) return type;
   try {
     return ReflectionCache.forName(tag);
   } catch (ClassNotFoundException ex) {
     throw new SerializationException(ex);
   }
 }
Exemplo n.º 8
0
 /** Frees the specified objects from the {@link #get(Class) pool}. */
 public void freeAll(Array objects) {
   if (objects == null) throw new IllegalArgumentException("objects cannot be null.");
   for (int i = 0, n = objects.size; i < n; i++) {
     Object object = objects.get(i);
     ReflectionPool pool = typePools.get(object.getClass());
     if (pool == null) return; // Ignore freeing an object that was never retained.
     pool.free(object);
   }
 }
Exemplo n.º 9
0
 public Class getClass(String tag) {
   Class type = tagToClass.get(tag);
   if (type != null) return type;
   try {
     return Class.forName(tag);
   } catch (ClassNotFoundException ex) {
     throw new SerializationException(ex);
   }
 }
Exemplo n.º 10
0
 public void setElementType(Class type, String fieldName, Class elementType) {
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   FieldMetadata metadata = fields.get(fieldName);
   if (metadata == null)
     throw new SerializationException(
         "Field not found: " + fieldName + " (" + type.getName() + ")");
   metadata.elementType = elementType;
 }
Exemplo n.º 11
0
 /**
  * Returns the attribute value with the specified name, or if no attribute is found, the text of
  * a child with the name.
  *
  * @throws GdxRuntimeException if no attribute or child was not found.
  */
 public String get(String name, String defaultValue) {
   if (attributes != null) {
     String value = attributes.get(name);
     if (value != null) return value;
   }
   Element child = getChildByName(name);
   if (child == null) return defaultValue;
   String value = child.getText();
   if (value == null) return defaultValue;
   return value;
 }
Exemplo n.º 12
0
 public void writeType(Class type) {
   if (typeName == null) return;
   String className = classToTag.get(type);
   if (className == null) className = type.getName();
   try {
     writer.set(typeName, className);
   } catch (IOException ex) {
     throw new SerializationException(ex);
   }
   if (debug) System.out.println("Writing type: " + type.getName());
 }
Exemplo n.º 13
0
  private Object[] getDefaultValues(Class type) {
    if (!usePrototypes) return null;
    if (classToDefaultValues.containsKey(type)) return classToDefaultValues.get(type);
    Object object;
    try {
      object = newInstance(type);
    } catch (Exception ex) {
      classToDefaultValues.put(type, null);
      return null;
    }

    ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
    if (fields == null) fields = cacheFields(type);

    Object[] values = new Object[fields.size];
    classToDefaultValues.put(type, values);

    int i = 0;
    for (FieldMetadata metadata : fields.values()) {
      Field field = metadata.field;
      try {
        values[i++] = field.get(object);
      } catch (IllegalAccessException ex) {
        throw new SerializationException(
            "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
      } catch (SerializationException ex) {
        ex.addTrace(field + " (" + type.getName() + ")");
        throw ex;
      } catch (RuntimeException runtimeEx) {
        SerializationException ex = new SerializationException(runtimeEx);
        ex.addTrace(field + " (" + type.getName() + ")");
        throw ex;
      }
    }
    return values;
  }
Exemplo n.º 14
0
 public <T> Serializer<T> getSerializer(Class<T> type) {
   return (Serializer<T>) classToSerializer.get(ReflectionCache.getType(type));
 }
Exemplo n.º 15
0
  /**
   * @param clazz May be null if the type is unknown.
   * @param elementType May be null if the type is unknown.
   * @return May be null.
   */
  public <T> T readValue(Class<T> clazz, Class elementType, JsonValue jsonData) {
    if (jsonData == null) return null;

    Type type = ReflectionCache.getType(clazz);
    if (jsonData.isObject()) {
      String className = typeName == null ? null : jsonData.getString(typeName, null);
      if (className != null) {
        jsonData.remove(typeName);
        try {
          type = ReflectionCache.forName(className);
        } catch (ClassNotFoundException ex) {
          type = tagToClass.get(className);
          if (type == null) throw new SerializationException(ex);
        }
      }

      Object object;
      if (type != null) {
        Serializer serializer = classToSerializer.get(type);
        if (serializer != null) return (T) serializer.read(this, jsonData, type.getClassOfType());

        object = newInstance(type);

        if (object instanceof Serializable) {
          ((Serializable) object).read(this, jsonData);
          return (T) object;
        }

        if (object instanceof HashMap) {
          HashMap result = (HashMap) object;
          for (JsonValue child = jsonData.child(); child != null; child = child.next())
            result.put(child.name(), readValue(elementType, null, child));
          return (T) result;
        }
      } else object = new OrderedMap();

      if (object instanceof ObjectMap) {
        ObjectMap result = (ObjectMap) object;
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          result.put(child.name(), readValue(elementType, null, child));
        return (T) result;
      }

      readFields(object, jsonData);
      return (T) object;
    }

    if (type != null) {
      Serializer serializer = classToSerializer.get(type);
      if (serializer != null) return (T) serializer.read(this, jsonData, type.getClassOfType());
    }

    if (jsonData.isArray()) {
      if (type == null || type.isAssignableFrom(ReflectionCache.getType(Array.class))) {
        Array newArray = new Array();
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          newArray.add(readValue(elementType, null, child));
        return (T) newArray;
      }
      if (type.isAssignableFrom(ReflectionCache.getType(ArrayList.class))) {
        ArrayList newArray = new ArrayList();
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          newArray.add(readValue(elementType, null, child));
        return (T) newArray;
      }
      if (type.isArray()) {
        Class componentType = type.getComponentType();
        if (elementType == null) elementType = componentType;
        Object newArray = ReflectionCache.newArray(componentType, jsonData.size());
        Type arrayType = ReflectionCache.getType(newArray.getClass());
        int i = 0;
        for (JsonValue child = jsonData.child(); child != null; child = child.next())
          arrayType.setArrayElement(newArray, i++, readValue(elementType, null, child));
        return (T) newArray;
      }
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    Class t = type == null ? null : type.getClassOfType();
    if (jsonData.isNumber()) {
      try {
        if (type == null || t == float.class || t == Float.class)
          return (T) (Float) jsonData.asFloat();
        if (t == int.class || t == Integer.class) return (T) (Integer) jsonData.asInt();
        if (t == long.class || t == Long.class) return (T) (Long) jsonData.asLong();
        if (t == double.class || t == Double.class) return (T) (Double) (double) jsonData.asFloat();
        if (t == String.class) return (T) Float.toString(jsonData.asFloat());
        if (t == short.class || t == Short.class) return (T) (Short) (short) jsonData.asInt();
        if (t == byte.class || t == Byte.class) return (T) (Byte) (byte) jsonData.asInt();
      } catch (NumberFormatException ignored) {
      }
      jsonData = new JsonValue(jsonData.asString());
    }

    if (jsonData.isBoolean()) {
      try {
        if (type == null || t == boolean.class || t == Boolean.class)
          return (T) (Boolean) jsonData.asBoolean();
      } catch (NumberFormatException ignored) {
      }
      jsonData = new JsonValue(jsonData.asString());
    }

    if (jsonData.isString()) {
      String string = jsonData.asString();
      if (type == null || t == String.class) return (T) string;
      try {
        if (t == int.class || t == Integer.class) return (T) Integer.valueOf(string);
        if (t == float.class || t == Float.class) return (T) Float.valueOf(string);
        if (t == long.class || t == Long.class) return (T) Long.valueOf(string);
        if (t == double.class || t == Double.class) return (T) Double.valueOf(string);
        if (t == short.class || t == Short.class) return (T) Short.valueOf(string);
        if (t == byte.class || t == Byte.class) return (T) Byte.valueOf(string);
      } catch (NumberFormatException ignored) {
      }
      if (t == boolean.class || t == Boolean.class) return (T) Boolean.valueOf(string);
      if (t == char.class || t == Character.class) return (T) (Character) string.charAt(0);
      if (type.isEnum()) {
        Object[] constants = type.getEnumConstants();
        for (int i = 0, n = constants.length; i < n; i++)
          if (string.equals(constants[i].toString())) return (T) constants[i];
      }
      if (t == CharSequence.class) return (T) string;
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    return null;
  }
Exemplo n.º 16
0
  /**
   * @param value May be null.
   * @param knownType May be null if the type is unknown.
   * @param elementType May be null if the type is unknown.
   */
  public void writeValue(Object value, Class knownType, Class elementType) {
    try {
      if (value == null) {
        writer.value(null);
        return;
      }

      Class actualType = value.getClass();

      if (actualType.isPrimitive()
          || actualType == String.class
          || actualType == Integer.class
          || actualType == Boolean.class
          || actualType == Float.class
          || actualType == Long.class
          || actualType == Double.class
          || actualType == Short.class
          || actualType == Byte.class
          || actualType == Character.class) {
        writer.value(value);
        return;
      }

      if (value instanceof Serializable) {
        writeObjectStart(actualType, knownType);
        ((Serializable) value).write(this);
        writeObjectEnd();
        return;
      }

      Serializer serializer = classToSerializer.get(actualType);
      if (serializer != null) {
        serializer.write(this, value, knownType);
        return;
      }

      if (value instanceof Array) {
        if (knownType != null && actualType != knownType)
          throw new SerializationException(
              "Serialization of an Array other than the known type is not supported.\n"
                  + "Known type: "
                  + knownType
                  + "\nActual type: "
                  + actualType);
        writeArrayStart();
        Array array = (Array) value;
        for (int i = 0, n = array.size; i < n; i++) writeValue(array.get(i), elementType, null);
        writeArrayEnd();
        return;
      }

      if (value instanceof Collection) {
        if (knownType != null && actualType != knownType && actualType != ArrayList.class)
          throw new SerializationException(
              "Serialization of a Collection other than the known type is not supported.\n"
                  + "Known type: "
                  + knownType
                  + "\nActual type: "
                  + actualType);
        writeArrayStart();
        for (Object item : (Collection) value) writeValue(item, elementType, null);
        writeArrayEnd();
        return;
      }

      if (actualType.isArray()) {
        if (elementType == null) elementType = actualType.getComponentType();
        int length = java.lang.reflect.Array.getLength(value);
        writeArrayStart();
        for (int i = 0; i < length; i++)
          writeValue(java.lang.reflect.Array.get(value, i), elementType, null);
        writeArrayEnd();
        return;
      }

      if (value instanceof OrderedMap) {
        if (knownType == null) knownType = OrderedMap.class;
        writeObjectStart(actualType, knownType);
        OrderedMap map = (OrderedMap) value;
        for (Object key : map.orderedKeys()) {
          writer.name(convertToString(key));
          writeValue(map.get(key), elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (value instanceof ArrayMap) {
        if (knownType == null) knownType = ArrayMap.class;
        writeObjectStart(actualType, knownType);
        ArrayMap map = (ArrayMap) value;
        for (int i = 0, n = map.size; i < n; i++) {
          writer.name(convertToString(map.keys[i]));
          writeValue(map.values[i], elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (value instanceof ObjectMap) {
        if (knownType == null) knownType = OrderedMap.class;
        writeObjectStart(actualType, knownType);
        for (Entry entry : ((ObjectMap<?, ?>) value).entries()) {
          writer.name(convertToString(entry.key));
          writeValue(entry.value, elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (value instanceof Map) {
        if (knownType == null) knownType = OrderedMap.class;
        writeObjectStart(actualType, knownType);
        for (Map.Entry entry : ((Map<?, ?>) value).entrySet()) {
          writer.name(convertToString(entry.getKey()));
          writeValue(entry.getValue(), elementType, null);
        }
        writeObjectEnd();
        return;
      }

      if (actualType.isEnum()) {
        writer.value(value);
        return;
      }

      writeObjectStart(actualType, knownType);
      writeFields(value);
      writeObjectEnd();
    } catch (IOException ex) {
      throw new SerializationException(ex);
    }
  }
Exemplo n.º 17
0
 public String getAttribute(String name, String defaultValue) {
   if (attributes == null) return defaultValue;
   String value = attributes.get(name);
   if (value == null) return defaultValue;
   return value;
 }
Exemplo n.º 18
0
 /** Frees an object from the {@link #get(Class) pool}. */
 public void free(Object object) {
   if (object == null) throw new IllegalArgumentException("object cannot be null.");
   ReflectionPool pool = typePools.get(object.getClass());
   if (pool == null) return; // Ignore freeing an object that was never retained.
   pool.free(object);
 }
Exemplo n.º 19
0
  /**
   * @param type May be null if the type is unknown.
   * @param elementType May be null if the type is unknown.
   * @return May be null.
   */
  public <T> T readValue(Class<T> type, Class elementType, Object jsonData) {
    if (jsonData == null) return null;

    if (jsonData instanceof OrderedMap) {
      OrderedMap<String, Object> jsonMap = (OrderedMap) jsonData;

      String className = typeName == null ? null : (String) jsonMap.remove(typeName);
      if (className != null) {
        try {
          type = (Class<T>) Class.forName(className);
        } catch (ClassNotFoundException ex) {
          type = tagToClass.get(className);
          if (type == null) throw new SerializationException(ex);
        }
      }

      Object object;
      if (type != null) {
        Serializer serializer = classToSerializer.get(type);
        if (serializer != null) return (T) serializer.read(this, jsonMap, type);

        object = newInstance(type);

        if (object instanceof Serializable) {
          ((Serializable) object).read(this, jsonMap);
          return (T) object;
        }

        if (object instanceof HashMap) {
          HashMap result = (HashMap) object;
          for (Entry entry : jsonMap.entries())
            result.put(entry.key, readValue(elementType, null, entry.value));
          return (T) result;
        }
      } else object = new OrderedMap();

      if (object instanceof ObjectMap) {
        ObjectMap result = (ObjectMap) object;
        for (String key : jsonMap.orderedKeys())
          result.put(key, readValue(elementType, null, jsonMap.get(key)));
        return (T) result;
      }

      readFields(object, jsonMap);
      return (T) object;
    }

    if (type != null) {
      Serializer serializer = classToSerializer.get(type);
      if (serializer != null) return (T) serializer.read(this, jsonData, type);
    }

    if (jsonData instanceof Array) {
      Array array = (Array) jsonData;
      if (type == null || Array.class.isAssignableFrom(type)) {
        Array newArray = type == null ? new Array() : (Array) newInstance(type);
        newArray.ensureCapacity(array.size);
        for (int i = 0, n = array.size; i < n; i++)
          newArray.add(readValue(elementType, null, array.get(i)));
        return (T) newArray;
      }
      if (ArrayList.class.isAssignableFrom(type)) {
        ArrayList newArray = type == null ? new ArrayList() : (ArrayList) newInstance(type);
        newArray.ensureCapacity(array.size);
        for (int i = 0, n = array.size; i < n; i++)
          newArray.add(readValue(elementType, null, array.get(i)));
        return (T) newArray;
      }
      if (type.isArray()) {
        Class componentType = type.getComponentType();
        if (elementType == null) elementType = componentType;
        Object newArray = java.lang.reflect.Array.newInstance(componentType, array.size);
        for (int i = 0, n = array.size; i < n; i++)
          java.lang.reflect.Array.set(newArray, i, readValue(elementType, null, array.get(i)));
        return (T) newArray;
      }
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    if (jsonData instanceof Float) {
      Float floatValue = (Float) jsonData;
      try {
        if (type == null || type == float.class || type == Float.class)
          return (T) (Float) floatValue;
        if (type == int.class || type == Integer.class) return (T) (Integer) floatValue.intValue();
        if (type == long.class || type == Long.class) return (T) (Long) floatValue.longValue();
        if (type == double.class || type == Double.class)
          return (T) (Double) floatValue.doubleValue();
        if (type == short.class || type == Short.class) return (T) (Short) floatValue.shortValue();
        if (type == byte.class || type == Byte.class) return (T) (Byte) floatValue.byteValue();
      } catch (NumberFormatException ignored) {
      }
      jsonData = String.valueOf(jsonData);
    }

    if (jsonData instanceof Boolean) jsonData = String.valueOf(jsonData);

    if (jsonData instanceof String) {
      String string = (String) jsonData;
      if (type == null || type == String.class) return (T) jsonData;
      try {
        if (type == int.class || type == Integer.class) return (T) Integer.valueOf(string);
        if (type == float.class || type == Float.class) return (T) Float.valueOf(string);
        if (type == long.class || type == Long.class) return (T) Long.valueOf(string);
        if (type == double.class || type == Double.class) return (T) Double.valueOf(string);
        if (type == short.class || type == Short.class) return (T) Short.valueOf(string);
        if (type == byte.class || type == Byte.class) return (T) Byte.valueOf(string);
      } catch (NumberFormatException ignored) {
      }
      if (type == boolean.class || type == Boolean.class) return (T) Boolean.valueOf(string);
      if (type == char.class || type == Character.class) return (T) (Character) string.charAt(0);
      if (type.isEnum()) {
        Object[] constants = type.getEnumConstants();
        for (int i = 0, n = constants.length; i < n; i++)
          if (string.equals(constants[i].toString())) return (T) constants[i];
      }
      if (type == CharSequence.class) return (T) string;
      throw new SerializationException(
          "Unable to convert value to required type: " + jsonData + " (" + type.getName() + ")");
    }

    return null;
  }
Exemplo n.º 20
0
 public String getTag(Class type) {
   String tag = classToTag.get(type);
   if (tag != null) return tag;
   return type.getName();
 }
Exemplo n.º 21
0
 public <T> Serializer<T> getSerializer(Class<T> type) {
   return classToSerializer.get(type);
 }