Ejemplo n.º 1
0
  private static void showFields(Object obj) {
    Class c = obj.getClass();
    for (Field field : c.getDeclaredFields()) {
      int modifiers = 0;
      try {
        Show show = field.getAnnotation(Show.class);
        if (show == null) {
          System.out.println("skip field " + field.getName());
          continue;
        }
        System.out.println("Name = " + show.name());

        modifiers = field.getModifiers();
        if ((modifiers & Modifier.PRIVATE) != 0) {
          System.out.print("private ");
          field.setAccessible(true);
        }
        if ((modifiers & Modifier.PUBLIC) != 0) System.out.print("public ");
        if (modifiers == 0) {
          System.out.print("package local");
          field.setAccessible(true);
        }
        System.out.println(field.getName() + " = " + field.get(obj) + " " + modifiers);
      } catch (IllegalAccessException e) {
        System.out.println(e.getMessage() + " " + field.getName() + " " + modifiers);
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 2
0
 /**
  * Get the key name
  *
  * @param keycode codepoint
  * @return string containing key name
  */
 public static String getKeyName(int keycode) {
   StringBuffer keybuf = new StringBuffer();
   keycode = removeModifier(keycode);
   int plane = findPlane(keycode);
   if (plane == 16) {
     keybuf.append(BlackenModifier.getModifierString(keycode));
   } else if (plane == 15) {
     String name = String.format("\\U%08x", keycode); // $NON-NLS-1$
     for (Field f : BlackenKeys.class.getDeclaredFields()) {
       String fieldName = f.getName();
       if (fieldName.startsWith("KEY_")
           || //$NON-NLS-1$
           fieldName.startsWith("CODEPOINT_")) { // $NON-NLS-1$
         try {
           if (f.getInt(null) == keycode) {
             name = f.getName();
             break;
           }
         } catch (IllegalArgumentException e) {
           continue;
         } catch (IllegalAccessException e) {
           continue;
         }
       }
     }
     keybuf.append(name);
   } else {
     keybuf.appendCodePoint(keycode);
   }
   return keybuf.toString();
 }
Ejemplo n.º 3
0
  private void setDNAndEntryFields(final T o, final Entry e) throws LDAPPersistException {
    if (dnField != null) {
      try {
        dnField.set(o, e.getDN());
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_DN.get(
                type.getName(), e.getDN(), dnField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }

    if (entryField != null) {
      try {
        entryField.set(o, new ReadOnlyEntry(e));
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_ENTRY.get(
                type.getName(), entryField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }
  }
Ejemplo n.º 4
0
  /**
   * bean对象转Map
   *
   * @param obj 实例对象
   * @return map集合
   */
  public static Map<String, String> beanToMap(Object obj) {
    Class<?> cls = obj.getClass();
    Map<String, String> valueMap = new HashMap<String, String>();
    // 取出bean里的所有方法
    Method[] methods = cls.getDeclaredMethods();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
      try {
        String fieldType = field.getType().getSimpleName();
        String fieldGetName = parseMethodName(field.getName(), "get");
        if (!haveMethod(methods, fieldGetName)) {
          continue;
        }
        Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});
        Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});
        String result = null;
        if ("Date".equals(fieldType)) {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
          result = sdf.format((Date) fieldVal);

        } else {
          if (null != fieldVal) {
            result = String.valueOf(fieldVal);
          }
        }
        valueMap.put(field.getName(), result);
      } catch (Exception e) {
        continue;
      }
    }
    return valueMap;
  }
Ejemplo n.º 5
0
  /**
   * This takes a Map of keys and business object entries and indexes all indexes attributes in one
   * method call.
   *
   * @param entries
   */
  public void indexAll(Map<RK, A> entries) {
    if (entries.size() > 0) {
      try {
        Map<String, Map<RK, String>> fentries = new HashMap<String, Map<RK, String>>();
        for (Field f : indexedFields) {
          Map<RK, String> m = new HashMap<RK, String>();
          fentries.put(f.getName(), m);
        }

        for (Map.Entry<RK, A> e : entries.entrySet()) {
          A bo = e.getValue();
          RK key = e.getKey();

          for (Field f : indexedFields) {
            String value = (String) f.get(bo);
            Map<RK, String> m = fentries.get(f.getName());
            m.put(key, value);
          }
        }

        for (Field f : indexedFields) {
          Map<RK, String> m = fentries.get(f.getName());
          Index<A, RK> index = getIndex(f.getName());
          index.insert(m);
        }
      } catch (IllegalAccessException e) {
        throw new ObjectGridRuntimeException(e);
      }
    }
  }
Ejemplo n.º 6
0
 /** @param elementType May be null if the type is unknown. */
 public void readField(
     Object object, String fieldName, String jsonName, Class elementType, Object jsonData) {
   OrderedMap jsonMap = (OrderedMap) jsonData;
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   FieldMetadata metadata = fields.get(fieldName);
   if (metadata == null)
     throw new SerializationException(
         "Field not found: " + fieldName + " (" + type.getName() + ")");
   Field field = metadata.field;
   Object jsonValue = jsonMap.get(jsonName);
   if (jsonValue == null) return;
   if (elementType == null) elementType = metadata.elementType;
   try {
     field.set(object, readValue(field.getType(), elementType, jsonValue));
   } catch (IllegalAccessException ex) {
     throw new SerializationException(
         "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
   } catch (SerializationException ex) {
     ex.addTrace(field.getName() + " (" + type.getName() + ")");
     throw ex;
   } catch (RuntimeException runtimeEx) {
     SerializationException ex = new SerializationException(runtimeEx);
     ex.addTrace(field.getName() + " (" + type.getName() + ")");
     throw ex;
   }
 }
Ejemplo n.º 7
0
 private static void reflectionAppend(
     Object obj,
     Object obj1,
     Class class1,
     CompareToBuilder comparetobuilder,
     boolean flag,
     String as[]) {
   Field afield[] = class1.getDeclaredFields();
   AccessibleObject.setAccessible(afield, true);
   int i = 0;
   do {
     if (i >= afield.length || comparetobuilder.comparison != 0) {
       return;
     }
     Field field = afield[i];
     if (!ArrayUtils.contains(as, field.getName())
         && field.getName().indexOf('$') == -1
         && (flag || !Modifier.isTransient(field.getModifiers()))
         && !Modifier.isStatic(field.getModifiers())) {
       try {
         comparetobuilder.append(field.get(obj), field.get(obj1));
       } catch (IllegalAccessException illegalaccessexception) {
         throw new InternalError("Unexpected IllegalAccessException");
       }
     }
     i++;
   } while (true);
 }
Ejemplo n.º 8
0
 private static String[] getPropertyNames(Class<?> clazz, boolean only4Copy) {
   List<String> ret_all = new ArrayList<String>();
   List<String> ret = new ArrayList<String>();
   Field[] fields = CE.of(clazz).getFields(Object.class);
   for (Field fld : fields) {
     if (fld.getModifiers() == Modifier.PUBLIC) {
       ret.add(fld.getName());
     }
     ret_all.add(fld.getName());
   }
   BeanInfo info = null;
   try {
     info = Introspector.getBeanInfo(clazz);
   } catch (IntrospectionException e) {
   }
   if (info != null) {
     PropertyDescriptor[] properties = info.getPropertyDescriptors();
     for (int i = 0; i < properties.length; i++) {
       PropertyDescriptor pd = properties[i];
       if (ret_all.contains(pd.getName()) && !ret.contains(pd.getName())) {
         if (!only4Copy || (pd.getReadMethod() != null && pd.getWriteMethod() != null))
           ret.add(properties[i].getName());
       }
     }
   }
   return ret.toArray(new String[ret.size()]);
 }
Ejemplo n.º 9
0
  /**
   * 将对象转换为XML报文字符串
   *
   * <p>
   * <li>通过java反射对象,将对象的每一个成员变量都转换成xml的标签
   * <li>然后将获取每个变量的值,放入标签之间
   *
   * @param obj 待转换对象
   * @return xml字符串
   */
  public static String obj2Xml(Object obj) {
    StringBuffer sb = new StringBuffer();
    try {
      Class clz = obj.getClass();
      Field[] fields = clz.getDeclaredFields();
      for (Field field : fields) {
        String fieldName = field.getName();
        sb.append("<" + fieldName + ">");
        String methodName = "get" + DataTools.stringUpdateFirst(field.getName());
        // 反射得到方法
        Method m = clz.getDeclaredMethod(methodName);
        // 通过反射调用set方法
        sb.append(m.invoke(obj));
        sb.append("</" + fieldName + ">");
      }
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }

    return sb.toString();
  }
  @Override
  public Object processAnnotation(final SystemProperty systemProperty, final Field field)
      throws AnnotationProcessingException {

    String key = systemProperty.value().trim();

    // check attribute
    rejectIfEmpty(key, missingAttributeValue("value", SystemProperty.class.getName(), field));

    // check system property
    String value = System.getProperty(key);
    if (value == null) {
      LOGGER.log(
          Level.WARNING,
          "System property ''{0}'' on field ''{1}'' of type ''{2}'' not found in system properties: {3}",
          new Object[] {
            key, field.getName(), field.getDeclaringClass().getName(), System.getProperties()
          });

      // Use default value if specified
      String defaultValue = systemProperty.defaultValue();
      if (defaultValue != null && !defaultValue.isEmpty()) {
        value = defaultValue.trim();
      } else {
        LOGGER.log(
            Level.WARNING,
            "Default value of system property ''{0}'' on field ''{1}'' of type ''{2}'' is empty",
            new Object[] {key, field.getName(), field.getDeclaringClass().getName()});
        return null;
      }
    }

    return value;
  }
Ejemplo n.º 11
0
 private static void loadFields(Class c, Map<String, Field> fields) {
   if (c == Object.class) return;
   for (Field f : c.getDeclaredFields()) {
     if (!fields.containsKey(f.getName())) fields.put(f.getName(), f);
   }
   loadFields(c.getSuperclass(), fields);
 }
Ejemplo n.º 12
0
  /** 从文件清空对象属性 */
  public void Clear(Object obj) {
    Log.v(LOG_TAG + "Clear", "Clear(Object) start");

    if (isNullObject(obj)) {
      Log.d(LOG_TAG + "Clear", "object is null");
      return;
    }

    // 获取文件编辑器
    SharedPreferences.Editor editor = getEditor();

    // 获取对象类名
    String objectName = obj.getClass().getName();
    Log.v(LOG_TAG + "Clear", "object name is " + objectName);

    // 获取对象的全部属性
    Field[] fields = obj.getClass().getDeclaredFields();

    // 遍历全部对象属性
    for (Field field : fields) {
      Log.v(LOG_TAG + "Clear", "field name is " + field.getName());
      // 移除一个属性值
      editor.remove(objectName + "." + field.getName());
    }

    // 提交保存
    editor.commit();
    Log.v(LOG_TAG + "Clear", "Clear(Object) end");
  }
Ejemplo n.º 13
0
  /**
   * @Title: printUserInfos @Description: TODO
   *
   * @param @param userInfoSels
   * @return void
   * @throws
   */
  protected static void printUserInfos(ArrayList<UserInfoEntity> userInfoSels) {
    for (UserInfoEntity userInfo : userInfoSels) {
      Method[] methods = InvokeUtils.getMethods(userInfo);
      Field[] fields = InvokeUtils.getFields(userInfo);
      for (Method method : methods) {
        for (Field field : fields) {
          if (method.getName().equalsIgnoreCase("get" + field.getName())) {
            if (field.getType().equals(String.class)) {
              System.out.print(
                  InvokeUtils.execute(userInfo, method.getName(), new Object[] {}) + "\t");
            } else if (field.getType().equals(Date.class)) {
              System.out.print(
                  InvokeUtils.execute(userInfo, method.getName(), new Object[] {}) + "\t");
            }
            if (field.getType().equals(byte[].class)) {}

          } else if (method.getName().equalsIgnoreCase("get" + field.getName() + "Str")) {
            System.out.print(
                InvokeUtils.execute(userInfo, method.getName(), new Object[] {}) + "\t");
          }
        }
      }
      System.out.println();
    }
  }
Ejemplo n.º 14
0
 private static Object valueWrap(final Class<?> cls, final Element element)
     throws InstantiationException, IllegalAccessException, IllegalArgumentException,
         InvocationTargetException, NoSuchMethodException, SecurityException {
   Field[] fie = cls.getDeclaredFields();
   Object obj = cls.newInstance();
   for (Field fi : fie) {
     Element ele = element.element(fi.getName());
     String value = "";
     if (ele == null) {
       value = element.getText();
       if (StringUtils.isBlank(value)) {
         value = element.attributeValue(fi.getName());
       }
     } else {
       value = ele.getText();
       if (StringUtils.isBlank(value)) {
         value = ele.attributeValue(fi.getName());
       }
     }
     String methodName = "set" + upperFirst(fi.getName());
     if (containsMethod(cls, methodName)) {
       cls.getMethod(methodName, String.class).invoke(obj, value);
     }
   }
   return obj;
 }
Ejemplo n.º 15
0
  /**
   * copy
   *
   * @param dest
   * @param orig
   * @param ignoreNull 忽略null,即orig为空的字段不做copy
   * @author Joeson
   */
  public static void copy(Object dest, Object orig, boolean ignoreNull) {
    if (null == dest || null == orig) {
      return;
    }

    Class destClz = dest.getClass();
    Class origClz = orig.getClass();

    Field[] destFields = destClz.getDeclaredFields();
    Field[] origFields = origClz.getDeclaredFields();

    for (Field origField : origFields) {
      try {
        String fieldName = origField.getName();
        origField.setAccessible(true);
        if (!ignoreNull || null != origField.get(orig)) {
          for (Field destField : destFields) {
            if (destField.getName().equals(origField.getName())
                && destField.getType().equals(origField.getType())) {
              destField.setAccessible(true);
              Object o = origField.get(orig);
              BeanUtils.copyProperty(dest, fieldName, o);
              break;
            }
          }
        }
      } catch (Exception e) {
        logger.error("copyNonNull exception.", e);
        throw new RuntimeException("copyNonNull exception.." + e.getMessage());
      }
    }
  }
Ejemplo n.º 16
0
 /**
  * 为对象的一个字段设值。 优先调用对象的 setter,如果没有,直接设置字段的值
  *
  * @param obj 对象
  * @param field 字段
  * @param value 值。如果为 null,字符和数字字段,都会设成 0
  * @throws FailToSetValueException
  */
 public void setValue(Object obj, Field field, Object value) throws FailToSetValueException {
   if (!field.isAccessible()) field.setAccessible(true);
   Class<?> ft = field.getType();
   // 非 null 值,进行转换
   if (null != value) {
     try {
       value = Castors.me().castTo(value, field.getType());
     } catch (FailToCastObjectException e) {
       throw makeSetValueException(obj.getClass(), field.getName(), value, e);
     }
   }
   // 如果是原生类型,转换成默认值
   else if (ft.isPrimitive()) {
     if (boolean.class == ft) {
       value = false;
     } else if (char.class == ft) {
       value = (char) 0;
     } else {
       value = (byte) 0;
     }
   }
   try {
     this.getSetter(field).invoke(obj, value);
   } catch (Exception e1) {
     try {
       field.set(obj, value);
     } catch (Exception e) {
       throw makeSetValueException(obj.getClass(), field.getName(), value, e);
     }
   }
 }
Ejemplo n.º 17
0
 /** @param elementType May be null if the type is unknown. */
 public void writeField(Object object, String fieldName, String jsonName, Class elementType) {
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   FieldMetadata metadata = fields.get(fieldName);
   if (metadata == null)
     throw new SerializationException(
         "Field not found: " + fieldName + " (" + type.getName() + ")");
   Field field = metadata.field;
   if (elementType == null) elementType = metadata.elementType;
   try {
     if (debug)
       System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
     writer.name(jsonName);
     writeValue(field.get(object), field.getType(), elementType);
   } catch (IllegalAccessException ex) {
     throw new SerializationException(
         "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
   } catch (SerializationException ex) {
     ex.addTrace(field + " (" + type.getName() + ")");
     throw ex;
   } catch (Exception runtimeEx) {
     SerializationException ex = new SerializationException(runtimeEx);
     ex.addTrace(field + " (" + type.getName() + ")");
     throw ex;
   }
 }
Ejemplo n.º 18
0
  private int getNumNonSerialVersionUIDFields(Class clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    int numFields = declaredFields.length;
    List<Field> fieldList = Arrays.asList(declaredFields);

    //        System.out.println(clazz);
    //
    //        for (Field field : fieldList) {
    //            System.out.println(field.getNode());
    //        }

    for (Field field : fieldList) {
      if (field.getName().equals("serialVersionUID")) {
        numFields--;
      }

      if (field.getName().equals("this$0")) {
        numFields--;
      }
    }

    //        System.out.println(numFields);

    return numFields;
  }
Ejemplo n.º 19
0
 public void readFields(Object object, Object jsonData) {
   OrderedMap<String, Object> jsonMap = (OrderedMap) jsonData;
   Class type = object.getClass();
   ObjectMap<String, FieldMetadata> fields = typeToFields.get(type);
   if (fields == null) fields = cacheFields(type);
   for (Entry<String, Object> entry : jsonMap.entries()) {
     FieldMetadata metadata = fields.get(entry.key);
     if (metadata == null) {
       if (ignoreUnknownFields) {
         if (debug)
           System.out.println(
               "Ignoring unknown field: " + entry.key + " (" + type.getName() + ")");
         continue;
       } else
         throw new SerializationException(
             "Field not found: " + entry.key + " (" + type.getName() + ")");
     }
     Field field = metadata.field;
     if (entry.value == null) continue;
     try {
       field.set(object, readValue(field.getType(), metadata.elementType, entry.value));
     } catch (IllegalAccessException ex) {
       throw new SerializationException(
           "Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
     } catch (SerializationException ex) {
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     } catch (RuntimeException runtimeEx) {
       SerializationException ex = new SerializationException(runtimeEx);
       ex.addTrace(field.getName() + " (" + type.getName() + ")");
       throw ex;
     }
   }
 }
Ejemplo n.º 20
0
  public boolean packetArrived(PacketArrivedEvent evt) throws MathLinkException {
    KernelLink ml = (KernelLink) evt.getSource();

    if (evt.getPktType() == MathLink.TEXTPKT) {
      resources.add(new Resource(evt.getPktType(), ml.getString()));
    }

    if (evt.getPktType() == MathLink.MESSAGEPKT) {
      resources.add(new Resource(evt.getPktType(), ml.getString()));
    }

    for (Field field : MathLink.class.getFields()) {
      if (field.getName().endsWith("PKT")) {
        try {
          if (evt.getPktType() == field.getInt(field)) {
            System.out.println(
                "Received Mathematica Packet: " + field.getName() + " (" + evt.getPktType() + ")");
          }
        } catch (IllegalArgumentException e) {
          System.out.println(e.getMessage());
        } catch (IllegalAccessException e) {
          System.out.println(e.getMessage());
        }
      }
    }

    return true;
  }
Ejemplo n.º 21
0
 private void addFields(Class<?> clazz) {
   Field[] fields = clazz.getDeclaredFields();
   for (Field field : fields) {
     if (canAccessPrivateMethods()) {
       try {
         field.setAccessible(true);
       } catch (Exception e) {
         // Ignored. This is only a final precaution, nothing we can do.
       }
     }
     if (field.isAccessible()) {
       if (!setMethods.containsKey(field.getName())) {
         // issue #379 - removed the check for final because JDK 1.5 allows
         // modification of final fields through reflection (JSR-133). (JGB)
         // pr #16 - final static can only be set by the classloader
         int modifiers = field.getModifiers();
         if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
           addSetField(field);
         }
       }
       if (!getMethods.containsKey(field.getName())) {
         addGetField(field);
       }
     }
   }
   if (clazz.getSuperclass() != null) {
     addFields(clazz.getSuperclass());
   }
 }
Ejemplo n.º 22
0
  /**
   * load attribute from the attributes
   *
   * @param p the properties
   */
  public void loadFromProperties(Properties p) {

    try {
      Field[] f = getClass().getDeclaredFields();
      for (Field field : f) {
        String name = field.getName();
        if (!name.contains("myPawns")
            && !name.contains("alliedPawns")
            && !name.contains("enemyPawns")
            && !name.contains("msg")) {
          if (name.contains("distance")) {
            field.setFloat(this, Float.parseFloat(p.getProperty(field.getName())));
          } else {
            field.setInt(this, Integer.parseInt(p.getProperty(field.getName())));
          }
        }
      }
      // TODO fehlerhandling
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 23
0
 public static Map<String, String> objectToMap(Object object, String... ignore) {
   Map<String, String> tempMap = new LinkedHashMap<String, String>();
   for (Field f : object.getClass().getDeclaredFields()) {
     if (!f.isAccessible()) {
       f.setAccessible(true);
     }
     boolean ig = false;
     if (ignore != null && ignore.length > 0) {
       for (String i : ignore) {
         if (i.equals(f.getName())) {
           ig = true;
           break;
         }
       }
     }
     if (ig) {
       continue;
     } else {
       Object o = null;
       try {
         o = f.get(object);
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       }
       if (o != null) {
         tempMap.put(f.getName(), o.toString());
       }
     }
   }
   return tempMap;
 }
  public static Field getCampo(Class<?> clase, String regex) {

    Field salida = null;
    regex = regex.trim().toUpperCase();
    ArrayList<Field> candidatos = new ArrayList();

    for (Field f : clase.getDeclaredFields()) {
      String nombre = f.getName().toUpperCase();
      if (nombre.matches(regex)) {
        candidatos.add(f);
      }
    }

    for (Field f : candidatos) {
      if (salida == null || salida.getName().length() > f.getName().length()) {
        salida = f;
      }
    }

    if (salida == null) {
      System.err.println(
          "No se encontro ningun campo en la clase "
              + clase.getName()
              + " que cumpla con la siguiente exprecion "
              + regex);
    }
    return salida;
  }
Ejemplo n.º 25
0
  void initIndexes(Class<A> indexClass) {
    Field[] fields = indexClass.getDeclaredFields();
    indexedFields = new ArrayList<Field>();

    for (Field f : fields) {
      Index<A, RK> index = null;
      SubstringIndex s = f.getAnnotation(SubstringIndex.class);
      ExactIndex e = f.getAnnotation(ExactIndex.class);
      PrefixIndex p = f.getAnnotation(PrefixIndex.class);
      String indexName = indexClass.getSimpleName() + "_" + f.getName();
      if (s != null) {
        index = new SubstringIndexImpl<A, RK>(this, indexName, s);
      }
      if (e != null) {
        index = new ExactIndexImpl<A, RK>(this, indexName, e);
      }
      if (p != null) {
        index = new PrefixIndexImpl<A, RK>(this, indexName, p);
      }
      if (index != null) {
        indexedFields.add(f);
        f.setAccessible(true);
        indices.put(f.getName(), index);
      }
    }
  }
 @Override
 public FieldProviderResponse overrideViaXml(
     OverrideViaXmlRequest overrideViaXmlRequest, Map<String, FieldMetadata> metadata) {
   Map<String, FieldMetadataOverride> overrides =
       getTargetedOverride(
           overrideViaXmlRequest.getRequestedConfigKey(),
           overrideViaXmlRequest.getRequestedCeilingEntity());
   if (overrides != null) {
     for (String propertyName : overrides.keySet()) {
       final FieldMetadataOverride localMetadata = overrides.get(propertyName);
       for (String key : metadata.keySet()) {
         if (key.equals(propertyName)) {
           try {
             if (metadata.get(key) instanceof AdornedTargetCollectionMetadata) {
               AdornedTargetCollectionMetadata serverMetadata =
                   (AdornedTargetCollectionMetadata) metadata.get(key);
               if (serverMetadata.getTargetClass() != null) {
                 Class<?> targetClass = Class.forName(serverMetadata.getTargetClass());
                 Class<?> parentClass = null;
                 if (serverMetadata.getOwningClass() != null) {
                   parentClass = Class.forName(serverMetadata.getOwningClass());
                 }
                 String fieldName = serverMetadata.getFieldName();
                 Field field =
                     overrideViaXmlRequest
                         .getDynamicEntityDao()
                         .getFieldManager()
                         .getField(targetClass, fieldName);
                 Map<String, FieldMetadata> temp = new HashMap<String, FieldMetadata>(1);
                 temp.put(field.getName(), serverMetadata);
                 FieldInfo info = buildFieldInfo(field);
                 buildAdornedTargetCollectionMetadata(
                     parentClass,
                     targetClass,
                     temp,
                     info,
                     localMetadata,
                     overrideViaXmlRequest.getDynamicEntityDao());
                 serverMetadata = (AdornedTargetCollectionMetadata) temp.get(field.getName());
                 metadata.put(key, serverMetadata);
                 if (overrideViaXmlRequest.getParentExcluded()) {
                   if (LOG.isDebugEnabled()) {
                     LOG.debug(
                         "applyAdornedTargetCollectionMetadataOverrides:Excluding "
                             + key
                             + "because parent is marked as excluded.");
                   }
                   serverMetadata.setExcluded(true);
                 }
               }
             }
           } catch (Exception e) {
             throw new RuntimeException(e);
           }
         }
       }
     }
   }
   return FieldProviderResponse.HANDLED;
 }
Ejemplo n.º 27
0
 private static void jsonFromField(StringBuilder sb, Object obj, int i, Field f) {
   if (f.getType().equals(String.class)) {
     try {
       String key = f.getName();
       String val = String.valueOf(f.get(obj));
       if (i != 0) {
         sb.append(", ");
       }
       sb.append("\"");
       sb.append(key);
       sb.append("\"");
       sb.append(":");
       sb.append("\"");
       sb.append(val);
       sb.append("\"");
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     }
   } else if (f.getType().equals(Date.class)) {
     try {
       String key = f.getName();
       Date val = (Date) f.get(obj);
       if (i != 0) {
         sb.append(", ");
       }
       sb.append("\"");
       sb.append(key);
       sb.append("\"");
       sb.append(":");
       // sb.append("\"");
       sb.append(val.getTime());
       // sb.append("\"");
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     }
   } else if (f.getType().equals(org.json.JSONObject.class)) {
     try {
       String key = f.getName();
       org.json.JSONObject jobj = (org.json.JSONObject) f.get(obj);
       if (jobj == null) return;
       String val = jobj.toString();
       if (i != 0) {
         sb.append(", ");
       }
       sb.append("\"");
       sb.append(key);
       sb.append("\"");
       sb.append(":");
       sb.append(val);
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 28
0
  @Override
  protected <T> void putFieldValue(T obj, FieldModel<T> f, Object value) {

    final Field field = f.getField();

    try {
      if (f.isPrivate()) {
        f.getField().set(obj, value);
      } else {
        f.getFieldAccess().putValue(obj, value);
      }
    } catch (IllegalArgumentException e) {
      throw new IllegalStateException(
          "Problem performing clone for field {"
              + field.getName()
              + "} of object {"
              + System.identityHashCode(obj)
              + "}: "
              + e.getMessage(),
          e);
    } catch (IllegalAccessException e) {
      throw new IllegalStateException(
          "Problem performing clone for field {"
              + field.getName()
              + "} of object {"
              + System.identityHashCode(obj)
              + "}: "
              + e.getMessage(),
          e);
    }
  }
 protected Serializable fieldValue(final Object obj, final AnnotatedElement annotatedElement) {
   if (annotatedElement instanceof Field) { // a field
     final Field f = (Field) annotatedElement;
     if (!f.isAccessible()) {
       f.setAccessible(true);
     }
     try {
       return (Serializable) f.get(obj);
     } catch (final IllegalArgumentException e) {
       logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e);
     } catch (final IllegalAccessException e) {
       logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e);
     } catch (final ClassCastException e) {
       logger.warn(obj.getClass().getName() + "的id字段" + f.getName() + "不可序列化。", e);
     }
   } else { // a method
     final Method m = (Method) annotatedElement;
     if (!m.isAccessible()) {
       m.setAccessible(true);
     }
     try {
       return (Serializable) ReflectionUtils.invokeMethod(m, obj);
     } catch (final ClassCastException e) {
       logger.warn(obj.getClass().getName() + "的id字段" + m.getName() + "不可序列化。", e);
     }
   }
   return null;
 }
 @Override
 public void create(Record record, JsonNode json, Class clazz, String dir) throws Exception {
   for (Field f : clazz.getFields()) {
     if (!json.has(f.getName())) return;
     JsonNode j = json.get(f.getName());
     JsonField field = f.getAnnotation(JsonField.class);
     JsonStruc struc = f.getAnnotation(JsonStruc.class);
     if (field != null) {
       SubRecordData sub = record.get(field.value()[0]);
       if (f.getType() == String.class) ((SubZString) sub).value = j.asText();
       else if (f.getType() == JsonFile.class)
         ((SubZString) sub).value =
             (j.asText().startsWith("/") ? j.asText().substring(1) : dir + "/" + j.asText())
                 .replace("/", "\\");
       else if (f.getType() == int[].class)
         for (int i = 0; i < sub.size(); i++) ((SubIntArray) sub).value[i] = j.get(i).intValue();
       else if (f.getType() == JsonFormID[].class) {
         if (field.value()[1] != null) record.get(field.value()[1]);
         ((SubFormIDList) sub).value.clear();
         for (int i = 0; i < sub.size(); i++)
           ((SubFormIDList) sub).value.add(getFormId(j.get(i), field.value(), 2));
       }
     }
     if (struc != null) {
       SubRecordData sub = record.get(struc.value()[0]);
       Field subf = sub.getClass().getField(struc.value()[1]);
       if (f.getType() == int.class) subf.setInt(sub, j.asInt());
       else if (f.getType() == float.class) subf.setFloat(sub, (float) j.asDouble());
     }
   }
 }