Example #1
0
 private final Method findMatchingMethod(final Class<?> classType, final Method matchingMethod) {
   for (final Method method : classType.getMethods()) {
     if (method.getName().equals(matchingMethod.getName())
         && method.getReturnType().equals(matchingMethod.getReturnType())
         && matchParameters(method.getParameters(), matchingMethod.getParameters())) {
       return method;
     }
   }
   return null;
 }
Example #2
0
  PrivilegeNG addController(Class<?> controller_class, Method method) {
    StringBuilder sb = new StringBuilder();
    sb.append(controller_class.getName());
    sb.append(": ");

    if (method.getReturnType().getSimpleName().equalsIgnoreCase("void") == false) {
      sb.append(method.getReturnType().getSimpleName());
      sb.append(" ");
    }
    sb.append(method.getName());
    sb.append("(");
    if (method.getParameterCount() > 0) {
      Parameter[] params = method.getParameters();
      for (int pos = 0; pos < params.length; pos++) {
        sb.append(params[pos].getType().getSimpleName());
        if (pos + 1 < params.length) {
          sb.append(", ");
        }
      }
    }
    sb.append(")");

    associated_controllers.add(sb.toString());
    return this;
  }
 private List<Method> GetMethods(java.lang.reflect.Method[] methods) {
   List<Method> list = new ArrayList<>();
   for (java.lang.reflect.Method mthd : methods) {
     String visibility = this.GetVisibility(mthd.getModifiers());
     boolean isStatic = this.GetIsStatic(mthd.getModifiers());
     boolean isfinal = this.GetIsFinal(mthd.getModifiers());
     String outputType = mthd.getGenericReturnType().toString();
     List<InputParameter> inputParameters = this.GetInputParameters(mthd.getParameters());
     List<String> annotations = this.GetAnnotations(mthd.getAnnotations());
     String name = mthd.getName();
     if (name.contains("_")) continue;
     boolean isThrowExceptions = false;
     if (mthd.getExceptionTypes().length > 0) {
       isThrowExceptions = true;
     }
     Method method =
         ModelFactory.GetMethodWithValue(
             outputType,
             name,
             visibility,
             isfinal,
             isStatic,
             isThrowExceptions,
             inputParameters,
             annotations,
             new ArrayList<>());
     list.add(method);
   }
   return list;
 }
  private UriComponents applyContributers(
      UriComponentsBuilder builder,
      Method method,
      Object[] argumentValues,
      Map<String, Object> uriVars) {

    if (this.contributors.isEmpty()) {
      return builder.buildAndExpand(uriVars);
    }

    int paramCount = method.getParameters().length;
    int argCount = argumentValues.length;

    Assert.isTrue(
        paramCount == argCount,
        "Number of method parameters "
            + paramCount
            + " does not match number of argument values "
            + argCount);

    for (int i = 0; i < paramCount; i++) {
      MethodParameter param = new MethodParameter(method, i);
      param.initParameterNameDiscovery(parameterNameDiscoverer);
      for (UriComponentsContributor c : this.contributors) {
        if (c.supportsParameter(param)) {
          c.contributeMethodArgument(
              param, argumentValues[i], builder, uriVars, this.conversionService);
          break;
        }
      }
    }

    return builder.buildAndExpand(uriVars);
  }
  public static void main(String[] args)
      throws ExecutionException, InterruptedException, InvocationTargetException,
          IllegalAccessException {
    for (String arg : args) {
      if (arg.startsWith("fan=")) System.setProperty("cassandra.btree.fanfactor", arg.substring(4));
      else if (arg.startsWith("min=")) minTreeSize = Integer.parseInt(arg.substring(4));
      else if (arg.startsWith("max=")) maxTreeSize = Integer.parseInt(arg.substring(4));
      else if (arg.startsWith("count=")) perThreadTrees = Integer.parseInt(arg.substring(6));
      else exit();
    }

    List<Method> methods = new ArrayList<>();
    for (Method m : LongBTreeTest.class.getDeclaredMethods()) {
      if (m.getParameters().length > 0) continue;
      for (Annotation annotation : m.getAnnotations())
        if (annotation.annotationType() == Test.class) methods.add(m);
    }

    LongBTreeTest test = new LongBTreeTest();
    Collections.sort(methods, (a, b) -> a.getName().compareTo(b.getName()));
    log(Lists.transform(methods, (m) -> m.getName()).toString());
    for (Method m : methods) {
      log(m.getName());
      m.invoke(test);
    }
    log("success");
  }
  /**
   * Extracts parameters from a method call and attaches these with the comments extracted from the
   * javadoc
   *
   * @param apiAction The Verb of the action containing these parametes
   * @param method The method to inspect
   * @param parameterComments The parameter comments associated with these parameters
   * @return A collection of parameters keyed by name
   */
  protected Map<String, RamlQueryParameter> extractQueryParameters(
      RamlActionType apiAction, Method method, Map<String, String> parameterComments) {
    // Since POST requests have a body we choose to keep all request data in one place as much as
    // possible
    if (apiAction.equals(RamlActionType.POST) || method.getParameterCount() == 0) {
      return Collections.emptyMap();
    }
    Map<String, RamlQueryParameter> queryParams = new LinkedHashMap<>();

    for (Parameter param : method.getParameters()) {
      if (isQueryParameter(
          param)) { // Lets skip resourceIds since these are going to be going in the URL
        RamlParamType simpleType = SchemaHelper.mapSimpleType(param.getType());

        if (simpleType == null) {
          queryParams.putAll(
              SchemaHelper.convertClassToQueryParameters(
                  param, javaDocs.getJavaDoc(param.getType())));
        } else {
          // Check if we have comments
          String paramComment = parameterComments.get(param.getName());
          queryParams.putAll(SchemaHelper.convertParameterToQueryParameter(param, paramComment));
        }
      }
    }
    return queryParams;
  }
  @RuntimeType
  public static Object intercept(
      @Origin Method method, @AllArguments Object[] arguments, @SuperCall Callable superCall) {

    val declaringClass = method.getDeclaringClass();

    val parameters = method.getParameters();

    val keyArguments =
        IntStream.range(0, parameters.length)
            .boxed()
            .map(i -> Argument.builder().type(parameters[i].getType()).value(arguments[i]).build())
            .collect(Collectors.toList());

    val cacheKey =
        CacheKey.builder().bucketName(declaringClass.getName()).arguments(keyArguments).build();

    return cache.computeIfAbsent(
        cacheKey,
        k -> {
          try {
            return superCall.call();
          } catch (Exception e) {
            return null;
          }
        });
  }
