Java Code Examples for java.lang.reflect.Method#toString()

The following examples show how to use java.lang.reflect.Method#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OperationLogAop.java    From common-mvc with MIT License 6 votes vote down vote up
@Around(value = "OperationLog()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Object res;
    res = point.proceed();

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    User user = (User) request.getSession().getAttribute("user");

    Method targetMethod = ((MethodSignature)(point.getSignature())).getMethod();
    OperationLog annotation = targetMethod.getAnnotation(OperationLog.class);
    String signature, businessName, userName, data;
    Integer userId = user.getId();
    signature = targetMethod.toString();
    businessName = annotation.businessName();
    userName = user.getUsername();
    data = JSONUtils.obj2json(point.getArgs());

    this.operationLogService.insertLog(signature, businessName, userId, userName, data);
    return  res;
}
 
Example 2
Source File: ContainerElement.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if(method.getDeclaringClass()==TypedXmlWriter.class || method.getDeclaringClass()==Object.class) {
        // forward to myself
        try {
            return method.invoke(this,args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    XmlAttribute xa = method.getAnnotation(XmlAttribute.class);
    XmlValue xv = method.getAnnotation(XmlValue.class);
    XmlElement xe = method.getAnnotation(XmlElement.class);


    if(xa!=null) {
        if(xv!=null || xe!=null)
            throw new IllegalAnnotationException(method.toString());

        addAttribute(xa,method,args);
        return proxy; // allow method chaining
    }
    if(xv!=null) {
        if(xe!=null)
            throw new IllegalAnnotationException(method.toString());

        _pcdata(args);
        return proxy; // allow method chaining
    }

    return addElement(xe,method,args);
}
 
Example 3
Source File: MemberName.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Method m, boolean wantSpecial) {
    m.getClass();  // NPE check
    // fill in vmtarget, vmindex while we have m in hand:
    MethodHandleNatives.init(this, m);
    if (clazz == null) {  // MHN.init failed
        if (m.getDeclaringClass() == MethodHandle.class &&
            isMethodHandleInvokeName(m.getName())) {
            // The JVM did not reify this signature-polymorphic instance.
            // Need a special case here.
            // See comments on MethodHandleNatives.linkMethod.
            MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
            int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
            init(MethodHandle.class, m.getName(), type, flags);
            if (isMethodHandleInvoke())
                return;
        }
        throw new LinkageError(m.toString());
    }
    assert(isResolved() && this.clazz != null);
    this.name = m.getName();
    if (this.type == null)
        this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
    if (wantSpecial) {
        if (isAbstract())
            throw new AbstractMethodError(this.toString());
        if (getReferenceKind() == REF_invokeVirtual)
            changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        else if (getReferenceKind() == REF_invokeInterface)
            // invokeSpecial on a default method
            changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
    }
}
 
Example 4
Source File: SqlScriptsTestExecutionListener.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]", prefixedResourcePath,
				elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: "
				+ "%s does not exist. Either declare statements or scripts via @Sql or make the "
				+ "default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 5
Source File: MemberName.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Method m, boolean wantSpecial) {
    m.getClass();  // NPE check
    // fill in vmtarget, vmindex while we have m in hand:
    MethodHandleNatives.init(this, m);
    if (clazz == null) {  // MHN.init failed
        if (m.getDeclaringClass() == MethodHandle.class &&
            isMethodHandleInvokeName(m.getName())) {
            // The JVM did not reify this signature-polymorphic instance.
            // Need a special case here.
            // See comments on MethodHandleNatives.linkMethod.
            MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
            int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
            init(MethodHandle.class, m.getName(), type, flags);
            if (isMethodHandleInvoke())
                return;
        }
        throw new LinkageError(m.toString());
    }
    assert(isResolved() && this.clazz != null);
    this.name = m.getName();
    if (this.type == null)
        this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
    if (wantSpecial) {
        if (isAbstract())
            throw new AbstractMethodError(this.toString());
        if (getReferenceKind() == REF_invokeVirtual)
            changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        else if (getReferenceKind() == REF_invokeInterface)
            // invokeSpecial on a default method
            changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
    }
}
 
