⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hambclientmessagehandler.java

📁 详细说明怎么使用mina开发应用程序-mina develop examples detailing how to use the development and application of pro
💻 JAVA
字号:
package com.liantuo.hamburger.handler.cli;

import java.io.IOException;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import org.apache.mina.handler.demux.DemuxingIoHandler;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.liantuo.hamburger.ApplicationBeanUtils;
import com.liantuo.hamburger.exception.ResSrvIsUnreachableException;
import com.liantuo.hamburger.exception.UnknowUserOrWrongPswExcption;
import com.liantuo.hamburger.exception.WaitsForReplyIsTimeOutException;
import com.liantuo.hamburger.exception.request.CmdOutOfPermissionException;
import com.liantuo.hamburger.exception.result.NoSessionException;
import com.liantuo.hamburger.exception.result.SessionIsClosedException;
import com.liantuo.hamburger.message.AuthAndQueryMessage;
import com.liantuo.hamburger.message.DataMessage;
import com.liantuo.hamburger.message.InfoReplyMessage;
import com.liantuo.hamburger.message.InfoRequestMessage;
import com.liantuo.hamburger.message.LoginRequestMessage;
import com.liantuo.hamburger.message.RequestRefusedMessage;
import com.liantuo.hamburger.util.HambLogger;
import com.liantuo.hamburger.util.SessionUtil;

public class HambClientMessageHandler extends DemuxingIoHandler {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(HambClientMessageHandler.class);

    private static int count;

    public HambClientMessageHandler() {
        super();
        this.registerHandler();
    }

