Example #1
0
 /**
  * Gets the datatype of the object.
  *
  * @param obj the object
  * @return the type
  */
 public static String getDataType(Object obj) {
   if (obj == null) {
     return null;
   }
   if (obj instanceof String) {
     return "string"; //$NON-NLS-1$
   } else if (obj instanceof Collection) {
     return "collection"; //$NON-NLS-1$
   } else if (obj.getClass().isArray()) {
     // make sure ultimate component class is acceptable
     Class componentType = obj.getClass().getComponentType();
     while (componentType.isArray()) {
       componentType = componentType.getComponentType();
     }
     String type = componentType.getName();
     if (type.indexOf(".") == -1
         && "intdoubleboolean".indexOf(type) == -1) { // $NON-NLS-1$ //$NON-NLS-2$
       return null;
     }
     return "array"; //$NON-NLS-1$
   } else if (obj instanceof Double) {
     return "double"; //$NON-NLS-1$
   } else if (obj instanceof Integer) {
     return "int"; //$NON-NLS-1$
   } else {
     return "object"; //$NON-NLS-1$
   }
 }
Example #2
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param value The value of the XML attribute containing the prop value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, String value) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)) {
      return parseBasicType(type, value);
    } else if (String.class.isAssignableFrom(type)) {
      return value;
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return parseDate(value, JOXDateHandler.determineDateFormat());
    } else {
      return null;
    }
  }
Example #3
0
 private static Object parseValue(String value, Prop p, Class type) {
   Object v = value;
   if (type.isArray()) {
     StringTokenizer st = new StringTokenizer(value, ",");
     Class ctype = type.getComponentType();
     v = Array.newInstance(ctype, st.countTokens());
     for (int i = 0; st.hasMoreTokens(); i++)
       Array.set(v, i, parseValue(st.nextToken(), p, ctype));
   } else if (type == boolean.class) {
     v = Boolean.valueOf(value);
   } else if (type == double.class) {
     v = Double.valueOf(value);
   } else if (type == int.class) {
     v = Integer.valueOf(value);
   } else if (p.field.isAnnotationPresent(TimeIntervalProp.class)) {
     if (value.endsWith("s")) {
       v = (long) (Double.parseDouble(value.substring(0, value.length() - 1)) * SEC);
     } else if (value.endsWith("m")) {
       v = (long) (Double.parseDouble(value.substring(0, value.length() - 1)) * MIN);
     } else {
       v = Long.valueOf(value);
     }
   }
   return v;
 }
Example #4
0
 public static boolean typesMatch(Class<?>[] usedTypes, Class<?>[] expectedTypes) {
   // expectedTypes is empty
   if (ArrayUtil.isEmpty(expectedTypes)) return ArrayUtil.isEmpty(usedTypes);
   Class<?> lastExpectedType = ArrayUtil.lastElementOf(expectedTypes);
   if (lastExpectedType.isArray()) {
     // process varargs parameter
     if (usedTypes.length < expectedTypes.length - 1) return false; // fault
     if (usedTypes.length == expectedTypes.length - 1)
       return typesMatch(
           usedTypes, ArrayUtil.copyOfRange(expectedTypes, 0, usedTypes.length)); // empty varargs
     // check if all used types match the varargs type
     if (usedTypes.length >= expectedTypes.length) {
       Class<?> componentType = lastExpectedType.getComponentType();
       for (int i = expectedTypes.length - 1; i < usedTypes.length; i++) {
         Class<?> foundType = usedTypes[i];
         if (!typeMatches(foundType, componentType)) return false;
       }
       return true;
     }
   }
   if (usedTypes.length != expectedTypes.length) return false;
   if (expectedTypes.length == 0 && usedTypes.length == 0) return true;
   for (int i = 0; i < usedTypes.length; i++) {
     Class<?> expectedType = expectedTypes[i];
     Class<?> foundType = usedTypes[i];
     if (!typeMatches(foundType, expectedType)) return false;
   }
   return true;
 }
