david-PC\david
2018-06-12 cc7f57619fd09f68582b748a3580402717b84c50
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package frame.server;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.apache.log4j.Logger;
 
import frame.call.writer.EnvelopWriter;
import frame.call.writer.IEnvelop;
import frame.config.Configer;
import frame.role.OnlineAnymous;
import frame.role.OnlineUser;
import frame.role.Statistics;
import frame.util.Util;
 
 
public class Dispatcher implements Filter {
 
    private static Dispatcher instance;
    private static Logger logger;
    private static String contextPath;
    private static boolean AuthorizeActive;
    private static Set<String> freeVisitTypes;
    private static ResourceFilter freeVisitResources;
    private static Set<String> freeVisitCalls;
    private static Map<String, VirtualPath> virtualPaths;
    private static Map<String, Class<? extends ICallObject>> callableClassMap;
    private static ExcludeList excludeList;
 
    static {
        logger = Logger.getLogger(Dispatcher.class);
 
        callableClassMap = new HashMap<String, Class<? extends ICallObject>>();
        freeVisitTypes = new HashSet<String>();
        freeVisitResources = new ResourceFilter();
        virtualPaths = new HashMap<String, VirtualPath>();
        freeVisitCalls = new HashSet<String>();
        excludeList = new ExcludeList();
    }
 
    public Dispatcher() {
        instance = this;
    }
 
    public synchronized static Dispatcher getInstance() {
        if (instance == null) {
            instance = new Dispatcher();
        }
 
        return instance;
    }
 
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        Map<String, Statistics> visitor = new HashMap<String, Statistics>();
        servletContext.setAttribute("visitor", visitor);
 
        contextPath = servletContext.getContextPath();
        RequestPath.contextLength = contextPath.length();
        logger.debug("contextPath: " + contextPath);
 
