Example usage for java.lang Class getMethods

List of usage examples for java.lang Class getMethods

Introduction

In this page you can find the example usage for java.lang Class getMethods.

Prototype

@CallerSensitive
public Method[] getMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Usage

From source file:com.runwaysdk.controller.URLConfigurationManager.java

public void readController(String uri, String controllerClassName, Element el) {
    ControllerMapping controllerMapping = new ControllerMapping(uri, controllerClassName);

    ArrayList<Method> methods = null;
    try {//  w ww. j  a  v  a  2s.c om
        Class<?> clazz = LoaderDecorator.load(controllerClassName);
        Class<?> clazzBase = LoaderDecorator.load(controllerClassName + "Base");
        methods = new ArrayList<Method>(Arrays.asList(clazz.getMethods()));
        Iterator<Method> it = methods.iterator();
        while (it.hasNext()) {
            Method m = it.next();
            if (!m.getDeclaringClass().equals(clazz) && !m.getDeclaringClass().equals(clazzBase)) {
                it.remove();
            }
        }
    } catch (Throwable t) {
        String exMsg = "Exception loading controller class [" + controllerClassName + "].";
        throw new RunwayConfigurationException(exMsg, t);
    }

    NodeList actions = el.getChildNodes();
    for (int iAction = 0; iAction < actions.getLength(); ++iAction) {
        Node nodeAct = actions.item(iAction);

        if (nodeAct.getNodeType() == Node.ELEMENT_NODE) {
            Element elAction = (Element) nodeAct;

            String method = elAction.getAttribute("method");
            String actionUrl = elAction.getAttribute("uri");

            boolean didMatch = false;
            for (Method m : methods) {
                if (m.getName().matches(method)) {
                    controllerMapping.add(m.getName(), actionUrl);
                    didMatch = true;
                }
            }

            if (!didMatch) {
                String exMsg = "The method regex [" + method + "] for action [" + actionUrl
                        + "] did not match any methods on the controller class definition ["
                        + controllerClassName + "].";
                throw new RunwayConfigurationException(exMsg);
            }
        }
    }

    mappings.add(controllerMapping);
}

From source file:au.com.onegeek.lambda.parser.Excel2SeleniumParser.java

private void parse(InputStream stream)
        throws CannotCompileException, NotFoundException, CannotCreateTestClassException,
        InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    logger.debug("Parsing...");

    if (this.dataMap != null && this.tests != null) {
        return;/* w w  w.  j  a  v a2s.com*/
    }

    this.dataMap = new ArrayList<Map<String, Object>>();
    this.tests = new ArrayList<Class<Test>>();

    Workbook workbook = null;
    try {
        workbook = new XSSFWorkbook(stream);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    logger.debug("workbook" + workbook.toString());

    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (sheet.getSheetName().startsWith("data")) {
            // parse key\value pairs
            HashMap<String, Object> map = new HashMap<String, Object>();
            dataMap.add(map);
            boolean done = false;

            Row row = sheet.getRow(sheet.getFirstRowNum());

            while (!done && row != null && row.getPhysicalNumberOfCells() > 0) {
                // TODO: parse numerics correctly (i.e. don't add decimal points if not needed)
                String key = (String) XslxUtil.objectFrom(workbook, row.getCell(0));
                String value = null;
                try {
                    value = (String) XslxUtil.objectFrom(workbook, row.getCell(1));
                    logger.debug("Adding variable to map: " + key + ":" + value);
                    map.put(key, value);

                    row = sheet.getRow(row.getRowNum() + 1);

                    if (row == null || (row.getRowNum() == sheet.getLastRowNum() + 1)) {
                        done = true;
                    }
                } catch (NullPointerException e) {
                    //throw new CannotCreateVariableException("No value found for variable '" + key + "' in dataset: " + sheet.getSheetName());
                    done = true;
                }
            }
        }
    }

    JavassistTestBuilderImpl builder = JavassistTestBuilderImpl.getInstance();

    // Parse Test sheets into Test objects
    for (int s = 0; s < workbook.getNumberOfSheets(); s++) {
        Sheet sheet = workbook.getSheetAt(s);
        int i = 0;

        // Ignore data sheets
        if (sheet.getSheetName().startsWith("suite")) {

            int maxRows = sheet.getPhysicalNumberOfRows();
            int currentRow = sheet.getFirstRowNum();
            logger.debug("Nr rows in sheet: " + maxRows);

            // Create Test Class
            String testCaseName = "Test" + Excel2SeleniumParser.toCamelCase(sheet.getSheetName());
            logger.debug("Creating Test class with name: " + testCaseName);
            builder.makeTestClass(testCaseName, this.dataMap);
            boolean testCaseInProgress = false;
            boolean dataProviderAdded = false;

            // Get First row, containing the test name and the data to be injected
            while (i < maxRows) {
                logger.debug("i: " + i);
                logger.debug("currentRow: " + currentRow);
                Row row = sheet.getRow(currentRow);
                TestCommand command = null;

                // Check for empty row
                if (row != null && row.getPhysicalNumberOfCells() != 0) {
                    i++;

                    // Get Cells
                    Iterator<Cell> iterator = row.cellIterator();
                    while (iterator.hasNext()) {
                        Cell cell = iterator.next();
                        String cellValue = (cell == null || cell.toString() == "") ? ""
                                : XslxUtil.objectFrom(workbook, cell).toString();
                        logger.debug("Cell: " + cellValue);

                        if (cellValue.startsWith("test")) {
                            logger.debug("Test case found: " + cellValue + ". Creating Test Case");

                            // Create new Test CASE
                            try {
                                builder.addTest(cellValue);
                                testCaseInProgress = true;
                                dataProviderAdded = false;
                            } catch (CannotModifyTestMethodException e) {
                                e.printStackTrace();
                                throw new CannotCreateTestClassException(
                                        "Could not create Test Class as there was a variable not found in test assertion. Embedded exception: "
                                                + e.getMessage());
                            } catch (VariableNotFoundException e) {
                                e.printStackTrace();
                                throw new CannotCreateTestClassException(
                                        "Could not create Test Class as there was a variable not found in test assertion. Embedded exception: "
                                                + e.getMessage());
                            }
                            break;
                        } else {
                            if (command == null & !cellValue.equals("")) {
                                logger.debug("Command found: " + cellValue + ". Creating new TestCommand");
                                command = new TestCommand(cellValue);
                            } else if (!cellValue.equals("")) {
                                logger.debug("Command argument found: " + cellValue);
                                command.addParameter(cellValue);
                            }
                        }
                    }
                } else {
                    // Blank row could mean a test case has just been completed
                    // Complete last test case by adding a data provider
                    if (testCaseInProgress && !dataProviderAdded) {
                        try {
                            logger.debug("In Progress Test Case now being closed off and added to class...");
                            builder.addDataProvider();
                            dataProviderAdded = true;
                            logger.debug("In Progress Test Case now closed off!");
                        } catch (CannotCreateDataProviderException e) {
                            throw new CannotCreateTestClassException(
                                    "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                            + e.getMessage());
                        }
                    }
                }
                try {
                    if (command != null) {
                        logger.debug("Adding command to method");
                        builder.appendTestToLastMethod(command);
                    }
                } catch (CannotModifyTestMethodException e) {
                    throw new CannotCreateTestClassException("Unable to add Test Case '" + command.toString()
                            + "' to Test Class. Embedded exception: " + e.getMessage());
                } catch (VariableNotFoundException e) {
                    throw new CannotCreateTestClassException("Unable to add Test Case '" + command.toString()
                            + "' to Test Class as a variable was not found. Embedded exception: "
                            + e.getMessage());
                }
                currentRow++;
            }
            // Blank row could mean a test case has just been completed
            // Complete last test case by adding a data provider
            logger.debug(
                    "End of rows...Checking if In Progress Test Case now being closed off and added to class...");
            if (testCaseInProgress && !dataProviderAdded) {
                logger.debug(" In Progress Test Case now being closed off and added to class...");
                try {
                    builder.addDataProvider();
                    dataProviderAdded = true;
                    logger.debug("In Progress Test Case now closed off!");
                } catch (CannotCreateDataProviderException e) {
                    throw new CannotCreateTestClassException(
                            "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                    + e.getMessage());
                }
            }

            if (testCaseInProgress) {
                logger.debug("Generating class file");
                try {
                    this.tests.add(builder.getCreatedClass());
                } catch (CannotModifyTestMethodException e) {
                    e.printStackTrace();
                    throw new CannotCreateTestClassException(
                            "Could not create Test case as a DataProvider for the method could not be created. Embedded exception: "
                                    + e.getMessage());
                }
                testCaseInProgress = false;
            }
        }
    }

    try {
        stream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.info("Looking at our classes...");

    // Look at the Test Objects
    for (Class<Test> clazz : tests) {
        logger.info("Class: " + clazz.getName());
        for (Method m : clazz.getMethods()) {
            logger.info("Method: " + m);
            if (m.getName().equalsIgnoreCase("testRetailDataProvider")) {
                logger.info("invoking data provider");
                Test test = clazz.newInstance();
                Object[][] data = (Object[][]) m.invoke(test);
                for (Object[] obs : data) {
                    for (Object o : obs) {
                        logger.info("data value: " + o);
                    }
                }
            }
        }
    }
}

From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java

/**
 * Utility method to find properties from a Java Type following Beans Convention.
 *
 * @param type//  w  ww .ja v  a 2  s .  c o  m
 * @return
 */
private <T> HashMap<Method, Field> findProperties(Class<T> type) {
    Field[] fields = type.getDeclaredFields();
    Method[] methods = type.getMethods();
    if (this.sortProperties) {
        // Ordering the properties
        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method m1, Method m2) {
                return m1.getName().compareTo(m2.getName());
            }
        });
    }

    LinkedHashMap<Method, Field> props = new LinkedHashMap<Method, Field>();
    // get valid properties (get method and respective field (if exists))
    for (Method method : methods) {
        Class<?> declaringClass = method.getDeclaringClass();
        if (declaringClass.equals(Object.class) || Collection.class.isAssignableFrom(declaringClass)) {
            continue;
        }

        if (isGetter(method)) {
            boolean hasField = false;
            for (Field field : fields) {
                String name = getNameFromGetter(method);
                Attributes attribs = field.getAnnotation(Attributes.class);
                boolean process = true;
                if (this.processAnnotatedOnly && attribs == null) {
                    process = false;
                }

                if (process && field.getName().equalsIgnoreCase(name)) {
                    props.put(method, field);
                    hasField = true;
                    break;
                }
            }
            if (!hasField) {
                props.put(method, null);
            }
        }
    }
    return props;
}

From source file:edu.utexas.cs.tactex.core.PowerTacBroker.java

/**
 * Finds all the handleMessage() methdods and registers them.
 */// w  ww.  j  a  v  a 2 s .com
private void registerMessageHandlers(Object thing) {
    Class<?> thingClass = thing.getClass();
    Method[] methods = thingClass.getMethods();
    for (Method method : methods) {
        if (method.getName().equals("handleMessage")) {
            Class<?>[] args = method.getParameterTypes();
            if (1 == args.length) {
                log.info("Register " + thing.getClass().getSimpleName() + ".handleMessage("
                        + args[0].getSimpleName() + ")");
                router.registerMessageHandler(thing, args[0]);
            }
        }
    }
}

From source file:com.wordnik.swagger.testframework.APITestRunner.java

/***
 * Runs individual test cases in all test suites and stored the result in output object
 * @param testPackage/*  w w  w .  j  a v  a 2s. com*/
 */
private void runTests(String apiServer, String apiPackageName, TestPackage testPackage, String language,
        int suiteId, String libraryPackageName, ApiKeyAuthTokenBasedSecurityHandler securityHandler,
        String libraryLocation) throws Exception {
    /**
     * Logic:
     *
     * 1. Get each test case
     *
     * 2. based on the patch arrive at the method that needs to be executed
     *
     * 3. From the method get list of input parameters
     *
     * 4. Read input parameters based on input structure
     *
     * 5 Execute method by calling system command
     *
     * 6. Get the output
     *
     * 7. Store output in output object
     *
     * 8. execute assertions
     *
     * 9. Continue with next test case
     */

    Map<Integer, TestResource> resourceMap = new HashMap<Integer, TestResource>();
    for (TestResource resource : testPackage.getResources()) {
        resourceMap.put(resource.getId(), resource);
    }

    for (TestSuite suite : testPackage.getTestSuites()) {
        if (suiteId != 0 && suiteId != suite.getId()) {
            continue;
        }
        int testSuiteId = suite.getId();
        //1
        for (TestCase testCase : suite.getTestCases()) {
            String testCasePath = testCasePath(testSuiteId, testCase.getId());

            //2
            TestResource resource = resourceMap.get(testCase.getResourceId());
            String path = resource.getPath();
            String className = namingPolicyProvider.getServiceName(path);
            String methodName = resource.getSuggestedMethodName();

            //3
            Class apiClass = Class.forName(libraryPackageName + "." + className);
            Method[] methods = apiClass.getMethods();
            Method methodToExecute = null;
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    methodToExecute = method;
                    break;
                }
            }
            try {
                if (methodToExecute != null) {
                    //4
                    Map<String, Object> arguments = getArgumentsForMethodCall(methodToExecute, testCase);

                    String authToken = "\"\"";
                    String postData = "\"\"";
                    StringBuilder queryPathParameters = new StringBuilder();
                    for (String argName : arguments.keySet()) {
                        Object value = arguments.get(argName);
                        if (argName.equals("authToken")) {
                            authToken = value.toString();
                        } else if (argName.equals(POST_PARAM_NAME)) {
                            postData = convertObjectToJSONString(value);
                        } else {
                            if (queryPathParameters.toString().length() > 0) {
                                queryPathParameters.append("~");
                            }
                            queryPathParameters.append(argName + "=" + value.toString());
                        }
                    }

                    //get eternal command
                    String[] externalCommand = constructExternalCommand(apiServer, apiPackageName,
                            securityHandler.getApiKey(), authToken, resource.getPath(),
                            resource.getHttpMethod(), resource.getSuggestedMethodName(),
                            queryPathParameters.toString(), postData, language, libraryLocation);
                    //print the command
                    System.out.println("Test Case :" + testCasePath);
                    for (String arg : externalCommand) {
                        System.out.print(arg + " ");
                    }
                    System.out.println("");
                    //execute and get data
                    String outputString = executeExternalTestCaseAndGetResult(externalCommand);
                    Object output = null;
                    if (outputString != null && outputString.length() > 0) {
                        output = convertJSONStringToObject(outputString, methodToExecute.getReturnType());
                    }
                    //6
                    Class returnType = methodToExecute.getReturnType();
                    if (!returnType.getName().equalsIgnoreCase("void")) {
                        //7
                        testCaseOutput.getData().put(testCasePath, output);
                    }
                    //8
                    //log it as passed, if there is any failures in assertions, assertions will update the status
                    //to failed
                    testStatus.logStatus(testCase, testCasePath, true);
                    executeAssertions(testCasePath, testCase);
                }
            } catch (Exception e) {
                boolean asserted = false;
                if (testCase.getAssertions() != null) {
                    for (Assertion assertion : testCase.getAssertions()) {
                        if (assertion.getCondition().equals("==")
                                && assertion.getExpectedOutput().equalsIgnoreCase("Exception")) {
                            testStatus.logStatus(testCase, testCasePath, true);
                            asserted = true;
                        }
                    }
                }
                if (!asserted) {
                    testStatus.logStatus(testCase, testCasePath, false, e.getMessage(), e);
                }
            }
        }
    }
    System.out.println(testStatus.printTestStatus());
}

From source file:org.synyx.hades.dao.orm.GenericDaoFactory.java

/**
 * Returns if the configured DAO interface has custom methods, that might
 * have to be delegated to a custom DAO implementation. This is used to
 * verify DAO configuration./*from w  ww .j  a  v  a2s  . com*/
 * 
 * @return
 */
private boolean hasCustomMethod(Class<? extends GenericDao<?, ?>> daoInterface) {

    boolean hasCustomMethod = false;

    // No detection required if no typing interface was configured
    if (ClassUtils.isGenericDaoInterface(daoInterface)) {
        return false;
    }

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

        if (isCustomMethod(method, daoInterface) && !isBaseClassMethod(method, daoInterface)) {
            return true;
        }
    }

    return hasCustomMethod;
}

From source file:io.swagger.inflector.SwaggerOperationController.java

public Method detectMethod(Operation operation) {
    String controller = getControllerName(operation);
    String methodName = getMethodName(path, httpMethod, operation);

    if (controller != null && methodName != null) {
        try {//from  w w w  .ja v  a 2s  . co  m
            Class<?> cls;
            try {
                cls = Class.forName(controller);
            } catch (ClassNotFoundException e) {
                controller = controller + "Controller";
                cls = Class.forName(controller);
            }

            JavaType[] args = getOperationParameterClasses(operation, this.definitions);
            Method[] methods = cls.getMethods();
            for (Method method : methods) {
                if (methodName.equals(method.getName())) {
                    Class<?>[] methodArgs = method.getParameterTypes();
                    if (methodArgs.length == args.length) {
                        int i = 0;
                        boolean matched = true;
                        if (!args[i].getRawClass().equals(methodArgs[i])) {
                            LOGGER.debug("failed to match " + args[i] + ", " + methodArgs[i]);
                            matched = false;
                        }
                        if (matched) {
                            this.parameterClasses = args;
                            this.controller = cls.newInstance();
                            LOGGER.debug("matched " + method);
                            return method;
                        }
                    }
                }
            }

            LOGGER.debug("no match in " + controller);
        } catch (ClassNotFoundException e) {
            LOGGER.debug("didn't find class " + controller);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.dianping.resource.io.util.ClassUtils.java

/**
 * Determine whether the given class has a public method with the given signature,
 * and return it if available (else throws an {@code IllegalStateException}).
 * <p>In case of any signature specified, only returns the method if there is a
 * unique candidate, i.e. a single public method with the specified name.
 * <p>Essentially translates {@code NoSuchMethodException} to {@code IllegalStateException}.
 * @param clazz the clazz to analyze//  ww w.  java2  s .  co m
 * @param methodName the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the method (never {@code null})
 * @throws IllegalStateException if the method has not been found
 * @see Class#getMethod
 */
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            throw new IllegalStateException("Expected method not found: " + ex);
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        } else if (candidates.isEmpty()) {
            throw new IllegalStateException("Expected method not found: " + clazz + "." + methodName);
        } else {
            throw new IllegalStateException("No unique method found: " + clazz + "." + methodName);
        }
    }
}

From source file:org.crazydog.util.spring.ClassUtils.java

/**
 * Determine whether the given class has a public method with the given signature,
 * and return it if available (else return {@code null}).
 * <p>In case of any signature specified, only returns the method if there is a
 * unique candidate, i.e. a single public method with the specified name.
 * <p>Essentially translates {@code NoSuchMethodException} to {@code null}.
 * @param clazz the clazz to analyze/*  w  w w .  ja  v a  2  s. c  o  m*/
 * @param methodName the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the method, or {@code null} if not found
 * @see Class#getMethod
 */
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    org.springframework.util.Assert.notNull(clazz, "Class must not be null");
    org.springframework.util.Assert.notNull(methodName, "Method name must not be null");
    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }
}

From source file:com.cloud.utils.db.SqlGenerator.java

protected boolean checkMethods(Class<?> clazz, Map<String, Attribute> attrs) {
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        String name = method.getName();
        if (name.startsWith("get")) {
            String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
            assert !attrs.containsKey(fieldName) : "Mismatch in " + clazz.getSimpleName() + " for " + name;
        } else if (name.startsWith("is")) {
            String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
            assert !attrs.containsKey(fieldName) : "Mismatch in " + clazz.getSimpleName() + " for " + name;
        } else if (name.startsWith("set")) {
            String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
            assert !attrs.containsKey(fieldName) : "Mismatch in " + clazz.getSimpleName() + " for " + name;
        }//from w  ww  . j av a  2  s. c  o  m
    }
    return true;

}