@SuppressWarnings({"rawtypes", "unchecked"})
  public static void enterA2Mode() {
    System.err.println("APV::enterA2Mode");
    try {
      Class epdControllerClass = Class.forName("android.hardware.EpdController");
      Class epdControllerRegionClass = Class.forName("android.hardware.EpdController$Region");
      Class epdControllerRegionParamsClass =
          Class.forName("android.hardware.EpdController$RegionParams");
      Class epdControllerWaveClass = Class.forName("android.hardware.EpdController$Wave");

      Object[] waveEnums = null;
      if (epdControllerWaveClass.isEnum()) {
        System.err.println("EpdController Wave Enum successfully retrived.");
        waveEnums = epdControllerWaveClass.getEnumConstants();
      }

      Object[] regionEnums = null;
      if (epdControllerRegionClass.isEnum()) {
        System.err.println("EpdController Region Enum successfully retrived.");
        regionEnums = epdControllerRegionClass.getEnumConstants();
      }

      Constructor RegionParamsConstructor =
          epdControllerRegionParamsClass.getConstructor(
              new Class[] {
                Integer.TYPE,
                Integer.TYPE,
                Integer.TYPE,
                Integer.TYPE,
                epdControllerWaveClass,
                Integer.TYPE
              });

      Object localRegionParams =
          RegionParamsConstructor.newInstance(
              new Object[] {0, 0, 600, 800, waveEnums[2], 16}); // Wave = DU

      Method epdControllerSetRegionMethod =
          epdControllerClass.getMethod(
              "setRegion",
              new Class[] {String.class, epdControllerRegionClass, epdControllerRegionParamsClass});
      epdControllerSetRegionMethod.invoke(
          null, new Object[] {"APV-ReadingView", regionEnums[2], localRegionParams});

      Thread.sleep(100L);
      localRegionParams =
          RegionParamsConstructor.newInstance(
              new Object[] {0, 0, 600, 800, waveEnums[3], 14}); // Wave = A2
      epdControllerSetRegionMethod.invoke(
          null, new Object[] {"APV-ReadingView", regionEnums[2], localRegionParams});

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Adapts the source object to a view object.
   *
   * @param mapper An action that is invoked for each source object in the graph that is to be
   *     adapted. The action can influence how the source object is adapted via the provided {@link
   *     SourceObjectMapping}.
   */
  public <T, S> T adapt(
      Class<T> targetType, S sourceObject, Action<? super SourceObjectMapping> mapper) {
    if (sourceObject == null) {
      return null;
    }
    Class<? extends T> wrapperType = targetTypeProvider.getTargetType(targetType, sourceObject);
    DefaultSourceObjectMapping mapping =
        new DefaultSourceObjectMapping(sourceObject, targetType, wrapperType);
    mapper.execute(mapping);
    wrapperType = mapping.wrapperType.asSubclass(targetType);
    if (wrapperType.isInstance(sourceObject)) {
      return wrapperType.cast(sourceObject);
    }
    if (targetType.isEnum()) {
      return adaptToEnum(targetType, sourceObject);
    }

    MixInMethodInvoker mixInMethodInvoker = null;
    if (mapping.mixInType != null) {
      mixInMethodInvoker =
          new MixInMethodInvoker(
              mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker()));
    }
    MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker);
    Object proxy =
        Proxy.newProxyInstance(
            wrapperType.getClassLoader(),
            new Class<?>[] {wrapperType},
            new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper));
    if (mixInMethodInvoker != null) {
      mixInMethodInvoker.setProxy(proxy);
    }
    return wrapperType.cast(proxy);
  }
Exemple #3
1
  /**
   * Coerce the given object to targetType.
   *
   * @param value object to be coerced
   * @param targetType which should be object coerced into
   * @return the given value coerced to targetType
   */
  public static <T> T coerce(Object value, Class<T> targetType) {
    if (value == null) {
      return null;
    }

    if (targetType.isInstance(value)) {
      return targetType.cast(value);
    }

    if (value instanceof String) {
      PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
      if (editor == null && Primitives.isWrapperType(targetType)) {
        editor = PropertyEditorManager.findEditor(Primitives.unwrap(targetType));
      }

      if (editor != null) {

        editor.setAsText((String) value);
        return targetType.cast(editor.getValue());
      } else if (targetType.isEnum()) {
        return targetType.cast(Enum.valueOf((Class<Enum>) targetType, (String) value));
      }
    }

    throw new IllegalArgumentException(
        MessageFormat.format(
            "Cannot convert {0} to object of {1} type", value, targetType.getName()));
  }
