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.kjt.service.common.SoafwTesterMojo.java

/**
 * //w w w . j a  v a 2s.c o  m
 * @param className 
 */
private void appendTest(String className) {
    /**
     * ?? ?public
     * ?MojoExecutionException??????
     */
    try {

        Map<String, Integer> methodCnt = new HashMap<String, Integer>();
        boolean hasmethod = false;

        Map<String, String> methodDefs = new HashMap<String, String>();
        Class cls = cl.loadClass(className);// 
        Class[] inters = cls.getInterfaces();
        int len = 0;
        if (inters == null || (len = inters.length) == 0) {
            return;
        }
        for (int i = 0; i < len; i++) {

            Class interCls = inters[i];

            this.getLog().info("@interface: " + interCls.getName());

            String name = project.getName();

            Method[] methods = null;

            if (name.endsWith("-dao")) {
                methods = interCls.getDeclaredMethods();
            } else {
                methods = interCls.getMethods();
            }

            int mlen = 0;
            if (methods != null && (mlen = methods.length) > 0) {

                StringBuffer methodBuf = new StringBuffer();

                for (int m = 0; m < mlen; m++) {
                    Method method = methods[m];
                    int modf = method.getModifiers();
                    if (modf == 1025) {// ??
                        hasmethod = true;
                        /**
                         * ??????Test ???=??+Test
                         * ??:basedPath+File.separator
                         * +src+File.separator+test+File.separator
                         * +pkg+definesArray[i]+Test+.java
                         */
                        if (methodCnt.containsKey(method.getName())) {
                            methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1);
                        } else {
                            methodCnt.put(method.getName(), 0);
                        }
                        int cnt = methodCnt.get(method.getName());

                        addMethod(methodDefs, methodBuf, method, cnt);
                    }
                }
            }
        }

        Class tstCls = cl.loadClass(className + "Test");// 

        Method[] methods = tstCls.getDeclaredMethods();
        len = methods == null ? 0 : methods.length;
        this.getLog().info("" + tstCls.getSimpleName() + "?" + len);

        /**
         * ??public
         */
        for (int m = 0; m < len; m++) {

            Method method = methods[m];
            SoaFwTest test = method.getAnnotation(SoaFwTest.class);
            if (test == null) {
                this.getLog()
                        .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest");
                continue;
            }

            String id = test.id();

            if (methodDefs.containsKey(id)) {
                methodDefs.remove(id);
            }
        }

        if ((len = methodDefs.size()) == 0) {
            return;
        }

        String[] methodImpls = new String[len];
        methodDefs.keySet().toArray(methodImpls);
        // TODO  ???
        this.getLog().info("???");

        StringBuilder src = new StringBuilder();

        String srcs = readTestSrc(className);

        int index = srcs.lastIndexOf("}");

        this.getLog().info(srcs);
        this.getLog().info("lastIndexOf(}):" + index);
        String impls = srcs.substring(0, index - 1);

        src.append(impls);

        src.append("\n");

        StringBuilder appends = new StringBuilder();
        this.getLog().info("?");
        for (int i = 0; i < len; i++) {
            String methodId = methodImpls[i];
            String method = methodDefs.get(methodId);
            appends.append(method);
            appends.append("\n");
        }

        src.append(appends.toString());

        src.append("}");

        Package pkg = tstCls.getPackage();
        String pkgName = pkg.getName();
        String pkgPath = pkgName.replace(".", File.separator);

        String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator
                + "java";
        String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath;

        write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString());

    } catch (Exception e) {
        this.getLog().error(e);
    } catch (Error er) {
        this.getLog().error(er);
    }
}

From source file:com.grepcurl.random.ObjectGenerator.java

public <T> T generate(Class<T> klass, SetterOverrides setterOverrides, String[] constructorArgTypes,
        Object... constructorArgs) {
    Validate.notNull(klass);/*from   w  w w  . j  a  v  a 2 s. co m*/
    Validate.notNull(constructorArgs);
    if (verbose) {
        log(String.format("generating object of type: %s, with args: %s, of types: %s, with overrides: %s",
                klass, Arrays.toString(constructorArgs), Arrays.toString(constructorArgTypes),
                setterOverrides));
    }
    try {
        Deque<Object> objectStack = new ArrayDeque<>();
        Class[] constructorTypes = _toClasses(constructorArgTypes, constructorArgs);
        T t = klass.getConstructor(constructorTypes).newInstance(constructorArgs);
        objectStack.push(t);
        Method[] methods = klass.getMethods();
        for (Method method : methods) {
            _processMethod(method, setterOverrides, t, objectStack);
        }
        objectStack.pop();
        return t;
    } catch (Exception e) {
        throw new FailedRandomObjectGenerationException(e);
    }
}

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

public Method detectMethod(Operation operation) {
    controllerName = getControllerName(operation);
    methodName = getMethodName(path, httpMethod, operation);
    JavaType[] args = getOperationParameterClasses(operation, this.definitions);

    StringBuilder builder = new StringBuilder();

    builder.append(getMethodName(path, httpMethod, operation)).append("(");

    for (int i = 0; i < args.length; i++) {
        if (i == 0) {
            builder.append(RequestContext.class.getCanonicalName()).append(" request");
        } else {//w  w w.jav a2 s .  c o  m
            builder.append(", ");
            if (args[i] == null) {
                LOGGER.error(
                        "didn't expect a null class for " + operation.getParameters().get(i - 1).getName());
            } else if (args[i].getRawClass() != null) {
                String className = args[i].getRawClass().getName();
                if (className.startsWith("java.lang.")) {
                    className = className.substring("java.lang.".length());
                }
                builder.append(className);
                builder.append(" ").append(operation.getParameters().get(i - 1).getName());
            }
        }
    }
    builder.append(")");

    operationSignature = "public io.swagger.inflector.models.ResponseContext " + builder.toString();

    LOGGER.info("looking for method: `" + operationSignature + "` in class `" + controllerName + "`");
    this.parameterClasses = args;

    if (controllerName != null && methodName != null) {
        try {
            Class<?> cls;
            try {
                cls = Class.forName(controllerName);
            } catch (ClassNotFoundException e) {
                controllerName = controllerName + "Controller";
                cls = Class.forName(controllerName);
            }

            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 = getControllerFactory().instantiateController(cls, operation);
                            LOGGER.debug("found class `" + controllerName + "`");
                            return method;
                        }
                    }
                }
            }
        } 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.nginious.http.serialize.JsonSerializerCreator.java

/**
 * Creates a JSON serializer for the specified bean class unless a serializer has already been
 * created. Created serializers are cached and returned on subsequent calls to this method.
 * /*ww  w . j  a  v  a  2s  . co m*/
 * @param factory serializer factory
 * @param <T> class type for bean
 * @param beanClazz bean class for which a serializer should be created
 * @return the created serializer
 * @throws SerializerFactoryException if unable to create serializer or class is not a bean
 */
@SuppressWarnings("unchecked")
<T> JsonSerializer<T> create(SerializerFactoryImpl factory, Class<T> beanClazz)
        throws SerializerFactoryException {
    JsonSerializer<T> serializer = (JsonSerializer<T>) serializers.get(beanClazz);

    if (serializer != null) {
        return serializer;
    }

    try {
        synchronized (this) {
            serializer = (JsonSerializer<T>) serializers.get(beanClazz);

            if (serializer != null) {
                return serializer;
            }

            checkSerializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intSerializerClazzName = new StringBuffer(intBeanClazzName).append("JsonSerializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization.createClassSignature("com/nginious/http/serialize/JsonSerializer",
                    intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intSerializerClazzName, signature,
                    "com/nginious/http/serialize/JsonSerializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonSerializer");

            // Create serialize method
            MethodVisitor visitor = createSerializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canSerialize = info == null
                        || (info != null && info.serialize() && info.types().indexOf("json") > -1);

                if (canSerialize && method.getName().startsWith("get") && !method.getName().equals("getClass")
                        && method.getReturnType() != null && method.getParameterTypes().length == 0) {
                    Class<?> returnType = method.getReturnType();
                    String propertyName = getPropertyName(method);

                    if (returnType.isPrimitive()) {
                        if (returnType.equals(boolean.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeBoolean",
                                    "Z", "Z", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(double.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDouble",
                                    "D", "D", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(float.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeFloat",
                                    "F", "F", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(int.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeInt",
                                    "I", "I", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(long.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeLong",
                                    "J", "J", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(short.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeShort",
                                    "S", "S", intBeanClazzName, method.getName(), propertyName);
                        }
                    } else if (Collection.class.isAssignableFrom(returnType)) {
                        Class<?> collectionType = canSerializeGenericCollectionType(method, "json");

                        if (collectionType != null) {
                            createBeanCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType, collectionType);
                        } else {
                            createObjectCollectionSerializationCode(visitor, returnType, intBeanClazzName,
                                    method.getName(), propertyName);
                        }
                    } else if (returnType.equals(Calendar.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeCalendar",
                                "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName,
                                method.getName(), propertyName);
                    } else if (returnType.equals(Date.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else if (returnType.equals(String.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeString",
                                "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else {
                        info = returnType.getAnnotation(Serializable.class);
                        canSerialize = info != null && info.serialize() && info.types().indexOf("json") > -1;

                        if (canSerialize) {
                            createBeanSerializationCode(visitor, method.getName(), propertyName, returnType,
                                    intBeanClazzName);
                        } else {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeObject",
                                    "Ljava/lang/Object;", "L" + returnType.getName().replace('.', '/') + ";",
                                    intBeanClazzName, method.getName(), propertyName);
                        }
                    }
                }
            }

            visitor.visitInsn(Opcodes.RETURN);
            visitor.visitMaxs(8, 7);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader, intSerializerClazzName.replace('/', '.'),
                    clazzBytes);
            serializer = (JsonSerializer<T>) clazz.newInstance();
            String propertyName = Serialization.createPropertyNameFromClass(beanClazz);
            serializer.setName(propertyName);
            serializer.setType(beanClazz);
            serializer.setSerializerFactory(factory);
            serializers.put(beanClazz, serializer);
            return serializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    }
}

From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

@Override
// public void loadSettings(Settings instance, Class<?> clazz, String fn)
public void loadSettings(Settings instance, String fn) {

    Class<?> clazz = instance.getClass().getInterfaces()[0];
    //      File file = new File("/" + DIR_PATH + "/" + fn);
    File file = new File(fn);
    Properties props = null;/*from ww w .  j  ava  2  s. c  om*/
    try {
        props = BotUtils.loadProperties(file);

        // botEnvironment.setClientIp((props.getProperty("client.ip",
        // "127.0.0.1"));
    } catch (IOException e) {
        // e.printStackTrace();
        //         logger.warn("Can't load settings /" + DIR_PATH + "/" + fn
        //               + ". Create new settings file.");
        logger.warn("Can't load settings " + fn + ". Create new settings file.");
        props = createSettings(clazz, fn, "Bot v" + VERSION);

    }
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        // Find setters
        if (method.getName().startsWith("set")) {

            if (method.isAnnotationPresent(Param.class)) {

                Annotation annotation = method.getAnnotation(Param.class);
                Param param = (Param) annotation;
                if (param.name().equals("") || param.values().length == 0) {
                    throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                Class<?>[] paramClazzes = method.getParameterTypes();
                if (paramClazzes.length != 1) {
                    throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                // Check param belongs to List
                Class<?> paramClazz = paramClazzes[0];

                try {
                    if (List.class.isAssignableFrom(paramClazz)) {
                        // Oh, its array...
                        // May be its InetSocketAddress?

                        Type[] gpt = method.getGenericParameterTypes();
                        if (gpt[0] instanceof ParameterizedType) {
                            ParameterizedType type = (ParameterizedType) gpt[0];
                            Type[] typeArguments = type.getActualTypeArguments();

                            for (Type typeArgument : typeArguments) {
                                Class<?> classType = ((Class<?>) typeArgument);
                                if (InetSocketAddress.class.isAssignableFrom(classType)) {
                                    List<InetSocketAddress> isaArr = new ArrayList<>();
                                    int cnt = Integer.parseInt(props.getProperty(param.name() + ".count", "2"));
                                    for (int i = 0; i < cnt; ++i) {
                                        String defaultHostname = "";
                                        String defaultPort = "";
                                        if (param.values().length > i * 2) {
                                            defaultHostname = param.values()[i * 2];
                                            defaultPort = param.values()[i * 2 + 1];
                                        } else {
                                            defaultHostname = DEFAULT_HOSTNAME;
                                            defaultPort = String.valueOf(DEFAULT_PORT);
                                        }
                                        InetSocketAddress isa = new InetSocketAddress(
                                                props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".ip",
                                                        defaultHostname),
                                                Integer.parseInt(props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".port",
                                                        defaultPort)));
                                        // invocableClazz.getMethod(method.getName(),
                                        // InetSocketAddress.class).invoke(
                                        // instance, isa);
                                        isaArr.add(isa);

                                    }

                                    method.invoke(instance, isaArr);

                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implemented yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        if (int.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Integer.parseInt(props.getProperty(param.name(), param.values()[0])));
                        } else if (long.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Long.parseLong(props.getProperty(param.name(), param.values()[0])));
                        } else if (boolean.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Boolean.parseBoolean(props.getProperty(param.name(), param.values()[0])));
                        } else if (double.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Double.parseDouble(props.getProperty(param.name(), param.values()[0])));
                        }

                    } else if (String.class.isAssignableFrom(paramClazz)) {
                        method.invoke(instance, props.getProperty(param.name(), param.values()[0]));
                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.grepcurl.random.ObjectGenerator.java

@SuppressWarnings("unused")
public <T> T generate(Class<T> klass, Object... constructorArgs) {
    Validate.notNull(klass);//ww w.  j av a 2  s  .c om
    Validate.notNull(constructorArgs);
    if (verbose) {
        log(String.format("generating object of type: %s, with args: %s", klass,
                Arrays.toString(constructorArgs)));
    }
    try {
        Deque<Object> objectStack = new ArrayDeque<>();
        Class[] constructorTypes = _toClasses(constructorArgs);
        T t;
        if (klass.isEnum()) {
            int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1);
            t = klass.getEnumConstants()[randomOrdinal];
        } else {
            t = klass.getConstructor(constructorTypes).newInstance(constructorArgs);
        }
        objectStack.push(t);
        Method[] methods = klass.getMethods();
        for (Method method : methods) {
            _processMethod(method, new SetterOverrides(), t, objectStack);
        }
        objectStack.pop();
        return t;
    } catch (Exception e) {
        throw new FailedRandomObjectGenerationException(e);
    }
}

From source file:com.alibaba.dubbo.governance.web.common.module.screen.Restful.java

public void execute(Map<String, Object> context) throws Throwable {
    if (context.get(WebConstants.CURRENT_USER_KEY) != null) {
        User user = (User) context.get(WebConstants.CURRENT_USER_KEY);
        currentUser = user;//from www  .  j  a v  a  2s  .co  m
        operator = user.getUsername();
        role = user.getRole();
        context.put(WebConstants.CURRENT_USER_KEY, user);
    }
    operatorAddress = (String) context.get("request.remoteHost");
    context.put("operator", operator);
    context.put("operatorAddress", operatorAddress);

    context.put("currentRegistry", currentRegistry);

    String httpMethod = (String) context.get("request.method");
    String method = (String) context.get("_method");
    String contextPath = (String) context.get("request.contextPath");
    context.put("rootContextPath", new RootContextPath(contextPath));

    // ?Method
    if (method == null || method.length() == 0) {
        String id = (String) context.get("id");
        if (id == null || id.length() == 0) {
            method = "index";
        } else {
            method = "show";
        }
    }
    if ("index".equals(method)) {
        if ("post".equalsIgnoreCase(httpMethod)) {
            method = "create";
        }
    } else if ("show".equals(method)) {
        if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // ????PUTPOST
            method = "update";
        } else if ("delete".equalsIgnoreCase(httpMethod)) { // ????DELETE?
            method = "delete";
        }
    }
    context.put("_method", method);

    try {
        Method m = null;
        try {
            m = getClass().getMethod(method, new Class<?>[] { Map.class });
        } catch (NoSuchMethodException e) {
            for (Method mtd : getClass().getMethods()) {
                if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) {
                    m = mtd;
                    break;
                }
            }
            if (m == null) {
                throw e;
            }
        }
        if (m.getParameterTypes().length > 2) {
            throw new IllegalStateException("Unsupport restful method " + m);
        } else if (m.getParameterTypes().length == 2 && (m.getParameterTypes()[0].equals(Map.class)
                || !m.getParameterTypes()[1].equals(Map.class))) {
            throw new IllegalStateException("Unsupport restful method " + m);
        }
        Object r;
        if (m.getParameterTypes().length == 0) {
            r = m.invoke(this, new Object[0]);
        } else {
            Object value;
            Class<?> t = m.getParameterTypes()[0];
            if (Map.class.equals(t)) {
                value = context;
            } else if (isPrimitive(t)) {
                String id = (String) context.get("id");
                value = convertPrimitive(t, id);
            } else if (t.isArray() && isPrimitive(t.getComponentType())) {
                String id = (String) context.get("id");
                String[] ids = id == null ? new String[0] : id.split("[.+]+");
                value = Array.newInstance(t.getComponentType(), ids.length);
                for (int i = 0; i < ids.length; i++) {
                    Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i]));
                }
            } else {
                value = t.newInstance();
                for (Method mtd : t.getMethods()) {
                    if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set")
                            && mtd.getParameterTypes().length == 1) {
                        String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4);
                        Object v = context.get(p);
                        if (v == null) {
                            if ("operator".equals(p)) {
                                v = operator;
                            } else if ("operatorAddress".equals(p)) {
                                v = (String) context.get("request.remoteHost");
                            }
                        }
                        if (v != null) {
                            try {
                                mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v,
                                        mtd.getParameterTypes()[0]) });
                            } catch (Throwable e) {
                                logger.warn(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
            if (m.getParameterTypes().length == 1) {
                r = m.invoke(this, new Object[] { value });
            } else {
                r = m.invoke(this, new Object[] { value, context });
            }
        }
        if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) {
            context.put("rundata.layout", "redirect");
            context.put("rundata.target", "redirect");
            context.put("success", r == null || ((Boolean) r).booleanValue());
            if (context.get("redirect") == null) {
                context.put("redirect", getDefaultRedirect(context, method));
            }
        } else if (m.getReturnType() == String.class) {
            String redirect = (String) r;
            if (redirect == null) {
                redirect = getDefaultRedirect(context, method);
            }

            if (context.get("chain") != null) {
                context.put("rundata.layout", "home");
                context.put("rundata.target", "home");
            } else {
                context.put("rundata.redirect", redirect);
            }
        } else {
            context.put("rundata.layout", method);
            context.put("rundata.target", context.get("rundata.target") + "/" + method);
        }
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException) {
            throw ((InvocationTargetException) e).getTargetException();
        }
        //            if (e instanceof InvocationTargetException) {
        //                e = ((InvocationTargetException) e).getTargetException();
        //            }
        //            logger.warn(e.getMessage(), e);
        //            context.put("rundata.layout", "redirect");
        //            context.put("rundata.target", "redirect");
        //            context.put("success", false);
        //            context.put("exception", e);
        //            context.put("redirect", getDefaultRedirect(context, method));
    }
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

/**
 * Finds the type that a constraint validator will check.
 *
 * <p>//from   www  .  ja v a2s .c o m
 * This type comes from the first parameter of the isValid() method on the constraint validator.
 * However, this is a bit tricky because ConstraintValidator has a parameterized type. When using
 * Java reflection, we will see multiple isValid() methods, including one that checks
 * java.lang.Object.
 * </p>
 *
 * <p>
 * Strategy: for now, assume there are at most two isValid() methods. If there are two, assume one
 * of them has a type that is assignable from the other. (Most likely, one of them will be
 * java.lang.Object.)
 * </p>
 *
 * @throws IllegalStateException if there isn't any isValid() method or there are more than two.
 */
static <T extends Annotation> Class<?> getTypeOfConstraintValidator(
        final Class<? extends ConstraintValidator<T, ?>> constraintClass) {

    int candidateCount = 0;
    Class<?> result = null;
    for (final Method method : constraintClass.getMethods()) {
        if (method.getName().equals("isValid") && method.getParameterTypes().length == 2
                && method.getReturnType().isAssignableFrom(Boolean.TYPE)) {
            final Class<?> firstArgType = method.getParameterTypes()[0];
            if (result == null || result.isAssignableFrom(firstArgType)) {
                result = firstArgType;
            }
            candidateCount++;
        }
    }

    if (candidateCount == 0) {
        throw new IllegalStateException("ConstraintValidators must have a isValid method");
    } else if (candidateCount > 2) {
        throw new IllegalStateException("ConstraintValidators must have no more than two isValid methods");
    }

    return result;
}

From source file:com.ocpsoft.pretty.faces.config.annotation.PrettyAnnotationHandler.java

/**
 * This method scans the supplied class for PrettyFaces annotations. The
 * method must be called for every class that should be scanner before
 * finally calling {@link #build(PrettyConfigBuilder)}.
 * /*  w ww  .  j  a va  2 s.c  om*/
 * @param clazz The class to scan
 */
public void processClass(Class clazz) {

    // log class name on trace level
    if (log.isTraceEnabled()) {
        log.trace("Analyzing class: " + clazz.getName());
    }

    try {

        // scan for PrettyAnnotation class
        // returns the mapping ID, if an annotation was found
        String[] classMappingIds = processClassMappingAnnotations(clazz);

        // scan for PrettyBean annotation
        processPrettyBeanAnnotation(clazz);

        // process annotations on public methods
        for (Method method : clazz.getMethods()) {
            processMethodAnnotations(method, classMappingIds);
        }

        // loop over fields to find URLQueryParameter annotations
        for (Field field : clazz.getDeclaredFields()) {
            processFieldAnnotations(field, classMappingIds);
        }

    } catch (NoClassDefFoundError e) {
        // reference to another class unknown to the classloader
        log.debug("Unable to process class '" + clazz.getName() + "': " + e.toString());
    }

}

From source file:com.tugo.dt.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {//from   w  w  w .  j a va 2 s.c o  m
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (org.apache.commons.lang.ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}