Ejemplo n.º 1
0
 /**
  * An introspection based equality predicate for GenericObjects.
  *
  * @other the other object to test against.
  */
 public boolean equals(Object that) {
   if (!this.getClass().equals(that.getClass())) return false;
   Class myclass = this.getClass();
   Field[] fields = myclass.getDeclaredFields();
   Class hisclass = that.getClass();
   Field[] hisfields = hisclass.getDeclaredFields();
   for (int i = 0; i < fields.length; i++) {
     Field f = fields[i];
     Field g = hisfields[i];
     // Only print protected and public members.
     int modifier = f.getModifiers();
     if ((modifier & Modifier.PRIVATE) == Modifier.PRIVATE) continue;
     Class fieldType = f.getType();
     String fieldName = f.getName();
     if (fieldName.compareTo("stringRepresentation") == 0) {
       continue;
     }
     if (fieldName.compareTo("indentation") == 0) {
       continue;
     }
     if (fieldName.compareTo("inputText") == 0) {
       continue;
     }
     try {
       // Primitive fields are printed with type: value
       if (fieldType.isPrimitive()) {
         String fname = fieldType.toString();
         if (fname.compareTo("int") == 0) {
           if (f.getInt(this) != g.getInt(that)) return false;
         } else if (fname.compareTo("short") == 0) {
           if (f.getShort(this) != g.getShort(that)) return false;
         } else if (fname.compareTo("char") == 0) {
           if (f.getChar(this) != g.getChar(that)) return false;
         } else if (fname.compareTo("long") == 0) {
           if (f.getLong(this) != g.getLong(that)) return false;
         } else if (fname.compareTo("boolean") == 0) {
           if (f.getBoolean(this) != g.getBoolean(that)) return false;
         } else if (fname.compareTo("double") == 0) {
           if (f.getDouble(this) != g.getDouble(that)) return false;
         } else if (fname.compareTo("float") == 0) {
           if (f.getFloat(this) != g.getFloat(that)) return false;
         }
       } else if (g.get(that) == f.get(this)) return true;
       else if (f.get(this) == null) return false;
       else if (g.get(that) == null) return false;
       else return f.get(this).equals(g.get(that));
     } catch (IllegalAccessException ex1) {
       InternalErrorHandler.handleException(ex1);
     }
   }
   return false;
 }
Ejemplo n.º 2
0
 /**
  * 设置预编译参数
  *
  * @param ps 预编译
  * @param index 序号
  * @param t vo模型
  * @param f 字段
  * @throws IllegalArgumentException
  * @throws SQLException
  * @throws IllegalAccessException
  */
 private void setParamter(PreparedStatement ps, int index, T t, Field f)
     throws IllegalArgumentException, SQLException, IllegalAccessException {
   if (!f.isAccessible()) {
     f.setAccessible(true);
   }
   if (isBoolean(f)) {
     ps.setBoolean(index, f.getBoolean(t));
   } else if (isInt(f)) {
     ps.setInt(index, f.getInt(t));
   } else if (isLong(f)) {
     ps.setLong(index, f.getLong(t));
   } else if (isString(f)) {
     ps.setString(index, (String) f.get(t));
   } else if (isDate(f)) {
     Object o = f.get(t);
     if (o == null) {
       ps.setDate(index, null);
     } else {
       ps.setTimestamp(index, new java.sql.Timestamp(((Date) o).getTime()));
     }
   } else if (isByte(f)) {
     ps.setByte(index, f.getByte(t));
   } else if (isChar(f)) {
     ps.setInt(index, f.getChar(t));
   } else if (isDouble(f)) {
     ps.setDouble(index, f.getDouble(t));
   } else if (isFloat(f)) {
     ps.setFloat(index, f.getFloat(t));
   } else {
     ps.setObject(index, f.get(t));
   }
 }
  @Test
  public void testSetAmount2() throws Exception {
    System.out.println("setAmount2");

    /* Set up a new loan */
    Loan target = new Loan();

    /* get the setAmount method details */
    Method method = Loan.class.getDeclaredMethod("setAmount", double.class);

    /* make the field assessible */
    method.setAccessible(true);

    /* invoke the method setAmount with the value 3000.0 */
    method.invoke(target, 3000.0);

    /*access the field loanAmount and check its value is set the 3000.0*/
    Class secretClass = target.getClass();
    Field f = secretClass.getDeclaredField("loanAmount");
    f.setAccessible(true);

    double result = f.getDouble(target);

    assertEquals("The amounts should be equal", 3000.00, result, 0.0);
  }
Ejemplo n.º 4
0
 public void buildThresholds(String sourceFieldName)
     throws SecurityException, NoSuchFieldException, IllegalArgumentException,
         IllegalAccessException {
   maxThreshold = 0;
   Class<?> c = objectStore.get(0).getClass();
   // TODO: implement ability to access private fields
   Field field = c.getField(sourceFieldName);
   String type = field.getType().getName();
   for (int i = 0; i != objectStore.size(); i++) {
     if (type.equals("long") || type.equals("java.lang.Long")) {
       maxThreshold += field.getLong(objectStore.get(i));
     } else if (type.equals("double") || type.equals("java.lang.Double")) {
       maxThreshold += Math.round(field.getDouble(objectStore.get(i)) * 1000);
     } else if (type.equals("int") || type.equals("java.lang.Integer")) {
       maxThreshold += field.getInt(objectStore.get(i));
     } else if (type.equals("short") || type.equals("java.lang.Short")) {
       maxThreshold += field.getShort(objectStore.get(i));
     } else if (type.equals("byte") || type.equals("java.lang.Byte")) {
       maxThreshold += field.getByte(objectStore.get(i));
     } else if (type.equals("float") || type.equals("java.lang.Float")) {
       maxThreshold += field.getFloat(objectStore.get(i));
     } else {
       throw new AssertionError(
           "fieldName = " + c.getName() + "." + sourceFieldName + ", type = " + type);
     }
     thresholdStore.add(maxThreshold);
   }
   // TODO: is this a good workaround?
   //		if (maxThreshold == 0) {
   //			System.out.println(Common.printInfo() + ": maxThreshold = 0");
   //			maxThreshold++;
   //		}
 }
