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

    MixInMethodInvoker mixInMethodInvoker = null;
    if (mapping.mixInType != null) {
      mixInMethodInvoker =
          new MixInMethodInvoker(
              mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker()));
    }
    MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker);
    Object proxy =
        Proxy.newProxyInstance(
            wrapperType.getClassLoader(),
            new Class<?>[] {wrapperType},
            new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper));
    if (mixInMethodInvoker != null) {
      mixInMethodInvoker.setProxy(proxy);
    }
    return wrapperType.cast(proxy);
  }
  private boolean addClassMemberStaticImports(String packageName) {
    try {
      Class c = Class.forName(packageName);
      initImports();
      if (c.isEnum()) {

        //noinspection unchecked
        for (Enum e : (EnumSet<?>) EnumSet.allOf(c)) {
          imports.put(e.name(), e);
        }
        return true;
      } else {
        for (Field f : c.getDeclaredFields()) {
          if ((f.getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) != 0) {
            imports.put(f.getName(), f.get(null));
          }
        }
      }
    } catch (ClassNotFoundException e) {
      // do nothing.
    } catch (IllegalAccessException e) {
      throw new RuntimeException("error adding static imports for: " + packageName, e);
    }
    return false;
  }
  private static AnnotationPropertyVal rebuild(
      String key, Class annotationClass, String valueStr, TypeResolver resolver)
      throws NoSuchMethodException {
    Method prop = annotationClass.getMethod(key);
    Class returnType = prop.getReturnType();
    Object val = decode(returnType, valueStr, resolver);
    AnnotationPropertyVal.ValType valType;
    if (returnType.isPrimitive()) {
      valType = AnnotationPropertyVal.ValType.PRIMITIVE;
    } else if (returnType.isEnum()) {
      valType = AnnotationPropertyVal.ValType.ENUMERATION;
    } else if (returnType.isArray()) {

      if (returnType.getComponentType().isEnum()) {
        valType = AnnotationPropertyVal.ValType.ENUMARRAY;
      } else if (returnType.getComponentType().isPrimitive()) {
        valType = AnnotationPropertyVal.ValType.PRIMARRAY;
      } else if (String.class.equals(returnType.getComponentType())) {
        valType = AnnotationPropertyVal.ValType.STRINGARRAY;
      } else {
        valType = AnnotationPropertyVal.ValType.CLASSARRAY;
      }

    } else if (String.class.equals(returnType)) {
      valType = AnnotationPropertyVal.ValType.STRING;
    } else {
      valType = AnnotationPropertyVal.ValType.KLASS;
    }

    AnnotationPropertyVal pv = new AnnotationPropertyVal(key, returnType, val, valType);
    return pv;
  }
