com.gateway.invoke.security.WhiteListSecurityCheck Maven / Gradle / Ivy
package com.gateway.invoke.security;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import com.gateway.connector.proto.Proto;
import com.gateway.message.SystemMessage;
import com.gateway.utils.TopicUtils;
public class WhiteListSecurityCheck implements ISecurityCheck {
private static int WhiteListCheck = 10004;
private static String WhiteListCheckMsg = "";
private String whiteListPath;
public String getWhiteListPath() {
return whiteListPath;
}
public void setWhiteListPath(String whiteListPath) {
this.whiteListPath = whiteListPath;
}
private ConcurrentHashMap> whiteListHm = new ConcurrentHashMap>();
public void init() throws Exception {
ArrayList tmp = readAll(whiteListPath);
tmp.add("loginsvr,login");//
if (tmp != null) {
whiteListHm.clear();
for (String str : tmp) {
String[] strs = str.split(",");
if (strs.length > 1) {
String serverName = strs[0];
String topic = strs[1];
CopyOnWriteArraySet cas = whiteListHm.get(serverName);
if (cas == null) {
cas = new CopyOnWriteArraySet<>();
whiteListHm.put(serverName, cas);
}
if (!cas.contains(topic)) {
cas.add(topic);
}
}
}
}
}
@Override
public SecurityResult check(SystemMessage sMsg, Proto message, String serverName, String method, String content,Map, ?> hm) {
SecurityResult pr = new SecurityResult();
CopyOnWriteArraySet cas = whiteListHm.get(serverName.toLowerCase());
if (cas != null) {
if (method.equals("subscribe") || method.equals("unsubscribe")) {
for (String stopic : cas) {
if (TopicUtils.matchTopic(stopic, content.toLowerCase())) {
return pr;
}
}
pr.code = WhiteListCheck;
pr.msg = WhiteListCheckMsg;
} else if (!cas.contains(method.toLowerCase())) {
pr.code = WhiteListCheck;
pr.msg = WhiteListCheckMsg;
}
} else {
pr.code = WhiteListCheck;
pr.msg = WhiteListCheckMsg;
}
return pr;
}
public static ArrayList readAll(String fileName) throws Exception {
ArrayList list = new ArrayList();
InputStreamReader fileReader = null;
BufferedReader reader = null;
try {
fileReader = new InputStreamReader(new FileInputStream(fileName), Charset.forName("utf-8"));
reader = new BufferedReader(fileReader);
String line = null;
while ((line = reader.readLine()) != null) {
if (line != null && line.length() > 0) {
list.add(line.toLowerCase());
}
}
} finally {
try {
reader.close();
} catch (IOException e) {
}
try {
fileReader.close();
} catch (IOException e) {
}
}
return list;
}
}