Пример #1
0
  private static List<LabelValue> makeList2(Class<? extends Enum> clazz) {
    List<LabelValue> list = new ArrayList<LabelValue>();
    Method method = ReflectionUtils.findMethod(clazz, "values");
    try {
      Object[] array = (Object[]) method.invoke(null);
      for (Object obj : array) {
        Method m = ReflectionUtils.findMethod(clazz, "getLabel");
        String cnName = (String) m.invoke(obj);
        m = ReflectionUtils.findMethod(clazz, "name");
        String name = (String) m.invoke(obj);
        LabelValue lv = new LabelValue(cnName, name);

        m = ReflectionUtils.findMethod(clazz, "isSelectList");
        if (m != null) {
          boolean flag = (boolean) m.invoke(obj);
          lv.setListFlag(flag);
        }
        list.add(lv);
      }
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    return list;
  }
 protected void init() throws ClassNotFoundException {
   this.proxyObjectType =
       ClassUtils.resolveClassName(getProxyInterfaceName(), ClassUtils.getDefaultClassLoader());
   final Class<?> modelParameterClazz =
       ClassUtils.resolveClassName(
           "org.springframework.web.servlet.ModelAndView", ClassUtils.getDefaultClassLoader());
   this.getModelMapMethod = ReflectionUtils.findMethod(modelParameterClazz, "getModelMap");
   this.getViewNameMethod = ReflectionUtils.findMethod(modelParameterClazz, "getViewName");
   this.setViewNameMethod =
       ReflectionUtils.findMethod(modelParameterClazz, "setViewName", String.class);
 }
 @Test
 public void specifiedOrder() {
   Method method =
       ReflectionUtils.findMethod(SampleEvents.class, "handleRaw", ApplicationEvent.class);
   ApplicationListenerMethodAdapter adapter = createTestInstance(method);
   assertEquals(42, adapter.getOrder());
 }
  private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
    Method method = ReflectionUtils.findMethod(domainClazz, event);
    if (method != null) {
      ReflectionUtils.makeAccessible(method);
      return new MethodCaller(method);
    }

    Field field = ReflectionUtils.findField(domainClazz, event);
    if (field != null) {
      ReflectionUtils.makeAccessible(field);
      return new FieldClosureCaller(field);
    }

    MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
    if (metaMethod != null) {
      return new MetaMethodCaller(metaMethod);
    }

    MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
    if (metaProperty != null) {
      return new MetaPropertyClosureCaller(metaProperty);
    }

    return null;
  }