Ejemplo n.º 5
0
  private final void from(Object source, java.lang.reflect.Field member, Field<?> field)
      throws IllegalAccessException {

    Class<?> mType = member.getType();

    if (mType.isPrimitive()) {
      if (mType == byte.class) {
        Utils.setValue(this, field, member.getByte(source));
      } else if (mType == short.class) {
        Utils.setValue(this, field, member.getShort(source));
      } else if (mType == int.class) {
        Utils.setValue(this, field, member.getInt(source));
      } else if (mType == long.class) {
        Utils.setValue(this, field, member.getLong(source));
      } else if (mType == float.class) {
        Utils.setValue(this, field, member.getFloat(source));
      } else if (mType == double.class) {
        Utils.setValue(this, field, member.getDouble(source));
      } else if (mType == boolean.class) {
        Utils.setValue(this, field, member.getBoolean(source));
      } else if (mType == char.class) {
        Utils.setValue(this, field, member.getChar(source));
      }
    } else {
      Utils.setValue(this, field, member.get(source));
    }
  }
Ejemplo n.º 6
0
  private boolean packPrimitive(final Field afield, OutputObjectState os) {
    try {
      /*
       * TODO deal with arrays of primitive types.
       *
       * Workaround - provide saveState and restoreState annotations.
       */

      if (afield.getType().equals(Boolean.TYPE)) os.packBoolean(afield.getBoolean(_theObject));
      else if (afield.getType().equals(Byte.TYPE)) os.packByte(afield.getByte(_theObject));
      else if (afield.getType().equals(Short.TYPE)) os.packShort(afield.getShort(_theObject));
      else if (afield.getType().equals(Integer.TYPE)) os.packInt(afield.getInt(_theObject));
      else if (afield.getType().equals(Long.TYPE)) os.packLong(afield.getLong(_theObject));
      else if (afield.getType().equals(Float.TYPE)) os.packFloat(afield.getFloat(_theObject));
      else if (afield.getType().equals(Double.TYPE)) os.packDouble(afield.getDouble(_theObject));
      else if (afield.getType().equals(Character.TYPE)) os.packChar(afield.getChar(_theObject));
      else return false;
    } catch (final IOException ex) {
      return false;
    } catch (final Exception ex) {
      return false;
    }

    return true;
  }
 public static void keep_writeDouble(Parcel paramParcel, Field paramField, Object paramObject) {
   try {
     paramParcel.writeDouble(paramField.getDouble(paramObject));
     return;
   } catch (Exception paramParcel) {
     v.e("MicroMsg.MCacheItem", "exception:%s", new Object[] {be.f(paramParcel)});
   }
 }
Ejemplo n.º 8
0
 public void read() {
   String type = field.getType().getName();
   try {
     if (type.equals("double")) value = field.getDouble(objectReference);
     else if (type.equals("float")) value = field.getFloat(objectReference);
     else if (type.equals("int")) value = field.getInt(objectReference);
     else if (type.equals("byte")) value = field.getByte(objectReference);
     else throw new RuntimeException();
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   }
   value = Math.round(value * getPrecisionMultiplier()) / getPrecisionMultiplier();
 }