Beispiel #4
0
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

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

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

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

        public T read(JsonReader reader) throws IOException {
          if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
          } else {
            return lowercaseToConstant.get(reader.nextString());
          }
        }
      };
    }
  private static Deserializer getDeserializer(Class<?> clazz, Type type) {

    Deserializer deserializer;

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

    deserializerMap.put(type, deserializer);

    return deserializer;
  }
 public void apply()
     throws IllegalAccessException, InvocationTargetException, InstantiationException {
   if (type.isEnum()) {
     for (T instance : type.getEnumConstants()) {
       assertThat(
           instance.toString(),
           is(
               type.getCanonicalName().substring(type.getPackage().getName().length() + 1)
                   + "."
                   + ((Enum<?>) instance).name()));
     }
     return;
   }
   for (Constructor<?> constructor : type.getDeclaredConstructors()) {
     if (constructor.isSynthetic() && skipSynthetic) {
       continue;
     }
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     Object[] actualArguments = new Object[parameterTypes.length];
     Object[] otherArguments = new Object[parameterTypes.length];
     int index = 0;
     for (Class<?> parameterType : parameterTypes) {
       putInstance(parameterType, actualArguments, otherArguments, index++);
     }
     int testIndex = 0;
     @SuppressWarnings("unchecked")
     T instance = (T) constructor.newInstance(actualArguments);
     assertThat(instance, is(instance));
     assertThat(instance, not(is((Object) null)));
     assertThat(instance, not(is(new Object())));
     Object similarInstance = constructor.newInstance(actualArguments);
     assertThat(instance.hashCode(), is(similarInstance.hashCode()));
     assertThat(instance, is(similarInstance));
     if (skipToString) {
       assertThat(instance.toString(), notNullValue());
     } else if (optionalToStringRegex == null) {
       checkString(instance);
     } else {
       assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex));
     }
     for (Object otherArgument : otherArguments) {
       Object[] compareArguments = new Object[actualArguments.length];
       int argumentIndex = 0;
       for (Object actualArgument : actualArguments) {
         if (argumentIndex == testIndex) {
           compareArguments[argumentIndex] = otherArgument;
         } else {
           compareArguments[argumentIndex] = actualArgument;
         }
         argumentIndex++;
       }
       Object unlikeInstance = constructor.newInstance(compareArguments);
       assertThat(instance.hashCode(), not(is(unlikeInstance)));
       assertThat(instance, not(is(unlikeInstance)));
       testIndex++;
     }
   }
 }
 private static Object decode(Class returnType, String valueStr, TypeResolver resolver) {
   if (returnType.isArray()) {
     int sIndex = valueStr.indexOf("{");
     int eIndex = valueStr.lastIndexOf("}");
     String content = valueStr.substring(sIndex + 1, eIndex).trim();
     StringTokenizer tok = new StringTokenizer(content, ",");
     Object ar =
         java.lang.reflect.Array.newInstance(returnType.getComponentType(), tok.countTokens());
     int j = 0;
     while (tok.hasMoreElements()) {
       java.lang.reflect.Array.set(
           ar, j++, decode(returnType.getComponentType(), tok.nextToken(), resolver));
     }
     return ar;
   } else if (returnType.isEnum()) {
     try {
       String value = valueStr.trim();
       if (value.indexOf('.') > 0) {
         value = valueStr.substring(valueStr.lastIndexOf(".") + 1);
       }
       return returnType.getMethod("valueOf", String.class).invoke(null, value);
     } catch (IllegalAccessException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (InvocationTargetException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (NoSuchMethodException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     }
   } else if (String.class.equals(returnType)) {
     return unquote(valueStr);
   } else if (boolean.class.equals(returnType)) {
     return Boolean.valueOf(valueStr);
   } else if (int.class.equals(returnType)) {
     return Integer.valueOf(valueStr);
   } else if (double.class.equals(returnType)) {
     return Double.valueOf(valueStr);
   } else if (long.class.equals(returnType)) {
     return Long.valueOf(valueStr);
   } else if (float.class.equals(returnType)) {
     return Float.valueOf(valueStr);
   } else if (short.class.equals(returnType)) {
     return Short.valueOf(valueStr);
   } else if (char.class.equals(returnType)) {
     return unquote(valueStr).charAt(0);
   } else if (Class.class.equals(returnType)) {
     try {
       String cName = valueStr.trim().replace(".class", "");
       return resolver.resolveType(cName);
     } catch (ClassNotFoundException cnfe) {
       cnfe.printStackTrace();
       return Object.class;
     }
   }
   return null;
 }
Beispiel #8
0
  @SuppressWarnings("unchecked")
  public static <T> T coerceClassic(Class<T> clz, Object value) {

    if (clz == null || value == null) {
      return null;
    }

    if (clz == value.getClass()) {
      return (T) value;
    }

    if (clz == Typ.string || clz == Typ.chars) {
      return (T) value.toString();
    } else if (clz == Typ.integer || clz == Typ.intgr) {
      Integer i = toInt(value);
      return (T) i;
    } else if (clz == Typ.longWrapper || clz == Typ.lng) {
      Long l = toLong(value);
      return (T) l;
    } else if (clz == Typ.doubleWrapper || clz == Typ.dbl) {
      Double i = toDouble(value);
      return (T) i;
    } else if (clz == Typ.date) {
      return (T) toDate(value);
    } else if (clz == Typ.bigInteger) {
      return (T) toBigInteger(value);
    } else if (clz == Typ.bigDecimal) {
      return (T) toBigDecimal(value);
    } else if (clz == Typ.calendar) {
      return (T) toCalendar(toDate(value));
    } else if (clz == Typ.floatWrapper || clz == Typ.flt) {
      Float i = toFloat(value);
      return (T) i;
    } else if (clz == Typ.stringArray) {
      die("Need to fix this");
      return null;
    } else if (clz == Typ.bool || clz == Typ.bln) {
      Boolean b = toBoolean(value);
      return (T) b;
    } else if (Typ.isMap(clz)) {
      return (T) toMap(value);
    } else if (clz.isArray()) {
      return toPrimitiveArrayIfPossible(clz, value);
    } else if (Typ.isCollection(clz)) {
      return toCollection(clz, value);
    } else if (clz.getPackage() != null
        && !clz.getPackage().getName().startsWith("java")
        && Typ.isMap(value.getClass())
        && Typ.doesMapHaveKeyTypeString(value)) {
      return (T) MapObjectConversion.fromMap((Map<String, Object>) value);
    } else if (clz.isEnum()) {
      return (T) toEnum((Class<? extends Enum>) clz, value);

    } else {
      return null;
    }
  }
Beispiel #9
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);
    }
  }
Beispiel #10
0
 public ObjectWrapper getWrapper(Class clazz) {
   ObjectWrapper ret;
   String classname = clazz.getName();
   if (handlers != null && handlers.containsKey(classname)) ret = initWrapper(classname, clazz);
   else {
     if (Map.class.isAssignableFrom(clazz)) ret = new DefaultMapWrapper(clazz);
     else if (Collection.class.isAssignableFrom(clazz)) ret = new DefaultCollectionWrapper(clazz);
     else if (clazz.isArray()) ret = new ArrayWrapper(clazz);
     else if (ReflectionUtil.isSimpleType(clazz)) return new DefaultSimpleTypeWrapper(clazz);
     else if (clazz.isEnum()) ret = new EnumWrapper(clazz);
     else ret = new DefaultBeanWrapper(clazz);
   }
   ret.setYamlConfig(this);
   return ret;
 }