Example #5
0
 static String javaSignature(Class<?> type) {
   if (!type.isArray()) {
     return type.getName();
   } else {
     int arrayDimension = 0;
     do {
       ++arrayDimension;
       type = type.getComponentType();
     } while (type.isArray());
     String name = type.getName();
     String suffix = "[]";
     if (arrayDimension == 1) {
       return name.concat(suffix);
     } else {
       int length = name.length() + arrayDimension * suffix.length();
       StringBuffer sb = new StringBuffer(length);
       sb.append(name);
       while (arrayDimension != 0) {
         --arrayDimension;
         sb.append(suffix);
       }
       return sb.toString();
     }
   }
 }
 private void putInstance(
     Class<?> parameterType, Object actualArguments, Object otherArguments, int index) {
   Object actualArgument, otherArgument;
   if (parameterType == boolean.class) {
     actualArgument = DEFAULT_BOOLEAN;
     otherArgument = OTHER_BOOLEAN;
   } else if (parameterType == byte.class) {
     actualArgument = DEFAULT_BYTE;
     otherArgument = OTHER_BYTE;
   } else if (parameterType == char.class) {
     actualArgument = DEFAULT_CHAR;
     otherArgument = OTHER_CHAR;
   } else if (parameterType == short.class) {
     actualArgument = DEFAULT_SHORT;
     otherArgument = OTHER_SHORT;
   } else if (parameterType == int.class) {
     actualArgument = DEFAULT_INT;
     otherArgument = OTHER_INT;
   } else if (parameterType == long.class) {
     actualArgument = DEFAULT_LONG;
     otherArgument = OTHER_LONG;
   } else if (parameterType == float.class) {
     actualArgument = DEFAULT_FLOAT;
     otherArgument = OTHER_FLOAT;
   } else if (parameterType == double.class) {
     actualArgument = DEFAULT_DOUBLE;
     otherArgument = OTHER_DOUBLE;
   } else if (parameterType.isEnum()) {
     Object[] enumConstants = parameterType.getEnumConstants();
     if (enumConstants.length == 1) {
       throw new IllegalArgumentException("Enum with only one constant: " + parameterType);
     }
     actualArgument = enumConstants[0];
     otherArgument = enumConstants[1];
   } else if (parameterType.isArray()) {
     actualArgument = Array.newInstance(parameterType.getComponentType(), 1);
     otherArgument = Array.newInstance(parameterType.getComponentType(), 1);
     putInstance(parameterType.getComponentType(), actualArgument, otherArgument, 0);
   } else {
     actualArgument = creator.replace(parameterType, generator, false);
     refinement.apply(actualArgument);
     otherArgument = creator.replace(parameterType, generator, true);
     refinement.apply(otherArgument);
   }
   Array.set(actualArguments, index, actualArgument);
   Array.set(otherArguments, index, otherArgument);
 }
Example #7
0
 int[] arrayDimensions(Object a_object) {
   int count = 0;
   for (Class clazz = a_object.getClass(); clazz.isArray(); clazz = clazz.getComponentType()) {
     count++;
   }
   int dim[] = new int[count];
   for (int i = 0; i < count; i++) {
     dim[i] = Array.getLength(a_object);
     a_object = Array.get(a_object, 0);
   }
   return dim;
 }
 static String jni_signature(Class c) {
   if (c == int.class) return "I";
   if (c == long.class) return "J";
   if (c == short.class) return "S";
   if (c == byte.class) return "B";
   if (c == boolean.class) return "Z";
   if (c == double.class) return "D";
   if (c == float.class) return "F";
   if (c == char.class) return "C";
   if (c == void.class) return "V";
   if (c.isArray()) return "[" + jni_signature(c.getComponentType());
   return "L" + name(c) + ";";
 }