Exemple #4
0
 @SuppressWarnings("rawtypes")
 protected Object saveObject(
     Object obj, Field field, ConfigurationSection cs, String path, int depth) throws Exception {
   Class clazz = getClassAtDepth(field.getGenericType(), depth);
   if (ConfigObject.class.isAssignableFrom(clazz) && isConfigObject(obj)) {
     return getConfigObject((ConfigObject) obj, path, cs);
   } else if (Location.class.isAssignableFrom(clazz) && isLocation(obj)) {
     return getLocation((Location) obj);
   } else if (Vector.class.isAssignableFrom(clazz) && isVector(obj)) {
     return getVector((Vector) obj);
   } else if (Map.class.isAssignableFrom(clazz) && isMap(obj)) {
     return getMap((Map) obj, field, cs, path, depth);
   } else if (clazz.isEnum() && isEnum(clazz, obj)) {
     return getEnum((Enum) obj);
   } else if (List.class.isAssignableFrom(clazz) && isList(obj)) {
     Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
     if (ConfigObject.class.isAssignableFrom(subClazz)
         || Location.class.isAssignableFrom(subClazz)
         || Vector.class.isAssignableFrom(subClazz)
         || Map.class.isAssignableFrom(subClazz)
         || List.class.isAssignableFrom(subClazz)
         || subClazz.isEnum()) {
       return getList((List) obj, field, cs, path, depth);
     } else {
       return obj;
     }
   } else {
     return obj;
   }
 }
Exemple #5
0
 @SuppressWarnings("rawtypes")
 protected Object loadObject(Field field, ConfigurationSection cs, String path, int depth)
     throws Exception {
   Class clazz = getClassAtDepth(field.getGenericType(), depth);
   if (ConfigObject.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) {
     return getConfigObject(clazz, cs.getConfigurationSection(path));
   } else if (Location.class.isAssignableFrom(clazz) && isJSON(cs.get(path))) {
     return getLocation((String) cs.get(path));
   } else if (Vector.class.isAssignableFrom(clazz) && isJSON(cs.get(path))) {
     return getVector((String) cs.get(path));
   } else if (Map.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) {
     return getMap(field, cs.getConfigurationSection(path), path, depth);
   } else if (clazz.isEnum() && isString(cs.get(path))) {
     return getEnum(clazz, (String) cs.get(path));
   } else if (List.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) {
     Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
     if (ConfigObject.class.isAssignableFrom(subClazz)
         || Location.class.isAssignableFrom(subClazz)
         || Vector.class.isAssignableFrom(subClazz)
         || Map.class.isAssignableFrom(subClazz)
         || List.class.isAssignableFrom(subClazz)
         || subClazz.isEnum()) {
       return getList(field, cs.getConfigurationSection(path), path, depth);
     } else {
       return cs.get(path);
     }
   } else {
     return cs.get(path);
   }
 }
  /**
   * Checks if the class under test has compliant modifiers compared to the API.
   *
   * @return true if modifiers are compliant.
   */
  private boolean checkClassModifiersCompliance() {
    int reflectionModifier = mClass.getModifiers();
    int apiModifier = mModifier;

    // If the api class isn't abstract
    if (((apiModifier & Modifier.ABSTRACT) == 0)
        &&
        // but the reflected class is
        ((reflectionModifier & Modifier.ABSTRACT) != 0)
        &&
        // and it isn't an enum
        !isEnumType()) {
      // that is a problem
      return false;
    }
    // ABSTRACT check passed, so mask off ABSTRACT
    reflectionModifier &= ~Modifier.ABSTRACT;
    apiModifier &= ~Modifier.ABSTRACT;

    if (isAnnotation()) {
      reflectionModifier &= ~CLASS_MODIFIER_ANNOTATION;
    }
    if (mClass.isInterface()) {
      reflectionModifier &= ~(Modifier.INTERFACE);
    }
    if (isEnumType() && mClass.isEnum()) {
      reflectionModifier &= ~CLASS_MODIFIER_ENUM;
    }

    return ((reflectionModifier == apiModifier) && (isEnumType() == mClass.isEnum()));
  }
  private Set<Class<?>> filterInputClasses(Set<Class<?>> referencedClasses) {
    Set<Class<?>> typesToUse = Sets.newHashSet();
    for (Class<?> beanClass : referencedClasses) {
      if (beanClass.isEnum()) {
        typesToUse.add(beanClass);
        continue;
      }
      if (beanClass.equals(void.class)) {
        continue;
      }
      if (beanClass instanceof Class && beanClass.isEnum()) {
        typesToUse.add(beanClass);
        continue;
      }
      if (beanClass == URI.class) {
        continue;
      }

      // Classes directly passed in to typescript-generator need to be directly serializable, so
      // filter out the ones that serializers
      // exist for.
      SerializationConfig serializationConfig = OBJECT_MAPPER.getSerializationConfig();
      final JavaType simpleType = OBJECT_MAPPER.constructType(beanClass);
      try {
        final JsonSerializer<?> jsonSerializer =
            BeanSerializerFactory.instance.createSerializer(serializationConfig, simpleType, null);
        if (jsonSerializer == null || jsonSerializer instanceof BeanSerializer) {
          typesToUse.add(beanClass);
        }
      } catch (Exception e) {

      }
    }
    return typesToUse;
  }