Example 6
Source File: MemberName.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Method m, boolean wantSpecial) {
    m.getClass();  // NPE check
    // fill in vmtarget, vmindex while we have m in hand:
    MethodHandleNatives.init(this, m);
    if (clazz == null) {  // MHN.init failed
        if (m.getDeclaringClass() == MethodHandle.class &&
            isMethodHandleInvokeName(m.getName())) {
            // The JVM did not reify this signature-polymorphic instance.
            // Need a special case here.
            // See comments on MethodHandleNatives.linkMethod.
            MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
            int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
            init(MethodHandle.class, m.getName(), type, flags);
            if (isMethodHandleInvoke())
                return;
        }
        throw new LinkageError(m.toString());
    }
    assert(isResolved() && this.clazz != null);
    this.name = m.getName();
    if (this.type == null)
        this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
    if (wantSpecial) {
        if (isAbstract())
            throw new AbstractMethodError(this.toString());
        if (getReferenceKind() == REF_invokeVirtual)
            changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        else if (getReferenceKind() == REF_invokeInterface)
            // invokeSpecial on a default method
            changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
    }
}
 
Example 7
Source File: AutomaticLazyLoadingTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
/**
 * Load an element with default configuration and call toString.
 * Expect that the toString triggers lazy loading which loads the nested Element
 * is available after closing the session.
 */
private void testScenario(String aConfiguration, boolean anExpectingAnException, Method aMethodToCall)
throws Exception {
  openSession(aConfiguration);

  Element myElement = selectElement();

  String myMethodCallDescription;
  
  if (aMethodToCall != null) {
    Object[] myArguments = new Object[aMethodToCall.getParameterTypes().length];
    
    aMethodToCall.invoke(myElement, myArguments);
    
    myMethodCallDescription = aMethodToCall.toString();
  } else {
    myMethodCallDescription = "not called a method";
  }
  
  myElement = disableLazyLoaders(myElement);
  
  closeSession();
  
  try {
    Assert.assertEquals("parent", myElement.getElement().getValue());
    
      if (anExpectingAnException) {
        Assert.fail("Excpected an exception, since " + myMethodCallDescription + " should not trigger lazy loading");
      }
  } catch(Exception anException) {
      if (!anExpectingAnException) {
        Assert.fail("Did not expect an exception, because " + myMethodCallDescription + " should trigger lazy loading");
      }
  }
}
 
Example 8
Source File: MemberName.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Method m, boolean wantSpecial) {
    m.getClass();  // NPE check
    // fill in vmtarget, vmindex while we have m in hand:
    MethodHandleNatives.init(this, m);
    if (clazz == null) {  // MHN.init failed
        if (m.getDeclaringClass() == MethodHandle.class &&
            isMethodHandleInvokeName(m.getName())) {
            // The JVM did not reify this signature-polymorphic instance.
            // Need a special case here.
            // See comments on MethodHandleNatives.linkMethod.
            MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
            int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
            init(MethodHandle.class, m.getName(), type, flags);
            if (isMethodHandleInvoke())
                return;
        }
        throw new LinkageError(m.toString());
    }
    assert(isResolved() && this.clazz != null);
    this.name = m.getName();
    if (this.type == null)
        this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
    if (wantSpecial) {
        if (isAbstract())
            throw new AbstractMethodError(this.toString());
        if (getReferenceKind() == REF_invokeVirtual)
            changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        else if (getReferenceKind() == REF_invokeInterface)
            // invokeSpecial on a default method
            changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
    }
}
 
Example 9
Source File: ReflectionNavigator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public Location getMethodLocation(final Method method) {
    return new Location() {

        @Override
        public String toString() {
            return method.toString();
        }
    };
}
 
