All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gateway.invoke.gw.GWProxy Maven / Gradle / Ivy

package com.gateway.invoke.gw;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.app.common.exception.CodeException;
import com.app.common.thread.AsyncSeqThreadGroup;
import com.app.common.utils.Consts;
import com.gateway.connector.api.listener.SessionEvent;
import com.gateway.connector.api.listener.SessionListener;
import com.gateway.connector.proto.Format;
import com.gateway.connector.proto.Proto;
import com.gateway.connector.tcp.client.IMessage;
import com.gateway.invoke.AbstractApiProxy;
import com.gateway.invoke.filter.IFilterTopic;
import com.gateway.message.MessageWrapper;
import com.gateway.message.SystemMessage;
import com.gateway.notify.NotifyProxy;
import com.gateway.utils.JsonUtils;
import com.gateway.utils.TopicUtils;

public class GWProxy extends AbstractApiProxy implements SessionListener {
	public NotifyProxy notifyProxy;

	public NotifyProxy getNotifyProxy() {
		return notifyProxy;
	}

	public void setNotifyProxy(NotifyProxy notifyProxy) {
		this.notifyProxy = notifyProxy;
	}

	public void setRequestService(String requestService) {
		GWApi.requestService = requestService;
	}

	public void setSubscribes(HashMap hm) {
		GWApi.subscribes = hm;
	}
	private List filterTopics = new ArrayList();

	public List getFilterTopics() {
		return filterTopics;
	}

	public void setFilterTopics(List filterTopics) {
		this.filterTopics = filterTopics;
	}

	public void filter(String topic, String content) {
		for (IFilterTopic filter : filterTopics) {
			if (TopicUtils.matchTopic(filter.getFilterTopic(), topic)) {
				filter.onMessage(topic, content);
			}
		}
	}
	public void init() {
		com.gw.common.utils.Consts.ServerName="gateway";
	 
		GWApi.messageListener = this.messageListener;
		GWApi.tcpConnector = this.tcpConnector;
		GWApi.notifyProxy = this.notifyProxy;
		GWApi.cedaProxy = this;
		GWApi.init(executorService);
	}

	IMessage messageListener = new IMessage() {
		private AsynOnMessage asynOnMessage = new AsynOnMessage(Runtime.getRuntime().availableProcessors() * 2);

		@Override
		public void onMessage(String topic, String content) {
			asynOnMessage.add(topic, new String[] { topic, content });

		}

		class AsynOnMessage extends AsyncSeqThreadGroup {

			public AsynOnMessage(int asyncBaseNum) {
				super(asyncBaseNum);
			}

			@Override
			protected void process(String[] t) {
				try {
					String topic = t[0];
					String content = t[1];
					logger.debug("{},{}", topic, content);
					filter(topic, content);
					String sid = null;
					if ("SYS.ATS.LOGIN".equals(topic)) {
						HashMap hm = JsonUtils.Deserialize(content, HashMap.class);
						Object tsid = hm.get("sid");
						String type = hm.get("type") + "";
						if ("logout".equals(type)) {
							if (tsid != null) {
								sid = tsid + "";
							}
						} else {
							return;
						}
					}
					if (notifyProxy != null) {
						if (StringUtils.isEmpty(sid)) {
							notifyProxy.notify(topic, content);
						} else {
							notifyProxy.notify(sid, topic, content);

						}
					}
				} catch (Exception e) {
					logger.error("", e);
				}

			}
		}
	};
	@SuppressWarnings("unchecked")
	@Override
	public MessageWrapper processLogin(SystemMessage sMsg, Proto message, String content) {
		try {
			String sid = message.getSessionId();
			String result = null;
			String userName = null;
			if (StringUtils.isEmpty(content) && !StringUtils.isEmpty(sid)) {
				result = GWApi.getUserInfo(sid);
			} else {
				HashMap hm = JSON.parseObject(content, HashMap.class);
				if (hm.containsKey("userName"))
					userName = hm.get("userName") + "";
				else if (hm.containsKey("user_id"))
					userName = hm.get("user_id") + "";

				String pwd = hm.get("pwd") + "";
				Object extendParam = hm.get("extendParam");
				List arr = null;
				if (extendParam != null) {
					arr = new ArrayList<>();
					arr.add(extendParam);
				}
				result = GWApi.Login(userName, pwd, sMsg.getRemoteAddress(),arr != null ? arr.toArray() : null);
			}
			String sessionId = "";
			boolean isSuccess = false;
			if (!StringUtils.isEmpty(result)) {
				HashMap rhm = JsonUtils.Deserialize(result, HashMap.class);
				int code = (int) rhm.get(Consts.Code);
				if (0==code) {
					if (rhm.containsKey("sid"))
						sessionId = rhm.get("sid") + "";
					else if (rhm.containsKey("data")) {
						Map dataMap = (Map) rhm.get("data");
						sessionId = dataMap.get("sid") + "";
					}

					isSuccess = true;
				}
				message.setBody(result.getBytes());
			}
			message.setSessionId(sessionId);
			MessageWrapper mr = new MessageWrapper(
					isSuccess ? MessageWrapper.MessageProtocol.CONNECT : MessageWrapper.MessageProtocol.NO_CONNECT,
					sessionId, message);
			mr.setUserName(userName);
			return mr;
		} catch (Exception e) {
			logger.error("content:" + content);
			throw e;
		}
	}