        AuthorizeActive = Util.StringToBoolean(Configer.getParam("AuthorizeActive"));
    }
 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        
        request.setCharacterEncoding("utf-8");
        saveIp(request, getIP(request));
 
        try {
            RequestPath path = new RequestPath(request);
            RequestType type = path.getType();
 
            if (logger.isDebugEnabled()) {
                logger.debug("filter request URI:" + path);
            }
 
            if (RequestType.Resource == type) {
                // 1.1 goto free resource
                if (freeVisitTypes.contains(path.getSuffix())) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher(path.getTarget());
                    dispatcher.forward(request, response);
                    return;
                }
                // 1.2 goto free sub resource
                else if (freeVisitResources.contains(path.getTarget())) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher(path.getTarget());
                    dispatcher.forward(request, response);
                    return;
                }
                // 1.3 goto authorized resources
                else {
                    OnlineUser onlineUser = getOnlineUser(path);
                    if (onlineUser == null) {
                        String target = Configer.getPage_TimeOut();
 
                        PrintWriter out = response.getWriter();
                        out.println("<script>");
                        out.println("window.top.location.href='" + target + "'");
                        out.println("</script>");
                        return;
                    }
 
                    RequestDispatcher dispatcher = request.getRequestDispatcher(path.getTarget());
                    dispatcher.forward(request, response);                    
                }
            }
            else {
                VirtualPath virtualPath = virtualPaths.get(path.getTarget());
 
                if (virtualPath != null) {
                    logger.debug("get virtual path: " + virtualPath);
 
                    //2.1 goto root
                    if (RequestType.Root == type) {
                        response.sendRedirect(virtualPath.getTarget());
                        return;
                    }
                    //2.2 goto resource
                    else if (VirtualPathType.Resource == virtualPath.getType()) {
                        // 4. goto resource on virtual path
                        RequestDispatcher dispatcher = request.getRequestDispatcher(virtualPath.getTarget());
                        dispatcher.forward(request, response);
                        return;
                    }
                    //2.3 goto error
                    else {
                        writeError(request, response, "resource not exists: " + path.getTarget());
                        return;
                    }
                }
 
                virtualPath = virtualPaths.get(path.getParent());
 
                if (virtualPath == null) {
                    if (excludeList.contains(path)) {
                        logger.debug("dispatch exclude url:" + path);
                        chain.doFilter(request, response);
                    }
                }
                
                if (virtualPath == null) {
                    writeError(request, response, "resource not exists: " + path.getTarget());
                    return;
                }
 
                Class<? extends ICallObject> clazz = virtualPath.getCallableClass();
                ICallObject callable = clazz.newInstance();
                callable.setRequest(request);
                callable.setResponse(response);
 
                OnlineUser onlineUser = getOnlineUser(path);
 
                // 3.1 goto free visit object
                if (onlineUser == null) {
                    if (freeVisitCalls.contains(path.getTarget())) {
                        onlineUser = OnlineAnymous.getInstance();
                    }
                    else {
                        writeSessionTimeout(request, response);
                        return;
                    }
                }
 
                // 3.2 goto authorized object
                callable.setOnlineUser(onlineUser);
                callable.receive(path.getShortTarget());
                return;
            }
        }
        catch (Exception e) {
            String error = printStackToString(e);
            logger.error("dispatch error:" + e.getMessage());
            logger.error(error);
            writeError(request, response, error);
        }
    }
 
    private OnlineUser getOnlineUser(RequestPath path) {
        HttpServletRequest request = path.getRequest();
        HttpSession session = request.getSession();
 
        // 获取OnlineUser类的简单类名
        String code = OnlineUser.class.getSimpleName();
        OnlineUser onlineUser = (OnlineUser) session.getAttribute(code);
 
        // 如果session中没有用户信息,但是不要权限验证,责返回一个匿名的用户信息,以便进行下面的操作
        if (onlineUser == null) {
            if (!AuthorizeActive) {
                onlineUser = OnlineAnymous.getInstance();
            }
 
            return onlineUser;
        }
 
        // 如果需要权限验证,如果真没有用户信息,将返回null
        return onlineUser;
    }
 
    public void destroy() {
 
    }
 
    private String printStackToString(Exception e) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(outStream);
        e.printStackTrace(printStream);
 
        return outStream.toString();
    }
 
    private void writeSessionTimeout(HttpServletRequest request, HttpServletResponse response) {
        try {
            EnvelopWriter envelopWriter = new EnvelopWriter(request, response);
            envelopWriter.ReplyError(IEnvelop.Error_Code_Timeout, IEnvelop.Error_Messgae_Timeout);
        }
        catch (Exception ex) {
        }
    }
 
    private void writeError(HttpServletRequest request, HttpServletResponse response, String error) {
        try {
            EnvelopWriter envelopWriter = new EnvelopWriter(request, response);
            envelopWriter.ReplyError(IEnvelop.Error_Code_ServerError, error);
        }
        catch (Exception ex) {
        }
    }
 
    public void clear() {
        callableClassMap.clear();
    }
 
    public void appendFreeVisitType(String type) {
        type = type.toLowerCase();
        freeVisitTypes.add(type);
    }
 
    public void appendFreeVisitResource(String resource) {
        resource = resource.toLowerCase();
        freeVisitResources.add(resource);
    }
 
    public void appendFreeVisitCalls(String call) {
        call = call.toLowerCase();
 
        if ('/' != call.charAt(0)) {
            call = "/" + call;
        }
 
        freeVisitCalls.add(call);
    }
 
 
    public void appendExcludeResources(String exclude) {
        exclude = exclude.toLowerCase();
        excludeList.add(exclude);
    }
    
    public void appendVirtualPaths(String path, String target, String className) throws Exception {
        if ('/' != path.charAt(0)) {
            path = "/" + path;
        }
 
        VirtualPath virtualPath = new VirtualPath(target, className);
        virtualPaths.put(path, virtualPath);
    }
 
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void appendCallableClass(String path, String classname) throws Exception {
        path = path.toLowerCase();
 
        Class clazz = Class.forName(classname);
        Class<? extends ICallObject> callableClass = (Class<? extends ICallObject>) clazz;
 
        callableClassMap.put(path, callableClass);
    }
    
    private String getIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
 
        if (ip == null) {
            ip = request.getRemoteAddr();
            return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
        }
 
        return ip;
    }
 
    @SuppressWarnings("deprecation")
    private void saveIp(HttpServletRequest request, String ip) {
        if (!request.getRequestURI().endsWith(".html")) { // 不对网页以外的请求做统计,例如图片等
            return;
        }
        ServletContext servletContext = request.getServletContext();
        @SuppressWarnings("unchecked")
        Map<String, Statistics> visitor = (Map<String, Statistics>) servletContext.getAttribute("visitor");
        if (visitor.keySet().contains(ip)) {
            Statistics s = visitor.get(ip);
            s.setCnt(s.getCnt() + 1);
            s.setDate(new Date().toLocaleString());
            visitor.put(ip, s);
            
            servletContext.setAttribute("visitor", visitor);
        }
        else {
            visitor.put(ip, new Statistics(ip, 1, new Date().toLocaleString()));
            servletContext.setAttribute("visitor", visitor);
        }
    }
 
}