Example #1
1
 private Object newValue(Class<?> type, String name) {
   try {
     if (type.isArray()) {
       Class<?> componentType = type.getComponentType();
       // TODO - only handles 2-dimensional arrays
       if (componentType.isArray()) {
         Object array = Array.newInstance(componentType, 1);
         Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
         return array;
       } else {
         return Array.newInstance(componentType, 0);
       }
     } else if (Collection.class.isAssignableFrom(type)) {
       return CollectionFactory.createCollection(type, 16);
     } else if (Map.class.isAssignableFrom(type)) {
       return CollectionFactory.createMap(type, 16);
     } else {
       return type.newInstance();
     }
   } catch (Exception ex) {
     // TODO Root cause exception context is lost here... should we throw another exception type
     // that preserves context instead?
     throw new NullValueInNestedPathException(
         getRootClass(),
         this.nestedPath + name,
         "Could not instantiate property type ["
             + type.getName()
             + "] to auto-grow nested property path: "
             + ex);
   }
 }
  private PropertyDescriptor findExistingPropertyDescriptor(
      String propertyName, Class<?> propertyType) {

    for (PropertyDescriptor pd : this.propertyDescriptors) {
      final Class<?> candidateType;
      final String candidateName = pd.getName();
      if (pd instanceof IndexedPropertyDescriptor) {
        IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
        candidateType = ipd.getIndexedPropertyType();
        if (candidateName.equals(propertyName)
            && (candidateType.equals(propertyType)
                || candidateType.equals(propertyType.getComponentType()))) {
          return pd;
        }
      } else {
        candidateType = pd.getPropertyType();
        if (candidateName.equals(propertyName)
            && (candidateType.equals(propertyType)
                || propertyType.equals(candidateType.getComponentType()))) {
          return pd;
        }
      }
    }
    return null;
  }
Example #3
0
  /**
   * Creates the type, it's private so you must use fromType.
   *
   * @param type
   */
  private JavaType(Type type) {

    // the type
    this.type = type;

    // parameterized?
    parameterizedType =
        ParameterizedType.class.isInstance(type) ? ParameterizedType.class.cast(type) : null;

    // generic info
    genericInfo = parameterizedType != null;

    // get class
    if (Class.class.isInstance(type)) {
      clazz = Class.class.cast(type);
    } else if (parameterizedType != null) {
      clazz = Class.class.cast(parameterizedType.getRawType());
    } else {
      clazz = null;
    }

    // component type
    if (clazz != null && clazz.getComponentType() != null) {
      componentType = clazz.getComponentType();
    }

    // instantiable
    instantiable = clazz != null;

    // typeParameters
    typeParameters = parameterizedType != null ? parameterizedType.getActualTypeArguments() : null;

    // genericInfo
    genericInfo = typeParameters != null;
  }
  private static AnnotationPropertyVal rebuild(
      String key, Class annotationClass, String valueStr, TypeResolver resolver)
      throws NoSuchMethodException {
    Method prop = annotationClass.getMethod(key);
    Class returnType = prop.getReturnType();
    Object val = decode(returnType, valueStr, resolver);
    AnnotationPropertyVal.ValType valType;
    if (returnType.isPrimitive()) {
      valType = AnnotationPropertyVal.ValType.PRIMITIVE;
    } else if (returnType.isEnum()) {
      valType = AnnotationPropertyVal.ValType.ENUMERATION;
    } else if (returnType.isArray()) {

      if (returnType.getComponentType().isEnum()) {
        valType = AnnotationPropertyVal.ValType.ENUMARRAY;
      } else if (returnType.getComponentType().isPrimitive()) {
        valType = AnnotationPropertyVal.ValType.PRIMARRAY;
      } else if (String.class.equals(returnType.getComponentType())) {
        valType = AnnotationPropertyVal.ValType.STRINGARRAY;
      } else {
        valType = AnnotationPropertyVal.ValType.CLASSARRAY;
      }

    } else if (String.class.equals(returnType)) {
      valType = AnnotationPropertyVal.ValType.STRING;
    } else {
      valType = AnnotationPropertyVal.ValType.KLASS;
    }

    AnnotationPropertyVal pv = new AnnotationPropertyVal(key, returnType, val, valType);
    return pv;
  }