Example #8
0
 public static int parseUid(Method m, Object[] args) {
   Parameter[] pas = m.getParameters();
   for (int i = 0; i < pas.length; i++) {
     if (pas[i].isAnnotationPresent(Uid.class)) {
       return (int) args[i];
     }
   }
   return -1;
 }
Example #9
0
  private static JInvocation generateInvocation(Method method) {
    JInvocation generatedInvocation = JExpr.invoke(JExpr.invoke("getWrapped"), method.getName());

    for (Parameter parameter : method.getParameters()) {
      generatedInvocation.arg(JExpr.ref(parameter.getName()));
    }

    return generatedInvocation;
  }
Example #10
0
 public static boolean hasFormTypes(Method method) {
   final List<java.lang.reflect.Parameter> params = Arrays.asList(method.getParameters());
   for (java.lang.reflect.Parameter param : params) {
     Class<?> type = param.getType();
     if (!formTypes.containsKey(type)) {
       return false;
     }
   }
   return true;
 }
  /**
   * @param method the method associated to the element
   * @param index the method parameter index
   * @param type the method parameter type
   * @return the associated {@link FilterElementParameterDescriptor}
   */
  private FilterElementParameterDescriptor<?> createFilterElementParameter(
      Method method, int index, Type type) {
    // @Name
    List<Name> nameAnnotations =
        ReflectionMethodUtils.getMethodParameterAnnotations(method, index, Name.class, true);

    String name;
    if (!nameAnnotations.isEmpty()) {
      name = nameAnnotations.get(0).value();
    } else {
      // Fallback on reflection to get the parameter name
      Parameter parameter = method.getParameters()[index];
      name = parameter.isNamePresent() ? method.getParameters()[index].getName() : null;
    }

    // @Default
    List<Default> defaultAnnotations =
        ReflectionMethodUtils.getMethodParameterAnnotations(method, index, Default.class, true);

    Object defaultValue;
    if (!defaultAnnotations.isEmpty()) {
      defaultValue = defaultAnnotations.get(0).value();

      if (defaultValue != null) {
        try {
          defaultValue = this.converter.convert(type, defaultValue);
        } catch (ConversionException e) {
          // TODO: remove that hack when String -> Map support is added to xwiki-properties
          if (ReflectionUtils.getTypeClass(type) == Map.class
              && ((String) defaultValue).isEmpty()) {
            defaultValue = Collections.EMPTY_MAP;
          } else {
            throw e;
          }
        }
      }
    } else {
      defaultValue = null;
    }

    return new FilterElementParameterDescriptor<Object>(index, name, type, defaultValue);
  }
  @Test
  public void findingAnnotationsRecursively() {
    Method method = findMethod(this.getClass(), "withMarker", String.class);

    List<Annotation> annotations = allAnnotations(method.getParameters()[0]);

    assertEquals(4, annotations.size());
    assertEquals(X.class, annotations.get(0).annotationType());
    assertEquals(Y.class, annotations.get(1).annotationType());
    assertEquals(Z.class, annotations.get(2).annotationType());
    assertEquals(W.class, annotations.get(3).annotationType());
  }
 @Override
 public String[] getParameterNames(Method method) {
   Parameter[] parameters = method.getParameters();
   String[] parameterNames = new String[parameters.length];
   for (int i = 0; i < parameters.length; i++) {
     Parameter param = parameters[i];
     if (!param.isNamePresent()) {
       return null;
     }
     parameterNames[i] = param.getName();
   }
   return parameterNames;
 }