Ejemplo n.º 9
0
 /**
  * 创建ContentValues对象通过Field对象
  *
  * @param bean 数据结构
  * @param field Field对象
  * @param cv ContentValues对象
  */
 private void createContentValuesByFields(BaseDaoBean bean, Field field, ContentValues cv) {
   String key = field.getName();
   Object keyValue = null;
   Class<?> clazz = field.getType();
   try {
     if (BaseDBConst.KEY_ID.equals(field.getName())) {
       return;
     }
     keyValue = field.get(bean);
     if (clazz != null && keyValue != null) {
       if (clazz.isPrimitive()) {
         if (Double.TYPE == clazz) {
           cv.put(key, field.getDouble(bean));
         } else if (Float.TYPE == clazz) {
           cv.put(key, field.getFloat(bean));
         } else if (Integer.TYPE == clazz) {
           cv.put(key, field.getInt(bean));
         } else if (Long.TYPE == clazz) {
           cv.put(key, field.getLong(bean));
         } else if (Short.TYPE == clazz) {
           cv.put(key, field.getShort(bean));
         }
       } else if (clazz == byte[].class) {
         cv.put(key, (byte[]) keyValue);
       } else if (Integer.class == clazz) {
         field.set(key, (Integer) keyValue);
       } else if (Long.class == clazz) {
         field.set(key, (Long) keyValue);
       } else if (Float.class == clazz) {
         field.set(key, (Float) keyValue);
       } else if (Double.class == clazz) {
         field.set(key, (Double) keyValue);
       } else if (Boolean.TYPE == clazz) {
         cv.put(key, (Boolean) keyValue);
       } else if (Byte.TYPE == clazz) {
         cv.put(key, (Byte) keyValue);
       } else if (String.class == clazz) {
         cv.put(key, (String) keyValue);
       }
     }
   } catch (IllegalArgumentException e) {
     Log.e(TAG, bean.getClass().getName() + "【" + key + "】的值是:" + keyValue);
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 10
0
 public static double getLoaderVersion() {
   // this is done via reflection to make it work in older version, where the class
   // lucee.loader.Version does not exist
   if (loaderVersion == 0D) {
     loaderVersion = 4D;
     Class cVersion = ClassUtil.loadClass(TP.class.getClassLoader(), "lucee.loader.Version", null);
     if (cVersion != null) {
       try {
         Field f = cVersion.getField("VERSION");
         loaderVersion = f.getDouble(null);
       } catch (Throwable t) {
         t.printStackTrace();
       }
     }
   }
   return loaderVersion;
 }
 // writes fields of a GlobalParcelable to a parcel
 // does not include the first parcelled item -- the class name
 protected static void dehydrate(GlobalParcelable model, Parcel out)
     throws IllegalArgumentException, IllegalAccessException {
   Log.i("GlobalParcelable", "dehydrating... " + model.getClass().toString());
   // get the fields
   Field[] fields = model.getClass().getDeclaredFields();
   // sort the fields so it is in deterministic order
   Arrays.sort(fields, compareMemberByName);
   // populate the fields
   for (Field field : fields) {
     field.setAccessible(true);
     if (field.getType().equals(int.class)) {
       out.writeInt(field.getInt(model));
     } else if (field.getType().equals(double.class)) {
       out.writeDouble(field.getDouble(model));
     } else if (field.getType().equals(float.class)) {
       out.writeFloat(field.getFloat(model));
     } else if (field.getType().equals(long.class)) {
       out.writeLong(field.getLong(model));
     } else if (field.getType().equals(String.class)) {
       out.writeString((String) field.get(model));
     } else if (field.getType().equals(boolean.class)) {
       out.writeByte(field.getBoolean(model) ? (byte) 1 : (byte) 0);
     } else if (field.getType().equals(Date.class)) {
       Date date = (Date) field.get(model);
       if (date != null) {
         out.writeLong(date.getTime());
       } else {
         out.writeLong(0);
       }
     } else if (GlobalParcelable.class.isAssignableFrom(field.getType())) {
       // why did this happen?
       Log.e(
           "GlobalParcelable",
           "GlobalParcelable F*ck up: " + " (" + field.getType().toString() + ")");
       out.writeParcelable((GlobalParcelable) field.get(model), 0);
     } else {
       // wtf
       Log.e(
           "GlobalParcelable",
           "Could not write field to parcel: " + " (" + field.getType().toString() + ")");
     }
   }
 }
Ejemplo n.º 12
0
 @Override
 public Map<String, Object> toMap() {
   Map<String, Object> map = new HashMap<String, Object>();
   Field[] fields = JNIInheritBaseParam.class.getDeclaredFields();
   for (Field field : fields) {
     try {
       field.setAccessible(true);
       if (field.getType().equals(Integer.TYPE))
         map.put(field.getName(), field.getInt(getSelf()));
       else if (field.getType().equals(Double.TYPE))
         map.put(field.getName(), field.getDouble(getSelf()));
       field.setAccessible(false);
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     }
   }
   return map;
 }
  /** Accessing a private field Test of loanamount, of class Loan. */
  @Test
  public void testSetAmount1() throws Exception {
    System.out.println("setAmount1");
    Loan target = new Loan(4000.0, 10.0, 5);

    /*creat secret class */
    Class secretClass = target.getClass();

    /* The the private field */
    Field f = secretClass.getDeclaredField("loanAmount");

    /*Set tha field to accessible */
    f.setAccessible(true);
    System.out.println("The value in f is " + f.get(target));

    /*get the value of the field */
    double result = f.getDouble(target);

    /*Assert the value is correct */
    assertEquals("The amounts should be equal", 4000.00, result, 0.0);
  }
  /**
   * Compares the values of a field for two instances of a class.
   *
   * @param <T> type of the instances. Type must contain the specified field.
   * @param instance1 first instance to test
   * @param instance2 second instance to test
   * @param field field to test
   * @return true iff the primitive fields are equal
   * @throws IllegalAccessException
   * @throws IllegalArgumentException
   */
  public static <T> boolean isPrimitiveFieldContentTheSame(T instance1, T instance2, Field field)
      throws IllegalArgumentException, IllegalAccessException {
    Class<?> type = field.getType();

    if (type == byte.class) return (field.getByte(instance1) == field.getByte(instance2));
    else if (type == short.class) return (field.getShort(instance1) == field.getShort(instance2));
    else if (type == int.class) return (field.getInt(instance1) == field.getInt(instance2));
    else if (type == long.class) return (field.getLong(instance1) == field.getLong(instance2));
    else if (type == float.class) {
      float float1 = field.getFloat(instance1);
      float float2 = field.getFloat(instance2);

      return ((float1 == float2) || (Double.isNaN(float1) && Double.isNaN(float2)));
    } else if (type == double.class) {
      double double1 = field.getDouble(instance1);
      double double2 = field.getDouble(instance2);

      return ((double1 == double2) || (Double.isNaN(double1) && Double.isNaN(double2)));
    } else if (type == boolean.class)
      return (field.getBoolean(instance1) == field.getBoolean(instance2));
    else if (type == char.class) return (field.getChar(instance1) == field.getChar(instance2));
    else throw new RuntimeException("Field content is not primitive");
  }
Ejemplo n.º 15
0
  private static String get(Object obj, Field field) {

    try {
      if (!field.isAccessible()) {
        field.setAccessible(true);
      }

      if (field.getType() == int.class) {
        return String.valueOf(field.getInt(obj));

      } else if (field.getType() == long.class) {
        return String.valueOf(field.getLong(obj));

      } else if (field.getType() == double.class) {
        return String.valueOf(field.getDouble(obj));
      } else if (field.getType() == byte.class) {
        return String.valueOf(field.getByte(obj));
      } else if (field.getType() == boolean.class) {
        return String.valueOf(field.getBoolean(obj));
      } else if (field.getType() == String.class) {
        if (field.get(obj) == null) {
          return "";
        }
        return String.valueOf(field.get(obj));
      } else if (field.getType() == Date.class) {
        if (field.get(obj) == null) {
          return "";
        }
        return MiscDateUtils.getDateTime((Date) field.get(obj));
      }

    } catch (Exception e) {

    }
    return "";
  }
Ejemplo n.º 16
0
  public static FakeBoundingBox getBoundingBox(Entity entity) {
    try {
      Object boundingBox = getNmsField("Entity", "boundingBox").get(getNmsEntity(entity));
      double x = 0, y = 0, z = 0;
      int stage = 0;
      for (Field field : boundingBox.getClass().getFields()) {
        if (field.getType().getSimpleName().equals("double")) {
          stage++;
          switch (stage) {
            case 1:
              x -= field.getDouble(boundingBox);
              break;
            case 2:
              y -= field.getDouble(boundingBox);
              break;
            case 3:
              z -= field.getDouble(boundingBox);
              break;
            case 4:
              x += field.getDouble(boundingBox);
              break;
            case 5:
              y += field.getDouble(boundingBox);
              break;
            case 6:
              z += field.getDouble(boundingBox);
              break;
            default:
              throw new Exception(
                  "Error while setting the bounding box, more doubles than I thought??");
          }
        }
      }
      return new FakeBoundingBox(x, y, z);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 17
0
  @SuppressWarnings("rawtypes")
  public void setData(
      Object obj, ByteBuffer byteBuffer, float[] floatValues, String[] stringValues, Indexes index)
      throws IllegalArgumentException, IllegalAccessException {

    Reporter r = null;

    if (BuildCraftCore.trackNetworkUsage) {
      if (!report.containsKey(clas.getName())) report.put(clas.getName(), new Reporter());

      r = report.get(clas.getName());
      r.clas = clas;
    } else r = new Reporter();

    r.occurences++;

    for (Field f : shortFields) {
      byteBuffer.writeShort(f.getShort(obj));
      r.bytes += 2;
      r.dataInt += 1;
    }

    for (Field f : intFields) {
      byteBuffer.writeInt(f.getInt(obj));
      r.bytes += 4;
      r.dataInt += 1;
    }

    for (Field f : booleanFields) {
      byteBuffer.writeUnsignedByte(f.getBoolean(obj) ? 1 : 0);
      r.bytes += 1;
      r.dataInt += 1;
    }

    for (Field f : enumFields) {
      byteBuffer.writeUnsignedByte(((Enum) f.get(obj)).ordinal());
      r.bytes += 1;
      r.dataInt += 1;
    }

    for (Field f : unsignedByteFields) {
      byteBuffer.writeUnsignedByte(f.getInt(obj));
      r.bytes += 1;
      r.dataInt += 1;
    }

    for (Field f : floatFields) {
      floatValues[index.floatIndex] = f.getFloat(obj);
      index.floatIndex++;
      r.bytes += 4;
      r.dataFloat += 1;
    }

    for (Field f : doubleFields) {
      floatValues[index.floatIndex] = (float) f.getDouble(obj);
      index.floatIndex++;
      r.bytes += 4;
      r.dataFloat += 1;
    }

    for (Field f : stringFields) {
      stringValues[index.stringIndex] = (String) f.get(obj);
      r.bytes += stringValues[index.stringIndex].length();
      index.stringIndex++;
      r.dataString += 1;
    }

    for (ClassMapping c : objectFields) {
      Object cpt = c.field.get(obj);

      if (cpt == null) {
        byteBuffer.writeUnsignedByte(0);

        for (int i = 0; i < c.sizeBytes; ++i) {
          byteBuffer.writeUnsignedByte(0);
          r.bytes += 1;
          r.dataInt += 1;
        }

        index.floatIndex += c.sizeFloat;
        index.stringIndex += c.sizeString;
      } else {
        byteBuffer.writeUnsignedByte(1);
        r.bytes += 1;
        r.dataInt += 1;

        c.setData(cpt, byteBuffer, floatValues, stringValues, index);
      }
    }

    for (Field f : doubleArrayFields) {
      TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i) {
        floatValues[index.floatIndex] = (float) ((double[]) f.get(obj))[i];
        index.floatIndex++;
        r.bytes += 4;
        r.dataFloat += 1;
      }
    }

    for (Field f : shortArrayFields) {
      TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i) {
        byteBuffer.writeShort(((short[]) f.get(obj))[i]);
        r.bytes += 2;
        r.dataInt += 1;
      }
    }

    for (Field f : intArrayFields) {
      TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i) {
        byteBuffer.writeInt(((int[]) f.get(obj))[i]);
        r.bytes += 4;
        r.dataInt += 1;
      }
    }

    for (Field f : booleanArrayFields) {
      TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i) {
        byteBuffer.writeUnsignedByte(((boolean[]) f.get(obj))[i] ? 1 : 0);
        r.bytes += 1;
        r.dataInt += 1;
      }
    }

    for (Field f : unsignedByteFields) {
      TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i) {
        byteBuffer.writeUnsignedByte(((int[]) f.get(obj))[i]);
        r.bytes += 1;
        r.dataInt += 1;
      }
    }

    for (Field f : stringArrayFields) {
      TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i) {
        stringValues[index.stringIndex] = ((String[]) f.get(obj))[i];
        r.bytes += stringValues[index.stringIndex].length();
        index.stringIndex++;
        r.dataString += 1;
      }
    }

    for (ClassMapping c : objectArrayFields) {
      TileNetworkData updateAnnotation = c.field.getAnnotation(TileNetworkData.class);

      Object[] cpts = (Object[]) c.field.get(obj);

      for (int i = 0; i < updateAnnotation.staticSize(); ++i)
        if (cpts[i] == null) {
          byteBuffer.writeUnsignedByte(0);

          for (int j = 0; j < c.sizeBytes; ++j) {
            byteBuffer.writeUnsignedByte(0);
            r.bytes += 1;
            r.dataInt += 1;
          }

          index.floatIndex += c.sizeFloat;
          index.stringIndex += c.sizeString;
        } else {
          byteBuffer.writeUnsignedByte(1);
          r.bytes += 1;
          r.dataInt += 1;

          c.setData(cpts[i], byteBuffer, floatValues, stringValues, index);
        }
    }
  }
