1 19 20 package org.openharmonise.rm.sessions; 21 22 import java.security.SecureRandom ; 23 import java.sql.*; 24 import java.text.SimpleDateFormat ; 25 import java.util.List ; 26 import java.util.logging.*; 27 28 import javax.servlet.http.HttpServletRequest ; 29 30 import org.openharmonise.commons.cache.*; 31 import org.openharmonise.commons.dsi.*; 32 import org.openharmonise.commons.dsi.dml.*; 33 import org.openharmonise.rm.*; 34 import org.openharmonise.rm.config.*; 35 import org.openharmonise.rm.dsi.DataStoreObject; 36 import org.openharmonise.rm.factory.*; 37 import org.openharmonise.rm.logging.*; 38 import org.openharmonise.rm.publishing.*; 39 import org.openharmonise.rm.resources.AbstractObject; 40 import org.openharmonise.rm.resources.publishing.Template; 41 import org.openharmonise.rm.resources.users.User; 42 import org.openharmonise.rm.security.authentication.*; 43 import org.w3c.dom.*; 44 45 46 58 public class Session implements DataStoreObject, Publishable { 59 60 protected static final String CLMN_SESSION_ID = "id"; 62 protected static final String CLMN_SESSION_DATE = "date"; 63 protected static final String CLMN_SESSION_TIMEOUT = "timeout"; 64 protected static final String CLMN_USER_ID = "users_id"; 65 protected static final String CLMN_TYPE = "type"; 66 protected static final String TBL_SESSION = "session"; 67 68 public static final String TAG_SESSION = "Session"; 70 public static final String TAG_LOGON = "Logon"; 71 public static final String TAG_LOGOFF = "Logoff"; 72 73 public static final String DEFAULT_TIMEOUT_PNAME = "DEFAULT_TIMEOUT"; 74 private static final int m_nDefaultNumChars = 20; 75 private static final String sCharBase = 76 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 77 private static final String DB_DATEFORMAT = "MM-dd-yyyy HH:mm:ss.SSS"; 78 private AbstractDataStoreInterface m_dsi; 79 80 public static String LAG_PERCENT_PNAME = "LAGTIME_PERCENT"; 81 public static String PREFIX_SEPARATOR = "_"; 82 public static String DEFAULT_USER_PREFIX = "D" + PREFIX_SEPARATOR; 83 public static String LOGGED_IN_USER_PREFIX = "L" + PREFIX_SEPARATOR; 84 85 protected CachePointer m_usrPtr = null; 86 protected String m_sSessionId = ""; 87 protected java.util.Date m_dtTimeout; 88 protected boolean m_bTimedOut = false; 89 protected boolean m_bDefaultUser = true; 90 91 protected int DEFAULT_USER_ID = 1; 93 protected int m_nTimeout = 60; 94 protected int m_nLagPercent = -1; 95 protected String sDefaultLagPercent = "25"; 96 protected java.util.Date m_dtLagTime; 97 98 101 private static final Logger m_logger = Logger.getLogger(Session.class.getName()); 102 103 public static User m_QueryUser = null; 104 105 static { 106 m_QueryUser = new User(); 107 } 108 109 113 public Session(AbstractDataStoreInterface dbinterf) { 114 m_dsi = dbinterf; 115 } 116 117 126 public Session( 127 AbstractDataStoreInterface dbinterf, 128 User usr, 129 String sessionId, 130 int timeout) 131 throws SessionException { 132 m_dsi = dbinterf; 133 134 try { 135 m_usrPtr = CacheHandler.getInstance(dbinterf).getCachePointer(usr); 136 } catch (CacheException e) { 137 throw new SessionException(e.getLocalizedMessage(),e); 138 } 139 this.m_sSessionId = sessionId; 140 141 setTimeout(timeout); 142 try { 143 setLagTime(timeout); 144 } catch (ConfigException e) { 145 throw new SessionException("Error occured setting lag time", e); 146 } 147 148 if (isSessionIdUnique(sessionId) == false) { 149 m_logger.logp(Level.INFO, this.getClass().getName(), "Session", "Session id " + sessionId + " is not unique and therefore not valid"); 150 throw new InvalidSessionIdException( 151 "Invalid session id - " + sessionId); 152 } 153 154 save(); 155 } 156 157 162 public Session(AbstractDataStoreInterface dbinterf, String sSessionId) throws SessionException { 163 m_dsi = dbinterf; 164 165 setDetailsFromId(sSessionId); 166 } 167 168 174 public Session(AbstractDataStoreInterface dbinterf, int timeout) throws SessionException { 175 m_dsi = dbinterf; 176 177 User user = null; 178 try { 179 user = (User) HarmoniseObjectFactory.instantiateHarmoniseObject(dbinterf, User.class.getName(), DEFAULT_USER_ID); 180 } catch (HarmoniseFactoryException e) { 181 throw new SessionException(e); 182 } 183 initialize(user, timeout); 184 } 185 186 192 public Session(AbstractDataStoreInterface dbinterf, User user, int timeout) 193 throws SessionException { 194 m_dsi = dbinterf; 195 initialize(user, timeout); 196 } 197 198 207 public static String removeSessionIdPrefix(String sSessId) { 208 String newSessId = sSessId; 209 int index = sSessId.indexOf(PREFIX_SEPARATOR); 210 211 if (index > 0) { 212 newSessId = sSessId.substring(index + 1); 213 } 214 215 return newSessId; 216 } 217 218 223 public String getSessionId() { 224 return m_sSessionId; 225 } 226 227 232 public User getUser() throws DataAccessException { 233 User usr = null; 234 235 try { 236 usr = (User) m_usrPtr.getObject(); 237 } catch (CacheException e) { 238 throw new DataAccessException(e.getLocalizedMessage(),e); 239 } 240 241 return usr; 242 } 243 244 245 248 public void registerHttpRequest(HttpServletRequest request) { 249 250 } 251 252 264 public void processState(State state, int nTimeout) 265 throws SessionException { 266 String sSessId = ""; 267 boolean bHasSessionId = false; 268 269 if (state == null) { 270 throw new SessionException("Null state object"); 271 } 272 273 NodeList nodeSession = state.getElementsByTagName(TAG_SESSION); 274 275 if (nodeSession.getLength() > 0) { 276 Element sessEl = (Element) nodeSession.item(0); 279 sSessId = sessEl.getAttribute(AbstractObject.ATTRIB_ID); 280 281 if ((sSessId.length() == 0) && (m_sSessionId.length() == 0)) { 282 throw new InvalidSessionIdException("Not found a Session Id"); 283 } 284 285 if (sSessId.length() > 0) { 286 if (!m_sSessionId.equals(sSessId)) { 287 throw new InvalidSessionIdException( 288 "Attempt to validate Session ID: " 289 + sSessId 290 + " against Session: " 291 + m_sSessionId); 292 } 293 } 294 295 bHasSessionId = true; 296 } 297 298 NodeList nodes = state.getElementsByTagName(TAG_LOGOFF); 301 302 if (nodes.getLength() > 0) { 303 304 try { 305 logoff((Element) nodes.item(0), getSessionId()); 306 } catch (DataStoreException e) { 307 throw new SessionException("Error occured with log off",e); 308 } 309 310 m_sSessionId = removeSessionIdPrefix(m_sSessionId); 312 m_sSessionId = DEFAULT_USER_PREFIX + m_sSessionId; 313 } 314 315 if (bHasSessionId) { 316 updateTimeout(nTimeout); 318 } 319 320 boolean bIsLogOn = false; 324 NodeList nodeLogOn = state.getElementsByTagName(TAG_LOGON); 325 326 if (nodeLogOn.getLength() > 0) { 327 bIsLogOn = true; 328 } 329 330 if (bIsLogOn == true) { 332 333 User user = logon((Element) nodeLogOn.item(0), state); 334 335 if (bHasSessionId 336 || (this.m_sSessionId != null 337 && this.m_sSessionId.length() > 0)) { 338 try { 340 updateUser(user); 341 } catch (DataStoreException e) { 342 throw new SessionException("Error occured updating user",e); 343 } 344 } else { 345 initialize(user, nTimeout); 347 348 bHasSessionId = true; 349 } 350 351 m_sSessionId = removeSessionIdPrefix(m_sSessionId); 353 m_sSessionId = LOGGED_IN_USER_PREFIX + m_sSessionId; 354 355 } else if ( 357 bHasSessionId == false 358 && (this.m_sSessionId == null 359 || this.m_sSessionId.length() == 0)) { 360 362 User user = getDefaultUser(); 363 sSessId = initialize(user, nTimeout); 364 365 bHasSessionId = true; 366 } 367 368 } 369 370 371 372 377 public void save() throws SessionException { 378 ResultSet rs = null; 379 InsertStatement insert = new InsertStatement(); 380 381 User usr = null; 382 383 try { 384 usr = getUser(); 385 } catch (DataAccessException e) { 386 throw new SessionException(e.getLocalizedMessage(),e); 387 } 388 389 if ((m_sSessionId.length() > 0) && (usr != null)) { 390 try { 392 insert.addColumnValue( 393 getInstanceColumnRef(CLMN_SESSION_ID), 394 removeSessionIdPrefix(m_sSessionId)); 395 insert.addColumnValue( 396 getInstanceColumnRef(CLMN_USER_ID), 397 usr.getId()); 398 insert.addColumnValue( 399 getInstanceColumnRef(CLMN_SESSION_TIMEOUT), 400 m_dtTimeout); 401 402 m_dsi.execute(insert); 403 } catch (DataStoreException e) { 404 405 m_logger.log(Level.WARNING, e.getMessage(), e); 406 throw new SessionException("Error occured saving session", e); 407 } 408 } else { 409 throw new InvalidSessionIdException("Error saving session"); 410 } 411 } 412 413 414 423 public void recordEvent(LogEvent event) throws SessionException { 424 try { 425 event.setSession(this); 426 427 EventLogController.getInstance().logEvent(event); 428 } catch (LogException e) { 429 throw new SessionException("Error logging event",e); 430 } 431 432 } 433 434 435 440 public static String generateSessionId() { 441 return (generateSessionId(m_nDefaultNumChars)); 442 } 443 444 445 448 public String toString() { 449 StringBuffer strbuf = new StringBuffer (); 450 SimpleDateFormat formatter = new SimpleDateFormat (DB_DATEFORMAT); 451 452 try { 453 strbuf 454 .append(" [") 455 .append("Session_id:") 456 .append(m_sSessionId) 457 .append(" for user_id:") 458 .append(m_usrPtr.getKey()) 459 .append(", timeout:") 460 .append( 461 (m_dtTimeout != null) 462 ? formatter.format(m_dtTimeout) 463 : "null") 464 .append(", Timed Out?:") 465 .append(m_bTimedOut) 466 .append(", lagtime:") 467 .append( 468 (m_dtLagTime != null) 469 ? formatter.format(m_dtLagTime) 470 : "null") 471 .append(", Lag timed out?:") 472 .append(isLagTimedOut()) 473 .append(" ]"); 474 } catch (Exception e) { 475 m_logger.log(Level.WARNING, e.getLocalizedMessage(), e); 476 } 477 478 return strbuf.toString(); 479 } 480 481 486 public void delete() throws SessionException { 487 488 try { 489 DeleteStatement delete = new DeleteStatement(); 490 ColumnRef crSessId = 491 new Session(m_dsi).getInstanceColumnRef(CLMN_SESSION_ID); 492 delete.addWhereCondition(crSessId, "=", m_sSessionId); 493 m_dsi.execute(delete); 494 495 WebPageEngineCache.getInstance(m_dsi).changeObject( 496 m_sSessionId, 497 AbstractCache.CHANGE_DELETE, 498 this); 499 } catch (DataStoreException e) { 500 throw new SessionException("Error occured deleting from DB",e); 501 } catch (CacheException e) { 502 throw new SessionException("Error getting webpage engine cache",e); 503 } 504 } 505 506 507 510 public ColumnRef getInstanceColumnRef(String sColumn, boolean bIsHist) 511 throws DataStoreException { 512 return getInstanceColumnRef(sColumn); 513 } 514 515 518 public JoinConditions getInstanceJoinConditions( 519 String sObjectTag, 520 boolean bIsOuter) 521 throws DataStoreException { 522 return null; 524 } 525 526 529 public List processResultSet(CachedResultSet resultSet,SelectStatement select) { 530 return null; 532 } 533 534 537 public List processResultSet(CachedResultSet resultSet,SelectStatement select, int limit) { 538 return null; 540 } 541 542 545 public String getDBTableName() { 546 return TBL_SESSION; 547 } 548 549 557 public Element publish(HarmoniseOutput output) throws PublishException { 558 Element xnSession = output.createElement(TAG_SESSION); 559 xnSession.setAttribute(AbstractObject.ATTRIB_ID, getSessionId()); 560 561 return xnSession; 562 } 563 564 567 public Element publish(Template template, HarmoniseOutput output, State state) throws PublishException { 568 Element resultEl = null; 569 570 try { 571 572 resultEl = 573 publish(template.getTemplateRootElement(), output, state); 574 } catch (DataAccessException e) { 575 throw new PublishException(e); 576 } 577 578 return resultEl; 579 } 580 581 584 public Element publish(Element topEl, HarmoniseOutput output, State state) throws PublishException { 585 Element xnSession = output.createElement(TAG_SESSION); 586 xnSession.setAttribute(AbstractObject.ATTRIB_ID, getSessionId()); 587 588 return xnSession; 589 } 590 591 594 public void populate(Element xmlElement, State state) throws PopulateException { 595 if(xmlElement.getTagName().equals(TAG_SESSION)) { 596 m_sSessionId = xmlElement.getAttribute(AbstractObject.ATTRIB_ID); 597 } 598 599 } 600 601 604 public String getTagName() { 605 return TAG_SESSION; 606 } 607 608 609 612 public int getId() { 613 return -1; 615 } 616 617 620 621 622 631 protected User logon(Element logon, State state) throws SessionException { 632 String sName = ""; 633 String sPassword = ""; 634 635 Element userEl = 637 (Element) logon.getElementsByTagName(User.TAG_USER).item(0); 638 639 NodeList nodes = userEl.getChildNodes(); 641 642 for (int i = 0; i < nodes.getLength(); i++) { 643 Element el = (Element) nodes.item(i); 644 645 if (el.getTagName().equals(User.TAG_NAME)) { 646 sName = el.getFirstChild().getNodeValue(); 647 } else if (el.getTagName().equals(User.TAG_PASSWORD)) { 648 sPassword = el.getFirstChild().getNodeValue(); 649 } 650 } 651 652 User user = null; 653 try { 654 UserAuthenticator authenticator = UserAuthenticatorFactory.getAuthenticator(); 656 user = authenticator.getUser(sName, sPassword); 657 658 int nId = user.getId(); 659 user = 660 (User) HarmoniseObjectFactory.instantiatePublishableObject( 661 m_dsi, 662 new User().getClass().getName(), 663 nId); 664 } catch (HarmoniseFactoryException e) { 665 throw new SessionException("Error occured getting user from factory",e); 666 } 667 catch (UserAuthenticationException e) { 668 m_logger.log(Level.WARNING, e.getLocalizedMessage(), e); 669 } 670 671 setDefaultUser(false); 672 673 return user; 674 } 675 676 677 684 protected boolean isTimedOut() throws SessionException { 685 686 java.util.Date dtNow = new java.util.Date (); 687 688 if (m_dtTimeout == null) { 689 throw new RuntimeException ("Timeout is null for this user " + this); 690 } 691 692 if (dtNow.after(m_dtTimeout)) { 693 694 DeleteStatement delete = new DeleteStatement(); 695 696 delete(); 698 699 m_bTimedOut = true; 700 m_sSessionId = ""; 701 } 702 703 return m_bTimedOut; 704 } 705 706 707 714 protected ColumnRef getInstanceColumnRef(String sColumn) 715 throws DataStoreException { 716 ColumnRef returnColRef = null; 717 718 if (sColumn.equals(CLMN_SESSION_ID)) { 719 return new ColumnRef(TBL_SESSION, CLMN_SESSION_ID, ColumnRef.TEXT); 720 } else if (sColumn.equals(CLMN_USER_ID)) { 721 return new ColumnRef(TBL_SESSION, CLMN_USER_ID, ColumnRef.NUMBER); 722 } else if (sColumn.equals(CLMN_SESSION_TIMEOUT)) { 723 return new ColumnRef( 724 TBL_SESSION, 725 CLMN_SESSION_TIMEOUT, 726 ColumnRef.DATE); 727 } else if (sColumn.equals(CLMN_SESSION_DATE)) { 728 return new ColumnRef( 729 TBL_SESSION, 730 CLMN_SESSION_DATE, 731 ColumnRef.DATE); 732 } else if (sColumn.equals(CLMN_TYPE)) { 733 return new ColumnRef(TBL_SESSION, CLMN_TYPE, ColumnRef.DATE); 734 } 735 736 if (returnColRef != null) { 737 return returnColRef; 738 } else { 739 throw new InvalidColumnReferenceException( 740 "No column of the name [" + sColumn + "] in Session"); 741 } 742 } 743 744 745 751 protected boolean isDefaultUser() { 752 return m_bDefaultUser; 753 } 754 755 760 protected void setDefaultUser(boolean defaultUser) { 761 m_bDefaultUser = defaultUser; 762 } 763 764 769 protected void setTimeout(int nTimeout) { 770 m_nTimeout = nTimeout; 771 772 java.util.Date dtNow = new java.util.Date (); 774 m_dtTimeout = 775 new java.util.Date (dtNow.getTime() + (m_nTimeout * 60 * 1000)); 776 } 777 778 785 protected void setLagTime(int nTimeout) throws ConfigException { 786 java.util.Date dtNow = new java.util.Date (); 788 m_dtLagTime = 789 new java.util.Date (dtNow.getTime() + calculateLagTime(nTimeout)); 790 } 791 792 798 protected void setDetailsFromId(String sSessId) throws SessionException { 799 ResultSet rs = null; 800 801 if (sSessId == null || sSessId.length() == 0) { 802 if(m_logger.isLoggable(Level.INFO)) { 803 m_logger.logp(Level.INFO, this.getClass().getName(), "setDetailFromId", "Invalid session id to process; null value or length = 0"); 804 } 805 throw new InvalidSessionIdException(); 806 } 807 808 SelectStatement select = new SelectStatement(); 809 810 try { 811 select.addSelectColumn(getInstanceColumnRef(CLMN_USER_ID)); 812 select.addSelectColumn(getInstanceColumnRef(CLMN_SESSION_TIMEOUT)); 813 814 select.addWhereCondition( 815 getInstanceColumnRef(CLMN_SESSION_ID), 816 "=", 817 removeSessionIdPrefix(sSessId)); 818 } catch (DataStoreException e) { 819 m_logger.log(Level.WARNING, "Error occured building query to populate session " + sSessId, e); 820 throw new SessionException("Error occured building query", e); 821 } 822 823 try { 824 825 rs = m_dsi.execute(select); 826 827 if (rs.next()) { 828 829 User usr = 830 (User) HarmoniseObjectFactory.instantiatePublishableObject( 831 m_dsi, 832 m_QueryUser.getClass().getName(), 833 rs.getInt(1)); 834 835 if(usr == null || usr.exists() == false) { 836 837 DeleteStatement delete = new DeleteStatement(); 838 839 delete.addWhereCondition(getInstanceColumnRef(CLMN_SESSION_ID), 840 "=", 841 removeSessionIdPrefix(sSessId)); 842 843 m_dsi.execute(delete); 844 845 throw new InvalidSessionIdException(); 846 } 847 848 m_usrPtr = CacheHandler.getInstance(m_dsi).getCachePointer(usr); 849 m_dtTimeout = rs.getTimestamp(2); 850 851 int timeout = 852 Integer.parseInt( 853 ConfigSettings.getProperty( 854 Session.DEFAULT_TIMEOUT_PNAME)); 855 setLagTime(timeout); 856 m_sSessionId = sSessId; 857 } else { 858 int index = sSessId.indexOf(DEFAULT_USER_PREFIX); 859 860 if (index > -1) { 861 862 m_sSessionId = sSessId; 863 864 int timeout = 865 Integer.parseInt( 866 ConfigSettings.getProperty( 867 Session.DEFAULT_TIMEOUT_PNAME)); 868 initialize(getDefaultUser(), timeout); 869 } else { 870 if(m_logger.isLoggable(Level.INFO)) { 871 m_logger.logp(Level.INFO, this.getClass().getName(), "setDetailFromId", "Session " + sSessId + " is not valid"); 872 } 873 throw new InvalidSessionIdException(); 874 } 875 } 876 } catch (SQLException e) { 877 throw new SessionException("SQL exception", e); 878 } catch (NumberFormatException e) { 879 throw new SessionException("Error parsing default timeout", e); 880 } catch (ConfigException e) { 881 throw new SessionException("Error getting config setting", e); 882 } catch (HarmoniseFactoryException e) { 883 throw new SessionException("Error getting user from factory", e); 884 } catch (DataStoreException e) { 885 m_logger.log(Level.WARNING, e.getMessage(), e); 886 throw new SessionException("Error processing query", e); 887 } catch (CacheException e) { 888 throw new SessionException(e.getLocalizedMessage(),e); 889 } finally { 890 if (rs != null) { 891 try { 892 rs.close(); 893 } catch (SQLException e) { 894 throw new SessionException("Error closing result set", e); 895 } 896 } 897 } 898 } 899 900 901 906 protected void updateTimeout(int nTimeout) throws SessionException { 907 if (!isDefaultUser() && isTimedOut()) { 908 if(m_logger.isLoggable(Level.INFO)) { 909 m_logger.info("Session " + m_sSessionId + " timed out"); 910 } 911 912 throw new SessionTimeOutException("Session: " + this.m_sSessionId); 913 } else { 914 915 m_nTimeout = nTimeout; 916 917 java.util.Date dtNow = new java.util.Date (); 918 m_dtTimeout = 919 new java.util.Date (dtNow.getTime() + (m_nTimeout * 60 * 1000)); 920 921 922 try { 923 updateSession(); 924 } catch (ConfigException e) { 925 throw new SessionException("Error occured accessig config setting",e); 926 } catch (DataStoreException e) { 927 throw new SessionException("Error occured updating session",e); 928 } 929 930 } 931 } 932 933 934 942 protected boolean logoff(Element logoff_tag, String sessId) throws DataStoreException { 943 944 if(m_logger.isLoggable(Level.FINE)) { 945 m_logger.logp(Level.FINE, this.getClass().getName(), "logoff", "Loging off session " + sessId); 946 } 947 948 NodeList nodes = logoff_tag.getChildNodes(); 952 953 for (int i = 0; i < nodes.getLength(); i++) { 954 Element el = (Element) nodes.item(i); 955 956 if (el.getTagName().equals(TAG_SESSION)) { 957 sessId = el.getAttribute(AbstractObject.ATTRIB_ID); 958 } 959 } 960 961 if (sessId.length() == 0) { 962 if(m_logger.isLoggable(Level.SEVERE)) { 963 m_logger.logp(Level.SEVERE, this.getClass().getName(), "logoff", "Invalid session to log off - [" + sessId +"]"); 964 } 965 throw new RuntimeException ( 966 "Attempt to log off without a valid session id" 967 + ", session id:" 968 + sessId); 969 } 970 971 User user = getDefaultUser(); 973 updateUser(user); 974 setDefaultUser(true); 975 976 return true; 977 } 978 979 980 986 protected int getLagPercent() throws ConfigException { 987 if (m_nLagPercent < 0) { 988 m_nLagPercent = 989 ConfigSettings.getIntProperty( 990 LAG_PERCENT_PNAME, 991 sDefaultLagPercent); 992 } 993 994 return m_nLagPercent; 995 } 996 997 1004 protected int calculateLagTime(int timeout) throws ConfigException { 1005 int lagtime = (timeout * 60 * 1000 * getLagPercent()) / 100; 1006 1007 return lagtime; 1008 } 1009 1010 1015 protected boolean isLagTimedOut() { 1016 boolean lagTimedOut = false; 1017 1018 java.util.Date dtNow = new java.util.Date (); 1019 1020 if (dtNow.after(m_dtLagTime)) { 1021 lagTimedOut = true; 1022 } 1023 1024 return lagTimedOut; 1025 } 1026 1027 1034 protected void updateUser(User user) throws DataStoreException { 1035 1036 try { 1037 m_usrPtr = CacheHandler.getInstance(m_dsi).getCachePointer(user); 1038 } catch (CacheException e) { 1039 throw new DataStoreException(e.getLocalizedMessage(),e); 1040 } 1041 1042 updateDataBase(); 1043 } 1044 1045 1048 1049 1056 private void updateSession() throws ConfigException, DataStoreException { 1057 if (isLagTimedOut()) { 1058 updateDataBase(); 1059 1060 java.util.Date dtNow = new java.util.Date (); 1061 m_dtLagTime = 1062 new java.util.Date ( 1063 dtNow.getTime() + calculateLagTime(m_nTimeout)); 1064 } 1065 } 1066 1067 1072 private void updateDataBase() throws DataStoreException { 1073 UpdateStatement update = new UpdateStatement(); 1074 1075 User usr = null; 1076 try { 1077 usr = (User) m_usrPtr.getObject(); 1078 } catch (CacheException e) { 1079 throw new DataStoreException(e.getLocalizedMessage(),e); 1080 } 1081 1082 update.addColumnValue( 1083 getInstanceColumnRef(CLMN_USER_ID), 1084 usr.getId()); 1085 update.addColumnValue( 1086 getInstanceColumnRef(CLMN_SESSION_TIMEOUT), 1087 m_dtTimeout); 1088 update.addWhereCondition( 1089 getInstanceColumnRef(CLMN_SESSION_ID), 1090 "=", 1091 removeSessionIdPrefix(m_sSessionId)); 1092 1093 m_dsi.execute(update); 1094 1095 } 1096 1097 1098 1104 private static String generateSessionId(int nNumChars) { 1105 String sSession = ""; 1106 SecureRandom rnd = new SecureRandom (); 1107 StringBuffer buffer = new StringBuffer (); 1108 1109 for (int i = 0; i < nNumChars; i++) { 1110 int nIndex = (int) (rnd.nextDouble() * (sCharBase.length() - 1)); 1111 buffer.append(sCharBase.charAt(nIndex)); 1112 } 1113 1114 sSession = buffer.toString(); 1115 1116 return sSession; 1117 } 1118 1119 1120 1127 private boolean isSessionIdUnique(String sSessId) throws SessionException { 1128 ResultSet rs = null; 1129 boolean bIsUnique = true; 1130 1131 try { 1132 SelectStatement select = new SelectStatement(); 1133 select.addSelectColumn(getInstanceColumnRef(CLMN_SESSION_ID)); 1134 select.addWhereCondition( 1135 getInstanceColumnRef(CLMN_SESSION_ID), 1136 "=", 1137 sSessId); 1138 1139 String temp = m_dsi.getSelectStatement(select); 1140 rs = m_dsi.executeQuery(select); 1141 1142 if (rs.next()) { 1143 bIsUnique = false; 1144 } 1145 } catch (DataStoreException e) { 1146 throw new SessionException("Error occured on query", e); 1147 } catch (SQLException e) { 1148 throw new SessionException("Error occured on query", e); 1149 } finally { 1150 if (rs != null) { 1151 try { 1152 rs.close(); 1153 } catch (SQLException e) { 1154 throw new SessionException( 1155 "Error occured closing result set", 1156 e); 1157 } 1158 } 1159 } 1160 1161 return bIsUnique; 1162 } 1163 1164 1165 1171 private void removeAllSessionEntries(int userKey) throws SessionException { 1172 DeleteStatement delete = null; 1173 1174 try { 1175 delete = new DeleteStatement(); 1176 delete.setTable(TBL_SESSION); 1177 delete.addWhereCondition( 1178 getInstanceColumnRef(CLMN_USER_ID), 1179 "=", 1180 userKey); 1181 1182 m_dsi.execute(delete); 1183 } catch (DataStoreException e) { 1184 throw new SessionException("Error removing sessions", e); 1185 } 1186 } 1187 1188 1189 1194 private User getDefaultUser() { 1195 User user = new User(m_dsi,DEFAULT_USER_ID); 1196 1197 return user; 1198 } 1199 1200 1209 private String initialize(User user, int nTimeout) throws SessionException { 1210 1211 1212 try { 1213 m_usrPtr = CacheHandler.getInstance(m_dsi).getCachePointer(user); 1214 } catch (CacheException e) { 1215 throw new SessionException(e.getLocalizedMessage(),e); 1216 } 1217 1218 setTimeout(nTimeout); 1219 try { 1220 setLagTime(nTimeout); 1221 } catch (ConfigException e) { 1222 throw new SessionException("Error setting lag time", e); 1223 } 1224 1225 String sSessId = ""; 1226 1227 if (m_sSessionId.equals("") == true) { 1228 sSessId = generateSessionId(); 1229 } else { 1230 sSessId = removeSessionIdPrefix(m_sSessionId); 1231 } 1232 1233 while (!isSessionIdUnique(sSessId)) { 1234 sSessId = generateSessionId(); 1235 } 1236 1237 int userId = user.getId(); 1238 1239 if (userId != this.DEFAULT_USER_ID) { 1242 m_sSessionId = LOGGED_IN_USER_PREFIX + sSessId; 1243 removeAllSessionEntries(userId); 1244 } else { 1245 m_sSessionId = DEFAULT_USER_PREFIX + sSessId; 1246 } 1247 1248 save(); 1249 1250 return m_sSessionId; 1251 } 1252 1253 1254 1255} | Popular Tags |