Example #14
0
  @Override
  public <E> DynamicType.Builder<E> processMethod(
      final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) {
    final java.lang.reflect.Parameter[] arguments = method.getParameters();

    if (ReflectionUtility.isGetMethod(method))
      if (arguments == null || arguments.length == 0)
        return this.getNode(builder, method, annotation);
      else
        throw new IllegalStateException(
            method.getName() + " was annotated with @OutVertex but had arguments.");
    else
      throw new IllegalStateException(
          method.getName() + " was annotated with @OutVertex but did not begin with: get");
  }
Example #15
0
  public static void main(String[] args) throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();

    Class template = AbstractBaseWrapper.class;

    String packageName = template.getPackage().getName();

    String className = template.getSimpleName().replace("Abstract", "") + "Impl";
    JPackage generatedPackage = codeModel._package(packageName);

    JDefinedClass generatedClass = generatedPackage._class(JMod.FINAL, className); // Creates
    // a
    // new
    // class
    generatedClass._extends(template);

    for (Method method : template.getMethods()) {

      if (Modifier.isAbstract(method.getModifiers())) {
        System.out.println(
            "Found abstract method "
                + Modifier.toString(method.getModifiers())
                + " "
                + method.getName());

        JMethod generatedMethod =
            generatedClass.method(JMod.PUBLIC, method.getReturnType(), method.getName());

        for (Parameter parameter : method.getParameters()) {
          generatedMethod.param(parameter.getModifiers(), parameter.getType(), parameter.getName());
        }

        if (method.getReturnType().equals(Void.TYPE)) {
          generatedMethod.body().add(generateInvocation(method));
        } else {

          generatedMethod.body()._return(generateInvocation(method));
        }
      }
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    codeModel.build(new SingleStreamCodeWriter(out));

    System.out.println(out);
  }