Ejemplo n.º 18
0
  /**
   * Generic print formatting function: Does depth-first descent of the structure and recursively
   * prints all non-private objects pointed to by this object. <bf> Warning - the following generic
   * string routine will bomb (go into infinite loop) if there are any circularly linked structures
   * so if you have these, they had better be private! </bf> We dont have to worry about such things
   * for our structures (we never use circular linked structures).
   */
  public String toString() {
    stringRepresentation = "";
    Class myclass = getClass();
    sprint(myclass.getName());
    sprint("{");
    sprint("inputText:");
    sprint(inputText);
    Field[] fields = myclass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
      Field f = fields[i];
      // Only print protected and public members.
      int modifier = f.getModifiers();
      if ((modifier & Modifier.PRIVATE) == Modifier.PRIVATE) continue;
      Class fieldType = f.getType();
      String fieldName = f.getName();
      if (fieldName.compareTo("stringRepresentation") == 0) {
        // avoid nasty recursions...
        continue;
      }
      if (fieldName.compareTo("indentation") == 0) {
        // formatting stuff - not relevant here.
        continue;
      }
      sprint(fieldName + ":");
      try {
        // Primitive fields are printed with type: value
        if (fieldType.isPrimitive()) {
          String fname = fieldType.toString();
          sprint(fname + ":");
          if (fname.compareTo("int") == 0) {
            int intfield = f.getInt(this);
            sprint(intfield);
          } else if (fname.compareTo("short") == 0) {
            short shortField = f.getShort(this);
            sprint(shortField);
          } else if (fname.compareTo("char") == 0) {
            char charField = f.getChar(this);
            sprint(charField);
          } else if (fname.compareTo("long") == 0) {
            long longField = f.getLong(this);
            sprint(longField);
          } else if (fname.compareTo("boolean") == 0) {
            boolean booleanField = f.getBoolean(this);
            sprint(booleanField);
          } else if (fname.compareTo("double") == 0) {
            double doubleField = f.getDouble(this);
            sprint(doubleField);
          } else if (fname.compareTo("float") == 0) {
            float floatField = f.getFloat(this);
            sprint(floatField);
          }
        } else if (Class.forName(SIP_PACKAGE + ".GenericObject").isAssignableFrom(fieldType)) {
          if (f.get(this) != null) {
            sprint(((GenericObject) f.get(this)).toString(indentation + 1));
          } else {
            sprint("<null>");
          }

        } else if (Class.forName(SIP_PACKAGE + ".GenericObjectList").isAssignableFrom(fieldType)) {
          if (f.get(this) != null) {
            sprint(((GenericObjectList) f.get(this)).toString(indentation + 1));
          } else {
            sprint("<null>");
          }

        } else {
          // Dont do recursion on things that are not
          // of our header type...
          if (f.get(this) != null) {
            sprint(f.get(this).getClass().getName() + ":");
          } else {
            sprint(fieldType.getName() + ":");
          }

          sprint("{");
          if (f.get(this) != null) {
            sprint(f.get(this).toString());
          } else {
            sprint("<null>");
          }
          sprint("}");
        }
      } catch (IllegalAccessException ex1) {
        continue; // we are accessing a private field...
      } catch (Exception ex) {
        InternalErrorHandler.handleException(ex);
      }
    }
    sprint("}");
    return stringRepresentation;
  }
