예제 #1
0
 private static int checkSingleArgument(
     String subroutineName,
     Class expectedType,
     ArgumentsList arguments,
     List<LispObject> args,
     int argsCounter,
     int i) {
   try {
     if (!(expectedType.isInstance(args.get(argsCounter)))) {
       if (expectedType.equals(LispList.class)
           && args.get(argsCounter).equals(LispSymbol.ourNil)) {
         arguments.setValue(i, LispList.list());
         return argsCounter + 1;
       }
       if (expectedType.equals(LispSymbol.class)
           && args.get(argsCounter).equals(LispSymbol.ourNil)) {
         arguments.setValue(i, LispSymbol.ourNil);
         return argsCounter + 1;
       }
       if (arguments.isOptional(i)) return -1;
       throw new WrongTypeArgumentException(expectedType.getSimpleName(), args.get(argsCounter));
     }
     arguments.setValue(i, args.get(argsCounter));
     return argsCounter + 1;
   } catch (IndexOutOfBoundsException e) {
     if (arguments.isOptional(i)) return -1;
     throw new WrongNumberOfArgumentsException(subroutineName, i);
   }
 }
예제 #2
0
 private static boolean typeMatches(Class<?> foundType, Class<?> expectedType) {
   if (foundType == null) return true;
   if (expectedType.isAssignableFrom(foundType)) return true;
   if (isPrimitiveType(expectedType.getName())
       && foundType.equals(getWrapper(expectedType.getName()))) return true;
   if (isPrimitiveType(foundType.getName())
       && expectedType.equals(getWrapper(foundType.getName()))) return true;
   if (isNumberType(foundType) && isNumberType(expectedType)) return true;
   return false;
 }
예제 #3
0
  /**
   * Method to resolve a TypeVariable to its most <a
   * href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#112582">reifiable</a>
   * form.
   *
   * <p>How to resolve a TypeVariable:<br>
   * All of the TypeVariables defined by a generic class will be given a Type by any class that
   * extends it. The Type given may or may not be reifiable; it may be another TypeVariable for
   * instance.
   *
   * <p>Consider <br>
   * <i>class Pair&gt;A,B> { A getA(){...}; ...}</i><br>
   * <i>class StringLongPair extends Pair&gt;String, Long> { }</i><br>
   * To resolve the actual return type of Pair.getA() you must first resolve the TypeVariable "A".
   * We can do that by first finding the index of "A" in the Pair.class.getTypeParameters() array of
   * TypeVariables.
   *
   * <p>To get to the Type provided by StringLongPair you access the generics information by calling
   * StringLongPair.class.getGenericSuperclass; this will be a ParameterizedType. ParameterizedType
   * gives you access to the actual type arguments provided to Pair by StringLongPair. The array is
   * in the same order as the array in Pair.class.getTypeParameters so you can use the index we
   * discovered earlier to extract the Type; String.class.
   *
   * <p>When extracting Types we only have to consider the superclass hierarchy and not the
   * interfaces implemented by the class. When a class implements a generic interface it must
   * provide types for the interface and any generic methods implemented from the interface will be
   * re-defined by the class with its generic type variables.
   *
   * @param typeVariable - the type variable to resolve.
   * @param containingType - the shallowest class in the class hierarchy (furthest from Object)
   *     where typeVariable is defined.
   * @return a Type that has had all possible TypeVariables resolved that have been defined between
   *     the type variable declaration and the containingType.
   */
  private static Type resolve(TypeVariable typeVariable, Type containingType) {
    // The generic declaration is either a Class, Method or Constructor
    final GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();

    if (!(genericDeclaration instanceof Class)) {
      // It's a method or constructor. The best we can do here is try to resolve the bounds
      // e.g. <T extends E> T getT(T param){} where E is defined by the class.
      final Type bounds0 = typeVariable.getBounds()[0];
      return resolve(bounds0, containingType);
    }

    final Class typeVariableOwner = (Class) genericDeclaration;

    // find the typeOwner in the containingType's hierarchy
    final LinkedList<Type> stack = new LinkedList<Type>();

    // If you pass a List<Long> as the containingType then the TypeVariable is going to be resolved
    // by the
    // containingType and not the super class.
    if (containingType instanceof ParameterizedType) {
      stack.add(containingType);
    }

    Class theClass = asClass(containingType);
    Type genericSuperclass = theClass.getGenericSuperclass();
    while (genericSuperclass != null
        && // true for interfaces with no superclass
        !theClass.equals(Object.class)
        && !theClass.equals(typeVariableOwner)) {
      stack.addFirst(genericSuperclass);
      theClass = asClass(genericSuperclass);
      genericSuperclass = theClass.getGenericSuperclass();
    }

    int i = getTypeVariableIndex(typeVariable);
    Type resolved = typeVariable;
    for (Type t : stack) {
      if (t instanceof ParameterizedType) {
        resolved = ((ParameterizedType) t).getActualTypeArguments()[i];
        if (resolved instanceof Class) return resolved;
        if (resolved instanceof TypeVariable) {
          // Need to look at the next class in the hierarchy
          i = getTypeVariableIndex((TypeVariable) resolved);
          continue;
        }
        return resolve(resolved, containingType);
      }
    }

    // the only way we get here is if resolved is still a TypeVariable, otherwise an
    // exception is thrown or a value is returned.
    return ((TypeVariable) resolved).getBounds()[0];
  }
