signature:
public class UserRoster { /** * Returns the presence info for a particular user . If the user is offline ,
 * or if no presence data is available ( such as when you are not subscribed
 * to the user ' s presence updates ) , unavailable presence will be returned .
 * If the user has several presences ( one for each resource ) , then the
 * presence with highest priority will be returned . If multiple presences
 * have the same priority , the one with the " most available " presence mode
 * will be returned . In order , that ' s
 * { @ link org . jivesoftware . smack . packet . Presence . Mode # chat free to chat } ,
 * { @ link org . jivesoftware . smack . packet . Presence . Mode # available available } ,
 * { @ link org . jivesoftware . smack . packet . Presence . Mode # away away } ,
 * { @ link org . jivesoftware . smack . packet . Presence . Mode # xa extended away } , and
 * { @ link org . jivesoftware . smack . packet . Presence . Mode # dnd do not disturb } .
 * Note that presence information is received asynchronously . So , just after
 * logging in to the server , presence values for users in the roster may be
 * unavailable even if they are actually online . In other words , the value
 * returned by this method should only be treated as a snapshot in time , and
 * may not accurately reflect other user ' s presence instant by instant . If
 * you need to track presence over time , such as when showing a visual
 * representation of the roster , consider using a { @ link RosterListener } .
 * @ param user
 * an XMPP ID . The address could be in any valid format ( e . g .
 * " domain / resource " , " user @ domain " or " user @ domain / resource " ) .
 * Any resource information that ' s part of the ID will be
 * discarded .
 * @ return the user ' s current presence , or unavailable presence if the user
 * is offline or if no presence information is available . . */
public Presence getPresence ( String user ) { } }

implementation:
String key = getPresenceMapKey ( StringUtils . parseBareAddress ( user ) ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return presence ; } else { // Find the resource with the highest priority
// Might be changed to use the resource with the highest
// availability instead .
Presence presence = null ; for ( String resource : userPresences . keySet ( ) ) { Presence p = userPresences . get ( resource ) ; if ( ! p . isAvailable ( ) ) { continue ; } // Chose presence with highest priority first .
if ( presence == null || p . getPriority ( ) > presence . getPriority ( ) ) { presence = p ; } // If equal priority , choose " most available " by the mode value .
else if ( p . getPriority ( ) == presence . getPriority ( ) ) { Presence . Show pMode = p . getShow ( ) ; // Default to presence mode of available .
if ( pMode == null ) { pMode = Presence . Show . chat ; } Presence . Show presenceMode = presence . getShow ( ) ; // Default to presence mode of available .
if ( presenceMode == null ) { presenceMode = Presence . Show . chat ; } if ( pMode . compareTo ( presenceMode ) < 0 ) { presence = p ; } } } if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return presence ; } else { return presence ; } }


signature:
public class UserRoster { /** * Returns the presence info for a particular user ' s resource , or
 * unavailable presence if the user is offline or if no presence information
 * is available , such as when you are not subscribed to the user ' s presence
 * updates .
 * @ param userWithResource
 * a fully qualified XMPP ID including a resource
 * ( user @ domain / resource ) .
 * @ return the user ' s current presence , or unavailable presence if the user
 * is offline or if no presence information is available . */
public Presence getPresenceResource ( String userWithResource ) { } }

implementation: String key = getPresenceMapKey ( userWithResource ) ; String resource = StringUtils . parseResource ( userWithResource ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { Presence presence = userPresences . get ( resource ) ; if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { return presence ; } }


signature:
public class UserRoster { /** * Returns an iterator ( of Presence objects ) for all of a user ' s current
 * presences or an unavailable presence if the user is unavailable ( offline )
 * or if no presence information is available , such as when you are not
 * subscribed to the user ' s presence updates .
 * @ param user
 * a XMPP ID , e . g . jdoe @ example . com .
 * @ return an iterator ( of Presence objects ) for all the user ' s current
 * presences , or an unavailable presence if the user is offline or
 * if no presence information is available . */
public Iterator < Presence > getPresences ( String user ) { } }

implementation: String key = getPresenceMapKey ( user ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return Arrays . asList ( presence ) . iterator ( ) ; } else { Collection < Presence > answer = new ArrayList < Presence > ( ) ; for ( Presence presence : userPresences . values ( ) ) { if ( presence . isAvailable ( ) ) { answer . add ( presence ) ; } } if ( ! answer . isEmpty ( ) ) { return answer . iterator ( ) ; } else { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return Arrays . asList ( presence ) . iterator ( ) ; } }


signature:
public class UserRoster { /** * Returns the key to use in the presenceMap for a fully qualified XMPP ID .
 * The roster can contain any valid address format such us
 * " domain / resource " , " user @ domain " or " user @ domain / resource " . If the roster
 * contains an entry associated with the fully qualified XMPP ID then use
 * the fully qualified XMPP ID as the key in presenceMap , otherwise use the
 * bare address . Note : When the key in presenceMap is a fully qualified XMPP
 * ID , the userPresences is useless since it will always contain one entry
 * for the user .
 * @ param user
 * the bare or fully qualified XMPP ID , e . g . jdoe @ example . com or
 * jdoe @ example . com / Work .
 * @ return the key to use in the presenceMap for the fully qualified XMPP
 * ID . */
private String getPresenceMapKey ( String user ) { } }

implementation: if ( user == null ) { return null ; } String key = user ; if ( ! contains ( user ) ) { key = StringUtils . parseBareAddress ( user ) ; } return key . toLowerCase ( ) ;


signature:
public class UserRoster { /** * Changes the presence of available contacts offline by simulating an
 * unavailable presence sent from the server . After a disconnection , every
 * Presence is set to offline . */
private void setOfflinePresences ( ) { } }

implementation: Presence packetUnavailable ; for ( String user : presenceMap . keySet ( ) ) { Map < String , Presence > resources = presenceMap . get ( user ) ; if ( resources != null ) { for ( String resource : resources . keySet ( ) ) { packetUnavailable = new Presence ( Presence . Type . unavailable ) ; packetUnavailable . setFrom ( user + "/" + resource ) ; presencePacketListener . processPacket ( packetUnavailable ) ; } } }


signature:
public class UserRoster { /** * Fires roster changed event to roster listeners indicating that the
 * specified collections of contacts have been added , updated or deleted
 * from the roster .
 * @ param addedEntries
 * the collection of address of the added contacts .
 * @ param updatedEntries
 * the collection of address of the updated contacts .
 * @ param deletedEntries
 * the collection of address of the deleted contacts . */
private void fireRosterChangedEvent ( Collection < String > addedEntries , Collection < String > updatedEntries , Collection < String > deletedEntries ) { } }

implementation: for ( RosterListener listener : rosterListeners ) { if ( ! addedEntries . isEmpty ( ) ) { listener . entriesAdded ( addedEntries ) ; } if ( ! updatedEntries . isEmpty ( ) ) { listener . entriesUpdated ( updatedEntries ) ; } if ( ! deletedEntries . isEmpty ( ) ) { listener . entriesDeleted ( deletedEntries ) ; } }


signature:
public class Authentication { /** * Sets the digest value using a connection ID and password . Password
 * digests offer a more secure alternative for authentication compared to
 * plain text . The digest is the hex - encoded SHA - 1 hash of the connection ID
 * plus the user ' s password . If the digest and password are set , digest
 * authentication will be used . If only one value is set , the respective
 * authentication mode will be used .
 * @ param connectionID
 * the connection ID .
 * @ param password
 * the password .
 * @ see org . jivesoftware . smack . Connection # getConnectionID ( ) */
public void setDigest ( String connectionID , String password ) { } }

implementation: setDigest ( StringUtils . hash ( connectionID + password ) ) ;


signature:
public class InformationProvider { /** * generates the resources
 * @ param resourceModel the resourceModel
 * @ param event the Event
 * @ return a Stream containing the resourceModel ( s ) */
@ Override public Optional < ? extends ResourceModel > generateResource ( ResourceModel resourceModel , Optional < EventModel > event ) { } }

implementation: switch ( resourceModel . getResourceID ( ) ) { case BroadcasterAvailablePlaylists . RESOURCE_ID : return createBroadcasterAvailablePlaylists ( ) ; case BroadcasterPlaylist . RESOURCE_ID : return createBroadcasterPlaylist ( resourceModel ) ; default : return MusicResourceGenerator . super . generateResource ( resourceModel , event ) ; }


signature:
public class AbstractMapEntry { /** * Sets the value stored in this Map Entry .
 * This Map Entry is not connected to a Map , so only the local data is
 * changed .
 * @ param value
 * the new value
 * @ return the previous value */
public V setValue ( V value ) { } }

implementation: V answer = this . value ; this . value = value ; return answer ;


signature:
public class ThreadPool { /** * / * ( non - Javadoc )
 * @ see org . apache . commons . pool . ObjectPool # borrowObject ( ) */
@ Override public Object borrowObject ( ) throws Exception { } }

implementation: log . debug ( " borrowing object.." ) ; WorkerThread thread = ( WorkerThread ) super . borrowObject ( ) ; thread . setPool ( this ) ; return thread ;


signature:
public class ThreadPool { /** * / * ( non - Javadoc )
 * @ see org . apache . commons . pool . ObjectPool # returnObject ( java . lang . Object ) */
@ Override public void returnObject ( Object obj ) throws Exception { } }

implementation: log . debug ( " returning object.." + obj ) ; super . returnObject ( obj ) ;


signature:
public class PresenceEvent { /** * creates a new PresenceEvent
 * @ param source the caller
 * @ param strict whether the addon can guarantee that the user is around
 * @ param known true if the addon knows if the person encountered is the ( main ) user
 * @ param firstEncounter if the user was first encountered in the specified mode
 * @ param descriptors the descriptors
 * @ return the optional PresenceEvent */
public static Optional < PresenceEvent > createPresenceEvent ( Identification source , boolean strict , boolean known , boolean firstEncounter , List < String > descriptors ) { } }

implementation: try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } if ( known ) { descriptors . add ( KNOWN_DESCRIPTOR ) ; } else { descriptors . add ( UNKNOWN_DESCRIPTOR ) ; } if ( firstEncounter ) descriptors . add ( FIRST_ENCOUNTER_DESCRIPTOR ) ; descriptors . add ( ID ) ; PresenceEvent stopRequest = new PresenceEvent ( source , descriptors ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class PresenceEvent { /** * creates a new PresenceEvent
 * @ param source the caller
 * @ param strict whether the addon can guarantee that the user is around
 * @ param known true if the addon knows if the person encountered is the ( main ) user
 * @ param firstEncounter if the user was first encountered in the specified mode
 * @ param descriptors the descriptors
 * @ param timePassed the time passed in seconds since the user was last encountered
 * @ return the optional PresenceEvent */
public static Optional < PresenceEvent > createPresenceEvent ( Identification source , boolean strict , boolean known , boolean firstEncounter , List < String > descriptors , Long timePassed ) { } }

implementation: try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } if ( known ) { descriptors . add ( KNOWN_DESCRIPTOR ) ; } else { descriptors . add ( UNKNOWN_DESCRIPTOR ) ; } if ( firstEncounter ) descriptors . add ( FIRST_ENCOUNTER_DESCRIPTOR ) ; descriptors . add ( ID ) ; PresenceEvent presenceEvent = new PresenceEvent ( source , descriptors ) ; presenceEvent . addResource ( new LastEncountered ( source , timePassed ) ) ; return Optional . of ( presenceEvent ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class SynchronizedMap { /** * Factory method to create a synchronized map .
 * @ param map the map to decorate , must not be null
 * @ throws IllegalArgumentException if map is null */
public static < K , V > Map < K , V > decorate ( Map < K , V > map ) { } }

implementation: return new SynchronizedMap < K , V > ( map ) ;


signature: public class SynchronizedMap { public void clear ( ) { } }

implementation: SyncUtils . synchronizeWrite ( lock , new Callback < Object > ( ) { @ Override protected void doAction ( ) { map . clear ( ) ; } } ) ;


signature:
public class PlayerRequest { /** * tries to set the Volume of the PlayerRequest .
 * if the Player supports the Change of the Volume , it will create a new PlayerRequest and return it , if not it
 * returns this .
 * @ param volume the Volume to set to
 * @ return a new PlayerRequest or this . */
public PlayerRequest trySetVolume ( Volume volume ) { } }

implementation: if ( capabilities . canChangeVolume ( ) ) { return new PlayerRequest ( trackInfo , playlist , permanent , player , capabilities , context , identifiable , volume ) ; } return this ;


signature:
public class PlayerRequest { /** * returns a List of Resources that can be added to an already existing event .
 * This causes the Addon to block the Event in the OutputPlugin lifecycle of the Event .
 * @ return a List of Resources */
@ SuppressWarnings ( "unused" ) public List < ResourceModel > resourcesForExisting ( ) { } }

implementation: List < ResourceModel > resourceModels = new ArrayList < > ( ) ; IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new MusicUsageResource ( id , true ) ) . ifPresent ( resourceModels :: add ) ; if ( volume != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new VolumeResource ( id , volume ) ) . ifPresent ( resourceModels :: add ) ; } if ( playlist != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new PlaylistResource ( id , playlist ) ) . ifPresent ( resourceModels :: add ) ; } if ( trackInfo != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new TrackInfoResource ( id , trackInfo ) ) . ifPresent ( resourceModels :: add ) ; } return resourceModels ;