Ejemplo n.º 19
0
 /**
  * An introspection based predicate matching using a template object. Allows for partial match of
  * two protocl Objects.
  *
  * @other the match pattern to test against. The match object has to be of the same type (class).
  *     Primitive types and non-sip fields that are non null are matched for equality. Null in any
  *     field matches anything. Some book-keeping fields are ignored when making the comparison.
  */
 public boolean match(Object other) {
   if (other == null) return true;
   if (!this.getClass().equals(other.getClass())) return false;
   GenericObject that = (GenericObject) other;
   Class myclass = this.getClass();
   Field[] fields = myclass.getDeclaredFields();
   Class hisclass = other.getClass();
   Field[] hisfields = hisclass.getDeclaredFields();
   for (int i = 0; i < fields.length; i++) {
     Field f = fields[i];
     Field g = hisfields[i];
     // Only print protected and public members.
     int modifier = f.getModifiers();
     if ((modifier & Modifier.PRIVATE) == Modifier.PRIVATE) continue;
     Class fieldType = f.getType();
     String fieldName = f.getName();
     if (fieldName.compareTo("stringRepresentation") == 0) {
       continue;
     }
     if (fieldName.compareTo("indentation") == 0) {
       continue;
     }
     if (fieldName.compareTo("inputText") == 0) {
       continue;
     }
     try {
       // Primitive fields are printed with type: value
       if (fieldType.isPrimitive()) {
         String fname = fieldType.toString();
         if (fname.compareTo("int") == 0) {
           if (f.getInt(this) != g.getInt(that)) return false;
         } else if (fname.compareTo("short") == 0) {
           if (f.getShort(this) != g.getShort(that)) return false;
         } else if (fname.compareTo("char") == 0) {
           if (f.getChar(this) != g.getChar(that)) return false;
         } else if (fname.compareTo("long") == 0) {
           if (f.getLong(this) != g.getLong(that)) return false;
         } else if (fname.compareTo("boolean") == 0) {
           if (f.getBoolean(this) != g.getBoolean(that)) return false;
         } else if (fname.compareTo("double") == 0) {
           if (f.getDouble(this) != g.getDouble(that)) return false;
         } else if (fname.compareTo("float") == 0) {
           if (f.getFloat(this) != g.getFloat(that)) return false;
         }
       } else {
         Object myObj = f.get(this);
         Object hisObj = g.get(that);
         if (hisObj == myObj) return true;
         else if (hisObj != null && myObj == null) return false;
         else if (GenericObject.isMySubclass(myObj.getClass())
             && !((GenericObject) myObj).match(hisObj)) return false;
         else if (hisObj instanceof java.lang.String && myObj instanceof java.lang.String) {
           if (((String) myObj).compareToIgnoreCase((String) hisObj) != 0) return false;
         } else if (GenericObjectList.isMySubclass(myObj.getClass())
             && !((GenericObjectList) myObj).match(hisObj)) return false;
       }
     } catch (IllegalAccessException ex1) {
       InternalErrorHandler.handleException(ex1);
     }
   }
   return true;
 }
