com.farsunset.cim.handler.BindHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.farsunset.cim.handler.BindHandler.java

Source

/**
 * Copyright 2013-2023 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.farsunset.cim.handler;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.farsunset.cim.push.SystemMessagePusher;
import com.farsunset.cim.sdk.server.constant.CIMConstant;
import com.farsunset.cim.sdk.server.handler.CIMRequestHandler;
import com.farsunset.cim.sdk.server.model.Message;
import com.farsunset.cim.sdk.server.model.ReplyBody;
import com.farsunset.cim.sdk.server.model.SentBody;
import com.farsunset.cim.sdk.server.session.CIMSession;
import com.farsunset.cim.sdk.server.session.DefaultSessionManager;
import com.farsunset.cim.util.ContextHolder;
import com.farsunset.cim.util.MessageDispatcher;
import com.farsunset.cim.util.StringUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import bean.PackGMessage;
import bean.PackPMessage;
import service.MessageService;

/**
 * ?
 * 
 */
public class BindHandler implements CIMRequestHandler {

    protected final Logger logger = Logger.getLogger(BindHandler.class);
    private MessageService messageService = new MessageService();

    public ReplyBody process(CIMSession newSession, SentBody message) {
        DefaultSessionManager sessionManager = ((DefaultSessionManager) ContextHolder.getBean("CIMSessionManager"));

        ReplyBody reply = new ReplyBody();
        reply.setCode(CIMConstant.ReturnCode.CODE_200);
        try {

            String account = message.get("account");
            newSession.setGid(StringUtil.getUUID());
            newSession.setAccount(account);
            newSession.setDeviceId(message.get("deviceId"));
            newSession.setHost(InetAddress.getLocalHost().getHostAddress());
            newSession.setChannel(message.get("channel"));
            newSession.setDeviceModel(message.get("device"));
            newSession.setClientVersion(message.get("version"));
            newSession.setSystemVersion(message.get("osVersion"));
            newSession.setBindTime(System.currentTimeMillis());
            newSession.setPackageName(message.get("packageName"));
            /**
             * ????
             */
            CIMSession oldSession = sessionManager.get(account);

            // ?????

            if (newSession.fromOtherDevice(oldSession)) {
                sendForceOfflineMessage(oldSession, account, newSession.getDeviceModel());
            }

            //??
            if (newSession.equals(oldSession)) {

                oldSession.setStatus(CIMSession.STATUS_ENABLED);
                sessionManager.update(oldSession);
                reply.put("sid", oldSession.getGid());
                return reply;
            }

            closeQuietly(oldSession);

            //
            newSession.setBindTime(System.currentTimeMillis());
            newSession.setHeartbeat(System.currentTimeMillis());

            sessionManager.add(newSession);

        } catch (Exception e) {
            reply.setCode(CIMConstant.ReturnCode.CODE_500);
            e.printStackTrace();
        }
        JsonObject json = new JsonObject();
        Gson gson = new Gson();
        List<PackPMessage> pmessage = messageService.getPrivateMessage(Integer.valueOf(message.get("account")));
        List<PackPMessage> privateMessages = new ArrayList<PackPMessage>();
        List<PackPMessage> validateMessages = new ArrayList<PackPMessage>();
        for (PackPMessage pp : pmessage) {
            if (pp.getMessages().get(0).getType().equals("3")) {
                validateMessages.add(pp);
            } else {
                privateMessages.add(pp);
            }
        }
        List<PackGMessage> gmessage = messageService.getGroupMessage(Integer.valueOf(message.get("account")));
        json.addProperty("private", gson.toJson(privateMessages));
        json.addProperty("validate", gson.toJson(validateMessages));
        json.addProperty("group", gson.toJson(gmessage));
        if (validateMessages.size() > 0 || privateMessages.size() > 0 || gmessage.size() > 0) {
            Message mm = new Message();
            mm.setContent(json.toString());
            mm.setAction("4");
            mm.setSender("all");
            mm.setReceiver(message.get("account"));
            MessageDispatcher.execute(mm, "127.0.0.1");
            mm.setTitle("?");
        }

        logger.debug("bind :account:" + message.get("account") + "-----------------------------" + reply.getCode());
        reply.put("sid", newSession.getGid());
        return reply;
    }

    private void sendForceOfflineMessage(CIMSession oldSession, String account, String deviceModel) {

        Message msg = new Message();
        msg.setMid(String.valueOf(System.currentTimeMillis()));
        msg.setAction(CIMConstant.MessageAction.ACTION_999);// ?
        msg.setReceiver(account);
        msg.setContent(deviceModel);

        closeQuietly(oldSession, msg);

        if (!oldSession.isLocalhost()) {
            ContextHolder.getBean(SystemMessagePusher.class).push(msg);
        }
    }

    //??
    private void closeQuietly(CIMSession oldSession) {
        if (oldSession != null && oldSession.isConnected()) {
            oldSession.removeAttribute(CIMConstant.SESSION_KEY);
            oldSession.closeNow();
        }

    }

    //????
    private void closeQuietly(CIMSession oldSession, Message msg) {
        if (oldSession.isConnected()) {
            oldSession.write(msg);
            oldSession.removeAttribute(CIMConstant.SESSION_KEY);
            oldSession.closeNow();
        }
    }

}