/**
  * Returns the approximate size (in bytes) of the XML messages stored for a particular user.
  *
  * @param username the username of the user.
  * @return the approximate size of stored messages (in bytes).
  */
 public int getSize(String username) {
   // See if the size is cached.
   if (sizeCache.containsKey(username)) {
     return sizeCache.get(username);
   }
   int size = 0;
   Connection con = null;
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     con = DbConnectionManager.getConnection();
     pstmt = con.prepareStatement(SELECT_SIZE_OFFLINE);
     pstmt.setString(1, username);
     rs = pstmt.executeQuery();
     if (rs.next()) {
       size = rs.getInt(1);
     }
     // Add the value to cache.
     sizeCache.put(username, size);
   } catch (Exception e) {
     Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
   } finally {
     DbConnectionManager.closeConnection(rs, pstmt, con);
   }
   return size;
 }
 /**
  * Set the presence of this session
  *
  * @param presence The presence for the session
  */
 public void setPresence(Presence presence) {
   Presence oldPresence = this.presence;
   this.presence = presence;
   if (oldPresence.isAvailable() && !this.presence.isAvailable()) {
     // The client is no longer available
     sessionManager.sessionUnavailable(this);
     // Mark that the session is no longer initialized. This means that if the user sends
     // an available presence again the session will be initialized again thus receiving
     // offline messages and offline presence subscription requests
     setInitialized(false);
     // Notify listeners that the session is no longer available
     PresenceEventDispatcher.unavailableSession(this, presence);
   } else if (!oldPresence.isAvailable() && this.presence.isAvailable()) {
     // The client is available
     sessionManager.sessionAvailable(this, presence);
     wasAvailable = true;
     // Notify listeners that the session is now available
     PresenceEventDispatcher.availableSession(this, presence);
   } else if (this.presence.isAvailable()
       && oldPresence.getPriority() != this.presence.getPriority()) {
     // The client has changed the priority of his presence
     sessionManager.changePriority(this, oldPresence.getPriority());
     // Notify listeners that the priority of the session/resource has changed
     PresenceEventDispatcher.presenceChanged(this, presence);
   } else if (this.presence.isAvailable()) {
     // Notify listeners that the show or status value of the presence has changed
     PresenceEventDispatcher.presenceChanged(this, presence);
   }
   if (ClusterManager.isClusteringStarted()) {
     // Track information about the session and share it with other cluster nodes
     Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
     cache.put(getAddress().toString(), new ClientSessionInfo(this));
   }
 }
 /**
  * Sets the Privacy list that overrides the default privacy list. This list affects only this
  * session and only for the duration of the session.
  *
  * @param activeList the Privacy list that overrides the default privacy list.
  */
 public void setActiveList(PrivacyList activeList) {
   this.activeList = activeList != null ? activeList.getName() : null;
   if (ClusterManager.isClusteringStarted()) {
     // Track information about the session and share it with other cluster nodes
     Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
     cache.put(getAddress().toString(), new ClientSessionInfo(this));
   }
 }
 /**
  * Sets if the user requested to not receive offline messages when sending an available presence.
  * The user may send a disco request with node "http://jabber.org/protocol/offline" so that no
  * offline messages are sent to the user when he becomes online. If the user is connected from
  * many resources then if one of the sessions stopped the flooding then no session should flood
  * the user.
  *
  * @param offlineFloodStopped if the user requested to not receive offline messages when sending
  *     an available presence.
  */
 public void setOfflineFloodStopped(boolean offlineFloodStopped) {
   this.offlineFloodStopped = offlineFloodStopped;
   if (ClusterManager.isClusteringStarted()) {
     // Track information about the session and share it with other cluster nodes
     Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
     cache.put(getAddress().toString(), new ClientSessionInfo(this));
   }
 }
 /**
  * Returns a specific privacy list of the specified user or <tt>null</tt> if none was found.
  *
  * @param username the name of the user to get his privacy list.
  * @param listName the name of the list to get.
  * @return a privacy list of the specified user or <tt>null</tt> if none was found.
  */
 public PrivacyList getPrivacyList(String username, String listName) {
   // Check if we have a list in the cache
   String cacheKey = getCacheKey(username, listName);
   PrivacyList list = listsCache.get(cacheKey);
   if (list == null) {
     // Load the list from the database
     list = provider.loadPrivacyList(username, listName);
     if (list != null) {
       listsCache.put(cacheKey, list);
     }
   }
   return list;
 }
 /**
  * Sets the default Privacy list used for the session's user. This list is processed if there is
  * no active list set for the session.
  *
  * @param defaultList the default Privacy list used for the session's user.
  */
 public void setDefaultList(PrivacyList defaultList) {
   // Do nothing if nothing has changed
   if ((this.defaultList == null && defaultList == null)
       || (defaultList != null && defaultList.getName().equals(this.defaultList))) {
     return;
   }
   this.defaultList = defaultList != null ? defaultList.getName() : null;
   if (ClusterManager.isClusteringStarted()) {
     // Track information about the session and share it with other cluster nodes
     Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache();
     cache.put(getAddress().toString(), new ClientSessionInfo(this));
   }
 }
  /**
   * Adds a message to this message store. Messages will be stored and made available for later
   * delivery.
   *
   * @param message the message to store.
   */
  public void addMessage(Message message) {
    if (message == null) {
      return;
    }
    if (!shouldStoreMessage(message)) {
      return;
    }
    JID recipient = message.getTo();
    String username = recipient.getNode();
    // If the username is null (such as when an anonymous user), don't store.
    if (username == null || !UserManager.getInstance().isRegisteredUser(recipient)) {
      return;
    } else if (!XMPPServer.getInstance()
        .getServerInfo()
        .getXMPPDomain()
        .equals(recipient.getDomain())) {
      // Do not store messages sent to users of remote servers
      return;
    }

    long messageID = SequenceManager.nextID(JiveConstants.OFFLINE);

    // Get the message in XML format.
    String msgXML = message.getElement().asXML();

    Connection con = null;
    PreparedStatement pstmt = null;
    try {
      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(INSERT_OFFLINE);
      pstmt.setString(1, username);
      pstmt.setLong(2, messageID);
      pstmt.setString(3, StringUtils.dateToMillis(new java.util.Date()));
      pstmt.setInt(4, msgXML.length());
      pstmt.setString(5, msgXML);
      pstmt.executeUpdate();
    } catch (Exception e) {
      Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    } finally {
      DbConnectionManager.closeConnection(pstmt, con);
    }

    // Update the cached size if it exists.
    if (sizeCache.containsKey(username)) {
      int size = sizeCache.get(username);
      size += msgXML.length();
      sizeCache.put(username, size);
    }
  }
 /**
  * Deletes an existing privacy list of a user. If the privacy list being deleted was the default
  * list then the user will end up with no default list. Therefore, the user will have to set a new
  * default list.
  *
  * @param username the username of the list owner.
  * @param listName the name of the list being deleted.
  */
 public void deletePrivacyList(String username, String listName) {
   // Trigger event that a privacy list is being deleted
   for (PrivacyListEventListener listener : listeners) {
     listener.privacyListDeleting(listName);
   }
   // Remove the list from the cache
   listsCache.remove(getCacheKey(username, listName));
   // Delete the privacy list from the DB
   provider.deletePrivacyList(username, listName);
   // Check if deleted list was the default list
   PrivacyList defaultList = listsCache.get(getDefaultCacheKey(username));
   if (defaultList != null && listName.equals(defaultList.getName())) {
     listsCache.remove(getDefaultCacheKey(username));
   }
 }
 /**
  * Returns true if the nonce was generated usig <code>generateNonce</code> and if this is the
  * first check for that nonce.
  *
  * @param nonce the nonce to be checked
  * @return true if the nonce if the nonce was generated and this is the first check for that nonce
  */
 public boolean isValidNonce(String nonce) {
   Long time = nonceCache.remove(nonce);
   if (time == null) {
     return false;
   }
   return System.currentTimeMillis() - time < JiveConstants.MINUTE;
 }
 public synchronized Element getVCard(String username) {
   Element vcard = vcardCache.get(username);
   if (vcard == null) {
     return cacheVCard(username);
   }
   return vcard;
 }
 /**
  * Returns the default privacy list of the specified user or <tt>null</tt> if none was found.
  *
  * @param username the name of the user to get his default list.
  * @return the default privacy list of the specified user or <tt>null</tt> if none was found.
  */
 public PrivacyList getDefaultPrivacyList(String username) {
   // Check if we have the default list in the cache
   String cacheKey = getDefaultCacheKey(username);
   PrivacyList list = listsCache.get(cacheKey);
   if (list == null) {
     synchronized (username.intern()) {
       list = listsCache.get(cacheKey);
       if (list == null) {
         // Load default list from the database
         list = provider.loadDefaultPrivacyList(username);
         if (list != null) {
           listsCache.put(cacheKey, list);
         }
       }
     }
   }
   return list;
 }
  synchronized Element cacheVCard(String username) {
    Element vCardElement = null;
    User user = UnfortunateLackOfSpringSupportFactory.getValidUsers().getUserByJid(username);
    if (user != null) {
      Element avatarFromDB = getAvatarCopy(defaultProvider.loadVCard(username));
      vCardElement = RestInterface.buildVCardFromXMLContactInfo(user, avatarFromDB);
      if (vCardElement != null) {
        vcardCache.remove(username);
        vcardCache.put(username, vCardElement);
      } else {
        logger.error("In cacheVCard buildVCardFromXMLContactInfo failed! ");
      }
    } else {
      logger.error("In cacheVCard Failed to find peer SIP user account for XMPP user " + username);
    }

    return vCardElement;
  }
  public Group getGroup(String name) throws GroupNotFoundException {
    try {
      Cache<String, org.jivesoftware.openfire.crowd.jaxb.Group> groupCache =
          CacheFactory.createLocalCache(GROUP_CACHE_NAME);
      org.jivesoftware.openfire.crowd.jaxb.Group group = groupCache.get(name);
      if (group == null) {
        group = manager.getGroup(name);
        groupCache.put(name, group);
      }
      Collection<JID> members = getGroupMembers(name);
      Collection<JID> admins = Collections.emptyList();
      return new Group(name, group.description, members, admins);

    } catch (RemoteException re) {
      LOG.error("Failure to load group:" + String.valueOf(name), re);
      throw new GroupNotFoundException(re);
    }
  }
 /**
  * Deletes all privacy lists of a user. This may be necessary when a user is being deleted from
  * the system.
  *
  * @param username the username of the list owner.
  */
 public void deletePrivacyLists(String username) {
   for (String listName : provider.getPrivacyLists(username).keySet()) {
     // Remove the list from the cache
     listsCache.remove(getCacheKey(username, listName));
     // Trigger event that a privacy list is being deleted
     for (PrivacyListEventListener listener : listeners) {
       listener.privacyListDeleting(listName);
     }
   }
   // Delete user privacy lists from the DB
   provider.deletePrivacyLists(username);
 }
 /**
  * Creates a new privacy list for the specified user.
  *
  * @param username the username of the list owner.
  * @param listName the name of the new privacy list.
  * @param listElement the XML that specifies the list and its items.
  * @return the newly created PrivacyList.
  */
 public PrivacyList createPrivacyList(String username, String listName, Element listElement) {
   // Create new list
   PrivacyList list = new PrivacyList(username, listName, false, listElement);
   // Add new list to cache
   listsCache.put(getCacheKey(username, listName), list);
   // Save new  list to database
   provider.createPrivacyList(username, list);
   // Trigger event that a new privacy list has been created
   for (PrivacyListEventListener listener : listeners) {
     listener.privacyListCreated(list);
   }
   return list;
 }
  /**
   * SipXconfig Does NOT support "delete user profile". So only the big cache (database) record is
   * removed.
   */
  @Override
  public synchronized void deleteVCard(String username) {
    vcardCache.remove(username);
    defaultProvider.deleteVCard(username);

    // Refill the cache
    Element vCard = cacheVCard(username);
    try {
      Util.updateAvatar(username, vCard);
    } catch (Exception e) {
      logger.error("Cannot send update Avatar notification", e);
    }
  }
  public CrowdGroupProvider() {
    String propertyValue = JiveGlobals.getProperty(JIVE_CROWD_GROUPS_CACHE_TTL_SECS);
    int ttl =
        (propertyValue == null || propertyValue.trim().length() == 0)
            ? CACHE_TTL
            : Integer.parseInt(propertyValue);

    Cache<String, Collection<JID>> groupMembershipCache =
        CacheFactory.createLocalCache(GROUP_MEMBERSHIP_CACHE_NAME);
    groupMembershipCache.setMaxCacheSize(-1);
    groupMembershipCache.setMaxLifetime(ttl * 1000); // msecs instead of sec - see Cache API

    Cache<JID, Collection<String>> userMembershipCache =
        CacheFactory.createLocalCache(USER_MEMBERSHIP_CACHE_NAME);
    userMembershipCache.setMaxCacheSize(-1);
    userMembershipCache.setMaxLifetime(ttl * 1000); // msecs instead of sec - see Cache API

    Cache<String, org.jivesoftware.openfire.crowd.jaxb.Group> groupCache =
        CacheFactory.createLocalCache(GROUP_CACHE_NAME);
    groupCache.setMaxCacheSize(-1);
    groupCache.setMaxLifetime(ttl * 1000); // msecs instead of sec - see Cache API
  }
 /**
  * Sets a given privacy list as the new default list of the user.
  *
  * @param username the name of the user that is setting a new default list.
  * @param newDefault the new default privacy list.
  * @param oldDefault the previous privacy list or <tt>null</tt> if no default list existed.
  */
 public void changeDefaultList(String username, PrivacyList newDefault, PrivacyList oldDefault) {
   // TODO Analyze concurrency issues when other resource may log in while doing this change
   if (oldDefault != null) {
     // Update old default list to become just another list
     oldDefault.setDefaultList(false);
     provider.updatePrivacyList(username, oldDefault);
   }
   // Update new list to become the default
   newDefault.setDefaultList(true);
   // Set new default list in the cache
   listsCache.put(getDefaultCacheKey(username), newDefault);
   // Update both lists in the database
   provider.updatePrivacyList(username, newDefault);
 }
 private void removeUsernameFromSizeCache(String username) {
   // Update the cached size if it exists.
   if (sizeCache.containsKey(username)) {
     sizeCache.remove(username);
   }
 }
 /**
  * Generates a new nonce. The <code>isValidNonce</code> method will return true when using nonces
  * generated by this method.
  *
  * @return a unique nonce
  */
 public String generateNonce() {
   String nonce = String.valueOf(nonceGenerator.nextLong());
   nonceCache.put(nonce, System.currentTimeMillis());
   return nonce;
 }
 protected FileTransfer retrieveFileTransfer(String key) {
   return fileTransferMap.get(key);
 }
 protected void cacheFileTransfer(String key, FileTransfer transfer) {
   fileTransferMap.put(key, transfer);
 }
 public void fireFileTransferIntercept(FileTransferProgress transfer, boolean isReady)
     throws FileTransferRejectedException {
   fireFileTransferIntercept(fileTransferMap.get(transfer.getSessionID()), isReady);
 }