Example #16
0
  public static void main(String[] args) throws ClassNotFoundException {
    // Получение объекта типа Class
    People people = new People();
    Class myClass = people.getClass();
    System.out.println("myClass = " + myClass);
    // Если у нас есть класс, для которого в момент компиляции известен тип, то получить экземпляр
    // класса ещё проще.
    Class myClass1 = People.class;
    System.out.println("myClass1 = " + myClass1);
    // Если имя класса не известно в момент компиляции, но становится известным во время выполнения
    // программы,
    // можно использовать метод forName(), чтобы получить объект Class.
    Class c = Class.forName("DZ_14.reflection_Test.Razbor.People");
    System.out.println("c = " + c);
    // Получение пакета
    Package p = People.class.getPackage();
    System.out.println("package " + p.getName() + ";");
    // Выводим интерфейсы, которые реализует класс
    Class[] interfaces = myClass.getInterfaces();
    for (int i = 0, size = interfaces.length; i < size; i++) {
      System.out.print(i == 0 ? "implements " : ", ");
      System.out.print(interfaces[i].getSimpleName());
    }
    System.out.println(" {");
    // Выводим поля класса
    Field[] fields = People.class.getDeclaredFields();
    for (Field field : fields) {
      System.out.println(
          "\t" + field.getModifiers() + field.getType() + " " + field.getName() + ";");
    }
    // Выводим методы, аннотации класса
    Method[] methods = People.class.getDeclaredMethods();
    for (Method m : methods) {
      Annotation[] annotations = m.getAnnotations();
      System.out.print("\t");
      for (Annotation a : annotations)
        System.out.print("@" + a.annotationType().getSimpleName() + " ");
      System.out.println();

      System.out.print(
          "\t" + m.getModifiers() + getType(m.getReturnType()) + " " + m.getName() + "(");
      System.out.print(m.getParameters());
      System.out.println(") { }");
    }
  }
 private void addMethodParameters(JaxrsResourceMethodDescription jaxrsRes, Method method) {
   for (Parameter param : method.getParameters()) {
     ParamInfo paramInfo = new ParamInfo();
     paramInfo.cls = param.getType();
     paramInfo.defaultValue = null;
     paramInfo.name = null;
     paramInfo.type = null;
     Annotation annotation;
     if ((annotation = param.getAnnotation(PathParam.class)) != null) {
       PathParam pathParam = (PathParam) annotation;
       paramInfo.name = pathParam.value();
       paramInfo.type = "@" + PathParam.class.getSimpleName();
     } else if ((annotation = param.getAnnotation(QueryParam.class)) != null) {
       QueryParam queryParam = (QueryParam) annotation;
       paramInfo.name = queryParam.value();
       paramInfo.type = "@" + QueryParam.class.getSimpleName();
     } else if ((annotation = param.getAnnotation(HeaderParam.class)) != null) {
       HeaderParam headerParam = (HeaderParam) annotation;
       paramInfo.name = headerParam.value();
       paramInfo.type = "@" + HeaderParam.class.getSimpleName();
     } else if ((annotation = param.getAnnotation(CookieParam.class)) != null) {
       CookieParam cookieParam = (CookieParam) annotation;
       paramInfo.name = cookieParam.value();
       paramInfo.type = "@" + CookieParam.class.getSimpleName();
     } else if ((annotation = param.getAnnotation(MatrixParam.class)) != null) {
       MatrixParam matrixParam = (MatrixParam) annotation;
       paramInfo.name = matrixParam.value();
       paramInfo.type = "@" + MatrixParam.class.getSimpleName();
     } else if ((annotation = param.getAnnotation(FormParam.class)) != null) {
       FormParam formParam = (FormParam) annotation;
       paramInfo.name = formParam.value();
       paramInfo.type = "@" + FormParam.class.getSimpleName();
     }
     if (paramInfo.name == null) {
       paramInfo.name = param.getName();
     }
     if ((annotation = param.getAnnotation(DefaultValue.class)) != null) {
       DefaultValue defaultValue = (DefaultValue) annotation;
       paramInfo.defaultValue = defaultValue.value();
     }
     jaxrsRes.parameters.add(paramInfo);
   }
 }