Example #9
0
 private static int checkArray(
     Class expectedType, ArgumentsList arguments, List<LispObject> args, int argsCounter, int i) {
   Class componentType = expectedType.getComponentType();
   ArrayList<LispObject> array = new ArrayList<>();
   while (argsCounter != args.size()) {
     if (!componentType.isInstance(args.get(argsCounter)))
       throw new WrongTypeArgumentException(componentType.toString(), args.get(argsCounter));
     array.add(args.get(argsCounter));
     ++argsCounter;
   }
   arguments.setValue(i, customizeArrayList(componentType, array));
   return argsCounter;
 }
 /**
  * Parses array from given JSONArray. Supports parsing of primitive types and {@link
  * com.vk.sdk.api.model.VKApiModel} instances.
  *
  * @param array JSONArray to parse
  * @param arrayClass type of array field in class.
  * @return object to set to array field in class
  * @throws org.json.JSONException if given array have incompatible type with given field.
  */
 private static Object parseArrayViaReflection(JSONArray array, Class arrayClass)
     throws JSONException {
   Object result = Array.newInstance(arrayClass.getComponentType(), array.length());
   Class<?> subType = arrayClass.getComponentType();
   for (int i = 0; i < array.length(); i++) {
     try {
       Object item = array.opt(i);
       if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) {
         VKApiModel model = (VKApiModel) subType.newInstance();
         item = model.parse((JSONObject) item);
       }
       Array.set(result, i, item);
     } catch (InstantiationException e) {
       throw new JSONException(e.getMessage());
     } catch (IllegalAccessException e) {
       throw new JSONException(e.getMessage());
     } catch (IllegalArgumentException e) {
       throw new JSONException(e.getMessage());
     }
   }
   return result;
 }
Example #11
0
  public Document serialize(Object object, Document doc) {
    Class c = object.getClass();
    Integer id = getID(object);
    map.put(object, id);
    String mapSize = Integer.toString(map.size());

    // creating serialization objects
    Element objectElement = new Element("object");
    objectElement.setAttribute(new Attribute("class", c.getName()));
    objectElement.setAttribute(new Attribute("id", mapSize));
    doc.getRootElement().addContent(objectElement);

    if (!c.isArray()) // class is not an array
    {
      Field[] fields = c.getDeclaredFields();
      ArrayList<Element> fieldXML = serializeFields(fields, object, doc);
      for (int i = 0; i < fieldXML.size(); i++) {
        objectElement.addContent(fieldXML.get(i));
      }
    } else // class is an array
    {
      Object array = object;
      objectElement.setAttribute(new Attribute("length", Integer.toString(Array.getLength(array))));
      if (c.getComponentType().isPrimitive()) // class is array of primitives
      {
        for (int i = 0; i < Array.getLength(array); i++) {
          Element value = new Element("value");
          value.setText(Array.get(c, i).toString());
          objectElement.addContent(value);
        }
      } else // class is array of references
      {
        for (int j = 0; j < Array.getLength(array); j++) {
          Element ref = new Element("reference");
          id = getID(Array.get(c, j));
          if (id != -1) {
            ref.setText(Integer.toString(id));
          }
        }
        for (int k = 0; k < Array.getLength(array); k++) {
          serialize(Array.get(array, k), doc);
        }
      }
    }
    if (currentElement == 0) {
      referenceID = 0;
    }

    return doc;
  }
Example #12
0
  public static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception {

    Configuration[] list = admin.listConfigurations(filter);
    Encoder encoder = codec.enc().to(osw);

    Protocol p = new Protocol();
    p.version = 1;
    p.date = new Date();
    p.size = list.length;
    encoder.put(p).append('\n');

    if (list != null)
      for (Configuration c : list) {
        Dictionary<String, Object> d = c.getProperties();
        Export export = new Export();
        export.values = new HashMap<String, Object>();
        export.factoryPid = c.getFactoryPid();
        export.pid = c.getPid();

        for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
          String k = e.nextElement();
          Object v = d.get(k);

          if (!(v instanceof String)) {

            if (export.types == null) export.types = new HashMap<String, Type>();

            Type type = new Type();

            Class<?> clazz = v.getClass();
            if (v instanceof Collection) {
              Collection<?> coll = (Collection<?>) v;
              clazz = String.class;
              if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass());
              else type.vectorOf = shortName(String.class);
            } else if (v.getClass().isArray()) {
              type.arrayOf = shortName(clazz.getComponentType());
            } else type.scalar = shortName(v.getClass());

            export.types.put(k, type);
          }
          export.values.put(k, v);
        }

        encoder.mark().put(export);
        // encoder.put(encoder.digest());
        encoder.append('\n');
      }
    osw.flush();
  }
