-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNSCommandManager.java
More file actions
98 lines (84 loc) · 2.39 KB
/
Copy pathNSCommandManager.java
File metadata and controls
98 lines (84 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.nullspace.command;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nullspace.packet.NSMessage;
import com.nullspace.socket.NSSocketSession;
import com.nullspace.utils.NSClassFileUtil;
public class NSCommandManager
{
private static Logger mLogger = LoggerFactory.getLogger(NSCommandManager.class);
public static Map<Integer, Class<?> > mCommandCache = new HashMap<>();
public static NSCommandManager instance = new NSCommandManager();
private ExecutorService mExecutor = Executors.newCachedThreadPool();
private NSCommandManager()
{
}
public void ExecuteMessage(NSSocketSession session, NSMessage message)
{
Class<?> type = getClass(message.mHead.mType);
if (type != null)
{
try {
Constructor<?> constructor = type.getConstructor(NSSocketSession.class, NSMessage.class);
if (constructor != null)
{
NSAbstractCommand command = (NSAbstractCommand) constructor.newInstance(session, message);
mExecutor.submit(command);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
else
{
mLogger.info("not exists type: " + message.mHead.mType);
}
}
public Class<?> getClass(int type)
{
if (mCommandCache.containsKey(type))
{
return mCommandCache.get(type);
}
return null;
}
public static boolean initCommandManager(String packageName)
{
List<Class<?>> allClasses = NSClassFileUtil.getClasses(packageName);
try
{
for (Class<?> clazz : allClasses)
{
NSCommandAnnotion cmd = clazz.getAnnotation(NSCommandAnnotion.class);
if (cmd == null)
{
continue;
}
if (mCommandCache.containsKey(cmd.code()))
{
mLogger.info(String.format(
"Duplicated first command code: [0x%x|%d].",
cmd.code(), cmd.code()));
return false;
}
mCommandCache.put(cmd.code(), clazz);
}
mLogger.info(String.format("command size: %d", mCommandCache
.size()));
return true;
}
catch (Exception e)
{
e.printStackTrace();
mLogger.error("加载command类 : " + e.getMessage());
return false;
}
}
}