Ejemplo n.º 20
0
  @Override
  protected <T> void handleClonePrimitiveField(
      T obj,
      T copy,
      CloneDriver driver,
      FieldModel<T> f,
      IdentityHashMap<Object, Object> referencesToReuse) {

    Field field = f.getField();

    try {
      Class<?> clazz = f.getFieldClass();

      if (f.isPrivate()) {
        if (java.lang.Boolean.TYPE == clazz) {
          field.setBoolean(copy, field.getBoolean(obj));
        } else if (java.lang.Byte.TYPE == clazz) {
          field.setByte(copy, field.getByte(obj));
        } else if (java.lang.Character.TYPE == clazz) {
          field.setChar(copy, field.getChar(obj));
        } else if (java.lang.Short.TYPE == clazz) {
          field.setShort(copy, field.getShort(obj));
        } else if (java.lang.Integer.TYPE == clazz) {
          field.setInt(copy, field.getInt(obj));
        } else if (java.lang.Long.TYPE == clazz) {
          field.setLong(copy, field.getLong(obj));
        } else if (java.lang.Float.TYPE == clazz) {
          field.setFloat(copy, field.getFloat(obj));
        } else if (java.lang.Double.TYPE == clazz) {
          field.setDouble(copy, field.getDouble(obj));
        } else {
          throw new IllegalStateException("Expected primitive but was :" + clazz.getName());
        }
      } else {
        if (java.lang.Boolean.TYPE == clazz) {
          f.getFieldAccess().putBooleanValue(copy, field.getBoolean(obj));
        } else if (java.lang.Byte.TYPE == clazz) {
          f.getFieldAccess().putByteValue(copy, field.getByte(obj));
        } else if (java.lang.Character.TYPE == clazz) {
          f.getFieldAccess().putCharValue(copy, field.getChar(obj));
        } else if (java.lang.Short.TYPE == clazz) {
          f.getFieldAccess().putShortValue(copy, field.getShort(obj));
        } else if (java.lang.Integer.TYPE == clazz) {
          f.getFieldAccess().putIntValue(copy, field.getInt(obj));
        } else if (java.lang.Long.TYPE == clazz) {
          f.getFieldAccess().putLongValue(copy, field.getLong(obj));
        } else if (java.lang.Float.TYPE == clazz) {
          f.getFieldAccess().putFloatValue(copy, field.getFloat(obj));
        } else if (java.lang.Double.TYPE == clazz) {
          f.getFieldAccess().putDoubleValue(copy, field.getDouble(obj));
        } else {
          throw new IllegalStateException("Expected primitive but was :" + clazz.getName());
        }
      }

    } 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);
    }
  }
 double getDouble(Object obj) throws IllegalArgumentException, IllegalAccessException {
   return javaField.getDouble(obj);
 }