    // inherit from super
    public void messageReceived(IoSession session, Object message) throws Exception {
        // 加入了处理数据库Session的代码,需要重构
        SessionFactory sessionFactory = lookupDBSessionFactory();
        Session dbSession = null;
        boolean participate = false;

        if (SessionUtil.getSrvSession(session).isClosing()) {
            throw new SessionIsClosedException();
        }

        // single session mode
        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            // Do not modify the Session: just set the participate flag.
            participate = true;
        } else {
            logger.debug("Opening single Hibernate Session when receive message");
            dbSession = getDBSession(sessionFactory);
            TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(dbSession));
        }

        try {
            super.messageReceived(session, message);
        } finally {
            if (!participate) {
                // single session mode
                TransactionSynchronizationManager.unbindResource(sessionFactory);
                logger.debug("Closing single Hibernate Session after receive message ");
                try {
                    closeDBSession(dbSession, sessionFactory);
                } catch (RuntimeException ex) {
                    logger.error("Unexpected exception on closing Hibernate Session", ex);
                }

            }
        }

        // add to flow-log
        try {
            String log = ">P> " + SessionUtil.getSessionInfo(session)
                    + message.toString().substring(message.toString().lastIndexOf("."));
            if (message instanceof DataMessage) {
                try {
                    log += " - " + ((DataMessage) message).getTextData().substring(0, 20);
                } catch (RuntimeException e) {
                    log += " - " + ((DataMessage) message).getTextData();
                }
            } else if (message instanceof AuthAndQueryMessage) {
                try {
                    log += " - " + ((AuthAndQueryMessage) message).getCmdText().substring(0, 20);
                } catch (RuntimeException e) {
                    log += " - " + ((AuthAndQueryMessage) message).getCmdText();
                }
            }
            HambLogger.getFlowLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session)).log(log);
        } catch (RuntimeException e) {
            try {
                HambLogger.getFlowLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session)).log(
                        e.getClass().toString());
            } catch (RuntimeException e1) {
            }
        }

    }

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        int fid = SessionUtil.getFunctionId(session);
        if (cause instanceof CmdOutOfPermissionException) {
            DataMessage reply = new DataMessage(fid, "无使用权限:" + cause.getMessage());
            session.write(reply);
        } else if (cause instanceof NoSessionException) {
            DataMessage reply = new DataMessage(fid, "无可用配置,请检查是否已放入配置.");
            session.write(reply);
        } else if (cause instanceof SessionIsClosedException) {
            DataMessage reply = new DataMessage(fid, "连接被重置,请重新登录.");
            session.write(reply).join();
            SessionUtil.killSession(session);
        } else if (cause instanceof WaitsForReplyIsTimeOutException) {
            DataMessage reply = new DataMessage(fid, "配置繁忙中,请重试.");
            session.write(reply);
        } else if (cause instanceof ResSrvIsUnreachableException) {
            RequestRefusedMessage refused = new RequestRefusedMessage();
            refused.setErrorType(RequestRefusedMessage.ERROR_TYPE_LOGIN);
            refused.setErrorMsg("连接超时,请稍候再试.");
            session.write(refused);
        } else if (cause instanceof UnknowUserOrWrongPswExcption) {
            RequestRefusedMessage refused = new RequestRefusedMessage();
            refused.setErrorType(RequestRefusedMessage.ERROR_TYPE_LOGIN);
            refused.setErrorMsg("用户名或密码错误,请重试.");
            session.write(refused);
        }
        // just closed
        else if (cause instanceof ProtocolDecoderException || cause instanceof IOException) {
            if (SessionUtil.getSrvSession(session) != null && !SessionUtil.getSrvSession(session).isClosing()) {
                SessionUtil.getSrvSession(session).close();
                logger.info("CLI:Srv is disconnected by client for EX:" + cause.getMessage());
            }
            session.close();
            logger.info("CLI:The " + SessionUtil.getSessionInfo(session) + "th. connection is cloSed for EX.");
        } else if (cause instanceof org.hibernate.HibernateException
                || cause instanceof org.springframework.orm.hibernate3.HibernateSystemException) {
            logger.warn("CLI:HibernateException  :" + cause.getClass());
            cause.printStackTrace();
            session.write(new DataMessage(fid, "保存数据时出现异常情况,请检查数据是否已正确更新"));
        } else {
            logger.warn("CLI:EX ****************  :" + cause.getClass());
            cause.printStackTrace();
            session.write(new DataMessage(fid, "系统繁忙,请稍后再试"));
        }

        // add to flow-log
        try {
            HambLogger.getFlowLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session)).log(
                    " P-EX " + SessionUtil.getSessionInfo(session)
                            + cause.getClass().toString().substring(cause.getClass().toString().lastIndexOf(".")));
        } catch (RuntimeException e) {
            try {
                HambLogger.getFlowLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session)).log(
                        " P-EX " + SessionUtil.getSessionInfo(session)
                                + e.getClass().toString().substring(cause.getClass().toString().lastIndexOf(".")));
            } catch (RuntimeException e1) {
            }
        }

        // count exceptions
        try {
            HambLogger.getExceptionLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session), cause).log(
                    SessionUtil.getSessionInfo(session) + cause.toString());
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);

        // add to flow-log
        try {
            String log = "<P< " + SessionUtil.getSessionInfo(session)
                    + message.toString().substring(message.toString().lastIndexOf("."));
            if (message instanceof DataMessage) {
                try {
                    log += " - " + ((DataMessage) message).getTextData().substring(0, 20);
                } catch (RuntimeException e) {
                    log += " - " + ((DataMessage) message).getTextData();
                }
            }
            HambLogger.getFlowLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session)).log(log);
        } catch (RuntimeException e) {
            try {
                HambLogger.getFlowLogger(SessionUtil.getUser(session), SessionUtil.getAgecy(session)).log(
                        e.getClass().toString());
            } catch (RuntimeException e1) {
            }
        }

        if (message instanceof DataMessage) {
            DataMessage dataMessage = ((DataMessage) message);
            String host = dataMessage.getHostData() == null ? "NULL" : new String(dataMessage.getHostData());
            String text = dataMessage.getTextData() == null ? "NULL" : dataMessage.getTextData();
            String parse = dataMessage.getParseData() == null ? "NULL" : dataMessage.getParseData();
            logger.debug("\nCLI:" + SessionUtil.getSessionInfo(session) + "<<<:\n-HOST:" + host + "\n-TEXT:" + text
                    + "\n-PARSE:" + parse);
        }
        // infoReply
        else if (message instanceof InfoReplyMessage) {
            InfoReplyMessage info = (InfoReplyMessage) message;
            logger.debug("\n>>>por" + SessionUtil.getSessionInfo(session) + ":" + info.getInfoType() + "\n"
                    + info.getXml());
        }
    }

    public void sessionClosed(IoSession session) throws Exception {
        if (SessionUtil.getSrvSession(session) != null && !SessionUtil.getSrvSession(session).isClosing()) {
            SessionUtil.getSrvSession(session).close();
            logger.info("CLI:Srv is disconnected by client");
        }

        if ((SessionUtil.getFromWhere(session) == LoginRequestMessage.FROMWHERE_BLACKSCREEN || SessionUtil
                .getFromWhere(session) == LoginRequestMessage.FROMWHERE_ETERMAPP)
                && SessionUtil.isKilled(session)) {
            SessionUtil.getLiveUsers(session).remove(SessionUtil.getUser(session).getCodeName());
        }

        logger.info("CLI:The " + SessionUtil.getSessionInfo(session) + "th. connection is clOsed.");

        if (session.getAttributeKeys() != null && session.getAttributeKeys().size() > 0) {
            Iterator it = session.getAttributeKeys().iterator();
            while (it.hasNext()) {
                session.removeAttribute((String) it.next());
            }
        }

        super.sessionClosed(session);
    }

    public void sessionCreated(IoSession session) throws Exception {
        SessionUtil.setSessionInfo(session, String.valueOf(count++));
        SessionUtil.markCliSession(session);
        super.sessionCreated(session);
        logger.info("CLI:" + SessionUtil.getSessionInfo(session) + "READER IDLE 300s THEN AUTO IG.");
        session.setIdleTime(IdleStatus.READER_IDLE, 300);
        session.setIdleTime(IdleStatus.WRITER_IDLE, 32);
    }

    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        // check srv-connection
        if (SessionUtil.getSrvSession(session).isClosing()) {
            throw new SessionIsClosedException();
        }

        // auto i
        if (status == IdleStatus.READER_IDLE
                && (SessionUtil.getPnrEditBuffer(session) != null || SessionUtil.getBookInformation(session) != null)) {
            SessionUtil.setPnrEditBuffer(session, null);
            SessionUtil.setBookInfomation(session, null);
            SessionUtil.setPnrAutoIged(session, true);
            logger.info("CLI: AUTO IG. AFTER IDLE FOR 5Min.");
        }
    }

    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
    }

    /**
     * register the certain handler to parse the certain message which is
     * received
     */
    private void registerHandler() {
        this.addMessageHandler(LoginRequestMessage.class, new LoginRequestMessageHandler());
        this.addMessageHandler(DataMessage.class, new ClientDataMessageHandler());
        this.addMessageHandler(InfoRequestMessage.class, new ClientInfoRequestMessageHandler());
        this.addMessageHandler(AuthAndQueryMessage.class, new WebRequestMessageHandler());
        this.addMessageHandler(InfoReplyMessage.class, new InfoReplyMessageHandler());
    }

    // @TODO 以下是处理数据库session的代码,需要重构

    protected SessionFactory lookupDBSessionFactory() {
        if (logger.isDebugEnabled()) {
            logger.debug("Using SessionFactory '" + getDBSessionFactoryBeanName() + "' for HambCliantMessageHandler");
        }

        return (SessionFactory) ApplicationBeanUtils.getBean(getDBSessionFactoryBeanName());
    }

    protected void closeDBSession(Session session, SessionFactory sessionFactory) {
        SessionFactoryUtils.releaseSession(session, sessionFactory);
    }

    protected Session getDBSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
        session.setFlushMode(FlushMode.NEVER);
        return session;
    }

    protected String getDBSessionFactoryBeanName() {
        return dbSessionFactoryBeanName;
    }

    public static final String DEFAULT_DB_SESSION_FACTORY_BEAN_NAME = "sessionFactory";

    private String dbSessionFactoryBeanName = DEFAULT_DB_SESSION_FACTORY_BEAN_NAME;

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -