Search in sources :

Example 71 with Method

use of java.lang.reflect.Method in project eweb4j-framework by laiweiwei.

the class ParamUtil method getLastPojo.

private static Object getLastPojo(Object parentPojo, String pojoParamName, Hashtable<String, Object> hasPojo) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (parentPojo == null)
        return null;
    if (Map.class.isAssignableFrom(parentPojo.getClass())) {
        return parentPojo;
    }
    ReflectUtil _ru = new ReflectUtil(parentPojo);
    Method pojoSetter = _ru.getSetter(pojoParamName);
    if (pojoSetter == null)
        return parentPojo;
    Class<?> pojoClass = pojoSetter.getParameterTypes()[0];
    Object subPojo = hasPojo.get(pojoParamName);
    if (subPojo == null) {
        if (Map.class.isAssignableFrom(pojoClass)) {
            subPojo = new HashMap<String, Object>();
        } else {
            subPojo = pojoClass.newInstance();
        }
        hasPojo.put(pojoParamName, subPojo);
    }
    pojoSetter.invoke(parentPojo, subPojo);
    return subPojo;
}
Also used : ReflectUtil(org.eweb4j.util.ReflectUtil) Method(java.lang.reflect.Method)

Example 72 with Method

use of java.lang.reflect.Method in project eweb4j-framework by laiweiwei.

the class ActionExecution method handleResult.

