1
22
23 package com.liferay.portlet.mail.util;
24
25 import com.liferay.portal.util.WebKeys;
26 import com.liferay.portlet.mail.util.multiaccount.MailCache;
27
28 import java.util.HashMap;
29 import java.util.Map;
30
31 import javax.mail.Folder;
32 import javax.mail.MessagingException;
33
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpSession;
36
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39
40
46 public class MailSessionLock {
47
48 public static void cleanUp(HttpSession ses) {
49 _instance._cleanUp(ses);
50 }
51
52 public static void lock(HttpServletRequest req) {
53 _instance._lock(req.getSession().getId());
54 }
55
56 public static void unlock(HttpServletRequest req) {
57 _instance._unlock(req.getSession().getId());
58 }
59
60 private MailSessionLock() {
61 }
62
63 private void _cleanUp(HttpSession ses) {
64 try {
65
66
69 Folder folder = (Folder)ses.getAttribute(WebKeys.MAIL_FOLDER);
70
71 if ((folder != null) && folder.isOpen()) {
72 try {
73 folder.close(false);
74 }
75 catch (MessagingException me) {
76 if (_log.isWarnEnabled()) {
77 _log.warn(me);
78 }
79 }
80
81 ses.removeAttribute(WebKeys.MAIL_FOLDER);
82 }
83
84 MailCache.clearCache(ses);
85
86 ses.removeAttribute(WebKeys.MAIL_MESSAGE_ID);
87 }
88 catch (Exception e) {
89 }
90
91 synchronized (_sessionMap) {
92 _sessionMap.remove(ses.getId());
93 }
94 }
95
96 private void _lock(String sessionId) {
97 ThreadLocal<Long> threadLocal = null;
98
99 for (;;) {
100 synchronized (_sessionMap) {
101 threadLocal = _sessionMap.get(sessionId);
102
103 if (threadLocal == null) {
104
105
107 threadLocal = new ThreadLocal<Long>();
108
109 threadLocal.set(new Long(0));
110
111 _sessionMap.put(sessionId, threadLocal);
112
113 break;
114 }
115 else if (threadLocal.get() != null) {
116
117
120 Long count = threadLocal.get();
121
122 threadLocal.set(new Long(count.longValue() + 1L));
123
124 break;
125 }
126 }
127
128
131 try {
132 wait(100);
133 }
134 catch (Exception ex) {
135 }
136 }
137 }
138
139 private void _unlock(String sessionId) {
140 ThreadLocal<Long> threadLocal = null;
141
142 synchronized (_sessionMap) {
143 threadLocal = _sessionMap.get(sessionId);
144
145
148 if (threadLocal != null) {
149 Long count = threadLocal.get();
150
151 if (count.longValue() == 0L) {
152
153
155 _sessionMap.remove(sessionId);
156 }
157 else {
158
159
161 count = new Long(count.longValue() - 1L);
162
163 threadLocal.set(count);
164 }
165 }
166 }
167 }
168
169 private static Log _log = LogFactory.getLog(MailSessionLock.class);
170
171 private static MailSessionLock _instance = new MailSessionLock();
172
173 private Map<String, ThreadLocal<Long>> _sessionMap =
174 new HashMap<String, ThreadLocal<Long>>();
175
176 }