Пример #5
0
 public static Method findGetterMethod(String propertyName, Class<?> entityClass) {
   StringBuilder sb = new StringBuilder();
   sb.append(GET);
   sb.append(Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1));
   Method method = ReflectionUtils.findMethod(entityClass, sb.toString());
   return method;
 }
 @Test
 public void listenerWithAnnotationValueAndParameter() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleStringAnnotationValueAndParameter", String.class);
   supportsEventType(true, method, createGenericEventType(String.class));
 }
 private void readObject(ObjectInputStream inputStream)
     throws IOException, ClassNotFoundException {
   inputStream.defaultReadObject();
   Method method =
       ReflectionUtils.findMethod(this.provider.getType().getClass(), this.methodName);
   this.result = ReflectionUtils.invokeMethod(method, this.provider.getType());
 }
  public static void update() {

    try {
      final String msg = "DatabaseSchemaUpdater: Begin";
      log(msg);

      final String applicationName = CommonServiceLocator.getInstance().getAppName();
      DAO dao = DAOConfigFactory.getInstance().getDAOFactory(applicationName).getDAO();
      Method getConnectionManagerMethod =
          ReflectionUtils.findMethod(dao.getClass(), "getConnectionManager");
      ReflectionUtils.makeAccessible(getConnectionManagerMethod);
      IConnectionManager connectionManager =
          (IConnectionManager) ReflectionUtils.invokeMethod(getConnectionManagerMethod, dao);

      Connection c = null;
      try {
        c = connectionManager.getConnection();
        update(c);
      } finally {
        try {
          connectionManager.commit();
        } catch (Exception e) {
        }
        connectionManager.closeConnection();
      }

    } catch (Exception e) {
      final String msg = "DatabaseSchemaUpdater: Failed with " + e.getMessage();
      log(msg);
    }
  }
  private Object doRequestAttribute(
      String methodName, final String attributeName, final String value) throws Exception {

    MethodParameter methodParameter =
        new MethodParameter(
            ReflectionUtils.findMethod(
                AnnotatedClass.class, methodName, new Class[] {String.class}),
            0);

    expect(nativeRequest.getNativeRequest()).andReturn(request);
    expect(request.getInputStream())
        .andReturn(
            new ServletInputStream() {

              @Override
              public int read() throws IOException {
                return -1;
              }
            });

    replayMocks();

    Object arg = resolver.resolveArgument(methodParameter, nativeRequest);

    verifyMocks();
    return arg;
  }
 @Test
 public void listenerWithSeveralTypes() {
   Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringOrInteger");
   supportsEventType(true, method, createGenericEventType(String.class));
   supportsEventType(true, method, createGenericEventType(Integer.class));
   supportsEventType(false, method, createGenericEventType(Double.class));
 }
 @Test
 public void genericListener() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleGenericString", GenericTestEvent.class);
   supportsEventType(true, method, getGenericApplicationEventType("stringEvent"));
 }
  @Test
  public void testOauthClient() throws Exception {
    AuthorizationRequest request = new AuthorizationRequest("foo", Collections.singleton("read"));
    request.setResourceIdsAndAuthoritiesFromClientDetails(
        new BaseClientDetails("foo", "", "", "client_credentials", "ROLE_CLIENT"));
    Authentication userAuthentication = null;

    OAuth2Request clientAuthentication =
        RequestTokenFactory.createOAuth2Request(
            request.getRequestParameters(),
            request.getClientId(),
            request.getAuthorities(),
            request.isApproved(),
            request.getScope(),
            request.getResourceIds(),
            request.getRedirectUri(),
            request.getResponseTypes(),
            request.getExtensions());

    OAuth2Authentication oAuth2Authentication =
        new OAuth2Authentication(clientAuthentication, userAuthentication);
    MethodInvocation invocation =
        new SimpleMethodInvocation(this, ReflectionUtils.findMethod(getClass(), "testOauthClient"));
    EvaluationContext context = handler.createEvaluationContext(oAuth2Authentication, invocation);
    Expression expression =
        handler.getExpressionParser().parseExpression("#oauth2.clientHasAnyRole('ROLE_CLIENT')");
    assertTrue((Boolean) expression.getValue(context));
  }
 @Test
 public void invokeListenerWithAnnotationValue() {
   Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleStringAnnotationClasses");
   PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
   invokeListener(method, event);
   verify(this.sampleEvents, times(1)).handleStringAnnotationClasses();
 }
  @Override
  protected Object retrieveAction(
      GroovyObject controller, String actionName, HttpServletResponse response) {

    Class<?> controllerClass = AopProxyUtils.ultimateTargetClass(controller);

    Method mAction =
        ReflectionUtils.findMethod(
            controllerClass, actionName, MethodGrailsControllerHelper.NOARGS);
    if (mAction != null) {
      ReflectionUtils.makeAccessible(mAction);
      if (mAction.getAnnotation(Action.class) != null) {
        return mAction;
      }
    }

    try {
      return controller.getProperty(actionName);
    } catch (MissingPropertyException mpe) {
      try {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
      } catch (IOException e) {
        throw new ControllerExecutionException("I/O error sending 404 error", e);
      }
    }
  }
 @Test
 public void invokeListenerWithPayloadWrongType() {
   Method method = ReflectionUtils.findMethod(SampleEvents.class, "handleString", String.class);
   PayloadApplicationEvent<Long> event = new PayloadApplicationEvent<>(this, 123L);
   invokeListener(method, event);
   verify(this.sampleEvents, never()).handleString(anyString());
 }
 @Override
 public Object accessValue(Object entity) {
   Assert.notNull(entity);
   Method method =
       ReflectionUtils.findMethod(entity.getClass(), this.getAccessMethodName(), String.class);
   return ReflectionUtils.invokeMethod(method, entity);
 }
  @Test
  public void testScopesRegex() throws Exception {

    OAuth2Request clientAuthentication =
        RequestTokenFactory.createOAuth2Request(
            null,
            "foo",
            null,
            false,
            Collections.singleton("ns_admin:read"),
            null,
            null,
            null,
            null);

    Authentication userAuthentication = null;
    OAuth2Authentication oAuth2Authentication =
        new OAuth2Authentication(clientAuthentication, userAuthentication);
    MethodInvocation invocation =
        new SimpleMethodInvocation(this, ReflectionUtils.findMethod(getClass(), "testOauthClient"));
    EvaluationContext context = handler.createEvaluationContext(oAuth2Authentication, invocation);
    Expression expression =
        handler.getExpressionParser().parseExpression("#oauth2.hasScopeMatching('.*_admin:read')");
    assertTrue((Boolean) expression.getValue(context));
    expression =
        handler
            .getExpressionParser()
            .parseExpression("#oauth2.hasAnyScopeMatching('.*_admin:write','.*_admin:read')");
    assertTrue((Boolean) expression.getValue(context));
  }
 @Test
 public void genericListenerWrongParameterizedType() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleGenericString", GenericTestEvent.class);
   supportsEventType(false, method, getGenericApplicationEventType("longEvent"));
 }
 @Test
 public void listenerWithMoreThanOneParameter() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "moreThanOneParameter", String.class, Integer.class);
   this.thrown.expect(IllegalStateException.class);
   createTestInstance(method);
 }
 @Test
 public void defaultOrder() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleGenericString", GenericTestEvent.class);
   ApplicationListenerMethodAdapter adapter = createTestInstance(method);
   assertEquals(0, adapter.getOrder());
 }
 @Test
 public void listenerWithTooManyParameters() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "tooManyParameters", String.class, String.class);
   this.thrown.expect(IllegalStateException.class);
   createTestInstance(method);
 }
 @Test
 public void invokeListenerWithAnyGenericPayload() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleGenericAnyPayload", EntityWrapper.class);
   EntityWrapper<String> payload = new EntityWrapper<>("test");
   invokeListener(method, new PayloadApplicationEvent<>(this, payload));
   verify(this.sampleEvents, times(1)).handleGenericAnyPayload(payload);
 }
 @Test
 public void invokeListenerWithGenericEvent() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleGenericString", GenericTestEvent.class);
   GenericTestEvent<String> event = new SmartGenericTestEvent<>(this, "test");
   invokeListener(method, event);
   verify(this.sampleEvents, times(1)).handleGenericString(event);
 }
 @Test
 public void invokeListenerWithWrongGenericPayload() {
   Method method =
       ReflectionUtils.findMethod(
           SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
   EntityWrapper<Integer> payload = new EntityWrapper<>(123);
   invokeListener(method, new PayloadApplicationEvent<>(this, payload));
   verify(this.sampleEvents, times(0)).handleGenericStringPayload(any());
 }
Пример #25
0
  /**
   * This method uses reflection to build a valid hash code.
   *
   * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This
   * means that it will throw a security exception if run under a security manager, if the
   * permissions are not set up correctly. It is also not as efficient as testing explicitly.
   *
   * <p>Transient members will not be used, as they are likely derived fields, and not part of the
   * value of the <code>Object</code>.
   *
   * <p>Static fields will not be tested. Superclass fields will be included.
   *
   * @param obj the object to create a <code>hashCode</code> for
   * @return the generated hash code, or zero if the given object is <code>null</code>
   */
  public static int reflectionHashCode(Object obj) {
    if (obj == null) return 0;

    Class<?> targetClass = obj.getClass();
    if (isArrayOfPrimitives(obj)) {
      // || ObjectUtils.isPrimitiveOrWrapper(targetClass)) {
      return ObjectUtils.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
      return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
      return reflectionHashCode((Collection<?>) obj);
    }

    if (obj instanceof Map) {
      return reflectionHashCode((Map<?, ?>) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
      return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by
    // java.lang.Object
    int hash = INITIAL_HASH;

    try {
      while (targetClass != null) {
        Field[] fields = targetClass.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);

        for (int i = 0; i < fields.length; i++) {
          Field field = fields[i];
          int modifiers = field.getModifiers();

          if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
            hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
          }
        }
        targetClass = targetClass.getSuperclass();
      }
    } catch (IllegalAccessException exception) {
      // ///CLOVER:OFF
      ReflectionUtils.handleReflectionException(exception);
      // ///CLOVER:ON
    }

    return hash;
  }
Пример #26
0
 /**
  * Returns the method for the interface
  *
  * @param resourceInterfaceWithOneMethod
  * @param resource
  * @return null or a Method
  */
 public static Method findMethod(
     Class<? extends ResourceAction> resourceInterfaceWithOneMethod, Class<?> resource) {
   Method[] resourceMethods = resourceInterfaceWithOneMethod.getMethods();
   if (resourceMethods == null || resourceMethods.length != 1) {
     // All the interfaces should have just one method.
     throw new IllegalArgumentException(
         resourceInterfaceWithOneMethod + " should be an interface with just one method.");
   }
   Method method = ReflectionUtils.findMethod(resource, resourceMethods[0].getName(), null);
   return method;
 }
 /**
  * Determine if the annotated field or method requires its dependency.
  *
  * <p>A 'required' dependency means that autowiring should fail when no beans are found.
  * Otherwise, the autowiring process will simply bypass the field or method when no beans are
  * found.
  *
  * @param annotation the Autowired annotation
  * @return whether the annotation indicates that a dependency is required
  */
 protected boolean determineRequiredStatus(Annotation annotation) {
   try {
     Method method =
         ReflectionUtils.findMethod(annotation.annotationType(), this.requiredParameterName);
     return (this.requiredParameterValue
         == (Boolean) ReflectionUtils.invokeMethod(method, annotation));
   } catch (Exception ex) {
     // required by default
     return true;
   }
 }
 public UndertowXnioBufferSupport() {
   this.xnioBufferPool = new org.xnio.ByteBufferSlicePool(1048, 1048);
   this.httpClientConnectCallbackMethod =
       ReflectionUtils.findMethod(
           UndertowClient.class,
           "connect",
           ClientCallback.class,
           URI.class,
           XnioWorker.class,
           Pool.class,
           OptionMap.class);
   this.httpClientConnectMethod =
       ReflectionUtils.findMethod(
           UndertowClient.class,
           "connect",
           URI.class,
           XnioWorker.class,
           Pool.class,
           OptionMap.class);
 }
 public Undertow13BufferSupport() {
   this.undertowBufferPool = new DefaultByteBufferPool(false, 1024, -1, 2);
   this.httpClientConnectCallbackMethod =
       ReflectionUtils.findMethod(
           UndertowClient.class,
           "connect",
           ClientCallback.class,
           URI.class,
           XnioWorker.class,
           ByteBufferPool.class,
           OptionMap.class);
   this.httpClientConnectMethod =
       ReflectionUtils.findMethod(
           UndertowClient.class,
           "connect",
           URI.class,
           XnioWorker.class,
           ByteBufferPool.class,
           OptionMap.class);
 }
  @Test
  public void invokeListenerCheckedException() {
    Method method =
        ReflectionUtils.findMethod(
            SampleEvents.class, "generateCheckedException", GenericTestEvent.class);
    GenericTestEvent<String> event = createGenericTestEvent("fail");

    this.thrown.expect(UndeclaredThrowableException.class);
    this.thrown.expectCause(is(instanceOf(IOException.class)));
    invokeListener(method, event);
  }