Example #5
0
  /**
   * Create an array from a String
   *
   * <p>Unfortunately, this feature is very poorly documented and true UDT support by the PostGreSQL
   * JDBC driver has been postponed for a long time.
   *
   * @param string A String representation of an array
   * @return The converted array
   */
  private static Object[] pgNewArray(Class<?> type, String string) throws SQLException {
    if (string == null) {
      return null;
    }

    try {
      Class<?> component = type.getComponentType();
      String values = string.replaceAll("^\\{(.*)\\}$", "$1");

      if ("".equals(values)) {
        return (Object[]) java.lang.reflect.Array.newInstance(component, 0);
      } else {
        String[] split = values.split(",");
        Object[] result = (Object[]) java.lang.reflect.Array.newInstance(component, split.length);

        for (int i = 0; i < split.length; i++) {
          result[i] = pgFromString(type.getComponentType(), split[i]);
        }

        return result;
      }
    } catch (Exception e) {
      throw new SQLException(e);
    }
  }
Example #6
0
  /**
   * Retrieve an editor object for a given class. This method seems unable to retrieve a primitive
   * editor for obscure reasons. So better use the one based on PropertyDescriptor if possible.
   */
  public static PropertyEditor findEditor(Class<?> cls) {
    PropertyEditor editor = PropertyEditorManager.findEditor(cls);

    // Try to unwrap primitives
    if (editor == null && Primitives.isWrapperType(cls)) {
      editor = PropertyEditorManager.findEditor(Primitives.unwrap(cls));
    }

    if ((editor == null) && useDefaultGOE) {
      if (cls.isArray()) {
        Class<?> unwrapped =
            Primitives.isWrapperType(cls.getComponentType())
                ? Primitives.unwrap(cls.getComponentType())
                : cls;
        if (unwrapped.isPrimitive()) {
          editor = new ArrayEditor();
        } else {
          editor = new ObjectArrayEditor<>(unwrapped.getComponentType());
        }
      } else if (cls.isEnum()) {
        editor = new EnumEditor();
      } else {
        editor = new GenericObjectEditor();
        ((GenericObjectEditor) editor).setClassType(cls);
      }
    }
    return editor;
  }
  public ExprNode validate(ExprValidationContext validationContext) throws ExprValidationException {
    // Must have 2 child nodes
    if (this.getChildNodes().length < 1) {
      throw new IllegalStateException("Group relational op node must have 1 or more parameters");
    }
    evaluators = ExprNodeUtility.getEvaluators(this.getChildNodes());

    Class typeOne = JavaClassHelper.getBoxedType(evaluators[0].getType());

    // collections, array or map not supported
    if ((typeOne.isArray())
        || (JavaClassHelper.isImplementsInterface(typeOne, Collection.class))
        || (JavaClassHelper.isImplementsInterface(typeOne, Map.class))) {
      throw new ExprValidationException(
          "Collection or array comparison is not allowed for the IN, ANY, SOME or ALL keywords");
    }

    List<Class> comparedTypes = new ArrayList<Class>();
    comparedTypes.add(typeOne);
    hasCollectionOrArray = false;
    for (int i = 0; i < this.getChildNodes().length - 1; i++) {
      Class propType = evaluators[i + 1].getType();
      if (propType.isArray()) {
        hasCollectionOrArray = true;
        if (propType.getComponentType() != Object.class) {
          comparedTypes.add(propType.getComponentType());
        }
      } else if (JavaClassHelper.isImplementsInterface(propType, Collection.class)) {
        hasCollectionOrArray = true;
      } else if (JavaClassHelper.isImplementsInterface(propType, Map.class)) {
        hasCollectionOrArray = true;
      } else {
        comparedTypes.add(propType);
      }
    }

    // Determine common denominator type
    Class coercionType;
    try {
      coercionType =
          JavaClassHelper.getCommonCoercionType(
              comparedTypes.toArray(new Class[comparedTypes.size()]));
    } catch (CoercionException ex) {
      throw new ExprValidationException("Implicit conversion not allowed: " + ex.getMessage());
    }

    // Must be either numeric or string
    if (coercionType != String.class) {
      if (!JavaClassHelper.isNumeric(coercionType)) {
        throw new ExprValidationException(
            "Implicit conversion from datatype '"
                + coercionType.getSimpleName()
                + "' to numeric is not allowed");
      }
    }

    computer = relationalOpEnum.getComputer(coercionType, coercionType, coercionType);
    return null;
  }
