/**
   * Define an operation on the managed object. Defines an operation with parameters. Refection is
   * used to determine find the method and it's return type. The description of the method is found
   * with a call to findDescription on "name(signature)". The name and description of each parameter
   * is found with a call to findDescription with "name(partialSignature", the returned description
   * is for the last parameter of the partial signature and is assumed to start with the parameter
   * name, followed by a colon.
   *
   * @param name The name of the method call.
   * @param signature The types of the operation parameters.
   * @param impact Impact as defined in MBeanOperationInfo
   * @param onMBean true if the operation is defined on the mbean
   */
  public synchronized void defineOperation(
      String name, String[] signature, int impact, boolean onMBean) {
    _dirty = true;
    Class oClass = onMBean ? this.getClass() : _object.getClass();
    if (signature == null) signature = new String[0];

    try {
      Class[] types = new Class[signature.length];
      MBeanParameterInfo[] pInfo = new MBeanParameterInfo[signature.length];

      // Check types and build methodKey
      String methodKey = name + "(";
      for (int i = 0; i < signature.length; i++) {
        Class type = TypeUtil.fromName(signature[i]);
        if (type == null)
          type = Thread.currentThread().getContextClassLoader().loadClass(signature[i]);
        types[i] = type;
        signature[i] = type.isPrimitive() ? TypeUtil.toName(type) : signature[i];
        methodKey += (i > 0 ? "," : "") + signature[i];
      }
      methodKey += ")";

      // Build param infos
      for (int i = 0; i < signature.length; i++) {
        String description = findDescription(methodKey + "[" + i + "]");
        int colon = description.indexOf(":");
        if (colon < 0) {
          description = "param" + i + ":" + description;
          colon = description.indexOf(":");
        }
        pInfo[i] =
            new MBeanParameterInfo(
                description.substring(0, colon).trim(),
                signature[i],
                description.substring(colon + 1).trim());
      }

      // build the operation info
      Method method = oClass.getMethod(name, types);
      Class returnClass = method.getReturnType();
      _method.put(methodKey, method);
      _operations.add(
          new ModelMBeanOperationInfo(
              name,
              findDescription(methodKey),
              pInfo,
              returnClass.isPrimitive() ? TypeUtil.toName(returnClass) : (returnClass.getName()),
              impact));
    } catch (Exception e) {
      log.warn("operation " + name, e);
      throw new IllegalArgumentException(e.toString());
    }
  }
  // the overload of type Object for Groovy coercions:  public void setFoo(Object foo)
  private void createTypeConvertingSetter(
      ClassVisitor visitor, Type generatedType, ModelProperty<?> property) {
    if (!property.isWritable() || !(property.getSchema() instanceof ScalarValueSchema)) {
      return;
    }

    Class<?> propertyClass = property.getType().getConcreteClass();
    Type propertyType = Type.getType(propertyClass);
    Class<?> boxedClass =
        propertyClass.isPrimitive() ? BOXED_TYPES.get(propertyClass) : propertyClass;
    Type boxedType = Type.getType(boxedClass);

    Method setter = property.getSetter().getMethod();
    MethodVisitor methodVisitor =
        declareMethod(
            visitor,
            setter.getName(),
            SET_OBJECT_PROPERTY_DESCRIPTOR,
            SET_OBJECT_PROPERTY_DESCRIPTOR);

    putThisOnStack(methodVisitor);
    putTypeConverterFieldValueOnStack(methodVisitor, generatedType);

    // Object converted = $typeConverter.convert(foo, Float.class, false);
    methodVisitor.visitVarInsn(ALOAD, 1); // put var #1 ('foo') on the stack
    methodVisitor.visitLdcInsn(boxedType); // push the constant Class onto the stack
    methodVisitor.visitInsn(
        propertyClass.isPrimitive()
            ? ICONST_1
            : ICONST_0); // push int 1 or 0 (interpreted as true or false) onto the stack
    methodVisitor.visitMethodInsn(
        INVOKEINTERFACE,
        TYPE_CONVERTER_TYPE.getInternalName(),
        "convert",
        COERCE_TO_SCALAR_DESCRIPTOR,
        true);
    methodVisitor.visitTypeInsn(CHECKCAST, boxedType.getInternalName());

    if (propertyClass.isPrimitive()) {
      unboxType(methodVisitor, propertyClass);
    }

    // invoke the typed setter, popping 'this' and 'converted' from the stack
    methodVisitor.visitMethodInsn(
        INVOKEVIRTUAL,
        generatedType.getInternalName(),
        setter.getName(),
        Type.getMethodDescriptor(Type.VOID_TYPE, propertyType),
        false);
    finishVisitingMethod(methodVisitor);
  }
