Пример #1
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
Пример #2
0
  /**
   * Sets up the mocks defined in the given mock class.
   *
   * <p>If the type {@linkplain MockClass#realClass referred to} by the mock class is actually an
   * interface, then a {@linkplain #newEmptyProxy(ClassLoader, Class) new empty proxy} is created.
   *
   * @param mockClassOrInstance the mock class itself (given by its {@code Class} literal), or an
   *     instance of the mock class
   * @return the new proxy instance created for the mocked interface, or {@code null} otherwise
   * @throws IllegalArgumentException if a given mock class fails to specify the corresponding real
   *     class using the {@code @MockClass(realClass = ...)} annotation; or if a mock class defines
   *     a mock method for which no corresponding real method or constructor exists in the real
   *     class; or if the real method matching a mock method is {@code abstract}
   * @see #setUpMock(Class, Object)
   * @see #setUpMocks(Object...)
   * @see <a
   *     href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/mockit/MockAnnotationsTest.java#696">
   *     Example</a>
   */
  public static <T> T setUpMock(Object mockClassOrInstance) {
    Class<?> mockClass;
    Object mock;

    if (mockClassOrInstance instanceof Class<?>) {
      mockClass = (Class<?>) mockClassOrInstance;
      mock = null;
    } else {
      mockClass = mockClassOrInstance.getClass();
      mock = mockClassOrInstance;
    }

    MockClassSetup setup = new MockClassSetup(mock, mockClass);
    Class<?> realClass = setup.getRealClass();
    T proxy = null;

    if (realClass.isInterface()) {
      //noinspection unchecked
      proxy = (T) newEmptyProxy(mockClass.getClassLoader(), realClass);
      setup.setRealClass(proxy.getClass());
    }

    setup.redefineMethods();

    return proxy;
  }
 public boolean compareAndSet(T obj, V expect, V update) {
   if (obj == null
       || obj.getClass() != tclass
       || cclass != null
       || (update != null && vclass != null && vclass != update.getClass()))
     updateCheck(obj, update);
   return unsafe.compareAndSwapObject(obj, offset, expect, update);
 }
 public void lazySet(T obj, V newValue) {
   if (obj == null
       || obj.getClass() != tclass
       || cclass != null
       || (newValue != null && vclass != null && vclass != newValue.getClass()))
     updateCheck(obj, newValue);
   unsafe.putOrderedObject(obj, offset, newValue);
 }
 public boolean compareAndSet(T obj, long expect, long update) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   synchronized (this) {
     long v = unsafe.getLong(obj, offset);
     if (v != expect) return false;
     unsafe.putLong(obj, offset, update);
     return true;
   }
 }
 public boolean weakCompareAndSet(T obj, V expect, V update) {
   // same implementation as strong form for now
   if (obj == null
       || obj.getClass() != tclass
       || cclass != null
       || (update != null && vclass != null && vclass != update.getClass()))
     updateCheck(obj, update);
   return unsafe.compareAndSwapObject(obj, offset, expect, update);
 }
Пример #7
0
 /**
  * Computes the display string for any value.
  *
  * @param t the value to print
  * @return the formatted string
  */
 public static <T> String print(T t) {
   if (t == null) {
     return "";
   }
   if (conversion.canConvert(t.getClass(), String.class)) {
     return conversion.convert(t, String.class);
   } else {
     return t.toString();
   }
 }
Пример #8
0
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   if (method.getDeclaringClass().isAssignableFrom(original.getClass())) {
     if (method.getName().equals("equals") && args.length == 1) {
       return args[0] == proxy;
     } else {
       return method.invoke(original, args);
     }
   } else {
     return getMethodHandle(method).bindTo(proxy).invokeWithArguments(args);
   }
 }
Пример #9
0
 /**
  * Computes the display string for any value, for a specific type.
  *
  * @param desc the field descriptor - custom formatters are extracted from this descriptor.
  * @param t the value to print
  * @return the formatted string
  */
 public static <T> String print(TypeDescriptor desc, T t) {
   if (t == null) {
     return "";
   }
   if (desc != null && conversion.canConvert(desc, TypeDescriptor.valueOf(String.class))) {
     return (String) conversion.convert(t, desc, TypeDescriptor.valueOf(String.class));
   } else if (conversion.canConvert(t.getClass(), String.class)) {
     return conversion.convert(t, String.class);
   } else {
     return t.toString();
   }
 }
 private void ensureProtectedAccess(T obj) {
   if (cclass.isInstance(obj)) {
     return;
   }
   throw new RuntimeException(
       new IllegalAccessException(
           "Class "
               + cclass.getName()
               + " can not access a protected member of class "
               + tclass.getName()
               + " using an instance of "
               + obj.getClass().getName()));
 }
Пример #11
0
 @SuppressWarnings("unchecked")
 public static <T> T clone(T object) {
   try {
     Method cloneMethod = object.getClass().getMethod("clone");
     return (T) cloneMethod.invoke(object);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("Unexpected exception", e); // This is not supposed to happen
   } catch (IllegalAccessException e) {
     throw new RuntimeException("Unexpected exception", e); // This is not supposed to happen
   } catch (InvocationTargetException e) {
     throw new RuntimeException("Execption occured in clone() method", e);
   }
 }
Пример #12
0
  private void initialize(Method method, T target) {
    if (Modifier.isStatic(method.getModifiers()) && target != null) {
      throw new IllegalArgumentException("Cannot supply a target for static methods.");
    }

    if (target != null && !method.getDeclaringClass().isAssignableFrom(target.getClass())) {
      throw new IllegalArgumentException("Method and target object are not type compatible.");
    }

    if (!method.getReturnType().isAssignableFrom(Tuple.class)) {
      throw new IllegalArgumentException("Can only wrap methods with return type Tuple.");
    }

    this.method = method;
    this.target = target;
  }