Exemple #8
0
  private static Object parseStringToCollection(String str, Class<?> toClass, Class<?> generic) {
    Collection collection;
    if (List.class.isAssignableFrom(toClass)) {
      collection = new ArrayList();
    } else if (Set.class.isAssignableFrom(toClass)) {
      collection = new HashSet();
    } else if (Collection.class.isAssignableFrom(toClass)) {
      collection = new ArrayList();
    } else {
      return str;
    }

    if (null != generic && generic.isEnum()) {
      String[] stringArray = breakString(str);
      Class<? extends Enum> enumClass = (Class<? extends Enum>) generic;

      for (String string : stringArray) {
        collection.add(Enum.valueOf(enumClass, string));
      }
    } else if (null != generic) {
      String[] stringArray = breakStringForCollection(str);
      for (String strItem : stringArray) {
        collection.add(parse(strItem, generic));
      }
    } else {
      String[] stringArray = breakStringForCollection(str);
      for (String element : stringArray) {
        collection.add(element.trim().replaceAll("%20", " "));
      }
    }

    return collection;
  }
Exemple #9
0
 /**
  * 将bean装换为一个map(能将枚举转换为int)
  *
  * @param bean
  * @return
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 public static Map buildMap(Object bean) {
   if (bean == null) {
     return null;
   }
   try {
     Map map = describe(bean);
     PropertyDescriptor[] pds = BEANUTILSBEAN.getPropertyUtils().getPropertyDescriptors(bean);
     for (PropertyDescriptor pd : pds) {
       Class type = pd.getPropertyType();
       if (type.isEnum()) {
         Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName());
         Enum enums = EnumUtils.valueOf(type, String.valueOf(value));
         map.put(pd.getName(), enums == null ? -1 : enums.ordinal());
       } else if (type == java.util.Date.class) { // 防止是Timestamp
         Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName());
         if (value != null) {
           Calendar cal = Calendar.getInstance();
           cal.setTime((java.util.Date) value);
           map.put(pd.getName(), cal.getTime());
         }
       }
     }
     return map;
   } catch (Throwable e) {
     LOGGER.error("BeanUtil 创建Map失败:", e);
     throw new RuntimeException(e);
   }
 }
 private AbstractField createField(Object property, Class<?> type) {
   AbstractField component = null;
   if (owner.getFilterGenerator() != null) {
     component = owner.getFilterGenerator().getCustomFilterComponent(property);
   }
   if (component != null) {
     customFields.put(component, property);
   } else if (type == null) {
     component = new TextField();
     component.setWidth("100%");
     return component;
   } else if (type == boolean.class || type == Boolean.class) {
     component = createBooleanField(property);
   } else if (type == Integer.class
       || type == Long.class
       || type == Float.class
       || type == Double.class
       || type == int.class
       || type == long.class
       || type == float.class
       || type == double.class) {
     component = createNumericField(type, property);
   } else if (type.isEnum()) {
     component = createEnumField(type, property);
   } else if (type == Date.class || type == Timestamp.class || type == java.sql.Date.class) {
     component = createDateField(property);
   } else {
     component = createTextField(property);
   }
   component.setWidth("100%");
   component.setImmediate(true);
   component.addListener(listener);
   return component;
 }
  public Json makeTyped(Object anything) {
    boolean isarray = anything.getClass().isArray();
    Class<?> type = isarray ? anything.getClass().getComponentType() : anything.getClass();
    JsonConverter converter = converterMap.get(type.getName());
    String typeName = shortNameMap.getY(type.getName());
    if (typeName == null) typeName = type.getName();
    if (isarray) {
      Json result = Json.array();
      Object[] A = (Object[]) anything;
      for (Object x : A) {
        if (x == null) result.add(Json.nil());
        else result.add(converter != null ? converter.to(x) : make(x));
      }
      return Json.object().set("javaArrayType", typeName).set("array", result);
    } else if (type.isEnum())
      return Json.object().set("java.lang.Enum", type.getName()).set("value", anything.toString());

    for (Class<?> abstractConv : converterFromAbstractMap.keySet())
      if (abstractConv.isAssignableFrom(type))
        return converterFromAbstractMap.get(abstractConv).to(anything);
    Json value = null;
    if (converter != null) value = converter.to(anything);
    else if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type))
      value = beanConverter.to(anything);
    else
      try {
        value = f.make(anything);
      } catch (Throwable t) {
        value = beanConverter.to(anything);
      }
    return Json.object().set("javaType", typeName).set("value", value);
  }
  private static int putEnumTypeInHash(Class<?> type, Hashtable<String, Class<?>> enums) {
    Class<?> flagsType = QFlags.class.isAssignableFrom(type) ? type : null;
    Class<?> enumType = type.isEnum() ? type : null;
    if (enumType == null && flagsType != null) {
      enumType = getEnumForQFlags(flagsType);
    }

    if (enumType == null) return 0;

    // Since Qt supports enums that are not part of the meta object
    // we need to check whether the enum can actually be used in
    // a property.
    Class<?> enclosingClass = enumType.getEnclosingClass();
    if (enclosingClass != null
        && ((!QObject.class.isAssignableFrom(enclosingClass) && !Qt.class.equals(enclosingClass))
            || enumType.isAnnotationPresent(QtBlockedEnum.class))) {
      return -1;
    }

    int enumConstantCount = 0;
    if (!enums.contains(enumType.getName())) {
      enums.put(enumType.getName(), enumType);

      enumConstantCount = enumType.getEnumConstants().length;
    }

    if (flagsType != null && !enums.contains(flagsType.getName()))
      enums.put(flagsType.getName(), flagsType);

    return enumConstantCount;
  }
  private Map<String, List<Object>> loadContextDatabase() {
    // context DB 생
    Map<String, List<Object>> contextMap = new HashMap<String, List<Object>>();

    log.d("pakage is " + pakagename);
    List<Class<?>> classlist = getFilterClasses(pakagename, ContextSchemable.class);

    try {
      ContextSchemable schemable;

      for (Class<?> clazz : classlist) {
        if (clazz.isEnum()) {
          // enum 타입
          schemable = (ContextSchemable) clazz.getEnumConstants()[0];
          //					log.d("Type of enum: "+clazz.getSimpleName());
        } else {
          // 그외 interface 타입
          schemable = (ContextSchemable) clazz.newInstance();
          //					log.d("Type of class: "+clazz.getSimpleName());
        }

        List<Object> list = schemable.getContextSchemaData();
        if (list != null) {
          contextMap.put(schemable.getClass().getSimpleName(), list);
        }
      }
    } catch (InstantiationException e) {
      log.e(e.getMessage());
    } catch (IllegalAccessException e) {
      log.e(e.getMessage());
    }
    return contextMap;
  }
  private static Deserializer getDeserializer(Class<?> clazz, Type type) {

    Deserializer deserializer;

    if (PrimitiveTypeUtils.isPrimitiveClass(clazz)) {
      deserializer = new PrimitiveTypeDeserializer();
    } else if (clazz.isEnum()) {
      deserializer = new EnumDeserializer(clazz);
    } else if (clazz.isArray()) {
      deserializer = ArrayDeserializer.INSTANCE;
    } else if (clazz == Set.class
        || clazz == HashSet.class
        || clazz == Collection.class
        || clazz == List.class
        || clazz == ArrayList.class) {
      deserializer = CollectionDeserializer.INSTANCE;
    } else if (Collection.class.isAssignableFrom(clazz)) {
      deserializer = CollectionDeserializer.INSTANCE;
    } else if (Map.class.isAssignableFrom(clazz)) {
      deserializer = MapDeserializer.INSTANCE;
    } else {
      deserializer = new JavaBeanDeserializer(clazz);
    }

    deserializerMap.put(type, deserializer);

    return deserializer;
  }
 /** 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);
 }
Exemple #16
0
 private static Object toValStr(Object value) {
   Class c = value.getClass();
   if (c == String.class
       || c == Integer.class
       || c == Long.class
       || c == Boolean.class
       || c == Double.class) {
     return value.toString();
   } else if (c.isEnum()) {
     return value.toString().toLowerCase();
   } else if (c == Timestamp.class) {
     return asUnixTimestamp((Timestamp) value);
   } else if (value instanceof List) {
     List origList = ((List) value);
     List<String> l = new ArrayList(origList.size());
     for (Object item : origList) {
       l.add((String) toValStr(item));
     }
     return l;
   } else if (value instanceof Object[]) {
     Object[] origList = ((Object[]) value);
     List<String> l = new ArrayList(origList.length);
     for (Object item : origList) {
       l.add((String) toValStr(item));
     }
     return l;
   } else {
     throw new RuntimeException("Type [" + c.getName() + "] not handled");
   }
 }
 protected JsonSerializer<?> findCustomSerializer(
     Class<?> paramClass, SerializationConfig paramSerializationConfig) {
   ClassKey localClassKey = new ClassKey(paramClass);
   if (this._directClassMappings != null) {
     JsonSerializer localJsonSerializer4 =
         (JsonSerializer) this._directClassMappings.get(localClassKey);
     if (localJsonSerializer4 != null) return localJsonSerializer4;
   }
   if ((paramClass.isEnum()) && (this._enumSerializerOverride != null))
     return this._enumSerializerOverride;
   if (this._transitiveClassMappings != null)
     for (Object localObject2 = paramClass;
         localObject2 != null;
         localObject2 = ((Class) localObject2).getSuperclass()) {
       localClassKey.reset((Class) localObject2);
       JsonSerializer localJsonSerializer3 =
           (JsonSerializer) this._transitiveClassMappings.get(localClassKey);
       if (localJsonSerializer3 != null) return localJsonSerializer3;
     }
   if (this._interfaceMappings != null) {
     localClassKey.reset(paramClass);
     JsonSerializer localJsonSerializer1 =
         (JsonSerializer) this._interfaceMappings.get(localClassKey);
     if (localJsonSerializer1 != null) return localJsonSerializer1;
     for (Object localObject1 = paramClass;
         localObject1 != null;
         localObject1 = ((Class) localObject1).getSuperclass()) {
       JsonSerializer localJsonSerializer2 =
           _findInterfaceMapping((Class) localObject1, localClassKey);
       if (localJsonSerializer2 != null) return localJsonSerializer2;
     }
   }
   return null;
 }
Exemple #18
0
  /**
   * Attempts to parse given String to an instance of a given class. The class may also have a
   * generic type. It will throw {@link java.lang.IllegalStateException} in case this method was not
   * able to parse the value.
   *
   * @param str String to parse
   * @param toClass a class to turn value into
   * @param generic generic class
   * @return parsed value, an instance of the given class
   */
  public static Object parseString(String str, Class<?> toClass, Class<?> generic) {
    if (isBlank(str, toClass)) {
      return (String.class.isAssignableFrom(toClass)) ? "" : null;
    }

    if (isDateOrPeriod(toClass)) {
      return parseDateOrPeriod(toClass, str);
    }

    try {
      if (toClass.isEnum()) {
        Class<? extends Enum> enumClass = (Class<? extends Enum>) toClass;
        return Enum.valueOf(enumClass, str);
      }

      if (Collection.class.isAssignableFrom(toClass)) {
        return parseStringToCollection(str, toClass, generic);
      } else if (Map.class.isAssignableFrom(toClass)) {
        return parseStringToMap(str);
      } else if (Locale.class.isAssignableFrom(toClass)) {
        return LocaleUtils.toLocale(str);
      } else if (Byte[].class.isAssignableFrom(toClass)) {
        return ArrayUtils.toObject(str.getBytes());
      } else {
        return MethodUtils.invokeStaticMethod(toClass, "valueOf", str);
      }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
      throw new IllegalStateException("Unable to parse value " + str + " to " + toClass, e);
    }
  }
  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;
  }
  // this GwtCreateHandler has been introduced to make possible the
  // instanciation of abstract classes
  // that gwt-test-utils doesn't patch right now
  public Object create(Class<?> classLiteral) throws Exception {
    if (classLiteral.isAnnotation()
        || classLiteral.isArray()
        || classLiteral.isEnum()
        || classLiteral.isInterface()
        || !Modifier.isAbstract(classLiteral.getModifiers())) {
      return null;
    }

    Class<?> newClass = cache.get(classLiteral);

    if (newClass != null) {
      return newClass.newInstance();
    }

    CtClass ctClass = GwtClassPool.getCtClass(classLiteral);
    CtClass subClass = GwtClassPool.get().makeClass(classLiteral.getCanonicalName() + "SubClass");

    subClass.setSuperclass(ctClass);

    for (CtMethod m : ctClass.getDeclaredMethods()) {
      if (javassist.Modifier.isAbstract(m.getModifiers())) {
        CtMethod copy = new CtMethod(m, subClass, null);
        subClass.addMethod(copy);
      }
    }

    GwtPatcherUtils.patch(subClass, null);

    newClass = subClass.toClass(GwtClassLoader.get(), null);
    cache.put(classLiteral, newClass);

    return newClass.newInstance();
  }
  /**
   * 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;
  }
Exemple #22
0
  public static Collection parseCollection(
      Collection val, Class<?> toClassDefinition, Class<?> generic) {
    Collection collection;
    if (List.class.isAssignableFrom(toClassDefinition)) {
      collection = new ArrayList();
    } else if (Set.class.isAssignableFrom(toClassDefinition)) {
      collection = new HashSet();
    } else if (Collection.class.isAssignableFrom(toClassDefinition)) {
      collection = new ArrayList();
    } else {
      return val;
    }

    if (null != generic) {
      if (generic.isEnum()) {
        Class<? extends Enum> enumClass = (Class<? extends Enum>) generic;

        for (Object item : val) {
          collection.add(Enum.valueOf(enumClass, item.toString()));
        }
      }
    } else {
      collection.addAll(val);
    }

    return collection;
  }
 static void init() {
   try {
     awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
     translucencyClass = Class.forName("com.sun.awt.AWTUtilities$Translucency");
     if (translucencyClass.isEnum()) {
       Object[] kinds = translucencyClass.getEnumConstants();
       if (kinds != null) {
         PERPIXEL_TRANSPARENT = kinds[0];
         TRANSLUCENT = kinds[1];
         PERPIXEL_TRANSLUCENT = kinds[2];
       }
     }
     mIsTranslucencySupported =
         awtUtilitiesClass.getMethod("isTranslucencySupported", translucencyClass);
     mIsTranslucencyCapable =
         awtUtilitiesClass.getMethod("isTranslucencyCapable", GraphicsConfiguration.class);
     mSetWindowShape = awtUtilitiesClass.getMethod("setWindowShape", Window.class, Shape.class);
     mSetWindowOpacity =
         awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
     mSetWindowOpaque =
         awtUtilitiesClass.getMethod("setWindowOpaque", Window.class, boolean.class);
   } catch (NoSuchMethodException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   } catch (SecurityException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   } catch (ClassNotFoundException ex) {
     Logger.getLogger(AWTUtilitiesWrapper.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
 /**
  * 获取值的数据库值
  *
  * @param value
  * @return
  */
 public static String toDbValue(Object value) {
   if (value == null) {
     return null;
   }
   Class<?> valueType = value.getClass();
   if (valueType.isEnum()) {
     for (Field field : valueType.getDeclaredFields()) {
       Annotation annotation = field.getAnnotation(DbValue.class);
       if (annotation != null) {
         DbValue dbValue = (DbValue) annotation;
         if (field.getName().equals(value.toString())) {
           return dbValue.value();
         }
       }
     }
   } else if (valueType == DateTime.class) {
     // 日期类型的,最小值认为是空
     DateTime dateTime = (DateTime) value;
     if (dateTime.equals(DateTime.getMinValue())) {
       return null;
     }
   } else if (valueType == Decimal.class) {
     Decimal decimal = (Decimal) value;
     return Decimal.round(decimal, Decimal.RESERVED_DECIMAL_PLACES_STORAGE).toString();
   }
   return value.toString();
 }