示例#3
0
  /** Detect cyclic references */
  protected void value(Object object, Method method) throws JSONException {
    if (object == null) {
      this.add("null");

      return;
    }

    if (this.stack.contains(object)) {
      Class clazz = object.getClass();

      // cyclic reference
      if (clazz.isPrimitive() || clazz.equals(String.class)) {
        this.process(object, method);
      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Cyclic reference detected on " + object);
        }

        this.add("null");
      }

      return;
    }

    this.process(object, method);
  }
示例#4
0
  public Class getPropertyType(BeanEventType eventType, EventAdapterService eventAdapterService) {
    Class result = null;

    for (Iterator<Property> it = properties.iterator(); it.hasNext(); ) {
      Property property = it.next();
      result = property.getPropertyType(eventType, eventAdapterService);

      if (result == null) {
        // property not found, return null
        return null;
      }

      if (it.hasNext()) {
        // Map cannot be used to further nest as the type cannot be determined
        if (result == Map.class) {
          return null;
        }

        if (result.isArray()
            || result.isPrimitive()
            || JavaClassHelper.isJavaBuiltinDataType(result)) {
          return null;
        }

        eventType =
            eventAdapterService
                .getBeanEventTypeFactory()
                .createBeanType(result.getName(), result, false, false, false);
      }
    }

    return result;
  }
  private void writeSetter(ClassVisitor visitor, Type generatedType, ModelProperty<?> property) {
    WeaklyTypeReferencingMethod<?, Void> weakSetter = property.getSetter();
    // There is no setter for this property
    if (weakSetter == null) {
      return;
    }

    String propertyName = property.getName();
    Class<?> propertyClass = property.getType().getConcreteClass();
    Type propertyType = Type.getType(propertyClass);
    Label calledOutsideOfConstructor = new Label();

    Method setter = weakSetter.getMethod();

    // the regular typed setter
    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, propertyType);
    MethodVisitor methodVisitor =
        declareMethod(
            visitor, setter.getName(), methodDescriptor, AsmClassGeneratorUtils.signature(setter));

    putCanCallSettersFieldValueOnStack(methodVisitor, generatedType);
    jumpToLabelIfStackEvaluatesToTrue(methodVisitor, calledOutsideOfConstructor);
    throwExceptionBecauseCalledOnItself(methodVisitor);

    methodVisitor.visitLabel(calledOutsideOfConstructor);
    putStateFieldValueOnStack(methodVisitor, generatedType);
    putConstantOnStack(methodVisitor, propertyName);
    putFirstMethodArgumentOnStack(methodVisitor, propertyType);
    if (propertyClass.isPrimitive()) {
      boxType(methodVisitor, propertyClass);
    }
    invokeStateSetMethod(methodVisitor);

    finishVisitingMethod(methodVisitor);
  }
 /**
  * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the
  * object's size measured so far. <code>f</code> is the field being probed.
  *
  * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code>
  * field's offset and representation size (unaligned).
  */
 private static long adjustForField(long sizeSoFar, final Field f) {
   final Class<?> type = f.getType();
   final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
   if (objectFieldOffsetMethod != null) {
     try {
       final long offsetPlusSize =
           ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize;
       return Math.max(sizeSoFar, offsetPlusSize);
     } catch (IllegalAccessException ex) {
       throw new RuntimeException("Access problem with sun.misc.Unsafe", ex);
     } catch (InvocationTargetException ite) {
       final Throwable cause = ite.getCause();
       if (cause instanceof RuntimeException) throw (RuntimeException) cause;
       if (cause instanceof Error) throw (Error) cause;
       // this should never happen (Unsafe does not declare
       // checked Exceptions for this method), but who knows?
       throw new RuntimeException(
           "Call to Unsafe's objectFieldOffset() throwed "
               + "checked Exception when accessing field "
               + f.getDeclaringClass().getName()
               + "#"
               + f.getName(),
           cause);
     }
   } else {
     // TODO: No alignments based on field type/ subclass fields alignments?
     return sizeSoFar + fsize;
   }
 }
