Example #1
2
  private static Object unmarshallMsgData(int formatter, int byteArray, Class msgDataClass)
      throws Exception {
    Object object = null;

    // Throw an exception if class does not match formatter
    formatters.checkDataClass(formatter, msgDataClass);

    if (msgDataClass.isArray()) {
      // Create a top-level fixed-length array, based on the formatter.
      object = formatters.createFixedArray(msgDataClass.getComponentType(), formatter);
    } else {
      // Create an object type that Java IPC can handle
      object = coerceDataClass(msgDataClass).newInstance();
    }
    formatters.unmarshall(formatter, byteArray, object);
    IPC_freeByteArray(byteArray);
    if (formatters.IPCPrim.class.isAssignableFrom(object.getClass())) {
      object = ((formatters.IPCPrim) object).coerce();
    }

    return object;
  }
Example #2
0
 /**
  * Gets the datatype of the object.
  *
  * @param obj the object
  * @return the type
  */
 public static String getDataType(Object obj) {
   if (obj == null) {
     return null;
   }
   if (obj instanceof String) {
     return "string"; //$NON-NLS-1$
   } else if (obj instanceof Collection) {
     return "collection"; //$NON-NLS-1$
   } else if (obj.getClass().isArray()) {
     // make sure ultimate component class is acceptable
     Class componentType = obj.getClass().getComponentType();
     while (componentType.isArray()) {
       componentType = componentType.getComponentType();
     }
     String type = componentType.getName();
     if (type.indexOf(".") == -1
         && "intdoubleboolean".indexOf(type) == -1) { // $NON-NLS-1$ //$NON-NLS-2$
       return null;
     }
     return "array"; //$NON-NLS-1$
   } else if (obj instanceof Double) {
     return "double"; //$NON-NLS-1$
   } else if (obj instanceof Integer) {
     return "int"; //$NON-NLS-1$
   } else {
     return "object"; //$NON-NLS-1$
   }
 }
Example #3
0
 private static Object parseValue(String value, Prop p, Class type) {
   Object v = value;
   if (type.isArray()) {
     StringTokenizer st = new StringTokenizer(value, ",");
     Class ctype = type.getComponentType();
     v = Array.newInstance(ctype, st.countTokens());
     for (int i = 0; st.hasMoreTokens(); i++)
       Array.set(v, i, parseValue(st.nextToken(), p, ctype));
   } else if (type == boolean.class) {
     v = Boolean.valueOf(value);
   } else if (type == double.class) {
     v = Double.valueOf(value);
   } else if (type == int.class) {
     v = Integer.valueOf(value);
   } else if (p.field.isAnnotationPresent(TimeIntervalProp.class)) {
     if (value.endsWith("s")) {
       v = (long) (Double.parseDouble(value.substring(0, value.length() - 1)) * SEC);
     } else if (value.endsWith("m")) {
       v = (long) (Double.parseDouble(value.substring(0, value.length() - 1)) * MIN);
     } else {
       v = Long.valueOf(value);
     }
   }
   return v;
 }
Example #4
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param value The value of the XML attribute containing the prop value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, String value) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)) {
      return parseBasicType(type, value);
    } else if (String.class.isAssignableFrom(type)) {
      return value;
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return parseDate(value, JOXDateHandler.determineDateFormat());
    } else {
      return null;
    }
  }
