Search in sources :

Example 1 with RestException

use of org.axe.exception.RestException in project Axe by DongyuCai.

the class ReflectionUtil method invokeMethod.

/**
     * 调用方法
     */
public static Object invokeMethod(Object obj, Method method, Object... args) {
    Object result;
    method.setAccessible(true);
    try {
        MethodHandle mh = MethodHandles.lookup().unreflect(method);
        ArrayList<Object> argList = new ArrayList<>();
        argList.add(obj);
        if (args != null) {
            for (Object arg : args) {
                argList.add(arg);
            }
        }
        result = mh.invokeWithArguments(argList);
    } catch (Throwable cause) {
        LOGGER.error("invoke method failure,method : " + method + ", args : " + args, cause);
        if (cause instanceof RestException) {
            //Rest中断异常,需要返回前台异常信息
            throw (RestException) cause;
        } else if (cause instanceof RedirectorInterrupt) {
            //重定向中断,需要跳转
            throw (RedirectorInterrupt) cause;
        } else {
            throw new RuntimeException(cause);
        }
    }
    /*try {
			result = method.invoke(obj,args);
		} catch (IllegalAccessException e) {
			LOGGER.error("invoke method failure,method : "+method+", args : "+args,e);
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			LOGGER.error("invoke method failure,method : "+method+", args : "+args,e);
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			LOGGER.error("invoke method failure,method : "+method+", args : "+args,e);
			Throwable cause = e.getCause();
			if(cause != null){
				if(cause instanceof RestException){
					//Rest中断异常,需要返回前台异常信息
					throw (RestException)e.getCause();
				}else if(cause instanceof RedirectorInterrupt){
					//重定向中断,需要跳转
					throw (RedirectorInterrupt)e.getCause();
				}else{
					throw new RuntimeException(cause);
				}
			}else{
				throw new RuntimeException(e);
				
			}
		}*/
    return result;
}
Also used : ArrayList(java.util.ArrayList) RestException(org.axe.exception.RestException) MethodHandle(java.lang.invoke.MethodHandle) RedirectorInterrupt(org.axe.exception.RedirectorInterrupt)

Example 2 with RestException

use of org.axe.exception.RestException in project Axe by DongyuCai.