示例#7
0
 /**
  * Returns the null value for the specific type
  *
  * @param type the type of the parameter for which the null value is required
  * @return the null value for the specific type
  */
 Object getNullValueForType(Class type) {
   if (!type.isPrimitive()) {
     return null;
   }
   if (type == Boolean.TYPE) {
     return Boolean.FALSE;
   }
   if (type == Character.TYPE) {
     return new Character((char) 0);
   }
   if (type == Byte.TYPE) {
     return new Byte((byte) 0);
   }
   if (type == Short.TYPE) {
     return new Short((short) 0);
   }
   if (type == Integer.TYPE) {
     return new Integer(0);
   }
   if (type == Long.TYPE) {
     return new Long(0L);
   }
   if (type == Float.TYPE) {
     return new Float(0f);
   }
   if (type == Double.TYPE) {
     return new Double(0d);
   }
   fail("Don't know how to handle type " + type);
   return null; // unreachable statement
 }
  /**
   * Returns the clone of <code>o_</code>. It calls <code>o_.clone()</code>, if possible, and either
   * raises an exception or returns null if fails.
   *
   * @param raiseException_ set to true if one wishes to get exception instead of receiving null
   *     when this method fails to call <code>o_.clone()</code>.
   */
  public static Object clone(Object o_, boolean raiseException_) {
    if (o_ == null) return null;
    if (o_ instanceof String) return o_;

    try {
      if (o_ instanceof drcl.ObjectCloneable) return ((drcl.ObjectCloneable) o_).clone();
      if (o_.getClass().isArray()) {
        int length_ = Array.getLength(o_);
        Class componentType_ = o_.getClass().getComponentType();
        Object that_ = Array.newInstance(componentType_, length_);
        if (componentType_.isPrimitive()) System.arraycopy(o_, 0, that_, 0, length_);
        else {
          for (int i = 0; i < length_; i++)
            Array.set(that_, i, clone(Array.get(o_, i), raiseException_));
        }
        return that_;
      }
      Method m_ = o_.getClass().getMethod("clone", null);
      return m_.invoke(o_, null);
    } catch (Exception e_) {
      if (raiseException_) {
        Thread t_ = Thread.currentThread();
        t_.getThreadGroup().uncaughtException(t_, e_);
      }
      return null;
    }
  }
 private void castFirstStackElement(MethodVisitor methodVisitor, Class<?> returnType) {
   if (returnType.isPrimitive()) {
     unboxType(methodVisitor, returnType);
   } else {
     methodVisitor.visitTypeInsn(CHECKCAST, Type.getInternalName(returnType));
   }
 }
 private static boolean verifyReturn(Class columnClass, Class returnType) {
   if (columnClass.isAssignableFrom(returnType)) return true;
   if (returnType.isPrimitive()) {
     return (columnClass.isAssignableFrom(getWrapper(returnType)));
   }
   return false;
 }
  /**
   * Create a default object of the given type. Prefers constructors with as few arguments as
   * possible. Creates an empty proxy for interfaces.
   *
   * @param type type to instantiate
   * @return default instance
   * @throws Exception if the default instance could not be created
   */
  private static Object instantiateType(Class<?> type) throws Exception {
    if (type.isPrimitive()) return Defaults.defaultValue(type);
    else if (type == Void.class) return null;
    else if (type.isArray()) return Array.newInstance(type, 0);
    else if (type.isInterface())
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          new Class[] {type},
          new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              return null;
            }
          });

    // Take a constructor with as few params as possible
    Constructor constructor = type.getDeclaredConstructors()[0];
    for (Constructor<?> c : type.getDeclaredConstructors()) {
      if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c;
    }

    Object[] params = new Object[constructor.getParameterTypes().length];
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
      params[i] = instantiateType(constructor.getParameterTypes()[i]);
    }
    return constructor.newInstance(params);
  }