Example #5
0
  /** Write a {@link Writable}, {@link String}, primitive type, or an array of the preceding. */
  public static void writeObject(
      DataOutput out, Object instance, Class declaredClass, Configuration conf) throws IOException {

    if (instance == null) { // null
      instance = new NullInstance(declaredClass, conf);
      declaredClass = Writable.class;
    }

    UTF8.writeString(out, declaredClass.getName()); // always write declared

    if (declaredClass.isArray()) { // array
      int length = Array.getLength(instance);
      out.writeInt(length);
      for (int i = 0; i < length; i++) {
        writeObject(out, Array.get(instance, i), declaredClass.getComponentType(), conf);
      }

    } else if (declaredClass == String.class) { // String
      UTF8.writeString(out, (String) instance);

    } else if (declaredClass.isPrimitive()) { // primitive type

      if (declaredClass == Boolean.TYPE) { // boolean
        out.writeBoolean(((Boolean) instance).booleanValue());
      } else if (declaredClass == Character.TYPE) { // char
        out.writeChar(((Character) instance).charValue());
      } else if (declaredClass == Byte.TYPE) { // byte
        out.writeByte(((Byte) instance).byteValue());
      } else if (declaredClass == Short.TYPE) { // short
        out.writeShort(((Short) instance).shortValue());
      } else if (declaredClass == Integer.TYPE) { // int
        out.writeInt(((Integer) instance).intValue());
      } else if (declaredClass == Long.TYPE) { // long
        out.writeLong(((Long) instance).longValue());
      } else if (declaredClass == Float.TYPE) { // float
        out.writeFloat(((Float) instance).floatValue());
      } else if (declaredClass == Double.TYPE) { // double
        out.writeDouble(((Double) instance).doubleValue());
      } else if (declaredClass == Void.TYPE) { // void
      } else {
        throw new IllegalArgumentException("Not a primitive: " + declaredClass);
      }
    } else if (declaredClass.isEnum()) { // enum
      UTF8.writeString(out, ((Enum) instance).name());
    } else if (Writable.class.isAssignableFrom(declaredClass)) { // Writable
      UTF8.writeString(out, instance.getClass().getName());
      ((Writable) instance).write(out);

    } else {
      throw new IOException("Can't write: " + instance + " as " + declaredClass);
    }
  }
 static String jni_signature(Class c) {
   if (c == int.class) return "I";
   if (c == long.class) return "J";
   if (c == short.class) return "S";
   if (c == byte.class) return "B";
   if (c == boolean.class) return "Z";
   if (c == double.class) return "D";
   if (c == float.class) return "F";
   if (c == char.class) return "C";
   if (c == void.class) return "V";
   if (c.isArray()) return "[" + jni_signature(c.getComponentType());
   return "L" + name(c) + ";";
 }
Example #7
0
  public static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception {

    Configuration[] list = admin.listConfigurations(filter);
    Encoder encoder = codec.enc().to(osw);

    Protocol p = new Protocol();
    p.version = 1;
    p.date = new Date();
    p.size = list.length;
    encoder.put(p).append('\n');

    if (list != null)
      for (Configuration c : list) {
        Dictionary<String, Object> d = c.getProperties();
        Export export = new Export();
        export.values = new HashMap<String, Object>();
        export.factoryPid = c.getFactoryPid();
        export.pid = c.getPid();

        for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
          String k = e.nextElement();
          Object v = d.get(k);

          if (!(v instanceof String)) {

            if (export.types == null) export.types = new HashMap<String, Type>();

            Type type = new Type();

            Class<?> clazz = v.getClass();
            if (v instanceof Collection) {
              Collection<?> coll = (Collection<?>) v;
              clazz = String.class;
              if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass());
              else type.vectorOf = shortName(String.class);
            } else if (v.getClass().isArray()) {
              type.arrayOf = shortName(clazz.getComponentType());
            } else type.scalar = shortName(v.getClass());

            export.types.put(k, type);
          }
          export.values.put(k, v);
        }

        encoder.mark().put(export);
        // encoder.put(encoder.digest());
        encoder.append('\n');
      }
    osw.flush();
  }