Exemple #25
0
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

      @SuppressWarnings("unchecked")
      Class<T> rawType = (Class<T>) type.getRawType();
      if (!rawType.isEnum()) {
        return null;
      }

      final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
      for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
      }

      return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
          if (value == null) {
            out.nullValue();
          } else {
            out.value(toLowercase(value));
          }
        }

        public T read(JsonReader reader) throws IOException {
          if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
          } else {
            return lowercaseToConstant.get(reader.nextString());
          }
        }
      };
    }
  @SuppressWarnings("rawtypes")
  public static boolean isSirenProperty(Class<?> type, Object obj, Field field) {
    boolean isProp = false;

    Siren4JProperty anno = field.getAnnotation(Siren4JProperty.class);
    if (anno != null || type.isEnum()) {
      isProp = true;
    } else if (ArrayUtils.contains(propertyTypes, type)) {
      isProp = true;
    } else if (obj != null && Collection.class.isAssignableFrom(type)) {
      // Try to determine value type
      if (!((Collection) obj).isEmpty()) {
        Object first = findFirstNonNull(((Collection) obj).iterator());
        if (first == null || ArrayUtils.contains(propertyTypes, first.getClass())) {
          isProp = true;
        }
      }
    } else if (obj != null && Map.class.isAssignableFrom(type)) {
      // Try to determine value types of key and value
      if (!((Map) obj).isEmpty()) {
        Object firstKey = findFirstNonNull(((Map) obj).keySet().iterator());
        Object firstVal = findFirstNonNull(((Map) obj).entrySet().iterator());
        if ((firstKey == null || ArrayUtils.contains(propertyTypes, firstKey.getClass()))
            && (firstVal == null
                || ArrayUtils.contains(
                    propertyTypes, ((HashMap.Entry) firstVal).getValue().getClass()))) {
          isProp = true;
        }
      }
    }
    return isProp;
  }