signature:
public class PlayerRequest { /** * helper method for PlaylistSelector
 * @ param playlist the playlist selected
 * @ param permanent the permanent addon
 * @ param player the player
 * @ param capabilities the capabilities
 * @ param context the context
 * @ param identifiable the identifiable
 * @ return a PlayerRequest */
static PlayerRequest createPlayerRequest ( Playlist playlist , boolean permanent , Identification player , Capabilities capabilities , Context context , Identifiable identifiable ) { } }

implementation: return new PlayerRequest ( null , playlist , permanent , player , capabilities , context , identifiable ) ;


signature:
public class PlayerRequest { /** * creates a new PlayerRequest .
 * the resulting PlayerRequest is not permanent , which means that it will mute all other sound but is limited to
 * 10 minutes . < br >
 * For this method to return a non - empty Optional the following criteria must be met : < br >
 * < ul >
 * < li > the player must exist and be support the standard defined through the sdk < / li >
 * < li > the players - capabilities must allow requests from outside < / li >
 * < li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo < / li >
 * < / ul >
 * @ param trackInfo the trackInfo to pass with the request
 * @ param player the player to target
 * @ param source the addOnModule used for Context etc .
 * @ return the optional PlayerRequest */
@ SuppressWarnings ( "unused" ) public static Optional < PlayerRequest > createPlayerRequest ( TrackInfo trackInfo , Identification player , AddOnModule source ) { } }

implementation: return createPlayerRequest ( trackInfo , false , player , source ) ;


signature:
public class PlayerRequest { /** * creates a new PlayerRequest .
 * the resulting PlayerRequest is not permanent , which means that it will mute all other sound but is limited to
 * 10 minutes . < br >
 * For this method to return a non - empty Optional the following criteria must be met : < br >
 * < ul >
 * < li > the player must exist and be support the standard defined through the sdk < / li >
 * < li > the players - capabilities must allow requests from outside < / li >
 * < li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo < / li >
 * < / ul >
 * @ param playlist the playlist to pass with the request
 * @ param player the player to target
 * @ param source the addOnModule used for Context etc .
 * @ return the optional PlayerRequest */
@ SuppressWarnings ( "unused" ) public static Optional < PlayerRequest > createPlayerRequest ( Playlist playlist , Identification player , AddOnModule source ) { } }

implementation: return createPlayerRequest ( playlist , false , player , source ) ;


signature:
public class PlayerRequest { /** * creates a new PlayerRequest .
 * For this method to return a non - empty Optional the following criteria must be met : < br >
 * < ul >
 * < li > the player must exist and be support the standard defined through the sdk < / li >
 * < li > the players - capabilities must allow requests from outside < / li >
 * < li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo < / li >
 * < / ul >
 * @ param playlist the playlist to pass with the request
 * @ param permanent true means the player can play indefinitely , but only if no one is currently using audio as
 * permanent . It will also not block . false is limited to 10 minutes playback , but will block .
 * @ param player the player to target
 * @ param source the addOnModule used for Context etc .
 * @ return the optional PlayerRequest */
@ SuppressWarnings ( "unused" ) public static Optional < PlayerRequest > createPlayerRequest ( Playlist playlist , boolean permanent , Identification player , AddOnModule source ) { } }

implementation: if ( playlist == null || player == null || source == null ) return Optional . empty ( ) ; try { return source . getContext ( ) . getResources ( ) . generateResource ( new CapabilitiesResource ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList < > ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( resource -> Capabilities . importFromResource ( resource , source . getContext ( ) ) ) ) . get ( 1 , TimeUnit . SECONDS ) . filter ( capabilities -> { if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { source . getContext ( ) . getLogger ( ) . error ( "player does not handle play-request from outside" ) ; return false ; } if ( ! capabilities . hasPlayRequestDetailed ( ) ) { source . getContext ( ) . getLogger ( ) . error ( "player does not handle playlist-request from outside" ) ; return false ; } if ( ! playlist . verify ( capabilities ) ) { source . getContext ( ) . getLogger ( ) . error ( "player can not handle the playlist, probably illegal PlaybackModes" ) ; return false ; } return true ; } ) . map ( capabilities -> new PlayerRequest ( null , playlist , permanent , player , capabilities , source . getContext ( ) , source ) ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { source . getContext ( ) . getLogger ( ) . debug ( "unable to obtain capabilities" ) ; return Optional . empty ( ) ; }


signature:
public class LastEncountered { /** * returns the time passed if available
 * @ param eventModel the event
 * @ return the optional long */
@ SuppressWarnings ( "unused" ) public static Optional < Long > getTimePassed ( EventModel eventModel ) { } }

implementation: if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( ob -> ob instanceof Long ) . map ( ob -> ( Long ) ob ) . findAny ( ) ; } else { return Optional . empty ( ) ; }


signature:
public class PropertiesAssistant { /** * the listener will always be called , when the Properties - file changes .
 * @ param listener the listener */
public void registerUpdateListener ( Consumer < PropertiesAssistant > listener ) { } }

implementation: if ( listener != null ) listeners . add ( new WeakReference < > ( listener ) ) ;


signature:
public class PropertiesAssistant { /** * Initializes properties in the addOn . Creates new properties file using default properties . */
public void initProperties ( ) { } }

implementation: propertiesPath = getContext ( ) . getFiles ( ) . getPropertiesLocation ( ) + File . separator + getContext ( ) . getAddOns ( ) . getAddOn ( ) . getID ( ) + ".properties" ; this . propertiesFile = new File ( propertiesPath ) ; if ( ! this . propertiesFile . exists ( ) ) try { this . propertiesFile . createNewFile ( ) ; } catch ( IOException e ) { error ( "Error while trying to create the new Properties file" , e ) ; } try { BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( this . propertiesFile ) , "UTF8" ) ) ; try { properties . load ( in ) ; } catch ( IOException e ) { error ( "unable to load the InputStream for the PropertiesFile" , e ) ; } } catch ( FileNotFoundException | UnsupportedEncodingException e ) { error ( "Error while trying to read Properties-File" , e ) ; } if ( defaultPropertiesPath != null && new File ( defaultPropertiesPath ) . exists ( ) ) { @ SuppressWarnings ( "unchecked" ) Enumeration < String > keys = ( Enumeration < String > ) properties . propertyNames ( ) ; if ( ! keys . hasMoreElements ( ) ) { try { createDefaultPropertyFile ( defaultPropertiesPath ) ; } catch ( IOException e ) { error ( "Error while trying to copy the Default-Properties File" , e ) ; } if ( new File ( defaultPropertiesPath ) . exists ( ) && ! writeToPropertiesFile ( defaultPropertiesPath ) ) return ; reloadProperties ( ) ; } }


signature:
public class PropertiesAssistant { /** * reloads the propertiesFile into the properties object */
private void reloadProperties ( ) { } }

implementation: Properties temp = new Properties ( ) ; BufferedReader bufferedReader = null ; try { File properties = new File ( propertiesPath ) ; bufferedReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( properties ) , "UTF8" ) ) ; temp . load ( bufferedReader ) ; this . properties = temp ; listeners . removeIf ( weakReference -> weakReference . get ( ) == null ) ; listeners . forEach ( weakReference -> { Consumer < PropertiesAssistant > consumer = weakReference . get ( ) ; if ( consumer != null ) consumer . accept ( this ) ; } ) ; } catch ( IOException e ) { error ( "Error while trying to load the Properties-File: " + propertiesPath , e ) ; } finally { if ( bufferedReader != null ) { try { bufferedReader . close ( ) ; } catch ( IOException e ) { error ( "Unable to close input stream" , e ) ; } } }


signature:
public class PacketParserUtils { /** * Parses stream error packets .
 * @ param doc
 * the XML parser .
 * @ return an stream error packet .
 * @ throws Exception
 * if an exception occurs while parsing the packet . */
public static StreamError parseStreamError ( Element el ) throws IOException , XmlPullParserException { } }

implementation: String code = null ; Element condEl = ( Element ) el . elements ( ) . iterator ( ) . next ( ) ; if ( condEl . getNamespace ( ) . getURI ( ) . equals ( StreamError . NAMESPACE ) ) { code = condEl . getName ( ) ; } String text = condEl . elementText ( "text" ) ; return new StreamError ( code , text ) ;


signature:
public class PacketParserUtils { /** * Parse the available SASL mechanisms reported from the server .
 * @ param mechanismsEl
 * the XML parser , positioned at the start of the mechanisms
 * stanza .
 * @ return a collection of Stings with the mechanisms included in the
 * mechanisms stanza .
 * @ throws Exception
 * if an exception occurs while parsing the stanza . */
@ SuppressWarnings ( "unchecked" ) public static Collection < String > parseMechanisms ( Element mechanismsEl ) throws Exception { } }

implementation: List < Element > mechanisms = mechanismsEl . elements ( "mechanism" ) ; List < String > mechanismsStr = new LinkedList < String > ( ) ; for ( Element mechanismEl : mechanisms ) { mechanismsStr . add ( mechanismEl . getText ( ) ) ; } return mechanismsStr ;


signature:
public class PacketParserUtils { /** * Parse the available compression methods reported from the server .
 * @ param compressionEl
 * the XML parser , positioned at the start of the compression
 * stanza .
 * @ return a collection of Stings with the methods included in the
 * compression stanza .
 * @ throws Exception
 * if an exception occurs while parsing the stanza . */
@ SuppressWarnings ( "unchecked" ) public static Collection < String > parseCompressionMethods ( Element compressionEl ) throws IOException , XmlPullParserException { } }

implementation: List < Element > methodsEls = compressionEl . elements ( "method" ) ; List < String > methodsStr = new LinkedList < String > ( ) ; for ( Element methodEl : methodsEls ) { methodsStr . add ( methodEl . getText ( ) ) ; } return methodsStr ;


signature:
public class PacketParserUtils { /** * Parses a packet extension sub - packet .
 * @ param elementName
 * the XML element name of the packet extension .
 * @ param namespace
 * the XML namespace of the packet extension .
 * @ param parser
 * the XML parser , positioned at the starting element of the
 * extension .
 * @ return a PacketExtension .
 * @ throws Exception
 * if a parsing error occurs . */
public static PacketExtension parsePacketExtension ( String elementName , String namespace , XmlPullParser parser ) throws Exception { } }

implementation:
DefaultPacketExtension extension = new DefaultPacketExtension ( elementName , namespace ) ; boolean done = false ; while ( ! done ) { int eventType = parser . next ( ) ; if ( eventType == XmlPullParser . START_TAG ) { String name = parser . getName ( ) ; // If an empty element , set the value with the empty string .
if ( parser . isEmptyElementTag ( ) ) { extension . setValue ( name , "" ) ; } // Otherwise , get the the element text .
else { eventType = parser . next ( ) ; if ( eventType == XmlPullParser . TEXT ) { String value = parser . getText ( ) ; extension . setValue ( name , value ) ; } } } else if ( eventType == XmlPullParser . END_TAG ) { if ( parser . getName ( ) . equals ( elementName ) ) { done = true ; } } } return extension ;


signature:
public class PacketParserUtils { /** * Decodes a String into an object of the specified type . If the object type
 * is not supported , null will be returned .
 * @ param type
 * the type of the property .
 * @ param value
 * the encode String value to decode .
 * @ return the String value decoded into the specified type .
 * @ throws Exception
 * If decoding failed due to an error . */
private static Object decode ( Class < ? > type , String value ) throws Exception { } }

implementation: if ( type . getName ( ) . equals ( "java.lang.String" ) ) { return value ; } if ( type . getName ( ) . equals ( "boolean" ) ) { return Boolean . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "int" ) ) { return Integer . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "long" ) ) { return Long . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "float" ) ) { return Float . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "double" ) ) { return Double . valueOf ( value ) ; } if ( type . getName ( ) . equals ( "java.lang.Class" ) ) { return Class . forName ( value ) ; } return null ;


signature:
public class StartMusicRequest { /** * creates a new StartRequest
 * @ param source the caller
 * @ param target the target who should start playing
 * @ return the optional StartMusicRequest */
public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target ) { } }

implementation: return createStartMusicRequest ( source , target , ( TrackInfo ) null ) ;


signature:
public class StartMusicRequest { /** * creates a new StartRequest
 * @ param source the caller
 * @ param target the target who should start playing
 * @ param trackInfo the track to play
 * @ return the optional StartMusicRequest */
public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , TrackInfo trackInfo ) { } }

implementation: return createStartMusicRequest ( source , target , trackInfo , true ) ;


signature:
public class StartMusicRequest { /** * creates a new StartRequest
 * @ param source the caller
 * @ param target the target who should start playing
 * @ param trackInfo the track to play
 * @ param isUsingJava true if the player is using java
 * @ return the optional StartMusicRequest */
public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , TrackInfo trackInfo , boolean isUsingJava ) { } }

implementation: if ( target . equals ( source ) ) return Optional . empty ( ) ; try { StartMusicRequest request = new StartMusicRequest ( source , isUsingJava ) ; request . addResource ( new SelectorResource ( source , target ) ) ; if ( trackInfo != null ) request . addResource ( new TrackInfoResource ( target , trackInfo , source ) ) ; return Optional . of ( request ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class StartMusicRequest { /** * creates a new StartRequest
 * @ param source the caller
 * @ param target the target who should start playing
 * @ param playlist the playlist to play
 * @ return the optional StartMusicRequest */
public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , Playlist playlist ) { } }

implementation: return createStartMusicRequest ( source , target , playlist , true ) ;


signature:
public class StartMusicRequest { /** * creates a new StartRequest
 * @ param source the caller
 * @ param target the target who should start playing
 * @ param playlist the playlist to play
 * @ param isUsingJava true if the player is using java
 * @ return the optional StartMusicRequest */
public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , Playlist playlist , boolean isUsingJava ) { } }