the class DispatcherServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) {
    String contentType = ContentType.APPLICATION_JSON.CONTENT_TYPE;
    String characterEncoding = CharacterEncoding.UTF_8.CHARACTER_ENCODING;
    List<Filter> doEndFilterList = null;
    try {
        //获取请求方法与请求路径
        String requestMethod = RequestUtil.getRequestMethod(request);
        String requestPath = RequestUtil.getRequestPath(request);
        if (requestPath != null && requestPath.equals("/favicon.ico")) {
            return;
        }
        //获取 Action 处理器
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if (handler != null) {
            //获取 Controller  类和 Bean 实例
            Class<?> controllerClass = handler.getControllerClass();
            Method actionMethod = handler.getActionMethod();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            contentType = handler.getContentType();
            characterEncoding = handler.getCharacterEncoding();
            //##1.创建你请求参数对象
            Param param;
            if (FormRequestHelper.isMultipart(request)) {
                //如果是文件上传
                param = FormRequestHelper.createParam(request, requestPath, handler.getMappingPath());
            } else {
                //如果不是
                param = AjaxRequestHelper.createParam(request, requestPath, handler.getMappingPath());
            }
            //                List<Object> actionParamList = this.convertRequest2RequestParam(actionMethod, param, request, response);
            //                param.setActionParamList(actionParamList);
            //##2.先执行Filter链
            List<Filter> filterList = handler.getFilterList();
            boolean doFilterSuccess = true;
            if (CollectionUtil.isNotEmpty(filterList)) {
                for (Filter filter : filterList) {
                    //被执行的Filter,都添加到end任务里
                    if (doEndFilterList == null) {
                        doEndFilterList = new ArrayList<>();
                    }
                    doEndFilterList.add(filter);
                    doFilterSuccess = filter.doFilter(request, response, param, handler);
                    //执行失败则跳出,不再往下进行
                    if (!doFilterSuccess)
                        break;
                }
            }
            //##3.执行Interceptor 列表
            List<Interceptor> interceptorList = handler.getInterceptorList();
            boolean doInterceptorSuccess = true;
            if (CollectionUtil.isNotEmpty(interceptorList)) {
                for (Interceptor interceptor : interceptorList) {
                    doInterceptorSuccess = interceptor.doInterceptor(request, response, param, handler);
                    if (!doInterceptorSuccess)
                        break;
                }
            }
            //##4.执行action
            if (doFilterSuccess && doInterceptorSuccess) {
                //调用 Action方法
                List<Object> actionParamList = this.convertRequest2RequestParam(actionMethod, param, request, response);
                Object result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, actionParamList.toArray());
                if (result != null) {
                    if (result instanceof View) {
                        handleViewResult((View) result, request, response);
                    } else if (result instanceof Data) {
                        handleDataResult((Data) result, response, handler);
                    } else {
                        Data data = new Data(result);
                        handleDataResult(data, response, handler);
                    }
                }
            }
        } else {
            //404
            throw new RestException(RestException.SC_NOT_FOUND, "404 Not Found");
        }
    } catch (RedirectorInterrupt e) {
        //被中断,跳转
        View view = new View(e.getPath());
        try {
            handleViewResult(view, request, response);
        } catch (Exception e1) {
            LOGGER.error("中断,跳转 error", e);
        }
    } catch (RestException e) {
        //需要返回前台信息的异常
        writeError(e.getStatus(), e.getMessage(), response, contentType, characterEncoding);
    } catch (Exception e) {
        LOGGER.error("server error", e);
        //500
        writeError(RestException.SC_INTERNAL_SERVER_ERROR, "500 server error", response, contentType, characterEncoding);
        try {
            //邮件通知
            MailHelper.errorMail(e);
        } catch (Exception e1) {
            LOGGER.error("mail error", e1);
        }
    } finally {
        //##5.执行Filter链各个节点的收尾工作
        if (CollectionUtil.isNotEmpty(doEndFilterList)) {
            for (Filter filter : doEndFilterList) {
                try {
                    filter.doEnd();
                } catch (Exception endEx) {
                    LOGGER.error("filter doEnd failed", endEx);
                }
            }
        }
    }
}
Also used : RestException(org.axe.exception.RestException) Handler(org.axe.bean.mvc.Handler) Data(org.axe.bean.mvc.Data) Method(java.lang.reflect.Method) View(org.axe.bean.mvc.View) ServletException(javax.servlet.ServletException) RestException(org.axe.exception.RestException) IOException(java.io.IOException) Filter(org.axe.interface_.mvc.Filter) RequestParam(org.axe.annotation.mvc.RequestParam) Param(org.axe.bean.mvc.Param) Interceptor(org.axe.interface_.mvc.Interceptor) RedirectorInterrupt(org.axe.exception.RedirectorInterrupt)

Example 3 with RestException

use of org.axe.exception.RestException in project Axe by DongyuCai.

the class TestFilter4 method doFilter.

@Override
public boolean doFilter(HttpServletRequest request, HttpServletResponse response, Param param, Handler handler) throws RestException {
    try {
        ServletInputStream in = request.getInputStream();
        byte[] data = new byte[1024];
        int len = 0;
        while ((len = in.read(data, 0, data.length)) > 0) {
            System.out.println("read:" + len);
        }
    } catch (Exception e) {
    }
    return true;
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) RestException(org.axe.exception.RestException)

Example 4 with RestException

use of org.axe.exception.RestException in project Axe by DongyuCai.

the class HomeController method refreshConfig.

@Request(value = "/refresh-config", method = RequestMethod.GET)
public void refreshConfig(@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) {
    String contextPath = request.getContextPath();
    ServletContext servletContext = request.getServletContext();
    try {
        HelperLoader.refresHelpers(servletContext);
    } catch (Exception e) {
        throw new RestException(e.getMessage());
    }
    StringBuilder html = new StringBuilder();
    html.append("<!DOCTYPE html>");
    html.append("<html>");
    html.append("<head>");
    html.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
    html.append("<title>axe save properties</title>");
    html.append("<script type=\"text/javascript\">");
    html.append("var number = 10;");
    html.append("");
    html.append("var int=self.setInterval(\"toHome()\",1000);");
    html.append("");
    html.append("function toHome(){");
    html.append("number = number-1;");
    html.append("document.getElementById(\"number\").innerHTML = number;");
    html.append("if(number <= 0){");
    html.append("window.clearInterval(int);");
    html.append("window.location = \"" + contextPath + "/axe?token=" + token + "\";");
    html.append("}");
    html.append("}");
    html.append("");
    html.append("</script>");
    html.append("</head>");
    html.append("<body>");
    html.append("<table width=\"100%\">");
    html.append("<tr><td align=\"right\">");
    if (ConfigHelper.getAxeSignIn()) {
        html.append("<a style=\"font-size: 15px;color: #AE0000\" href=\"" + contextPath + "/axe/sign-out?token=" + token + "\"><b>退出</b></a>");
    }
    html.append("&nbsp;<a style=\"font-size: 15px;color: #AE0000\" href=\"" + contextPath + "/axe?token=" + token + "\"><b>首页</b></a>");
    html.append("</td></tr>");
    html.append("<tr><td align=\"center\"><span id=\"number\">10</span>秒后自动跳转<a href=\"" + contextPath + "/axe?token=" + token + "\">/axe首页</a></td></tr>");
    html.append("<tr><td align=\"center\"><font size=\"28\"><b>刷新配置成功!</b></font></td></tr>");
    html.append("</table>");
    html.append("</body>");
    html.append("</html>");
    printHtml(response, html.toString());
}
Also used : RestException(org.axe.exception.RestException) ServletContext(javax.servlet.ServletContext) RestException(org.axe.exception.RestException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.axe.annotation.mvc.Request)

Example 5 with RestException

use of org.axe.exception.RestException in project Axe by DongyuCai.

the class TestController method getOne.

//==================== postman success ================//
@Request(value = "/getOne/{id}", method = RequestMethod.GET)
public Data getOne(@RequestParam("id") Long id, Param param) {
    //    	Data data = analysisParam(param);
    if (id == null) {
        throw new RestException(RestException.SC_BAD_REQUEST, "id不正确");
    }
    TestTable one = testService.get(id);
    Data data = new Data(one);
    return data;
}
Also used : RestException(org.axe.exception.RestException) Data(org.axe.bean.mvc.Data) TestTable(org.test.bean.TestTable) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.axe.annotation.mvc.Request)

Aggregations

RestException (org.axe.exception.RestException)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Request (org.axe.annotation.mvc.Request)2 Data (org.axe.bean.mvc.Data)2 RedirectorInterrupt (org.axe.exception.RedirectorInterrupt)2 IOException (java.io.IOException)1 MethodHandle (java.lang.invoke.MethodHandle)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 ServletContext (javax.servlet.ServletContext)1 ServletException (javax.servlet.ServletException)1 ServletInputStream (javax.servlet.ServletInputStream)1 RequestParam (org.axe.annotation.mvc.RequestParam)1 Handler (org.axe.bean.mvc.Handler)1 Param (org.axe.bean.mvc.Param)1 View (org.axe.bean.mvc.View)1 Filter (org.axe.interface_.mvc.Filter)1 Interceptor (org.axe.interface_.mvc.Interceptor)1 TestTable (org.test.bean.TestTable)1