Example #13
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }
  private static Object createArgumentPlaceholder(Class<?> clazz, Integer placeholderId) {
    if (clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || Character.class == clazz)
      return getPrimitivePlaceHolder(clazz, placeholderId);

    if (clazz == String.class) return String.valueOf(placeholderId);
    if (Date.class.isAssignableFrom(clazz)) return new Date(placeholderId);
    if (clazz.isArray()) return Array.newInstance(clazz.getComponentType(), 1);

    try {
      return createArgumentPlaceholderForUnknownClass(clazz, placeholderId);
    } catch (Exception e) {
      throw new ArgumentConversionException(
          "It is not possible to create a placeholder for class: " + clazz.getName(), e);
    }
  }
Example #15
0
 private static void vis(String name, Class type, Object value, String indent) throws Exception {
   if (value == null) { // nothing interesting to say
     prt(indent + name + ": null");
   } else if (type.isPrimitive()) { // primitive
     if (type == Boolean.TYPE) prt(indent + name + ": " + ((Boolean) value).booleanValue());
     else if (type == Character.TYPE) prt(indent + name + ": " + ((Character) value).charValue());
     else if (type == Byte.TYPE) prt(indent + name + ": " + ((Byte) value).byteValue());
     else if (type == Short.TYPE) prt(indent + name + ": " + ((Short) value).shortValue());
     else if (type == Integer.TYPE) prt(indent + name + ": " + ((Integer) value).intValue());
     else if (type == Long.TYPE) prt(indent + name + ": " + ((Long) value).longValue());
     else if (type == Float.TYPE) prt(indent + name + ": " + ((Float) value).floatValue());
     else if (type == Double.TYPE) prt(indent + name + ": " + ((Double) value).doubleValue());
     else throw new IllegalArgumentException(); // NotReached
   } else if (type.isArray()) { // array
     Class componentType = type.getComponentType();
     prt(indent + name + ": " + componentType.getName() + "[]");
     for (int i = 0, n = Array.getLength(value); i < n; ++i)
       vis("" + i, componentType, Array.get(value, i), indent + "   ");
   } else if (type.getName()
       .equals("java.lang.String")) { // treat frequently used type as special case
     prt(indent + name + ": \"" + (String) value + "\"");
   } else { // class (or interface)
     Field[] fields =
         type
             .getFields(); // !!note: Sun's jvm only returns *public* fields, jx returns *all*
                           // fields
     if (fields.length == 0) { // no fields
       // prt(indent + name + ": declared as " + type.getName() + " actually is " + (value == null
       // ? "null" : value.getClass().getName()) + " self-described as \"" + value + "\"");
       prt(
           indent
               + name
               + ": declared as "
               + type.getName()
               + " actually is "
               + (value == null ? "null" : value.getClass().getName()));
     } else { // use fields to describe object
       prt(indent + name + ": " + type.getName());
       for (int i = 0, n = fields.length; i < n; ++i) {
         Field f = fields[i];
         if (Modifier.isStatic(f.getModifiers()))
           vis(f.getName(), f.getType(), f.get(value), indent + "   static ");
         else vis(f.getName(), f.getType(), f.get(value), indent + "   ");
       }
     }
   }
 }
Example #16
0
 /**
  * This method provides a readable classname if it's an array, i.e. either the classname of the
  * component type for arrays of java reference types or the name of the primitive type for arrays
  * of java primitive types. Otherwise, it returns null.
  */
 public static String getArrayClassName(String name) {
   String className = null;
   if (name.startsWith("[")) {
     int index = name.lastIndexOf("[");
     className = name.substring(index, name.length());
     if (className.startsWith("[L")) {
       className = className.substring(2, className.length() - 1);
     } else {
       try {
         Class<?> c = Class.forName(className);
         className = c.getComponentType().getName();
       } catch (ClassNotFoundException e) {
         // Should not happen
         throw new IllegalArgumentException("Bad class name " + name, e);
       }
     }
   }
   return className;
 }