예제 #4
0
  /**
   * Generates a method called "super$methodName()" which can be called from JavaScript that is
   * equivalent to calling "super.methodName()" from Java. Eventually, this may be supported
   * directly in JavaScript.
   */
  private static void generateSuper(
      ClassFileWriter cfw,
      String genName,
      String superName,
      String methodName,
      String methodSignature,
      Class<?>[] parms,
      Class<?> returnType) {
    cfw.startMethod("super$" + methodName, methodSignature, ClassFileWriter.ACC_PUBLIC);

    // push "this"
    cfw.add(ByteCode.ALOAD, 0);

    // push the rest of the parameters.
    int paramOffset = 1;
    for (Class<?> parm : parms) {
      paramOffset += generatePushParam(cfw, paramOffset, parm);
    }

    // call the superclass implementation of the method.
    cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, methodName, methodSignature);

    // now, handle the return type appropriately.
    Class<?> retType = returnType;
    if (!retType.equals(Void.TYPE)) {
      generatePopResult(cfw, retType);
    } else {
      cfw.add(ByteCode.RETURN);
    }
    cfw.stopMethod((short) (paramOffset + 1));
  }
예제 #5
0
    public void addGetter(MetaBeanProperty property) throws Exception {
      MetaMethod getter = property.getGetter();

      // GENERATE private boolean <prop>Set;

      String flagName = String.format("%sSet", property.getName());
      visitor.visitField(
          Opcodes.ACC_PRIVATE, flagName, Type.BOOLEAN_TYPE.getDescriptor(), null, null);

      addConventionGetter(getter.getName(), flagName, property);

      String getterName = getter.getName();
      Class<?> returnType = getter.getReturnType();

      // If it's a boolean property, there can be get or is type variants.
      // If this class has both, decorate both.
      if (returnType.equals(Boolean.TYPE)) {
        boolean getterIsIsMethod = getterName.startsWith("is");
        String propertyNameComponent = getterName.substring(getterIsIsMethod ? 2 : 3);
        String alternativeGetterName =
            String.format("%s%s", getterIsIsMethod ? "get" : "is", propertyNameComponent);

        try {
          type.getMethod(alternativeGetterName);
          addConventionGetter(alternativeGetterName, flagName, property);
        } catch (NoSuchMethodException e) {
          // ignore, no method to override
        }
      }
    }
예제 #6
0
  /**
   * Do a recursive find and replace of objects pointed to by this object.
   *
   * @since v1.0
   * @param objectText is the canonical string representation of the object that we want to replace.
   * @param replacement is the object that we want to replace it with.
   * @param matchSubstring a boolean which tells if we should match a substring of the target object
   *     A replacement will occur if a portion of the structure is found with matching encoded text
   *     (a substring if matchSubstring is true) as objectText and with the same class as
   *     replacement.
   */
  public void replace(String objectText, GenericObject replacement, boolean matchSubstring)
      throws IllegalArgumentException {
    if (objectText == null || replacement == null) {
      throw new IllegalArgumentException("null argument!");
    }
    Class replacementClass = replacement.getClass();
    Class myclass = getClass();
    Field[] fields = myclass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
      Field f = fields[i];
      Class fieldType = f.getType();
      if (!getClassFromName(SIP_PACKAGE + ".GenericObject").isAssignableFrom(fieldType)
          && !getClassFromName(SIP_PACKAGE + ".GenericObjectList").isAssignableFrom(fieldType)) {
        continue;
      } else if ((f.getModifiers() & Modifier.PRIVATE) == Modifier.PRIVATE) {
        continue;
      }

      try {
        if (fieldType.equals(replacementClass)) {

          if (GenericObject.isMySubclass(replacementClass)) {
            GenericObject obj = (GenericObject) f.get(this);
            if (!matchSubstring) {
              if (objectText.compareTo(obj.encode()) == 0) {
                f.set(this, replacement);
              }
            } else {
              // Substring match is specified
              if (obj.encode().indexOf(objectText) >= 0) {
                f.set(this, replacement);
              }
            }
          }
        } else if (GenericObjectList.isMySubclass(replacementClass)) {
          GenericObjectList obj = (GenericObjectList) f.get(this);
          if (!matchSubstring) {
            if (objectText.compareTo(obj.encode()) == 0) {
              f.set(this, replacement);
            }
          } else {
            if (obj.encode().indexOf(objectText) >= 0) {
              f.set(this, replacement);
            }
          }
        } else if (getClassFromName(SIP_PACKAGE + ".GenericObject").isAssignableFrom(fieldType)) {
          GenericObject g = (GenericObject) f.get(this);
          g.replace(objectText, replacement, matchSubstring);
        } else if (getClassFromName(SIP_PACKAGE + ".GenericObjectList")
            .isAssignableFrom(fieldType)) {
          GenericObjectList g = (GenericObjectList) f.get(this);
          g.replace(objectText, replacement, matchSubstring);
        }
      } catch (IllegalAccessException ex) {
        InternalErrorHandler.handleException(ex);
      }
    }
  }
예제 #7
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;
    }
  }
예제 #8
0
  /**
   * @param methodName getter method
   * @param clazz value object class
   * @return attribute name related to the specified getter method
   */
  private String getAttributeName(String methodName, Class classType) {
    String attributeName = null;
    if (methodName.startsWith("is"))
      attributeName =
          methodName.substring(2, 3).toLowerCase()
              + (methodName.length() > 3 ? methodName.substring(3) : "");
    else
      attributeName =
          methodName.substring(3, 4).toLowerCase()
              + (methodName.length() > 4 ? methodName.substring(4) : "");

    // an attribute name "Xxxx" becomes "xxxx" and this is not correct!
    try {
      Class c = classType;
      boolean attributeFound = false;
      while (!c.equals(Object.class)) {
        try {
          c.getDeclaredField(attributeName);
          attributeFound = true;
          break;
        } catch (Throwable ex2) {
          c = c.getSuperclass();
        }
      }
      if (!attributeFound) {
        // now trying to find an attribute having the first character in upper case (e.g. "Xxxx")
        String name = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
        c = classType;
        while (!c.equals(Object.class)) {
          try {
            c.getDeclaredField(name);
            attributeFound = true;
            break;
          } catch (Throwable ex2) {
            c = c.getSuperclass();
          }
        }
        if (attributeFound) attributeName = name;
      }
    } catch (Throwable ex1) {
    }

    return attributeName;
  }