Example #8
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }
Example #9
0
  private static void writeValue(Object value, OutputStream os) throws IOException {

    if (value == null) {
      os.write(-1);
    } else {
      Class valueClass = value.getClass();
      // write 0 for a single value, 1 for array, and 2 for Vector
      if (valueClass.isArray()) {
        os.write(1);
        int length = Array.getLength(value);
        PDataStream.writeInt(length, os);
        Class componentType = valueClass.getComponentType();
        if (componentType.isPrimitive()) {
          // primitive
          PDataStream.writeBoolean(true, os);
          // 1: int;2: long; 3: byte; 4: boolean; 5: character; 6:
          // short; 7: float; 8: double
          writePrimitiveArray(componentType, value, length, os);
        } else {
          PDataStream.writeBoolean(false, os);
          PDataStream.writeUTF(componentType.getName(), os);
          Object[] oArr = (Object[]) value;
          for (int i = 0; i < length; i++) {
            writeValue(oArr[i], os);
          }
        }
      } else if (valueClass.equals(Vector.class)) {
        os.write(2);
        int size = ((Vector) value).size();
        PDataStream.writeInt(size, os);
        for (int i = 0; i < size; i++) {
          writeValue(((Vector) value).elementAt(i), os);
        }
      } else {
        os.write(0);
        writeRealObject(value, valueClass, os);
      }
    }
  }
Example #10
0
 private static StringBuilder appendTypeString(StringBuilder sb, Class<?> type) {
   while (type.isArray()) {
     sb.append('[');
     type = type.getComponentType();
   }
   if (type.isPrimitive()) {
     char typeLetter;
     if (type == Boolean.TYPE) {
       typeLetter = 'Z';
     } else if (type == Long.TYPE) {
       typeLetter = 'J';
     } else {
       String typeName = type.getName();
       typeLetter = Character.toUpperCase(typeName.charAt(0));
     }
     sb.append(typeLetter);
   } else {
     sb.append('L');
     sb.append(type.getName().replace('.', '/'));
     sb.append(';');
   }
   return sb;
 }
 /** Mimics SimpleXML's naming for classes without {@link Root#name()}. */
 private static String getClassName(Class<?> type) {
   if (type.isArray()) type = type.getComponentType();
   final String name = type.getSimpleName();
   if (type.isPrimitive()) return name;
   else return Introspector.decapitalize(name);
 }
  /**
   * Checks all of the classes in the serialization scope that implement TetradSerializable to make
   * sure all of their fields are either themselves (a) primitive, (b) TetradSerializable, or (c)
   * assignable from types designated as safely serializable by virtue of being included in the
   * safelySerializableTypes array (see), or are arrays whose lowest order component types satisfy
   * either (a), (b), or (c). Safely serializable classes in the Java API currently include
   * collections classes, plus String and Class. Collections classes are included, since their types
   * will be syntactically checkable in JDK 1.5. String and Class are members of a broader type of
   * Class whose safely can by checked by making sure there is no way to pass into them via
   * constructor or method argument any object that is not TetradSerializable or safely
   * serializable. But it's easy enough now to just make a list.
   *
   * @see #safelySerializableTypes
   */
  public void checkNestingOfFields() {
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    boolean foundUnsafeField = false;

    for (Object aClass : classes) {
      Class clazz = (Class) aClass;

      if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
        continue;
      }

      Field[] fields = clazz.getDeclaredFields();

      FIELDS:
      for (Field field : fields) {
        //                System.out.println(field);

        if (Modifier.isTransient(field.getModifiers())) {
          continue;
        }

        if (Modifier.isStatic(field.getModifiers())) {
          continue;
        }

        Class type = field.getType();

        while (type.isArray()) {
          type = type.getComponentType();
        }

        if (type.isPrimitive()) {
          continue;
        }

        if (type.isEnum()) {
          continue;
        }

        //                // Printing out Collections fields temporarily.
        //                if (Collection.class.isAssignableFrom(type)) {
        //                    System.out.println("COLLECTION FIELD: " + field);
        //                }
        //
        //                if (Map.class.isAssignableFrom(type)) {
        //                    System.out.println("MAP FIELD: " + field);
        //                }

        if (TetradSerializable.class.isAssignableFrom(type)
            && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
          continue;
        }

        for (Class safelySerializableClass : safelySerializableTypes) {
          if (safelySerializableClass.isAssignableFrom(type)) {
            continue FIELDS;
          }
        }

        // A reference in an inner class to the outer class.
        if (field.getName().equals("this$0")) {
          continue;
        }

        System.out.println("UNSAFE FIELD:" + field);
        foundUnsafeField = true;
      }
    }

    if (foundUnsafeField) {
      throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately.");
    }
  }
