/* Chat module: Roster

Integration of Roster Items and Presence Subscriptions
http://xmpp.org/rfcs/rfc3921.html#int
default - Mutual Subscription

----------------------------------------------------------------------------- 
@namespace QB.chat.roster
480307
function RosterProxy(options) {
    this.service = options.service;
    this.helpers = options.helpers;
    this.connection = options.stropheClient;
    this.Client = options.xmppClient;
    this.nodeStanzasCallbacks = options.nodeStanzasCallbacks;
    //
    this.contacts = {};
}
460553
private final void addToMessage(SubscriptionMessageHandler messageHandler, 
                                  Hashtable subscriptions)  
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) 
      SibTr.entry(tc, "addToMessage", 
        new Object[]{messageHandler, subscriptions});
    // Get the enumeration of the subscriptions.
    Enumeration enu = subscriptions.elements();

    while (enu.hasMoreElements())
    {
      final MESubscription subscription = (MESubscription) enu.nextElement();

      // Add this subscription into the message.
      messageHandler.addSubscriptionToMessage(subscription, isLocalBus);

    }
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addToMessage");
  }
457413
private static MultiUserChat getMuc(XMPPConnection connection, Jid jid) {
        EntityBareJid ebj = jid.asEntityBareJidIfPossible();
        if (ebj == null) {
            return null;
        }

        MultiUserChatManager mucm = MultiUserChatManager.getInstanceFor(connection);
        Set<EntityBareJid> joinedRooms = mucm.getJoinedRooms();
        if (joinedRooms.contains(ebj)) {
            return mucm.getMultiUserChat(ebj);
        }

        return null;
    }
876045
def subscribe(self, peer_jid):
        
        self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare())
729737
private void fireRosterPresenceEvent(final Presence presence) {
        synchronized (rosterListenersAndEntriesLock) {
            for (RosterListener listener : rosterListeners) {
                listener.presenceChanged(presence);
            }
        }
    }
1272451
@Override
  public PostingsFormat postingsFormat() {
    initDelegate();
    if (delegate.postingsFormat() instanceof PerFieldPostingsFormat) {
      Codec defaultCodec = Codec.getDefault();
      PostingsFormat defaultPostingsFormat = defaultCodec.postingsFormat();
      if (defaultPostingsFormat instanceof PerFieldPostingsFormat) {
        defaultPostingsFormat = ((PerFieldPostingsFormat) defaultPostingsFormat)
            .getPostingsFormatForField(null);
        if ((defaultPostingsFormat == null)
            || (defaultPostingsFormat instanceof PerFieldPostingsFormat)) {
          // fallback option
          return new MtasCodecPostingsFormat(
              PostingsFormat.forName("Lucene70"));
        } else {
          return new MtasCodecPostingsFormat(defaultPostingsFormat);
        }
      } else {
        return new MtasCodecPostingsFormat(defaultPostingsFormat);
      }
    } else {
      return new MtasCodecPostingsFormat(delegate.postingsFormat());
    }
  }
199219
private void handlePacket(Stanza packet) {
        if (packet instanceof Presence) {
            Presence presence = (Presence) packet;

            // The workgroup can send us a number of different presence packets. We
            // check for different packet extensions to see what type of presence
            // packet it is.

            Resourcepart queueName = presence.getFrom().getResourceOrNull();
            WorkgroupQueue queue = queues.get(queueName);
            // If there isn't already an entry for the queue, create a new one.
            if (queue == null) {
                queue = new WorkgroupQueue(queueName);
                queues.put(queueName, queue);
            }

            // QueueOverview packet extensions contain basic information about a queue.
            QueueOverview queueOverview = presence.getExtension(QueueOverview.ELEMENT_NAME, QueueOverview.NAMESPACE);
            if (queueOverview != null) {
                if (queueOverview.getStatus() == null) {
                    queue.setStatus(WorkgroupQueue.Status.CLOSED);
                }
                else {
                    queue.setStatus(queueOverview.getStatus());
                }
                queue.setAverageWaitTime(queueOverview.getAverageWaitTime());
                queue.setOldestEntry(queueOverview.getOldestEntry());
                // Fire event.
                fireQueueUsersEvent(queue, queueOverview.getStatus(),
                        queueOverview.getAverageWaitTime(), queueOverview.getOldestEntry(),
                        null);
                return;
            }

            // QueueDetails packet extensions contain information about the users in
            // a queue.
            QueueDetails queueDetails = packet.getExtension(QueueDetails.ELEMENT_NAME, QueueDetails.NAMESPACE);
            if (queueDetails != null) {
                queue.setUsers(queueDetails.getUsers());
                // Fire event.
                fireQueueUsersEvent(queue, null, -1, null, queueDetails.getUsers());
                return;
            }

            // Notify agent packets gives an overview of agent activity in a queue.
            StandardExtensionElement notifyAgents = presence.getExtension("notify-agents", "http://jabber.org/protocol/workgroup");
            if (notifyAgents != null) {
                int currentChats = Integer.parseInt(notifyAgents.getFirstElement("current-chats", "http://jabber.org/protocol/workgroup").getText());
                int maxChats = Integer.parseInt(notifyAgents.getFirstElement("max-chats", "http://jabber.org/protocol/workgroup").getText());
                queue.setCurrentChats(currentChats);
                queue.setMaxChats(maxChats);
                // Fire event.
                // TODO: might need another event for current chats and max chats of queue
                return;
            }
        }
        else if (packet instanceof Message) {
            Message message = (Message) packet;

            // Check if a room invitation was sent and if the sender is the workgroup
            MUCUser mucUser = message.getExtension("x",
                    "http://jabber.org/protocol/muc#user");
            MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null;
            if (invite != null && workgroupJID.equals(invite.getFrom())) {
                String sessionID = null;
                Map<String, List<String>> metaData = null;

                SessionID sessionIDExt = message.getExtension(SessionID.ELEMENT_NAME,
                        SessionID.NAMESPACE);
                if (sessionIDExt != null) {
                    sessionID = sessionIDExt.getSessionID();
                }

                MetaData metaDataExt = message.getExtension(MetaData.ELEMENT_NAME,
                        MetaData.NAMESPACE);
                if (metaDataExt != null) {
                    metaData = metaDataExt.getMetaData();
                }

                this.fireInvitationEvent(message.getFrom(), sessionID, message.getBody(),
                        message.getFrom(), metaData);
            }
        }
    }
904104
NatsSubscription createSubscription(String subject, String queueName, NatsDispatcher dispatcher) {
        if (isClosed()) {
            throw new IllegalStateException("Connection is Closed");
        } else if (isDraining() && (dispatcher == null || dispatcher != this.inboxDispatcher.get())) {
            throw new IllegalStateException("Connection is Draining");
        }

        NatsSubscription sub = null;
        long sidL = nextSid.getAndIncrement();
        String sid = String.valueOf(sidL);

        sub = new NatsSubscription(sid, subject, queueName, this, dispatcher);
        subscribers.put(sid, sub);

        sendSubscriptionMessage(sid, subject, queueName, false);
        return sub;
    }
1025841
@Override
    public OfferRequestPacket parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
        int eventType = parser.getEventType();
        String sessionID = null;
        int timeout = -1;
        OfferContent content = null;
        boolean done = false;
        Map<String, List<String>> metaData = new HashMap<>();

        if (eventType != XmlPullParser.START_TAG) {
            // throw exception
        }

        Jid userJID = ParserUtils.getJidAttribute(parser);
        // Default userID to the JID.
        Jid userID = userJID;

        while (!done) {
            eventType = parser.next();

            if (eventType == XmlPullParser.START_TAG) {
                String elemName = parser.getName();

                if ("timeout".equals(elemName)) {
                    timeout = Integer.parseInt(parser.nextText());
                }
                else if (MetaData.ELEMENT_NAME.equals(elemName)) {
                    metaData = MetaDataUtils.parseMetaData(parser);
                }
                else if (SessionID.ELEMENT_NAME.equals(elemName)) {
                   sessionID = parser.getAttributeValue("", "id");
                }
                else if (UserID.ELEMENT_NAME.equals(elemName)) {
                    userID = ParserUtils.getJidAttribute(parser, "id");
                }
                else if ("user-request".equals(elemName)) {
                    content = UserRequest.getInstance();
                }
                else if (RoomInvitation.ELEMENT_NAME.equals(elemName)) {
                    RoomInvitation invitation = (RoomInvitation) PacketParserUtils
                            .parseExtensionElement(RoomInvitation.ELEMENT_NAME, RoomInvitation.NAMESPACE, parser, xmlEnvironment);
                    content = new InvitationRequest(invitation.getInviter(), invitation.getRoom(),
                            invitation.getReason());
                }
                else if (RoomTransfer.ELEMENT_NAME.equals(elemName)) {
                    RoomTransfer transfer = (RoomTransfer) PacketParserUtils
                            .parseExtensionElement(RoomTransfer.ELEMENT_NAME, RoomTransfer.NAMESPACE, parser, xmlEnvironment);
                    content = new TransferRequest(transfer.getInviter(), transfer.getRoom(), transfer.getReason());
                }
            }
            else if (eventType == XmlPullParser.END_TAG) {
                if ("offer".equals(parser.getName())) {
                    done = true;
                }
            }
        }

        OfferRequestPacket offerRequest =
                new OfferRequestPacket(userJID, userID, timeout, metaData, sessionID, content);
        offerRequest.setType(IQ.Type.set);

        return offerRequest;
    }
227322
@Override
    public RosterExchange parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
                    throws XmlPullParserException, IOException {
        // CHECKSTYLE:OFF
        RosterExchange rosterExchange = new RosterExchange();
        boolean done = false;
        RemoteRosterEntry remoteRosterEntry;
        Jid jid = null;
		String name = "";
		ArrayList<String> groupsName = new ArrayList<>();
        while (!done) {
            int eventType = parser.next();
            if (eventType == XmlPullParser.START_TAG) {
                if (parser.getName().equals("item")) {
                	// Reset this variable since they are optional for each item
					groupsName = new ArrayList<>();
					// Initialize the variables from the parsed XML
                    jid = ParserUtils.getJidAttribute(parser);
                    name = parser.getAttributeValue("", "name");
                }
                if (parser.getName().equals("group")) {
					groupsName.add(parser.nextText());
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (parser.getName().equals("item")) {
					// Create packet.
					remoteRosterEntry = new RemoteRosterEntry(jid, name, groupsName.toArray(new String[groupsName.size()]));
                    rosterExchange.addRosterEntry(remoteRosterEntry);
                }
                if (parser.getName().equals("x")) {
                    done = true;
                }
            }
        }
        // CHECKSTYLE:ON
        return rosterExchange;

    }
730546
function subscriptionDispatcher (topic, data, options, subscriptions) {
    var
      resolver = createResolver(),
      fulfill = resolveUse('fulfilledValues', 'fulfilled', options, resolver),
      reject = resolveUse('rejectedValues', 'rejected', options, resolver);

    resolver.i = subscriptions.length - 1;
    resolver.resume = {
      topic: topic,
      data: data,
      subscriptions: subscriptions,
      fulfill: fulfill,
      reject: reject
    };

    resumeSubscriptionDispatcher(
      topic, data, options, subscriptions, resolver, fulfill, reject
    );
    evaluateLatch(resolver, options);

    return resolver.promise;
  }
822836
function notifyAboutCallState(type) {
    var self = this;
    var messageTo;

    if (currentDialog.type === 3) {
        messageTo = QB.chat.helpers.getRecipientId(currentDialog.occupants_ids, currentUser.id);
    } else {
        messageTo = currentDialog.xmpp_room_jid;
    }

    QB.chat.send(messageTo, {
        type: currentDialogType(),
        extension: {
            notification_type: type,
            dialog_id: currentDialog._id
        }
    });
}
250484
public static void rcvXACommit(CommsByteBuffer request,
                                  Conversation conversation,
                                  int requestNumber,
                                  boolean allocatedFromBufferPool,
                                  boolean partOfExchange)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvXACommit",
                                           new Object[]
                                           {
                                              request,
                                              conversation,
                                              ""+requestNumber,
                                              ""+allocatedFromBufferPool,
                                              ""+partOfExchange
                                            });

      ConversationState convState = (ConversationState) conversation.getAttachment();
      ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();

      boolean onePhase = false;

      final boolean optimizedTx = CommsUtils.requiresOptimizedTransaction(conversation);

      try
      {
         int clientTransactionId = request.getInt();
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
         {
            SibTr.debug(tc, "XAResource Object ID", clientTransactionId);
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Getting Xid");
         XidProxy xid = (XidProxy) request.getXid();
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Completed:", xid);

         byte onePhaseByte = request.get();
         if (onePhaseByte == 1) onePhase = true;
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "One phase:", onePhase);

         boolean endRequired = false;
         int endFlags = 0;
         if (optimizedTx)
         {
            endRequired = request.get() == 0x01;
            endFlags = request.getInt();

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            {
               SibTr.debug(tc, "End Required:", ""+endRequired);
               SibTr.debug(tc, "End Flags:", ""+endFlags);
            }
         }

         boolean requiresMSResource = false;
         if (conversation.getHandshakeProperties().getFapLevel() >= JFapChannelConstants.FAP_VERSION_5)
         {
            requiresMSResource = request.get() == 0x01;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Requires MS Resource:", ""+requiresMSResource);
         }

         // Get the transaction out of the table
         IdToTransactionTable transactionTable = linkState.getTransactionTable();
         if (endRequired) transactionTable.endOptimizedGlobalTransactionBranch(clientTransactionId, endFlags);
         SITransaction tran = null;

         // As commits (for the same XAResource) can be scheduled concurrently by the receive listener
         // dispatcher - perform all updates to the IdToTransaction table inside a synchronized block.
         boolean isInvalidTransaction = false;
         boolean isUnitOfWorkInError = false;
         Throwable rollbackException = null;
         synchronized(transactionTable)
         {
            tran = transactionTable.getResourceForGlobalTransactionBranch(clientTransactionId, xid);
            if (tran != null)
            {
               isInvalidTransaction = tran == IdToTransactionTable.INVALID_TRANSACTION;
               if (!isInvalidTransaction)
               {
                  isUnitOfWorkInError =
                     transactionTable.isGlobalTransactionBranchRollbackOnly(clientTransactionId, xid);
               }

               if (isInvalidTransaction || isUnitOfWorkInError)
               {
                  rollbackException =
                     transactionTable.getExceptionForRollbackOnlyGlobalTransactionBranch(clientTransactionId, xid);
               }

               // Leave the invalid transaction in the table.  The only way to remove it is to
               // roll it back.
               if (!isInvalidTransaction)
               {
                  transactionTable.removeGlobalTransactionBranch(clientTransactionId, xid);
               }
            }
         }

         SIXAResource xaResource = getResourceFromTran(tran, convState, requiresMSResource);

         // If the UOW was never created (because we were running with the
         // optimization that gets an XAResource and enlists it as part of the
         // first piece of transacted work and this failed) then throw
         // an exception notifying the caller that the UOW has been rolled back.
         if (isInvalidTransaction)
         {
            String errorMsg =
               nls.getFormattedMessage("TRANSACTION_MARKED_AS_ERROR_SICO2029",
                     new Object[]{ rollbackException },
                     null);

            XAException xa = new XAException(errorMsg);
            xa.initCause(rollbackException);
            xa.errorCode = XAException.XA_RBOTHER;

            throw xa;
         }

         if (isUnitOfWorkInError)
         {
            // PK59276 Rollback the transaction, as after we throw a XA_RB* error the
            // transaction manager will not call us with xa_rollback.
            xaResource.rollback(xid);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "The transaction was marked as error due to",
                                                 rollbackException);

            // And respond with an error
            XAException xa = new XAException(
               nls.getFormattedMessage("TRANSACTION_MARKED_AS_ERROR_SICO2029",
                                       new Object[]{ rollbackException },
                                       null)
            );
            xa.initCause(rollbackException);
            xa.errorCode = XAException.XA_RBOTHER;

            throw xa;
         }

         // Now call the method on the XA resource
         xaResource.commit(xid, onePhase);

         try
         {
            conversation.send(poolManager.allocate(),
                              JFapChannelConstants.SEG_XACOMMIT_R,
                              requestNumber,
                              JFapChannelConstants.PRIORITY_MEDIUM,
                              true,
                              ThrottlingPolicy.BLOCK_THREAD,
                              null);
         }
         catch (SIException e)
         {
            FFDCFilter.processException(e,
                                        CLASS_NAME + ".rcvXACommit",
                                        CommsConstants.STATICCATXATRANSACTION_XACOMMIT_01);

            SibTr.error(tc, "COMMUNICATION_ERROR_SICO2027", e);
         }
      }
      catch (XAException e)
      {
         FFDCFilter.processException(e,
                                     CLASS_NAME + ".rcvXACommit",
                                     CommsConstants.STATICCATXATRANSACTION_XACOMMIT_02);

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "XAException - RC: " + e.errorCode, e);

         StaticCATHelper.sendExceptionToClient(e,
                                               CommsConstants.STATICCATXATRANSACTION_XACOMMIT_02,     // d186970
                                               conversation, requestNumber);
      }

      request.release(allocatedFromBufferPool);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvXACommit");
   }
1028823
function(callback) {
        /**
         * Callback for QB.chat.privacylist.getNames().
         * @param {Object} error - The error object
         * @param {Object} response - The privacy list object (var names = response.names;)
         * @callback getNamesPrivacylistCallback
         * */

        var self = this,
            iq,
            stanzaParams = {
                'type': 'get',
                'from': self.helpers.getUserCurrentJid(),
                'id': chatUtils.getUniqueId('getNames')
            };

        if(Utils.getEnv().browser){
            iq = $iq(stanzaParams).c('query', {
                xmlns: Strophe.NS.PRIVACY_LIST
            });

            self.connection.sendIQ(iq, function(stanzaResult) {
                var allNames = [], namesList = {},
                    defaultList = stanzaResult.getElementsByTagName('default'),
                    activeList = stanzaResult.getElementsByTagName('active'),
                    allLists = stanzaResult.getElementsByTagName('list');

                var defaultName = defaultList && defaultList.length > 0 ? defaultList[0].getAttribute('name') : null;
                var activeName = activeList && activeList.length > 0 ? activeList[0].getAttribute('name') : null;

                for (var i = 0, len = allLists.length; i < len; i++) {
                    allNames.push(allLists[i].getAttribute('name'));
                }

                namesList = {
                    'default': defaultName,
                    'active': activeName,
                    'names': allNames
                };

                callback(null, namesList);
            }, function(stanzaError){
                if(stanzaError){
                    var errorObject = chatUtils.getErrorFromXMLNode(stanzaError);
                    callback(errorObject, null);
                }else{
                    callback(Utils.getError(408), null);
                }
            });
        } else {
            iq = new XMPP.Stanza('iq', stanzaParams);

            iq.c('query', {
                xmlns: chatUtils.MARKERS.PRIVACY
            });

            self.nodeStanzasCallbacks[iq.attrs.id] = function(stanza){
                if(stanza.attrs.type !== 'error'){

                    var allNames = [], namesList = {},
                        query = stanza.getChild('query'),
                        defaultList = query.getChild('default'),
                        activeList = query.getChild('active'),
                        allLists = query.getChildElements('list');

                    var defaultName = defaultList ? defaultList.attrs.name : null,
                        activeName = activeList ? activeList.attrs.name : null;

                    for (var i = 0, len = allLists.length; i < len; i++) {
                        allNames.push(allLists[i].attrs.name);
                    }

                    namesList = {
                        'default': defaultName,
                        'active': activeName,
                        'names': allNames
                    };

                    callback(null, namesList);
                } else {
                    callback(Utils.getError(408));
                }
            };

            self.Client.send(iq);
        }
    }
762880
function Messenger(namespace, options) {
  if (!(this instanceof Messenger)) {
    return new Messenger(namespace, options);
  }

  if (!namespace) {
    throw new Error('Cannot create Messenger without a namespace');
  }

  events.EventEmitter.call(this);

  this.namespace = namespace;
  this.options = merge(Object.create(Messenger.DEFAULTS), options || {});
  this.socketPath = this._getFileDescriptorPath(this.options.uid);

  this._init();
}
1155882
function queueLink(uri, context) {
  var queuedDetails = { queueOnly: true, member: context.member, categories: context.categories, relevance: context.relevance, attempts: 0, lastAttempt: new Date().toISOString(), team: context.team };
  var toQueue = { title: 'Queued ' + context.categories, uri: uri, state: utils.states.content.queued, queued: queuedDetails};
  contentLib.indexContentItem(toQueue, context, utils.passingError);
}
780656
@Override
	public void setSbbContext(SbbContext sbbContext) {
		this.sbbContext = (SbbContextExt) sbbContext;
		if (tracer == null) {
			tracer = sbbContext.getTracer(PublicationClientChildSbb.class.getSimpleName());
		}
		try {
			//sip ra
			this.sipActivityContextInterfaceFactory = (SipActivityContextInterfaceFactory) this.sbbContext.getActivityContextInterfaceFactory(sipResourceAdaptorTypeID);
			this.sleeSipProvider = (SleeSipProvider) this.sbbContext.getResourceAdaptorInterface(sipResourceAdaptorTypeID, "SipRA");
			//sip stuff
			this.messageFactory = this.sleeSipProvider.getMessageFactory();
			this.addressFactory = this.sleeSipProvider.getAddressFactory();
			this.headerFactory = this.sleeSipProvider.getHeaderFactory();
			//env, conf
			Context context = (Context) new InitialContext();
			try{
				String serverAddress = (String) context.lookup("server.address");
				if(serverAddress!=null) {	
					//RFC show entity as SIP URI and ECS address?
					this.ecsAddress = this.sleeSipProvider.getAddressFactory().createAddress(serverAddress);
				}
			}
			catch(NamingException e) {
				if(tracer.isInfoEnabled()) {
					tracer.info("No ECS/PA address to use in Route header.");
				}
			}
			
			try{
				String expireTime = (String) context.lookup("expires.drift");
				if(expireTime!=null) {	
					int intExpireTime = Integer.parseInt(expireTime);
					if(intExpireTime<0) {
						if(tracer.isInfoEnabled()) {
							tracer.info("Expire time drift less than zero, using default: "+this.expiresDrift+"s.");
						}
					}
					else {
						this.expiresDrift = intExpireTime;
						if(tracer.isInfoEnabled()) {
							tracer.info("Expire time drift set to: "+this.expiresDrift+"s.");
						}
					}					
				}
			}catch(NamingException e)
			{
				if(tracer.isInfoEnabled())
				{
					tracer.info("No Expire time drift, using default: "+this.expiresDrift+"s.");
				}
			}
		} catch (NamingException e) {
			tracer.severe("Can't set sbb context.", e);
		} catch (ParseException e) {
			tracer.severe("Can't set sbb context.", e);
		}
	}