Beispiel #11
0
 public ObjectWrapper getWrapperSetContent(String classname, String content) {
   SimpleObjectWrapper wrapper;
   Class type = ReflectionUtil.classForName(transfer2classname(classname));
   if (handlers != null && handlers.containsKey(classname)) {
     wrapper = (SimpleObjectWrapper) initWrapper(classname, type);
     wrapper.setObject(Utilities.convertType(content, wrapper.expectedArgType()));
   } else if (type != null && type.isEnum()) {
     wrapper = new EnumWrapper(type);
     wrapper.setObject(Utilities.convertType(content, wrapper.expectedArgType()));
   } else {
     wrapper = new DefaultSimpleTypeWrapper(type);
     wrapper.setObject(Utilities.convertType(content, wrapper.expectedArgType()));
   }
   wrapper.setYamlConfig(this);
   return wrapper;
 }
 private void putInstance(
     Class<?> parameterType, Object actualArguments, Object otherArguments, int index) {
   Object actualArgument, otherArgument;
   if (parameterType == boolean.class) {
     actualArgument = DEFAULT_BOOLEAN;
     otherArgument = OTHER_BOOLEAN;
   } else if (parameterType == byte.class) {
     actualArgument = DEFAULT_BYTE;
     otherArgument = OTHER_BYTE;
   } else if (parameterType == char.class) {
     actualArgument = DEFAULT_CHAR;
     otherArgument = OTHER_CHAR;
   } else if (parameterType == short.class) {
     actualArgument = DEFAULT_SHORT;
     otherArgument = OTHER_SHORT;
   } else if (parameterType == int.class) {
     actualArgument = DEFAULT_INT;
     otherArgument = OTHER_INT;
   } else if (parameterType == long.class) {
     actualArgument = DEFAULT_LONG;
     otherArgument = OTHER_LONG;
   } else if (parameterType == float.class) {
     actualArgument = DEFAULT_FLOAT;
     otherArgument = OTHER_FLOAT;
   } else if (parameterType == double.class) {
     actualArgument = DEFAULT_DOUBLE;
     otherArgument = OTHER_DOUBLE;
   } else if (parameterType.isEnum()) {
     Object[] enumConstants = parameterType.getEnumConstants();
     if (enumConstants.length == 1) {
       throw new IllegalArgumentException("Enum with only one constant: " + parameterType);
     }
     actualArgument = enumConstants[0];
     otherArgument = enumConstants[1];
   } else if (parameterType.isArray()) {
     actualArgument = Array.newInstance(parameterType.getComponentType(), 1);
     otherArgument = Array.newInstance(parameterType.getComponentType(), 1);
     putInstance(parameterType.getComponentType(), actualArgument, otherArgument, 0);
   } else {
     actualArgument = creator.replace(parameterType, generator, false);
     refinement.apply(actualArgument);
     otherArgument = creator.replace(parameterType, generator, true);
     refinement.apply(otherArgument);
   }
   Array.set(actualArguments, index, actualArgument);
   Array.set(otherArguments, index, otherArgument);
 }
  /**
   * @return Null if class might be a bean; type String (that identifies why it's not a bean) if not
   */
  public static String canBeABeanType(Class<?> type) {
    // First: language constructs that ain't beans:
    if (type.isAnnotation()) {
      return "annotation";
    }
    if (type.isArray()) {
      return "array";
    }
    if (type.isEnum()) {
      return "enum";
    }
    if (type.isPrimitive()) {
      return "primitive";
    }

    // Anything else? Seems valid, then
    return null;
  }
Beispiel #14
0
  @SuppressWarnings("unchecked")
  private <T> T clone(final T o, final Map<Object, Object> clones) throws IllegalAccessException {
    if (o == null) return null;
    if (ignoredInstances.containsKey(o)) return o;

    final Class<T> clz = (Class<T>) o.getClass();
    if (clz.isEnum()) return o;
    // skip cloning ignored classes
    if (ignored.contains(clz)) return o;
    final Object clonedPreviously = clones != null ? clones.get(o) : null;
    if (clonedPreviously != null) return (T) clonedPreviously;

    if (clz.isArray()) {
      final int length = Array.getLength(o);
      final T newInstance = (T) Array.newInstance(clz.getComponentType(), length);
      clones.put(o, newInstance);
      for (int i = 0; i < length; i++) {
        final Object v = Array.get(o, i);
        final Object clone = clones != null ? clone(v, clones) : v;
        Array.set(newInstance, i, clone);
      }
      return newInstance;
    }

    T newInstance = null;
    try {
      newInstance = newInstance(clz);
    } catch (InstantiationException e) {
      e.printStackTrace();
    }
    if (clones != null) {
      clones.put(o, newInstance);
    }
    final List<Field> fields = allFields(clz);
    for (final Field field : fields) {
      if (!Modifier.isStatic(field.getModifiers())) {
        field.setAccessible(true);
        final Object fieldObject = field.get(o);
        final Object fieldObjectClone = clones != null ? clone(fieldObject, clones) : fieldObject;
        field.set(newInstance, fieldObjectClone);
      }
    }
    return newInstance;
  }
 public JSONObject describeClass(Class<?> clazz) throws Exception {
   JSONObject desc = new JSONObject();
   desc.put("name", clazz.getName());
   if (clazz.isEnum()) {
     @SuppressWarnings("unchecked")
     Class<Enum<?>> enumClass = (Class<Enum<?>>) clazz;
     ArrayList<String> enumNames = Lists.newArrayList();
     for (Enum<?> e : enumClass.getEnumConstants()) {
       enumNames.add(e.name());
     }
     desc.put("enum", enumNames);
   }
   UI_TYPE ui_type = UI_TYPE.getEnumFor(clazz);
   if (ui_type != null) {
     desc.put("uiType", ui_type.getName());
   }
   desc.put("properties", getClassProperties(clazz, 0));
   return desc;
 }