示例#12
0
  /**
   * check whether a class should not be considered for transformation
   *
   * @param clazz the class to check
   * @return true if clazz should not be considered for transformation otherwise false
   */
  protected boolean isSkipClass(Class<?> clazz) {
    if (!inst.isModifiableClass(clazz)) {
      return true;
    }

    // we can safely skip array classes, interfaces and primitive classes

    if (clazz.isArray()) {
      return true;
    }

    if (clazz.isInterface()) {
      return true;
    }

    if (clazz.isPrimitive()) {
      return true;
    }

    String name = clazz.getName();

    if (isBytemanClass(name) || !isTransformable(name)) {
      return true;
    }

    return false;
  }
示例#13
0
  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;
  }
示例#14
0
 /**
  * Generates code to return a Java type, after calling a Java method that returns the same type.
  * Generates the appropriate RETURN bytecode.
  */
 private static void generatePopResult(ClassFileWriter cfw, Class<?> retType) {
   if (retType.isPrimitive()) {
     String typeName = retType.getName();
     switch (typeName.charAt(0)) {
       case 'b':
       case 'c':
       case 's':
       case 'i':
       case 'z':
         cfw.add(ByteCode.IRETURN);
         break;
       case 'l':
         cfw.add(ByteCode.LRETURN);
         break;
       case 'f':
         cfw.add(ByteCode.FRETURN);
         break;
       case 'd':
         cfw.add(ByteCode.DRETURN);
         break;
     }
   } else {
     cfw.add(ByteCode.ARETURN);
   }
 }
示例#15
0
 /**
  * Generates code to push typed parameters onto the operand stack prior to a direct Java method
  * call.
  */
 private static int generatePushParam(ClassFileWriter cfw, int paramOffset, Class<?> paramType) {
   if (!paramType.isPrimitive()) {
     cfw.addALoad(paramOffset);
     return 1;
   }
   String typeName = paramType.getName();
   switch (typeName.charAt(0)) {
     case 'z':
     case 'b':
     case 'c':
     case 's':
     case 'i':
       // load an int value, convert to double.
       cfw.addILoad(paramOffset);
       return 1;
     case 'l':
       // load a long, convert to double.
       cfw.addLLoad(paramOffset);
       return 2;
     case 'f':
       // load a float, convert to double.
       cfw.addFLoad(paramOffset);
       return 1;
     case 'd':
       cfw.addDLoad(paramOffset);
       return 2;
   }
   throw Kit.codeBug();
 }
示例#16
0
 public Class[] getValidAnnotationTypes(Class type) {
   Class[] valid_types;
   if (Buffer.class.isAssignableFrom(type)) valid_types = getValidBufferTypes(type);
   else if (type.isPrimitive()) valid_types = getValidPrimitiveTypes(type);
   else if (String.class.equals(type)) valid_types = new Class[] {GLubyte.class};
   else valid_types = new Class[] {};
   return valid_types;
 }
示例#17
0
 /**
  * Add an adaptor for a kind of object so ST knows how to pull properties from them. Add adaptors
  * in increasing order of specificity. ST adds Object, Map, and ST model adaptors for you first.
  * Adaptors you add have priority over default adaptors.
  *
  * <p>If an adaptor for type T already exists, it is replaced by the adaptor arg.
  *
  * <p>This must invalidate cache entries, so set your adaptors up before render()ing your
  * templates for efficiency.
  */
 public void registerModelAdaptor(Class attributeType, ModelAdaptor adaptor) {
   if (attributeType.isPrimitive()) {
     throw new IllegalArgumentException(
         "can't register ModelAdaptor for primitive type " + attributeType.getSimpleName());
   }
   adaptors.put(attributeType, adaptor);
   invalidateModelAdaptorCache(attributeType);
 }
