Search in sources :

Example 16 with Context

use of org.nutz.lang.util.Context in project nutz by nutzam.

the class NutServlet method service.

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (!Mvcs.DISABLE_X_POWERED_BY)
        resp.setHeader("X-Powered-By", Mvcs.X_POWERED_BY);
    String markKey = "nutz_ctx_mark";
    Integer mark = (Integer) req.getAttribute(markKey);
    if (mark != null) {
        req.setAttribute(markKey, mark + 1);
    } else {
        req.setAttribute(markKey, 0);
    }
    ServletContext prCtx = Mvcs.getServletContext();
    Mvcs.setServletContext(sc);
    String preName = Mvcs.getName();
    Context preContext = Mvcs.resetALL();
    try {
        if (sp != null)
            req = sp.filter(req, resp, sc);
        Mvcs.set(selfName, req, resp);
        if (!handler.handle(req, resp))
            resp.sendError(404);
    } finally {
        Mvcs.resetALL();
        //仅当forward/incule时,才需要恢复之前设置
        if (mark != null) {
            Mvcs.setServletContext(prCtx);
            Mvcs.set(preName, req, resp);
            Mvcs.ctx().reqCtx(preContext);
            if (mark == 0) {
                req.removeAttribute(markKey);
            } else {
                req.setAttribute(markKey, mark - 1);
            }
        } else {
            Mvcs.setServletContext(null);
            Mvcs.ctx().removeReqCtx();
        }
    }
}
Also used : ServletContext(javax.servlet.ServletContext) Context(org.nutz.lang.util.Context) ServletContext(javax.servlet.ServletContext)

Example 17 with Context

use of org.nutz.lang.util.Context in project nutz by nutzam.

the class Sockets method localListen.

/**
     * 监听本地某一个端口,根据用户输入的命令的不同,执行不同的操作
     * <p>
     * 当然,你如果想让一个过程处理多种命令,请给的 key 前用 "REGEX:" 作为前缀,后面用一个正则表达式 来表示你的你要的匹配的命令 <br>
     * "REGEX:!" 开头的,表示后面的正则表达式是一个命令过滤,所有没有匹配上的命令都会被处理
     * 
     * @param port
     *            要监听的端口
     * @param actions
     *            动作执行类映射表
     * @param service
     *            线程池的实现类
     */
