idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
19,200
public void store ( String correlationId , String key , CredentialParams credential ) { synchronized ( _lock ) { if ( credential != null ) _items . put ( key , credential ) ; else _items . remove ( key ) ; } }
Stores credential parameters into the store .
19,201
public CredentialParams lookup ( String correlationId , String key ) { synchronized ( _lock ) { return _items . get ( key ) ; } }
Lookups credential parameters by its key .
19,202
private void createClassLoader ( ) { if ( ! Utils . isNullOrEmpty ( settings . getJarFiles ( ) ) ) { try { String [ ] files = settings . getJarFiles ( ) . split ( ";" ) ; List < URL > urls = newArrayList ( ) ; for ( String path : files ) { File file = new File ( path ) ; if ( file . isFile ( ) ) { urls . add ( file . toURI ( ) . toURL ( ) ) ; } } classLoader = new Java4CppClassLoader ( urls . toArray ( new URL [ files . length ] ) , classLoader ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to load jar " + e . getMessage ( ) ) ; } } }
Construct the context class loader by adding all jars .
19,203
public boolean installed ( Class < ? > component ) { Preconditions . checkArgument ( component != null , "Parameter 'component' must not be [" + component + "]" ) ; return installed . contains ( component ) ; }
Indicates the specified component installed or not in the container .
19,204
@ SuppressWarnings ( "unchecked" ) private static < T > Class < T > getGenericType ( Class < ? > thisClass ) { Type type = thisClass ; do { type = ( ( Class < ? > ) type ) . getGenericSuperclass ( ) ; if ( type instanceof ParameterizedType ) { return ( Class < T > ) ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } } while ( type instanceof Class < ? > && ! type . equals ( AbstractFormatter . class ) ) ; return ( Class < T > ) Object . class ; }
Loads the class information from the generic type of the specified class .
19,205
private void registerInternal ( final Object receiver , final Method method , final Class < ? extends T > eventClass ) { List < ReceiverDescriptor > receivers = this . receiverMap . get ( eventClass ) ; if ( receivers == null ) { receivers = new LinkedList < ReceiverDescriptor > ( ) ; this . receiverMap . put ( eventClass , receivers ) ; } final ReceiverDescriptor rd = new ReceiverDescriptor ( ) ; rd . receiverReference = new SoftReference < Object > ( receiver ) ; rd . method = method ; receivers . add ( rd ) ; }
Registers a receiver to an internal map .
19,206
private < Q extends T > Q dispatch ( final Q event , boolean stopOnFirstException ) { if ( event == null ) { throw new IllegalArgumentException ( "event is null" ) ; } if ( this . baseClass != null && ! this . baseClass . isAssignableFrom ( event . getClass ( ) ) ) { throw new IllegalArgumentException ( "event of type " + event . getClass ( ) . getName ( ) + " not dispatchable over this event scope of base type '" + this . baseClass . getName ( ) + "'" ) ; } final Collection < ReceiverDescriptor > receivers = new TreeSet < ReceiverDescriptor > ( new DispatchComparator ( ) ) ; this . collectReceiver ( event . getClass ( ) , receivers ) ; if ( receivers == null || receivers . size ( ) < 1 ) { return event ; } final List < ReceiverDescriptor > defunct = new LinkedList < ReceiverDescriptor > ( ) ; try { for ( final ReceiverDescriptor receiverDescriptor : receivers ) { final Object receiver = receiverDescriptor . receiverReference . get ( ) ; if ( receiver == null ) { defunct . add ( receiverDescriptor ) ; continue ; } try { receiverDescriptor . method . setAccessible ( true ) ; receiverDescriptor . method . invoke ( receiver , event ) ; } catch ( final Exception e ) { if ( stopOnFirstException ) { throw new DispatchException ( receiver , event , e ) ; } } } } finally { receivers . removeAll ( defunct ) ; } return event ; }
Dispatch an event to receivers synchronously .
19,207
public synchronized < Q extends T > void dispatchAsynchronous ( final Q event , final IPostProcessor < Q > pPostProcessor ) { new Thread ( new Runnable ( ) { public void run ( ) { try { pPostProcessor . done ( dispatch ( event ) ) ; } catch ( DispatchException lEx ) { pPostProcessor . done ( lEx ) ; } } } ) . start ( ) ; }
Dispatch an event to receivers asynchronously . Does start a thread and then return immediately .
19,208
private void collectReceiver ( final Class < ? > eventClass , final Collection < ReceiverDescriptor > receiverCollection ) { if ( this . receiverMap . get ( eventClass ) != null ) { receiverCollection . addAll ( this . receiverMap . get ( eventClass ) ) ; } if ( ! eventClass . isInterface ( ) && eventClass . getSuperclass ( ) != Object . class ) { this . collectReceiver ( eventClass . getSuperclass ( ) , receiverCollection ) ; } for ( final Class interfaceClass : eventClass . getInterfaces ( ) ) { this . collectReceiver ( interfaceClass , receiverCollection ) ; } }
collects receiver descriptors of super classes and interfaces .
19,209
public static MnoHttpClient getAuthenticatedClient ( String key , String secret , String contentType ) { MnoHttpClient client = new MnoHttpClient ( contentType ) ; String authStr = key + ":" + secret ; client . basicAuthHash = "Basic " + DatatypeConverter . printBase64Binary ( authStr . getBytes ( ) ) ; return client ; }
Return a client with HTTP Basic Authentication setup
19,210
public String post ( String url , String payload ) throws AuthenticationException , ApiException { return performRequest ( url , "POST" , null , null , payload ) ; }
Perform a POST request on the specified endpoint
19,211
protected HttpURLConnection openConnection ( String url , Map < String , String > header ) throws IOException { URL urlObj = null ; HttpURLConnection conn = null ; int redirectCount = 0 ; boolean redirect = true ; while ( redirect ) { if ( redirectCount > 10 ) { throw new ProtocolException ( "Too many redirects: " + redirectCount ) ; } if ( conn == null ) { urlObj = new URL ( url ) ; } else { urlObj = new URL ( conn . getHeaderField ( "Location" ) ) ; } conn = ( HttpURLConnection ) urlObj . openConnection ( ) ; conn . setRequestMethod ( header . get ( "method" ) ) ; conn . setInstanceFollowRedirects ( true ) ; if ( conn . getRequestMethod ( ) == "POST" || conn . getRequestMethod ( ) == "PUT" ) { conn . setDoOutput ( true ) ; } for ( Map . Entry < String , String > headerAttr : header . entrySet ( ) ) { conn . addRequestProperty ( headerAttr . getKey ( ) , headerAttr . getValue ( ) ) ; } redirect = false ; if ( conn . getRequestMethod ( ) == "GET" ) { int status = conn . getResponseCode ( ) ; if ( status != HttpURLConnection . HTTP_OK ) { if ( status == HttpURLConnection . HTTP_MOVED_TEMP || status == HttpURLConnection . HTTP_MOVED_PERM || status == HttpURLConnection . HTTP_SEE_OTHER ) redirect = true ; redirectCount ++ ; } } } return conn ; }
Open a connection and follow the redirect
19,212
@ SuppressWarnings ( "unchecked" ) public static < T > EventScope < T > get ( final Class < T > pEventType ) { if ( pEventType == Object . class ) { return null ; } EventScope < T > lResult = ( EventScope < T > ) sScopes . get ( pEventType ) ; if ( lResult != null ) { return lResult ; } for ( final Class < ? > lInterface : pEventType . getInterfaces ( ) ) { lResult = ( EventScope < T > ) sScopes . get ( pEventType ) ; if ( lResult != null ) { return lResult ; } } return ( EventScope < T > ) get ( pEventType . getSuperclass ( ) ) ; }
Returns the event scope bound to that event type . This is an expensive operation so make sure to only call as seldom as possible .
19,213
private boolean increment ( int index ) { if ( index == - 1 ) { return false ; } int value = current . get ( index ) ; if ( value < max . get ( index ) ) { current . set ( index , value + 1 ) ; updateMinMax ( index + 1 ) ; return true ; } boolean hasNext = increment ( index - 1 ) ; if ( hasNext ) { current . set ( index , min . get ( index ) ) ; } return hasNext ; }
Increment the current value starting at the given index and return whether this was possible
19,214
public static Credentials copy ( Credentials credentials ) { if ( credentials == null ) { return null ; } return new Credentials ( credentials . login , credentials . password ) ; }
Creates a new copy of authentication pair .
19,215
protected String parseNumberToString ( Number number , Context context , Arguments args ) { final NumberFormat numberFormat = parseFormatter ( context , args ) ; final Currency currency = context . get ( Contexts . CURRENCY ) ; if ( currency != null ) { numberFormat . setCurrency ( currency ) ; } return numberFormat . format ( number ) ; }
Parses the given number to a string depending on the context .
19,216
public OmemoDevice getOwnDevice ( ) { synchronized ( LOCK ) { BareJid jid = getOwnJid ( ) ; if ( jid == null ) { return null ; } return new OmemoDevice ( jid , getDeviceId ( ) ) ; } }
Return the OmemoDevice of the user .
19,217
void setDeviceId ( int nDeviceId ) { synchronized ( LOCK ) { INSTANCES . get ( connection ( ) ) . remove ( getDeviceId ( ) ) ; INSTANCES . get ( connection ( ) ) . put ( nDeviceId , this ) ; this . deviceId = nDeviceId ; } }
Set the deviceId of the manager to nDeviceId .
19,218
void notifyOmemoMessageReceived ( Stanza stanza , OmemoMessage . Received decryptedMessage ) { for ( OmemoMessageListener l : omemoMessageListeners ) { l . onOmemoMessageReceived ( stanza , decryptedMessage ) ; } }
Notify all registered OmemoMessageListeners about a received OmemoMessage .
19,219
void notifyOmemoMucMessageReceived ( MultiUserChat muc , Stanza stanza , OmemoMessage . Received decryptedMessage ) { for ( OmemoMucMessageListener l : omemoMucMessageListeners ) { l . onOmemoMucMessageReceived ( muc , stanza , decryptedMessage ) ; } }
Notify all registered OmemoMucMessageListeners of an incoming OmemoMessageElement in a MUC .
19,220
public void stopStanzaAndPEPListeners ( ) { PepManager . getInstanceFor ( connection ( ) ) . removePepListener ( deviceListUpdateListener ) ; connection ( ) . removeAsyncStanzaListener ( internalOmemoMessageStanzaListener ) ; CarbonManager . getInstanceFor ( connection ( ) ) . removeCarbonCopyReceivedListener ( internalOmemoCarbonCopyListener ) ; }
Remove active stanza listeners needed for OMEMO .
19,221
public void rebuildSessionWith ( OmemoDevice contactsDevice ) throws InterruptedException , SmackException . NoResponseException , CorruptedOmemoKeyException , SmackException . NotConnectedException , CannotEstablishOmemoSessionException , SmackException . NotLoggedInException { if ( ! connection ( ) . isAuthenticated ( ) ) { throw new SmackException . NotLoggedInException ( ) ; } getOmemoService ( ) . buildFreshSessionWithDevice ( connection ( ) , getOwnDevice ( ) , contactsDevice ) ; }
Build a fresh session with a contacts device . This might come in handy if a session is broken .
19,222
private static void initBareJidAndDeviceId ( OmemoManager manager ) { if ( ! manager . getConnection ( ) . isAuthenticated ( ) ) { throw new IllegalStateException ( "Connection MUST be authenticated." ) ; } if ( manager . ownJid == null ) { manager . ownJid = manager . getConnection ( ) . getUser ( ) . asBareJid ( ) ; } if ( UNKNOWN_DEVICE_ID . equals ( manager . deviceId ) ) { SortedSet < Integer > storedDeviceIds = manager . getOmemoService ( ) . getOmemoStoreBackend ( ) . localDeviceIdsOf ( manager . ownJid ) ; if ( storedDeviceIds . size ( ) > 0 ) { manager . setDeviceId ( storedDeviceIds . first ( ) ) ; } else { manager . setDeviceId ( randomDeviceId ( ) ) ; } } }
Get the bareJid of the user from the authenticated XMPP connection . If our deviceId is unknown use the bareJid to look up deviceIds available in the omemoStore . If there are ids available choose the smallest one . Otherwise generate a random deviceId .
19,223
private void showNewDebugger ( EnhancedDebugger debugger ) { if ( frame == null ) { createDebug ( ) ; } debugger . tabbedPane . setName ( "XMPPConnection_" + tabbedPane . getComponentCount ( ) ) ; tabbedPane . add ( debugger . tabbedPane , tabbedPane . getComponentCount ( ) - 1 ) ; tabbedPane . setIconAt ( tabbedPane . indexOfComponent ( debugger . tabbedPane ) , connectionCreatedIcon ) ; frame . setTitle ( "Smack Debug Window -- Total connections: " + ( tabbedPane . getComponentCount ( ) - 1 ) ) ; debuggers . add ( debugger ) ; }
Shows the new debugger in the debug window .
19,224
static synchronized void userHasLogged ( EnhancedDebugger debugger , String user ) { int index = getInstance ( ) . tabbedPane . indexOfComponent ( debugger . tabbedPane ) ; getInstance ( ) . tabbedPane . setTitleAt ( index , user ) ; getInstance ( ) . tabbedPane . setIconAt ( index , connectionActiveIcon ) ; }
Notification that a user has logged in to the server . A new title will be set to the tab of the given debugger .
19,225
static synchronized void connectionClosed ( EnhancedDebugger debugger ) { getInstance ( ) . tabbedPane . setIconAt ( getInstance ( ) . tabbedPane . indexOfComponent ( debugger . tabbedPane ) , connectionClosedIcon ) ; }
Notification that the connection was properly closed .
19,226
static synchronized void connectionClosedOnError ( EnhancedDebugger debugger , Exception e ) { int index = getInstance ( ) . tabbedPane . indexOfComponent ( debugger . tabbedPane ) ; getInstance ( ) . tabbedPane . setToolTipTextAt ( index , "XMPPConnection closed due to the exception: " + e . getMessage ( ) ) ; getInstance ( ) . tabbedPane . setIconAt ( index , connectionClosedOnErrorIcon ) ; }
Notification that the connection was closed due to an exception .
19,227
private synchronized void rootWindowClosing ( WindowEvent evt ) { for ( EnhancedDebugger debugger : debuggers ) { debugger . cancel ( ) ; } debuggers . clear ( ) ; instance = null ; frame = null ; notifyAll ( ) ; }
Notification that the root window is closing . Stop listening for received and transmitted packets in all the debugged connections .
19,228
public MucConfigFormManager setRoomOwners ( Collection < ? extends Jid > newOwners ) throws MucConfigurationNotSupportedException { if ( ! supportsRoomOwners ( ) ) { throw new MucConfigurationNotSupportedException ( MUC_ROOMCONFIG_ROOMOWNERS ) ; } owners . clear ( ) ; owners . addAll ( newOwners ) ; return this ; }
Set the owners of the room .
19,229
public MucConfigFormManager setMembersOnly ( boolean isMembersOnly ) throws MucConfigurationNotSupportedException { if ( ! supportsMembersOnly ( ) ) { throw new MucConfigurationNotSupportedException ( MUC_ROOMCONFIG_MEMBERSONLY ) ; } answerForm . setAnswer ( MUC_ROOMCONFIG_MEMBERSONLY , isMembersOnly ) ; return this ; }
Set if the room is members only . Rooms are not members only per default .
19,230
public MucConfigFormManager setIsPasswordProtected ( boolean isPasswordProtected ) throws MucConfigurationNotSupportedException { if ( ! supportsMembersOnly ( ) ) { throw new MucConfigurationNotSupportedException ( MUC_ROOMCONFIG_PASSWORDPROTECTEDROOM ) ; } answerForm . setAnswer ( MUC_ROOMCONFIG_PASSWORDPROTECTEDROOM , isPasswordProtected ) ; return this ; }
Set if this room is password protected . Rooms are by default not password protected .
19,231
@ SuppressWarnings ( "deprecation" ) public static STUN getSTUNServer ( XMPPConnection connection ) throws NotConnectedException , InterruptedException { if ( ! connection . isConnected ( ) ) { return null ; } STUN stunPacket = new STUN ( ) ; stunPacket . setTo ( DOMAIN + "." + connection . getXMPPServiceDomain ( ) ) ; StanzaCollector collector = connection . createStanzaCollectorAndSend ( stunPacket ) ; STUN response = collector . nextResult ( ) ; collector . cancel ( ) ; return response ; }
Get a new STUN Server Address and port from the server . If a error occurs or the server don t support STUN Service null is returned .
19,232
public static boolean serviceAvailable ( XMPPConnection connection ) throws XMPPException , SmackException , InterruptedException { if ( ! connection . isConnected ( ) ) { return false ; } LOGGER . fine ( "Service listing" ) ; ServiceDiscoveryManager disco = ServiceDiscoveryManager . getInstanceFor ( connection ) ; DiscoverItems items = disco . discoverItems ( connection . getXMPPServiceDomain ( ) ) ; for ( DiscoverItems . Item item : items . getItems ( ) ) { DiscoverInfo info = disco . discoverInfo ( item . getEntityID ( ) ) ; for ( DiscoverInfo . Identity identity : info . getIdentities ( ) ) { if ( identity . getCategory ( ) . equals ( "proxy" ) && identity . getType ( ) . equals ( "stun" ) ) if ( info . containsFeature ( NAMESPACE ) ) return true ; } LOGGER . fine ( item . getName ( ) + "-" + info . getType ( ) ) ; } return false ; }
Check if the server support STUN Service .
19,233
protected int getFreePort ( ) { ServerSocket ss ; int freePort = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { freePort = ( int ) ( 10000 + Math . round ( Math . random ( ) * 10000 ) ) ; freePort = freePort % 2 == 0 ? freePort : freePort + 1 ; try { ss = new ServerSocket ( freePort ) ; freePort = ss . getLocalPort ( ) ; ss . close ( ) ; return freePort ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "exception" , e ) ; } } try { ss = new ServerSocket ( 0 ) ; freePort = ss . getLocalPort ( ) ; ss . close ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "exception" , e ) ; } return freePort ; }
Obtain a free port we can use .
19,234
public void setField ( String field , String value , boolean isUnescapable ) { if ( ! isUnescapable ) { otherSimpleFields . put ( field , value ) ; } else { otherUnescapableFields . put ( field , value ) ; } }
Set generic unescapable VCard field . If unescapable is set to true XML maybe a part of the value .
19,235
public void setAvatar ( URL avatarURL ) { byte [ ] bytes = new byte [ 0 ] ; try { bytes = getBytes ( avatarURL ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Error getting bytes from URL: " + avatarURL , e ) ; } setAvatar ( bytes ) ; }
Set the avatar for the VCard by specifying the url to the image .
19,236
public void setAvatar ( byte [ ] bytes , String mimeType ) { if ( bytes == null ) { removeAvatar ( ) ; return ; } String encodedImage = Base64 . encodeToString ( bytes ) ; setAvatar ( encodedImage , mimeType ) ; }
Specify the bytes for the avatar to use as well as the mime type .
19,237
public static byte [ ] getBytes ( URL url ) throws IOException { final String path = url . getPath ( ) ; final File file = new File ( path ) ; if ( file . exists ( ) ) { return getFileBytes ( file ) ; } return null ; }
Common code for getting the bytes of a url .
19,238
public String getAvatarHash ( ) { byte [ ] bytes = getAvatar ( ) ; if ( bytes == null ) { return null ; } MessageDigest digest ; try { digest = MessageDigest . getInstance ( "SHA-1" ) ; } catch ( NoSuchAlgorithmException e ) { LOGGER . log ( Level . SEVERE , "Failed to get message digest" , e ) ; return null ; } digest . update ( bytes ) ; return StringUtils . encodeHex ( digest . digest ( ) ) ; }
Returns the SHA - 1 Hash of the Avatar image .
19,239
public void load ( XMPPConnection connection ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { load ( connection , null ) ; }
Load VCard information for a connected user . XMPPConnection should be authenticated and not anonymous .
19,240
public void load ( XMPPConnection connection , EntityBareJid user ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { VCard result = VCardManager . getInstanceFor ( connection ) . loadVCard ( user ) ; copyFieldsFrom ( result ) ; }
Load VCard information for a given user . XMPPConnection should be authenticated and not anonymous .
19,241
public void updateKeys ( XMPPConnection connection ) throws InterruptedException , SmackException . NotConnectedException , SmackException . NoResponseException , XMPPException . XMPPErrorException , PubSubException . NotALeafNodeException , PubSubException . NotAPubSubNodeException , IOException { PublicKeysListElement metadata = OpenPgpPubSubUtil . fetchPubkeysList ( connection , getJid ( ) ) ; if ( metadata == null ) { return ; } updateKeys ( connection , metadata ) ; }
Update the contacts keys by consulting the users PubSub nodes . This method fetches the users metadata node and then tries to fetch any announced keys .
19,242
private void setupPayloads ( ) { payloads . add ( new PayloadType . Audio ( 3 , "gsm" ) ) ; payloads . add ( new PayloadType . Audio ( 4 , "g723" ) ) ; payloads . add ( new PayloadType . Audio ( 0 , "PCMU" , 16000 ) ) ; }
Setup API supported Payloads
19,243
public static void setupJMF ( ) { String homeDir = System . getProperty ( "user.home" ) ; File jmfDir = new File ( homeDir , ".jmf" ) ; String classpath = System . getProperty ( "java.class.path" ) ; classpath += System . getProperty ( "path.separator" ) + jmfDir . getAbsolutePath ( ) ; System . setProperty ( "java.class.path" , classpath ) ; if ( ! jmfDir . exists ( ) ) jmfDir . mkdir ( ) ; File jmfProperties = new File ( jmfDir , "jmf.properties" ) ; if ( ! jmfProperties . exists ( ) ) { try { jmfProperties . createNewFile ( ) ; } catch ( IOException ex ) { LOGGER . log ( Level . FINE , "Failed to create jmf.properties" , ex ) ; } } runLinuxPreInstall ( ) ; new JMFInit ( null , false ) ; }
Runs JMFInit the first time the application is started so that capture devices are properly detected and initialized by JMF .
19,244
public void setDeliverOn ( boolean deliverNotifications ) { addField ( SubscribeOptionFields . deliver , FormField . Type . bool ) ; setAnswer ( SubscribeOptionFields . deliver . getFieldName ( ) , deliverNotifications ) ; }
Sets whether an entity wants to receive notifications .
19,245
public void setDigestOn ( boolean digestOn ) { addField ( SubscribeOptionFields . deliver , FormField . Type . bool ) ; setAnswer ( SubscribeOptionFields . deliver . getFieldName ( ) , digestOn ) ; }
Sets whether notifications should be delivered as aggregations or not .
19,246
public void setDigestFrequency ( int frequency ) { addField ( SubscribeOptionFields . digest_frequency , FormField . Type . text_single ) ; setAnswer ( SubscribeOptionFields . digest_frequency . getFieldName ( ) , frequency ) ; }
Sets the minimum number of milliseconds between sending notification digests .
19,247
public Date getExpiry ( ) { String dateTime = getFieldValue ( SubscribeOptionFields . expire ) ; try { return XmppDateTime . parseDate ( dateTime ) ; } catch ( ParseException e ) { UnknownFormatConversionException exc = new UnknownFormatConversionException ( dateTime ) ; exc . initCause ( e ) ; throw exc ; } }
Get the time at which the leased subscription will expire or has expired .
19,248
public void setExpiry ( Date expire ) { addField ( SubscribeOptionFields . expire , FormField . Type . text_single ) ; setAnswer ( SubscribeOptionFields . expire . getFieldName ( ) , XmppDateTime . formatXEP0082Date ( expire ) ) ; }
Sets the time at which the leased subscription will expire or has expired .
19,249
public void setIncludeBody ( boolean include ) { addField ( SubscribeOptionFields . include_body , FormField . Type . bool ) ; setAnswer ( SubscribeOptionFields . include_body . getFieldName ( ) , include ) ; }
Sets whether the entity wants to receive an XMPP message body in addition to the payload format .
19,250
public void addListener ( AgentRosterListener listener ) { synchronized ( listeners ) { if ( ! listeners . contains ( listener ) ) { listeners . add ( listener ) ; for ( EntityBareJid jid : getAgents ( ) ) { if ( entries . contains ( jid ) ) { listener . agentAdded ( jid ) ; Jid j ; try { j = JidCreate . from ( jid ) ; } catch ( XmppStringprepException e ) { throw new IllegalStateException ( e ) ; } Map < Resourcepart , Presence > userPresences = presenceMap . get ( j ) ; if ( userPresences != null ) { Iterator < Presence > presences = userPresences . values ( ) . iterator ( ) ; while ( presences . hasNext ( ) ) { listener . presenceChanged ( presences . next ( ) ) ; } } } } } } }
Adds a listener to this roster . The listener will be fired anytime one or more changes to the roster are pushed from the server .
19,251
public boolean contains ( Jid jid ) { if ( jid == null ) { return false ; } synchronized ( entries ) { for ( Iterator < EntityBareJid > i = entries . iterator ( ) ; i . hasNext ( ) ; ) { EntityBareJid entry = i . next ( ) ; if ( entry . equals ( jid ) ) { return true ; } } } return false ; }
Returns true if the specified XMPP address is an agent in the workgroup .
19,252
private void fireEvent ( int eventType , Object eventObject ) { AgentRosterListener [ ] listeners ; synchronized ( this . listeners ) { listeners = new AgentRosterListener [ this . listeners . size ( ) ] ; this . listeners . toArray ( listeners ) ; } for ( int i = 0 ; i < listeners . length ; i ++ ) { switch ( eventType ) { case EVENT_AGENT_ADDED : listeners [ i ] . agentAdded ( ( EntityBareJid ) eventObject ) ; break ; case EVENT_AGENT_REMOVED : listeners [ i ] . agentRemoved ( ( EntityBareJid ) eventObject ) ; break ; case EVENT_PRESENCE_CHANGED : listeners [ i ] . presenceChanged ( ( Presence ) eventObject ) ; break ; } } }
Fires event to listeners .
19,253
public String toXML ( org . jivesoftware . smack . packet . XmlEnvironment enclosingNamespace ) { StringBuilder buf = new StringBuilder ( ) ; if ( message != null ) { buf . append ( "<error type=\"cancel\">" ) ; buf . append ( '<' ) . append ( message ) . append ( " xmlns=\"" ) . append ( NAMESPACE ) . append ( "\"/>" ) ; buf . append ( "</error>" ) ; } return buf . toString ( ) ; }
Returns the error as XML .
19,254
public boolean isAvailable ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { Presence directedPresence = new Presence ( Presence . Type . available ) ; directedPresence . setTo ( workgroupJID ) ; StanzaFilter typeFilter = new StanzaTypeFilter ( Presence . class ) ; StanzaFilter fromFilter = FromMatchesFilter . create ( workgroupJID ) ; StanzaCollector collector = connection . createStanzaCollectorAndSend ( new AndFilter ( fromFilter , typeFilter ) , directedPresence ) ; Presence response = collector . nextResultOrThrow ( ) ; return Presence . Type . available == response . getType ( ) ; }
Returns true if the workgroup is available for receiving new requests . The workgroup will be available only when agents are available for this workgroup .
19,255
public ChatSetting getChatSetting ( String key ) throws XMPPException , SmackException , InterruptedException { ChatSettings chatSettings = getChatSettings ( key , - 1 ) ; return chatSettings . getFirstEntry ( ) ; }
Returns a single chat setting based on it s identified key .
19,256
private ChatSettings getChatSettings ( String key , int type ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { ChatSettings request = new ChatSettings ( ) ; if ( key != null ) { request . setKey ( key ) ; } if ( type != - 1 ) { request . setType ( type ) ; } request . setType ( IQ . Type . get ) ; request . setTo ( workgroupJID ) ; ChatSettings response = connection . createStanzaCollectorAndSend ( request ) . nextResultOrThrow ( ) ; return response ; }
Asks the workgroup for it s Chat Settings .
19,257
public boolean isEmailAvailable ( ) throws SmackException , InterruptedException { ServiceDiscoveryManager discoManager = ServiceDiscoveryManager . getInstanceFor ( connection ) ; try { DomainBareJid workgroupService = workgroupJID . asDomainBareJid ( ) ; DiscoverInfo infoResult = discoManager . discoverInfo ( workgroupService ) ; return infoResult . containsFeature ( "jive:email:provider" ) ; } catch ( XMPPException e ) { return false ; } }
The workgroup service may be configured to send email . This queries the Workgroup Service to see if the email service has been configured and is available .
19,258
public OfflineSettings getOfflineSettings ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { OfflineSettings request = new OfflineSettings ( ) ; request . setType ( IQ . Type . get ) ; request . setTo ( workgroupJID ) ; return connection . createStanzaCollectorAndSend ( request ) . nextResultOrThrow ( ) ; }
Asks the workgroup for it s Offline Settings .
19,259
public SoundSettings getSoundSettings ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { SoundSettings request = new SoundSettings ( ) ; request . setType ( IQ . Type . get ) ; request . setTo ( workgroupJID ) ; return connection . createStanzaCollectorAndSend ( request ) . nextResultOrThrow ( ) ; }
Asks the workgroup for it s Sound Settings .
19,260
public WorkgroupProperties getWorkgroupProperties ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { WorkgroupProperties request = new WorkgroupProperties ( ) ; request . setType ( IQ . Type . get ) ; request . setTo ( workgroupJID ) ; return connection . createStanzaCollectorAndSend ( request ) . nextResultOrThrow ( ) ; }
Asks the workgroup for it s Properties .
19,261
public void addRosterEntry ( RosterEntry rosterEntry ) { List < String > groupNamesList = new ArrayList < > ( ) ; String [ ] groupNames ; for ( RosterGroup group : rosterEntry . getGroups ( ) ) { groupNamesList . add ( group . getName ( ) ) ; } groupNames = groupNamesList . toArray ( new String [ groupNamesList . size ( ) ] ) ; RemoteRosterEntry remoteRosterEntry = new RemoteRosterEntry ( rosterEntry . getJid ( ) , rosterEntry . getName ( ) , groupNames ) ; addRosterEntry ( remoteRosterEntry ) ; }
Adds a roster entry to the packet .
19,262
public Iterator < RemoteRosterEntry > getRosterEntries ( ) { synchronized ( remoteRosterEntries ) { List < RemoteRosterEntry > entries = Collections . unmodifiableList ( new ArrayList < > ( remoteRosterEntries ) ) ; return entries . iterator ( ) ; } }
Returns an Iterator for the roster entries in the packet .
19,263
public String toXML ( org . jivesoftware . smack . packet . XmlEnvironment enclosingNamespace ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( '<' ) . append ( getElementName ( ) ) . append ( " xmlns=\"" ) . append ( getNamespace ( ) ) . append ( "\">" ) ; for ( Iterator < RemoteRosterEntry > i = getRosterEntries ( ) ; i . hasNext ( ) ; ) { RemoteRosterEntry remoteRosterEntry = i . next ( ) ; buf . append ( remoteRosterEntry . toXML ( ) ) ; } buf . append ( "</" ) . append ( getElementName ( ) ) . append ( '>' ) ; return buf . toString ( ) ; }
Returns the XML representation of a Roster Item Exchange according the specification .
19,264
public JingleMediaSession createMediaSession ( PayloadType payloadType , final TransportCandidate remote , final TransportCandidate local , final JingleSession jingleSession ) { return new AudioMediaSession ( payloadType , remote , local , null , null ) ; }
Returns a new jingleMediaSession .
19,265
public static < T extends Collection < ? > > T requireNonNullNorEmpty ( T collection , String message ) { if ( requireNonNull ( collection ) . isEmpty ( ) ) { throw new IllegalArgumentException ( message ) ; } return collection ; }
Require a collection to be neither null nor empty .
19,266
public synchronized void resolve ( JingleSession session ) throws XMPPException , NotConnectedException , InterruptedException { setResolveInit ( ) ; clearCandidates ( ) ; sid = random . nextInt ( Integer . MAX_VALUE ) ; RTPBridge rtpBridge = RTPBridge . getRTPBridge ( connection , String . valueOf ( sid ) ) ; String localIp = getLocalHost ( ) ; TransportCandidate localCandidate = new TransportCandidate . Fixed ( rtpBridge . getIp ( ) , rtpBridge . getPortA ( ) ) ; localCandidate . setLocalIp ( localIp ) ; TransportCandidate remoteCandidate = new TransportCandidate . Fixed ( rtpBridge . getIp ( ) , rtpBridge . getPortB ( ) ) ; remoteCandidate . setLocalIp ( localIp ) ; localCandidate . setSymmetric ( remoteCandidate ) ; remoteCandidate . setSymmetric ( localCandidate ) ; localCandidate . setPassword ( rtpBridge . getPass ( ) ) ; remoteCandidate . setPassword ( rtpBridge . getPass ( ) ) ; localCandidate . setSessionId ( rtpBridge . getSid ( ) ) ; remoteCandidate . setSessionId ( rtpBridge . getSid ( ) ) ; localCandidate . setConnection ( this . connection ) ; remoteCandidate . setConnection ( this . connection ) ; addCandidate ( localCandidate ) ; setResolveEnd ( ) ; }
1 Resolve Bridged Candidate .
19,267
public Subject addSubject ( String language , String subject ) { language = determineLanguage ( language ) ; Subject messageSubject = new Subject ( language , subject ) ; subjects . add ( messageSubject ) ; return messageSubject ; }
Adds a subject with a corresponding language .
19,268
public boolean removeSubject ( String language ) { language = determineLanguage ( language ) ; for ( Subject subject : subjects ) { if ( language . equals ( subject . language ) ) { return subjects . remove ( subject ) ; } } return false ; }
Removes the subject with the given language from the message .
19,269
public List < String > getSubjectLanguages ( ) { Subject defaultSubject = getMessageSubject ( null ) ; List < String > languages = new ArrayList < String > ( ) ; for ( Subject subject : subjects ) { if ( ! subject . equals ( defaultSubject ) ) { languages . add ( subject . language ) ; } } return Collections . unmodifiableList ( languages ) ; }
Returns all the languages being used for the subjects not including the default subject .
19,270
public void setBody ( CharSequence body ) { String bodyString ; if ( body != null ) { bodyString = body . toString ( ) ; } else { bodyString = null ; } setBody ( bodyString ) ; }
Sets the body of the message .
19,271
public Body addBody ( String language , String body ) { language = determineLanguage ( language ) ; removeBody ( language ) ; Body messageBody = new Body ( language , body ) ; addExtension ( messageBody ) ; return messageBody ; }
Adds a body with a corresponding language .
19,272
public boolean removeBody ( String language ) { language = determineLanguage ( language ) ; for ( Body body : getBodies ( ) ) { String bodyLanguage = body . getLanguage ( ) ; if ( Objects . equals ( bodyLanguage , language ) ) { removeExtension ( body ) ; return true ; } } return false ; }
Removes the body with the given language from the message .
19,273
public List < String > getBodyLanguages ( ) { Body defaultBody = getMessageBody ( null ) ; List < String > languages = new ArrayList < String > ( ) ; for ( Body body : getBodies ( ) ) { if ( ! body . equals ( defaultBody ) ) { languages . add ( body . language ) ; } } return Collections . unmodifiableList ( languages ) ; }
Returns all the languages being used for the bodies not including the default body .
19,274
public JingleContent parse ( XmlPullParser parser , int initialDepth , XmlEnvironment xmlEnvironment ) { String elementName = parser . getName ( ) ; String creator = parser . getAttributeValue ( "" , JingleContent . CREATOR ) ; String name = parser . getAttributeValue ( "" , JingleContent . NAME ) ; return new JingleContent ( creator , name ) ; }
Parse a JingleContent extension .
19,275
public static long calculateDelta ( long reportedHandledCount , long lastKnownHandledCount ) { if ( lastKnownHandledCount > reportedHandledCount ) { throw new IllegalStateException ( "Illegal Stream Management State: Last known handled count (" + lastKnownHandledCount + ") is greater than reported handled count (" + reportedHandledCount + ')' ) ; } return ( reportedHandledCount - lastKnownHandledCount ) & MASK_32_BIT ; }
Calculates the delta of the last known stanza handled count and the new reported stanza handled count while considering that the new value may be wrapped after 2^32 - 1 .
19,276
public synchronized JingleSession accept ( ) throws XMPPException , SmackException , InterruptedException { JingleSession session ; synchronized ( manager ) { session = manager . createIncomingJingleSession ( this ) ; session . setSid ( this . getSessionID ( ) ) ; session . updatePacketListener ( ) ; session . receivePacketAndRespond ( this . getJingle ( ) ) ; } return session ; }
Accepts this request and creates the incoming Jingle session .
19,277
public synchronized void reject ( ) { JingleSession session ; synchronized ( manager ) { try { session = manager . createIncomingJingleSession ( this ) ; session . setSid ( this . getSessionID ( ) ) ; session . updatePacketListener ( ) ; session . terminate ( "Declined" ) ; } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Exception in reject" , e ) ; } } }
Rejects the session request .
19,278
public void addFeatures ( Collection < String > featuresToAdd ) { if ( featuresToAdd == null ) return ; for ( String feature : featuresToAdd ) { addFeature ( feature ) ; } }
Adds a collection of features to the packet . Does noting if featuresToAdd is null .
19,279
public void addIdentity ( Identity identity ) { identities . add ( identity ) ; identitiesSet . add ( identity . getKey ( ) ) ; }
Adds a new identity of the requested entity to the discovered information .
19,280
public void addIdentities ( Collection < Identity > identitiesToAdd ) { if ( identitiesToAdd == null ) return ; for ( Identity identity : identitiesToAdd ) { addIdentity ( identity ) ; } }
Adds identities to the DiscoverInfo stanza .
19,281
public boolean hasIdentity ( String category , String type ) { String key = XmppStringUtils . generateKey ( category , type ) ; return identitiesSet . contains ( key ) ; }
Returns true if this DiscoverInfo contains at least one Identity of the given category and type .
19,282
public List < Identity > getIdentities ( String category , String type ) { List < Identity > res = new ArrayList < > ( identities . size ( ) ) ; for ( Identity identity : identities ) { if ( identity . getCategory ( ) . equals ( category ) && identity . getType ( ) . equals ( type ) ) { res . add ( identity ) ; } } return res ; }
Returns all Identities of the given category and type of this DiscoverInfo .
19,283
public boolean containsDuplicateIdentities ( ) { List < Identity > checkedIdentities = new LinkedList < > ( ) ; for ( Identity i : identities ) { for ( Identity i2 : checkedIdentities ) { if ( i . equals ( i2 ) ) return true ; } checkedIdentities . add ( i ) ; } return false ; }
Test if a DiscoverInfo response contains duplicate identities .
19,284
public synchronized void setName ( String name ) throws NotConnectedException , NoResponseException , XMPPErrorException , InterruptedException { if ( name != null && name . equals ( getName ( ) ) ) { return ; } RosterPacket packet = new RosterPacket ( ) ; packet . setType ( IQ . Type . set ) ; packet . addRosterItem ( toRosterItem ( this , name ) ) ; connection ( ) . createStanzaCollectorAndSend ( packet ) . nextResultOrThrow ( ) ; item . setName ( name ) ; }
Sets the name associated with this entry .
19,285
public List < RosterGroup > getGroups ( ) { List < RosterGroup > results = new ArrayList < > ( ) ; for ( RosterGroup group : roster . getGroups ( ) ) { if ( group . contains ( this ) ) { results . add ( group ) ; } } return results ; }
Returns an copied list of the roster groups that this entry belongs to .
19,286
public void cancelSubscription ( ) throws NotConnectedException , InterruptedException { Presence unsubscribed = new Presence ( item . getJid ( ) , Type . unsubscribed ) ; connection ( ) . sendStanza ( unsubscribed ) ; }
Cancel the presence subscription the XMPP entity representing this roster entry has with us .
19,287
private IQ receiveContentAcceptAction ( Jingle jingle , JingleDescription description ) throws XMPPException , NotConnectedException , InterruptedException { IQ response ; List < PayloadType > offeredPayloads = description . getAudioPayloadTypesList ( ) ; bestCommonAudioPt = calculateBestCommonAudioPt ( offeredPayloads ) ; if ( bestCommonAudioPt == null ) { setNegotiatorState ( JingleNegotiatorState . FAILED ) ; response = session . createJingleError ( jingle , JingleError . NEGOTIATION_ERROR ) ; } else { setNegotiatorState ( JingleNegotiatorState . SUCCEEDED ) ; triggerMediaEstablished ( getBestCommonAudioPt ( ) ) ; LOGGER . severe ( "Media choice:" + getBestCommonAudioPt ( ) . getName ( ) ) ; response = session . createAck ( jingle ) ; } return response ; }
The other side has sent us a content - accept . The payload types in that message may not match with what we sent but XEP - 167 says that the other side should retain the order of the payload types we first sent .
19,288
private IQ receiveSessionInitiateAction ( Jingle jingle , JingleDescription description ) { IQ response = null ; List < PayloadType > offeredPayloads = description . getAudioPayloadTypesList ( ) ; bestCommonAudioPt = calculateBestCommonAudioPt ( offeredPayloads ) ; synchronized ( remoteAudioPts ) { remoteAudioPts . addAll ( offeredPayloads ) ; } if ( bestCommonAudioPt != null ) { setNegotiatorState ( JingleNegotiatorState . PENDING ) ; } else { setNegotiatorState ( JingleNegotiatorState . FAILED ) ; } return response ; }
Receive a session - initiate packet .
19,289
private IQ receiveSessionInfoAction ( Jingle jingle , JingleDescription description ) throws JingleException { IQ response = null ; PayloadType oldBestCommonAudioPt = bestCommonAudioPt ; List < PayloadType > offeredPayloads ; boolean ptChange = false ; offeredPayloads = description . getAudioPayloadTypesList ( ) ; if ( ! offeredPayloads . isEmpty ( ) ) { synchronized ( remoteAudioPts ) { remoteAudioPts . clear ( ) ; remoteAudioPts . addAll ( offeredPayloads ) ; } bestCommonAudioPt = calculateBestCommonAudioPt ( remoteAudioPts ) ; if ( bestCommonAudioPt != null ) { ptChange = ! bestCommonAudioPt . equals ( oldBestCommonAudioPt ) ; if ( oldBestCommonAudioPt == null || ptChange ) { } } else { throw new JingleException ( JingleError . NO_COMMON_PAYLOAD ) ; } } return response ; }
A content info has been received . This is done for publishing the list of payload types ...
19,290
private IQ receiveSessionAcceptAction ( Jingle jingle , JingleDescription description ) throws JingleException { IQ response = null ; PayloadType . Audio agreedCommonAudioPt ; if ( bestCommonAudioPt == null ) { bestCommonAudioPt = calculateBestCommonAudioPt ( remoteAudioPts ) ; } List < PayloadType > offeredPayloads = description . getAudioPayloadTypesList ( ) ; if ( ! offeredPayloads . isEmpty ( ) ) { if ( offeredPayloads . size ( ) == 1 ) { agreedCommonAudioPt = ( PayloadType . Audio ) offeredPayloads . get ( 0 ) ; if ( bestCommonAudioPt != null ) { if ( ! agreedCommonAudioPt . equals ( bestCommonAudioPt ) ) { throw new JingleException ( JingleError . NEGOTIATION_ERROR ) ; } } } else if ( offeredPayloads . size ( ) > 1 ) { throw new JingleException ( JingleError . MALFORMED_STANZA ) ; } } return response ; }
A jmf description has been accepted . In this case we must save the accepted payload type and notify any listener ...
19,291
public void addRemoteAudioPayloadType ( PayloadType . Audio pt ) { if ( pt != null ) { synchronized ( remoteAudioPts ) { remoteAudioPts . add ( pt ) ; } } }
Adds a payload type to the list of remote payloads .
19,292
protected void triggerMediaClosed ( PayloadType currPt ) { List < JingleListener > listeners = getListenersList ( ) ; for ( JingleListener li : listeners ) { if ( li instanceof JingleMediaListener ) { JingleMediaListener mli = ( JingleMediaListener ) li ; mli . mediaClosed ( currPt ) ; } } }
Trigger a jmf closed event .
19,293
public JingleDescription getJingleDescription ( ) { JingleDescription result = null ; PayloadType payloadType = getBestCommonAudioPt ( ) ; if ( payloadType != null ) { result = new JingleDescription . Audio ( payloadType ) ; } else { result = new JingleDescription . Audio ( ) ; result . addAudioPayloadTypes ( localAudioPts ) ; } return result ; }
Create a JingleDescription that matches this negotiator .
19,294
public static synchronized ChatManager getInstanceFor ( XMPPConnection connection ) { ChatManager manager = INSTANCES . get ( connection ) ; if ( manager == null ) manager = new ChatManager ( connection ) ; return manager ; }
Returns the ChatManager instance associated with a given XMPPConnection .
19,295
public Chat createChat ( EntityJid userJID , ChatMessageListener listener ) { return createChat ( userJID , null , listener ) ; }
Creates a new chat and returns it .
19,296
public Chat createChat ( EntityJid userJID , String thread , ChatMessageListener listener ) { if ( thread == null ) { thread = nextID ( ) ; } Chat chat = threadChats . get ( thread ) ; if ( chat != null ) { throw new IllegalArgumentException ( "ThreadID is already used" ) ; } chat = createChat ( userJID , thread , true ) ; chat . addMessageListener ( listener ) ; return chat ; }
Creates a new chat using the specified thread ID then returns it .
19,297
public static void addProperty ( Stanza packet , String name , Object value ) { JivePropertiesExtension jpe = ( JivePropertiesExtension ) packet . getExtension ( JivePropertiesExtension . NAMESPACE ) ; if ( jpe == null ) { jpe = new JivePropertiesExtension ( ) ; packet . addExtension ( jpe ) ; } jpe . setProperty ( name , value ) ; }
Convenience method to add a property to a packet .
19,298
public static Object getProperty ( Stanza packet , String name ) { Object res = null ; JivePropertiesExtension jpe = ( JivePropertiesExtension ) packet . getExtension ( JivePropertiesExtension . NAMESPACE ) ; if ( jpe != null ) { res = jpe . getProperty ( name ) ; } return res ; }
Convenience method to get a property from a packet . Will return null if the stanza contains not property with the given name .
19,299
public static Collection < String > getPropertiesNames ( Stanza packet ) { JivePropertiesExtension jpe = ( JivePropertiesExtension ) packet . getExtension ( JivePropertiesExtension . NAMESPACE ) ; if ( jpe == null ) { return Collections . emptyList ( ) ; } return jpe . getPropertyNames ( ) ; }
Return a collection of the names of all properties of the given packet . If the packet contains no properties extension then an empty collection will be returned .