Example 10
Source File: ShellConsole.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public Object invoke(Object proxy, Method method, Object[] args) {
    if (method.equals(this.completeMethod)) {
        int result = complete((String)args[0], ((Integer) args[1]).intValue(),
                (List<String>) args[2]);
        return Integer.valueOf(result);
    }
    throw new NoSuchMethodError(method.toString());
}
 
Example 11
Source File: TypedAnnotationWriter.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    if(method.getDeclaringClass()==JAnnotationWriter.class) {
        try {
            return method.invoke(this,args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    String name = method.getName();
    Object arg=null;
    if(args!=null && args.length>0)
        arg = args[0];

    // check how it's defined on the annotation
    Method m = annotation.getDeclaredMethod(name);
    Class<?> rt = m.getReturnType();

    // array value
    if(rt.isArray()) {
        return addArrayValue(proxy,name,rt.getComponentType(),method.getReturnType(),arg);
    }

    // sub annotation
    if(Annotation.class.isAssignableFrom(rt)) {
        Class<? extends Annotation> r = (Class<? extends Annotation>)rt;
        return new TypedAnnotationWriter(
            r,method.getReturnType(),use.annotationParam(name,r)).createProxy();
    }

    // scalar value

    if(arg instanceof JType) {
        JType targ = (JType) arg;
        checkType(Class.class,rt);
        if(m.getDefaultValue()!=null) {
            // check the default
            if(targ.equals(targ.owner().ref((Class)m.getDefaultValue())))
                return proxy;   // defaulted
        }
        use.param(name,targ);
        return proxy;
    }

    // other Java built-in types
    checkType(arg.getClass(),rt);
    if(m.getDefaultValue()!=null && m.getDefaultValue().equals(arg))
        // defaulted. no need to write out.
        return proxy;

    if(arg instanceof String) {
        use.param(name,(String)arg);
        return proxy;
    }
    if(arg instanceof Boolean) {
        use.param(name,(Boolean)arg);
        return proxy;
    }
    if(arg instanceof Integer) {
        use.param(name,(Integer)arg);
        return proxy;
    }
    if(arg instanceof Class) {
        use.param(name,(Class)arg);
        return proxy;
    }
    if(arg instanceof Enum) {
        use.param(name,(Enum)arg);
        return proxy;
    }

    throw new IllegalArgumentException("Unable to handle this method call "+method.toString());
}
 
Example 12
Source File: CTestStructure.java    From lin-check with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Constructs {@link CTestStructure} for the specified test class.
 */
public static CTestStructure getFromTestClass(Class<?> testClass) {
    // Read named parameter paramgen (declared for class)
    Map<String, ParameterGenerator<?>> namedGens = new HashMap<>();
    for (Param paramAnn : testClass.getAnnotationsByType(Param.class)) {
        if (paramAnn.name().isEmpty()) {
            throw new IllegalArgumentException("@Param name in class declaration cannot be empty");
        }
        namedGens.put(paramAnn.name(), createGenerator(paramAnn));
    }
    // Read group configurations
    Map<String, OperationGroup> groupConfigs = new HashMap<>();
    for (OpGroupConfig opGroupConfigAnn: testClass.getAnnotationsByType(OpGroupConfig.class)) {
        groupConfigs.put(opGroupConfigAnn.name(), new OperationGroup(opGroupConfigAnn.name(),
            opGroupConfigAnn.nonParallel()));
    }
    // Create actor paramgen
    List<ActorGenerator> actorGenerators = new ArrayList<>();
    for (Method m : testClass.getDeclaredMethods()) {
        // Operation
        if (m.isAnnotationPresent(Operation.class)) {
            Operation operationAnn = m.getAnnotation(Operation.class);
            // Check that params() in @Operation is empty or has the same size as the method
            if (operationAnn.params().length > 0 && operationAnn.params().length != m.getParameterCount()) {
                throw new IllegalArgumentException("Invalid count of paramgen for " + m.toString()
                    + " method in @Operation");
            }
            // Construct list of parameter paramgen
            final List<ParameterGenerator<?>> gens = new ArrayList<>();
            for (int i = 0; i < m.getParameterCount(); i++) {
                String nameInOperation = operationAnn.params().length > 0 ? operationAnn.params()[i] : null;
                gens.add(getOrCreateGenerator(m, m.getParameters()[i], nameInOperation, namedGens));
            }
            // Get list of handled exceptions if they are presented
            List<Class<? extends Throwable>> handledExceptions = Arrays.asList(operationAnn.handleExceptionsAsResult());
            ActorGenerator actorGenerator = new ActorGenerator(m, gens, handledExceptions, operationAnn.runOnce());
            actorGenerators.add(actorGenerator);
            // Get list of groups and add this operation to specified ones
            String opGroup = operationAnn.group();
            if (!opGroup.isEmpty()) {
                OperationGroup operationGroup = groupConfigs.get(opGroup);
                if (operationGroup == null)
                    throw new IllegalStateException("Operation group " + opGroup + " is not configured");
                operationGroup.actors.add(actorGenerator);
            }
        }
    }
    // Create StressCTest class configuration
    return new CTestStructure(actorGenerators, new ArrayList<>(groupConfigs.values()));
}
 
Example 13
Source File: TestSynchronization.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private static void testMethod(Class<?> aClass, Method m) throws
        Exception {
    /*
     * Construct call with arguments of the correct type. Note that the
     * values are somewhat irrelevant. If the call actually succeeds, it
     * means we aren't synchronized and the test has failed.
     */
    Class<?>[] pTypes = m.getParameterTypes();
    List<Integer> charSequenceArgs = new ArrayList<>();
    Object[] args = new Object[pTypes.length];
    for (int i = 0; i < pTypes.length; i++) {
        // determine the type and create the corresponding actual argument
        Class<?> pType = pTypes[i];
        if (pType.equals(boolean.class)) {
            args[i] = BOOLEAN_VAL;
        } else if (pType.equals(char.class)) {
            args[i] = CHAR_VAL;
        } else if (pType.equals(int.class)) {
            args[i] = INT_VAL;
        } else if (pType.equals(double.class)) {
            args[i] = DOUBLE_VAL;
        } else if (pType.equals(float.class)) {
            args[i] = FLOAT_VAL;
        } else if (pType.equals(long.class)) {
            args[i] = LONG_VAL;
        } else if (pType.equals(Object.class)) {
            args[i] = OBJECT_VAL;
        } else if (pType.equals(StringBuilder.class)) {
            args[i] = STRING_BUILDER_VAL;
        } else if (pType.equals(StringBuffer.class)) {
            args[i] = STRING_BUFFER_VAL;
        } else if (pType.equals(String.class)) {
            args[i] = STRING_VAL;
        } else if (pType.isArray() && pType.getComponentType().equals(char.class)) {
            args[i] = CHAR_ARRAY_VAL;
        } else if (pType.equals(CharSequence.class)) {
            charSequenceArgs.add(new Integer(i));
        } else {
            throw new RuntimeException("Test Failed: not accounting for method call with parameter type of " + pType.getName() + " You must update the test.");
        }
    }
    /*
     * If there are no CharSequence args, we can simply invoke our method
     * and test it
     */
    if (charSequenceArgs.isEmpty()) {
        invokeMethod(aClass, m, args);
    } else {
        /*
         * Iterate through the different CharSequence types and invoke the
         * method for each type.
         */
        if (charSequenceArgs.size() > 1) {
            throw new RuntimeException("Test Failed: the test cannot handle a method with multiple CharSequence arguments.  You must update the test to handle the method "
                    + m.toString());
        }
        for (int j = 0; j < CHAR_SEQUENCE_VAL.length; j++) {
            args[charSequenceArgs.get(0)] = CHAR_SEQUENCE_VAL[j];
            invokeMethod(aClass, m, args);
        }
    }
}
 
Example 14
Source File: TestSynchronization.java    From native-obfuscator with GNU General Public License v3.0 4 votes vote down vote up
private static void testMethod(Class<?> aClass, Method m) throws
        Exception {
    /*
     * Construct call with arguments of the correct type. Note that the
     * values are somewhat irrelevant. If the call actually succeeds, it
     * means we aren't synchronized and the test has failed.
     */
    Class<?>[] pTypes = m.getParameterTypes();
    List<Integer> charSequenceArgs = new ArrayList<>();
    Object[] args = new Object[pTypes.length];
    for (int i = 0; i < pTypes.length; i++) {
        // determine the type and create the corresponding actual argument
        Class<?> pType = pTypes[i];
        if (pType.equals(boolean.class)) {
            args[i] = BOOLEAN_VAL;
        } else if (pType.equals(char.class)) {
            args[i] = CHAR_VAL;
        } else if (pType.equals(int.class)) {
            args[i] = INT_VAL;
        } else if (pType.equals(double.class)) {
            args[i] = DOUBLE_VAL;
        } else if (pType.equals(float.class)) {
            args[i] = FLOAT_VAL;
        } else if (pType.equals(long.class)) {
            args[i] = LONG_VAL;
        } else if (pType.equals(Object.class)) {
            args[i] = OBJECT_VAL;
        } else if (pType.equals(StringBuilder.class)) {
            args[i] = STRING_BUILDER_VAL;
        } else if (pType.equals(StringBuffer.class)) {
            args[i] = STRING_BUFFER_VAL;
        } else if (pType.equals(String.class)) {
            args[i] = STRING_VAL;
        } else if (pType.isArray() && pType.getComponentType().equals(char.class)) {
            args[i] = CHAR_ARRAY_VAL;
        } else if (pType.equals(CharSequence.class)) {
            charSequenceArgs.add(new Integer(i));
        } else {
            throw new RuntimeException("Test Failed: not accounting for method call with parameter type of " + pType.getName() + " You must update the test.");
        }
    }
    /*
     * If there are no CharSequence args, we can simply invoke our method
     * and test it
     */
    if (charSequenceArgs.isEmpty()) {
        invokeMethod(aClass, m, args);
    } else {
        /*
         * Iterate through the different CharSequence types and invoke the
         * method for each type.
         */
        if (charSequenceArgs.size() > 1) {
            throw new RuntimeException("Test Failed: the test cannot handle a method with multiple CharSequence arguments.  You must update the test to handle the method "
                    + m.toString());
        }
        for (int j = 0; j < CHAR_SEQUENCE_VAL.length; j++) {
            args[charSequenceArgs.get(0)] = CHAR_SEQUENCE_VAL[j];
            invokeMethod(aClass, m, args);
        }
    }
}
 
Example 15
Source File: TypedAnnotationWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    if(method.getDeclaringClass()==JAnnotationWriter.class) {
        try {
            return method.invoke(this,args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    String name = method.getName();
    Object arg=null;
    if(args!=null && args.length>0)
        arg = args[0];

    // check how it's defined on the annotation
    Method m = annotation.getDeclaredMethod(name);
    Class<?> rt = m.getReturnType();

    // array value
    if(rt.isArray()) {
        return addArrayValue(proxy,name,rt.getComponentType(),method.getReturnType(),arg);
    }

    // sub annotation
    if(Annotation.class.isAssignableFrom(rt)) {
        Class<? extends Annotation> r = (Class<? extends Annotation>)rt;
        return new TypedAnnotationWriter(
            r,method.getReturnType(),use.annotationParam(name,r)).createProxy();
    }

    // scalar value

    if(arg instanceof JType) {
        JType targ = (JType) arg;
        checkType(Class.class,rt);
        if(m.getDefaultValue()!=null) {
            // check the default
            if(targ.equals(targ.owner().ref((Class)m.getDefaultValue())))
                return proxy;   // defaulted
        }
        use.param(name,targ);
        return proxy;
    }

    // other Java built-in types
    checkType(arg.getClass(),rt);
    if(m.getDefaultValue()!=null && m.getDefaultValue().equals(arg))
        // defaulted. no need to write out.
        return proxy;

    if(arg instanceof String) {
        use.param(name,(String)arg);
        return proxy;
    }
    if(arg instanceof Boolean) {
        use.param(name,(Boolean)arg);
        return proxy;
    }
    if(arg instanceof Integer) {
        use.param(name,(Integer)arg);
        return proxy;
    }
    if(arg instanceof Class) {
        use.param(name,(Class)arg);
        return proxy;
    }
    if(arg instanceof Enum) {
        use.param(name,(Enum)arg);
        return proxy;
    }

    throw new IllegalArgumentException("Unable to handle this method call "+method.toString());
}
 
Example 16
Source File: ActionClassGenerator.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
private String generateActionDefinition( String actionName,
                                         Method actionImplementation,
                                         String transferUnit,
                                         boolean registerAction ) {

    log.info("Generating method implementation for action '" + actionName + "'");

    String[] paramNames = new String[actionImplementation.getParameterTypes().length];
    String[] paramTypes = new String[actionImplementation.getParameterTypes().length];

    Annotation[][] parameterAnnotations = actionImplementation.getParameterAnnotations();
    for (int i = 0; i < parameterAnnotations.length; i++) {
        Class<?> paramType = actionImplementation.getParameterTypes()[i];

        Annotation[] currentParamAnnotations = parameterAnnotations[i];

        Parameter paramAnnotation = null;
        for (int j = 0; j < currentParamAnnotations.length; j++) {
            if (currentParamAnnotations[j] instanceof Parameter) {
                paramAnnotation = (Parameter) currentParamAnnotations[j];
                break;
            }
        }

        if (paramAnnotation == null) {
            throw new BuildException("No @Parameter annotation for one of the parameters of action method "
                                     + actionImplementation.toString());
        }

        paramNames[i] = paramAnnotation.name();

        if (paramType.isArray() && paramType.getComponentType().isEnum()) {
            //array of enums should be represented by array of String in the generated stub
            paramTypes[i] = "String[]";
        } else if (paramType.isEnum()) {
            //enums should be represented by Strings in the generated stub
            paramTypes[i] = "String";
        } else {
            paramTypes[i] = paramType.getSimpleName();
        }
    }

    //parameters and arguments
    if (paramNames.length != paramTypes.length) {
        throw new BuildException("Parameter names count different than parameter types count for action method "
                                 + actionImplementation.toString());
    }

    Annotation deprecatedAnnotation = actionImplementation.getAnnotation(Deprecated.class);
    boolean isDeprecated = (deprecatedAnnotation != null);

    try {
        return new MethodTemplateProcessor(actionImplementation, actionName, paramNames, registerAction,
                                           paramTypes, transferUnit, isDeprecated).processTemplate();
    } catch (IOException ioe) {
        throw new BuildException(ioe);
    }
}
 
Example 17
Source File: TestSynchronization.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void testMethod(Class<?> aClass, Method m) throws
        Exception {
    /*
     * Construct call with arguments of the correct type. Note that the
     * values are somewhat irrelevant. If the call actually succeeds, it
     * means we aren't synchronized and the test has failed.
     */
    Class<?>[] pTypes = m.getParameterTypes();
    List<Integer> charSequenceArgs = new ArrayList<>();
    Object[] args = new Object[pTypes.length];
    for (int i = 0; i < pTypes.length; i++) {
        // determine the type and create the corresponding actual argument
        Class<?> pType = pTypes[i];
        if (pType.equals(boolean.class)) {
            args[i] = BOOLEAN_VAL;
        } else if (pType.equals(char.class)) {
            args[i] = CHAR_VAL;
        } else if (pType.equals(int.class)) {
            args[i] = INT_VAL;
        } else if (pType.equals(double.class)) {
            args[i] = DOUBLE_VAL;
        } else if (pType.equals(float.class)) {
            args[i] = FLOAT_VAL;
        } else if (pType.equals(long.class)) {
            args[i] = LONG_VAL;
        } else if (pType.equals(Object.class)) {
            args[i] = OBJECT_VAL;
        } else if (pType.equals(StringBuilder.class)) {
            args[i] = STRING_BUILDER_VAL;
        } else if (pType.equals(StringBuffer.class)) {
            args[i] = STRING_BUFFER_VAL;
        } else if (pType.equals(String.class)) {
            args[i] = STRING_VAL;
        } else if (pType.isArray() && pType.getComponentType().equals(char.class)) {
            args[i] = CHAR_ARRAY_VAL;
        } else if (pType.equals(CharSequence.class)) {
            charSequenceArgs.add(new Integer(i));
        } else {
            throw new RuntimeException("Test Failed: not accounting for method call with parameter type of " + pType.getName() + " You must update the test.");
        }
    }
    /*
     * If there are no CharSequence args, we can simply invoke our method
     * and test it
     */
    if (charSequenceArgs.isEmpty()) {
        invokeMethod(aClass, m, args);
    } else {
        /*
         * Iterate through the different CharSequence types and invoke the
         * method for each type.
         */
        if (charSequenceArgs.size() > 1) {
            throw new RuntimeException("Test Failed: the test cannot handle a method with multiple CharSequence arguments.  You must update the test to handle the method "
                    + m.toString());
        }
        for (int j = 0; j < CHAR_SEQUENCE_VAL.length; j++) {
            args[charSequenceArgs.get(0)] = CHAR_SEQUENCE_VAL[j];
            invokeMethod(aClass, m, args);
        }
    }
}
 
Example 18
Source File: RetainedStateTestEnvironment.java    From Akatsuki with Apache License 2.0 4 votes vote down vote up
public void executeTestCaseWithFields(Set<? extends TestField> fieldList,
		Predicate<String> methodNamePredicate, FieldFilter accessorTypeFilter,
		Accessor accessor, Function<TestField, Integer> times) {
	Set<TestField> allFields = new HashSet<>(fieldList);

	for (Method method : Bundle.class.getMethods()) {

		// check correct signature and name predicate
		if (!checkMethodIsAccessor(method, accessor)
				|| !methodNamePredicate.test(method.getName())) {
			continue;
		}

		// find methods who's accessor type matches the given fields
		List<TestField> matchingField = allFields.stream()
				.filter(f -> filterTypes(method, accessor, accessorTypeFilter, f))
				.collect(Collectors.toList());

		// no signature match
		if (matchingField.isEmpty()) {
			continue;
		}

		// more than one match, we should have exactly one match
		if (matchingField.size() > 1) {
			throw new AssertionError(method.toString() + " matches multiple field "
					+ fieldList + ", this is ambiguous and should not happen."
					+ environment.printReport());
		}
		final TestField field = matchingField.get(0);
		try {
			if (accessor == Accessor.PUT) {
				method.invoke(verify(mockedBundle, times(times.apply(field))),
						eq(field.name), any(field.clazz));
			} else {
				method.invoke(verify(mockedBundle, times(times.apply(field))),
						eq(field.name));
			}
			allFields.remove(field);

		} catch (Exception e) {
			throw new AssertionError("Invocation of method " + method.getName()
					+ " on mocked object failed." + environment.printReport(), e);
		}
	}
	if (!allFields.isEmpty())
		throw new RuntimeException("While testing for accessor:" + accessor
				+ " some fields are left untested because a suitable accessor cannot be found: "
				+ allFields + environment.printReport());
}
 
Example 19
Source File: CacheKeyGenerator.java    From wallride with Apache License 2.0 4 votes vote down vote up
@Override
public Object generate(Object target, Method method, Object... params) {
	return method.toString() + " [" + StringUtils.arrayToCommaDelimitedString(params) + "]";
}
 
Example 20
Source File: SagaTaskMethodParameterException.java    From choerodon-starters with Apache License 2.0 4 votes vote down vote up
public SagaTaskMethodParameterException(Method method) {
    super("@SagaTask method's parameter can only be one string, method: " + method.toString());
}