예제 #9
0
 /**
  * Find the class for the projection
  *
  * @param proj projection
  * @return corresponding ProjectionClass (or null if not found)
  */
 private ProjectionClass findProjectionClass(Projection proj) {
   Class want = proj.getClass();
   ComboBoxModel projClassList = projClassCB.getModel();
   for (int i = 0; i < projClassList.getSize(); i++) {
     ProjectionClass pc = (ProjectionClass) projClassList.getElementAt(i);
     if (want.equals(pc.projClass)) {
       return pc;
     }
   }
   return null;
 }
 private Object convertCollectionInternal(
     Class<?> collectionClass,
     Type targetElementType,
     Iterable<?> sourceObject,
     Action<? super SourceObjectMapping> mapping) {
   Collection<Object> convertedElements = collectionMapper.createEmptyCollection(collectionClass);
   convertCollectionInternal(convertedElements, targetElementType, sourceObject, mapping);
   if (collectionClass.equals(DomainObjectSet.class)) {
     return new ImmutableDomainObjectSet(convertedElements);
   } else {
     return convertedElements;
   }
 }
예제 #11
0
파일: Types.java 프로젝트: khushnood/grapht
  /**
   * Return the type distance between the child and parent types. The child type must be a subtype
   * of the parent. The type distance between a class and itself is 0; the distance from a class to
   * one of its immediate supertypes (superclass or a directly implemented interface) is 1; deeper
   * distances are computed recursively.
   *
   * @param child The child type
   * @param parent The parent type
   * @return The type distance
   * @throws IllegalArgumentException if {@code child} is not a subtype of {@code parent}.
   */
  public static int getTypeDistance(@Nonnull Class<?> child, @Nonnull Class<?> parent) {
    Preconditions.notNull("child class", child);
    Preconditions.notNull("parent class", parent);

    if (child.equals(parent)) {
      // fast-path same-class tests
      return 0;
    } else if (!parent.isAssignableFrom(child)) {
      // if child does not extend from the parent, return -1
      throw new IllegalArgumentException("child not a subclass of parent");
    } else if (!parent.isInterface()) {
      // if the parent is not an interface, we only need to follower superclasses
      int distance = 0;
      Class<?> cur = child;
      while (!cur.equals(parent)) {
        distance++;
        cur = cur.getSuperclass();
      }
      return distance;
    } else {
      // worst case, recursively compute the type
      // recursion is safe, as types aren't too deep except in crazy-land
      int minDepth = Integer.MAX_VALUE;
      Class<?> sup = child.getSuperclass();
      if (sup != null && parent.isAssignableFrom(sup)) {
        minDepth = getTypeDistance(sup, parent);
      }
      for (Class<?> iface : child.getInterfaces()) {
        if (parent.isAssignableFrom(iface)) {
          int d = getTypeDistance(iface, parent);
          if (d < minDepth) {
            minDepth = d;
          }
        }
      }
      // minDepth now holds the depth of the superclass with shallowest depth
      return minDepth + 1;
    }
  }
예제 #12
0
 public static <C, I> Type[] getGenericInterfaceParams(
     Class<C> checkedClass, Class<I> searchedInterface) {
   for (Type type : checkedClass.getGenericInterfaces()) {
     ParameterizedType pt = (ParameterizedType) type;
     if (searchedInterface.equals(pt.getRawType())) {
       ParameterizedType pType = ((ParameterizedType) type);
       return pType.getActualTypeArguments();
     }
   }
   if (!Object.class.equals(checkedClass.getSuperclass()))
     return getGenericInterfaceParams(checkedClass.getSuperclass(), searchedInterface);
   throw new ConfigurationError(
       checkedClass
           + " does not implement interface with generic parameters: "
           + searchedInterface);
 }
예제 #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());
      }
    }
  }
예제 #14
0
    @Override
    public boolean matches(Type type, Annotations annotations) {
      Class<?> tc = getTypeClass(this.type);
      Class<?> typec = getTypeClass(type);
      if (tc == typec || tc.equals(typec)) {
        return true;
      }

      if ((type == Long.TYPE && Pointer.class.isAssignableFrom(tc))
          || (Pointer.class.isAssignableFrom(typec) && tc == Long.TYPE)) {
        return true;
      }

      return equivalentTypes(
          type,
          typec,
          annotations,
          this.type,
          tc,
          null); // TODO isAssignableFrom or the opposite, depending on context
    }
예제 #15
0
  /**
   * Reads an string into a basic type
   *
   * @param type The type of the string to read
   * @param str The string containing the value
   * @return The parsed value of the string
   */
  public static Object parseBasicType(Class type, String str) {
    // Parse the text based on the property type

    if (type.equals(Integer.TYPE) || Integer.class.isAssignableFrom(type)) {
      return new Integer(str);
    } else if (type.equals(Long.TYPE) || Long.class.isAssignableFrom(type)) {
      return new Long(str);
    } else if (type.equals(Short.TYPE) || Short.class.isAssignableFrom(type)) {
      return new Short(str);
    } else if (type.equals(Byte.TYPE) || Byte.class.isAssignableFrom(type)) {
      return new Byte(str);
    } else if (type.equals(Boolean.TYPE) || Boolean.class.isAssignableFrom(type)) {
      return new Boolean(str);
    } else if (type.equals(Float.TYPE) || Float.class.isAssignableFrom(type)) {
      return new Float(str);
    } else if (type.equals(Double.TYPE) || Double.class.isAssignableFrom(type)) {
      return new Double(str);
    }

    return null;
  }