private void handleResult() throws Exception {
    this.exeActionLog();
    if (retn == null)
        return;
    String baseUrl = (String) this.context.getServletContext().getAttribute(MVCConfigConstant.BASE_URL_KEY);
    if (File.class.isAssignableFrom(retn.getClass())) {
        File file = (File) retn;
        this.handleDownload(file);
        return;
    } else if (File[].class.isAssignableFrom(retn.getClass())) {
        File[] files = (File[]) retn;
        String fileName = CommonUtil.getNowTime("yyyyMMddHHmmss") + "_" + "download.zip";
        HttpServletResponse resp = this.context.getResponse();
        resp.reset();
        resp.setContentType("application/zip");
        resp.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        ServletOutputStream outputStream = resp.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (File file : files) {
            byte[] b = new byte[1024];
            int len;
            zip.putNextEntry(new ZipEntry(file.getName()));
            FileInputStream fis = new FileInputStream(file);
            while ((len = fis.read(b)) != -1) {
                zip.write(b, 0, len);
            }
            fis.close();
        }
        zip.flush();
        zip.close();
        outputStream.flush();
        return;
    }
    if (!String.class.isAssignableFrom(retn.getClass())) {
        String mimeType = null;
        boolean hasProduces = JAXWSUtil.hasProduces(method);
        if (hasProduces) {
            String[] mimeTypes = ProducesUtil.getProducesValue(method);
            if (mimeTypes != null && mimeTypes.length > 0)
                mimeType = mimeTypes[0];
        }
        if (mimeType == null || mimeType.trim().length() == 0)
            mimeType = this.context.getRequest().getParameter(MVCConfigConstant.HTTP_HEADER_ACCEPT_PARAM);
        if (mimeType == null || mimeType.trim().length() == 0) {
            String contentType = this.context.getRequest().getContentType();
            if (contentType != null) {
                this.context.getResponse().setContentType(contentType);
                mimeType = contentType.split(";")[0];
            }
        }
        if (this.context.getWriter() == null)
            this.context.setWriter(this.context.getResponse().getWriter());
        if (MIMEType.JSON.equals(mimeType) || "json".equalsIgnoreCase(mimeType)) {
            this.context.getResponse().setContentType(MIMEType.JSON);
            this.context.getWriter().print(CommonUtil.toJson(retn));
        } else if (MIMEType.XML.equals(mimeType) || "xml".equalsIgnoreCase(mimeType)) {
            Class<?> cls = retn.getClass();
            if (Collection.class.isAssignableFrom(cls)) {
                Class<?> _cls = ClassUtil.getPojoClass(this.method);
                if (_cls != null)
                    cls = _cls;
            }
            XMLWriter writer = BeanXMLUtil.getBeanXMLWriter(retn);
            writer.setCheckStatck(true);
            writer.setSubNameAuto(true);
            writer.setClass(cls);
            writer.setRootElementName(null);
            this.context.getResponse().setContentType(MIMEType.XML);
            this.context.getWriter().print(writer.toXml());
        } else {
            //默认都用json
            this.context.getResponse().setContentType(MIMEType.JSON);
            this.context.getWriter().print(CommonUtil.toJson(retn));
        }
        return;
    }
    List<String> produces = this.context.getActionConfigBean().getProduces();
    if (produces != null && produces.size() > 0)
        for (String produce : produces) {
            this.context.getResponse().setContentType(produce);
            break;
        }
    String re = String.valueOf(retn);
    //model driven
    for (Field f : fields) {
        Method getter = ru.getGetter(f.getName());
        if (getter == null)
            continue;
        String name = f.getName();
        if (this.context.getModel().containsKey(name))
            continue;
        this.context.getModel().put(name, getter.invoke(actionObject));
    }
    this.context.getModel().put(MVCConfigConstant.BASE_URL_KEY, this.context.getServletContext().getAttribute(MVCConfigConstant.BASE_URL_KEY));
    this.context.getModel().put(MVCConfigConstant.APPLICATION_SCOPE_KEY, new ServletContextProxy(this.context.getServletContext()).attrs());
    this.context.getModel().put(MVCConfigConstant.SESSION_SCOPE_KEY, new HttpSessionProxy(this.context.getSession()).attrs());
    this.context.getModel().put(MVCConfigConstant.COOKIE_SCOPE_KEY, new CookieProxy(this.context.getRequest().getCookies()).attrs());
    this.context.getModel().put(MVCConfigConstant.REQ_PARAM_SCOPE_KEY, this.context.getQueryParamMap());
    // 客户端重定向
    if (re.startsWith(RenderType.REDIRECT + ":")) {
        String url = re.substring((RenderType.REDIRECT + ":").length());
        String location = url;
        this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));
        return;
    } else if (re.startsWith(RenderType.ACTION + ":")) {
        String path = re.substring((RenderType.ACTION + ":").length());
        // ACTION 重定向
        handleActionRedirect(context, path, baseUrl);
        return;
    } else if (re.startsWith(RenderType.OUT + ":")) {
        String location = re.substring((RenderType.OUT + ":").length());
        this.context.getWriter().print(location);
        return;
    } else if (re.startsWith(RenderType.FORWARD + ":") || re.startsWith(RenderType.JSP + ":") || re.endsWith("." + RenderType.JSP)) {
        String[] str = re.split("@");
        re = str[0];
        String location = re;
        if (re.startsWith(RenderType.FORWARD + ":"))
            location = re.substring((RenderType.FORWARD + ":").length());
        else if (re.startsWith(RenderType.JSP + ":"))
            location = re.substring((RenderType.JSP + ":").length());
        //渲染JSP
        JSPRendererImpl render = new JSPRendererImpl();
        render.setContext(context);
        if (str.length > 1)
            render.layout(str[1]);
        render.target(location).render(context.getWriter(), context.getModel());
        return;
    } else if (re.startsWith(RenderType.FREEMARKER + ":") || re.startsWith(RenderType.FREEMARKER2 + ":") || re.endsWith("." + RenderType.FREEMARKER2)) {
        String[] str = re.split("@");
        re = str[0];
        String location = re;
        if (re.startsWith(RenderType.FREEMARKER + ":"))
            location = re.substring((RenderType.FREEMARKER + ":").length());
        else if (re.startsWith(RenderType.FREEMARKER2 + ":"))
            location = re.substring((RenderType.FREEMARKER2 + ":").length());
        //渲染Freemarker
        Renderer render = RenderFactory.create(RenderType.FREEMARKER).target(location);
        if (str.length > 1)
            render.layout(str[1]);
        render.render(context.getWriter(), context.getModel());
        //	        this.context.getWriter().flush();
        return;
    } else if (re.startsWith(RenderType.VELOCITY + ":") || re.startsWith(RenderType.VELOCITY2 + ":") || re.endsWith("." + RenderType.VELOCITY2)) {
        String[] str = re.split("@");
        re = str[0];
        String location = re;
        if (re.startsWith(RenderType.VELOCITY + ":"))
            location = re.substring((RenderType.VELOCITY + ":").length());
        else if (re.startsWith(RenderType.VELOCITY2 + ":"))
            location = re.substring((RenderType.VELOCITY2 + ":").length());
        //渲染Velocity
        Renderer render = RenderFactory.create(RenderType.VELOCITY).target(location);
        if (str.length > 1)
            render.layout(str[1]);
        render.render(context.getWriter(), context.getModel());
        //	        this.context.getWriter().flush();
        return;
    } else {
        List<ResultConfigBean> results = this.context.getActionConfigBean().getResult();
        if (results == null || results.size() == 0) {
            this.context.getWriter().print(retn);
            //				this.context.getWriter().flush();
            return;
        }
        boolean isOut = true;
        for (ResultConfigBean r : results) {
            if (!"_props_".equals(r.getName()) && !r.getName().equals(re) && !"".equals(re)) {
                continue;
            }
            isOut = false;
            String type = r.getType();
            String location = r.getLocation();
            if (RenderType.REDIRECT.equalsIgnoreCase(type)) {
                this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));
                return;
            } else if (RenderType.FORWARD.equalsIgnoreCase(type) || RenderType.JSP.equalsIgnoreCase(type)) {
                //渲染JSP
                String[] str = location.split("@");
                JSPRendererImpl render = new JSPRendererImpl();
                render.setContext(context);
                if (str.length > 1)
                    render.layout(str[1]);
                render.target(str[0]).render(context.getWriter(), context.getModel());
                return;
            } else if (RenderType.FREEMARKER.equalsIgnoreCase(type) || RenderType.FREEMARKER2.equalsIgnoreCase(type)) {
                //渲染Freemarker
                String[] str = location.split("@");
                Renderer render = RenderFactory.create(RenderType.FREEMARKER).target(str[0]);
                if (str.length > 1)
                    render.layout(str[1]);
                render.render(context.getWriter(), context.getModel());
                return;
            } else if (RenderType.VELOCITY.equalsIgnoreCase(type) || RenderType.VELOCITY2.equalsIgnoreCase(type)) {
                //渲染Velocity
                String[] str = location.split("@");
                Renderer render = RenderFactory.create(RenderType.VELOCITY).target(str[0]);
                if (str.length > 1)
                    render.layout(str[1]);
                render.render(context.getWriter(), context.getModel());
                return;
            } else if (RenderType.ACTION.equalsIgnoreCase(type)) {
                // ACTION 重定向
                handleActionRedirect(context, location, baseUrl);
                return;
            } else if (RenderType.OUT.equalsIgnoreCase(type) || location.trim().length() == 0) {
                this.context.getWriter().print(location);
                return;
            }
        }
        if (isOut) {
            this.context.getWriter().print(retn);
        //				this.context.getWriter().flush();
        }
    }
}
Also used : ServletContextProxy(org.eweb4j.mvc.ServletContextProxy) ServletOutputStream(javax.servlet.ServletOutputStream) ZipEntry(java.util.zip.ZipEntry) HttpServletResponse(javax.servlet.http.HttpServletResponse) Method(java.lang.reflect.Method) CookieProxy(org.eweb4j.mvc.CookieProxy) XMLWriter(org.eweb4j.util.xml.XMLWriter) FileInputStream(java.io.FileInputStream) Field(java.lang.reflect.Field) HttpSessionProxy(org.eweb4j.mvc.HttpSessionProxy) ZipOutputStream(java.util.zip.ZipOutputStream) ResultConfigBean(org.eweb4j.mvc.config.bean.ResultConfigBean) JSPRendererImpl(org.eweb4j.mvc.view.JSPRendererImpl) Renderer(org.eweb4j.mvc.view.Renderer) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) UploadFile(org.eweb4j.mvc.upload.UploadFile) File(java.io.File)

