private void configureParameterNameProviderIfPossible(Configuration configuration) {
    try {
      Class<?> parameterNameProviderClass =
          ClassUtils.forName("javax.validation.ParameterNameProvider", getClass().getClassLoader());
      Method parameterNameProviderMethod =
          Configuration.class.getMethod("parameterNameProvider", parameterNameProviderClass);
      final Object defaultProvider =
          ReflectionUtils.invokeMethod(
              Configuration.class.getMethod("getDefaultParameterNameProvider"), configuration);
      final ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer;
      Object parameterNameProvider =
          Proxy.newProxyInstance(
              getClass().getClassLoader(),
              new Class[] {parameterNameProviderClass},
              new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                  if (method.getName().equals("getParameterNames")) {
                    String[] result = null;
                    if (args[0] instanceof Constructor) {
                      result = discoverer.getParameterNames((Constructor) args[0]);
                    } else if (args[0] instanceof Method) {
                      result = discoverer.getParameterNames((Method) args[0]);
                    }
                    if (result != null) {
                      return Arrays.asList(result);
                    } else {
                      try {
                        return method.invoke(defaultProvider, args);
                      } catch (InvocationTargetException ex) {
                        throw ex.getTargetException();
                      }
                    }
                  } else {
                    // toString, equals, hashCode
                    try {
                      return method.invoke(this, args);
                    } catch (InvocationTargetException ex) {
                      throw ex.getTargetException();
                    }
                  }
                }
              });
      ReflectionUtils.invokeMethod(
          parameterNameProviderMethod, configuration, parameterNameProvider);

    } catch (Exception ex) {
      // Bean Validation 1.1 API not available - simply not applying the ParameterNameDiscoverer
    }
  }
  /**
   * @param testContext the current test context
   * @throws Exception if there is a problem
   * @see TestExecutionListener#beforeTestMethod(TestContext)
   */
  @Override
  public void beforeTestMethod(TestContext testContext) throws Exception {
    Method hasAttributeMethod =
        TestContext.class.getMethod(HAS_ATTRIBUTE_METHOD_NAME, String.class);
    Boolean hasAttribute =
        (Boolean) ReflectionUtils.invokeMethod(hasAttributeMethod, testContext, STEP_EXECUTION);

    if (hasAttribute) {
      Method method = TestContext.class.getMethod(GET_ATTRIBUTE_METHOD_NAME, String.class);
      StepExecution stepExecution =
          (StepExecution) ReflectionUtils.invokeMethod(method, testContext, STEP_EXECUTION);

      StepSynchronizationManager.register(stepExecution);
    }
  }
  /**
   * Discover a {@link StepExecution} as a field in the test case or create one if none is
   * available.
   *
   * @param testContext the current test context
   * @return a {@link StepExecution}
   */
  protected StepExecution getStepExecution(TestContext testContext) {
    Object target;

    try {
      Method method = TestContext.class.getMethod(GET_TEST_INSTANCE_METHOD);
      target = ReflectionUtils.invokeMethod(method, testContext);
    } catch (NoSuchMethodException e) {
      throw new IllegalStateException(
          "No such method " + GET_TEST_INSTANCE_METHOD + " on provided TestContext", e);
    }

    ExtractorMethodCallback method =
        new ExtractorMethodCallback(StepExecution.class, "getStepExecution");
    ReflectionUtils.doWithMethods(target.getClass(), method);
    if (method.getName() != null) {
      HippyMethodInvoker invoker = new HippyMethodInvoker();
      invoker.setTargetObject(target);
      invoker.setTargetMethod(method.getName());
      try {
        invoker.prepare();
        return (StepExecution) invoker.invoke();
      } catch (Exception e) {
        throw new IllegalArgumentException(
            "Could not create step execution from method: " + method.getName(), e);
      }
    }

    return MetaDataInstanceFactory.createStepExecution();
  }
  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);
    }
  }
  /**
   * Create a new JRuby-scripted object from the given script source.
   *
   * @param scriptSource the script source text
   * @param interfaces the interfaces that the scripted Java object is to implement
   * @param classLoader the {@link ClassLoader} to create the script proxy with
   * @return the scripted Java object
   * @throws JumpException in case of JRuby parsing failure
   */
  public static Object createJRubyObject(
      String scriptSource, Class[] interfaces, ClassLoader classLoader) {
    Ruby ruby = initializeRuntime();

    Node scriptRootNode =
        (oldParseMethod != null
            ? (Node)
                ReflectionUtils.invokeMethod(
                    oldParseMethod, ruby, new Object[] {scriptSource, "", null})
            : ruby.parse(scriptSource, "", null, 0));
    IRubyObject rubyObject = ruby.eval(scriptRootNode);

    if (rubyObject instanceof RubyNil) {
      String className = findClassName(scriptRootNode);
      rubyObject = ruby.evalScript("\n" + className + ".new");
    }
    // still null?
    if (rubyObject instanceof RubyNil) {
      throw new IllegalStateException(
          "Compilation of JRuby script returned RubyNil: " + rubyObject);
    }

    return Proxy.newProxyInstance(
        classLoader, interfaces, new RubyObjectInvocationHandler(rubyObject, ruby));
  }
  @Override
  protected Object handleRequestMessage(Message<?> requestMessage) {
    final Object requestPayload = requestMessage.getPayload();
    final Object targetPayload;
    if (requestPayload instanceof Cloneable && this.shouldClonePayload) {
      try {
        Method cloneMethod = requestPayload.getClass().getMethod("clone");
        targetPayload = ReflectionUtils.invokeMethod(cloneMethod, requestPayload);
      } catch (Exception e) {
        throw new MessageHandlingException(requestMessage, "Failed to clone payload object", e);
      }
    } else {
      targetPayload = requestPayload;
    }
    final Message<?> actualRequestMessage;
    if (this.requestPayloadExpression == null) {
      actualRequestMessage = requestMessage;
    } else {
      final Object requestMessagePayload =
          this.requestPayloadExpression.getValue(this.sourceEvaluationContext, requestMessage);
      actualRequestMessage =
          MessageBuilder.withPayload(requestMessagePayload)
              .copyHeaders(requestMessage.getHeaders())
              .build();
    }
    final Message<?> replyMessage;
    if (this.gateway == null) {
      replyMessage = actualRequestMessage;
    } else {
      replyMessage = this.gateway.sendAndReceiveMessage(actualRequestMessage);
      if (replyMessage == null) {
        return replyMessage;
      }
    }
    for (Map.Entry<Expression, Expression> entry : this.propertyExpressions.entrySet()) {
      Expression propertyExpression = entry.getKey();
      Expression valueExpression = entry.getValue();
      Object value = valueExpression.getValue(this.sourceEvaluationContext, replyMessage);
      propertyExpression.setValue(this.targetEvaluationContext, targetPayload, value);
    }

    if (this.headerExpressions.isEmpty()) {
      return targetPayload;
    } else {
      Map<String, Object> targetHeaders =
          new HashMap<String, Object>(this.headerExpressions.size());
      for (Map.Entry<String, HeaderValueMessageProcessor<?>> entry :
          this.headerExpressions.entrySet()) {
        String header = entry.getKey();
        HeaderValueMessageProcessor<?> valueProcessor = entry.getValue();
        Boolean overwrite = valueProcessor.isOverwrite();
        overwrite = overwrite != null ? overwrite : true;
        if (overwrite || !requestMessage.getHeaders().containsKey(header)) {
          Object value = valueProcessor.processMessage(replyMessage);
          targetHeaders.put(header, value);
        }
      }
      return MessageBuilder.withPayload(targetPayload).copyHeaders(targetHeaders).build();
    }
  }
 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());
 }
 protected Serializable fieldValue(final Object obj, final AnnotatedElement annotatedElement) {
   if (annotatedElement instanceof Field) { // a field
     final Field f = (Field) annotatedElement;
     if (!f.isAccessible()) {
       f.setAccessible(true);
     }
     try {
       return (Serializable) f.get(obj);
     } catch (final IllegalArgumentException e) {
       logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e);
     } catch (final IllegalAccessException e) {
       logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e);
     } catch (final ClassCastException e) {
       logger.warn(obj.getClass().getName() + "的id字段" + f.getName() + "不可序列化。", e);
     }
   } else { // a method
     final Method m = (Method) annotatedElement;
     if (!m.isAccessible()) {
       m.setAccessible(true);
     }
     try {
       return (Serializable) ReflectionUtils.invokeMethod(m, obj);
     } catch (final ClassCastException e) {
       logger.warn(obj.getClass().getName() + "的id字段" + m.getName() + "不可序列化。", e);
     }
   }
   return null;
 }
 @Override
 public Object accessValue(Object entity) {
   Assert.notNull(entity);
   Method method =
       ReflectionUtils.findMethod(entity.getClass(), this.getAccessMethodName(), String.class);
   return ReflectionUtils.invokeMethod(method, entity);
 }
 @Override
 @SuppressWarnings("unchecked")
 public IoFuture<ClientConnection> httpClientConnect(
     UndertowClient httpClient, URI uri, XnioWorker worker, OptionMap options) {
   return (IoFuture<ClientConnection>)
       ReflectionUtils.invokeMethod(
           httpClientConnectMethod, httpClient, uri, worker, this.undertowBufferPool, options);
 }
 /** @noinspection unchecked */
 public void setName(String feature) throws ClassNotFoundException {
   String[] features = feature.split("\\.");
   Class<?> clz = Class.forName("no.bekk.bekkopen.cde.feature.Feature$" + features[0]);
   enabled =
       (Enabled)
           ReflectionUtils.invokeMethod(
               findMethod(clz, "valueOf", String.class), null, features[1]);
   System.out.println(enabled.isEnabled());
 }
  /**
   * Set up a {@link StepExecution} as a test context attribute.
   *
   * @param testContext the current test context
   * @throws Exception if there is a problem
   * @see TestExecutionListener#prepareTestInstance(TestContext)
   */
  @Override
  public void prepareTestInstance(TestContext testContext) throws Exception {
    StepExecution stepExecution = getStepExecution(testContext);

    if (stepExecution != null) {
      Method method =
          TestContext.class.getMethod(SET_ATTRIBUTE_METHOD_NAME, String.class, Object.class);
      ReflectionUtils.invokeMethod(method, testContext, STEP_EXECUTION, stepExecution);
    }
  }
  protected Object getParamValue(
      GrailsParameterMap params, String conversionMethodName, String paramName) {
    Method method = PARAMS_METHODS.get(conversionMethodName);
    if (method == null) {
      log.warn("No method found for " + conversionMethodName + " in GrailsParameterMap");
      return null;
    }

    return ReflectionUtils.invokeMethod(method, params, paramName);
  }
  /**
   * @param testContext the current test context
   * @throws Exception if there is a problem
   * @see TestExecutionListener#afterTestMethod(TestContext)
   */
  @Override
  public void afterTestMethod(TestContext testContext) throws Exception {
    Method method = TestContext.class.getMethod(HAS_ATTRIBUTE_METHOD_NAME, String.class);
    Boolean hasAttribute =
        (Boolean) ReflectionUtils.invokeMethod(method, testContext, STEP_EXECUTION);

    if (hasAttribute) {
      StepSynchronizationManager.close();
    }
  }
 /**
  * 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;
   }
 }
 @Override
 public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
   if (source == null) {
     return null;
   }
   Method finder = getFinder(targetType.getType());
   Object id =
       this.conversionService.convert(
           source, sourceType, TypeDescriptor.valueOf(finder.getParameterTypes()[0]));
   return ReflectionUtils.invokeMethod(finder, source, id);
 }
 public String getSessionId() {
   Object session = getExternalContext().getSession(true);
   try {
     // Both HttpSession and PortletSession have a getId() method.
     Method getIdMethod = session.getClass().getMethod("getId", new Class[0]);
     return ReflectionUtils.invokeMethod(getIdMethod, session).toString();
   } catch (NoSuchMethodException ex) {
     throw new IllegalStateException(
         "Session object [" + session + "] does not have a getId() method");
   }
 }
 private Integer getLocalPort(Connector connector) {
   try {
     // Jetty 9 internals are different, but the method name is the same
     return (Integer)
         ReflectionUtils.invokeMethod(
             ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), connector);
   } catch (Exception ex) {
     JettyEmbeddedServletContainer.logger.info(
         "could not determine port ( " + ex.getMessage() + ")");
     return 0;
   }
 }
示例#19
0
  @Override
  protected void run(CitrusJUnit4Runner.CitrusFrameworkMethod frameworkMethod) {
    if (frameworkMethod.getMethod().getAnnotation(CitrusTest.class) != null) {
      init();
      name(frameworkMethod.getTestName());

      testRunner.start();
      ReflectionUtils.invokeMethod(frameworkMethod.getMethod(), this);
      testRunner.stop();
    } else {
      super.run(frameworkMethod);
    }
  }
  /**
   * Created a {@link RequestMappingInfo} from a 'Spring Integration HTTP Inbound Endpoint' {@link
   * RequestMapping}.
   *
   * @see RequestMappingHandlerMapping#getMappingForMethod
   */
  private RequestMappingInfo getMappingForEndpoint(HttpRequestHandlingEndpointSupport endpoint) {
    final RequestMapping requestMapping = endpoint.getRequestMapping();

    if (ObjectUtils.isEmpty(requestMapping.getPathPatterns())) {
      return null;
    }

    org.springframework.web.bind.annotation.RequestMapping requestMappingAnnotation =
        new org.springframework.web.bind.annotation.RequestMapping() {
          @Override
          public String[] value() {
            return requestMapping.getPathPatterns();
          }

          @Override
          public RequestMethod[] method() {
            return requestMapping.getRequestMethods();
          }

          @Override
          public String[] params() {
            return requestMapping.getParams();
          }

          @Override
          public String[] headers() {
            return requestMapping.getHeaders();
          }

          @Override
          public String[] consumes() {
            return requestMapping.getConsumes();
          }

          @Override
          public String[] produces() {
            return requestMapping.getProduces();
          }

          @Override
          public Class<? extends Annotation> annotationType() {
            return org.springframework.web.bind.annotation.RequestMapping.class;
          }
        };

    Object[] createRequestMappingInfoParams =
        new Object[] {requestMappingAnnotation, this.getCustomTypeCondition(endpoint.getClass())};
    return (RequestMappingInfo)
        ReflectionUtils.invokeMethod(
            CREATE_REQUEST_MAPPING_INFO_METHOD, this, createRequestMappingInfoParams);
  }
  private String getValue(Annotation[] annotations, Class<? extends Annotation> annotationClass) {
    for (Annotation annotation : annotations) {
      if (annotationClass.isInstance(annotation)) {
        Method valueMethod = ReflectionUtils.findMethod(annotationClass, "value");
        if (valueMethod != null) {
          return (String) ReflectionUtils.invokeMethod(valueMethod, annotation);
        } else {
          return null;
        }
      }
    }

    return null;
  }
 /**
  * utility method that generically returns a criterion using methods in Restrictions
  *
  * @param constraintName - the criteria
  */
 protected Criterion callRestrictionsMethod(
     String constraintName, Class<?>[] paramTypes, Object[] params) {
   final Method restrictionsMethod =
       ReflectionUtils.findMethod(Restrictions.class, constraintName, paramTypes);
   Assert.notNull(
       restrictionsMethod,
       "Could not find method: "
           + constraintName
           + " in class Restrictions for parameters: "
           + ArrayUtils.toString(params)
           + " with types: "
           + ArrayUtils.toString(paramTypes));
   return (Criterion) ReflectionUtils.invokeMethod(restrictionsMethod, null, params);
 }
 @Override
 protected boolean isEligibleForOverriding(String className) {
   if (isExcluded(className) || ContextTypeMatchClassLoader.this.isExcluded(className)) {
     return false;
   }
   ReflectionUtils.makeAccessible(findLoadedClassMethod);
   ClassLoader parent = getParent();
   while (parent != null) {
     if (ReflectionUtils.invokeMethod(findLoadedClassMethod, parent, className) != null) {
       return false;
     }
     parent = parent.getParent();
   }
   return true;
 }
 @Override
 public void httpClientConnect(
     UndertowClient httpClient,
     ClientCallback<ClientConnection> listener,
     URI uri,
     XnioWorker worker,
     OptionMap options) {
   ReflectionUtils.invokeMethod(
       httpClientConnectCallbackMethod,
       httpClient,
       listener,
       uri,
       worker,
       this.undertowBufferPool,
       options);
 }
 /**
  * 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);
     if (method == null) {
       // annotations like @Inject and @Value don't have a method (attribute) named "required"
       // -> default to required status
       return true;
     }
     return (this.requiredParameterValue
         == (Boolean) ReflectionUtils.invokeMethod(method, annotation));
   } catch (Exception ex) {
     // an exception was thrown during reflective invocation of the required attribute
     // -> default to required status
     return true;
   }
 }
 @Override
 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) {
   if (getControllerMethod.equals(method)) {
     return this.controllerMethod;
   } else if (getArgumentValues.equals(method)) {
     return this.argumentValues;
   } else if (ReflectionUtils.isObjectMethod(method)) {
     return ReflectionUtils.invokeMethod(method, obj, args);
   } else {
     this.controllerMethod = method;
     this.argumentValues = args;
     Class<?> returnType = method.getReturnType();
     return (void.class.equals(returnType)
         ? null
         : returnType.cast(initProxy(returnType, this)));
   }
 }
 private void setFeatureConfiguration(HtmlCompressor compressor) {
   for (Entry<String, Boolean> entrySet : props.getFeatures().entrySet()) {
     Method method = null;
     String capitalizedKey = StringUtils.capitalize(entrySet.getKey());
     String methodname = "set" + capitalizedKey;
     try {
       method = compressor.getClass().getMethod(methodname, boolean.class);
       method.setAccessible(true);
       ReflectionUtils.invokeMethod(method, compressor, entrySet.getValue());
     } catch (Exception e) {
       logger.warn(
           "failed to invoke method: {} with value {}. Exception: {}",
           methodname,
           entrySet.getValue(),
           e.getMessage());
     }
   }
 }
 @Test
 public void sendToAnnotationFoundOnProxy() {
   ConfigurableApplicationContext context =
       new AnnotationConfigApplicationContext(
           Config.class, ProxyConfig.class, ProxyTestBean.class);
   try {
     JmsListenerContainerTestFactory factory =
         context.getBean(JmsListenerContainerTestFactory.class);
     assertEquals(
         "one container should have been registered", 1, factory.getListenerContainers().size());
     JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint();
     Method m = ReflectionUtils.findMethod(endpoint.getClass(), "getDefaultResponseDestination");
     ReflectionUtils.makeAccessible(m);
     Object destination = ReflectionUtils.invokeMethod(m, endpoint);
     assertEquals("SendTo annotation not found on proxy", "foobar", destination);
   } finally {
     context.close();
   }
 }
  protected Serializable getIdValue(final Object domainObject) {
    final Class<?> clazz = domainObject.getClass();
    // 直接用getId
    try {
      final AclManaged aclManaged = AnnotationUtils.findAnnotation(clazz, AclManaged.class);
      final Method getIdMethod = clazz.getMethod(aclManaged.getIdMethodName());
      if (getIdMethod != null) {
        final Object id = ReflectionUtils.invokeMethod(getIdMethod, domainObject);
        if (id == null) {
          logger.warn("此对象id为空:" + domainObject);
          return null;
        }
        if (!(id instanceof Serializable)) {
          logger.warn("此对象id不能序列化:" + domainObject + " ,id:" + id); // 来到这里就扯淡了吧?
          return null;
        }
        return (Serializable) id;
      }
    } catch (final NoSuchMethodException e) {
      // 没有getId方法就不用它呗
    } catch (final SecurityException e) {
      logger.debug(domainObject.getClass().getName() + "getId方法访问不能访问。", e);
    }
    // 没有getId方法

    // 用标注了@Id注解的字段
    final Field[] fields = clazz.getDeclaredFields();

    Serializable idValueStr = concatIdValues(domainObject, fields);
    if (idValueStr == null) {
      idValueStr = concatIdValues(domainObject, ReflectionUtils.getAllDeclaredMethods(clazz));
    }
    if (idValueStr == null) {
      logger.warn(domainObject.getClass().getName() + "没有id字段。");
      return null;
    }
    if (String.valueOf(idValueStr).isEmpty()) {
      logger.warn("此对象的id字段值都是空字符串:" + domainObject);
      return null;
    }
    return idValueStr;
  }
示例#30
0
  private void setField(T instance, Field field, Object value) {
    String setterMethodName = "set" + capitalize(field.getName());
    Method method =
        findMethod(instance.getClass(), setterMethodName, new Class[] {field.getType()});
    Class<?> type = field.getType();

    Object newInstance = value;
    if (value != null && !value.equals("")) {
      if (Number.class.isAssignableFrom(type)) {
        try {
          Constructor<?> constructor = type.getConstructor(new Class[] {String.class});
          newInstance = constructor.newInstance(value);
        } catch (Exception e) {
          // Swallow the exception could not happen
        }
      }

      invokeMethod(method, instance, new Object[] {newInstance});
    }
  }