예제 #16
0
  @SuppressWarnings("unchecked")
  LDAPObjectHandler(final Class<T> type) throws LDAPPersistException {
    this.type = type;

    final Class<? super T> superclassType = type.getSuperclass();
    if (superclassType == null) {
      superclassHandler = null;
    } else {
      final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class);
      if (superclassAnnotation == null) {
        superclassHandler = null;
      } else {
        superclassHandler = new LDAPObjectHandler(superclassType);
      }
    }

    final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>();
    final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>();
    final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>();

    ldapObject = type.getAnnotation(LDAPObject.class);
    if (ldapObject == null) {
      throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName()));
    }

    final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10);

    final String oc = ldapObject.structuralClass();
    if (oc.length() == 0) {
      structuralClass = getUnqualifiedClassName(type);
    } else {
      structuralClass = oc;
    }

    final StringBuilder invalidReason = new StringBuilder();
    if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) {
      objectClasses.put(toLowerCase(structuralClass), structuralClass);
    } else {
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get(
              type.getName(), structuralClass, invalidReason.toString()));
    }

    auxiliaryClasses = ldapObject.auxiliaryClass();
    for (final String auxiliaryClass : auxiliaryClasses) {
      if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) {
        objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass);
      } else {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get(
                type.getName(), auxiliaryClass, invalidReason.toString()));
      }
    }

    superiorClasses = ldapObject.superiorClass();
    for (final String superiorClass : superiorClasses) {
      if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) {
        objectClasses.put(toLowerCase(superiorClass), superiorClass);
      } else {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get(
                type.getName(), superiorClass, invalidReason.toString()));
      }
    }

    if (superclassHandler != null) {
      for (final String s : superclassHandler.objectClassAttribute.getValues()) {
        objectClasses.put(toLowerCase(s), s);
      }
    }

    objectClassAttribute = new Attribute("objectClass", objectClasses.values());

    final String parentDNStr = ldapObject.defaultParentDN();
    try {
      defaultParentDN = new DN(parentDNStr);
    } catch (LDAPException le) {
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get(
              type.getName(), parentDNStr, le.getMessage()),
          le);
    }

    final String postDecodeMethodName = ldapObject.postDecodeMethod();
    if (postDecodeMethodName.length() > 0) {
      try {
        postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName);
        postDecodeMethod.setAccessible(true);
      } catch (Exception e) {
        debugException(e);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get(
                type.getName(), postDecodeMethodName, getExceptionMessage(e)),
            e);
      }
    } else {
      postDecodeMethod = null;
    }

    final String postEncodeMethodName = ldapObject.postEncodeMethod();
    if (postEncodeMethodName.length() > 0) {
      try {
        postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class);
        postEncodeMethod.setAccessible(true);
      } catch (Exception e) {
        debugException(e);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get(
                type.getName(), postEncodeMethodName, getExceptionMessage(e)),
            e);
      }
    } else {
      postEncodeMethod = null;
    }

    try {
      constructor = type.getDeclaredConstructor();
      constructor.setAccessible(true);
    } catch (Exception e) {
      debugException(e);
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e);
    }

    Field tmpDNField = null;
    Field tmpEntryField = null;
    final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>();
    for (final Field f : type.getDeclaredFields()) {
      final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class);
      final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class);
      final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class);

      if (fieldAnnotation != null) {
        f.setAccessible(true);

        final FieldInfo fieldInfo = new FieldInfo(f, type);
        final String attrName = toLowerCase(fieldInfo.getAttributeName());
        if (fields.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName()));
        } else {
          fields.put(attrName, fieldInfo);
        }

        switch (fieldInfo.getFilterUsage()) {
          case REQUIRED:
            tmpRFilterFields.add(fieldInfo);
            break;
          case ALWAYS_ALLOWED:
            tmpAAFilterFields.add(fieldInfo);
            break;
          case CONDITIONALLY_ALLOWED:
            tmpCAFilterFields.add(fieldInfo);
            break;
          case EXCLUDED:
          default:
            break;
        }

        if (fieldInfo.includeInRDN()) {
          tmpRDNFields.add(fieldInfo);
        }
      }

      if (dnFieldAnnotation != null) {
        f.setAccessible(true);

        if (fieldAnnotation != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get(
                  type.getName(), "LDAPField", "LDAPDNField", f.getName()));
        }

        if (tmpDNField != null) {
          throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName()));
        }

        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName()));
        } else if (Modifier.isStatic(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName()));
        }

        final Class<?> fieldType = f.getType();
        if (fieldType.equals(String.class)) {
          tmpDNField = f;
        } else {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get(
                  type.getName(), f.getName(), fieldType.getName()));
        }
      }

      if (entryFieldAnnotation != null) {
        f.setAccessible(true);

        if (fieldAnnotation != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get(
                  type.getName(), "LDAPField", "LDAPEntryField", f.getName()));
        }

        if (tmpEntryField != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName()));
        }

        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName()));
        } else if (Modifier.isStatic(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName()));
        }

        final Class<?> fieldType = f.getType();
        if (fieldType.equals(ReadOnlyEntry.class)) {
          tmpEntryField = f;
        } else {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get(
                  type.getName(), f.getName(), fieldType.getName()));
        }
      }
    }

    dnField = tmpDNField;
    entryField = tmpEntryField;
    requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields);
    alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields);
    conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields);
    rdnFields = Collections.unmodifiableList(tmpRDNFields);

    final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>();
    for (final Method m : type.getDeclaredMethods()) {
      final LDAPGetter getter = m.getAnnotation(LDAPGetter.class);
      final LDAPSetter setter = m.getAnnotation(LDAPSetter.class);

      if (getter != null) {
        m.setAccessible(true);

        if (setter != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get(
                  type.getName(), "LDAPGetter", "LDAPSetter", m.getName()));
        }

        final GetterInfo methodInfo = new GetterInfo(m, type);
        final String attrName = toLowerCase(methodInfo.getAttributeName());
        if (fields.containsKey(attrName) || getters.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName()));
        } else {
          getters.put(attrName, methodInfo);
        }

        switch (methodInfo.getFilterUsage()) {
          case REQUIRED:
            tmpRFilterGetters.add(methodInfo);
            break;
          case ALWAYS_ALLOWED:
            tmpAAFilterGetters.add(methodInfo);
            break;
          case CONDITIONALLY_ALLOWED:
            tmpCAFilterGetters.add(methodInfo);
            break;
          case EXCLUDED:
          default:
            // No action required.
            break;
        }

        if (methodInfo.includeInRDN()) {
          tmpRDNGetters.add(methodInfo);
        }
      }

      if (setter != null) {
        m.setAccessible(true);

        final SetterInfo methodInfo = new SetterInfo(m, type);
        final String attrName = toLowerCase(methodInfo.getAttributeName());
        if (fields.containsKey(attrName) || setters.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName()));
        } else {
          setters.put(attrName, methodInfo);
        }
      }
    }

    requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters);
    alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters);
    conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters);

    rdnGetters = Collections.unmodifiableList(tmpRDNGetters);
    if (rdnFields.isEmpty() && rdnGetters.isEmpty()) {
      throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName()));
    }

    fieldMap = Collections.unmodifiableMap(fields);
    getterMap = Collections.unmodifiableMap(getters);
    setterMap = Collections.unmodifiableMap(setters);

    final TreeSet<String> attrSet = new TreeSet<String>();
    final TreeSet<String> lazySet = new TreeSet<String>();
    if (ldapObject.requestAllAttributes()) {
      attrSet.add("*");
      attrSet.add("+");
    } else {
      for (final FieldInfo i : fields.values()) {
        if (i.lazilyLoad()) {
          lazySet.add(i.getAttributeName());
        } else {
          attrSet.add(i.getAttributeName());
        }
      }

      for (final SetterInfo i : setters.values()) {
        attrSet.add(i.getAttributeName());
      }
    }
    attributesToRequest = new String[attrSet.size()];
    attrSet.toArray(attributesToRequest);

    lazilyLoadedAttributes = new String[lazySet.size()];
    lazySet.toArray(lazilyLoadedAttributes);
  }