Exemple #27
0
 /**
  * Tries to convert a string value to a data type given as a parameter. There are few cases, that
  * can occure.
  *
  * <ol>
  *   <li>Given value is null or an empty string. In such case the null is also returned.
  *   <li>Defined class is a java primitive like int, double etc. For these instances the object
  *       representation is returned. It means that for int it returns Integer, for double Double
  *       etc.
  *   <li>Value is well-known object primitive, like Integer, Date etc. In these cases the string
  *       is parsed into given object and returned.
  *   <li>Defined class is complex. In such cases the original string value is returned because
  *       there is not known converter.
  * </ol>
  *
  * <p>Note: When the given class is inherited from some java primitive then the returned object is
  * that primitive type. For example this can occure for {@link java.sql.Date} which inherits from
  * {@link java.util.Date}
  *
  * @param <T> desired type to be converted to
  * @param value string representation of converted value
  * @param type target class of the value
  * @return converted value if the conversion is defined
  * @throws ParseException this occures when the date is in bad format. The format can be redefined
  *     in {@link #dateFormat}.
  * @throws NumberFormatException conversion of string to number has failed. It occures when the
  *     input string is not a number but the target class is.
  */
 public static <T> Object tryToConvertTo(final String value, final Class<T> type)
     throws ParseException, NumberFormatException {
   if (value == null || "".equals(value)) {
     return null;
   }
   if (java.util.Date.class.isAssignableFrom(type)) {
     return (java.util.Date)
         (new java.text.SimpleDateFormat(dateFormat, java.util.Locale.getDefault()).parse(value));
   } else if (String.class.isAssignableFrom(type)) {
     return type.cast(value);
   } else if (Integer.class.isAssignableFrom(type) || Integer.TYPE.equals(type)) {
     return Integer.valueOf(value);
   } else if (Double.class.isAssignableFrom(type) || Double.TYPE.equals(type)) {
     return Double.valueOf(value);
   } else if (Long.class.isAssignableFrom(type) || Long.TYPE.equals(type)) {
     return Long.valueOf(value);
   } else if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.equals(type)) {
     return (BooleanHelper.isTrue(value) ? Boolean.TRUE : (Boolean.valueOf(value)));
   } else if (Byte.class.isAssignableFrom(type) || Byte.TYPE.equals(type)) {
     return Byte.valueOf(value);
   } else if (type.isEnum()) {
     for (T enumValue : type.getEnumConstants()) {
       if (enumValue.toString().equals(value)) {
         return enumValue;
       }
     }
     return null;
   } else {
     return value;
   }
 }
  public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
    if (out.addRef(obj)) return;

    Class cl = obj.getClass();

    if (!cl.isEnum() && cl.getSuperclass().isEnum()) cl = cl.getSuperclass();

    String name = null;
    try {
      name = (String) _name.invoke(obj, (Object[]) null);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    int ref = out.writeObjectBegin(cl.getName());

    if (ref < -1) {
      out.writeString("name");
      out.writeString(name);
      out.writeMapEnd();
    } else {
      if (ref == -1) {
        out.writeClassFieldLength(1);
        out.writeString("name");
        out.writeObjectBegin(cl.getName());
      }

      out.writeString(name);
    }
  }
 private Object sample(Class<?> type) {
   if (type.isPrimitive()) {
     if (type == long.class) {
       return random.nextLong();
     }
     if (type == boolean.class) {
       return random.nextBoolean();
     }
   } else if (type.isEnum()) {
     Object[] candidates = type.getEnumConstants();
     return candidates[random.nextInt(candidates.length)];
   } else if (!type.isArray()) {
     if (type == String.class) {
       StringBuilder result = new StringBuilder();
       for (int len = 5 + random.nextInt(10); len > 0; len--) {
         result.append('a' + random.nextInt('z' - 'a'));
       }
       return result.toString();
     }
     if (type == Long.class) {
       return random.nextLong();
     }
     return mock(type);
   }
   throw new UnsupportedOperationException(
       "doesn't support " + type + " please add support for it.");
 }
  private boolean addClassMemberStaticImports(String packageName) {
    try {
      Class c = Class.forName(packageName);
      initImports();
      if (c.isEnum()) {

        //noinspection unchecked
        for (Enum e : (EnumSet<?>) EnumSet.allOf(c)) {
          imports.put(e.name(), e);
        }
        return true;
      } else {
        for (Field f : c.getDeclaredFields()) {
          if ((f.getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) != 0) {
            imports.put(f.getName(), f.get(null));
          }
        }
      }
    } catch (ClassNotFoundException e) {
      // do nothing.
    } catch (IllegalAccessException e) {
      throw new RuntimeException("error adding static imports for: " + packageName, e);
    }
    return false;
  }