Example #17
0
  public static Class<?> getActualType(Type genericType, final int pos) {

    if (genericType == null) return null;
    if (!ParameterizedType.class.isAssignableFrom(genericType.getClass())) {
      if (genericType instanceof TypeVariable)
        genericType = getType(((TypeVariable<?>) genericType).getBounds(), pos);
      else if (genericType instanceof WildcardType) {
        final WildcardType wildcardType = (WildcardType) genericType;
        Type[] bounds = wildcardType.getLowerBounds();
        if (bounds.length == 0) bounds = wildcardType.getUpperBounds();
        genericType = getType(bounds, pos);
      }

      final Class<?> cls = (Class<?>) genericType;
      return cls.isArray() ? cls.getComponentType() : cls;
    }
    final ParameterizedType paramType = (ParameterizedType) genericType;
    final Type t = getType(paramType.getActualTypeArguments(), pos);
    return t instanceof Class ? (Class<?>) t : getActualType(t, pos);
  }
Example #18
0
 private static StringBuilder appendTypeString(StringBuilder sb, Class<?> type) {
   while (type.isArray()) {
     sb.append('[');
     type = type.getComponentType();
   }
   if (type.isPrimitive()) {
     char typeLetter;
     if (type == Boolean.TYPE) {
       typeLetter = 'Z';
     } else if (type == Long.TYPE) {
       typeLetter = 'J';
     } else {
       String typeName = type.getName();
       typeLetter = Character.toUpperCase(typeName.charAt(0));
     }
     sb.append(typeLetter);
   } else {
     sb.append('L');
     sb.append(type.getName().replace('.', '/'));
     sb.append(';');
   }
   return sb;
 }
  /*
   * Non-recursive version of object descend. This consumes more memory than recursive in-depth
   * traversal but prevents stack overflows on long chains of objects
   * or complex graphs (a max. recursion depth on my machine was ~5000 objects linked in a chain
   * so not too much).
   */
  private static long measureObjectSize(Object root) {
    // Objects seen so far.
    final IdentityHashSet<Object> seen = new IdentityHashSet<Object>();
    // Class cache with reference Field and precalculated shallow size.
    final IdentityHashMap<Class<?>, ClassCache> classCache =
        new IdentityHashMap<Class<?>, ClassCache>();
    // Stack of objects pending traversal. Recursion caused stack overflows.
    final ArrayList<Object> stack = new ArrayList<Object>();
    stack.add(root);

    long totalSize = 0;
    while (!stack.isEmpty()) {
      final Object ob = stack.remove(stack.size() - 1);

      if (ob == null || seen.contains(ob)) {
        continue;
      }
      seen.add(ob);

      final Class<?> obClazz = ob.getClass();
      if (obClazz.isArray()) {
        /*
         * Consider an array, possibly of primitive types. Push any of its references to
         * the processing stack and accumulate this array's shallow size.
         */
        long size = NUM_BYTES_ARRAY_HEADER;
        final int len = Array.getLength(ob);
        if (len > 0) {
          Class<?> componentClazz = obClazz.getComponentType();
          if (componentClazz.isPrimitive()) {
            size += (long) len * primitiveSizes.get(componentClazz);
          } else {
            size += (long) NUM_BYTES_OBJECT_REF * len;

            // Push refs for traversal later.
            for (int i = len; --i >= 0; ) {
              final Object o = Array.get(ob, i);
              if (o != null && !seen.contains(o)) {
                stack.add(o);
              }
            }
          }
        }
        totalSize += alignObjectSize(size);
      } else {
        /*
         * Consider an object. Push any references it has to the processing stack
         * and accumulate this object's shallow size.
         */
        try {
          ClassCache cachedInfo = classCache.get(obClazz);
          if (cachedInfo == null) {
            classCache.put(obClazz, cachedInfo = createCacheEntry(obClazz));
          }

          for (Field f : cachedInfo.referenceFields) {
            // Fast path to eliminate redundancies.
            final Object o = f.get(ob);
            if (o != null && !seen.contains(o)) {
              stack.add(o);
            }
          }

          totalSize += cachedInfo.alignedShallowInstanceSize;
        } catch (IllegalAccessException e) {
          // this should never happen as we enabled setAccessible().
          throw new RuntimeException("Reflective field access failed?", e);
        }
      }
    }

    // Help the GC (?).
    seen.clear();
    stack.clear();
    classCache.clear();

    return totalSize;
  }
  /** Type-munging for field setting and method invocation. Conforms to LC3 specification */
  static Object coerceTypeImpl(Class<?> type, Object value) {
    if (value != null && value.getClass() == type) {
      return value;
    }

    switch (getJSTypeCode(value)) {
      case JSTYPE_NULL:
        // raise error if type.isPrimitive()
        if (type.isPrimitive()) {
          reportConversionError(value, type);
        }
        return null;

      case JSTYPE_UNDEFINED:
        if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) {
          return "undefined";
        } else {
          reportConversionError("undefined", type);
        }
        break;

      case JSTYPE_BOOLEAN:
        // Under LC3, only JS Booleans can be coerced into a Boolean value
        if (type == Boolean.TYPE
            || type == ScriptRuntime.BooleanClass
            || type == ScriptRuntime.ObjectClass) {
          return value;
        } else if (type == ScriptRuntime.StringClass) {
          return value.toString();
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_NUMBER:
        if (type == ScriptRuntime.StringClass) {
          return ScriptRuntime.toString(value);
        } else if (type == ScriptRuntime.ObjectClass) {
          return coerceToNumber(Double.TYPE, value);
        } else if ((type.isPrimitive() && type != Boolean.TYPE)
            || ScriptRuntime.NumberClass.isAssignableFrom(type)) {
          return coerceToNumber(type, value);
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_STRING:
        if (type == ScriptRuntime.StringClass || type.isInstance(value)) {
          return value;
        } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) {
          // Special case for converting a single char string to a
          // character
          // Placed here because it applies *only* to JS strings,
          // not other JS objects converted to strings
          if (((String) value).length() == 1) {
            return new Character(((String) value).charAt(0));
          } else {
            return coerceToNumber(type, value);
          }
        } else if ((type.isPrimitive() && type != Boolean.TYPE)
            || ScriptRuntime.NumberClass.isAssignableFrom(type)) {
          return coerceToNumber(type, value);
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_JAVA_CLASS:
        if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
        }

        if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) {
          return value;
        } else if (type == ScriptRuntime.StringClass) {
          return value.toString();
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_JAVA_OBJECT:
      case JSTYPE_JAVA_ARRAY:
        if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
        }
        if (type.isPrimitive()) {
          if (type == Boolean.TYPE) {
            reportConversionError(value, type);
          }
          return coerceToNumber(type, value);
        } else {
          if (type == ScriptRuntime.StringClass) {
            return value.toString();
          } else {
            if (type.isInstance(value)) {
              return value;
            } else {
              reportConversionError(value, type);
            }
          }
        }
        break;

      case JSTYPE_OBJECT:
        if (type == ScriptRuntime.StringClass) {
          return ScriptRuntime.toString(value);
        } else if (type.isPrimitive()) {
          if (type == Boolean.TYPE) {
            reportConversionError(value, type);
          }
          return coerceToNumber(type, value);
        } else if (type.isInstance(value)) {
          return value;
        } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) {
          double time = ((NativeDate) value).getJSTimeValue();
          // XXX: This will replace NaN by 0
          return new Date((long) time);
        } else if (type.isArray() && value instanceof NativeArray) {
          // Make a new java array, and coerce the JS array components
          // to the target (component) type.
          NativeArray array = (NativeArray) value;
          long length = array.getLength();
          Class<?> arrayType = type.getComponentType();
          Object Result = Array.newInstance(arrayType, (int) length);
          for (int i = 0; i < length; ++i) {
            try {
              Array.set(Result, i, coerceType(arrayType, array.get(i, array)));
            } catch (EvaluatorException ee) {
              reportConversionError(value, type);
            }
          }

          return Result;
        } else if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
          if (type.isInstance(value)) return value;
          reportConversionError(value, type);
        } else if (type.isInterface() && value instanceof Callable) {
          // Try to use function as implementation of Java interface.
          //
          // XXX: Currently only instances of ScriptableObject are
          // supported since the resulting interface proxies should
          // be reused next time conversion is made and generic
          // Callable has no storage for it. Weak references can
          // address it but for now use this restriction.
          if (value instanceof ScriptableObject) {
            ScriptableObject so = (ScriptableObject) value;
            Object key = Kit.makeHashKeyFromPair(COERCED_INTERFACE_KEY, type);
            Object old = so.getAssociatedValue(key);
            if (old != null) {
              // Function was already wrapped
              return old;
            }
            Context cx = Context.getContext();
            Object glue = InterfaceAdapter.create(cx, type, (Callable) value);
            // Store for later retrival
            glue = so.associateValue(key, glue);
            return glue;
          }
          reportConversionError(value, type);
        } else {
          reportConversionError(value, type);
        }
        break;
    }

    return value;
  }