예제 #17
0
  public ValueType getValueType(
      int iParam,
      int nParams,
      Class<?> c,
      Type t,
      AnnotatedElement element,
      Annotation... directAnnotations) {
    boolean isPtr = isAnnotationPresent(Ptr.class, element, directAnnotations);
    boolean isCLong = isAnnotationPresent(org.bridj.ann.CLong.class, element, directAnnotations);
    Constructor cons = getAnnotation(Constructor.class, element, directAnnotations);

    if (isPtr || cons != null || isCLong) {
      if (!(c == Long.class || c == Long.TYPE))
        throw new RuntimeException(
            "Annotation should only be used on a long parameter, not on a " + c.getName());

      if (isPtr) {
        if (!Platform.is64Bits()) direct = false;
      } else if (isCLong) {
        if (Platform.CLONG_SIZE != 8) direct = false;
      } else if (cons != null) {
        isCPlusPlus = true;
        startsWithThis = true;
        if (iParam != 0)
          throw new RuntimeException(
              "Annotation "
                  + Constructor.class.getName()
                  + " cannot have more than one (long) argument");
      }
      return ValueType.eSizeTValue;
    }
    if (c == null || c.equals(Void.TYPE)) return ValueType.eVoidValue;
    if (c == Integer.class || c == Integer.TYPE) return ValueType.eIntValue;
    if (c == Long.class || c == Long.TYPE) {
      return !isPtr || Platform.is64Bits() ? ValueType.eLongValue : ValueType.eIntValue;
    }
    if (c == Short.class || c == Short.TYPE) return ValueType.eShortValue;
    if (c == Byte.class || c == Byte.TYPE) return ValueType.eByteValue;
    if (c == Boolean.class || c == Boolean.TYPE) return ValueType.eBooleanValue;
    if (c == Float.class || c == Float.TYPE) {
      usesFloats();
      return ValueType.eFloatValue;
    }
    if (c == char.class || c == Character.TYPE) {
      if (Platform.WCHAR_T_SIZE != 2) direct = false;
      return ValueType.eWCharValue;
    }
    if (c == Double.class || c == Double.TYPE) {
      usesFloats();
      return ValueType.eDoubleValue;
    }
    if (c == CLong.class) {
      direct = false;
      return ValueType.eCLongObjectValue;
    }
    if (c == SizeT.class) {
      direct = false;
      return ValueType.eSizeTObjectValue;
    }
    if (c == TimeT.class) {
      direct = false;
      return ValueType.eTimeTObjectValue;
    }
    if (Pointer.class.isAssignableFrom(c)) {
      direct = false;
      CallIO cio = CallIO.Utils.createPointerCallIO(c, t);
      if (BridJ.veryVerbose) BridJ.info("CallIO : " + cio);
      addCallIO(cio);
      return ValueType.ePointerValue;
    }
    if (c.isArray() && iParam == nParams - 1) {
      direct = false;
      return ValueType.eEllipsis;
    }
    if (ValuedEnum.class.isAssignableFrom(c)) {
      direct = false;
      CallIO cio =
          CallIO.Utils.createValuedEnumCallIO(
              (Class) Utils.getClass(Utils.getUniqueParameterizedTypeParameter(t)));
      if (BridJ.veryVerbose) BridJ.info("CallIO : " + cio);
      addCallIO(cio);

      return ValueType.eIntFlagSet;
    }
    if (NativeObject.class.isAssignableFrom(c)) {
      Pointer<DCstruct> pStruct = null;
      if (StructObject.class.isAssignableFrom(c)) {
        StructIO io = StructIO.getInstance(c, t);
        try {
          pStruct = DyncallStructs.buildDCstruct(io.desc);
        } catch (Throwable th) {
          BridJ.error(
              "Unable to create low-level struct metadata for "
                  + Utils.toString(t)
                  + " : won't be able to use it as a by-value function argument.",
              th);
        }
      }
      addCallIO(new CallIO.NativeObjectHandler((Class<? extends NativeObject>) c, t, pStruct));
      direct = false;
      return ValueType.eNativeObjectValue;
    }

    throw new NoSuchElementException(
        "No " + ValueType.class.getSimpleName() + " for class " + c.getName());
  }