Example #13
0
  /** Read a {@link Writable}, {@link String}, primitive type, or an array of the preceding. */
  @SuppressWarnings("unchecked")
  public static Object readObject(DataInput in, ObjectWritable objectWritable, Configuration conf)
      throws IOException {
    String className = UTF8.readString(in);
    Class<?> declaredClass = PRIMITIVE_NAMES.get(className);
    if (declaredClass == null) {
      declaredClass = loadClass(conf, className);
    }

    Object instance;

    if (declaredClass.isPrimitive()) { // primitive types

      if (declaredClass == Boolean.TYPE) { // boolean
        instance = Boolean.valueOf(in.readBoolean());
      } else if (declaredClass == Character.TYPE) { // char
        instance = Character.valueOf(in.readChar());
      } else if (declaredClass == Byte.TYPE) { // byte
        instance = Byte.valueOf(in.readByte());
      } else if (declaredClass == Short.TYPE) { // short
        instance = Short.valueOf(in.readShort());
      } else if (declaredClass == Integer.TYPE) { // int
        instance = Integer.valueOf(in.readInt());
      } else if (declaredClass == Long.TYPE) { // long
        instance = Long.valueOf(in.readLong());
      } else if (declaredClass == Float.TYPE) { // float
        instance = Float.valueOf(in.readFloat());
      } else if (declaredClass == Double.TYPE) { // double
        instance = Double.valueOf(in.readDouble());
      } else if (declaredClass == Void.TYPE) { // void
        instance = null;
      } else {
        throw new IllegalArgumentException("Not a primitive: " + declaredClass);
      }

    } else if (declaredClass.isArray()) { // array
      int length = in.readInt();
      instance = Array.newInstance(declaredClass.getComponentType(), length);
      for (int i = 0; i < length; i++) {
        Array.set(instance, i, readObject(in, conf));
      }

    } else if (declaredClass == String.class) { // String
      instance = UTF8.readString(in);
    } else if (declaredClass.isEnum()) { // enum
      instance = Enum.valueOf((Class<? extends Enum>) declaredClass, UTF8.readString(in));
    } else { // Writable
      Class instanceClass = null;
      String str = UTF8.readString(in);
      instanceClass = loadClass(conf, str);

      Writable writable = WritableFactories.newInstance(instanceClass, conf);
      writable.readFields(in);
      instance = writable;

      if (instanceClass == NullInstance.class) { // null
        declaredClass = ((NullInstance) instance).declaredClass;
        instance = null;
      }
    }

    if (objectWritable != null) { // store values
      objectWritable.declaredClass = declaredClass;
      objectWritable.instance = instance;
    }

    return instance;
  }
  /** Type-munging for field setting and method invocation. Conforms to LC3 specification */
  static Object coerceTypeImpl(Class<?> type, Object value) {
    if (value != null && value.getClass() == type) {
      return value;
    }

    switch (getJSTypeCode(value)) {
      case JSTYPE_NULL:
        // raise error if type.isPrimitive()
        if (type.isPrimitive()) {
          reportConversionError(value, type);
        }
        return null;

      case JSTYPE_UNDEFINED:
        if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) {
          return "undefined";
        } else {
          reportConversionError("undefined", type);
        }
        break;

      case JSTYPE_BOOLEAN:
        // Under LC3, only JS Booleans can be coerced into a Boolean value
        if (type == Boolean.TYPE
            || type == ScriptRuntime.BooleanClass
            || type == ScriptRuntime.ObjectClass) {
          return value;
        } else if (type == ScriptRuntime.StringClass) {
          return value.toString();
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_NUMBER:
        if (type == ScriptRuntime.StringClass) {
          return ScriptRuntime.toString(value);
        } else if (type == ScriptRuntime.ObjectClass) {
          return coerceToNumber(Double.TYPE, value);
        } else if ((type.isPrimitive() && type != Boolean.TYPE)
            || ScriptRuntime.NumberClass.isAssignableFrom(type)) {
          return coerceToNumber(type, value);
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_STRING:
        if (type == ScriptRuntime.StringClass || type.isInstance(value)) {
          return value;
        } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) {
          // Special case for converting a single char string to a
          // character
          // Placed here because it applies *only* to JS strings,
          // not other JS objects converted to strings
          if (((String) value).length() == 1) {
            return new Character(((String) value).charAt(0));
          } else {
            return coerceToNumber(type, value);
          }
        } else if ((type.isPrimitive() && type != Boolean.TYPE)
            || ScriptRuntime.NumberClass.isAssignableFrom(type)) {
          return coerceToNumber(type, value);
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_JAVA_CLASS:
        if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
        }

        if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) {
          return value;
        } else if (type == ScriptRuntime.StringClass) {
          return value.toString();
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_JAVA_OBJECT:
      case JSTYPE_JAVA_ARRAY:
        if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
        }
        if (type.isPrimitive()) {
          if (type == Boolean.TYPE) {
            reportConversionError(value, type);
          }
          return coerceToNumber(type, value);
        } else {
          if (type == ScriptRuntime.StringClass) {
            return value.toString();
          } else {
            if (type.isInstance(value)) {
              return value;
            } else {
              reportConversionError(value, type);
            }
          }
        }
        break;

      case JSTYPE_OBJECT:
        if (type == ScriptRuntime.StringClass) {
          return ScriptRuntime.toString(value);
        } else if (type.isPrimitive()) {
          if (type == Boolean.TYPE) {
            reportConversionError(value, type);
          }
          return coerceToNumber(type, value);
        } else if (type.isInstance(value)) {
          return value;
        } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) {
          double time = ((NativeDate) value).getJSTimeValue();
          // XXX: This will replace NaN by 0
          return new Date((long) time);
        } else if (type.isArray() && value instanceof NativeArray) {
          // Make a new java array, and coerce the JS array components
          // to the target (component) type.
          NativeArray array = (NativeArray) value;
          long length = array.getLength();
          Class<?> arrayType = type.getComponentType();
          Object Result = Array.newInstance(arrayType, (int) length);
          for (int i = 0; i < length; ++i) {
            try {
              Array.set(Result, i, coerceType(arrayType, array.get(i, array)));
            } catch (EvaluatorException ee) {
              reportConversionError(value, type);
            }
          }

          return Result;
        } else if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
          if (type.isInstance(value)) return value;
          reportConversionError(value, type);
        } else if (type.isInterface() && value instanceof Callable) {
          // Try to use function as implementation of Java interface.
          //
          // XXX: Currently only instances of ScriptableObject are
          // supported since the resulting interface proxies should
          // be reused next time conversion is made and generic
          // Callable has no storage for it. Weak references can
          // address it but for now use this restriction.
          if (value instanceof ScriptableObject) {
            ScriptableObject so = (ScriptableObject) value;
            Object key = Kit.makeHashKeyFromPair(COERCED_INTERFACE_KEY, type);
            Object old = so.getAssociatedValue(key);
            if (old != null) {
              // Function was already wrapped
              return old;
            }
            Context cx = Context.getContext();
            Object glue = InterfaceAdapter.create(cx, type, (Callable) value);
            // Store for later retrival
            glue = so.associateValue(key, glue);
            return glue;
          }
          reportConversionError(value, type);
        } else {
          reportConversionError(value, type);
        }
        break;
    }

    return value;
  }
Example #15
0
 public static int dimensions(Class<?> c) {
   if (c.getComponentType() != null) {
     return 1 + dimensions(c.getComponentType());
   }
   return 0;
 }