Ejemplo n.º 22
0
  /** 数据绑定 * */
  private void bindValues(SQLiteStatement stmt, T entity) {
    for (int i = 0; i < mSetArgs.length; i++) {
      int stmtIndex = i + 1;
      try {
        Field field = mClazz.getDeclaredField(mSetArgs[i]);
        field.setAccessible(true);

        Type columnType = field.getType();
        if (String.class.equals(columnType)) {
          String value = (String) field.get(entity);
          if (value == null) {
            stmt.bindNull(stmtIndex);
          } else {
            stmt.bindString(stmtIndex, value);
          }

        } else if (columnType.equals(Integer.class) || columnType.equals(int.class)) {
          int value = field.getInt(entity);
          stmt.bindLong(stmtIndex, value);

        } else if (columnType.equals(Float.class) || columnType.equals(float.class)) {
          float value = field.getFloat(entity);
          stmt.bindDouble(stmtIndex, value);

        } else if (columnType.equals(Double.class) || columnType.equals(double.class)) {
          double value = field.getDouble(entity);
          stmt.bindDouble(stmtIndex, value);

        } else if (columnType.equals(Long.class) || columnType.equals(long.class)) {
          long value = field.getLong(entity);
          stmt.bindLong(stmtIndex, value);

        } else {
          Object obj = field.get(entity);
          if (obj == null) {
            stmt.bindNull(stmtIndex);
          } else {
            byte[] value = SerializeHelper.serialize(obj);
            stmt.bindBlob(stmtIndex, value);
          }
        }

      } catch (NoSuchFieldException e) {
        e.printStackTrace();
        stmt.bindNull(stmtIndex);
        continue;
      } catch (IllegalAccessException e) {
        e.printStackTrace();
        stmt.bindNull(stmtIndex);
        continue;
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
        stmt.bindNull(stmtIndex);
        continue;
      }
    }

    if (mWhereArgs != null) {
      for (int i = 0; i < mWhereArgs.length; i++) {
        int columnIndex = mSetArgs.length + i + 1;
        stmt.bindString(columnIndex, mWhereArgValues[i]);
      }
    }
  }