Example 73 with Method

use of java.lang.reflect.Method in project eweb4j-framework by laiweiwei.

the class ActionExecution method execute.

/**
	 * 执行Action
	 * 
	 * @throws Exception
	 */
public void execute() throws Exception {
    // 实例化pojo
    initPojo();
    // IOC注入对象到pojo中
    injectIocBean();
    String methodName = this.context.getActionConfigBean().getMethod();
    Method[] methods = ru.getMethods(methodName);
    if (methods == null || methods.length == 0)
        return;
    method = this.getFirstMethd(methods);
    if (method == null)
        return;
    //		Consumes cons = method.getAnnotation(Consumes.class);
    boolean hasConsumes = JAXWSUtil.hasConsumes(method);
    if (hasConsumes) {
        String[] cts = ConsumesUtil.getConsumesValue(method);
        for (String ct : cts) {
            if ("json".equals(ct) || MIMEType.JSON.equals(ct)) {
                String[] jss = this.context.getQueryParamMap().get("_json_data_");
                if (jss != null) {
                    for (String json : jss) {
                        Map<String, Object> map;
                        try {
                            map = CommonUtil.parse(json, Map.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                            break;
                        }
                        for (Iterator<Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext(); ) {
                            Entry<String, Object> e = it.next();
                            String key = e.getKey();
                            String val = String.valueOf(e.getValue());
                            //继续解析,如果解析成功说明是多级的json格式,最后将其平展开来
                            try {
                                Map<String, Object> subMap = CommonUtil.parse(val, Map.class);
                                for (Iterator<Entry<String, Object>> subIt = subMap.entrySet().iterator(); subIt.hasNext(); ) {
                                    Entry<String, Object> subE = subIt.next();
                                    String subKey = subE.getKey();
                                    String subVal = String.valueOf(subE.getValue());
                                    String newKey = key + "." + subKey;
                                    try {
                                        Map<String, Object> subSubMap = CommonUtil.parse(subVal, Map.class);
                                        for (Iterator<Entry<String, Object>> subSubIt = subSubMap.entrySet().iterator(); subSubIt.hasNext(); ) {
                                            Entry<String, Object> subSubE = subSubIt.next();
                                            String subSubKey = subSubE.getKey();
                                            String subSubVal = String.valueOf(subSubE.getValue());
                                            String newSubKey = newKey + "." + subSubKey;
                                            assemJsonData(newSubKey, subSubVal);
                                        }
                                    } catch (Exception ex2) {
                                        assemJsonData(newKey, subVal);
                                    }
                                }
                            } catch (Exception ex) {
                                assemJsonData(key, val);
                            }
                        }
                    }
                }
            }
        }
    }
    // 注入框架mvc action 上下文环境
    this.injectActionCxt2Pojo(this.ru);
    //		if (IAction.class.isAssignableFrom(this.actionObject.getClass())) {
    //			// struts2风格
    //			IAction action = (IAction) actionObject;
    //			action.init(this.context);
    //			retn = action.execute();
    //			// 对Action执行返回结果的处理
    //			this.handleResult();
    //			
    //			return ;
    //		}
    // 执行验证器
    this.handleValidator();
    try {
        // 注入mvc action 请求参数
        ParamUtil.injectParam(this.context, this.ru, null);
        /* 方法体内的前置拦截器执行  */
        Before before = method.getAnnotation(Before.class);
        if (before != null) {
            InterExecution before_interExe = new InterExecution("before", context);
            before_interExe.execute(before.value());
            if (before_interExe.getError() != null) {
                before_interExe.showErr();
                return;
            }
        }
        // execute the action method
        excuteMethod(methodName);
        /* 方法体内的后置拦截器执行  */
        After after = method.getAnnotation(After.class);
        if (after != null) {
            // 后置拦截器
            InterExecution after_interExe = new InterExecution("after", context);
            after_interExe.execute(after.value());
            if (after_interExe.getError() != null) {
                after_interExe.showErr();
                return;
            }
        }
        /* 外部配置的后置拦截器后执行 */
        // 7.后置拦截器
        InterExecution after_interExe = new InterExecution("after", this.context);
        if (after_interExe.findAndExecuteInter()) {
            after_interExe.showErr();
            return;
        }
        // 对Action执行返回结果的处理
        this.handleResult();
    } catch (Exception e) {
        throw e;
    }
}
Also used : Before(org.eweb4j.mvc.interceptor.Before) Method(java.lang.reflect.Method) IOException(java.io.IOException) ZipEntry(java.util.zip.ZipEntry) Entry(java.util.Map.Entry) InterExecution(org.eweb4j.mvc.interceptor.InterExecution) After(org.eweb4j.mvc.interceptor.After) Map(java.util.Map) HashMap(java.util.HashMap)

Example 74 with Method

use of java.lang.reflect.Method in project eweb4j-framework by laiweiwei.

the class ActionExecution method injectActionCxt2Pojo.

private void injectActionCxt2Pojo(ReflectUtil ru) throws Exception {
    HttpServletRequest req = this.context.getRequest();
    HttpServletResponse res = this.context.getResponse();
    PrintWriter out = this.context.getWriter();
    HttpSession session = this.context.getSession();
    ActionProp actionProp = this.context.getActionProp();
    QueryParams queryParams = this.context.getQueryParams();
    for (String n : ru.getFieldsName()) {
        Method m = ru.getSetter(n);
        if (m == null)
            continue;
        Class<?> clazz = m.getParameterTypes()[0];
        if (Context.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), this.context);
        } else if (HttpServletRequest.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), req);
        } else if (HttpServletResponse.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), res);
        } else if (PrintWriter.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), out);
        } else if (ServletOutputStream.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), this.context.getOut());
        } else if (HttpSession.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), session);
        } else if (ActionProp.class.isAssignableFrom(clazz)) {
            if (actionProp == null)
                actionProp = new ActionProp(clazz.getName());
            this.context.setActionProp(actionProp);
            m.invoke(ru.getObject(), actionProp);
        } else if (QueryParams.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), queryParams);
        } else if (Validation.class.isAssignableFrom(clazz)) {
            m.invoke(ru.getObject(), this.context.getValidation());
        } else {
            /* 如果找不到注入的类型,则尝试从IOC容器获取 */
            Object obj = IOC.getBean(n);
            if (obj != null)
                m.invoke(ru.getObject(), obj);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) Method(java.lang.reflect.Method) PrintWriter(java.io.PrintWriter)

Example 75 with Method

use of java.lang.reflect.Method 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)

Aggregations

Method (java.lang.reflect.Method)8797 Test (org.junit.Test)1772 InvocationTargetException (java.lang.reflect.InvocationTargetException)1084 ArrayList (java.util.ArrayList)665 Field (java.lang.reflect.Field)611 IOException (java.io.IOException)549 HashMap (java.util.HashMap)352 Map (java.util.Map)290 List (java.util.List)275 PropertyDescriptor (java.beans.PropertyDescriptor)253 Annotation (java.lang.annotation.Annotation)212 Type (java.lang.reflect.Type)202 HashSet (java.util.HashSet)199 File (java.io.File)173 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)170 BeanInfo (java.beans.BeanInfo)166 ParameterizedType (java.lang.reflect.ParameterizedType)132 Constructor (java.lang.reflect.Constructor)131 SimpleBeanInfo (java.beans.SimpleBeanInfo)128 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)128