@SuppressWarnings("rawtypes")
public static void localListen(int port, Map<String, SocketAction> actions, ExecutorService service, Class<? extends SocketAtom> klass) {
    try {
        // 建立动作映射表
        SocketActionTable saTable = new SocketActionTable(actions);
        // 初始化 socket 接口
        final ServerSocket server;
        try {
            server = new ServerSocket(port);
        } catch (IOException e1) {
            throw Lang.wrapThrow(e1);
        }
        if (log.isInfoEnabled())
            log.infof("Local socket is up at :%d with %d action ready", port, actions.size());
        final Context context = Lang.context();
        context.set("stop", false);
        /*
             * 启动一个守护线程,判断是否该关闭 socket 服务
             */
        (new Thread() {

            @Override
            public void run() {
                setName("Nutz.Sockets monitor thread");
                while (true) {
                    try {
                        Thread.sleep(1000);
                        if (context.getBoolean("stop")) {
                            try {
                                server.close();
                            } catch (Throwable e) {
                            }
                            return;
                        }
                    } catch (Throwable e) {
                    }
                }
            }
        }).start();
        /*
             * 准备 SocketAtom 的生成器
             */
        Borning borning = Mirror.me(klass).getBorningByArgTypes(Context.class, Socket.class, SocketActionTable.class);
        if (borning == null) {
            log.error("boring == null !!!!");
            return;
        }
        /*
             * 进入监听循环
             */
        while (!context.getBoolean("stop")) {
            try {
                if (log.isDebugEnabled())
                    log.debug("Waiting for new socket");
                Socket socket = server.accept();
                if (context.getBoolean("stop")) {
                    Sockets.safeClose(socket);
                    // 监护线程也许还是睡觉,还没来得及关掉哦,所以自己检查一下
                    break;
                }
                if (log.isDebugEnabled())
                    log.debug("accept a new socket, create new SocketAtom to handle it ...");
                Runnable runnable = (Runnable) borning.born(new Object[] { context, socket, saTable });
                service.execute(runnable);
            } catch (Throwable e) {
                log.info("Throwable catched!! maybe ask to exit", e);
            }
        }
        if (!server.isClosed()) {
            try {
                server.close();
            } catch (Throwable e) {
            }
        }
        log.info("Seem stop signal was got, wait 15 for all running thread");
        try {
            service.shutdown();
            service.awaitTermination(15, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
        }
        try {
            service.shutdownNow();
        } catch (Throwable e2) {
        }
    } catch (RuntimeException e) {
        throw e;
    } finally {
        if (log.isInfoEnabled())
            log.info("Stop services ...");
        service.shutdown();
    }
    if (log.isInfoEnabled())
        log.infof("Local socket is down for :%d", port);
}
Also used : Context(org.nutz.lang.util.Context) Borning(org.nutz.lang.born.Borning) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 18 with Context

use of org.nutz.lang.util.Context in project nutz by nutzam.

the class Mvcs method resetALL.

// ==================================================================
/**
     * 重置当前线程所持有的对象
     */
public static Context resetALL() {
    Context context = reqt();
    NAME.set(null);
    ctx().removeReqCtx();
    return context;
}
Also used : SessionIocContext(org.nutz.mvc.ioc.SessionIocContext) IocContext(org.nutz.ioc.IocContext) ServletContext(javax.servlet.ServletContext) Context(org.nutz.lang.util.Context)

Example 19 with Context

use of org.nutz.lang.util.Context in project nutz by nutzam.

the class NutFilter method doFilter.

public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException {
    if (!Mvcs.DISABLE_X_POWERED_BY)
        ((HttpServletResponse) resp).setHeader("X-Powered-By", Mvcs.X_POWERED_BY);
    ServletContext prCtx = Mvcs.getServletContext();
    Mvcs.setServletContext(sc);
    if (proxyFilter != null) {
        proxyFilter.doFilter(req, resp, chain);
        return;
    }
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    String matchUrl = request.getServletPath() + Strings.sBlank(request.getPathInfo());
    String markKey = "nutz_ctx_mark";
    Integer mark = (Integer) req.getAttribute(markKey);
    if (mark != null) {
        req.setAttribute(markKey, mark + 1);
    } else {
        req.setAttribute(markKey, 0);
    }
    String preName = Mvcs.getName();
    Context preContext = Mvcs.resetALL();
    try {
        if (sp != null)
            request = sp.filter(request, response, Mvcs.getServletContext());
        Mvcs.set(this.selfName, request, response);
        if (!isExclusion(matchUrl)) {
            if (handler.handle(request, response))
                return;
        }
        nextChain(request, response, chain);
    } finally {
        //仅当forward/incule时,才需要恢复之前设置
        if (mark != null) {
            Mvcs.ctx().reqCtx(preContext);
            Mvcs.setServletContext(prCtx);
            Mvcs.set(preName, request, response);
            if (mark == 0) {
                req.removeAttribute(markKey);
            } else {
                req.setAttribute(markKey, mark - 1);
            }
        } else {
            Mvcs.set(null, null, null);
            Mvcs.ctx().removeReqCtx();
            Mvcs.setServletContext(null);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletContext(javax.servlet.ServletContext) Context(org.nutz.lang.util.Context) ServletContext(javax.servlet.ServletContext) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 20 with Context

use of org.nutz.lang.util.Context in project nutz by nutzam.

the class NutMvcContext method reqCtx.

public Context reqCtx() {
    Context ctx = reqThreadLocal.get();
    if (ctx == null) {
        ctx = Lang.context();
        reqThreadLocal.set(ctx);
    }
    return ctx;
}
Also used : SimpleContext(org.nutz.lang.util.SimpleContext) Context(org.nutz.lang.util.Context)

Aggregations

Context (org.nutz.lang.util.Context)40 Test (org.junit.Test)29 SimpleSpeedTest (org.nutz.el.speed.SimpleSpeedTest)24 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)3 ServletContext (javax.servlet.ServletContext)3 El (org.nutz.el.El)3 Map (java.util.Map)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 BigDecimal (java.math.BigDecimal)1 ServerSocket (java.net.ServerSocket)1 Socket (java.net.Socket)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1 Ignore (org.junit.Ignore)1 ElException (org.nutz.el.ElException)1 Issue293 (org.nutz.el.issue.Issue293)1 Issue303 (org.nutz.el.issue.Issue303)1