示例#18
0
 /**
  * Register a renderer for all objects of a particular "kind" for all templates evaluated relative
  * to this group. Use r to render if object in question is instanceof(attributeType).
  */
 public void registerRenderer(Class attributeType, AttributeRenderer r) {
   if (attributeType.isPrimitive()) {
     throw new IllegalArgumentException(
         "can't register renderer for primitive type " + attributeType.getSimpleName());
   }
   typeToAdaptorCache.clear(); // be safe, not clever; wack all values
   if (renderers == null) {
     renderers = Collections.synchronizedMap(new LinkedHashMap<Class, AttributeRenderer>());
   }
   renderers.put(attributeType, r);
 }
示例#19
0
 private boolean isStandardProperty(Class clazz) {
   return clazz.isPrimitive()
       || clazz.isAssignableFrom(Byte.class)
       || clazz.isAssignableFrom(Short.class)
       || clazz.isAssignableFrom(Integer.class)
       || clazz.isAssignableFrom(Long.class)
       || clazz.isAssignableFrom(Float.class)
       || clazz.isAssignableFrom(Double.class)
       || clazz.isAssignableFrom(Character.class)
       || clazz.isAssignableFrom(String.class)
       || clazz.isAssignableFrom(Boolean.class);
 }
  /**
   * Returns compact class host.
   *
   * @param obj Object to compact.
   * @return String.
   */
  @Nullable
  public static Object compactObject(Object obj) {
    if (obj == null) return null;

    if (obj instanceof Enum) return obj.toString();

    if (obj instanceof String || obj instanceof Boolean || obj instanceof Number) return obj;

    if (obj instanceof Collection) {
      Collection col = (Collection) obj;

      Object[] res = new Object[col.size()];

      int i = 0;

      for (Object elm : col) res[i++] = compactObject(elm);

      return res;
    }

    if (obj.getClass().isArray()) {
      Class<?> arrType = obj.getClass().getComponentType();

      if (arrType.isPrimitive()) {
        if (obj instanceof boolean[]) return Arrays.toString((boolean[]) obj);
        if (obj instanceof byte[]) return Arrays.toString((byte[]) obj);
        if (obj instanceof short[]) return Arrays.toString((short[]) obj);
        if (obj instanceof int[]) return Arrays.toString((int[]) obj);
        if (obj instanceof long[]) return Arrays.toString((long[]) obj);
        if (obj instanceof float[]) return Arrays.toString((float[]) obj);
        if (obj instanceof double[]) return Arrays.toString((double[]) obj);
      }

      Object[] arr = (Object[]) obj;

      int iMax = arr.length - 1;

      StringBuilder sb = new StringBuilder("[");

      for (int i = 0; i <= iMax; i++) {
        sb.append(compactObject(arr[i]));

        if (i != iMax) sb.append(", ");
      }

      sb.append("]");

      return sb.toString();
    }

    return U.compact(obj.getClass().getName());
  }
示例#21
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);
    }
  }
 /** Return shallow size of any <code>array</code>. */
 private static long shallowSizeOfArray(Object array) {
   long size = NUM_BYTES_ARRAY_HEADER;
   final int len = Array.getLength(array);
   if (len > 0) {
     Class<?> arrayElementClazz = array.getClass().getComponentType();
     if (arrayElementClazz.isPrimitive()) {
       size += (long) len * primitiveSizes.get(arrayElementClazz);
     } else {
       size += (long) NUM_BYTES_OBJECT_REF * len;
     }
   }
   return alignObjectSize(size);
 }