implementation: if ( target . equals ( source ) ) return Optional . empty ( ) ; try { StartMusicRequest request = new StartMusicRequest ( source , isUsingJava ) ; request . addResource ( new SelectorResource ( source , target ) ) ; if ( playlist != null ) request . addResource ( new PlaylistResource ( target , playlist , source ) ) ; return Optional . of ( request ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class StartMusicRequest { /** * verifies that the StartMusicRequest is correct and checks whether the you are meant to react to it
 * @ param eventModel the EventModel to check against
 * @ param player the identifiable
 * @ param capabilities the capabilities
 * @ param activators the activators which are able to start the player if it is not able to start from outside commands
 * @ return true if verified , false if not */
public static boolean verify ( EventModel eventModel , Capabilities capabilities , Identifiable player , List < Identifiable > activators ) { } }

implementation: if ( ! eventModel . containsDescriptor ( StartMusicRequest . ID ) ) return false ; if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { if ( activators . stream ( ) . noneMatch ( identifiable -> identifiable . isOwner ( eventModel . getSource ( ) ) ) ) return false ; } if ( ! PlaylistResource . getPlaylist ( eventModel ) . map ( playlist -> playlist . verify ( capabilities ) ) . orElse ( true ) ) { return false ; } return SelectorResource . isTarget ( eventModel , player ) . orElse ( false ) ;


signature:
public class ComparisonFilterFactory { /** * Creates a filter where valid when an object in a
 * collection is the < strong > same as < / strong > the base object . */
public static < E > Filter < E > createSameAsFilter ( final E base ) { } }

implementation: return new Filter < E > ( ) { public boolean isValid ( E obj ) { return ( base == obj ) ; } } ;


signature:
public class ComparisonFilterFactory { /** * Creates a filter where valid when an object in a
 * collection is the < strong > equal to < / strong > the base object . */
public static < E > Filter < E > createEqualToFilter ( final Object base ) { } }

implementation: return new Filter < E > ( ) { public boolean isValid ( E obj ) { return obj . equals ( base ) ; } } ;


signature:
public class ComparisonFilterFactory { /** * Creates a filter where valid when an Comparable in a
 * collection is considered < strong > less than < / strong > the base object . */
public static < E extends Comparable < E > > Filter < E > createLessThanFilter ( final E base ) { } }

implementation: return createLessThanFilter ( base , new Comparator < E > ( ) { public int compare ( E obj1 , E obj2 ) { return obj1 . compareTo ( obj2 ) ; } } ) ;


signature:
public class ComparisonFilterFactory { /** * Creates a filter where valid when an Object in a
 * collection is considered < strong > less than < / strong > the base object ,
 * based on the given Comparator . */
public static < E > Filter < E > createLessThanFilter ( final E base , final Comparator < E > comparator ) { } }

implementation: return new Filter < E > ( ) { public boolean isValid ( E obj ) { return comparator . compare ( obj , base ) < 0 ; } } ;


signature:
public class PlaybackStateResource { /** * returns the PlaybackState from the resource
 * @ param x the resourceModel
 * @ return the optional Playbackstate ( empty if illegal resource ) */
public static Optional < PlaybackState > getPlaybackStateFromResource ( ResourceModel x ) { } }

implementation: if ( ! x . getResourceID ( ) . equals ( ID ) ) return Optional . empty ( ) ; Object resource = x . getResource ( ) ; if ( resource instanceof String ) { String state = ( String ) resource ; try { return Optional . of ( PlaybackState . valueOf ( state ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } } else { return Optional . empty ( ) ; }


signature:
public class ExternalComponentManager { /** * Returns the secret key for a sub - domain . If no key was found then the
 * default secret key will be returned .
 * @ param subdomain
 * the subdomain to return its secret key .
 * @ return the secret key for a sub - domain . */
public String getSecretKey ( String subdomain ) { } }

implementation:
// Find the proper secret key to connect as the subdomain .
String secretKey = secretKeys . get ( subdomain ) ; if ( secretKey == null ) { secretKey = defaultSecretKey ; } return secretKey ;


signature:
public class ExternalComponentManager { /** * Returns if we want components to be able to connect multiple times to the
 * same JID . This is a custom Openfire extension and will not work with any
 * other XMPP server . Other XMPP servers should ignore this extra setting .
 * @ param subdomain
 * the sub - domain .
 * @ return True or false if we are allowing multiple connections . */
public boolean isMultipleAllowed ( String subdomain ) { } }

implementation: Boolean allowed = allowMultiple . get ( subdomain ) ; return allowed != null && allowed ;


signature:
public class AbstractReferenceMap { /** * Gets the value mapped to the key specified .
 * @ param key
 * the key
 * @ return the mapped value , null if no match */
public V get ( Object key ) { } }

implementation: purgeBeforeRead ( ) ; Entry < K , V > entry = getEntry ( key ) ; if ( entry == null ) { return null ; } return entry . getValue ( ) ;


signature:
public class AbstractReferenceMap { /** * Puts a key - value mapping into this map . Neither the key nor the value may
 * be null .
 * @ param key
 * the key to add , must not be null
 * @ param value
 * the value to add , must not be null
 * @ return the value previously mapped to this key , null if none
 * @ throws NullPointerException
 * if either the key or value is null */
public V put ( K key , V value ) { } }

implementation: if ( key == null ) { throw new NullPointerException ( "null keys not allowed" ) ; } if ( value == null ) { throw new NullPointerException ( "null values not allowed" ) ; } purgeBeforeWrite ( ) ; return super . put ( key , value ) ;


signature:
public class AbstractReferenceMap { /** * Removes the specified mapping from this map .
 * @ param key
 * the mapping to remove
 * @ return the value mapped to the removed key , null if key not in map */
public V remove ( Object key ) { } }

implementation: if ( key == null ) { return null ; } purgeBeforeWrite ( ) ; return super . remove ( key ) ;


signature:
public class AbstractReferenceMap { /** * Returns a set view of this map ' s entries . An iterator returned entry is
 * valid until < code > next ( ) < / code > is called again . The
 * < code > setValue ( ) < / code > method on the < code > toArray < / code > entries has no
 * effect .
 * @ return a set view of this map ' s entries */
public Set < Map . Entry < K , V > > entrySet ( ) { } }

implementation: if ( entrySet == null ) { entrySet = new ReferenceEntrySet < K , V > ( this ) ; } return entrySet ;


signature:
public class AbstractReferenceMap { /** * Returns a set view of this map ' s keys .
 * @ return a set view of this map ' s keys */
public Set < K > keySet ( ) { } }

implementation: if ( keySet == null ) { keySet = new ReferenceKeySet < K , V > ( this ) ; } return keySet ;


signature:
public class AbstractReferenceMap { /** * Returns a collection view of this map ' s values .
 * @ return a set view of this map ' s values */
public Collection < V > values ( ) { } }

implementation: if ( values == null ) { values = new ReferenceValues < K , V > ( this ) ; } return values ;


signature:
public class AbstractReferenceMap { /** * Purges stale mappings from this map .
 * Note that this method is not synchronized ! Special care must be taken if ,
 * for instance , you want stale mappings to be removed on a periodic basis
 * by some background thread . */
protected void purge ( ) { } }

implementation: Reference ref = queue . poll ( ) ; while ( ref != null ) { purge ( ref ) ; ref = queue . poll ( ) ; }


signature:
public class AbstractReferenceMap { /** * Purges the specified reference .
 * @ param ref
 * the reference to purge */
protected void purge ( Reference ref ) { } }

implementation:
// The hashCode of the reference is the hashCode of the
// mapping key , even if the reference refers to the
// mapping value . . .
int hash = ref . hashCode ( ) ; int index = hashIndex ( hash , data . length ) ; HashEntry < K , V > previous = null ; HashEntry < K , V > entry = data [ index ] ; while ( entry != null ) { if ( ( ( ReferenceEntry < K , V > ) entry ) . purge ( ref ) ) { if ( previous == null ) { data [ index ] = entry . next ; } else { previous . next = entry . next ; } this . size -- ; return ; } previous = entry ; entry = entry . next ; }


signature:
public class AbstractReferenceMap { /** * Gets the entry mapped to the key specified .
 * @ param key
 * the key
 * @ return the entry , null if no match */
protected HashEntry < K , V > getEntry ( Object key ) { } }

implementation: if ( key == null ) { return null ; } else { return super . getEntry ( key ) ; }


signature:
public class AbstractReferenceMap { /** * Gets the hash code for a MapEntry . Subclasses can override this , for
 * example to use the identityHashCode .
 * @ param key
 * the key to get a hash code for , may be null
 * @ param value
 * the value to get a hash code for , may be null
 * @ return the hash code , as per the MapEntry specification */
protected int hashEntry ( Object key , Object value ) { } }

implementation: return ( key == null ? 0 : key . hashCode ( ) ) ^ ( value == null ? 0 : value . hashCode ( ) ) ;


signature:
public class AbstractReferenceMap { /** * Creates a ReferenceEntry instead of a HashEntry .
 * @ param next
 * the next entry in sequence
 * @ param hashCode
 * the hash code to use
 * @ param key
 * the key to store
 * @ param value
 * the value to store
 * @ return the newly created entry */
public HashEntry < K , V > createEntry ( HashEntry < K , V > next , int hashCode , K key , V value ) { } }

implementation: return new ReferenceEntry < K , V > ( this , ( ReferenceEntry < K , V > ) next , hashCode , key , value ) ;


signature:
public class AbstractReferenceMap { /** * Replaces the superclass method to store the state of this class .
 * Serialization is not one of the JDK ' s nicest topics . Normal serialization
 * will initialise the superclass before the subclass . Sometimes however ,
 * this isn ' t what you want , as in this case the < code > put ( ) < / code > method
 * on read can be affected by subclass state .
 * The solution adopted here is to serialize the state data of this class in
 * this protected method . This method must be called by the
 * < code > writeObject ( ) < / code > of the first serializable subclass .
 * Subclasses may override if they have a specific field that must be
 * present on read before this implementation will work . Generally , the read
 * determines what must be serialized here , if anything .
 * @ param out
 * the output stream */
protected void doWriteObject ( ObjectOutputStream out ) throws IOException { } }

implementation:
out . writeInt ( keyType ) ; out . writeInt ( valueType ) ; out . writeBoolean ( purgeValues ) ; out . writeFloat ( loadFactor ) ; out . writeInt ( data . length ) ; for ( MapIterator it = mapIterator ( ) ; it . hasNext ( ) ; ) { out . writeObject ( it . next ( ) ) ; out . writeObject ( it . getValue ( ) ) ; } out . writeObject ( null ) ; // null terminate map
// do not call super . doWriteObject ( ) as code there doesn ' t work for
// reference map


signature:
public class AbstractReferenceMap { /** * Replaces the superclassm method to read the state of this class .
 * Serialization is not one of the JDK ' s nicest topics . Normal serialization
 * will initialise the superclass before the subclass . Sometimes however ,
 * this isn ' t what you want , as in this case the < code > put ( ) < / code > method
 * on read can be affected by subclass state .
 * The solution adopted here is to deserialize the state data of this class
 * in this protected method . This method must be called by the
 * < code > readObject ( ) < / code > of the first serializable subclass .
 * Subclasses may override if the subclass has a specific field that must be
 * present before < code > put ( ) < / code > or < code > calculateThreshold ( ) < / code >
 * will work correctly .
 * @ param in
 * the input stream */
protected void doReadObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { } }

implementation:
this . keyType = in . readInt ( ) ; this . valueType = in . readInt ( ) ; this . purgeValues = in . readBoolean ( ) ; this . loadFactor = in . readFloat ( ) ; int capacity = in . readInt ( ) ; init ( ) ; data = new HashEntry [ capacity ] ; while ( true ) { K key = ( K ) in . readObject ( ) ; if ( key == null ) { break ; } V value = ( V ) in . readObject ( ) ; put ( key , value ) ; } threshold = calculateThreshold ( data . length , loadFactor ) ; // do not call super . doReadObject ( ) as code there doesn ' t work for
// reference map


signature:
public class PresenceConstant { /** * Controls whether the fired Event should be dispatched to all the listeners . This method should execute quickly
 * @ param eventModel the Event
 * @ return true if it should dispatch , false if not */
@ Override public boolean controlEvents ( EventModel eventModel ) { } }

implementation:
if ( level . compareTo ( PresenceIndicatorLevel . WEAK ) >= 0 ) { return present ; } else // noinspection SimplifiableIfStatement
if ( level . compareTo ( PresenceIndicatorLevel . WEAK ) < 0 && mostVague . get ( ) ) { return present ; } else { return true ; }


signature:
public class PresenceConstant { /** * sets the presence
 * @ param present true for presence , false if not */
public void setPresence ( boolean present ) { } }

implementation: if ( this . present == present ) return ; this . present = present ; updateVague ( ) ; if ( present ) { firePresence ( true ) ; } else { fireLeaving ( ) ; }


signature:
public class PresenceConstant { /** * updates the boolean whether it is the mode vague */
private void updateVague ( ) { } }

implementation: generateResource ( PresenceResource . ID ) . orElse ( CompletableFuture . completedFuture ( new ArrayList < > ( ) ) ) . thenAccept ( list -> mostVague . set ( list . stream ( ) . map ( Presence :: importPresence ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . map ( Presence :: getLevel ) . noneMatch ( level -> level . compareTo ( getLevel ( ) ) > 0 ) ) ) ;


signature:
public class Chat { /** * Sends the specified text as a message to the other chat participant . This
 * is a convenience method for :
 * < pre >
 * Message message = chat . createMessage ( ) ;
 * message . setBody ( messageText ) ;
 * chat . sendMessage ( message ) ;
 * < / pre >
 * @ param text
 * the text to send .
 * @ throws XMPPException
 * if sending the message fails . */
public void sendMessage ( String text ) throws XMPPException { } }

implementation: Message message = new Message ( ) ; message . setTo ( participant ) ; message . setType ( Type . chat ) ; message . setThread ( threadID ) ; message . setBody ( text ) ; chatManager . sendMessage ( this , message ) ;


signature:
public class Chat { /** * Delivers a message directly to this chat , which will add the message to
 * the collector and deliver it to all listeners registered with the Chat .
 * This is used by the Connection class to deliver messages without a thread
 * ID .
 * @ param message
 * the message . */
void deliver ( Message message ) { } }

implementation:
// Because the collector and listeners are expecting a thread ID with
// a specific value , set the thread ID on the message even though it
// probably never had one .
message . setThread ( threadID ) ; for ( MessageListener listener : listeners ) { listener . processMessage ( this , message ) ; }


signature:
public class Gen_RunScripts { /** * Generates a script .
 * @ param clazz the class for the script
 * @ param targetMap map for targets
 * @ return the final template for the script */
protected final ST generateScript ( String clazz , HashMap < String , Boolean > targetMap ) { } }

implementation: ST ret = this . stg . getInstanceOf ( "generateExec" ) ; ret . add ( "target" , targetMap ) ; ret . add ( "applicationHome" , this . applicationDir ) ; ret . add ( "runName" , this . configuration . get ( PROP_RUN_SCRIPT_NAME ) ) ; ret . add ( "class" , clazz ) ; return ret ;


signature:
public class Gen_RunScripts { /** * Loads and tests the configuration from configuration properties file .
 * The default configuration file name is " de / vandermeer / execs / configuration . properties " .
 * The file name can be overwritten using the " - - property - file " CLI option .
 * The method will also test for some configuration keys to exist and fail if they are not defined .
 * @ return 0 on success with configuration loaded , - 1 on error with errors printed on standard error */
protected final int initConfiguration ( ) { } }

implementation: String propFile = this . optionPropFile . getValue ( ) ; this . configuration = this . loadProperties ( propFile ) ; if ( this . configuration == null ) { System . err . println ( this . getAppName ( ) + ": could not load configuration properties from file <" + propFile + ">, exiting" ) ; return - 1 ; } if ( this . configuration . get ( PROP_RUN_SCRIPT_NAME ) == null ) { System . err . println ( this . getAppName ( ) + ": configuration does not contain key <" + PROP_RUN_SCRIPT_NAME + ">, exiting" ) ; return - 1 ; } if ( this . configuration . get ( PROP_RUN_CLASS ) == null ) { System . err . println ( this . getAppName ( ) + ": configuration does not contain key <" + PROP_RUN_CLASS + ">, exiting" ) ; return - 1 ; } if ( this . configuration . get ( PROP_JAVA_CP ) == null ) { System . err . println ( this . getAppName ( ) + ": configuration does not contain key <" + PROP_JAVA_CP + ">, exiting" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + ": using configuration: " ) ; System . out . println ( "  - run script name: " + this . configuration . get ( PROP_RUN_SCRIPT_NAME ) ) ; System . out . println ( "  - run class      : " + this . configuration . get ( PROP_RUN_CLASS ) ) ; System . out . println ( "  - java cp        : " + this . configuration . get ( PROP_JAVA_CP ) ) ; System . out . println ( "  - auto-gen reg   : " + this . configuration . get ( PROP_EXECS_AUTOGEN_REGISTERED ) ) ; for ( Object key : this . configuration . keySet ( ) ) { if ( StringUtils . startsWith ( key . toString ( ) , PROP_JAVAPROP_START ) ) { System . out . println ( "  - java property  : " + key + " = " + this . configuration . getProperty ( key . toString ( ) ) ) ; } } System . out . println ( ) ; return 0 ;


signature:
public class Gen_RunScripts { /** * Sets target for generation and initializes an STG object from an stg template file .
 * The default template file name is " de / vandermeer / execs / executable - script . stg " .
 * This default can be overwritten using the property " stg . file " in the configuration properties file .
 * The default and the property file name can be overwritten using the " - - stg - file " CLI option .
 * The set target ( CLI option " - - target " ) must be supported by the template file , otherwise this method will fail .
 * @ return 0 on success with configuration loaded , - 1 on error with errors printed on standard error */
protected final int initTargetAndStg ( ) { } }

implementation: this . target = this . optionTarget . getValue ( ) ; if ( this . target == null ) { System . err . println ( this . getAppName ( ) + ": no target set" ) ; return - 1 ; } String fileName = this . optionStgFile . getValue ( ) ; try { this . stg = new STGroupFile ( fileName ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + ": cannot load stg file <" + fileName + ">, general exception\n--> " + e ) ; return - 1 ; } String [ ] availableTargets = null ; try { availableTargets = StringUtils . split ( this . stg . getInstanceOf ( "supportedTargets" ) . render ( ) , " , " ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + ": stg file <" + fileName + "> does not contain <supportedTargets> function" ) ; return - 1 ; } if ( availableTargets . length == 0 ) { System . err . println ( this . getAppName ( ) + ": stg file <" + fileName + "> does not have a list of targets in <supportedTargets> function" ) ; return - 1 ; } if ( ! ArrayUtils . contains ( availableTargets , this . target ) ) { System . err . println ( this . getAppName ( ) + ": target " + this . target + " not supported in stg file <" + fileName + ">" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + ": generating scripts for target: " + this . target ) ; System . out . println ( ) ; return 0 ;


signature:
public class Gen_RunScripts { /** * Initializes the application directory for the generator .
 * There is no default set and no configuration property can be used .
 * The application directory has to be set using the CLI option " - - application - directory " .
 * Otherwise this method will fail .
 * @ return 0 on success with configuration loaded , - 1 on error with errors printed on standard error */
protected final int initApplicationDir ( ) { } }

implementation: this . applicationDir = this . optionAppHome . getValue ( ) ; if ( this . applicationDir == null ) { System . err . println ( this . getAppName ( ) + ": no application directory set" ) ; return - 1 ; } return 0 ;


signature:
public class Gen_RunScripts { /** * Loads a classmap from a property file .
 * A classmap maps class names to script names .
 * A class name must be an implementation of the executable application interface { @ link ExecS _ Application } .
 * No default map is used .
 * This default can be overwritten using the property " execs . classmap " in the configuration properties file .
 * The default and the property file name can be overwritten using the " - - classmap - file " CLI option .
 * @ return 0 on success with configuration loaded , - 1 on error with errors printed on standard error */
protected final int initClassmap ( ) { } }

implementation: this . optionClassMapFile . setPropertyValue ( this . configuration ) ; String fileName = this . optionClassMapFile . getValue ( ) ; if ( fileName == null ) { System . err . println ( this . getAppName ( ) + ": no classmap file name given" ) ; return - 2 ; } this . classMap = this . loadProperties ( fileName ) ; if ( this . classMap == null ) { System . err . println ( this . getAppName ( ) + ": could not load classmap, exiting" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + ": generating scripts for:" ) ; for ( Object key : this . classMap . keySet ( ) ) { System . out . println ( "  - " + key + " --> " + this . classMap . getProperty ( key . toString ( ) ) ) ; } System . out . println ( ) ; return 0 ;


signature:
public class Gen_RunScripts { /** * Tests and if necessary creates an output directory .
 * The root path is the current directory as given by the system property " user . dir " .
 * The created output directory has the name of the specified target for the generator .
 * The method fails if the output directory cannot be created or if it exists and is write protected .
 * @ return 0 on success with configuration loaded , - 1 on error with errors printed on standard error */
protected final int initOutputDir ( ) { } }

implementation:
String parent = System . getProperty ( "user.dir" ) ; String target = parent + File . separator + this . target ; File targetDir = new File ( target ) ; File parentDir = targetDir . getParentFile ( ) ; if ( targetDir . exists ( ) ) { // target dir exists , let ' s see if it is what we want it to be
if ( ! targetDir . isDirectory ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir <" + target + "> exists but is not a directory, exiting" ) ; return - 1 ; } if ( ! targetDir . canWrite ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir <" + target + "> exists but but cannot write into it, exiting" ) ; return - 1 ; } } else { // target dir does not exist , let ' s see if we can create it the way we need
if ( ! parentDir . isDirectory ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir parent <" + parent + "> exists but is not a directory, exiting" ) ; return - 1 ; } if ( ! parentDir . canWrite ( ) ) { System . err . println ( this . getAppName ( ) + ": target dir parent <" + parent + "> exists but but cannot write into it, exiting" ) ; return - 1 ; } if ( ! targetDir . mkdir ( ) ) { System . err . println ( this . getAppName ( ) + ": could not create target dir <" + target + ">, exiting" ) ; return - 1 ; } } this . outputDir = target ; return 0 ;


signature:
public class Gen_RunScripts { /** * Loads properties from a file .
 * @ param filename property file loaded from class path or file system
 * @ return loaded properties , null if nothing could be loaded plus error messages to standard error if exceptions are caught */
protected final Properties loadProperties ( String filename ) { } }

implementation: Properties ret = new Properties ( ) ; URL url = null ; File f = new File ( filename . toString ( ) ) ; if ( f . exists ( ) ) { try { url = f . toURI ( ) . toURL ( ) ; } catch ( Exception ignore ) { } } else { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; url = loader . getResource ( filename ) ; if ( url == null ) { loader = Gen_RunScripts . class . getClassLoader ( ) ; url = loader . getResource ( filename ) ; } } try { ret . load ( url . openStream ( ) ) ; } catch ( IOException e ) { System . err . println ( this . getAppName ( ) + ": cannot load property file <" + filename + ">, IO exception\n--><" + e + ">" ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + ": cannot load property file <" + filename + ">, general exception\n--><" + e + ">" ) ; } return ret ;


signature:
public class Gen_RunScripts { /** * Writes an ST object to a file .
 * @ param fn file name
 * @ param st ST template
 * @ return 0 on success with configuration loaded , - 1 on error with errors printed on standard error */
protected final int writeFile ( String fn , ST st ) { } }

implementation: try { FileWriter fs = new FileWriter ( fn ) ; BufferedWriter bw = new BufferedWriter ( fs ) ; bw . write ( st . render ( ) ) ; bw . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return - 1 ; } return 0 ;


signature:
public class ProgressResource { /** * gets the first Progress if found in the EventModel
 * @ param eventModel the EventModel
 * @ return return the optional Progress */
public static Optional < Progress > getProgress ( EventModel eventModel ) { } }

implementation: if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . findAny ( ) . flatMap ( Progress :: importResource ) ; } else { return Optional . empty ( ) ; }


signature:
public class SynchronizedCollection { /** * Factory method to create a synchronized collection .
 * @ param coll the collection to decorate , must not be null
 * @ throws IllegalArgumentException if collection is null */
public static < E > Collection < E > decorate ( Collection < E > coll ) { } }

implementation: return new SynchronizedCollection < E > ( coll ) ;


signature: public class SynchronizedCollection { public boolean add ( final E object ) { } }

implementation: Boolean ret = SyncUtils . synchronizeWrite ( lock , new Callback < Boolean > ( ) { @ Override protected void doAction ( ) { _return ( collection . add ( object ) ? Boolean . TRUE : Boolean . FALSE ) ; } } ) ; return ret . booleanValue ( ) ;


signature:
public class ServiceResolver { /** * Discover FireREST services located in a range of IPv4 InetAddresses .
 * E . g . , The range of 256 addresses that starts with 10.0.1.128 ends with 10.0.2.127.
 * @ param start first InetAddress to scan ( null for localhost )
 * @ param count number of subsequent InetAddresses in the range
 * @ param msTimeout maximum time to wait for host response
 * @ return ServiceResolvers that resolve to a FireREST service . */
public static Collection < ServiceResolver > discover ( InetAddress start , int count , int msTimeout ) { } }

implementation: Collection < ServiceResolver > result = new ArrayList < ServiceResolver > ( ) ; Collection < InetAddress > hosts = IPv4Scanner . scanRange ( start , count , msTimeout ) ; for ( InetAddress host : hosts ) { ServiceResolver resolver = new ServiceResolver ( host ) ; logger . info ( "resolving {} {}" , host . getHostAddress ( ) , host . getCanonicalHostName ( ) ) ; JSONResult config = resolver . getConfig ( ) ; if ( config != null ) { result . add ( resolver ) ; } } return result ;


signature:
public class ServiceResolver { /** * ( Re - ) discover the service configuration
 * @ return true if config . json was successfully obtained */
public void resolve ( ) { } }

implementation: attempts ++ ; config = null ; Exception caughtException = null ; String host = address == null ? "null" : address . getCanonicalHostName ( ) ; if ( url == null ) { URL attemptUrl = null ; int [ ] ports = { 8080 , 80 } ; for ( int i = 0 ; i < ports . length ; i ++ ) { try { attemptUrl = new URL ( "http" , host , ports [ i ] , "/firerest/config.json" ) ; break ; } catch ( Exception e ) { attemptUrl = null ; caughtException = e ; } } if ( attemptUrl == null ) { throw new FireRESTException ( "Could not resolve service at " + host , caughtException ) ; } url = attemptUrl ; } if ( config == null ) { logger . info ( "Resolving {}" , url ) ; config = new FireREST ( ) . withTimeout ( msTimeout ) . getJSON ( url ) ; }


signature:
public class ServiceResolver { /** * Return the cached service configuration , resolving the service if required .
 * @ return service configuration or null if service could not be resolved . */
public JSONResult getConfig ( ) { } }

implementation:
if ( attempts == 0 ) { try { resolve ( ) ; } catch ( Exception e ) { // discard exception
} } if ( config == null ) { logger . info ( "{} => no response" , url ) ; return null ; } logger . info ( "{} => {}" , url , config . get ( "FireREST" ) . getString ( ) ) ; return config ;


signature: public class WideColumnIndexer { @ Override public void invalidate ( String keySpace , String columnFamily , Map < String , Object > queryProperties ) { } }

implementation: Map < String , CacheHolder > queryCache = client . getQueryCache ( ) ; if ( queryCache == null ) { return ; } String cacheKey = getCacheKey ( keySpace , columnFamily , queryProperties ) ; if ( cacheKey != null ) { LOGGER . debug ( "Removing Cached Query {} " , cacheKey ) ; queryCache . remove ( cacheKey ) ; }


signature:
public class Registration { /** * Returns the map of String key / value pairs of account attributes .
 * @ return the account attributes . */
@ SuppressWarnings ( "unchecked" ) public Map < String , String > getAttributes ( ) { } }

implementation: Map < String , String > attributes = null ; List < Element > elements = queryEl . elements ( ) ; for ( Element element : elements ) { if ( ! element . getName ( ) . equals ( "instructions" ) ) { if ( attributes == null ) { attributes = new HashMap < String , String > ( ) ; } attributes . put ( element . getName ( ) , element . getText ( ) ) ; } } return attributes ;


signature:
public class Registration { /** * Sets the account attributes . The map must only contain String key / value
 * pairs .
 * @ param attributes
 * the account attributes . */
public void setAttributes ( Map < String , String > attributes ) { } }

implementation: for ( Entry < String , String > attribute : attributes . entrySet ( ) ) { PacketParserUtils . updateText ( queryEl , attribute . getKey ( ) , attribute . getValue ( ) ) ; }


signature:
public class Context { /** * returns the API used to manage the ThreadPool
 * @ return ThreadPool */
@ Override public org . intellimate . izou . sdk . specification . context . ThreadPool getThreadPool ( ) { } }

implementation: return threadPool ;


signature:
public class StopMusic { /** * creates a new StopRequest
 * @ param source the caller
 * @ param target the target who should start playing
 * @ return the optional StopMusicRequest */
public static Optional < StopMusic > createStopMusic ( Identification source , Identification target ) { } }

implementation: if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { StopMusic stopRequest = new StopMusic ( source ) ; stopRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class StopMusic { /** * verifies that the StopMusicRequest is correct and checks whether the you are meant to react to it
 * @ param eventModel the EventModel to check against
 * @ param player the identifiable
 * @ return true if verified , false if not */
public static boolean verify ( EventModel eventModel , Identifiable player ) { } }

implementation: if ( ! eventModel . containsDescriptor ( StopMusic . ID ) ) return false ; return SelectorResource . isTarget ( eventModel , player ) . orElse ( true ) ;


signature:
public class DseSessionManager { /** * { @ inheritDoc } */
@ Override protected DseCluster createCluster ( ClusterIdentifier ci ) { } }

implementation: return DseUtils . newDseCluster ( ci . hostsAndPorts , ci . username , ci . password , ci . authorizationId , getConfiguration ( ) ) ;


signature:
public class DseSessionManager { /** * { @ inheritDoc } */
@ Override protected DseSession createSession ( Cluster cluster , String keyspace ) { } }

implementation: return DseUtils . newDseSession ( ( DseCluster ) cluster , keyspace ) ;


signature:
public class DseSessionManager { /** * { @ inheritDoc } */
@ Override public DseCluster getCluster ( String hostsAndPorts , String username , String password ) { } }

implementation: return getCluster ( hostsAndPorts , username , password , null ) ;


signature:
public class DseSessionManager { /** * Obtain a DSE cluster instance .
 * @ param hostsAndPorts
 * format : " host1 : port1 , host2 , host3 : port3 " . If no port is
 * specified , the { @ link CqlUtils # DEFAULT _ CASSANDRA _ PORT } is used .
 * @ param username
 * @ param password
 * @ param authorizationId
 * DSE allows a user to connect as another user or role , provide the name of the
 * user / role you want to connect as via this parameter
 * @ return */
public DseCluster getCluster ( String hostsAndPorts , String username , String password , String authorizationId ) { } }

implementation: return getCluster ( ClusterIdentifier . getInstance ( hostsAndPorts , username , password , authorizationId ) ) ;


signature:
public class DseSessionManager { /** * { @ inheritDoc } */
@ Override synchronized protected DseSession getSession ( SessionIdentifier si , boolean forceNew ) { } }

implementation: return ( DseSession ) super . getSession ( si , forceNew ) ;


signature:
public class DseSessionManager { /** * { @ inheritDoc } */
@ Override public DseSession getSession ( String hostsAndPorts , String username , String password , String keyspace ) { } }

implementation: return getSession ( hostsAndPorts , username , password , null , keyspace , false ) ;


signature:
public class DseSessionManager { /** * Obtain a DSE session instance .
 * The existing session instance will be returned if such existed .
 * @ param hostsAndPorts
 * @ param username
 * @ param password
 * @ param authorizationId
 * DSE allows a user to connect as another user or role , provide the name of the
 * user / role you want to connect as via this parameter
 * @ param keyspace
 * @ return
 * @ throws NoHostAvailableException
 * @ throws AuthenticationException */
public DseSession getSession ( String hostsAndPorts , String username , String password , String authorizationId , String keyspace ) { } }

implementation: return getSession ( hostsAndPorts , username , password , authorizationId , keyspace , false ) ;


signature:
public class DseSessionManager { /** * Obtain a DSE session instance .
 * @ param hostsAndPorts
 * @ param username
 * @ param password
 * @ param authorizationId
 * DSE allows a user to connect as another user or role , provide the name of the
 * user / role you want to connect as via this parameter
 * @ param keyspace
 * @ param forceNew
 * force create new session instance ( the existing one , if any ,
 * will be closed by calling { @ link Session # closeAsync ( ) } )
 * @ return
 * @ throws NoHostAvailableException
 * @ throws AuthenticationException */
public DseSession getSession ( String hostsAndPorts , String username , String password , String authorizationId , String keyspace , boolean forceNew ) { } }

implementation: return getSession ( SessionIdentifier . getInstance ( hostsAndPorts , username , password , authorizationId , keyspace ) , forceNew ) ;


signature:
public class DseSessionManager { /** * { @ inheritDoc } */
public DseSession getSession ( boolean forceNew ) { } }

implementation: return getSession ( getDefaultHostsAndPorts ( ) , getDefaultUsername ( ) , getDefaultPassword ( ) , defaultAuthorizationId , getDefaultKeyspace ( ) , forceNew ) ;


signature:
public class Connection { /** * Adds a connection listener to this connection that will be notified when
 * the connection closes or fails .
 * @ param connectionListener
 * a connection listener . */
public void addConnectionListener ( ConnectionListener connectionListener ) { } }

implementation: if ( connectionListener == null ) { return ; } if ( ! connectionListeners . contains ( connectionListener ) ) { connectionListeners . add ( connectionListener ) ; }


signature:
public class Connection { /** * Creates a new packet collector for this connection . A packet filter
 * determines which packets will be accumulated by the collector . A
 * PacketCollector is more suitable to use than a { @ link PacketListener }
 * when you need to wait for a specific result .
 * @ param packetFilter
 * the packet filter to use .
 * @ return a new packet collector . */
public PacketCollector createPacketCollector ( PacketFilter packetFilter ) { } }

implementation:
PacketCollector collector = new PacketCollector ( this , packetFilter ) ; // Add the collector to the list of active collectors .
collectors . add ( collector ) ; return collector ;


signature:
public class Connection { /** * Registers a packet listener with this connection . A packet listener will
 * be invoked only when an incoming packet is received . A packet filter
 * determines which packets will be delivered to the listener . If the same
 * packet listener is added again with a different filter , only the new
 * filter will be used .
 * NOTE : If you want get a similar callback for outgoing packets , see
 * { @ link # addPacketInterceptor ( PacketInterceptor , PacketFilter ) } .
 * @ param packetListener
 * the packet listener to notify of new received packets .
 * @ param packetFilter
 * the packet filter to use . */
public void addPacketListener ( PacketListener packetListener , PacketFilter packetFilter ) { } }

implementation: if ( packetListener == null ) { throw new NullPointerException ( "Packet listener is null." ) ; } ListenerWrapper wrapper = new ListenerWrapper ( packetListener , packetFilter ) ; recvListeners . put ( packetListener , wrapper ) ;


signature:
public class Connection { /** * Registers a packet listener with this connection . The listener will be
 * notified of every packet that this connection sends . A packet filter
 * determines which packets will be delivered to the listener . Note that the
 * thread that writes packets will be used to invoke the listeners .
 * Therefore , each packet listener should complete all operations quickly or
 * use a different thread for processing .
 * @ param packetListener
 * the packet listener to notify of sent packets .
 * @ param packetFilter
 * the packet filter to use . */
public void addPacketSendingListener ( PacketListener packetListener , PacketFilter packetFilter ) { } }

implementation: if ( packetListener == null ) { throw new NullPointerException ( "Packet listener is null." ) ; } ListenerWrapper wrapper = new ListenerWrapper ( packetListener , packetFilter ) ; sendListeners . put ( packetListener , wrapper ) ;


signature:
public class Connection { /** * Process all packet listeners for sending packets .
 * @ param packet
 * the packet to process . */
protected void firePacketSendingListeners ( Packet packet ) { } }

implementation:
// Notify the listeners of the new sent packet
for ( ListenerWrapper listenerWrapper : sendListeners . values ( ) ) { listenerWrapper . notifyListener ( packet ) ; }


signature:
public class Connection { /** * Registers a packet interceptor with this connection . The interceptor will
 * be invoked every time a packet is about to be sent by this connection .
 * Interceptors may modify the packet to be sent . A packet filter determines
 * which packets will be delivered to the interceptor .
 * NOTE : For a similar functionality on incoming packets , see
 * { @ link # addPacketListener ( PacketListener , PacketFilter ) } .
 * @ param packetInterceptor
 * the packet interceptor to notify of packets about to be sent .
 * @ param packetFilter
 * the packet filter to use . */
public void addPacketInterceptor ( PacketInterceptor packetInterceptor , PacketFilter packetFilter ) { } }

implementation: if ( packetInterceptor == null ) { throw new NullPointerException ( "Packet interceptor is null." ) ; } interceptors . put ( packetInterceptor , new InterceptorWrapper ( packetInterceptor , packetFilter ) ) ;


signature:
public class Connection { /** * Process interceptors . Interceptors may modify the packet that is about to
 * be sent . Since the thread that requested to send the packet will invoke
 * all interceptors , it is important that interceptors perform their work as
 * soon as possible so that the thread does not remain blocked for a long
 * period .
 * @ param packet
 * the packet that is going to be sent to the server */
protected void firePacketInterceptors ( Packet packet ) { } }

implementation: if ( packet != null ) { for ( InterceptorWrapper interceptorWrapper : interceptors . values ( ) ) { interceptorWrapper . notifyListener ( packet ) ; } }


signature:
public class Connection { /** * Initialize the { @ link # debugger } . You can specify a customized
 * { @ link SmackDebugger } by setup the system property
 * < code > smack . debuggerClass < / code > to the implementation .
 * @ throws IllegalStateException
 * if the reader or writer isn ' t yet initialized .
 * @ throws IllegalArgumentException
 * if the SmackDebugger can ' t be loaded . */
protected void initDebugger ( ) { } }

implementation:
if ( reader == null || writer == null ) { throw new NullPointerException ( "Reader or writer isn't initialized." ) ; } // If debugging is enabled , we open a window and write out all network
// traffic .
if ( config . isDebuggerEnabled ( ) ) { if ( debugger == null ) { // Detect the debugger class to use .
String className = null ; // Use try block since we may not have permission to get a
// system
// property ( for example , when an applet ) .
try { className = System . getProperty ( "smack.debuggerClass" ) ; } catch ( Throwable t ) { // Ignore .
} Class < ? > debuggerClass = null ; if ( className != null ) { try { debuggerClass = Class . forName ( className ) ; } catch ( Exception e ) { log . warn ( "Unabled to instantiate debugger class " + className ) ; } } if ( debuggerClass == null ) { try { debuggerClass = Class . forName ( "org.jivesoftware.smackx.debugger.EnhancedDebugger" ) ; } catch ( Exception ex ) { try { debuggerClass = Class . forName ( "org.jivesoftware.smack.debugger.LiteDebugger" ) ; } catch ( Exception ex2 ) { log . warn ( "Unabled to instantiate either Smack debugger class" ) ; } } } // Create a new debugger instance . If an exception occurs then
// disable the debugging
// option
try { Constructor < ? > constructor = debuggerClass . getConstructor ( Connection . class , Writer . class , Reader . class ) ; debugger = ( SmackDebugger ) constructor . newInstance ( this , writer , reader ) ; reader = debugger . getReader ( ) ; writer = debugger . getWriter ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Can't initialize the configured debugger!" , e ) ; } } else { // Obtain new reader and writer from the existing debugger
reader = debugger . newConnectionReader ( reader ) ; writer = debugger . newConnectionWriter ( writer ) ; } }


signature:
public class RequestUtils { /** * Creates the most suitable type .
 * @ param name
 * the name . Types are specified as name @ Type where Type is the
 * name of the type . If the name ends with a [ ] the type is
 * forced to be an array .
 * @ param value
 * the value the value . If its an array , the type is assumed to
 * be an array provided there is more than one element . If there
 * is one element and the name ends with [ ] an array is created ,
 * otherwise a scalar is created .
 * @ return an instance */
public static Object toValue ( String name , Object value ) { } }

implementation: String [ ] parts = StringUtils . split ( name , "@" , 2 ) ; String fieldName = null ; String fieldType = "String" ; if ( parts . length == 2 ) { fieldType = parts [ 1 ] ; fieldName = parts [ 0 ] ; } else if ( parts . length == 1 ) { fieldName = parts [ 0 ] ; } else { throw new IllegalArgumentException ( "Invalid property name" ) ; } try { int l = Array . getLength ( value ) ; RequestParameterType < ? > rpt = TYPES . get ( fieldType ) ; if ( rpt == null ) { rpt = TYPES . get ( RequestParameterType . STRING ) ; } if ( ! fieldName . endsWith ( "[]" ) && l == 1 ) { return rpt . newInstance ( Array . get ( value , 0 ) ) ; } Class < ? > componentType = rpt . getComponentType ( ) ; Object [ ] a = ( Object [ ] ) Array . newInstance ( componentType , l ) ; for ( int i = 0 ; i < l ; i ++ ) { a [ i ] = rpt . newInstance ( Array . get ( value , i ) ) ; } return a ; } catch ( IllegalArgumentException e ) { RequestParameterType < ? > rpt = TYPES . get ( fieldType ) ; if ( rpt == null ) { rpt = TYPES . get ( RequestParameterType . STRING ) ; } return rpt . newInstance ( value ) ; }


signature:
public class ExternalComponent { /** * Generates a connection with the server and tries to authenticate . If an
 * error occurs in any of the steps then a ComponentException is thrown .
 * @ param host
 * the host to connect with .
 * @ param port
 * the port to use .
 * @ param subdomain
 * the subdomain that this component will be handling .
 * @ throws ComponentException
 * if an error happens during the connection and authentication
 * steps . */
public void connect ( String host , int port , String subdomain ) throws ComponentException { } }

implementation:
try { // Open a socket to the server
this . socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( host , port ) , manager . getConnectTimeout ( ) ) ; if ( manager . getServerName ( ) != null ) { this . domain = subdomain + "." + manager . getServerName ( ) ; } else { this . domain = subdomain ; } this . subdomain = subdomain ; // Keep these variables that will be used in case a reconnection is
// required
this . host = host ; this . port = port ; try { factory = XmlPullParserFactory . newInstance ( ) ; reader = new XPPPacketReader ( ) ; reader . setXPPFactory ( factory ) ; reader . getXPPParser ( ) . setInput ( new InputStreamReader ( socket . getInputStream ( ) , CHARSET ) ) ; // Get a writer for sending the open stream tag
writer = new BufferedWriter ( new OutputStreamWriter ( socket . getOutputStream ( ) , CHARSET ) ) ; // Open the stream .
StringBuilder stream = new StringBuilder ( ) ; stream . append ( "<stream:stream" ) ; stream . append ( " xmlns=\"jabber:component:accept\"" ) ; stream . append ( " xmlns:stream=\"http://etherx.jabber.org/streams\"" ) ; if ( manager . isMultipleAllowed ( subdomain ) ) { stream . append ( " allowMultiple=\"true\"" ) ; } stream . append ( " to=\"" ) . append ( domain ) . append ( "\">" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; stream = null ; // Get the answer from the server
XmlPullParser xpp = reader . getXPPParser ( ) ; for ( int eventType = xpp . getEventType ( ) ; eventType != XmlPullParser . START_TAG ; ) { eventType = xpp . next ( ) ; } // Set the streamID returned from the server
connectionID = xpp . getAttributeValue ( "" , "id" ) ; if ( xpp . getAttributeValue ( "" , "from" ) != null ) { this . domain = xpp . getAttributeValue ( "" , "from" ) ; } xmlSerializer = new XMLWriter ( writer ) ; // Handshake with the server
stream = new StringBuilder ( ) ; stream . append ( "<handshake>" ) ; stream . append ( StringUtils . hash ( connectionID + manager . getSecretKey ( subdomain ) ) ) ; stream . append ( "</handshake>" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; stream = null ; // Get the answer from the server
try { Element doc = reader . parseDocument ( ) . getRootElement ( ) ; if ( "error" . equals ( doc . getName ( ) ) ) { StreamError error = new StreamError ( doc ) ; // Close the connection
socket . close ( ) ; socket = null ; // throw the exception with the wrapped error
throw new ComponentException ( error ) ; } // Everything went fine
// Start keep alive thread to send every 30 seconds of
// inactivity a heart beat
keepAliveTask = new KeepAliveTask ( ) ; TaskEngine . getInstance ( ) . scheduleAtFixedRate ( keepAliveTask , 15000 , 30000 ) ; timeoutTask = new TimeoutTask ( ) ; TaskEngine . getInstance ( ) . scheduleAtFixedRate ( timeoutTask , 2000 , 2000 ) ; } catch ( DocumentException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing
} throw new ComponentException ( e ) ; } catch ( XmlPullParserException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing
} throw new ComponentException ( e ) ; } } catch ( XmlPullParserException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing
} throw new ComponentException ( e ) ; } } catch ( UnknownHostException uhe ) { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { // Do nothing
} throw new ComponentException ( uhe ) ; } catch ( IOException ioe ) { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { // Do nothing
} throw new ComponentException ( ioe ) ; }


signature:
public class ExternalComponent { /** * Notification message that the connection with the server was lost
 * unexpectedly . We will try to reestablish the connection for ever until
 * the connection has been reestablished or this thread has been stopped . */
public void connectionLost ( ) { } }

implementation:
// Ensure that only one thread will try to reconnect .
synchronized ( this ) { if ( reconnecting ) { return ; } reconnecting = true ; } readerThread = null ; boolean isConnected = false ; if ( ! shutdown ) { // Notify the component that connection was lost so it needs to
// shutdown . The component is
// still registered in the local component manager but just not
// connected to the server
component . shutdown ( ) ; } while ( ! isConnected && ! shutdown ) { try { connect ( host , port , subdomain ) ; isConnected = true ; // It may be possible that while a new connection was being
// established the
// component was required to shutdown so in this case we need to
// close the new
// connection
if ( shutdown ) { disconnect ( ) ; } else { // Component is back again working so start it up again
start ( ) ; } } catch ( ComponentException e ) { manager . getLog ( ) . error ( "Error trying to reconnect with the server" , e ) ; // Wait for 5 seconds until the next retry
try { Thread . sleep ( 5000 ) ; } catch ( InterruptedException e1 ) { // Do nothing
} } } reconnecting = false ;


signature:
public class ExternalComponent { /** * Adds an { @ link IQResultListener } that will be invoked when an IQ result
 * is sent to the server itself and is of type result or error . This is a
 * nice way for the server to send IQ packets to other XMPP entities and be
 * waked up when a response is received back .
 * Once an IQ result was received , the listener will be invoked and removed
 * from the list of listeners .
 * @ param id
 * the id of the IQ packet being sent from the server to an XMPP
 * entity .
 * @ param listener
 * the IQResultListener that will be invoked when an answer is
 * received
 * @ param timeoutmillis
 * The amount of milliseconds after which waiting for a response
 * should be stopped . */
void addIQResultListener ( String id , IQResultListener listener , long timeoutmillis ) { } }

implementation:
// be generated by the server and simulate like the client sent it . This
// will let listeners
// react and be removed from the collection
resultListeners . put ( id , listener ) ; resultTimeout . put ( id , System . currentTimeMillis ( ) + timeoutmillis ) ;


signature:
public class TransactionalBidiTreeMap { /** * Rolls back the changes to the map . */
public void rollback ( ) { } }

implementation: if ( auto_commit ) return ; String id = getCurrentThreadId ( ) ; ArrayList < Entry < K , V > > list = new ArrayList < Entry < K , V > > ( allEntrySet ( ) ) ; for ( Iterator < Entry < K , V > > i = list . iterator ( ) ; i . hasNext ( ) ; ) { final Node < K , V > node = ( Node < K , V > ) i . next ( ) ; if ( node . is ( Node . ADDED , id ) ) { doRedBlackDelete ( node ) ; if ( rollback_notifiers != null ) { SyncUtils . synchronizeRead ( rollback_notifiers , new Callback ( ) { @ Override protected void doAction ( ) { for ( Iterator i2 = rollback_notifiers . iterator ( ) ; i2 . hasNext ( ) ; ) ( ( TransactionNotifiable ) i2 . next ( ) ) . removedFromMap ( node . getKey ( ) , node . getValue ( ) ) ; } } ) ; } } if ( node . is ( Node . DELETED , id ) ) { node . setStatus ( Node . NO_CHANGE , null ) ; if ( rollback_notifiers != null ) { SyncUtils . synchronizeRead ( rollback_notifiers , new Callback ( ) { @ Override protected void doAction ( ) { for ( Iterator i2 = rollback_notifiers . iterator ( ) ; i2 . hasNext ( ) ; ) ( ( TransactionNotifiable ) i2 . next ( ) ) . addedToMap ( node . getKey ( ) , node . getValue ( ) ) ; } } ) ; } } }


signature:
public class TransactionalBidiTreeMap { /** * Retrieve the current thread id for use by the
 * transaction code .
 * @ return the thread id of the current thread */
protected String getCurrentThreadId ( ) { } }

implementation: String attach_id = ( String ) ThreadSession . getValue ( getThreadSessionKey ( ) ) ; if ( attach_id != null ) return attach_id ; Thread thread = Thread . currentThread ( ) ; return thread . toString ( ) + "(" + thread . hashCode ( ) + ")" ;


signature:
public class TransactionalBidiTreeMap { /** * Checks that this node is valid for the current thread
 * @ param node the node to be checked
 * @ return true if node is valid , otherwise false */
private boolean validNode ( final Node < K , V > node , final String thread_id ) { } }

implementation: if ( auto_commit || node == null ) return ( node != null ) ; return ! ( ( node . is ( Node . DELETED , thread_id ) ) || ( node . is ( Node . ADDED , null ) && node . is ( Node . NO_CHANGE , thread_id ) ) ) ;


signature:
public class TransactionalBidiTreeMap { /** * Returns the key to which this map maps the specified value .
 * Returns null if the map contains no mapping for this value .
 * @ param value value whose associated key is to be returned .
 * @ return the key to which this map maps the specified value , or
 * null if the map contains no mapping for this value .
 * @ throws ClassCastException if the value is of an
 * inappropriate type for this map .
 * @ throws NullPointerException if the value is null */
public K getKeyForValue ( final Object value ) throws ClassCastException , NullPointerException { } }

implementation: return ( K ) doGet ( value , VALUE ) ;


signature:
public class TransactionalBidiTreeMap { /** * Returns a set view of the mappings contained in this map . Each
 * element in the returned set is a Map . Entry . The set is backed
 * by the map , so changes to the map are reflected in the set , and
 * vice - versa . If the map is modified while an iteration over the
 * set is in progress , the results of the iteration are
 * undefined . The set supports element removal , which removes the
 * corresponding mapping from the map , via the Iterator . remove ,
 * Set . remove , removeAll , retainAll and clear operations . It does
 * not support the add or addAll operations . < p >
 * The difference between this method and entrySet is that
 * entrySet ' s iterator ( ) method returns an iterator that iterates
 * over the mappings in ascending order by key . This method ' s
 * iterator method iterates over the mappings in descending order
 * by value .
 * @ return a set view of the mappings contained in this map . */
public FilterableSet < Entry < K , V > > entrySetByValueDescending ( ) { } }

implementation: return new AbstractFilterableSet < Entry < K , V > > ( ) { @ Override public Iterator < Entry < K , V > > iterator ( ) { return new TransactionalBidiTreeMapDescendingIterator < Entry < K , V > > ( VALUE ) { @ Override protected Entry < K , V > doGetNext ( ) { return lastReturnedNode ; } } ; } @ Override public boolean contains ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object key = entry . getKey ( ) ; Node < K , V > node = lookupValid ( entry . getValue ( ) , VALUE , getCurrentThreadId ( ) ) ; return ( node != null ) && node . getData ( KEY ) . equals ( key ) ; } @ Override public boolean remove ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } String thread_id = getCurrentThreadId ( ) ; Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object key = entry . getKey ( ) ; Node < K , V > node = lookupValid ( entry . getValue ( ) , VALUE , thread_id ) ; if ( ( node != null ) && node . getData ( KEY ) . equals ( key ) ) { if ( auto_commit || node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else node . setStatus ( Node . DELETED , thread_id ) ; return true ; } return false ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ;


signature:
public class TransactionalBidiTreeMap { /** * Returns a set view of the keys contained in this map . The set
 * is backed by the map , so changes to the map are reflected in
 * the set , and vice - versa . If the map is modified while an
 * iteration over the set is in progress , the results of the
 * iteration are undefined . The set supports element removal ,
 * which removes the corresponding mapping from the map , via the
 * Iterator . remove , Set . remove , removeAll , retainAll , and clear
 * operations . It does not support the add or addAll
 * operations . < p >
 * The difference between this method and keySet is that keySet ' s
 * iterator ( ) method returns an iterator that iterates over the
 * keys in ascending order by key . This method ' s iterator method
 * iterates over the keys in ascending order by value .
 * @ return a set view of the keys contained in this map . */
public FilterableSet < K > keySetByValue ( ) { } }

implementation: if ( setOfKeysByValue == null ) { setOfKeysByValue = new AbstractFilterableSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new TransactionalBidiTreeMapIterator < K > ( VALUE ) { @ Override protected K doGetNext ( ) { return ( K ) lastReturnedNode . getData ( KEY ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsKey ( o ) ; } @ Override public boolean remove ( Object o ) { int oldnodeCount = nodeCount ; TransactionalBidiTreeMap . this . remove ( o ) ; return nodeCount != oldnodeCount ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfKeysByValue ;


signature:
public class TransactionalBidiTreeMap { /** * Returns a collection view of the values contained in this
 * map . The collection is backed by the map , so changes to the map
 * are reflected in the collection , and vice - versa . If the map is
 * modified while an iteration over the collection is in progress ,
 * the results of the iteration are undefined . The collection
 * supports element removal , which removes the corresponding
 * mapping from the map , via the Iterator . remove ,
 * Collection . remove , removeAll , retainAll and clear operations .
 * It does not support the add or addAll operations . < p >
 * The difference between this method and values is that values ' s
 * iterator ( ) method returns an iterator that iterates over the
 * values in ascending order by key . This method ' s iterator method
 * iterates over the values in ascending order by value .
 * @ return a collection view of the values contained in this map . */
public FilterableCollection < V > valuesByValue ( ) { } }

implementation: if ( collectionOfValuesByValue == null ) { collectionOfValuesByValue = new AbstractFilterableCollection < V > ( ) { @ Override public Iterator < V > iterator ( ) { return new TransactionalBidiTreeMapIterator < V > ( VALUE ) { @ Override protected V doGetNext ( ) { return ( V ) lastReturnedNode . getData ( VALUE ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsValue ( o ) ; } @ Override public boolean remove ( Object o ) { int oldnodeCount = nodeCount ; removeValue ( o ) ; return nodeCount != oldnodeCount ; } @ Override public boolean removeAll ( Collection < ? > c ) { boolean modified = false ; Iterator < ? > iter = c . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( removeValue ( iter . next ( ) ) != null ) { modified = true ; } } return modified ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return collectionOfValuesByValue ;


signature:
public class TransactionalBidiTreeMap { /** * common remove logic ( remove by key or remove by value )
 * @ param o the key , or value , that we ' re looking for
 * @ param index KEY or VALUE
 * @ return the key , if remove by value , or the value , if remove by
 * key . null if the specified key or value could not be
 * found
 * @ throws ConcurrentModificationException if the node has been
 * removed by another thread */
private Object doRemove ( final Object o , final int index ) throws ConcurrentModificationException { } }

implementation: checkNonNullComparable ( o , index ) ; String thread_id = getCurrentThreadId ( ) ; Node < K , V > node = lookupValid ( o , index , thread_id ) ; Object rval = null ; if ( validNode ( node , thread_id ) ) { if ( node != null && node . is ( Node . DELETED , null ) && ! node . is ( Node . DELETED , thread_id ) ) throw new ConcurrentModificationException ( ) ; rval = node . getData ( oppositeIndex ( index ) ) ; if ( auto_commit || node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else { node . setStatus ( Node . DELETED , thread_id ) ; } } return rval ;


signature:
public class TransactionalBidiTreeMap { /** * common get logic , used to get by key or get by value
 * @ param o the key or value that we ' re looking for
 * @ param index KEY or VALUE
 * @ return the key ( if the value was mapped ) or the value ( if the
 * key was mapped ) ; null if we couldn ' t find the specified
 * object */
private Object doGet ( final Object o , final int index ) { } }

implementation: checkNonNullComparable ( o , index ) ; Node < K , V > node = lookupValid ( o , index , getCurrentThreadId ( ) ) ; return ( node == null ) ? null : node . getData ( oppositeIndex ( index ) ) ;


signature:
public class TransactionalBidiTreeMap { /** * do the actual lookup of a piece of valid data
 * @ param data the key or value to be looked up
 * @ param index KEY or VALUE
 * @ return the desired Node , or null if there is no mapping of the
 * specified data */
private Node < K , V > lookupValid ( final Object data , final int index , final String thread_id ) { } }

implementation: return nextEqualValid ( getFloorEqualNode ( lookup ( data , index ) , index ) , index , thread_id ) ;


signature:
public class TransactionalBidiTreeMap { /** * do the actual lookup of a piece of data
 * @ param data the key or value to be looked up
 * @ param index KEY or VALUE
 * @ return the desired Node , or null if there is no mapping of the
 * specified data */
private Node < K , V > lookup ( final Object data , final int index ) { } }

implementation: Node < K , V > rval = null ; Node < K , V > node = rootNode [ index ] ; while ( node != null ) { int cmp = compare ( Node . NO_CHANGE , data , node . getStatus ( ) , node . getData ( index ) , index ) ; if ( cmp == 0 ) { rval = node ; break ; } else { node = ( cmp < 0 ) ? node . getLeft ( index ) : node . getRight ( index ) ; } } return rval ;


signature:
public class TransactionalBidiTreeMap { /** * Compare two objects
 * @ param o1 the first object
 * @ param o2 the second object
 * @ return negative value if o1 < o2 ; 0 if o1 = = o2 ; positive
 * value if o1 > o2 */
private int compare ( final int o1_status , final Object o1 , final int o2_status , final Object o2 , final int index ) { } }

implementation: if ( comparators [ index ] == null ) { if ( o1 instanceof TransactionalComparable ) return ( ( TransactionalComparable ) o1 ) . compareTo ( o1_status , o2 , o2_status ) ; else return ( ( Comparable ) o1 ) . compareTo ( o2 ) ; } else { return comparators [ index ] . compare ( o1 , o2 ) ; }


signature:
public class TransactionalBidiTreeMap { /** * find the least node from a given node . very useful for starting
 * a sorting iterator . . .
 * @ param node the node from which we will start searching
 * @ param index KEY or VALUE
 * @ return the smallest node , from the specified node , in the
 * specified mapping */
private Node < K , V > leastNode ( final Node < K , V > node , final int index ) { } }

implementation: Node < K , V > lval = node ; if ( lval != null ) { while ( lval . getLeft ( index ) != null ) { lval = lval . getLeft ( index ) ; } } return lval ;


signature:
public class TransactionalBidiTreeMap { /** * find the most node from a given node .
 * @ param node the node from which we will start searching
 * @ param index KEY or VALUE
 * @ return the largest node , from the specified node , in the
 * specified mapping */
private Node < K , V > mostNode ( final Node < K , V > node , final int index ) { } }

implementation: Node < K , V > rval = node ; if ( rval != null ) { while ( rval . getRight ( index ) != null ) { rval = rval . getRight ( index ) ; } } return rval ;