1 13 package com.tonbeller.wcf.controller; 14 15 import javax.servlet.http.HttpServletRequest ; 16 import javax.servlet.http.HttpSession ; 17 18 import org.apache.log4j.Logger; 19 20 23 public class RequestSynchronizer { 24 private static final String WEBKEY = "requestSynchronizer"; 25 private static Logger logger = Logger.getLogger(RequestSynchronizer.class); 26 27 31 private String resultURI = null; 32 33 42 private Thread currentThread = null; 43 44 RequestSynchronizer() { 45 } 46 47 public static synchronized RequestSynchronizer instance(HttpServletRequest request) { 48 HttpSession session = request.getSession(true); 49 RequestSynchronizer rsync = (RequestSynchronizer) session.getAttribute(WEBKEY); 50 if (rsync == null) { 51 rsync = new RequestSynchronizer(); 52 session.setAttribute(WEBKEY, rsync); 53 } 54 return rsync; 55 } 56 57 public interface Handler { 58 59 62 void normalRequest() throws Exception ; 63 64 67 void recursiveRequest() throws Exception ; 68 69 76 void showBusyPage(boolean redirect) throws Exception ; 77 78 81 String getResultURI(); 82 83 86 boolean isBusyPage(); 87 } 88 89 private synchronized boolean startNormalRequest(Handler handler) { 90 if (currentThread == null) { 91 logInfo("normal request"); 92 currentThread = Thread.currentThread(); 93 return true; 94 } 95 return false; 96 } 97 98 private synchronized void endNormalRequest() { 99 currentThread = null; 100 } 101 102 private synchronized boolean startRecursiveRequest(Handler handler) { 103 if (Thread.currentThread().equals(currentThread)) { 104 logInfo("recursive request"); 105 return true; 106 } 107 return false; 108 } 109 110 private synchronized void endRecursiveRequest() { 111 } 112 113 public void handleRequest(Handler handler) throws Exception { 114 115 if (handler.isBusyPage()) { 117 handler.showBusyPage(false); 118 logInfo("handle-busy-false"); 119 return; 120 } 121 122 if (startNormalRequest(handler)) { 123 try { 125 resultURI = handler.getResultURI(); 126 logInfo("handle-normal"); 127 handler.normalRequest(); 128 } finally { 129 endNormalRequest(); 130 } 131 resultURI = handler.getResultURI(); 132 return; 133 } 134 135 if (startRecursiveRequest(handler)) { 136 try { 138 logInfo("handle-recursive"); 139 handler.recursiveRequest(); 140 } finally { 141 endRecursiveRequest(); 142 } 143 return; 144 } 145 146 logInfo("handle-busy-true"); 148 handler.showBusyPage(true); 149 } 150 151 public String getResultURI() { 152 return resultURI; 153 } 154 155 private void logInfo(String id) { 156 if (logger.isInfoEnabled()) 157 logger.info("Log " + id + " Thread = " + Thread.currentThread().getName() + ", resultURI = " 158 + resultURI + ", currentThread = " + currentThread); 159 } 160 161 } | Popular Tags |