示例#23
0
  /**
   * Generates code to wrap Java argument into Object. Non-primitive Java types are left unconverted
   * pending conversion in the helper method. Leaves the wrapper object on the top of the stack.
   */
  private static int generateWrapArg(ClassFileWriter cfw, int paramOffset, Class<?> argType) {
    int size = 1;
    if (!argType.isPrimitive()) {
      cfw.add(ByteCode.ALOAD, paramOffset);

    } else if (argType == Boolean.TYPE) {
      // wrap boolean values with java.lang.Boolean.
      cfw.add(ByteCode.NEW, "java/lang/Boolean");
      cfw.add(ByteCode.DUP);
      cfw.add(ByteCode.ILOAD, paramOffset);
      cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Boolean", "<init>", "(Z)V");

    } else if (argType == Character.TYPE) {
      // Create a string of length 1 using the character parameter.
      cfw.add(ByteCode.ILOAD, paramOffset);
      cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/String", "valueOf", "(C)Ljava/lang/String;");

    } else {
      // convert all numeric values to java.lang.Double.
      cfw.add(ByteCode.NEW, "java/lang/Double");
      cfw.add(ByteCode.DUP);
      String typeName = argType.getName();
      switch (typeName.charAt(0)) {
        case 'b':
        case 's':
        case 'i':
          // load an int value, convert to double.
          cfw.add(ByteCode.ILOAD, paramOffset);
          cfw.add(ByteCode.I2D);
          break;
        case 'l':
          // load a long, convert to double.
          cfw.add(ByteCode.LLOAD, paramOffset);
          cfw.add(ByteCode.L2D);
          size = 2;
          break;
        case 'f':
          // load a float, convert to double.
          cfw.add(ByteCode.FLOAD, paramOffset);
          cfw.add(ByteCode.F2D);
          break;
        case 'd':
          cfw.add(ByteCode.DLOAD, paramOffset);
          size = 2;
          break;
      }
      cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Double", "<init>", "(D)V");
    }
    return size;
  }
 @SuppressWarnings("unchecked")
 @Test
 public void FullySerializable() {
   Set<Class<?>> checked = new HashSet<Class<?>>();
   checked.addAll(
       Arrays.asList(
           Collection.class,
           List.class,
           Set.class,
           Map.class,
           Object.class,
           String.class,
           Class.class));
   Stack<Class<?>> classes = new Stack<Class<?>>();
   classes.addAll(
       Arrays.<Class<?>>asList(
           NumberPath.class,
           NumberOperation.class,
           NumberTemplate.class,
           BeanPath.class,
           DefaultQueryMetadata.class));
   while (!classes.isEmpty()) {
     Class<?> clazz = classes.pop();
     checked.add(clazz);
     if (!Serializable.class.isAssignableFrom(clazz) && !clazz.isPrimitive()) {
       fail(clazz.getName() + " is not serializable");
     }
     for (Field field : clazz.getDeclaredFields()) {
       if (Modifier.isTransient(field.getModifiers())) {
         continue;
       }
       Set<Class<?>> types = new HashSet<Class<?>>(3);
       types.add(field.getType());
       if (field.getType().getSuperclass() != null) {
         types.add(field.getType().getSuperclass());
       }
       if (field.getType().getComponentType() != null) {
         types.add(field.getType().getComponentType());
       }
       if (Collection.class.isAssignableFrom(field.getType())) {
         types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0));
       } else if (Map.class.isAssignableFrom(field.getType())) {
         types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 0));
         types.add(ReflectionUtils.getTypeParameterAsClass(field.getGenericType(), 1));
       }
       types.removeAll(checked);
       classes.addAll(types);
     }
   }
 }
示例#25
0
  private static Object createArgumentPlaceholder(Class<?> clazz, Integer placeholderId) {
    if (clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || Character.class == clazz)
      return getPrimitivePlaceHolder(clazz, placeholderId);

    if (clazz == String.class) return String.valueOf(placeholderId);
    if (Date.class.isAssignableFrom(clazz)) return new Date(placeholderId);
    if (clazz.isArray()) return Array.newInstance(clazz.getComponentType(), 1);

    try {
      return createArgumentPlaceholderForUnknownClass(clazz, placeholderId);
    } catch (Exception e) {
      throw new ArgumentConversionException(
          "It is not possible to create a placeholder for class: " + clazz.getName(), e);
    }
  }
  static String[] c_signature(Class c, String expr) {
    if (c.isPrimitive()) return strs("j" + c.toString(), expr, expr);
    if (c == Pointer.class)
      return strs(
          "void*",
          "createPointerFromIO(env, " + expr + ", NULL)",
          "getPointerPeer(env, " + expr + ")"); // TODO callIO
    if (c == CLong.class)
      return strs("long", "BoxCLong(env, " + expr + ")", "UnBoxCLong(env, " + expr + ")");
    if (c == SizeT.class)
      return strs("size_t", "BoxSizeT(env, " + expr + ")", "UnBoxSizeT(env, " + expr + ")");
    if (c == TimeT.class)
      return strs("time_t", "BoxTimeT(env, " + expr + ")", "UnBoxTimeT(env, " + expr + ")");

    throw new UnsupportedOperationException("Cannot compute C signature for " + c.getName());
  }