Beispiel #16
0
  public String objectToString(Object object) {
    if (object == null) {
      return null;
    }

    Class<?> objectClass = object.getClass();
    if (objectClass.isEnum()) {
      return ((Enum<?>) object).name();
    } else if (object instanceof java.sql.Date) {
      return object.toString();
    } else if (object instanceof java.sql.Time) {
      return object.toString();
    } else if (object instanceof java.sql.Timestamp) {
      return object.toString();
    } else if (object instanceof Date) {
      return new SimpleDateFormat(datePattern).format((Date) object);
    }

    return object.toString();
  }
Beispiel #17
0
  public Object objectFromString(String value, Class<?> objectClass) throws ParseException {
    if (value == null) {
      return null;
    } else if (objectClass.isAssignableFrom(value.getClass())) {
      return value;
    }

    // re-use the infinitely useful ParameterValue class
    ParameterValue pv = new ParameterValue(value);
    if (objectClass.isEnum()) {
      return pv.toEnum((Class) objectClass);
    } else if (java.sql.Date.class.isAssignableFrom(objectClass)) {
      return pv.toSqlDate();
    } else if (java.sql.Time.class.isAssignableFrom(objectClass)) {
      return pv.toSqlTime();
    } else if (java.sql.Timestamp.class.isAssignableFrom(objectClass)) {
      return pv.toSqlTimestamp();
    } else if (Date.class.isAssignableFrom(objectClass)) {
      return pv.toDate(datePattern);
    }

    return pv.to(objectClass);
  }
 @SuppressWarnings("unchecked")
 private static <T> T createFinalArgumentPlaceholder(Class<T> clazz) {
   if (clazz == Boolean.TYPE || clazz == Boolean.class) return (T) Boolean.FALSE;
   if (clazz.isEnum()) return (T) EnumSet.allOf((Class<? extends Enum>) clazz).iterator().next();
   return (T) createArgumentPlaceholder(clazz, FINAL_PLACEHOLDER_SEED);
 }
 @SuppressWarnings("unchecked")
 Object getNextPlaceholder(Class<?> clazz) {
   return clazz.isEnum()
       ? getNextEnumPlaceholder((Class<? extends Enum>) clazz)
       : getNextBooleanPlaceholder();
 }
 private static boolean isLimitedValues(Class<?> clazz) {
   return clazz == Boolean.TYPE || clazz == Boolean.class || clazz.isEnum();
 }
  // splitting this slows down ...
  protected void writeObjectWithContext(FSTClazzInfo.FSTFieldInfo referencee, Object toWrite)
      throws IOException {
    int startPosition = codec.getWritten();
    boolean dontShare = objects.disabled;
    objectWillBeWritten(toWrite, startPosition);

    try {
      if (toWrite == null) {
        codec.writeTag(NULL, null, 0, toWrite);
        return;
      }
      final Class clazz = toWrite.getClass();
      if (clazz == String.class) {
        String[] oneOf = referencee.getOneOf();
        if (oneOf != null) {
          for (int i = 0; i < oneOf.length; i++) {
            String s = oneOf[i];
            if (s.equals(toWrite)) {
              codec.writeTag(ONE_OF, oneOf, i, toWrite);
              codec.writeFByte(i);
              return;
            }
          }
        }
        if (dontShare) {
          codec.writeTag(STRING, toWrite, 0, toWrite);
          codec.writeStringUTF((String) toWrite);
          return;
        }
      } else if (clazz == Integer.class) {
        codec.writeTag(BIG_INT, null, 0, toWrite);
        codec.writeFInt(((Integer) toWrite).intValue());
        return;
      } else if (clazz == Long.class) {
        codec.writeTag(BIG_LONG, null, 0, toWrite);
        codec.writeFLong(((Long) toWrite).longValue());
        return;
      } else if (clazz == Boolean.class) {
        codec.writeTag(
            ((Boolean) toWrite).booleanValue() ? BIG_BOOLEAN_TRUE : BIG_BOOLEAN_FALSE,
            null,
            0,
            toWrite);
        return;
      } else if ((referencee.getType() != null && referencee.getType().isEnum())
          || toWrite instanceof Enum) {
        if (!codec.writeTag(ENUM, toWrite, 0, toWrite)) {
          boolean isEnumClass = toWrite.getClass().isEnum();
          if (!isEnumClass) {
            // weird stuff ..
            Class c = toWrite.getClass();
            while (c != null && !c.isEnum()) {
              c = toWrite.getClass().getEnclosingClass();
            }
            if (c == null) {
              throw new RuntimeException("Can't handle this enum: " + toWrite.getClass());
            }
            codec.writeClass(c);
          } else {
            codec.writeClass(getFstClazzInfo(referencee, toWrite.getClass()));
          }
          codec.writeFInt(((Enum) toWrite).ordinal());
        }
        return;
      }

      FSTClazzInfo serializationInfo = getFstClazzInfo(referencee, clazz);
      // check for identical / equal objects
      FSTObjectSerializer ser = serializationInfo.getSer();
      if (!dontShare
          && !referencee.isFlat()
          && !serializationInfo.isFlat()
          && (ser == null || !ser.alwaysCopy())) {
        int handle =
            objects.registerObjectForWrite(toWrite, codec.getWritten(), serializationInfo, tmp);
        // determine class header
        if (handle >= 0) {
          final boolean isIdentical =
              tmp[0] == 0; // objects.getReadRegisteredObject(handle) == toWrite;
          if (isIdentical) {
            //                        System.out.println("POK writeHandle"+handle+"
            // "+toWrite.getClass().getName());
            if (!codec.writeTag(HANDLE, null, handle, toWrite)) codec.writeFInt(handle);
            return;
          }
        }
      }
      if (clazz.isArray()) {
        if (codec.writeTag(ARRAY, toWrite, 0, toWrite))
          return; // some codecs handle primitive arrays like an primitive type
        writeArray(referencee, toWrite);
      } else if (ser == null) {
        // default write object wihtout custom serializer
        // handle write replace
        if (!dontShare) {
          if (serializationInfo.getWriteReplaceMethod() != null) {
            Object replaced = null;
            try {
              replaced = serializationInfo.getWriteReplaceMethod().invoke(toWrite);
            } catch (Exception e) {
              throw FSTUtil.rethrow(e);
            }
            if (replaced != toWrite) {
              toWrite = replaced;
              serializationInfo = getClassInfoRegistry().getCLInfo(toWrite.getClass());
              // fixme: update object map ?
            }
          }
          // clazz uses some JDK special stuff (frequently slow)
          if (serializationInfo.useCompatibleMode() && !serializationInfo.isExternalizable()) {
            writeObjectCompatible(referencee, toWrite, serializationInfo);
            return;
          }
        }
        if (!writeObjectHeader(
            serializationInfo,
            referencee,
            toWrite)) { // skip in case codec can write object as primitive
          defaultWriteObject(toWrite, serializationInfo);
          if (serializationInfo.isExternalizable()) codec.externalEnd(serializationInfo);
        }
      } else { // object has custom serializer
        // Object header (nothing written till here)
        int pos = codec.getWritten();
        if (!writeObjectHeader(
            serializationInfo,
            referencee,
            toWrite)) { // skip in case code can write object as primitive
          // write object depending on type (custom, externalizable, serializable/java, default)
          ser.writeObject(this, toWrite, serializationInfo, referencee, pos);
          codec.externalEnd(serializationInfo);
        }
      }
    } finally {
      objectHasBeenWritten(toWrite, startPosition, codec.getWritten());
    }
  }
  @SuppressWarnings("unused")
  public Map<String, String> marshall(PushRequest request) {

    Map<String, String> params = new TreeMap<String, String>();
    Field[] childField = request.getClass().getDeclaredFields();
    Field[] superFileds = request.getClass().getSuperclass().getDeclaredFields();

    List<Field> fieldList = new LinkedList<Field>();
    fieldList.addAll(Arrays.asList(childField));
    fieldList.addAll(Arrays.asList(superFileds));

    for (Field field : fieldList.toArray(new Field[0])) {
      try {
        field.setAccessible(true);
        if (field.isAnnotationPresent(HttpParamKeyName.class)) {
          Object obj = field.get(request);
          if (obj == null) {
            HttpParamKeyName annotation = field.getAnnotation(HttpParamKeyName.class);
            if (annotation.param() == R.REQUIRE) {
              throw new RuntimeException(obj.getClass().getName() + "require set");
            }
          } else {
            HttpParamKeyName annotation = field.getAnnotation(HttpParamKeyName.class);
            Class<?> zlass = field.getType();
            if (zlass.equals(Long.class) || "long".equalsIgnoreCase(zlass.getName())) {
              if (obj == null) { // (Long)obj < 0
                if (annotation.param() == R.REQUIRE) {
                  throw new RuntimeException(obj.getClass().getName() + "require set");
                }
              } else {
                params.put(annotation.name(), obj.toString());
              }
            } else if (zlass.equals(Integer.class) || "int".equalsIgnoreCase(zlass.getName())) {
              if (obj == null) { // (Integer)obj < 0
                if (annotation.param() == R.REQUIRE) {
                  throw new RuntimeException(obj.getClass().getName() + "require set");
                }
              } else {
                params.put(annotation.name(), obj.toString());
              }
            } else if (zlass.equals(String.class)) {
              params.put(annotation.name(), (String) obj);
            } else if (zlass.equals(java.util.Date.class)) {
              params.put(annotation.name(), YunCommonUtility.formatFromDate((java.util.Date) obj));
            } else if (zlass.isEnum()) {
              params.put(annotation.name(), obj.toString());
            } else if (zlass.equals(java.util.List.class)) {
              params.put(annotation.name(), StringUtility.toJson((java.util.List<?>) obj));
            } else if (zlass.equals(java.util.Set.class)) {
              params.put(annotation.name(), StringUtility.toJson((java.util.Set) obj));
            } else {
            }
          }
        }
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
    return params;
  }
  /**
   * 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.");
    }
  }
Beispiel #24
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;
  }
  public void getHelp(Caller caller, Workspace workspace, LinkedList<String> tokens) {

    WorkspaceService service = plugin.getWorkspaceService();
    String source = service.getWorkspaceName(caller.getSender());
    String firstToken = tokens.pollFirst();
    if (firstToken == null) firstToken = "";
    MetaClass callerScriptMetaClass = InvokerHelper.getMetaClass(CallerScript.class);
    MetaClass workspaceMetaClass = InvokerHelper.getMetaClass(Workspace.class);
    Map workspaceVars = null;
    if (workspace != null) workspaceVars = workspace.getBinding().getVariables();
    Map globalVars = service.getBinding().getVariables();
    PreparedScriptProperties properties = new PreparedScriptProperties();
    properties.setCaller(caller);
    properties.setServer(plugin.getServer());
    properties.setWorkspace(workspace);

    if (tokens.isEmpty()) { // get current method or class
      if (firstToken.equals("_")) {
        Object result = caller.getLastResult();
        String type = "null";
        if (result != null) type = result.getClass().getName();
        caller.sendPrintMessage("Last result: " + AQUA + type + RESET, source);
        return;
      }
      MetaProperty prop = callerScriptMetaClass.getMetaProperty(firstToken);
      if (prop != null) {
        caller.sendPrintMessage(
            String.format(
                "Script property %s: %s",
                YELLOW + prop.getName() + RESET, AQUA + prop.getType().getName() + RESET),
            source);
        return;
      }
      Class compClass = service.getImportTabCompleteClasses().get(firstToken);
      if (compClass != null) {
        String type = "Class";
        if (compClass.isInterface()) type = "Interface";
        else if (compClass.isEnum()) type = "Enum class";
        StringBuilder buf = new StringBuilder();
        Class superClass = compClass.getSuperclass();
        buf.append(type).append(" ").append(YELLOW).append(compClass.getName()).append(RESET);
        if (superClass != null) {
          buf.append(" extends ").append(AQUA).append(superClass.getName()).append(RESET);
        }
        caller.sendPrintMessage(buf, source);
        return;
      }
      for (MetaMethod metaMethod : callerScriptMetaClass.getMetaMethods()) {
        String name = metaMethod.getName();
        String methodEnd = "(";
        if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
        else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Script meta method ")
              .append(YELLOW)
              .append(metaMethod.getName())
              .append(RESET);
          buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = metaMethod.getNativeParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append('\n').append(RESET);
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
        int args = metaMethod.getParameterTypes().length;
        if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
            && name.length() > 3) {
          String propertyName = getPropertyName(name);
          if (propertyName != null && propertyName.equals(firstToken)) {
            caller.sendPrintMessage(
                String.format(
                    "Script meta getter %s returns %s",
                    YELLOW + name + "()" + RESET,
                    AQUA + metaMethod.getReturnType().getName() + RESET),
                source);
          }
        }
      }
      for (MetaMethod metaMethod : workspaceMetaClass.getMetaMethods()) {
        String name = metaMethod.getName();
        String methodEnd = "(";
        if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{";
        else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Workspace meta method ")
              .append(YELLOW)
              .append(metaMethod.getName())
              .append(RESET);
          buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = metaMethod.getNativeParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
      for (Method method : CallerScript.class.getMethods()) {
        String name = method.getName();
        String methodEnd = "(";
        Class<?>[] params = method.getParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Script method ").append(YELLOW).append(method.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
          buf.append(RESET).append('\n');
          buf.append("arguments: ").append(YELLOW).append(params.length).append(RESET).append('\n');
          for (Class<?> type : params)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
        int args = params.length;
        if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1)
            && name.length() > 3) {
          String propertyName = getPropertyName(name);
          if (propertyName != null && propertyName.equals(firstToken)) {
            caller.sendPrintMessage(
                String.format(
                    "Script getter %s returns %s",
                    YELLOW + name + "()" + RESET, AQUA + method.getReturnType().getName() + RESET),
                source);
          }
        }
      }
      for (Method method : Workspace.class.getMethods()) {
        String name = method.getName();
        String methodEnd = "(";
        Class<?>[] params = method.getParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Workspace method ").append(YELLOW).append(method.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
          buf.append(RESET).append('\n');
          buf.append("arguments: ").append(YELLOW).append(params.length).append(RESET).append('\n');
          for (Class<?> type : params)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
      if (workspaceVars != null) {
        Object result = workspaceVars.get(firstToken);
        if (result != null || workspaceVars.containsKey(firstToken)) {
          caller.sendPrintMessage(
              String.format(
                  "Workspace variable %s: %s",
                  YELLOW + firstToken + RESET,
                  AQUA + (result == null ? "null" : result.getClass().getName()) + RESET),
              source);
          return;
        }
      }
      if (globalVars != null) {
        Object result = globalVars.get(firstToken);
        if (result != null || globalVars.containsKey(firstToken)) {
          caller.sendPrintMessage(
              String.format(
                  "Workspace variable %s: %s",
                  YELLOW + firstToken + RESET,
                  AQUA + (result == null ? "null" : result.getClass().getName()) + RESET),
              source);
          return;
        }
      }
      for (GroovyObject modifier : CallerScript.getDynamicModifiers()) {
        Object[] params = {properties};
        try {
          Map<?, ?> map =
              (Map) modifier.getMetaClass().invokeMethod(modifier, "getPropertyMapFor", params);
          Object result = map.get(firstToken);
          if (result != null || map.containsKey(firstToken)) {
            Class resultClass = result instanceof Class ? (Class) result : null;
            caller.sendPrintMessage(
                String.format(
                    "Dynamic variable %s: %s",
                    YELLOW + firstToken + RESET,
                    AQUA + (resultClass == null ? "unknown type" : resultClass.getName()) + RESET),
                source);
          }
        } catch (Exception ignored) {
        }
        try {
          Map<?, ?> map =
              (Map) modifier.getMetaClass().invokeMethod(modifier, "getMethodMapFor", params);
          String funToken = firstToken;
          if (funToken.endsWith("(")) funToken = firstToken.substring(0, funToken.length() - 1);
          Object result = map.get(funToken);
          if (result != null || map.containsKey(funToken)) {
            Class resultClass = result instanceof Class ? (Class) result : null;
            caller.sendPrintMessage(
                String.format(
                    "Dynamic function %s: %s",
                    YELLOW + firstToken + RESET,
                    AQUA + (resultClass == null ? "unknown type" : resultClass.getName()) + RESET),
                source);
          }
        } catch (Exception ignored) {
        }
      }
      return;
    }

    MetaClass metaClass =
        getFirstTokenMeta(
            caller,
            firstToken,
            caller.getSender(),
            service,
            callerScriptMetaClass,
            workspaceMetaClass,
            workspace,
            workspaceVars,
            globalVars,
            properties);
    boolean classHook =
        tokens.size() <= 1 && service.getImportTabCompleteClasses().containsKey(firstToken);

    metaClass = skipTokens(tokens, metaClass);
    if (metaClass == null) return;

    // select property or method of last metaclass
    String token = tokens.pollFirst();
    Class theClass = metaClass.getTheClass();
    MetaProperty metaProperty = metaClass.getMetaProperty(token);
    if (metaProperty != null) {
      caller.sendPrintMessage(
          String.format(
              "Meta property %s: %s",
              YELLOW + token + RESET, AQUA + metaProperty.getType().getName() + RESET),
          source);
    }
    for (MetaMethod metaMethod : metaClass.getMetaMethods()) {
      String name = metaMethod.getName();
      String methodEnd = "(";
      Class<?>[] params = metaMethod.getNativeParameterTypes();
      if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
      else if (params.length == 0) methodEnd = "()";
      if (token.equals(name) || token.equals(name + methodEnd)) {
        StringBuilder buf = new StringBuilder();
        buf.append("Meta method ").append(YELLOW).append(metaMethod.getName()).append(RESET);
        buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
        buf.append(RESET).append('\n');
        Class[] types = metaMethod.getNativeParameterTypes();
        buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
        for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
        buf.deleteCharAt(buf.length() - 1);
        caller.sendPrintMessage(buf, source);
      }
      int args = params.length;
      if (name.startsWith("get") && args == 0 && name.length() > 3) {
        String propertyName = getPropertyName(name);
        if (propertyName != null && propertyName.equals(token)) {
          caller.sendPrintMessage(
              String.format(
                  "Meta getter %s returns %s",
                  YELLOW + name + "()" + RESET,
                  AQUA + metaMethod.getReturnType().getName() + RESET),
              source);
        }
      }
    }
    for (Method method : theClass.getMethods()) {
      String name = method.getName();
      String methodEnd = "(";
      Class<?>[] params = method.getParameterTypes();
      if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
      else if (params.length == 0) methodEnd = "()";
      if (token.equals(name) || token.equals(name + methodEnd)) {
        StringBuilder buf = new StringBuilder();
        buf.append("Method ").append(YELLOW).append(method.getName()).append(RESET);
        buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
        buf.append(RESET).append('\n');
        Class[] types = method.getParameterTypes();
        buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
        for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
        buf.deleteCharAt(buf.length() - 1);
        caller.sendPrintMessage(buf, source);
      }
      int args = params.length;
      if (name.startsWith("get") && args == 0 && name.length() > 3) {
        String propertyName = getPropertyName(name);
        if (propertyName != null && propertyName.equals(token)) {
          caller.sendPrintMessage(
              String.format(
                  "Getter %s returns %s",
                  YELLOW + name + "()" + RESET, AQUA + method.getReturnType().getName() + RESET),
              source);
        }
      }
    }
    if (Enum.class.isAssignableFrom(theClass)) {
      Enum[] enumValues = getEnumValues(theClass);
      if (enumValues != null)
        for (Enum anEnum : enumValues) {
          String name = anEnum.name();
          if (name.equals(token)) {
            caller.sendPrintMessage(
                String.format(
                    "Enum value %s: %s", YELLOW + name + RESET, AQUA + theClass.getName() + RESET),
                source);
          }
        }
    }
    if (classHook) {
      MetaProperty property = InvokerHelper.getMetaClass(Class.class).getMetaProperty(token);
      if (property != null) {
        caller.sendPrintMessage(
            String.format(
                "Meta property %s: %s",
                YELLOW + token + RESET, AQUA + property.getType().getName() + RESET),
            source);
      }
      for (MetaMethod metaMethod : InvokerHelper.getMetaClass(Class.class).getMetaMethods()) {
        String name = metaMethod.getName();
        String methodEnd = "(";
        Class<?>[] params = metaMethod.getNativeParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Method ").append(YELLOW).append(metaMethod.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = metaMethod.getNativeParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
      for (Method method : Class.class.getMethods()) {
        String name = method.getName();
        String methodEnd = "(";
        Class<?>[] params = method.getParameterTypes();
        if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{";
        else if (params.length == 0) methodEnd = "()";
        if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) {
          StringBuilder buf = new StringBuilder();
          buf.append("Method ").append(YELLOW).append(method.getName()).append(RESET);
          buf.append(" returns ").append(AQUA).append(method.getReturnType().getName());
          buf.append(RESET).append('\n');
          Class[] types = method.getParameterTypes();
          buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n');
          for (Class type : types)
            buf.append(AQUA).append(type.getName()).append(RESET).append('\n');
          buf.deleteCharAt(buf.length() - 1);
          caller.sendPrintMessage(buf, source);
        }
      }
    }
  }
Beispiel #26
0
  /**
   * Construct an instance of RM class of given name and values.
   *
   * <p>If the input is a string, and the required attribute is some other types (integer, double
   * etc), it will be converted into right type. if there is any error during conversion,
   * AttributeFormatException will be thrown.
   *
   * @param rmClassName
   * @param valueMap
   * @return created instance
   * @throws RMObjectBuildingException
   */
  public RMObject construct(String rmClassName, Map<String, Object> valueMap)
      throws RMObjectBuildingException {

    Class rmClass = retrieveRMType(rmClassName);

    // replace underscore separated names with camel case
    Map<String, Object> filteredMap = new HashMap<String, Object>();
    for (String name : valueMap.keySet()) {
      filteredMap.put(toCamelCase(name), valueMap.get(name));
    }
    Constructor constructor = fullConstructor(rmClass);
    Map<String, Class> typeMap = attributeType(rmClass);
    Map<String, Integer> indexMap = attributeIndex(rmClass);
    Map<String, Attribute> attributeMap = attributeMap(rmClass);
    Object[] valueArray = new Object[indexMap.size()];

    for (String name : typeMap.keySet()) {

      Object value = filteredMap.get(name);

      if (!typeMap.containsKey(name) || !attributeMap.containsKey(name)) {
        throw new RMObjectBuildingException("unknown attribute " + name);
      }

      Class type = typeMap.get(name);
      Integer index = indexMap.get(name);

      Attribute attribute = attributeMap.get(name);
      if (index == null || type == null) {
        throw new RMObjectBuildingException("unknown attribute \"" + name + "\"");
      }

      // system supplied value
      if (attribute.system()) {
        SystemValue sysvalue = SystemValue.fromId(name);
        if (sysvalue == null) {
          throw new RMObjectBuildingException("unknonw system value" + "\"" + name + "\"");
        }
        value = systemValues.get(sysvalue);
        if (value == null) {
          throw new AttributeMissingException(
              "missing value for "
                  + "system attribute \""
                  + name
                  + "\" in class: "
                  + rmClass
                  + ", with valueMap: "
                  + valueMap);
        }
      }

      // check required attributes
      if (value == null && attribute.required()) {
        log.info(attribute);
        throw new AttributeMissingException(
            "missing value for "
                + "required attribute \""
                + name
                + "\" of type "
                + type
                + " while constructing "
                + rmClass
                + " with valueMap: "
                + valueMap);
      }

      // enum
      else if (type.isEnum() && !value.getClass().isEnum()) {
        // OG added
        if (type.equals(ProportionKind.class))
          value = ProportionKind.fromValue(Integer.parseInt(value.toString()));
        else value = Enum.valueOf(type, value.toString());
      }

      // in case of null, create a default value
      else if (value == null) {
        value = defaultValue(type);
      }

      // in case of string value, convert to right type if necessary
      else if (value instanceof String) {
        String str = (String) value;
        try {

          // for DvCount
          if (type.equals(int.class)) {
            value = Integer.parseInt(str);

            // for DvQuantity
          } else if (type.equals(double.class)) {
            value = Double.parseDouble(str);

            // for DvProportion.precision
          } else if (type.equals(Integer.class)) {
            value = new Integer(str);
          }

        } catch (NumberFormatException e) {
          throw new AttributeFormatException(
              "wrong format of " + "attribute " + name + ", expect " + type);
        }

        // deal with mismatch between array and list
      } else if (type.isAssignableFrom(List.class) && value.getClass().isArray()) {

        Object[] array = (Object[]) value;
        List list = new ArrayList();
        for (Object o : array) {
          list.add(o);
        }
        value = list;

        // deal with mismatch between array and set
      } else if (type.isAssignableFrom(Set.class) && value.getClass().isArray()) {

        Object[] array = (Object[]) value;
        Set set = new HashSet();
        for (Object o : array) {
          set.add(o);
        }
        value = set;
      }
      // check type
      else if (value != null && !type.isPrimitive()) {
        try {
          type.cast(value);
        } catch (ClassCastException e) {
          throw new RMObjectBuildingException(
              "Failed to construct: "
                  + rmClassName
                  + ", value for attribute '"
                  + name
                  + "' has wrong type, expected \""
                  + type
                  + "\", but got \""
                  + value.getClass()
                  + "\"");
        }
      }
      valueArray[index] = value;
    }

    Object ret = null;
    try {
      // OG added hack
      if (rmClassName.equalsIgnoreCase("DVCOUNT")) {
        log.debug("Fixing DVCOUNT...");
        for (int i = 0; i < valueArray.length; i++) {
          Object value = valueArray[i];
          if (value != null && value.getClass().equals(Float.class))
            valueArray[i] = Double.parseDouble(value.toString());
          else if (value != null && value.getClass().equals(Long.class))
            valueArray[i] = Integer.parseInt(value.toString());
        }
      }
      ret = constructor.newInstance(valueArray);
    } catch (Exception e) {

      if (log.isDebugEnabled()) {
        e.printStackTrace();
      }

      log.debug("failed in constructor.newInstance()", e);

      if (stringParsingTypes.contains(rmClassName)) {
        throw new AttributeFormatException("wrong format for type " + rmClassName);
      }

      throw new RMObjectBuildingException(
          "failed to create new instance of  "
              + rmClassName
              + " with valueMap: "
              + toString(valueMap)
              + ", cause: "
              + e.getMessage());
    }
    return (RMObject) ret;
  }