Ejemplo n.º 23
0
  /**
   * Read the argument of the function from the ports, call the native method throw the generated
   * interface, and put the results on the corresponding ports.
   *
   * @exception IllegalActionException If a exception occured
   */
  public void fire() throws IllegalActionException {
    super.fire();
    // getting the in/inout parameters
    Iterator ports = this.portList().iterator();
    Vector args = new Vector();

    while (ports.hasNext()) {
      TypedIOPort port = (TypedIOPort) ports.next();

      if (port.isInput() && port.hasToken(0) && !(port.isOutput() && !port.isInput())) {
        Token tok = port.get(0);

        String typ = _methods[_methodIndex].getParameterTypes()[args.size()].toString();

        if (typ.equals("boolean")) {
          args.add(Boolean.valueOf(((BooleanToken) tok).booleanValue()));
        } else if (typ.equals("int")) {
          args.add(Integer.valueOf(((IntToken) tok).intValue()));
        } else if (typ.equals("long")) {
          args.add(Long.valueOf(((ScalarToken) tok).longValue()));
        } else if (typ.equals("double")) {
          args.add(Double.valueOf(((DoubleToken) tok).doubleValue()));
        } else if (typ.equals("class [I")) {
          int siz = ((ArrayToken) tok).arrayValue().length;
          int[] tab = new int[siz];

          for (int j = 0; j < siz; j++) {
            tab[j] = ((IntToken) (((ArrayToken) tok).arrayValue()[j])).intValue();
          }

          // (int[])((ArrayToken)tok).arrayValue();
          args.add(tab);
        } else if (typ.equals("class [J")) {
          int siz = ((ArrayToken) tok).length();
          long[] tab = new long[siz];

          for (int j = 0; j < siz; j++) {
            Token element = ((ArrayToken) tok).getElement(j);
            try {
              tab[j] = ((LongToken) element).longValue();
            } catch (Throwable throwable) {
              throw new IllegalActionException(
                  this,
                  throwable,
                  "Failed to create LongToken, element "
                      + j
                      + " was: "
                      + element.getClass().getName()
                      + ", value: "
                      + element
                      + ", port: "
                      + port);
            }
          }

          // (int[])((ArrayToken)tok).arrayValue();
          args.add(tab);
        } else {
          System.out.println(
              "The intype \"" + typ + "\" is not convertible " + "with Ptolemy II types.");
        }
      }
    }

    // tBFixed : the out parameter is not in by definition
    // ...so no port in can initialize the param
    // call the native function
    Object obj = null;
    Object ret = null;

    try {
      try {
        obj = _class.newInstance();
      } catch (Error error) {
        // Using JNI to link in a native library
        // can result in a java.lang.UnsatisfiedLinkError
        // which extends Error, not Exception.
        // FIXME: Rethrow the error as an exception
        String libraryPath = StringUtilities.getProperty("java.library.path");

        throw new Exception(
            "Class '"
                + _class
                + "' cannot be instantiated.\n"
                + "If you are running under Windows, "
                + "be sure that the directory containing the library "
                + "is in your PATH.\n"
                + "If you are running under Solaris, "
                + "be sure that the directory containing the library "
                + "is in your LD_LIBRARY_PATH and that the library "
                + "name begin with 'lib' and end with '.so'.\n"
                + "You may need to exit, set your "
                + "PATH or LD_LIBRARY_PATH to include the directory "
                + "that contains the shared library and "
                + "restart.\n"
                + "For example, under Windows "
                + "in a Cygwin bash shell:\n"
                + "PATH=/cygdrive/c/ptII/jni/dll:${PATH}\n"
                + "export PATH\n"
                + "vergil -jni foo.xml\n"
                + "A common error is that "
                + "the class cannot be found in "
                + "property 'java.library.path' "
                + "which is:\n"
                + libraryPath
                + "\nError message was: "
                + error.getMessage(),
            error);
      }
    } catch (Exception ex) {
      throw new IllegalActionException(this, ex, "Class cannot be instantiated");
    }

    try {
      ret = _methods[_methodIndex].invoke(obj, args.toArray());
    } catch (Throwable ex) {
      StringBuffer argumentsDescription = new StringBuffer("");

      try {
        if (args.size() >= 1) {
          argumentsDescription.append(args.elementAt(0).toString());

          for (int i = 1; i < args.size(); i++) {
            argumentsDescription.append(", " + args.elementAt(i).toString());
          }
        }
      } catch (Throwable throwable) {
        // Ignore
      }

      throw new IllegalActionException(
          this,
          ex,
          "Native operation call failed."
              + "Failed to invoke '"
              + obj
              + "' with "
              + args.size()
              + " arg(s) "
              + argumentsDescription.toString());
    }

    ports = portList().iterator();

    while (ports.hasNext()) {
      TypedIOPort port = (TypedIOPort) ports.next();

      // if the argument is return
      if (getArgumentReturn() == null) {
        System.err.println("Warning: GenericJNIActor.java: " + "getArgumentReturn() returns null?");
      }

      if ((port != null)
          && (port.getName() != null)
          && (getArgumentReturn() != null)
          && port.getName().equals(this.getArgumentReturn().getName())) {
        String typ = "";
        Field field = null;

        try {
          field = _class.getDeclaredField("_" + port.getName());
          typ = field.getType().toString();
        } catch (NoSuchFieldException e) {
          try {
            throw new IllegalActionException(
                this, e, "No return type field '_" + port.getName() + "'");
          } catch (Throwable throwable) {
            getDirector().stop();
          }
        }

        if (typ.equals("boolean")) {
          port.send(0, new BooleanToken(((Boolean) ret).booleanValue()));
        } else if (typ.equals("double")) {
          port.send(0, new DoubleToken(((Double) ret).doubleValue()));
        } else if (typ.equals("int")) {
          port.send(0, new IntToken(((Integer) ret).intValue()));
        } else if (typ.equals("long")) {
          port.send(0, new LongToken(((Long) ret).longValue()));
        } else if (typ.equals("char")) {
          port.send(0, new UnsignedByteToken(((Byte) ret).byteValue()));
        } else {
          System.out.println("The return type is not convertible " + "with Ptolemy II types.");
        }
      }
      // if the argument is output
      else if ((port != null)
          && port.isOutput()
          && (port.getName() != null)
          && (getArgumentReturn() != null)
          && !(port.getName().equals(this.getArgumentReturn().getName()))) {
        String typ = "";
        Field field = null;

        try {
          field = _class.getDeclaredField("_" + port.getName());
          typ = field.getType().toString();
        } catch (NoSuchFieldException ex) {
          try {
            field =
                _class.getDeclaredField(
                    "_" + port.getName().substring(0, port.getName().length() - 3));
            typ = field.getType().toString();
          } catch (Throwable throwable) {
            try {
              throw new IllegalActionException(
                  this, throwable, "No '+" + port.getName() + "' field !");
            } catch (Throwable throwable2) {
              getDirector().stop();
            }
          }
        }

        if (field == null) {
          throw new InternalErrorException(
              "Field '" + port.getName() + "' in '" + _class + "' is null?");
        } else {
          if (typ.equals("boolean")) {
            try {
              port.send(0, new BooleanToken(field.getBoolean(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("double")) {
            try {
              port.send(0, new DoubleToken(field.getDouble(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("int")) {
            try {
              port.send(0, new IntToken(field.getInt(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("long")) {
            try {
              port.send(0, new LongToken(field.getLong(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("char")) {
            try {
              port.send(0, new UnsignedByteToken(field.getChar(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("class [I")) {
            try {
              if (obj == null) {
                throw new InternalErrorException("obj == null?");
              }
              if (field.get(obj) == null) {
                throw new InternalErrorException(
                    "field.get(obj)  == null? (field = " + field + " obj = " + obj);
              }
              Token[] toks = new Token[((int[]) field.get(obj)).length];

              for (int j = 0; j < ((int[]) field.get(obj)).length; j++) {
                toks[j] = new IntToken(((int[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(BaseType.INT, toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("class [J")) {
            Token[] toks = null;
            try {
              if (obj == null) {
                throw new InternalErrorException("obj == null?");
              }
              if (field.get(obj) == null) {
                throw new InternalErrorException(
                    "field.get(obj)  == null? (field = " + field + " obj = " + obj);
              }
              toks = new Token[((long[]) field.get(obj)).length];

              for (int j = 0; j < ((long[]) field.get(obj)).length; j++) {
                toks[j] = new LongToken(((long[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(BaseType.LONG, toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            } catch (IllegalActionException ex2) {
              throw new IllegalActionException(
                  this,
                  ex2,
                  "Failed to send a Long array token "
                      + (toks == null ? "null" : toks.length)
                      + " to "
                      + port);
            }
          } else if (typ.equals("class [D")) {
            try {
              Token[] toks = new Token[((double[]) field.get(obj)).length];

              for (int j = 0; j < ((double[]) field.get(obj)).length; j++) {
                toks[j] = new DoubleToken(((double[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else {
            // FIXME: for char[] and boolean[], there is
            // no corresponding Token type.
            System.out.println(
                "The outtype '" + typ + "' is not convertible " + "with Ptolemy II types.");
          }
        }
      }
    }
  }