Example #8
0
 /**
  * Returns an array projection of this optional value.
  *
  * @param c The class type of the array to return.
  * @return An array projection of this optional value.
  */
 @SuppressWarnings({"unchecked"})
 public Array<A> toArray(final Class<A[]> c) {
   if (isSome()) {
     final A[] a = (A[]) java.lang.reflect.Array.newInstance(c.getComponentType(), 1);
     a[0] = some();
     return array(a);
   } else return array((A[]) java.lang.reflect.Array.newInstance(c.getComponentType(), 0));
 }
 private static Object decode(Class returnType, String valueStr, TypeResolver resolver) {
   if (returnType.isArray()) {
     int sIndex = valueStr.indexOf("{");
     int eIndex = valueStr.lastIndexOf("}");
     String content = valueStr.substring(sIndex + 1, eIndex).trim();
     StringTokenizer tok = new StringTokenizer(content, ",");
     Object ar =
         java.lang.reflect.Array.newInstance(returnType.getComponentType(), tok.countTokens());
     int j = 0;
     while (tok.hasMoreElements()) {
       java.lang.reflect.Array.set(
           ar, j++, decode(returnType.getComponentType(), tok.nextToken(), resolver));
     }
     return ar;
   } else if (returnType.isEnum()) {
     try {
       String value = valueStr.trim();
       if (value.indexOf('.') > 0) {
         value = valueStr.substring(valueStr.lastIndexOf(".") + 1);
       }
       return returnType.getMethod("valueOf", String.class).invoke(null, value);
     } catch (IllegalAccessException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (InvocationTargetException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (NoSuchMethodException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     }
   } else if (String.class.equals(returnType)) {
     return unquote(valueStr);
   } else if (boolean.class.equals(returnType)) {
     return Boolean.valueOf(valueStr);
   } else if (int.class.equals(returnType)) {
     return Integer.valueOf(valueStr);
   } else if (double.class.equals(returnType)) {
     return Double.valueOf(valueStr);
   } else if (long.class.equals(returnType)) {
     return Long.valueOf(valueStr);
   } else if (float.class.equals(returnType)) {
     return Float.valueOf(valueStr);
   } else if (short.class.equals(returnType)) {
     return Short.valueOf(valueStr);
   } else if (char.class.equals(returnType)) {
     return unquote(valueStr).charAt(0);
   } else if (Class.class.equals(returnType)) {
     try {
       String cName = valueStr.trim().replace(".class", "");
       return resolver.resolveType(cName);
     } catch (ClassNotFoundException cnfe) {
       cnfe.printStackTrace();
       return Object.class;
     }
   }
   return null;
 }
  /**
   * Transform an primitive array to an object array.
   *
   * @param arr the array.
   * @return an array.
   */
  private static Object toArray(Object arr) {

    if (arr == null) {
      return arr;
    }

    Class cls = arr.getClass();
    if (!cls.isArray()) {
      return arr;
    }

    Class compType = cls.getComponentType();
    int dim = 1;
    while (!compType.isPrimitive()) {
      if (!compType.isArray()) {
        return arr;
      } else {
        dim++;
        compType = compType.getComponentType();
      }
    }

    int[] length = new int[dim];
    length[0] = Array.getLength(arr);
    Object[] newarr = null;

    try {
      if (compType.equals(Integer.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Integer"), length);
      } else if (compType.equals(Double.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Double"), length);
      } else if (compType.equals(Long.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Long"), length);
      } else if (compType.equals(Float.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Float"), length);
      } else if (compType.equals(Short.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Short"), length);
      } else if (compType.equals(Byte.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Byte"), length);
      } else if (compType.equals(Character.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Character"), length);
      } else if (compType.equals(Boolean.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Boolean"), length);
      }
    } catch (ClassNotFoundException ex) {
      System.out.println(ex);
    }

    for (int i = 0; i < length[0]; i++) {
      if (dim != 1) {
        newarr[i] = toArray(Array.get(arr, i));
      } else {
        newarr[i] = Array.get(arr, i);
      }
    }
    return newarr;
  }
Example #11
0
  public String toString(Object object) {
    if (object == null) {
      return "null";
    }
    if (visited.contains(object)) {
      return "...";
    }
    visited.add(object);
    Class clazz = object.getClass();
    if (clazz == String.class) {
      return (String) object;
    }
    if (clazz.isArray()) {
      String r = clazz.getComponentType() + "[]{";
      for (int i = 0; i < Array.getLength(object); i++) {
        if (i > 0) {
          r += ",";
        }
        Object val = Array.get(object, i);
        if (clazz.getComponentType().isPrimitive()) {
          r += val;
        } else {
          r += toString(val);
        }
      }
      return r + "}";
    }

    String r = clazz.getName();
    do {
      r += "[";
      Field[] fields = clazz.getDeclaredFields();
      AccessibleObject.setAccessible(fields, true);
      for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
          if (!r.endsWith("[")) {
            r += ",";
          }
          r += field.getName() + "=";
          try {
            Class t = field.getType();
            Object val = field.get(object);
            if (t.isPrimitive()) {
              r += val;
            } else {
              r += toString(val);
            }
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
        }
      }
      r += "]";
      clazz = clazz.getSuperclass();
    } while (clazz != null);
    return r;
  }
 public static void main(String[] args) {
   System.out.println(String[][].class.getName());
   System.out.println(Object[][].class.getName());
   Class s2Class = int[][].class;
   System.out.println(s2Class.getComponentType());
   ;
   System.out.println(s2Class.getComponentType().getComponentType());
   ;
   System.out.print(s2Class.getComponentType().getComponentType().isArray());
 }
 static Coercion getCoercion(Class c) {
   Coercion co = (Coercion) COERCIONS.get(c);
   if (co != null) {
     return co;
   }
   if (c.isArray()) {
     Class typ = c.getComponentType();
     co = new ArrayCoercion(c.getComponentType());
   } else {
     co = new ObjectCoercion(c);
   }
   COERCIONS.put(c, co);
   return co;
 }
 private ArrayValueCommand makeArray(Class<?> type, Object value) throws SerializationException {
   ArrayValueCommand toReturn = new ArrayValueCommand(type.getComponentType());
   identityMap.put(value, toReturn);
   for (int i = 0, j = Array.getLength(value); i < j; i++) {
     Object arrayValue = Array.get(value, i);
     if (arrayValue == null) {
       toReturn.add(NullValueCommand.INSTANCE);
     } else {
       Class<? extends Object> valueType =
           type.getComponentType().isPrimitive() ? type.getComponentType() : arrayValue.getClass();
       toReturn.add(makeValue(valueType, arrayValue));
     }
   }
   return toReturn;
 }
Example #15
0
  public static Object stringToArray(String s, Class parameterType, Object[] context) {
    // FIXED: regression... byte array handling is 'special'... or... "originally handled before
    // arrays"?
    if (parameterType.equals(byte[].class)) {
      return stringToBasicObject(s, parameterType, context);
    }

    // NB: CSV seems to be the most common for command-line flags
    // NB: ...but this is *also* called for each array argument.
    // e.g. "do-something --with=a,b,c --but-not=d,e,f other arguments here"
    // TODO: support "literal" arrays, like "['a','b','c']", or a better parsing mechanic (JSON?).
    final String[] args = s.split(",");

    final Class componentType = parameterType.getComponentType();

    final Object retval = Array.newInstance(componentType, args.length);

    int i = 0;

    for (String arg : args) {
      Array.set(retval, i, stringToBasicObject(arg, componentType, context));
      i++;
    }

    return retval;
  }
Example #16
0
 public TypeWrapper(Class c) throws IntrospectionException {
   Map<String, Field> fields = new HashMap();
   loadFields(c, fields);
   BeanInfo bi = Introspector.getBeanInfo(c, Object.class);
   PropertyDescriptor[] props = bi.getPropertyDescriptors();
   for (int i = 0; i < props.length; i++) {
     PropertyDescriptor pd = props[i];
     Annotation[] ann = null;
     Field f = fields.get(pd.getName());
     if (f != null) {
       f.getAnnotations();
     }
     Class type = pd.getPropertyType();
     boolean arrayFlag = type.isArray();
     PropertyInfo pi =
         new PropertyInfo(
             pd.getName(),
             ann,
             (arrayFlag ? type.getComponentType() : type),
             arrayFlag,
             pd.getReadMethod(),
             pd.getWriteMethod());
     this.properties.put(pi.getName(), pi);
   }
 }
Example #17
0
  private static String printTypeName(Class<?> type) {
    // Primitives
    //
    if (type.equals(Integer.TYPE)) {
      return "int";
    } else if (type.equals(Long.TYPE)) {
      return "long";
    } else if (type.equals(Short.TYPE)) {
      return "short";
    } else if (type.equals(Byte.TYPE)) {
      return "byte";
    } else if (type.equals(Character.TYPE)) {
      return "char";
    } else if (type.equals(Boolean.TYPE)) {
      return "boolean";
    } else if (type.equals(Float.TYPE)) {
      return "float";
    } else if (type.equals(Double.TYPE)) {
      return "double";
    }

    // Arrays
    //
    if (type.isArray()) {
      Class<?> componentType = type.getComponentType();
      return printTypeName(componentType) + "[]";
    }

    // Everything else
    //
    return type.getName().replace('$', '.');
  }
 /** Method used by {@link TypeParser} when generics-aware version is constructed. */
 protected JavaType _fromParameterizedClass(Class<?> clz, List<JavaType> paramTypes) {
   if (clz.isArray()) { // ignore generics (should never have any)
     return ArrayType.construct(_fromType(clz.getComponentType(), null));
   }
   if (clz.isEnum()) { // ditto for enums
     return new SimpleType(clz);
   }
   if (Map.class.isAssignableFrom(clz)) {
     // First: if we do have param types, use them
     JavaType keyType, contentType;
     if (paramTypes.size() > 0) {
       keyType = paramTypes.get(0);
       contentType = (paramTypes.size() >= 2) ? paramTypes.get(1) : _unknownType();
       return MapType.construct(clz, keyType, contentType);
     }
     return _mapType(clz);
   }
   if (Collection.class.isAssignableFrom(clz)) {
     if (paramTypes.size() >= 1) {
       return CollectionType.construct(clz, paramTypes.get(0));
     }
     return _collectionType(clz);
   }
   if (paramTypes.size() == 0) {
     return new SimpleType(clz);
   }
   JavaType[] pt = paramTypes.toArray(new JavaType[paramTypes.size()]);
   return _constructSimple(clz, pt);
 }
 /**
  * Add class to class import list
  *
  * @param cl
  */
 private void addImportClass(Class<?> cl) {
   if (cl.isArray()) {
     cl = cl.getComponentType();
   }
   if (cl.isPrimitive()) return;
   addImportClass(cl.getCanonicalName());
 }
Example #20
0
File: Exps.java Project: sunyh/nutz
  public static SqlExpression create(String name, String op, Object value) {
    op = Strings.trim(op.toUpperCase());

    // NULL
    if (null == value) {
      SqlExpression re;
      // IS NULL
      if ("IS".equals(op) || "NOT IS".equals(op) || "IS NOT".equals(op)) {
        re = isNull(name);
      }
      // !!!
      else {
        throw Lang.makeThrow("null can only use 'IS' or 'NOT IS'");
      }
      return re.setNot(op.startsWith("NOT") || op.endsWith("NOT"));
    }
    // IN
    else if ("IN".equals(op) || "NOT IN".equals(op)) {
      Class<?> type = value.getClass();
      SqlExpression re;
      // 数组
      if (type.isArray()) {
        re = _evalRange((Mirror<?>) Mirror.me(type.getComponentType()), name, value);
      }
      // 集合
      else if (Collection.class.isAssignableFrom(type)) {
        Object first = Lang.first(value);
        if (null == first) return null;
        re = _evalRange((Mirror<?>) Mirror.me(first), name, value);
      }
      // Sql Range
      else {
        re = inSql(name, value.toString());
      }
      return re.setNot(op.startsWith("NOT"));
    }
    // LIKE || IS
    else if ("LIKE".equals(op) || "NOT LIKEs".equals(op)) {
      String v = value.toString();
      Like re;
      if (v.length() == 1) {
        re = like(name, v);
      } else {
        re = like(name, v.substring(1, v.length() - 1));
        re.left(v.substring(0, 1));
        re.right(v.substring(v.length() - 1, v.length()));
      }
      return re.ignoreCase(false).setNot(op.startsWith("NOT"));
    }
    // =
    else if ("=".equals(op)) {
      return eq(name, value);
    }
    // !=
    else if ("!=".equals(op) || "<>".equals(op)) { // TODO 检查一下,原本是&&, 明显永远成立
      return eq(name, value).setNot(true);
    }
    // Others
    return new SimpleExpression(name, op, value);
  }
Example #21
0
 /** @return if the class represents an array of immutable values. */
 private boolean isArrayOfImmutableTypes(Class<?> clazz) {
   if (!clazz.isArray()) {
     return false;
   }
   Class<?> component = clazz.getComponentType();
   return component.isPrimitive() || isImmutable(component);
 }
Example #22
0
 private boolean parametersMatchParameterList(Class<?>[] prmTypes, String[][] parameters) {
   int ndx = 0;
   while (ndx < prmTypes.length) {
     Class<?> prmType = prmTypes[ndx];
     if (ndx >= parameters.length) {
       return ndx == prmTypes.length - 1 && prmType.isArray();
     }
     if (ndx == prmTypes.length - 1
         && prmType.isArray()) { // Assume this only occurs for functions with var args
       Class<?> varArgClass = prmType.getComponentType();
       while (ndx < parameters.length) {
         Class<?> prmClass = resolver.resolveClass(parameters[ndx][0]);
         if (!varArgClass.isAssignableFrom(prmClass)) {
           return false;
         }
         ndx++;
       }
     } else {
       Class<?> prmClass = resolver.resolveClass(parameters[ndx][0]);
       if (!prmTypes[ndx].isAssignableFrom(prmClass)) {
         return false;
       }
     }
     ndx++;
   }
   return true;
 }
 /**
  * Set the value of a parameter using an object; use the java.lang equivalent objects for integral
  * values.
  *
  * <p>The JDBC specification specifies a standard mapping from Java Object types to SQL types. The
  * given argument java object will be converted to the corresponding SQL type before being sent to
  * the database.
  *
  * <p>Note that this method may be used to pass datatabase specific abstract data types, by using
  * a Driver specific Java type.
  *
  * @param parameterIndex The first parameter is 1, the second is 2, ...
  * @param x The object containing the input parameter value
  * @exception SQLException if a database-access error occurs.
  */
 public void setObject(int parameterIndex, Object x) throws SQLException {
   if (x == null) {
     setNull(parameterIndex, java.sql.Types.VARCHAR);
   } else if (x instanceof java.lang.String) {
     setString(parameterIndex, (String) x);
   } else if (x instanceof java.math.BigDecimal) {
     setBigDecimal(parameterIndex, (BigDecimal) x);
   } else if (x instanceof java.lang.Integer) {
     setInt(parameterIndex, ((Number) x).intValue());
   } else if (x instanceof java.lang.Long) {
     setLong(parameterIndex, ((Number) x).longValue());
   } else if (x instanceof java.lang.Byte) {
     setByte(parameterIndex, ((Number) x).byteValue());
   } else if (x instanceof java.lang.Short) {
     setShort(parameterIndex, ((Number) x).shortValue());
   } else if (x instanceof java.lang.Boolean) {
     setBoolean(parameterIndex, ((Boolean) x).booleanValue());
   } else if (x instanceof java.lang.Double) {
     setDouble(parameterIndex, ((Number) x).doubleValue());
   } else if (x instanceof java.lang.Float) {
     setFloat(parameterIndex, ((Number) x).floatValue());
   } else if (x instanceof java.sql.Date) {
     setDate(parameterIndex, (java.sql.Date) x);
   } else if (x instanceof java.util.Date) {
     setTimestamp(parameterIndex, new Timestamp(((java.util.Date) x).getTime()));
   } else {
     Class c = x.getClass();
     if (c.isArray() && c.getComponentType().equals(byte.class)) {
       setBytes(parameterIndex, (byte[]) x);
     } else {
       throw new SQLException("Not implemented");
     }
   }
 }
Example #24
0
 /**
  * Return a method handle that takes the indicated number of typed arguments and returns an array
  * of them. The type argument is the array type.
  */
 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
   Class<?> elemType = arrayType.getComponentType();
   if (elemType == null) throw new IllegalArgumentException("not an array: " + arrayType);
   // FIXME: Need more special casing and caching here.
   if (nargs >= MAX_JVM_ARITY / 2 - 1) {
     int slots = nargs;
     final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1; // 1 for receiver MH
     if (arrayType == double[].class || arrayType == long[].class) slots *= 2;
     if (slots > MAX_ARRAY_SLOTS)
       throw new IllegalArgumentException(
           "too many arguments: " + arrayType.getSimpleName() + ", length " + nargs);
   }
   if (elemType == Object.class) return varargsArray(nargs);
   // other cases:  primitive arrays, subtypes of Object[]
   MethodHandle cache[] = TYPED_COLLECTORS.get(elemType);
   MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
   if (mh != null) return mh;
   if (elemType.isPrimitive()) {
     MethodHandle builder = FILL_NEW_ARRAY;
     MethodHandle producer = buildArrayProducer(arrayType);
     mh = buildVarargsArray(builder, producer, nargs);
   } else {
     @SuppressWarnings("unchecked")
     Class<? extends Object[]> objArrayType = (Class<? extends Object[]>) arrayType;
     Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType);
     MethodHandle builder = FILL_NEW_TYPED_ARRAY.bindTo(example);
     MethodHandle producer = ARRAY_IDENTITY;
     mh = buildVarargsArray(builder, producer, nargs);
   }
   mh =
       mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)));
   assert (assertCorrectArity(mh, nargs));
   if (nargs < cache.length) cache[nargs] = mh;
   return mh;
 }
Example #25
0
  public static long[] getLongValues(Object value, long[] defaultValue) {
    Class<?> clazz = value.getClass();

    if (clazz.isArray()) {
      Class<?> componentType = clazz.getComponentType();

      if (componentType.isAssignableFrom(String.class)) {
        return getLongValues((String[]) value, defaultValue);
      } else if (componentType.isAssignableFrom(Long.class)) {
        return (long[]) value;
      } else if (Number.class.isAssignableFrom(componentType)) {
        Number[] numbers = (Number[]) value;

        long[] values = new long[numbers.length];

        for (int i = 0; i < values.length; i++) {
          values[i] = numbers[i].longValue();
        }

        return values;
      }
    }

    return defaultValue;
  }
Example #26
0
 public static Object convertArrayElements(Class<?> arrayType, Object array) {
   Class<?> src = array.getClass().getComponentType();
   Class<?> dst = arrayType.getComponentType();
   if (src == null || dst == null) throw new IllegalArgumentException("not array type");
   Wrapper sw = (src.isPrimitive() ? Wrapper.forPrimitiveType(src) : null);
   Wrapper dw = (dst.isPrimitive() ? Wrapper.forPrimitiveType(dst) : null);
   int length;
   if (sw == null) {
     Object[] a = (Object[]) array;
     length = a.length;
     if (dw == null) return Arrays.copyOf(a, length, arrayType.asSubclass(Object[].class));
     Object res = dw.makeArray(length);
     dw.copyArrayUnboxing(a, 0, res, 0, length);
     return res;
   }
   length = j86.java.lang.reflect.Array.getLength(array);
   Object[] res;
   if (dw == null) {
     res = Arrays.copyOf(NO_ARGS_ARRAY, length, arrayType.asSubclass(Object[].class));
   } else {
     res = new Object[length];
   }
   sw.copyArrayBoxing(array, 0, res, 0, length);
   if (dw == null) return res;
   Object a = dw.makeArray(length);
   dw.copyArrayUnboxing(res, 0, a, 0, length);
   return a;
 }
Example #27
0
  /** Try and convert an object to a List. */
  private List<?> toList(Object o) {
    Class<?> c = o.getClass();
    if (!c.isArray()) {
      return null;
    }

    if (c.getComponentType().isPrimitive()) {
      if (o instanceof boolean[]) {
        return Arrays.asList(ArrayUtils.toObject((boolean[]) o));
      } else if (o instanceof byte[]) {
        return Arrays.asList(ArrayUtils.toObject((byte[]) o));
      } else if (o instanceof short[]) {
        return Arrays.asList(ArrayUtils.toObject((short[]) o));
      } else if (o instanceof int[]) {
        return Arrays.asList(ArrayUtils.toObject((int[]) o));
      } else if (o instanceof long[]) {
        return Arrays.asList(ArrayUtils.toObject((long[]) o));
      } else if (o instanceof float[]) {
        return Arrays.asList(ArrayUtils.toObject((float[]) o));
      } else if (o instanceof double[]) {
        return Arrays.asList(ArrayUtils.toObject((double[]) o));
      } else if (o instanceof char[]) {
        return Arrays.asList(ArrayUtils.toObject((char[]) o));
      } else {
        throw new RuntimeException("Unhandled primitive type");
      }
    } else {
      return Arrays.asList((Object[]) o);
    }
  }
Example #28
0
  /** Filters out hidden elements. */
  private static Object filterHidden(Object o, Class<?> expected) {
    if (o == null) {
      return null;
    }

    Class<?> type = o.getClass();
    if (type.getName().startsWith("com.sun.")) {
      // TODO: Implement interfaces from superclasses, too.
      return Proxy.newProxyInstance(
          type.getClassLoader(), type.getInterfaces(), new HideHandler(o));
    } else if (o instanceof Object[]) {
      Class<?> componentType = expected.getComponentType();
      Object[] array = (Object[]) o;
      List<Object> list = new ArrayList<Object>(array.length);
      for (Object entry : array) {
        if ((entry instanceof Doc) && isHidden((Doc) entry)) {
          continue;
        }
        list.add(filterHidden(entry, componentType));
      }
      return list.toArray((Object[]) Array.newInstance(componentType, list.size()));
    } else {
      return o;
    }
  }
Example #29
0
  /**
   * Returns the component types of the given type. Returns <code>null</code> if given type does not
   * have a single component type. For example the following types all have the component-type
   * MyClass:
   *
   * <ul>
   *   <li>MyClass[]
   *   <li>List&lt;MyClass&gt;
   *   <li>Foo&lt;? extends MyClass&gt;
   *   <li>Bar&lt;? super MyClass&gt;
   *   <li>&lt;T extends MyClass&gt; T[]
   * </ul>
   */
  public static Class[] getComponentTypes(Type type, Class implClass) {
    if (type instanceof Class) {
      Class clazz = (Class) type;
      if (clazz.isArray()) {
        return new Class[] {clazz.getComponentType()};
      }
    } else if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;

      Type[] generics = pt.getActualTypeArguments();

      if (generics.length == 0) {
        return null;
      }

      Class[] types = new Class[generics.length];

      for (int i = 0; i < generics.length; i++) {
        types[i] = getRawType(generics[i], implClass);
      }
      return types;
    } else if (type instanceof GenericArrayType) {
      GenericArrayType gat = (GenericArrayType) type;

      Class rawType = getRawType(gat.getGenericComponentType(), implClass);
      if (rawType == null) {
        return null;
      }

      return new Class[] {rawType};
    }
    return null;
  }
 /**
  * Writes the messages which have been set in the model
  *
  * <p>If messages stored in the model is in the form of a class that extends {@code Iterable} or
  * an Array, {@link #writeMessage(TagWriter, Object)} is called multiple times, to write<br>
  * {@link #innerElement} and messages.<br>
  * If there is only a single message, this method calls {@link #writeMessage(TagWriter, Object)}
  * only once
  *
  * @param tagWriter a TegWriter instance
  * @param messages messages
  * @throws JspException If {@link JspException} occurs in caller writeMessage
  */
 protected void writeMessages(TagWriter tagWriter, Object messages) throws JspException {
   Class<?> clazz = messages.getClass();
   if (Iterable.class.isAssignableFrom(clazz)) {
     Iterable<?> col = (Iterable<?>) messages;
     for (Object message : col) {
       writeMessage(tagWriter, message);
     }
   } else if (clazz.isArray()) {
     Class<?> type = clazz.getComponentType();
     if (Object.class.isAssignableFrom(type)) {
       Object[] arr = (Object[]) messages;
       for (Object message : arr) {
         writeMessage(tagWriter, message);
       }
     } else {
       int len = Array.getLength(messages);
       for (int i = 0; i < len; i++) {
         Object message = Array.get(messages, i);
         writeMessage(tagWriter, message);
       }
     }
   } else {
     writeMessage(tagWriter, messages);
   }
 }