예제 #18
0
파일: Utils.java 프로젝트: jryans/parboiled
  /**
   * Gets the actual type arguments that are used in a given implementation of a given generic base
   * class or interface. (Based on code copyright 2007 by Ian Robertson).
   *
   * @param base the generic base class or interface
   * @param implementation the type (potentially) implementing the given base class or interface
   * @return a list of the raw classes for the actual type arguments.
   */
  @NotNull
  public static List<Class<?>> getTypeArguments(
      @NotNull Class<?> base, @NotNull Class<?> implementation) {
    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();

    // first we need to resolve all supertypes up to the required base class or interface
    // and find the right Type for it
    Type type;

    Queue<Type> toCheck = new LinkedList<Type>();
    toCheck.add(implementation);
    while (true) {
      // if we have checked everything and not found the base class we return an empty list
      if (toCheck.isEmpty()) return ImmutableList.of();

      type = toCheck.remove();
      Class<?> clazz;

      if (type instanceof Class) {
        // there is no useful information for us in raw types, so just keep going up the inheritance
        // chain
        clazz = (Class) type;
        if (base.isInterface()) {
          // if we are actually looking for the type parameters to an interface we also need to
          // look at all the ones implemented by the given current one
          toCheck.addAll(Arrays.asList(clazz.getGenericInterfaces()));
        }
      } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        clazz = (Class) parameterizedType.getRawType();

        // for instances of ParameterizedType we extract and remember all type arguments
        TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        for (int i = 0; i < actualTypeArguments.length; i++) {
          resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
        }
      } else {
        return ImmutableList.of();
      }

      // we can stop if we have reached the sought for base type
      if (base.equals(getClass(type))) break;

      toCheck.add(clazz.getGenericSuperclass());
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible) the raw class for that type argument.
    Type[] actualTypeArguments;
    if (type instanceof Class) {
      actualTypeArguments = ((Class) type).getTypeParameters();
    } else {
      actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }
    List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
    // resolve types by chasing down type variables.
    for (Type baseType : actualTypeArguments) {
      while (resolvedTypes.containsKey(baseType)) {
        baseType = resolvedTypes.get(baseType);
      }
      typeArgumentsAsClasses.add(getClass(baseType));
    }
    return typeArgumentsAsClasses;
  }
예제 #19
0
  /**
   * Determines if the suspected super type is assignable from the suspected sub type.
   *
   * @param suspectedSuperType e.g. {@code GenericDAO<Pet, String>}
   * @param suspectedSubType e.g. {@code PetDAO extends GenericDAO<Pet,String>}
   * @return true if (sourceType)targetClass is a valid cast
   */
  public static boolean isAssignableFrom(Type suspectedSuperType, Type suspectedSubType) {
    final Class suspectedSuperClass = asClass(suspectedSuperType);
    final Class suspectedSubClass = asClass(suspectedSubType);

    // The raw types need to be compatible.
    if (!suspectedSuperClass.isAssignableFrom(suspectedSubClass)) {
      return false;
    }

    // From this point we know that the raw types are assignable.
    // We need to figure out what the generic parameters in the targetClass are
    // as they pertain to the sourceType.

    if (suspectedSuperType instanceof WildcardType) {
      // ? extends Number
      // needs to match all the bounds (there will only be upper bounds or lower bounds
      for (Type t : ((WildcardType) suspectedSuperType).getUpperBounds()) {
        if (!isAssignableFrom(t, suspectedSubType)) return false;
      }
      for (Type t : ((WildcardType) suspectedSuperType).getLowerBounds()) {
        if (!isAssignableFrom(suspectedSubType, t)) return false;
      }
      return true;
    }

    Type curType = suspectedSubType;
    Class curClass;

    while (curType != null && !curType.equals(Object.class)) {
      curClass = asClass(curType);

      if (curClass.equals(suspectedSuperClass)) {
        final Type resolved = resolve(curType, suspectedSubType);

        if (suspectedSuperType instanceof Class) {
          if (resolved instanceof Class) return suspectedSuperType.equals(resolved);

          // They may represent the same class, but the suspectedSuperType is not parameterized. The
          // parameter
          // types default to Object so they must be a match.
          // e.g. Pair p = new StringLongPair();
          //      Pair p = new Pair<? extends Number, String>

          return true;
        }

        if (suspectedSuperType instanceof ParameterizedType) {
          if (resolved instanceof ParameterizedType) {
            final Type[] type1Arguments =
                ((ParameterizedType) suspectedSuperType).getActualTypeArguments();
            final Type[] type2Arguments = ((ParameterizedType) resolved).getActualTypeArguments();
            if (type1Arguments.length != type2Arguments.length) return false;

            for (int i = 0; i < type1Arguments.length; ++i) {
              if (!isAssignableFrom(type1Arguments[i], type2Arguments[i])) return false;
            }
            return true;
          }
        } else if (suspectedSuperType instanceof GenericArrayType) {
          if (resolved instanceof GenericArrayType) {
            return isAssignableFrom(
                ((GenericArrayType) suspectedSuperType).getGenericComponentType(),
                ((GenericArrayType) resolved).getGenericComponentType());
          }
        }

        return false;
      }

      final Type[] types = curClass.getGenericInterfaces();
      for (Type t : types) {
        final Type resolved = resolve(t, suspectedSubType);
        if (isAssignableFrom(suspectedSuperType, resolved)) return true;
      }

      curType = curClass.getGenericSuperclass();
    }
    return false;
  }