Пример #13
0
  public static <T> T mixin(T target, Class<?>... interfaces) {
    if (target == null) return null;

    // When request is
    final Class<?> targetClass = target.getClass();
    if (Arrays.stream(interfaces).allMatch(i -> i.isAssignableFrom(targetClass))) {
      return target;
    }

    Class[] classes;
    int addedIndex;
    if (Proxy.isProxyClass(targetClass)) {
      MixinProxyHandler<T> handler = ((MixinProxyHandler<T>) Proxy.getInvocationHandler(target));
      target = handler.getOriginal();
      Class[] originalInterfaces = handler.getProxyInterfaces();
      classes = new Class[originalInterfaces.length + interfaces.length];
      System.arraycopy(originalInterfaces, 0, classes, 0, originalInterfaces.length);
      addedIndex = originalInterfaces.length;
    } else {
      Class[] targetInterfaces = getAllInterfaces(targetClass);
      classes = new Class[targetInterfaces.length + interfaces.length];
      System.arraycopy(targetInterfaces, 0, classes, 0, targetInterfaces.length);
      addedIndex = targetInterfaces.length;
    }
    Arrays.asList(interfaces)
        .forEach(
            i ->
                Arrays.asList(i.getMethods())
                    .stream()
                    .filter(Method::isDefault)
                    .forEach(MixinUtils::getMethodHandle));

    System.arraycopy(interfaces, 0, classes, addedIndex, interfaces.length);

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return (T) Proxy.newProxyInstance(cl, classes, new MixinProxyHandler(target, classes));
  }
 public boolean weakCompareAndSet(T obj, long expect, long update) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   return unsafe.compareAndSwapLong(obj, offset, expect, update);
 }
 public V get(T obj) {
   if (obj == null || obj.getClass() != tclass || cclass != null) targetCheck(obj);
   return (V) unsafe.getObjectVolatile(obj, offset);
 }
 public void set(T obj, long newValue) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   unsafe.putLongVolatile(obj, offset, newValue);
 }
 public void lazySet(T obj, long newValue) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   unsafe.putOrderedLong(obj, offset, newValue);
 }
 public long get(T obj) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   return unsafe.getLongVolatile(obj, offset);
 }
  /**
   * Parses object with follow rules:
   *
   * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to
   * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of
   * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list
   * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or
   * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s.
   *
   * <p>4. Boolean fields defines by vk_int == 1 expression.
   *
   * @param object object to initialize
   * @param source data to read values
   * @param <T> type of result
   * @return initialized according with given data object
   * @throws org.json.JSONException if source object structure is invalid
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
      source = source.optJSONObject("response");
    }
    if (source == null) {
      return object;
    }
    for (Field field : object.getClass().getFields()) {
      field.setAccessible(true);
      String fieldName = field.getName();
      Class<?> fieldType = field.getType();

      Object value = source.opt(fieldName);
      if (value == null) {
        continue;
      }
      try {
        if (fieldType.isPrimitive() && value instanceof Number) {
          Number number = (Number) value;
          if (fieldType.equals(int.class)) {
            field.setInt(object, number.intValue());
          } else if (fieldType.equals(long.class)) {
            field.setLong(object, number.longValue());
          } else if (fieldType.equals(float.class)) {
            field.setFloat(object, number.floatValue());
          } else if (fieldType.equals(double.class)) {
            field.setDouble(object, number.doubleValue());
          } else if (fieldType.equals(boolean.class)) {
            field.setBoolean(object, number.intValue() == 1);
          } else if (fieldType.equals(short.class)) {
            field.setShort(object, number.shortValue());
          } else if (fieldType.equals(byte.class)) {
            field.setByte(object, number.byteValue());
          }
        } else {
          Object result = field.get(object);
          if (value.getClass().equals(fieldType)) {
            result = value;
          } else if (fieldType.isArray() && value instanceof JSONArray) {
            result = parseArrayViaReflection((JSONArray) value, fieldType);
          } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKAttachments.class.isAssignableFrom(fieldType)
              && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKList.class.equals(fieldType)) {
            ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
            Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
            if (VKApiModel.class.isAssignableFrom(genericType)
                && Parcelable.class.isAssignableFrom(genericType)
                && Identifiable.class.isAssignableFrom(genericType)) {
              if (value instanceof JSONArray) {
                result = new VKList((JSONArray) value, genericType);
              } else if (value instanceof JSONObject) {
                result = new VKList((JSONObject) value, genericType);
              }
            }
          } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
            result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
          }
          field.set(object, result);
        }
      } catch (InstantiationException e) {
        throw new JSONException(e.getMessage());
      } catch (IllegalAccessException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodException e) {
        throw new JSONException(e.getMessage());
      } catch (InvocationTargetException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodError e) {
        // Примечание Виталия:
        // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО.
        // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве
        // платформы разработки.
        throw new JSONException(e.getMessage());
      }
    }
    return object;
  }
 public void set(T obj, long newValue) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   synchronized (this) {
     unsafe.putLong(obj, offset, newValue);
   }
 }
 public long get(T obj) {
   if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
   synchronized (this) {
     return unsafe.getLong(obj, offset);
   }
 }
Пример #22
0
 public static <T> ModelType<T> typeOf(T instance) {
   // TODO: should validate that clazz is of a non parameterized type
   @SuppressWarnings("unchecked")
   Class<T> clazz = (Class<T>) instance.getClass();
   return of(clazz);
 }
Пример #23
0
 public Invokeable(String method, T target) throws NoSuchMethodException {
   initialize(getMethod(method, target.getClass()), target);
 }