001: /*
002: * (C) Copyright 2006 Nabh Information Systems, Inc.
003: *
004: * This program is free software; you can redistribute it and/or
005: * modify it under the terms of the GNU General Public License
006: * as published by the Free Software Foundation; either version 2
007: * of the License, or (at your option) any later version.
008: *
009: * This program is distributed in the hope that it will be useful,
010: * but WITHOUT ANY WARRANTY; without even the implied warranty of
011: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
012: * GNU General Public License for more details.
013: *
014: * You should have received a copy of the GNU General Public License
015: * along with this program; if not, write to the Free Software
016: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
017: *
018: */
019: package com.nabhinc.portal.core;
020:
021: import java.rmi.RemoteException;
022: import java.sql.Connection;
023: import java.sql.PreparedStatement;
024: import java.sql.ResultSet;
025: import java.sql.SQLException;
026: import java.sql.Timestamp;
027: import java.sql.Types;
028: import java.text.DateFormat;
029: import java.util.ArrayList;
030: import java.util.List;
031: import java.util.Map;
032:
033: import javax.naming.NamingException;
034: import javax.portlet.RenderRequest;
035: import javax.servlet.ServletConfig;
036: import javax.servlet.ServletException;
037: import javax.servlet.http.HttpServletRequest;
038: import javax.servlet.http.HttpSession;
039:
040: import org.apache.commons.logging.Log;
041: import org.apache.commons.logging.LogFactory;
042:
043: import com.nabhinc.portal.model.PortalConfiguration;
044: import com.nabhinc.util.ComponentConfig;
045: import com.nabhinc.util.db.DBConfigUtil;
046: import com.nabhinc.util.db.DBUtil;
047: import com.nabhinc.util.i18n.DateTimeFormatUtil;
048:
049: /**
050: *
051: *
052: * @author Padmanabh Dabke
053: * (c) 2006 Nabh Information Systems, Inc. All Rights Reserved.
054: */
055: public class SessionManager {
056: private static Log smLogger = LogFactory
057: .getLog(SessionManager.class);
058: /**
059: * Login interceptors
060: */
061: private static LoginInterceptor[] smLoginInterceptors = new LoginInterceptor[0];
062:
063: protected static void init(ServletConfig config)
064: throws ServletException {
065: createInMemoryTable();
066: List<ComponentConfig> interceptorList = PortalConfiguration
067: .getInstance().getLoginInterceptorConfigs();
068: if (interceptorList == null) {
069: smLoginInterceptors = new LoginInterceptor[0];
070: return;
071: }
072: smLoginInterceptors = new LoginInterceptor[interceptorList
073: .size()];
074: for (int i = 0; i < interceptorList.size(); i++) {
075: ComponentConfig pluginConfig = interceptorList.get(i);
076: try {
077: smLoginInterceptors[i] = (LoginInterceptor) ComponentConfig
078: .createComponent(pluginConfig);
079: } catch (Exception e) {
080: throw new ServletException(
081: "Failed to instantiate plug-in number " + i, e);
082: }
083:
084: try {
085: smLoginInterceptors[i].init(config);
086: } catch (Exception e) {
087: throw new ServletException(
088: "Failed to initialize plug-in number " + i, e);
089: }
090: }
091: }
092:
093: protected static void createInMemoryTable() throws ServletException {
094: Connection conn = null;
095: PreparedStatement st = null;
096: try {
097: conn = DBUtil.getConnection(DBConfigUtil.getInstance()
098: .getOnlineUserDataSourceName());
099: conn.setAutoCommit(true);
100: st = conn.prepareStatement("DROP TABLE "
101: + DBConfigUtil.getInstance()
102: .getOnlineUserTableName());
103: try {
104: st.execute();
105: } catch (Exception ex) { /* ignore */
106: }
107: st = conn
108: .prepareStatement("CREATE TABLE "
109: + DBConfigUtil.getInstance()
110: .getOnlineUserTableName()
111: + " ( username VARCHAR(30), sessionid VARCHAR(255), created TIMESTAMP, lastaccess TIMESTAMP, host VARCHAR(100), addr VARCHAR(30), userid INTEGER )");
112: st.execute();
113: } catch (Exception ex) {
114: throw new ServletException(
115: "Failed to create in-memory sessions table.", ex);
116: } finally {
117: try {
118: st.close();
119: conn.close();
120: } catch (Exception ex1) {
121: }
122: }
123: }
124:
125: protected static void updateTimeLastAccessed(String sessionID) {
126: Connection conn = null;
127: PreparedStatement st = null;
128: try {
129: conn = DBUtil.getConnection(DBConfigUtil.getInstance()
130: .getOnlineUserDataSourceName());
131: conn.setAutoCommit(true);
132: st = conn.prepareStatement("UPDATE "
133: + DBConfigUtil.getInstance()
134: .getOnlineUserTableName()
135: + " SET lastaccess = ? WHERE sessionid = ?");
136: st.setTimestamp(1,
137: new Timestamp(System.currentTimeMillis()));
138: st.setString(2, sessionID);
139: st.execute();
140: } catch (Exception ex) {
141: PortalServlet
142: .getInstance()
143: .error(
144: "Failed to update table for storing active sessions: ",
145: ex);
146: } finally {
147: try {
148: st.close();
149: conn.close();
150: } catch (Exception ex1) {
151: }
152: }
153:
154: }
155:
156: public static int getNumberOfUsers() {
157:
158: try {
159: String userCountStr = DBUtil.getField(DBConfigUtil
160: .getInstance().getOnlineUserDataSourceName(),
161: // "SELECT COUNT(*) FROM " + DBConfigUtil.getInstance().getOnlineUserTableName() + " WHERE userid > -1", Types.INTEGER, null);
162: "SELECT COUNT(*) FROM "
163: + DBConfigUtil.getInstance()
164: .getOnlineUserTableName(),
165: Types.INTEGER, null);
166: if (userCountStr == null)
167: return 0;
168: return Integer.parseInt(userCountStr);
169:
170: } catch (Exception ex) {
171: smLogger.error(
172: "Exception in getting number of online users.", ex);
173: return 0;
174: }
175: }
176:
177: public static boolean isUserOnline(String userName) {
178: try {
179: return DBUtil.checkRelation(DBConfigUtil.getInstance()
180: .getOnlineUserDataSourceName(),
181: "SELECT username FROM "
182: + DBConfigUtil.getInstance()
183: .getOnlineUserTableName()
184: + " WHERE username = '" + userName + "'");
185: } catch (Exception ex) {
186: smLogger.error(
187: "Exception in checking if a user is online.", ex);
188: return false;
189: }
190: }
191:
192: protected static void removeSession(String sessionID) {
193: Connection conn = null;
194: try {
195: conn = DBUtil.getConnection(DBConfigUtil.getInstance()
196: .getOnlineUserDataSourceName());
197: PreparedStatement st = conn.prepareStatement("DELETE FROM "
198: + DBConfigUtil.getInstance()
199: .getOnlineUserTableName()
200: + " WHERE sessionid = ?");
201: st.setString(1, sessionID);
202: st.execute();
203: } catch (Exception ex) {
204: smLogger
205: .error(
206: "Failed to update table for storing active sessions: ",
207: ex);
208: } finally {
209: try {
210: conn.close();
211: } catch (Exception ex1) {
212: }
213: }
214:
215: }
216:
217: protected static void insertSession(HttpServletRequest req,
218: HttpSession session, String userName) {
219: Connection conn = null;
220: try {
221:
222: int userID = -1;
223: if (userName == null) {
224: userName = PortalConstants.GUEST_USER;
225: } else {
226: try {
227: userID = Integer
228: .parseInt((String) ((Map) session
229: .getAttribute(PortalConstants.USER_INFO_ATTRIBUTE))
230: .get("user.id"));
231: } catch (Exception e) {
232: // Ignore this exception. User ID is not guaranteed to be available (e.g. when using LDAP);
233: }
234: }
235: conn = DBUtil.getConnection(DBConfigUtil.getInstance()
236: .getOnlineUserDataSourceName());
237: conn.setAutoCommit(true);
238: Timestamp tm = new Timestamp(System.currentTimeMillis());
239: PreparedStatement st = conn
240: .prepareStatement("INSERT INTO "
241: + DBConfigUtil.getInstance()
242: .getOnlineUserTableName()
243: + " (sessionid, username, created, lastaccess, host, addr, userid) VALUES (?,?,?,?,?,?,?)");
244: st.setString(1, session.getId());
245: st.setString(2, userName);
246: st.setTimestamp(3, tm);
247: st.setTimestamp(4, tm);
248: st.setString(5, req.getRemoteHost());
249: st.setString(6, req.getRemoteAddr());
250: st.setInt(7, userID);
251: st.execute();
252: } catch (Exception ex) {
253: smLogger
254: .error(
255: "Failed to update table for storing active sessions: ",
256: ex);
257: } finally {
258: try {
259: conn.close();
260: } catch (Exception ex1) {
261: }
262: }
263:
264: }
265:
266: public static void interceptLogin(String sessionId,
267: ClientInfo config, int logType) throws ServletException {
268: if (smLoginInterceptors != null)
269: for (int i = 0; i < smLoginInterceptors.length; i++)
270: smLoginInterceptors[i].intercept(sessionId,
271: config.userName, logType, config.remoteHost,
272: config.remoteAddress);
273:
274: }
275:
276: @SuppressWarnings("unchecked")
277: public static List getOnlineSessions(int offset, int maxUsers,
278: String orderby, boolean isDescending, RenderRequest request)
279: throws RemoteException {
280: Connection conn = null;
281: ResultSet results = null;
282: PreparedStatement st = null;
283:
284: try {
285: String selectSQL = "SELECT username, created, lastaccess, host, addr, userid, sessionid FROM "
286: + DBConfigUtil.getInstance()
287: .getOnlineUserTableName();
288: if (orderby != null) {
289: selectSQL += " ORDER BY " + orderby;
290: if (isDescending)
291: selectSQL += " DESC";
292: }
293:
294: conn = DBUtil.getConnection(DBConfigUtil.getInstance()
295: .getOnlineUserDataSourceName());
296: st = conn.prepareStatement(selectSQL);
297: results = st.executeQuery();
298: List userList = new ArrayList();
299:
300: // Skip upto offset
301: for (int i = 0; i < offset; i++) {
302: if (!results.next())
303: return userList;
304: }
305:
306: // Create maxRoles roles and add them to the vector.
307: DateFormat d = DateTimeFormatUtil.getDateTimeFormat(request
308: .getLocale());
309: for (int i = 0; i < maxUsers; i++) {
310: if (!results.next())
311: break;
312: String[] userInfo = new String[7];
313: userInfo[0] = results.getString(1);
314: userInfo[1] = d.format(results.getTimestamp(2));
315: userInfo[2] = d.format(results.getTimestamp(3));
316: for (int j = 4; j < 8; j++) {
317: userInfo[j - 1] = results.getString(j);
318: }
319: userList.add(userInfo);
320: }
321:
322: return userList;
323:
324: } catch (NamingException ex) {
325: throw new RemoteException("Failed to look up data source: "
326: + DBConfigUtil.getInstance()
327: .getOnlineUserDataSourceName(), ex);
328: } catch (SQLException ex) {
329: throw new RemoteException("System exception.", ex);
330: } finally {
331: DBUtil.close(st);
332: DBUtil.close(results);
333: DBUtil.close(conn);
334: }
335: }
336:
337: }
|