예제 #20
0
  protected void getBeanElementProperties(Element element, Object bean, PropertyDescriptor pd)
      throws IntrospectionException, IllegalAccessException {
    Element propertyElement = null;
    Class classOfProperty = pd.getPropertyType();
    Object[] argsNone = {};
    // If the property is "class" and the type is java.lang.Class.class then
    // this is the class of the bean, which we've already encoded.
    // In this special case, return null.
    if (!((pd.getName().charAt(0) == 'c') && pd.getName().equals("class"))
        && !classOfProperty.equals(java.lang.Class.class)) {
      // Don't process property if it is in the list of fields to be ignored
      boolean omittedField = false;
      try {
        Field field = bean.getClass().getDeclaredField(pd.getName());
        omittedField = field.isAnnotationPresent(ObjectXmlOmitField.class);
      } catch (NoSuchFieldException nsfe) {
      }
      if (!omittedField) {
        String propertyName = formatName(pd.getName());
        // Hereafter, we're trying to create a representation of the property
        // based on the property's value.
        // The very first thing we need to do is get the value of the
        // property as an object. If we can't do that, we can't get any
        // representation of the property at all.
        Object propertyValue = null;
        try {
          Method getter = pd.getReadMethod();
          if (getter != null) {
            propertyValue = getter.invoke(bean, argsNone);
          }
        } catch (Exception ex) {
          // couldn't get value
          System.err.println(ex.getMessage());
        }
        // See if this property's value is something we can represent as a
        // standard data type that can be converted to an xsd type,
        // or if it's something that must be represented as a JavaBean.
        if (propertyElement == null) {

          PropertyEditor propEditor = PropertyEditorManager.findEditor(classOfProperty);
          // If the property editor is not null, pass the property's
          // value to the PropertyEditor, and then ask the PropertyEditor
          // for the object and then attempt to convert it to a standard type.

          if ((propEditor != null)
              || (classOfProperty == java.util.Calendar.class)
              || (classOfProperty == java.util.Date.class)) {
            // The object is a standard type
            // (e.g. a wrapper around a primitive type, a String, or a Date or Calendar object)
            try {
              Object object;
              if ((classOfProperty == java.util.Calendar.class)
                  || (classOfProperty == java.util.Date.class)) object = propertyValue;
              else {
                propEditor.setValue(propertyValue);
                object = propEditor.getValue();
              }
              Element childElement = getStandardObjectElement(document, object, propertyName);
              if (includeNullValues
                  || !childElement
                      .getAttribute(
                          NamespaceConstants.NSPREFIX_SCHEMA_XSI
                              + ":"
                              + org.apache.axis.Constants.ATTR_TYPE)
                      .equals("anyType")) {
                if (!includeTypeInfo) {
                  childElement.removeAttribute(
                      NamespaceConstants.NSPREFIX_SCHEMA_XSI
                          + ":"
                          + org.apache.axis.Constants.ATTR_TYPE);
                  childElement.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
                }
                try {
                  Field field = bean.getClass().getDeclaredField(propertyName);
                  if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) {
                    String attrName = null;
                    if (includeTypeInfo) attrName = nsPrefix + ":" + propertyName;
                    else attrName = propertyName;
                    element.setAttribute(attrName, childElement.getFirstChild().getNodeValue());
                  } else if (field.isAnnotationPresent(ObjectXmlAsValue.class))
                    element.setTextContent(childElement.getFirstChild().getNodeValue());
                  else element.appendChild(childElement);
                } catch (NoSuchFieldException nfse) {
                  element.appendChild(childElement);
                }
              }
            } catch (Exception e) {
            }
          } else {
            // The object is not an XSD-encoded datatype, it must be a JavaBean
            try {
              String propertyTypeName = null;
              if (propertyValue != null) {
                // get object type
                Class propertyType = pd.getPropertyType();
                propertyTypeName = propertyType.getName();
              }
              getBeanElements(element, propertyName, propertyTypeName, propertyValue);
            } catch (Exception e) {
            }
          }
        }
      }
    }
  }
예제 #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;
      }
    }
  }
  /**
   * Parses object with follow rules:
   *
   * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to
   * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of
   * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list
   * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or
   * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s.
   *
   * <p>4. Boolean fields defines by vk_int == 1 expression.
   *
   * @param object object to initialize
   * @param source data to read values
   * @param <T> type of result
   * @return initialized according with given data object
   * @throws org.json.JSONException if source object structure is invalid
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
      source = source.optJSONObject("response");
    }
    if (source == null) {
      return object;
    }
    for (Field field : object.getClass().getFields()) {
      field.setAccessible(true);
      String fieldName = field.getName();
      Class<?> fieldType = field.getType();

      Object value = source.opt(fieldName);
      if (value == null) {
        continue;
      }
      try {
        if (fieldType.isPrimitive() && value instanceof Number) {
          Number number = (Number) value;
          if (fieldType.equals(int.class)) {
            field.setInt(object, number.intValue());
          } else if (fieldType.equals(long.class)) {
            field.setLong(object, number.longValue());
          } else if (fieldType.equals(float.class)) {
            field.setFloat(object, number.floatValue());
          } else if (fieldType.equals(double.class)) {
            field.setDouble(object, number.doubleValue());
          } else if (fieldType.equals(boolean.class)) {
            field.setBoolean(object, number.intValue() == 1);
          } else if (fieldType.equals(short.class)) {
            field.setShort(object, number.shortValue());
          } else if (fieldType.equals(byte.class)) {
            field.setByte(object, number.byteValue());
          }
        } else {
          Object result = field.get(object);
          if (value.getClass().equals(fieldType)) {
            result = value;
          } else if (fieldType.isArray() && value instanceof JSONArray) {
            result = parseArrayViaReflection((JSONArray) value, fieldType);
          } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKAttachments.class.isAssignableFrom(fieldType)
              && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKList.class.equals(fieldType)) {
            ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
            Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
            if (VKApiModel.class.isAssignableFrom(genericType)
                && Parcelable.class.isAssignableFrom(genericType)
                && Identifiable.class.isAssignableFrom(genericType)) {
              if (value instanceof JSONArray) {
                result = new VKList((JSONArray) value, genericType);
              } else if (value instanceof JSONObject) {
                result = new VKList((JSONObject) value, genericType);
              }
            }
          } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
            result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
          }
          field.set(object, result);
        }
      } catch (InstantiationException e) {
        throw new JSONException(e.getMessage());
      } catch (IllegalAccessException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodException e) {
        throw new JSONException(e.getMessage());
      } catch (InvocationTargetException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodError e) {
        // Примечание Виталия:
        // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО.
        // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве
        // платформы разработки.
        throw new JSONException(e.getMessage());
      }
    }
    return object;
  }
예제 #23
0
  /**
   * @param obj ValueObject where updating the value for the specified attribute (identified by
   *     colunm index)
   * @param attributeName attribute name
   * @param value new Object to set onto ValueObject
   */
  public final void setField(ValueObject obj, String attributeName, Object value) {
    try {
      Method[] getter = ((Method[]) voGetterMethods.get(attributeName));
      Method[] setter = ((Method[]) voSetterMethods.get(attributeName));
      if (getter == null)
        Logger.error(
            this.getClass().getName(),
            "setField",
            "No getter method for attribute name '" + attributeName + "'.",
            null);
      if (setter == null)
        Logger.error(
            this.getClass().getName(),
            "setField",
            "No setter method for attribute name '" + attributeName + "'.",
            null);

      if (value != null
          && (value instanceof Number || !value.equals("") && value instanceof String)) {
        if (!getter[getter.length - 1].getReturnType().equals(value.getClass())) {
          Class attrType = getter[getter.length - 1].getReturnType();
          if (attrType.equals(Integer.class) || attrType.equals(Integer.TYPE))
            value = new Integer(Double.valueOf(value.toString()).intValue());
          else if (attrType.equals(Double.class) || attrType.equals(Double.TYPE))
            value = new Double(value.toString());
          else if (attrType.equals(BigDecimal.class)) value = new BigDecimal(value.toString());
          else if (attrType.equals(Long.class) || attrType.equals(Long.TYPE))
            value = new Long(Double.valueOf(value.toString()).longValue());
          else if (attrType.equals(Short.class) || attrType.equals(Short.TYPE))
            value = new Short(Double.valueOf(value.toString()).shortValue());
          else if (attrType.equals(Float.class) || attrType.equals(Float.TYPE))
            value = new Float(Double.valueOf(value.toString()).floatValue());
        }
      } else if (value != null && value.equals("")) {
        if (!getter[getter.length - 1].getReturnType().equals(value.getClass())) value = null;
      }
      // test date compatibility...
      if (value != null && value.getClass().equals(java.util.Date.class)) {
        if (setter[setter.length - 1].getParameterTypes()[0].equals(java.sql.Date.class))
          value = new java.sql.Date(((java.util.Date) value).getTime());
        else if (setter[setter.length - 1].getParameterTypes()[0].equals(java.sql.Timestamp.class))
          value = new java.sql.Timestamp(((java.util.Date) value).getTime());
      }

      // retrieve inner v.o.: if not present then maybe create it, according to "createInnerVO"
      // property...
      Method[] m = (Method[]) voGetterMethods.get(attributeName);
      if (m == null)
        Logger.error(
            this.getClass().getName(),
            "setField",
            "No getter method for attribute name '" + attributeName + "'.",
            null);
      Object oldObj = obj;
      String auxAttr;
      for (int i = 0; i < m.length - 1; i++) {
        oldObj = obj;
        obj = (ValueObject) m[i].invoke(oldObj, new Object[0]);
        if (obj == null) {
          if (grids.getGridControl() == null || !grids.getGridControl().isCreateInnerVO()) return;
          else {
            obj = (ValueObject) m[i].getReturnType().newInstance();
            String[] attrs = attributeName.split("\\.");

            auxAttr = "";
            for (int k = 0; k <= i; k++) auxAttr += attrs[k] + ".";
            auxAttr = auxAttr.substring(0, auxAttr.length() - 1);
            Method aux = ((Method[]) voSetterMethods.get(auxAttr))[i];
            aux.invoke(oldObj, new Object[] {obj});
          }
        }
      }

      // avoid to set null for primitive types!
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Long.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Long(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Integer.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Integer(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Short.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Short((short) 0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Float.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Float(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Double.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {new Double(0)});
      if (value == null && setter[setter.length - 1].getParameterTypes()[0].equals(Boolean.TYPE))
        setter[setter.length - 1].invoke(obj, new Object[] {Boolean.FALSE});
      else setter[setter.length - 1].invoke(obj, new Object[] {value});
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }