Search in sources :

Example 26 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ActionExecution method injectParam2Pojo.

private Object injectParam2Pojo(Class<?> paramClass, String startName) throws Exception {
    Object paramObj = paramClass.newInstance();
    ReflectUtil ru = new ReflectUtil(paramObj);
    this.injectActionCxt2Pojo(ru);
    // 注入mvc action 请求参数
    ParamUtil.injectParam(this.context, ru, startName);
    return paramObj;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil)

Example 27 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class CheckConfigBean method checkMVCAction.

/**
	 * Check the MVC independent components configuration files
	 * 
	 * @param mvc
	 * @return
	 */
public static String checkMVCAction(ActionConfigBean mvc, String xmlFile) {
    String error = null;
    ConfigBean cb = (ConfigBean) SingleBeanCache.get(ConfigBean.class.getName());
    if ("true".equalsIgnoreCase(cb.getMvc().getOpen()) || "1".equals(cb.getMvc().getOpen())) {
        StringBuilder sb = new StringBuilder();
        if (!"".equals(mvc.getClazz())) {
            try {
                Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(mvc.getClazz());
                if (clazz == null) {
                    sb.append("当前您填写的( class=").append(mvc.getClazz()).append(" )是错误的!它必须是一个有效的类 ;\n");
                } else {
                    if (mvc.getMethod() != null && !"".equals(mvc.getMethod())) {
                        Method m = new ReflectUtil(clazz.newInstance()).getMethod(mvc.getMethod());
                        if (m == null) {
                            sb.append("当前您填写的( method=").append(mvc.getMethod()).append(" )是错误的!它必须是一个有效的方法 ;\n");
                        }
                    }
                }
            } catch (ClassNotFoundException e) {
                sb.append("当前您填写的( class=").append(mvc.getClazz()).append(" )是错误的!它必须是一个有效的类 ;\n");
            } catch (InstantiationException e) {
                sb.append("当前您填写的( class=").append(mvc.getClazz()).append(" )是错误的!它必须是一个提供无参构造方法的类 ;\n");
            } catch (IllegalAccessException e) {
                sb.append("当前您填写的( class=").append(mvc.getClazz()).append(" )是错误的!它必须是一个有效的类 ;\n");
            }
        }
        if (!"".equals(sb.toString())) {
            error = "\n<br /><b>" + xmlFile + ":[bean name=" + mvc.getUriMapping() + "]</b>\n" + sb.toString();
        }
    }
    return error;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) ORMConfigBean(org.eweb4j.orm.config.bean.ORMConfigBean) FieldConfigBean(org.eweb4j.mvc.config.bean.FieldConfigBean) DBInfoConfigBean(org.eweb4j.orm.dao.config.bean.DBInfoConfigBean) ParamConfigBean(org.eweb4j.mvc.config.bean.ParamConfigBean) ResultConfigBean(org.eweb4j.mvc.config.bean.ResultConfigBean) IOCConfigBean(org.eweb4j.ioc.config.bean.IOCConfigBean) LogConfigBean(org.eweb4j.config.bean.LogConfigBean) ActionConfigBean(org.eweb4j.mvc.config.bean.ActionConfigBean) ConfigBean(org.eweb4j.config.bean.ConfigBean) InterConfigBean(org.eweb4j.mvc.config.bean.InterConfigBean) ValidatorConfigBean(org.eweb4j.mvc.config.bean.ValidatorConfigBean) Method(java.lang.reflect.Method)

Example 28 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ActionAnnotationConfig method handleClass.

/**
	 * handle action class
	 * 
	 * @param clsName
	 * @throws Exception
	 */
public boolean handleClass(String clsName) {
    //log.debug("handleClass -> " + clsName);
    Class<?> cls = null;
    try {
        cls = Thread.currentThread().getContextClassLoader().loadClass(clsName);
        if (cls == null)
            return false;
        String simpleName = cls.getSimpleName();
        Controller controlAnn = cls.getAnnotation(Controller.class);
        if (controlAnn == null && !simpleName.endsWith("Controller") && !simpleName.endsWith("Action") && !simpleName.endsWith("Control"))
            return false;
        String moduleName = CommonUtil.toLowCaseFirst(simpleName.replace("Controller", "").replace("Control", ""));
        if (simpleName.endsWith("Action"))
            moduleName = "";
        if ("application".equals(moduleName))
            moduleName = "/";
        //			boolean hasPath = JAXWSUtil.hasPath(cls);
        //			if (hasPath){
        //				moduleName = PathUtil.getPathValue(cls);
        //			}
        Object obj = null;
        try {
            if (cls.getAnnotation(Singleton.class) != null) {
                obj = SingleBeanCache.get(cls.getName());
                if (obj == null) {
                    obj = cls.newInstance();
                    SingleBeanCache.add(cls.getName(), obj);
                }
            } else
                obj = cls.newInstance();
        } catch (Throwable e) {
            log.warn("the action class new instance failued -> " + clsName + " | " + e.toString(), e);
            return false;
        }
        ReflectUtil ru = new ReflectUtil(obj);
        Method[] ms = ru.getMethods();
        if (ms == null)
            return false;
        // 扫描方法的注解信息
        for (Method m : ms) {
            if (m.getModifiers() != 1)
                continue;
            boolean hasPath = JAXWSUtil.hasPath(m);
            //log.debug("scan method->"+m+" has path->"+hasPath);
            if (!hasPath) {
                String methodName = m.getName();
                Method getter = ru.getGetter(methodName.replace("get", ""));
                Method setter = ru.getSetter(methodName.replace("set", ""));
                // 默认下setter和getter不作为action方法
                if (getter != null || setter != null)
                    continue;
            }
            handleActionConfigInfo(ru, cls, m, moduleName);
        }
    } catch (Error e) {
        return false;
    } catch (Exception e) {
        return false;
    }
    return true;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Singleton(org.eweb4j.mvc.action.annotation.Singleton) ActionMethod(org.eweb4j.mvc.ActionMethod) Method(java.lang.reflect.Method) Controller(org.eweb4j.mvc.action.annotation.Controller)

Example 29 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class ActionUrlUtil method mathersUrlMapping.

/**
	 * 匹配url中变量部分{},并将其转换成正则表达式 将url中的{xxx}转化为正则\\d+或者\\[a-zA-Z\\_]+
	 * 
	 * @param m
	 *            控制器中的actoin方法
	 * @param actionName
	 *            控制器的@RequestMapping的value值+方法中@RequestMapping的value值
	 * @return
	 */
public static String mathersUrlMapping(Method m, String actionName, Class<?> cls) {
    List<String> paramNames = new ArrayList<String>();
    List<Class<?>> paramClasses = new ArrayList<Class<?>>();
    // 方法参数变量
    Class<?>[] paramTypes = m.getParameterTypes();
    Annotation[][] paramAnns = m.getParameterAnnotations();
    loadParam(paramTypes, paramAnns, paramNames, paramClasses);
    // Action类实例属性变量
    ReflectUtil ru = null;
    try {
        ru = new ReflectUtil(cls);
    } catch (Error e) {
        return null;
    } catch (Exception e) {
        return null;
    }
    Field[] fields = ru.getFields();
    loadParam(fields, paramNames, paramClasses);
    if (paramClasses != null && paramClasses.size() > 0)
        actionName = urlParamToRegex(actionName, paramNames, paramClasses);
    if (actionName.endsWith("/"))
        actionName = actionName.substring(0, actionName.length() - 1);
    if (actionName.startsWith("/"))
        actionName = actionName.substring(1);
    return actionName;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList)

Example 30 with ReflectUtil

use of org.eweb4j.util.ReflectUtil in project eweb4j-framework by laiweiwei.

the class IOC method getBean.

/**
	 * 生产出符合beanID名字的bean
	 * 
	 * @param <T>
	 * @param beanID
	 * @return
	 * @throws Exception
	 */
public static synchronized <T> T getBean(String beanID) {
    if (!containsBean(beanID)) {
        return null;
    }
    // 声明用来返回的对象
    T t = null;
    try {
        // 声明构造方法参数列表的初始化值 
        Object[] initargs = null;
        // 声明构造方法参数列表
        Class<?>[] args = null;
        List<Object> initargList = new ArrayList<Object>();
        List<Class<?>> argList = new ArrayList<Class<?>>();
        // setters cache
        Map<String, Object> properties = new Hashtable<String, Object>();
        // 遍历配置文件,找出beanID的bean
        if (IOCConfigBeanCache.containsKey(beanID)) {
            IOCConfigBean iocBean = IOCConfigBeanCache.get(beanID);
            // 取出该bean的类型,便于最后使用反射调用构造方法实例化
            Class<T> clazz = (Class<T>) Thread.currentThread().getContextClassLoader().loadClass(iocBean.getClazz());
            // 判断该bean的生命周期
            if (IOCConfigConstant.SINGLETON_SCOPE.equalsIgnoreCase(iocBean.getScope())) {
                // 如果是单件,就从单件缓存池中取
                if (SingleBeanCache.containsKey(beanID)) {
                    t = (T) SingleBeanCache.get(beanID);
                    return t;
                }
            }
            // 遍历每个bean的注入配置
            for (Iterator<Injection> it = iocBean.getInject().iterator(); it.hasNext(); ) {
                Injection inj = it.next();
                if (inj == null)
                    continue;
                String ref = inj.getRef();
                if (ref != null && !"".equals(ref)) {
                    // 如果ref不为空,说明注入的是对象类型,后面需要进入递归
                    String name = inj.getName();
                    if (name != null && !"".equals(name)) {
                        // 如果属性名字不为空,说明使用的是setter注入方式
                        properties.put(name, getBean(ref));
                    } else {
                        // 如果属性名字为空,说明使用的是构造器注入方式
                        // 使用构造器注入的时候,需要按照构造器参数列表顺序实例化
                        Object obj = getBean(ref);
                        initargList.add(obj);
                        String type = inj.getType();
                        if (type != null && type.trim().length() > 0) {
                            Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(type);
                            argList.add(cls);
                        } else {
                            argList.add(obj.getClass());
                        }
                    }
                } else {
                    // 注入基本类型
                    String type = inj.getType();
                    String value = inj.getValue();
                    if (value == null)
                        value = "";
                    String name = inj.getName();
                    if (name != null && !"".equals(name)) {
                        // 如果属性名字不为空,说明使用的是setter注入方式
                        if (IOCConfigConstant.INT_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Integer".equalsIgnoreCase(type)) {
                            if ("".equals(value.trim()))
                                value = "0";
                            // int
                            properties.put(name, Integer.parseInt(value));
                        } else if (IOCConfigConstant.STRING_ARGTYPE.equalsIgnoreCase(type) || "java.lang.String".equalsIgnoreCase(type)) {
                            // String
                            properties.put(name, value);
                        } else if (IOCConfigConstant.LONG_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Long".equalsIgnoreCase(type)) {
                            // long
                            if ("".equals(value.trim()))
                                value = "0";
                            properties.put(name, Long.parseLong(value));
                        } else if (IOCConfigConstant.FLOAT_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Float".equalsIgnoreCase(type)) {
                            // float
                            if ("".equals(value.trim()))
                                value = "0.0";
                            properties.put(name, Float.parseFloat(value));
                        } else if (IOCConfigConstant.BOOLEAN_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Boolean".equalsIgnoreCase(type)) {
                            // boolean
                            if ("".equals(value.trim()))
                                value = "false";
                            properties.put(name, Boolean.parseBoolean(value));
                        } else if (IOCConfigConstant.DOUBLE_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Double".equalsIgnoreCase(type)) {
                            // double
                            if ("".equals(value.trim()))
                                value = "0.0";
                            properties.put(name, Double.parseDouble(value));
                        }
                    } else {
                        // 使用构造器注入的时候,需要按照构造器参数列表顺序实例化
                        if (IOCConfigConstant.INT_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Integer".equalsIgnoreCase(type)) {
                            // int
                            if ("".equals(value.trim()))
                                value = "0";
                            argList.add(int.class);
                            initargList.add(Integer.parseInt(value));
                        } else if (IOCConfigConstant.LONG_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Long".equalsIgnoreCase(type)) {
                            // long
                            if ("".equals(value.trim()))
                                value = "0";
                            argList.add(long.class);
                            initargList.add(Long.parseLong(value));
                        } else if (IOCConfigConstant.FLOAT_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Float".equalsIgnoreCase(type)) {
                            // float
                            if ("".equals(value.trim()))
                                value = "0.0";
                            argList.add(float.class);
                            initargList.add(Float.parseFloat(value));
                        } else if (IOCConfigConstant.BOOLEAN_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Boolean".equalsIgnoreCase(type)) {
                            // boolean
                            if ("".equals(value.trim()))
                                value = "false";
                            argList.add(boolean.class);
                            initargList.add(Boolean.parseBoolean(value));
                        } else if (IOCConfigConstant.DOUBLE_ARGTYPE.equalsIgnoreCase(type) || "java.lang.Double".equalsIgnoreCase(type)) {
                            // double
                            if ("".equals(value.trim()))
                                value = "0.0";
                            argList.add(double.class);
                            initargList.add(Double.parseDouble(value));
                        } else if (IOCConfigConstant.STRING_ARGTYPE.equalsIgnoreCase(type) || "java.lang.String".equalsIgnoreCase(type)) {
                            // String
                            argList.add(String.class);
                            initargList.add(value);
                        }
                    }
                }
            }
            // 如果构造方法参数列表不为空,说明需要使用构造方法进行注入
            if (argList.size() > 0 && initargList.size() > 0) {
                args = new Class<?>[argList.size()];
                initargs = new Object[initargList.size()];
                for (int i = 0; i < argList.size(); i++) {
                    args[i] = argList.get(i);
                    initargs[i] = initargList.get(i);
                }
                t = clazz.getDeclaredConstructor(args).newInstance(initargs);
            } else if (t == null) {
                t = clazz.newInstance();
                for (Iterator<Entry<String, Object>> it = properties.entrySet().iterator(); it.hasNext(); ) {
                    Entry<String, Object> e = it.next();
                    final String name = e.getKey();
                    ReflectUtil ru = new ReflectUtil(t);
                    Method m = ru.getSetter(name);
                    if (m == null)
                        continue;
                    m.invoke(t, e.getValue());
                }
            }
            // 判断该bean的生命周期
            if (IOCConfigConstant.SINGLETON_SCOPE.equalsIgnoreCase(iocBean.getScope())) {
                // 如果是单件,就从单件缓存池中取
                if (!SingleBeanCache.containsKey(beanID)) {
                    SingleBeanCache.add(beanID, t);
                }
            }
        }
    } catch (Throwable e) {
        log.error("IOC.getBean(" + beanID + ") failed!", e);
    }
    String info = "IOC.getBean(" + beanID + ") -> " + t;
    log.debug(info);
    return t;
}
Also used : Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Injection(org.eweb4j.ioc.config.bean.Injection) Method(java.lang.reflect.Method) IOCConfigBean(org.eweb4j.ioc.config.bean.IOCConfigBean) ReflectUtil(org.eweb4j.util.ReflectUtil) Entry(java.util.Map.Entry) Iterator(java.util.Iterator)

Aggregations

ReflectUtil (org.eweb4j.util.ReflectUtil)49 Method (java.lang.reflect.Method)37 Field (java.lang.reflect.Field)26 JoinColumn (javax.persistence.JoinColumn)14 ManyToOne (javax.persistence.ManyToOne)10 ArrayList (java.util.ArrayList)9 OneToOne (javax.persistence.OneToOne)9 DAOException (org.eweb4j.orm.dao.DAOException)9 JoinTable (javax.persistence.JoinTable)7 HashMap (java.util.HashMap)6 ManyToMany (javax.persistence.ManyToMany)6 OneToMany (javax.persistence.OneToMany)6 ORMConfigBean (org.eweb4j.orm.config.bean.ORMConfigBean)6 Property (org.eweb4j.orm.config.bean.Property)6 Entry (java.util.Map.Entry)5 File (java.io.File)4 List (java.util.List)4 Map (java.util.Map)4 ConfigBean (org.eweb4j.config.bean.ConfigBean)4 Hashtable (java.util.Hashtable)3