Example #18
0
  /** Execute the action */
  @Override
  public void run() {

    try {
      // get the second parameter
      Class<?> parameterType = actionMethod.getParameters()[1].getClass();
      ObjectMapper mapper = new ObjectMapper();
      Object parameterData = mapper.treeToValue(parameter, parameterType);

      // Class<?> returnType = actionMethod.getReturnType();
      // Object returnData = null;

      // returnData =
      actionMethod.invoke(targetObject, identity, parameterData);

    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }
  @Before("ClassInfoCheck()")
  public Object ClassInfoCheckAround(JoinPoint joinPoint) throws Throwable {
    System.out.println("ClassInfoCheckAround");
    Object obj = joinPoint.getTarget();
    System.out.println(obj.getClass().toString());
    // Todo : 리플렉션을 이용해서 어노테이션의 값을 체크
    Class[] args = new Class[1];
    args[0] = SearchVO.class;
    // System.out.println(obj.getClass().getMethod("selectPlayerList",
    // args).getAnnotation(ClassInfo.class).created() + " No For");

    // 어노테이션을 사용한 객체와 메소드
    for (Method method : obj.getClass().getMethods()) {
      Parameter[] parameters = method.getParameters();
      method.getDefaultValue();
      for (Parameter parameter : parameters) {
        // if(!parameter.isNamePresent()) {
        //	throw new IllegalArgumentException("Parameter names are not present!");
        // }
        // System.out.println(method.getName() + " : " + parameter.getParameterizedType());
      }

      Type[] types = method.getGenericParameterTypes();
      for (Type type : types) {
        // System.out.println(method.getName() + " " + type.getClass());
      }

      ClassInfo classInfo = (ClassInfo) method.getAnnotation(ClassInfo.class);
      if (classInfo != null && classInfo.created() != null) {
        // System.out.println(classInfo.created() + " For");
      }
    }

    // 사용된 어노테이션
    Class<?> object = joinPoint.getTarget().getClass();
    for (Method method : object.getDeclaredMethods()) {
      if (method.isAnnotationPresent(RequestMapping.class)) {
        Annotation annotation = method.getAnnotation(RequestMapping.class);
        System.out.println(annotation);
      }
    }
    return obj;
  }
Example #20
0
 /**
  * Invokes the specified method on the specified object with the specified parameter.
  *
  * @param object the object to invoke the method on
  * @param setter the method to invoke
  * @param parameter the parameter to pass to the method
  * @throws ReflectiveOperationException if there is any reflection error
  * @throws IllegalArgumentException if the specified parameter is not valid
  */
 @SuppressWarnings("unchecked")
 private static <E extends Enum<E>> void invoke(Object object, Method setter, Object parameter)
     throws ReflectiveOperationException, IllegalArgumentException {
   Class<?> paramType = setter.getParameters()[0].getType();
   if (String.class.equals(paramType)) {
     setter.invoke(object, parameter.toString());
   } else if (boolean.class.equals(paramType)) {
     setter.invoke(object, Boolean.valueOf(parameter.toString()));
   } else if (int.class.equals(paramType)) {
     setter.invoke(object, Integer.parseInt(parameter.toString()));
   } else if (double.class.equals(paramType)) {
     setter.invoke(object, Double.parseDouble(parameter.toString()));
   } else if (Character.class.equals(paramType)) {
     setter.invoke(object, parameter.toString().charAt(0));
   } else if (paramType.isEnum()) {
     Class<E> e = (Class<E>) paramType;
     setter.invoke(object, Enum.valueOf(e, parameter.toString()));
   } else {
     throw new RuntimeException("Unknown setter type: " + paramType);
   }
 }
  public Object routeRequest(String http_method, String url, Map<String, String> args)
      throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    /* find matching method */
    final String entry = http_method + ":" + url;
    Method method = routing.get(entry);
    if (method == null) {
      throw new IllegalAccessException("No such route exposed");
    }

    /* map named arguments to positional */
    Parameter parameters[] = method.getParameters();
    Object mapped_args[] = new Object[parameters.length];
    for (int i = 0; i < parameters.length; ++i) {
      final String argname = parameters[i].getName();
      if (!args.containsKey(argname)) {
        throw new IllegalArgumentException("Missing argument " + argname);
      }
      mapped_args[i] = args.get(argname);
    }

    /* invoke method with arguments */
    return method.invoke(this, mapped_args);
  }
 private Parameter findParameterOfMethod(String methodName, Class<?>... parameterTypes) {
   Method method = ReflectionUtils.findMethod(Sample.class, methodName, parameterTypes).get();
   return method.getParameters()[0];
 }