示例#27
0
  public static Object[] getActionMethodArgs(Method method, Object o) throws Exception {
    String[] paramsNames = Java.parameterNames(method);
    if (paramsNames == null && method.getParameterTypes().length > 0) {
      throw new UnexpectedException("Parameter names not found for method " + method);
    }

    // Check if we have already performed the bind operation
    Object[] rArgs = CachedBoundActionMethodArgs.current().retrieveActionMethodArgs(method);
    if (rArgs != null) {
      // We have already performed the binding-operation for this method
      // in this request.
      return rArgs;
    }

    rArgs = new Object[method.getParameterTypes().length];
    for (int i = 0; i < method.getParameterTypes().length; i++) {

      Class<?> type = method.getParameterTypes()[i];
      Map<String, String[]> params = new HashMap<String, String[]>();

      // In case of simple params, we don't want to parse the body.
      if (type.equals(String.class) || Number.class.isAssignableFrom(type) || type.isPrimitive()) {
        params.put(paramsNames[i], Scope.Params.current().getAll(paramsNames[i]));
      } else {
        params.putAll(Scope.Params.current().all());
      }
      Logger.trace(
          "getActionMethodArgs name ["
              + paramsNames[i]
              + "] annotation ["
              + Utils.join(method.getParameterAnnotations()[i], " ")
              + "]");

      RootParamNode root = ParamNode.convert(params);
      rArgs[i] =
          Binder.bind(
              root,
              paramsNames[i],
              method.getParameterTypes()[i],
              method.getGenericParameterTypes()[i],
              method.getParameterAnnotations()[i],
              new Binder.MethodAndParamInfo(o, method, i + 1));
    }

    CachedBoundActionMethodArgs.current().storeActionMethodArgs(method, rArgs);
    return rArgs;
  }
示例#28
0
  /**
   * @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;
  }
  /**
   * Returns the shallow instance size in bytes an instance of the given class would occupy. This
   * works with all conventional classes and primitive types, but not with arrays (the size then
   * depends on the number of elements and varies from object to object).
   *
   * @see #shallowSizeOf(Object)
   * @throws IllegalArgumentException if {@code clazz} is an array class.
   */
  public static long shallowSizeOfInstance(Class<?> clazz) {
    if (clazz.isArray())
      throw new IllegalArgumentException("This method does not work with array classes.");
    if (clazz.isPrimitive()) return primitiveSizes.get(clazz);

    long size = NUM_BYTES_OBJECT_HEADER;

    // Walk type hierarchy
    for (; clazz != null; clazz = clazz.getSuperclass()) {
      final Field[] fields = clazz.getDeclaredFields();
      for (Field f : fields) {
        if (!Modifier.isStatic(f.getModifiers())) {
          size = adjustForField(size, f);
        }
      }
    }
    return alignObjectSize(size);
  }
  protected void invokeAllMethods(ConnectionDecorator connectionDecorator) {
    for (Method method : getConnectionMethods(connectionDecorator)) {
      Class<?>[] parameterTypes = method.getParameterTypes();
      Object[] parameters = new Object[parameterTypes.length];

      for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> parameterType = parameterTypes[i];
        if (!parameterType.isPrimitive()) {
          Object finalObject = classToFinalObjects.get(parameterType);
          parameters[i] = finalObject != null ? finalObject : Mockito.mock(parameterType);
        } else {
          parameters[i] = classToPrimitives.get(parameterType);
        }
      }
      ReflectionUtils.invoke(
          connectionDecorator,
          ReflectionUtils.getMethod(connectionDecorator, method.getName(), parameterTypes),
          parameters);
    }
  }