	@Override
	public MessageWrapper processAppRequestReply(SystemMessage sMsg, Proto message, String serverName, String method,
			String content) {
		message.setFormat(Format.REPLY);
		String sid = message.getSessionId();
		if ("subscribe".equals(method)) {
			try {
				GWApi.requestAsync(serverName, content, "", false, sid);
			} catch (Exception e) {
				logger.error("processAppRequestReply error", e);
			}
			return null;
		}
		if (serverName.equals("gateway") && "notify".equals(method)) {
			Map map = JsonUtils.Deserialize(content, Map.class);
			String topic = map.get("topic") + "";
			String content2 = map.get("content") + "";
			notifyProxy.notify(topic, content2);
			return createReply(0, "Success", message);
		} else {
			try {

				if (sMsg.isSyncFlag()) {
					String body = GWApi.requestSync(serverName, method, content, sid);
					message.setBody(body.getBytes());
					logger.info("{}:{} result:{}", serverName, method, body);
					return new MessageWrapper(MessageWrapper.MessageProtocol.REPLY, message.getSessionId(), message);
				} else {
					GWApi.requestAsync(message, serverName, method, content, false, sid);
				}
			} catch (CodeException e) {
				String ct = GWApi.faileMsg(e.code(), e.getMessage());
				message.setBody(ct.getBytes());
				message.setFormat(Format.REPLY);
				return new MessageWrapper(MessageWrapper.MessageProtocol.REPLY, message.getSessionId(), message);
			}
			return null;

		}
	}

	private List sessionServiceLt = new ArrayList();

	public List getSessionService() {
		return sessionServiceLt;
	}

	public void setSessionService(String sessionService) {
		String[] strs = sessionService.split(",");
		for (String str : strs) {
			if (!StringUtils.isEmpty(str)) {
				sessionServiceLt.add(str);
			}
		}
	}

	public void sessionCreated(SessionEvent se) {
		publishSession(se.getSession().getUserName(), 1);
	}

	public void sessionDestroyed(SessionEvent se) {
		publishSession(se.getSession().getUserName(), 0);
	}

	private void publishSession(String userName, int status) {
		List userNames = new ArrayList();
		userNames.add(userName);
		publishSession(userNames, status, false);
	}

	public void publishSession(List userNames, int status, boolean isall) {
		HashMap hm = new HashMap();
		hm.put("userNames", userNames);
		hm.put("status", status);
		hm.put("all", isall);
		String content = JSON.toJSONString(hm);
		for (String serverName : sessionServiceLt) {
			try {
				GWApi.requestAsync(null, serverName, "SessionStatus", content, false, null);
			} catch (CodeException e) {
				logger.error("publishSession {} error", serverName, e);
			}
		}
	}
	@Override
	public MessageWrapper invokeAsync(SystemMessage sMsg, Proto message, String serverName, String method,
			String content, com.gateway.connector.tcp.client.IMessage callback) {
		try {
			String sid = message.getSessionId();
			GWApi.requestAsync("SERVER."+serverName, method, content, sid,callback);
		} catch (Exception e) {
			String ct = GWApi.faileMsg(Consts.NoKnowCode, e.getMessage());
			message.setBody(ct.getBytes());
			message.setFormat(Format.REPLY);
			return new MessageWrapper(MessageWrapper.MessageProtocol.REPLY, message.getSessionId(), message);
		}
		return null;

	}
}