Example #21
0
  void doTest(String name) throws Exception {
    Method m = tests.get(name);
    Method m_check = tests.get(name + "_check");
    Class[] paramTypes = m.getParameterTypes();
    Object[] params = new Object[paramTypes.length];
    Class retType = m.getReturnType();
    boolean isIntArray =
        (retType.isPrimitive() && !retType.equals(Void.TYPE))
            || (retType.equals(Void.TYPE) && paramTypes[0].getComponentType().isPrimitive())
            || (retType.isArray() && retType.getComponentType().isPrimitive());

    Args args = m.getAnnotation(Args.class);

    Object src = null;
    switch (args.src()) {
      case SMALL:
        {
          if (isIntArray) {
            src = small_int_src;
          } else {
            src = small_a_src;
          }
          break;
        }
      case LARGE:
        {
          if (isIntArray) {
            src = large_int_src;
          } else {
            src = large_a_src;
          }
          break;
        }
      case ZERO:
        {
          if (isIntArray) {
            src = zero_int_src;
          } else {
            src = zero_a_src;
          }
          break;
        }
    }

    for (int i = 0; i < 20000; i++) {
      boolean failure = false;

      int p = 0;

      if (params.length > 0) {
        if (isIntArray) {
          params[0] = ((int[]) src).clone();
        } else {
          params[0] = ((A[]) src).clone();
        }
        p++;
      }

      if (params.length > 1) {
        switch (args.dst()) {
          case NEW:
            {
              if (isIntArray) {
                params[1] = new int[((int[]) params[0]).length];
              } else {
                params[1] = new A[((A[]) params[0]).length];
              }
              p++;
              break;
            }
          case SRC:
            {
              params[1] = params[0];
              p++;
              break;
            }
          case NONE:
            break;
        }
      }

      for (int j = 0; j < args.extra_args().length; j++) {
        params[p + j] = args.extra_args()[j];
      }

      Object res = m.invoke(null, params);

      if (retType.isPrimitive() && !retType.equals(Void.TYPE)) {
        int s = (int) res;
        int sum = 0;
        int[] int_res = (int[]) src;
        for (int j = 0; j < int_res.length; j++) {
          sum += int_res[j];
        }
        failure = (s != sum);
        if (failure) {
          System.out.println("Test " + name + " failed: result = " + s + " != " + sum);
        }
      } else {
        Object dest = null;
        if (!retType.equals(Void.TYPE)) {
          dest = res;
        } else {
          dest = params[1];
        }

        if (m_check != null) {
          failure = (boolean) m_check.invoke(null, new Object[] {src, dest});
        } else {
          if (isIntArray) {
            int[] int_res = (int[]) src;
            int[] int_dest = (int[]) dest;
            for (int j = 0; j < int_res.length; j++) {
              if (int_res[j] != int_dest[j]) {
                System.out.println(
                    "Test "
                        + name
                        + " failed for "
                        + j
                        + " src["
                        + j
                        + "]="
                        + int_res[j]
                        + ", dest["
                        + j
                        + "]="
                        + int_dest[j]);
                failure = true;
              }
            }
          } else {
            Object[] object_res = (Object[]) src;
            Object[] object_dest = (Object[]) dest;
            for (int j = 0; j < object_res.length; j++) {
              if (object_res[j] != object_dest[j]) {
                System.out.println(
                    "Test "
                        + name
                        + " failed for "
                        + j
                        + " src["
                        + j
                        + "]="
                        + object_res[j]
                        + ", dest["
                        + j
                        + "]="
                        + object_dest[j]);
                failure = true;
              }
            }
          }
        }
      }

      if (failure) {
        success = false;
        break;
      }
    }
  }
Example #22
0
  public static DeepHierarchyElement[] getDeepFieldHierarchy(
      Class<?> parentClass, String field, HintContainer deepIndexHintContainer) {
    if (!MappingUtils.isDeepMapping(field)) {
      MappingUtils.throwMappingException("Field does not contain deep field delimitor");
    }

    StringTokenizer toks = new StringTokenizer(field, DozerConstants.DEEP_FIELD_DELIMITER);
    Class<?> latestClass = parentClass;
    DeepHierarchyElement[] hierarchy = new DeepHierarchyElement[toks.countTokens()];
    int index = 0;
    int hintIndex = 0;
    while (toks.hasMoreTokens()) {
      String aFieldName = toks.nextToken();
      String theFieldName = aFieldName;
      int collectionIndex = -1;

      if (aFieldName.contains("[")) {
        theFieldName = aFieldName.substring(0, aFieldName.indexOf("["));
        collectionIndex =
            Integer.parseInt(
                aFieldName.substring(aFieldName.indexOf("[") + 1, aFieldName.indexOf("]")));
      }

      PropertyDescriptor propDescriptor =
          findPropertyDescriptor(latestClass, theFieldName, deepIndexHintContainer);
      DeepHierarchyElement r = new DeepHierarchyElement(propDescriptor, collectionIndex);

      if (propDescriptor == null) {
        MappingUtils.throwMappingException(
            "Exception occurred determining deep field hierarchy for Class --> "
                + parentClass.getName()
                + ", Field --> "
                + field
                + ".  Unable to determine property descriptor for Class --> "
                + latestClass.getName()
                + ", Field Name: "
                + aFieldName);
      }

      latestClass = propDescriptor.getPropertyType();
      if (toks.hasMoreTokens()) {
        if (latestClass.isArray()) {
          latestClass = latestClass.getComponentType();
        } else if (Collection.class.isAssignableFrom(latestClass)) {
          Class<?> genericType = determineGenericsType(propDescriptor);

          if (genericType == null && deepIndexHintContainer == null) {
            MappingUtils.throwMappingException(
                "Hint(s) or Generics not specified.  Hint(s) or Generics must be specified for deep mapping with indexed field(s). Exception occurred determining deep field hierarchy for Class --> "
                    + parentClass.getName()
                    + ", Field --> "
                    + field
                    + ".  Unable to determine property descriptor for Class --> "
                    + latestClass.getName()
                    + ", Field Name: "
                    + aFieldName);
          }
          if (genericType != null) {
            latestClass = genericType;
          } else {
            latestClass = deepIndexHintContainer.getHint(hintIndex);
            hintIndex += 1;
          }
        }
      }
      hierarchy[index++] = r;
    }

    return hierarchy;
  }
Example #23
0
 public static int dimensions(Class<?> c) {
   if (c.getComponentType() != null) {
     return 1 + dimensions(c.getComponentType());
   }
   return 0;
 }
Example #24
-21
  /**
   * Returns all the classes related to <code>type</code> by a {@link Connection}
   *
   * @param type The given {@link Model} interface.
   * @return A list that contains all the models in a relationship with <code>type</code> interface.
   */
  protected List<Class> getAllReleatedClasses(Class type) {

    if (relatedClasses.containsKey(type)) return relatedClasses.get(type);

    List<Class> related = new ArrayList<Class>();
    Method[] getters = CommonStatic.getDeclaredGetters(type);

    for (Method g : getters)
      if (g.isAnnotationPresent(Connection.class)) {

        Class t = g.getReturnType();
        t = t.isArray() ? t.getComponentType() : t;

        if (!related.contains(t)) related.add(t);
      }

    relatedClasses.put(type, related);

    return related;
  }