signature:
public class SmackConfiguration { /** * Add a Collection of SASL mechanisms to the list to be used .
 * @ param mechs
 * the Collection of SASL mechanisms to be added */
public static void addSaslMechs ( Collection < String > mechs ) { } }

implementation: initialize ( ) ; for ( String mech : mechs ) { addSaslMech ( mech ) ; }


signature:
public class ConsoleDebugger { /** * Creates the listeners that will print in the console when new activity is
 * detected . */
private void createDebug ( ) { } }

implementation:
// Create a special Reader that wraps the main Reader and logs data to
// the GUI .
ObservableReader debugReader = new ObservableReader ( reader ) ; readerListener = new ReaderListener ( ) { public void read ( String str ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " RCV  (" + connection . hashCode ( ) + "): " + str ) ; } } ; debugReader . addReaderListener ( readerListener ) ; // Create a special Writer that wraps the main Writer and logs data to
// the GUI .
ObservableWriter debugWriter = new ObservableWriter ( writer ) ; writerListener = new WriterListener ( ) { public void write ( String str ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " SENT (" + connection . hashCode ( ) + "): " + str ) ; } } ; debugWriter . addWriterListener ( writerListener ) ; // Assign the reader / writer objects to use the debug versions . The
// packet reader
// and writer will use the debug versions when they are created .
reader = debugReader ; writer = debugWriter ; // Create a thread that will listen for all incoming packets and write
// them to
// the GUI . This is what we call " interpreted " packet data , since it ' s
// the packet
// data as Smack sees it and not as it ' s coming in as raw XML .
listener = new PacketListener ( ) { public void processPacket ( Packet packet ) { if ( printInterpreted ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " RCV PKT (" + connection . hashCode ( ) + "): " + packet . toXML ( ) ) ; } } } ; connListener = new ConnectionListener ( ) { public void connectionClosed ( ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection closed (" + connection . hashCode ( ) + ")" ) ; } public void connectionClosedOnError ( Exception e ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection closed due to an exception (" + connection . hashCode ( ) + ")" ) ; e . printStackTrace ( ) ; } public void reconnectionFailed ( Exception e ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Reconnection failed due to an exception (" + connection . hashCode ( ) + ")" ) ; e . printStackTrace ( ) ; } public void reconnectionSuccessful ( ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection reconnected (" + connection . hashCode ( ) + ")" ) ; } public void reconnectingIn ( int seconds ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + " Connection (" + connection . hashCode ( ) + ") will reconnect in " + seconds ) ; } } ;


signature:
public class ProxyClientServiceImpl { /** * Create resources used by this component .
 * @ param ctx
 * @ throws Exception */
protected void activate ( Map < String , Object > properties ) throws Exception { } }

implementation:
configProperties = properties ; String [ ] safePostProcessorNames = ( String [ ] ) configProperties . get ( SAFE_POSTPROCESSORS ) ; if ( safePostProcessorNames == null ) { safeOpenProcessors . add ( "rss" ) ; safeOpenProcessors . add ( "trustedLoginTokenProxyPostProcessor" ) ; } else { for ( String pp : safePostProcessorNames ) { safeOpenProcessors . add ( pp ) ; } } // allow communications via a proxy server if command line
// java parameters http . proxyHost , http . proxyPort , http . proxyUser ,
// http . proxyPassword have been provided .
String proxyHost = System . getProperty ( "http.proxyHost" , "" ) ; if ( ! proxyHost . equals ( "" ) ) { useJreProxy = true ; }


signature:
public class ProxyClientServiceImpl { /** * Executes a HTTP call using a path in the JCR to point to a template and a
 * map of properties to populate that template with . An example might be a
 * SOAP call .
 * < pre >
 * { http : / / www . w3 . org / 2001/12 / soap - envelope } Envelope : {
 * { http : / / www . w3 . org / 2001/12 / soap - envelope } Body : {
 * { http : / / www . example . org / stock } GetStockPriceResponse : {
 * & gt ; body : [ ]
 * { http : / / www . example . org / stock } Price : {
 * & gt ; body : [ 34.5]
 * & gt ; body : [ ]
 * & gt ; body : [ ]
 * { http : / / www . w3 . org / 2001/12 / soap - envelope } encodingStyle : [ http : / / www . w3 . org / 2001/12 / soap - encoding ]
 * < / pre >
 * @ param resource
 * the resource containing the proxy end point specification .
 * @ param headers
 * a map of headers to set int the request .
 * @ param input
 * a map of parameters for all templates ( both url and body )
 * @ param requestInputStream
 * containing the request body ( can be null if the call requires
 * no body or the template will be used to generate the body )
 * @ param requestContentLength
 * if the requestImputStream is specified , the length specifies
 * the lenght of the body .
 * @ param requerstContentType
 * the content type of the request , if null the node property
 * sakai : proxy - request - content - type will be used .
 * @ throws ProxyClientException */
public ProxyResponse executeCall ( Map < String , Object > config , Map < String , Object > headers , Map < String , Object > input , InputStream requestInputStream , long requestContentLength , String requestContentType ) throws ProxyClientException { } }

implementation:
try { LOGGER . info ( "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] " + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] " , new Object [ ] { config , headers , input , requestInputStream , requestContentLength , requestContentType } ) ; bindConfig ( config ) ; if ( config != null && config . containsKey ( CONFIG_REQUEST_PROXY_ENDPOINT ) ) { // setup the post request
String endpointURL = ( String ) config . get ( CONFIG_REQUEST_PROXY_ENDPOINT ) ; if ( isUnsafeProxyDefinition ( config ) ) { try { URL u = new URL ( endpointURL ) ; String host = u . getHost ( ) ; if ( host . indexOf ( '$' ) >= 0 ) { throw new ProxyClientException ( "Invalid Endpoint template, relies on request to resolve valid URL " + u ) ; } } catch ( MalformedURLException e ) { throw new ProxyClientException ( "Invalid Endpoint template, relies on request to resolve valid URL" , e ) ; } } LOGGER . info ( "Valied Endpoint Def" ) ; Map < String , Object > context = Maps . newHashMap ( input ) ; // add in the config properties from the bundle overwriting
// everything else .
context . put ( "config" , configProperties ) ; endpointURL = processUrlTemplate ( endpointURL , context ) ; LOGGER . info ( "Calling URL {} " , endpointURL ) ; ProxyMethod proxyMethod = ProxyMethod . GET ; if ( config . containsKey ( CONFIG_REQUEST_PROXY_METHOD ) ) { try { proxyMethod = ProxyMethod . valueOf ( ( String ) config . get ( CONFIG_REQUEST_PROXY_METHOD ) ) ; } catch ( Exception e ) { } } HttpClient client = getHttpClient ( ) ; HttpUriRequest method = null ; switch ( proxyMethod ) { case GET : if ( config . containsKey ( CONFIG_LIMIT_GET_SIZE ) ) { long maxSize = ( Long ) config . get ( CONFIG_LIMIT_GET_SIZE ) ; HttpHead h = new HttpHead ( endpointURL ) ; HttpParams params = h . getParams ( ) ; // make certain we reject the body of a head
params . setBooleanParameter ( "http.protocol.reject-head-body" , true ) ; h . setParams ( params ) ; populateMessage ( method , config , headers ) ; HttpResponse response = client . execute ( h ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 200 ) { // Check if the content - length is smaller than the
// maximum ( if any ) .
Header contentLengthHeader = response . getLastHeader ( "Content-Length" ) ; if ( contentLengthHeader != null ) { long length = Long . parseLong ( contentLengthHeader . getValue ( ) ) ; if ( length > maxSize ) { return new ProxyResponseImpl ( HttpServletResponse . SC_PRECONDITION_FAILED , "Response too large" , response ) ; } } } else { return new ProxyResponseImpl ( response ) ; } } method = new HttpGet ( endpointURL ) ; break ; case HEAD : method = new HttpHead ( endpointURL ) ; break ; case OPTIONS : method = new HttpOptions ( endpointURL ) ; break ; case POST : method = new HttpPost ( endpointURL ) ; break ; case PUT : method = new HttpPut ( endpointURL ) ; break ; default : method = new HttpGet ( endpointURL ) ; } populateMessage ( method , config , headers ) ; if ( requestInputStream == null && ! config . containsKey ( CONFIG_PROXY_REQUEST_TEMPLATE ) ) { if ( method instanceof HttpPost ) { HttpPost postMethod = ( HttpPost ) method ; MultipartEntity multipart = new MultipartEntity ( ) ; for ( Entry < String , Object > param : input . entrySet ( ) ) { String key = param . getKey ( ) ; Object value = param . getValue ( ) ; if ( value instanceof Object [ ] ) { for ( Object val : ( Object [ ] ) value ) { addPart ( multipart , key , val ) ; } } else { addPart ( multipart , key , value ) ; } postMethod . setEntity ( multipart ) ; } } } else { if ( method instanceof HttpEntityEnclosingRequestBase ) { String contentType = requestContentType ; if ( contentType == null && config . containsKey ( CONFIG_REQUEST_CONTENT_TYPE ) ) { contentType = ( String ) config . get ( CONFIG_REQUEST_CONTENT_TYPE ) ; } if ( contentType == null ) { contentType = APPLICATION_OCTET_STREAM ; } HttpEntityEnclosingRequestBase eemethod = ( HttpEntityEnclosingRequestBase ) method ; if ( requestInputStream != null ) { eemethod . setHeader ( HttpHeaders . CONTENT_TYPE , contentType ) ; eemethod . setEntity ( new InputStreamEntity ( requestInputStream , requestContentLength ) ) ; } else { // build the request
StringWriter body = new StringWriter ( ) ; templateService . evaluate ( context , body , ( String ) config . get ( "path" ) , ( String ) config . get ( CONFIG_PROXY_REQUEST_TEMPLATE ) ) ; byte [ ] soapBodyContent = body . toString ( ) . getBytes ( "UTF-8" ) ; eemethod . setHeader ( HttpHeaders . CONTENT_TYPE , contentType ) ; eemethod . setEntity ( new InputStreamEntity ( new ByteArrayInputStream ( soapBodyContent ) , soapBodyContent . length ) ) ; } } } HttpResponse response = client . execute ( method ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 302 && method instanceof HttpEntityEnclosingRequestBase ) { // handle redirects on post and put
String url = response . getFirstHeader ( "Location" ) . getValue ( ) ; method = new HttpGet ( url ) ; response = client . execute ( method ) ; } return new ProxyResponseImpl ( response ) ; } } catch ( ProxyClientException e ) { throw e ; } catch ( Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new ProxyClientException ( "The Proxy request specified by  " + config + " failed, cause follows:" , e ) ; } finally { unbindConfig ( ) ; } throw new ProxyClientException ( "The Proxy request specified by " + config + " does not contain a valid endpoint specification " ) ;


signature:
public class EventPropertiesAssistant { /** * registers the standard - events */
private void registerStandardEvents ( ) { } }

implementation: CommonEvents . Descriptors . stopListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . leavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . presenceListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . fullResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . majorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . minorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . notificationListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . responseListener ( this ) . ifPresent ( this :: registerEventListener ) ;


signature:
public class EventPropertiesAssistant { /** * Registers or adds an event to the local _ events . properties file with the informations found in the EventListener
 * @ param eventListener the eventListener to add */
public void registerEventListener ( EventListener eventListener ) { } }

implementation: registerEventID ( eventListener . getDescription ( ) , eventListener . getDescriptorID ( ) , eventListener . getDescriptor ( ) ) ;


signature:
public class EventPropertiesAssistant { /** * Registers or adds an event to the local _ events . properties file
 * @ param description a simple description of the Event
 * @ param key the key with which to store the event ID
 * @ param value the complete event ID */
public void registerEventID ( String description , String key , String value ) { } }

implementation: BufferedWriter bufferedWriter ; FileOutputStream out = null ; try { out = new FileOutputStream ( eventPropertiesPath , true ) ; bufferedWriter = new BufferedWriter ( new OutputStreamWriter ( out ) ) ; doWithLock ( out . getChannel ( ) , lock -> { unlockedReloadFile ( ) ; if ( getEventID ( key ) != null ) { return ; } try { bufferedWriter . write ( "\n\n" + key + "_DESCRIPTION = " + description + "\n" + key + " = " + value ) ; bufferedWriter . flush ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } ) ; } catch ( FileNotFoundException e ) { error ( "Unable find file" , e ) ; } finally { try { if ( out != null ) { out . close ( ) ; } } catch ( IOException e ) { error ( "Unable to close lock" , e ) ; } }


signature:
public class EventPropertiesAssistant { /** * executes with a lock
 * @ param channel the channel where the lock is acquired from
 * @ param consumer the consumer to execute */
private void doWithLock ( FileChannel channel , Consumer < FileLock > consumer ) { } }

implementation: FileLock lock = null ; try { while ( lock == null ) { try { lock = channel . tryLock ( ) ; } catch ( OverlappingFileLockException e ) { Thread . sleep ( 500 ) ; } } consumer . accept ( lock ) ; } catch ( IOException | InterruptedException e ) { error ( "Unable to write" , e ) ; } finally { try { if ( lock != null ) { lock . release ( ) ; } } catch ( IOException e ) { error ( "Unable to close lock" , e ) ; } }


signature:
public class EventPropertiesAssistant { /** * Unregisters or deletes an event from the local _ events . properties file
 * @ param eventKey the key under which the complete event ID is stored in the properties file */
public void unregisterEventID ( String eventKey ) { } }

implementation: properties . remove ( eventKey + "_DESCRIPTION" ) ; properties . remove ( eventKey ) ; FileOutputStream out = null ; BufferedReader reader = null ; BufferedWriter writer = null ; try { out = new FileOutputStream ( eventPropertiesPath , true ) ; final File tempFile = new File ( eventPropertiesPath + "temp.properties" ) ; final BufferedReader readerFinal = new BufferedReader ( new FileReader ( eventPropertiesPath ) ) ; final BufferedWriter writerFinal = new BufferedWriter ( new FileWriter ( tempFile ) ) ; doWithLock ( out . getChannel ( ) , lock -> { unlockedReloadFile ( ) ; if ( getEventID ( eventKey ) != null ) { return ; } try { String currentLine = readerFinal . readLine ( ) ; while ( currentLine != null ) { String trimmedLine = currentLine . trim ( ) ; if ( trimmedLine . equals ( eventKey + "_DESCRIPTION" ) || trimmedLine . equals ( eventKey ) ) continue ; writerFinal . write ( currentLine + System . getProperty ( "line.separator" ) ) ; currentLine = readerFinal . readLine ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } ) ; reader = readerFinal ; writer = writerFinal ; tempFile . renameTo ( new File ( eventPropertiesPath ) ) ; } catch ( IOException e ) { error ( "Unable find file" , e ) ; } finally { try { if ( out != null ) { out . close ( ) ; } if ( writer != null ) { writer . close ( ) ; } if ( reader != null ) { reader . close ( ) ; } } catch ( IOException e ) { error ( "Unable to close lock" , e ) ; } }


signature:
public class OutputExtensionArgument { /** * Checks if the outputExtension can execute with the current event
 * @ param event the event to check against
 * @ return the state of whether the outputExtension can execute with the current event */
@ Override public boolean canRun ( EventModel event ) { } }

implementation:
// noinspection SimplifiableIfStatement
if ( event != null ) { return event . getListResourceContainer ( ) . providesResource ( getResourceIdWishList ( ) ) ; } return false ;


signature:
public class PlayerUpdate { /** * Creates a new Event Object
 * @ param source the source of the Event , most likely a this reference .
 * @ return the optional PlayerUpdate ( if no illegal arguments got passed )
 * @ throws IllegalArgumentException if one of the Arguments is null or empty */
public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source ) { } }

implementation: try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class PlayerUpdate { /** * Creates a new Event Object
 * @ param source the source of the Event , most likely a this reference .
 * @ param volume the current volume , not null
 * @ return the optional PlayerUpdate ( if no illegal arguments got passed )
 * @ throws IllegalArgumentException if one of the Arguments is null or empty */
public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , Volume volume ) { } }

implementation: if ( volume == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new VolumeResource ( source , volume ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class PlayerUpdate { /** * Creates a new Event Object
 * @ param source the source of the Event , most likely a this reference .
 * @ param playlist the current playing tracks
 * @ return the optional PlayerUpdate ( if no illegal arguments got passed )
 * @ throws IllegalArgumentException if one of the Arguments is null or empty */
public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , Playlist playlist ) { } }

implementation: if ( playlist == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new PlaylistResource ( source , playlist ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class PlayerUpdate { /** * Creates a new Event Object
 * @ param source the source of the Event , most likely a this reference .
 * @ param trackInfo the current song
 * @ return the optional PlayerUpdate ( if no illegal arguments got passed )
 * @ throws IllegalArgumentException if one of the Arguments is null or empty */
public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , TrackInfo trackInfo ) { } }

implementation: if ( trackInfo == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new TrackInfoResource ( source , trackInfo ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class ClusterIdentifier { /** * Helper method to get an instance of { @ link ClusterIdentifier } .
 * @ param hostsAndPorts
 * example { @ code " localhost : 9042 , host2 , host3:19042 " }
 * @ param username
 * username to authenticate against Cassandra cluster
 * @ param password
 * password to authenticate against Cassandra cluster
 * @ return */
public static ClusterIdentifier getInstance ( String hostsAndPorts , String username , String password ) { } }

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


signature:
public class ClusterIdentifier { /** * Helper method to get an instance of { @ link ClusterIdentifier } .
 * @ param hostsAndPorts
 * example { @ code " localhost : 9042 , host2 , host3:19042 " }
 * @ param username
 * username to authenticate against Cassandra cluster
 * @ param password
 * password to authenticate against Cassandra cluster
 * @ param authorizationId
 * DSE ' s proxied user / role id ( used with DSE only )
 * @ return */
public static ClusterIdentifier getInstance ( String hostsAndPorts , String username , String password , String authorizationId ) { } }

implementation: String [ ] key = { hostsAndPorts , username , password , authorizationId } ; try { return cache . get ( key ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; }


signature:
public class DseUtils { /** * Build a new DSE cluster instance .
 * @ param hostsAndPorts
 * format : " host1 : port1 , host2 , host3 : port3 " . If no port is
 * specified , the { @ link # DEFAULT _ CASSANDRA _ PORT } is used .
 * @ param username
 * @ param password
 * @ param proxiedUser
 * 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 static DseCluster newDseCluster ( String hostsAndPorts , String username , String password , String proxiedUser ) { } }

implementation: return newDseCluster ( hostsAndPorts , username , password , proxiedUser , null ) ;


signature:
public class DseUtils { /** * Build a new DSE cluster instance .
 * @ param hostsAndPorts
 * format : " host1 : port1 , host2 , host3 : port3 " . If no port is
 * specified , the { @ link # DEFAULT _ CASSANDRA _ PORT } is used .
 * @ param username
 * @ param password
 * @ param proxiedUser
 * 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 configuration
 * @ return */
public static DseCluster newDseCluster ( String hostsAndPorts , String username , String password , String proxiedUser , Configuration configuration ) { } }

implementation: DseCluster . Builder builder = DseCluster . builder ( ) ; if ( ! StringUtils . isBlank ( username ) ) { AuthProvider authProvider ; if ( StringUtils . isBlank ( proxiedUser ) ) { authProvider = new DsePlainTextAuthProvider ( username , password ) ; } else { authProvider = new DsePlainTextAuthProvider ( username , password , proxiedUser ) ; } builder = builder . withAuthProvider ( authProvider ) ; } Collection < InetSocketAddress > contactPointsWithPorts = new HashSet < InetSocketAddress > ( ) ; String [ ] hostAndPortArr = StringUtils . split ( hostsAndPorts , ";, " ) ; for ( String hostAndPort : hostAndPortArr ) { String [ ] tokens = StringUtils . split ( hostAndPort , ':' ) ; String host = tokens [ 0 ] ; int port = tokens . length > 1 ? Integer . parseInt ( tokens [ 1 ] ) : DEFAULT_CASSANDRA_PORT ; contactPointsWithPorts . add ( new InetSocketAddress ( host , port ) ) ; } builder = builder . addContactPointsWithPorts ( contactPointsWithPorts ) ; buildPolicies ( configuration , builder ) ; buildOptions ( configuration , builder ) ; DseCluster cluster = builder . build ( ) ; return cluster ;


signature:
public class DseUtils { /** * Create a new session for a DSE cluster , initializes it and sets the keyspace
 * to the provided one .
 * @ param cluster
 * @ param keyspace
 * @ return
 * @ throws NoHostAvailableException
 * @ throws AuthenticationException
 * @ throws IllegalStateException */
public static DseSession newDseSession ( DseCluster cluster , String keyspace ) { } }

implementation: return cluster . connect ( StringUtils . isBlank ( keyspace ) ? null : keyspace ) ;


signature:
public class PlayerError { /** * creates a new MusicPlayerError
 * @ param source the source
 * @ param error the error ( not null and not empty )
 * @ return the optional event */
public static Optional < PlayerError > createMusicPlayerError ( Identification source , String error ) { } }

implementation: if ( error == null || error . isEmpty ( ) ) return Optional . empty ( ) ; try { PlayerError playerError = new PlayerError ( source ) ; playerError . addResource ( new MusicErrorResource ( source , error ) ) ; return Optional . of ( playerError ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class PlayerController { /** * starts the playing command
 * @ param trackInfo the track to play */
public void startPlaying ( TrackInfo trackInfo ) { } }

implementation: Optional < Identification > ownIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) ; Optional < Identification > playerIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( player ) ; if ( ! ownIdentification . isPresent ( ) || ! playerIdentification . isPresent ( ) ) { error ( "unable to obtain identification" ) ; return ; } StartMusicRequest . createStartMusicRequest ( ownIdentification . get ( ) , playerIdentification . get ( ) , trackInfo , player . isUsingJava ) . ifPresent ( event -> fire ( event , 5 ) ) ;


signature:
public class PlayerController { /** * stops the playing of the music */
public void stopPlaying ( ) { } }

implementation: Optional < Identification > ownIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) ; Optional < Identification > playerIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( player ) ; if ( ! ownIdentification . isPresent ( ) || ! playerIdentification . isPresent ( ) ) { error ( "unable to obtain id" ) ; return ; } StopMusic . createStopMusic ( ownIdentification . get ( ) , playerIdentification . get ( ) ) . ifPresent ( event -> fire ( event , 5 ) ) ;


signature:
public class PlayerController { /** * commands the player to fulfill the command
 * @ param command the command
 * @ param playlist the playlist , or null if not needed
 * @ param progress the progress , or null if not needed
 * @ param trackInfo the trackInfo , or null if not needed
 * @ param volume the volume , or null if not needed */
public void command ( String command , Playlist playlist , Progress progress , TrackInfo trackInfo , Volume volume ) { } }

implementation: Optional < Identification > ownIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) ; Optional < Identification > playerIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( player ) ; if ( ! ownIdentification . isPresent ( ) || ! playerIdentification . isPresent ( ) ) { error ( "unable to obtain id" ) ; return ; } Optional < PlayerCommand > playerCommand = PlayerCommand . createPlayerCommand ( ownIdentification . get ( ) , playerIdentification . get ( ) , command , player . getCapabilities ( ) , getContext ( ) ) ; if ( playlist != null ) { playerCommand . get ( ) . addResource ( new PlaylistResource ( ownIdentification . get ( ) , playlist ) ) ; } if ( progress != null ) { playerCommand . get ( ) . addResource ( new ProgressResource ( ownIdentification . get ( ) , progress ) ) ; } if ( trackInfo != null ) { playerCommand . get ( ) . addResource ( new TrackInfoResource ( ownIdentification . get ( ) , trackInfo ) ) ; } if ( volume != null ) { playerCommand . get ( ) . addResource ( new VolumeResource ( ownIdentification . get ( ) , volume ) ) ; } fire ( playerCommand . get ( ) , 5 ) ;


signature:
public class BroadcasterPlaylist { /** * creates the Playlist - Request
 * @ param provider the provider of the playlist
 * @ param playlistName the name of the playlist
 * @ return the resource */
public static BroadcasterPlaylist createPlaylistRequest ( Identification provider , String playlistName ) { } }

implementation: HashMap < String , Object > hashMap = new HashMap < > ( ) ; hashMap . put ( RESOURCE_ID , playlistName ) ; return new BroadcasterPlaylist ( provider , hashMap ) ;


signature:
public class BroadcasterPlaylist { /** * creates the Playlist - Answer
 * @ param provider the provider
 * @ param playlist the playlist
 * @ return the resource */
public static BroadcasterPlaylist createPlaylistAnswer ( Identification provider , Playlist playlist ) { } }

implementation: return new BroadcasterPlaylist ( provider , playlist . export ( ) ) ;


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

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


signature:
public class VelocityLogger { /** * { @ inheritDoc }
 * @ see org . apache . velocity . runtime . log . LogChute # log ( int , java . lang . String ) */
public void log ( int level , String msg ) { } }

implementation: if ( inDebugMode ) { logger . info ( msg ) ; } switch ( level ) { case LogChute . DEBUG_ID : logger . debug ( msg ) ; break ; case LogChute . ERROR_ID : logger . error ( msg ) ; break ; case LogChute . INFO_ID : logger . info ( msg ) ; break ; case LogChute . TRACE_ID : logger . trace ( msg ) ; break ; case LogChute . WARN_ID : logger . warn ( msg ) ; break ; }


signature:
public class UrlBuilder { /** * Appends one or more postfixes and separates them by slashes .
 * @ param encode if true , the postFixes are url encoded .
 * @ param postFix one or more String values
 * @ return the builder */
public UrlBuilder append ( boolean encode , String ... postFix ) { } }

implementation: for ( String part : postFix ) { if ( StringUtils . isNotBlank ( part ) ) { if ( url . charAt ( url . length ( ) - 1 ) != '/' && ! part . startsWith ( "/" ) ) { url . append ( '/' ) ; } if ( encode ) { try { url . append ( URLEncoder . encode ( part , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } else { url . append ( part ) ; } } } return this ;


signature:
public class UrlBuilder { /** * Create a query parameter with a boolean value .
 * @ param name parameter name
 * @ param value value
 * @ return the builder */
public UrlBuilder queryParam ( String name , Boolean value ) { } }

implementation: if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; }


signature:
public class UrlBuilder { /** * Create a query parameter with a number value .
 * @ param name parameter name
 * @ param value value
 * @ return the builder */
public UrlBuilder queryParam ( String name , Number value ) { } }


signature:
public class UrlBuilder { /** * Create a query parameter with a String value . The value will be urlencoded .
 * @ param name name
 * @ param value value
 * @ return the builder */
public UrlBuilder queryParam ( String name , String value ) { } }

implementation: return queryParam ( name , value , true ) ;


signature:
public class UrlBuilder { /** * Create a query parameter with a String value .
 * @ param name name
 * @ param value value
 * @ param encode if true , the value is urlencoded .
 * @ return the builder */
public UrlBuilder queryParam ( String name , String value , boolean encode ) { } }

implementation: if ( StringUtils . isNotEmpty ( value ) ) { if ( encode ) { try { value = URLEncoder . encode ( value , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } params . add ( new EntryImpl ( name , value ) ) ; } return this ;


signature:
public class PlaylistResource { /** * gets the first playlist if found in the EventModel
 * @ param eventModel the EventModel
 * @ return return the optional Playlist */
public static Optional < Playlist > getPlaylist ( EventModel eventModel ) { } }

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


signature:
public class LaunchNakamura { /** * This method is called from within the constructor to initialize the form .
 * Note : This code was generated by Netbeans . */
private void initComponents ( ) { } }

implementation:
launchButton = new javax . swing . JButton ( ) ; statusLabel = new javax . swing . JLabel ( ) ; exitButton = new javax . swing . JButton ( ) ; headingLabel = new javax . swing . JLabel ( ) ; disclaimerLabel = new javax . swing . JLabel ( ) ; browserButton = new javax . swing . JButton ( ) ; setDefaultCloseOperation ( javax . swing . WindowConstants . EXIT_ON_CLOSE ) ; setTitle ( "Launch Nakamura" ) ; setName ( "mainFrame" ) ; // NOI18N
setResizable ( false ) ; launchButton . setFont ( new java . awt . Font ( "Arial" , 0 , 13 ) ) ; // NOI18N
launchButton . setText ( "Launch" ) ; launchButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { launchButtonActionPerformed ( evt ) ; } } ) ; statusLabel . setFont ( new java . awt . Font ( "Arial" , 0 , 12 ) ) ; // NOI18N
statusLabel . setText ( "Nakamura is not running." ) ; exitButton . setFont ( new java . awt . Font ( "Arial" , 0 , 13 ) ) ; // NOI18N
exitButton . setText ( "Exit" ) ; exitButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { exitButtonActionPerformed ( evt ) ; } } ) ; headingLabel . setText ( "SakaiOAE icon" ) ; headingLabel . setBorder ( javax . swing . BorderFactory . createEtchedBorder ( ) ) ; disclaimerLabel . setFont ( new java . awt . Font ( "Arial" , 0 , 13 ) ) ; // NOI18N
disclaimerLabel . setText ( "jLabel1" ) ; disclaimerLabel . setVerticalAlignment ( javax . swing . SwingConstants . TOP ) ; disclaimerLabel . setAutoscrolls ( true ) ; disclaimerLabel . setBorder ( javax . swing . BorderFactory . createTitledBorder ( "Disclaimer" ) ) ; browserButton . setText ( "Open Sakai OAE" ) ; browserButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { browserButtonActionPerformed ( evt ) ; } } ) ; javax . swing . GroupLayout layout = new javax . swing . GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 27 , 27 , 27 ) . addComponent ( launchButton ) . addGap ( 18 , 18 , 18 ) . addComponent ( statusLabel ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , 162 , Short . MAX_VALUE ) . addComponent ( browserButton ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( exitButton ) ) . addGroup ( javax . swing . GroupLayout . Alignment . CENTER , layout . createSequentialGroup ( ) . addContainerGap ( ) . addComponent ( headingLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 149 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addGap ( 18 , 18 , 18 ) . addComponent ( disclaimerLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 493 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) ) . addContainerGap ( ) ) ) ; layout . linkSize ( javax . swing . SwingConstants . HORIZONTAL , new java . awt . Component [ ] { exitButton , launchButton } ) ; layout . setVerticalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( disclaimerLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 215 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( headingLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 116 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addGap ( 58 , 58 , 58 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . CENTER ) . addComponent ( browserButton ) . addComponent ( exitButton ) ) . addContainerGap ( ) ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 259 , 259 , 259 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( launchButton , javax . swing . GroupLayout . PREFERRED_SIZE , 50 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( statusLabel ) ) . addContainerGap ( javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) ; pack ( ) ;


signature:
public class LaunchNakamura { /** * This is the launch button action method . This method launches the Apache Sling
 * bootloader and informs the user to wait before accessing it in a browser .
 * @ param evt
 * The details of the Action event .
 * @ throws IOException */
private void launchButtonActionPerformed ( java . awt . event . ActionEvent evt ) { } }

implementation:
// Launch Nakamura
if ( runStatus == APP_NOT_RUNNING ) { System . setSecurityManager ( null ) ; try { NakamuraMain . main ( savedArgs ) ; // Update label
statusLabel . setText ( "Nakamura is starting..." ) ; // Notify the user
JOptionPane . showMessageDialog ( this , "Nakamura has been started.\nPlease allow 30-60 seconds for it to be ready." , "Information" , JOptionPane . INFORMATION_MESSAGE ) ; runStatus = APP_RUNNING ; isStartupFinished ( ) ; } catch ( IOException e ) { statusLabel . setText ( "Nakamura is startup failed " + e . getMessage ( ) ) ; } } else { // Can ' t start it again . . .
// custom title , warning icon
JOptionPane . showMessageDialog ( this , "Nakamura is already running." , "Warning" , JOptionPane . WARNING_MESSAGE ) ; }


signature:
public class LaunchNakamura { /** * Pings the Apache Sling server URL every 5 seconds to see if it has finished booting .
 * Once it receives an OK status , it enables the button to launch the browser and
 * disables the launch Nakamura button . */
private void isStartupFinished ( ) { } }

implementation: boolean started = false ; try { while ( ! started ) { if ( exists ( localhostURL ) ) started = true ; Thread . sleep ( 5 * 1000 ) ; } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( started ) { statusLabel . setText ( "Nakamura is running." ) ; statusLabel . setForeground ( Color . green ) ; launchButton . setEnabled ( false ) ; browserButton . setEnabled ( true ) ; }


signature:
public class LaunchNakamura { /** * Pings the Apache Sling server URL , looking for an OK status . Returns true once that
 * OK status is received .
 * @ param URLName
 * The URL to ping .
 * @ return true if OK status is received back . False if not OK . */
public static boolean exists ( String URLName ) { } }

implementation:
try { HttpURLConnection . setFollowRedirects ( false ) ; // note : you may also need
// HttpURLConnection . setInstanceFollowRedirects ( false )
HttpURLConnection con = ( HttpURLConnection ) new URL ( URLName ) . openConnection ( ) ; con . setRequestMethod ( "HEAD" ) ; return ( con . getResponseCode ( ) == HttpURLConnection . HTTP_OK ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return false ; }


signature:
public class LaunchNakamura { /** * Performs the action when the browser button is pressed , which is launch a web browser
 * and browse to the server URL .
 * @ param evt
 * The details of the event . */
private void browserButtonActionPerformed ( java . awt . event . ActionEvent evt ) { } }

implementation: try { Desktop . getDesktop ( ) . browse ( new URL ( localhostURL ) . toURI ( ) ) ; } catch ( IOException e ) { System . err . println ( "IO Exception: " + e . getMessage ( ) ) ; } catch ( URISyntaxException e ) { System . err . println ( "URISyntaxException: " + e . getMessage ( ) ) ; }


signature:
public class LaunchNakamura { /** * Returns an ImageIcon , or null if the path was invalid .
 * @ param path
 * The path to the icon .
 * @ param description
 * The description of the icon .
 * @ return the newly created ImageIcon or null . */
protected ImageIcon createImageIcon ( String path , String description ) { } }

implementation: java . net . URL imgURL = getClass ( ) . getResource ( path ) ; if ( imgURL != null ) { return new ImageIcon ( imgURL , description ) ; } else { System . err . println ( "Couldn't find file: " + path ) ; return null ; }


signature:
public class LaunchNakamura { /** * Returns the full contents of a ( assumed ) text file for use in a label .
 * @ param path
 * The path to the text file .
 * @ return The contents of the file as a String .
 * @ throws IOException
 * thrown if the file is unable to be read . */
protected String getLabelText ( String path ) throws IOException { } }

implementation: InputStream is = this . getClass ( ) . getResourceAsStream ( path ) ; if ( is != null ) { Writer writer = new StringWriter ( ) ; char [ ] buffer = new char [ 1024 ] ; try { Reader reader = new BufferedReader ( new InputStreamReader ( is , "UTF-8" ) ) ; int n ; while ( ( n = reader . read ( buffer ) ) != - 1 ) { writer . write ( buffer , 0 , n ) ; } } finally { is . close ( ) ; } return writer . toString ( ) ; } else { System . err . println ( "Couldn't find file: " + path ) ; return null ; }


signature:
public class LaunchNakamura { /** * The Main method which executes the program .
 * @ param args
 * the command line arguments */
public static void main ( String args [ ] ) { } }

implementation: savedArgs = args ; java . awt . EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { new LaunchNakamura ( ) . setVisible ( true ) ; } } ) ;


signature:
public class IntArray { /** * Replace contents with given values */
public IntArray with ( int ... values ) { } }

implementation: if ( values . length != this . length ) throw new IllegalArgumentException ( "Array size mismatch" ) ; value = values . clone ( ) ; return this ;


signature:
public class Presence { /** * exports the Presence to a HashMap
 * @ return the resulting HashMap */
public HashMap < String , Object > export ( ) { } }

implementation: HashMap < String , Object > data = new HashMap < > ( ) ; data . put ( LEVEL_DESCRIPTOR , level . name ( ) ) ; data . put ( PRESENT_DESCRIPTOR , present ) ; data . put ( STRICT_DESCRIPTOR , strict ) ; data . put ( KNOWN_DESCRIPTOR , known ) ; return data ;


signature:
public class Presence { /** * imports ( if no errors occurred ) the Presence from the ResourceModel
 * @ param resourceModel the resourcemodel to import from
 * @ return the ( optional ) presence */
public static Optional < Presence > importPresence ( ResourceModel resourceModel ) { } }

implementation:
Object resource = resourceModel . getResource ( ) ; try { // noinspection unchecked
HashMap < String , Object > data = ( HashMap < String , Object > ) resource ; PresenceIndicatorLevel level ; try { level = PresenceIndicatorLevel . valueOf ( ( String ) data . get ( LEVEL_DESCRIPTOR ) ) ; } catch ( IllegalArgumentException e ) { level = PresenceIndicatorLevel . VERY_WEAK ; } boolean present = ( boolean ) data . get ( PRESENT_DESCRIPTOR ) ; boolean strict = ( boolean ) data . get ( STRICT_DESCRIPTOR ) ; boolean known = ( boolean ) data . get ( KNOWN_DESCRIPTOR ) ; return Optional . of ( new Presence ( level , present , strict , known ) ) ; } catch ( Exception e ) { return Optional . empty ( ) ; }


signature:
public class JSONResult { /** * Advance current JSON value to specified element in JSON array .
 * Set current JSON value to null otherwise .
 * @ param index zero - based JSON array index
 * @ return JSONResult for fluent method chaining */
public JSONResult get ( int index ) { } }

implementation: if ( value instanceof JSONArray ) { JSONArray array = ( JSONArray ) value ; Object result = array . get ( index ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONObject ) { return get ( String . valueOf ( index ) ) ; } return new JSONResult ( null ) ;


signature:
public class JSONResult { /** * Advance current JSON value to specified value of current JSON object .
 * Set current JSON value to null otherwise .
 * @ param key element key
 * @ return JSONResult for fluent method chaining */
public JSONResult get ( String key ) { } }

implementation: if ( value instanceof JSONObject ) { JSONObject obj = ( JSONObject ) value ; Object result = obj . get ( key ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONArray ) { try { int index = Integer . parseInt ( key ) ; return get ( index ) ; } catch ( NumberFormatException e ) { throw createException ( "Excpected JSONObject " + key + ":" ) ; } } return new JSONResult ( null ) ;


signature:
public class JSONResult { /** * Return an integer for current JSON value , parsing string values as required . */
public Integer getInt ( Integer defaultValue ) { } }

implementation: if ( value instanceof Number ) { return ( ( Number ) value ) . intValue ( ) ; } if ( value instanceof String ) { String s = ( String ) value ; return Integer . parseInt ( s ) ; } if ( value == null ) { return defaultValue ; } throw createException ( "Expected integer:" ) ;


signature:
public class JSONResult { /** * Return a double number for current JSON value , parsing string values as required . */
public Double getDouble ( Double defaultValue ) { } }

implementation: if ( value instanceof Number ) { return ( ( Number ) value ) . doubleValue ( ) ; } if ( value instanceof String ) { String s = ( String ) value ; return Double . parseDouble ( s ) ; } if ( value == null ) { return defaultValue ; } throw createException ( "Expected number:" ) ;


signature:
public class JSONResult { /** * Return string value for current JSON value */
public String getString ( String defaultValue ) { } }

implementation: if ( value instanceof String || value instanceof Number ) { return value . toString ( ) ; } if ( value == null ) { return null ; } if ( value instanceof JSONArray ) { return ( ( JSONArray ) value ) . toJSONString ( ) ; } if ( value instanceof JSONObject ) { return ( ( JSONObject ) value ) . toJSONString ( ) ; } if ( value == null ) { return defaultValue ; } throw createException ( "Expected string:" ) ;


signature:
public class CommandResource { /** * creates a new Resource .
 * @ param provider the Provider of the Resource
 * @ param command the resource
 * @ param capabilities the capabilities of the player
 * @ param context used for logging
 * @ return the commandResource if nothing illegal was passed */
public static Optional < CommandResource > createCommandResource ( Identification provider , String command , Capabilities capabilities , Context context ) { } }

implementation: CommandResource commandResource = new CommandResource ( provider , command , capabilities ) ; if ( ! verifyCommand ( command ) ) { context . getLogger ( ) . error ( "IllegalCommand!" ) ; return Optional . empty ( ) ; } if ( ! verifyCapabilities ( command , capabilities ) ) { context . getLogger ( ) . error ( "Player is not able to handle Command!" ) ; return Optional . empty ( ) ; } return Optional . of ( commandResource ) ;


signature:
public class CommandResource { /** * verifies that an command is not malformed
 * @ param command the Command
 * @ return false if malformed */
public static boolean verifyCommand ( String command ) { } }

implementation: return command . equals ( PLAY ) || command . equals ( PAUSE ) || command . equals ( STOP ) || command . equals ( SELECT_TRACK ) || command . equals ( NEXT ) || command . equals ( PREVIOUS ) || command . equals ( CHANGE_PLAYBACK ) || command . equals ( CHANGE_VOLUME ) ;


signature:
public class CommandResource { /** * verifies that the player is capable of handling the command
 * @ param command the command
 * @ param capabilities the capabilities
 * @ return true if capable , false if not */
public static boolean verifyCapabilities ( String command , Capabilities capabilities ) { } }

implementation: switch ( command ) { case PLAY : return capabilities . hasPlayPauseControl ( ) ; case PAUSE : return capabilities . hasPlayPauseControl ( ) ; case SELECT_TRACK : return capabilities . isAbleToSelectTrack ( ) ; case NEXT : return capabilities . hasNextPrevious ( ) ; case PREVIOUS : return capabilities . hasNextPrevious ( ) ; case JUMP : return capabilities . isAbleToJump ( ) ; case CHANGE_PLAYBACK : return capabilities . isPlaybackChangeable ( ) ; case CHANGE_VOLUME : return capabilities . canChangeVolume ( ) ; case STOP : return true ; } return false ;


signature:
public class CommandResource { /** * verifies tha the command is legal and able to be executed
 * @ param command the command
 * @ param capabilities the capabilities
 * @ return true if able , false if not */
public static boolean verify ( String command , Capabilities capabilities ) { } }

implementation: return verifyCommand ( command ) && verifyCapabilities ( command , capabilities ) ;


signature:
public class SessionManager { /** * Create a { @ link Cluster } instance .
 * @ param ci
 * @ return
 * @ since 0.4.0 */
protected Cluster createCluster ( ClusterIdentifier ci ) { } }

implementation: return CqlUtils . newCluster ( ci . hostsAndPorts , ci . username , ci . password , getConfiguration ( ) ) ;


signature:
public class SessionManager { /** * Create a { @ link Session } instance .
 * @ param cluster
 * @ param keyspace
 * @ return */
protected Session createSession ( Cluster cluster , String keyspace ) { } }

implementation: return CqlUtils . newSession ( cluster , keyspace ) ;


signature:
public class SessionManager { /** * Obtain a Cassandra cluster instance .
 * @ param key
 * @ return
 * @ since 0.4.0 */
synchronized protected Cluster getCluster ( ClusterIdentifier key ) { } }

implementation: Cluster cluster ; try { cluster = clusterCache . get ( key ) ; if ( cluster . isClosed ( ) ) { LOGGER . info ( "Cluster [" + cluster + "] was closed, obtaining a new one..." ) ; clusterCache . invalidate ( key ) ; cluster = clusterCache . get ( key ) ; } } catch ( ExecutionException e ) { Throwable t = e . getCause ( ) ; throw t instanceof RuntimeException ? ( RuntimeException ) t : new RuntimeException ( t ) ; } return cluster ;


signature:
public class SessionManager { /** * Obtain a Cassandra 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
 * @ return */
public Cluster getCluster ( String hostsAndPorts , String username , String password ) { } }

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


signature:
public class SessionManager { /** * Obtain a Cassandra session instance .
 * The existing session instance will be returned if such existed .
 * @ param hostsAndPorts
 * @ param username
 * @ param password
 * @ param keyspace
 * @ return
 * @ throws NoHostAvailableException
 * @ throws AuthenticationException */
public Session getSession ( String hostsAndPorts , String username , String password , String keyspace ) { } }

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


signature:
public class SessionManager { /** * Obtain a Cassandra session instance .
 * @ param si
 * @ param forceNew
 * @ return */
synchronized protected Session getSession ( SessionIdentifier si , boolean forceNew ) { } }

implementation:
/* * Since 0.2.6 : refresh cluster cache before obtaining the session to
 * avoid exception
 * " You may have used a PreparedStatement that was created with another Cluster instance " */
Cluster cluster = getCluster ( si ) ; if ( cluster == null ) { return null ; } try { LoadingCache < SessionIdentifier , Session > cacheSessions = sessionCache . get ( si ) ; Session existingSession = cacheSessions . getIfPresent ( si ) ; if ( existingSession != null && existingSession . isClosed ( ) ) { LOGGER . info ( "Session [" + existingSession + "] was closed, obtaining a new one..." ) ; cacheSessions . invalidate ( si ) ; return cacheSessions . get ( si ) ; } if ( forceNew ) { if ( existingSession != null ) { cacheSessions . invalidate ( si ) ; } return cacheSessions . get ( si ) ; } return existingSession != null ? existingSession : cacheSessions . get ( si ) ; } catch ( ExecutionException e ) { Throwable t = e . getCause ( ) ; throw t instanceof RuntimeException ? ( RuntimeException ) t : new RuntimeException ( t ) ; }


signature:
public class SessionManager { /** * Obtain a Cassandra session instance .
 * @ param hostsAndPorts
 * @ param username
 * @ param password
 * @ param keyspace
 * @ param forceNew
 * force create new session instance ( the existing one , if any ,
 * will be closed )
 * @ return
 * @ throws NoHostAvailableException
 * @ throws AuthenticationException
 * @ since 0.2.2 */
public Session getSession ( String hostsAndPorts , String username , String password , String keyspace , boolean forceNew ) { } }

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


signature:
public class SessionManager { /** * Bind values to a { @ link PreparedStatement } .
 * @ param stm
 * @ param values
 * @ return
 * @ since 0.4.0 */
public BoundStatement bindValues ( PreparedStatement stm , Object ... values ) { } }

implementation: return CqlUtils . bindValues ( stm , values ) ;


signature:
public class SessionManager { /** * Bind values to a { @ link PreparedStatement } .
 * @ param stm
 * @ param values
 * @ return
 * @ since 0.4.0 */
public BoundStatement bindValues ( PreparedStatement stm , Map < String , Object > values ) { } }


signature:
public class SessionManager { /** * Execute a SELECT query and returns the { @ link ResultSet } .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param cql
 * @ param bindValues
 * @ return
 * @ since 0.4.0 */
public ResultSet execute ( String cql , Object ... bindValues ) { } }

implementation: return CqlUtils . execute ( getSession ( ) , cql , bindValues ) ;


signature:
public class SessionManager { /** * Execute a SELECT query and returns the { @ link ResultSet } .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param stm
 * @ param bindValues
 * @ return
 * @ since 0.4.0 */
public ResultSet execute ( PreparedStatement stm , Map < String , Object > bindValues ) { } }

implementation: return CqlUtils . execute ( getSession ( ) , stm , bindValues ) ;


signature:
public class SessionManager { /** * Execute a SELECT query and returns the { @ link ResultSet } .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param stm
 * @ param consistencyLevel
 * @ return
 * @ since 0.4.0.2 */
public ResultSet execute ( Statement stm , ConsistencyLevel consistencyLevel ) { } }

implementation: if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } return getSession ( ) . execute ( stm ) ;


signature:
public class SessionManager { /** * Execute a SELECT query and returns just one row .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param cql
 * @ param consistencyLevel
 * @ param bindValues
 * @ return
 * @ since 0.4.0 */
public Row executeOne ( String cql , ConsistencyLevel consistencyLevel , Map < String , Object > bindValues ) { } }

implementation: return CqlUtils . executeOne ( getSession ( ) , cql , consistencyLevel , bindValues ) ;


signature:
public class SessionManager { /** * Execute a SELECT query and returns just one row .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param stm
 * @ param bindValues
 * @ return
 * @ since 0.4.0 */
public Row executeOne ( PreparedStatement stm , Object ... bindValues ) { } }

implementation: return CqlUtils . executeOne ( getSession ( ) , stm , bindValues ) ;


signature:
public class SessionManager { /** * Execute a SELECT query and returns just one row .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param stm
 * @ param consistencyLevel
 * @ return
 * @ since 0.4.0.2 */
public Row executeOne ( Statement stm , ConsistencyLevel consistencyLevel ) { } }

implementation: if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } return getSession ( ) . execute ( stm ) . one ( ) ;


signature: public class SessionManager { private FutureCallback < ResultSet > wrapCallbackResultSet ( FutureCallback < ResultSet > callback ) { } }

implementation: return new FutureCallback < ResultSet > ( ) { @ Override public void onSuccess ( ResultSet result ) { try { callback . onSuccess ( result ) ; } finally { asyncSemaphore . release ( ) ; } } @ Override public void onFailure ( Throwable t ) { try { callback . onFailure ( t ) ; } finally { asyncSemaphore . release ( ) ; } } } ;


signature:
public class SessionManager { /** * Async - execute a query .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param callback
 * { @ link ExceedMaxAsyncJobsException } will be passed to
 * { @ link FutureCallback # onFailure ( Throwable ) } if number of async - jobs exceeds
 * { @ link # getMaxAsyncJobs ( ) } .
 * @ param stm
 * @ since 0.4.0.2
 * @ throws ExceedMaxAsyncJobsException
 * If number of running jobs exceeds a threshold < i > and < / i > { @ code callback } is
 * { @ code null } . */
public void executeAsync ( FutureCallback < ResultSet > callback , Statement stm ) throws ExceedMaxAsyncJobsException { } }

implementation: executeAsync ( callback , stm , null ) ;


signature:
public class SessionManager { /** * Async - execute a query .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param callback
 * { @ link ExceedMaxAsyncJobsException } will be passed to
 * { @ link FutureCallback # onFailure ( Throwable ) } if number of async - jobs exceeds
 * { @ link # getMaxAsyncJobs ( ) } .
 * @ param stm
 * @ param consistencyLevel
 * @ since 0.4.0.2
 * @ throws ExceedMaxAsyncJobsException
 * If number of running jobs exceeds a threshold < i > and < / i > { @ code callback } is
 * { @ code null } . */
public void executeAsync ( FutureCallback < ResultSet > callback , Statement stm , ConsistencyLevel consistencyLevel ) throws ExceedMaxAsyncJobsException { } }

implementation: if ( ! asyncSemaphore . tryAcquire ( ) ) { if ( callback == null ) { throw new ExceedMaxAsyncJobsException ( maxSyncJobs ) ; } else { callback . onFailure ( new ExceedMaxAsyncJobsException ( maxSyncJobs ) ) ; } } else { try { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } ResultSetFuture rsf = CqlUtils . executeAsync ( getSession ( ) , stm ) ; if ( callback != null ) { Futures . addCallback ( rsf , wrapCallbackResultSet ( callback ) , asyncExecutor ) ; } } catch ( Exception e ) { asyncSemaphore . release ( ) ; LOGGER . error ( e . getMessage ( ) , e ) ; } }


signature: public class SessionManager { private FutureCallback < ResultSet > wrapCallbackRow ( FutureCallback < Row > callback ) { } }

implementation: return new FutureCallback < ResultSet > ( ) { @ Override public void onSuccess ( ResultSet result ) { try { callback . onSuccess ( result . one ( ) ) ; } finally { asyncSemaphore . release ( ) ; } } @ Override public void onFailure ( Throwable t ) { try { callback . onFailure ( t ) ; } finally { asyncSemaphore . release ( ) ; } } } ;


signature:
public class SessionManager { /** * Async - execute a query .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param callback
 * { @ link ExceedMaxAsyncJobsException } will be passed to
 * { @ link FutureCallback # onFailure ( Throwable ) } if number of async - jobs exceeds
 * { @ link # getMaxAsyncJobs ( ) } .
 * @ param stm
 * @ throws ExceedMaxAsyncJobsException
 * If number of running jobs exceeds a threshold < i > and < / i > { @ code callback } is
 * { @ code null } .
 * @ since 0.4.0.2 */
public void executeOneAsync ( FutureCallback < Row > callback , Statement stm ) throws ExceedMaxAsyncJobsException { } }

implementation: executeOneAsync ( callback , stm , null ) ;


signature:
public class SessionManager { /** * Execute a batch statement .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param consistencyLevel
 * @ param statements
 * @ return
 * @ since 0.4.0 */
public ResultSet executeBatch ( ConsistencyLevel consistencyLevel , Statement ... statements ) { } }

implementation: return CqlUtils . executeBatch ( getSession ( ) , consistencyLevel , statements ) ;


signature:
public class SessionManager { /** * Execute a batch statement .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param batchType
 * @ param statements
 * @ return
 * @ since 0.4.0 */
public ResultSet executeBatch ( BatchStatement . Type batchType , Statement ... statements ) { } }

implementation: return CqlUtils . executeBatch ( getSession ( ) , batchType , statements ) ;


signature:
public class SessionManager { /** * Async - execute a batch statement .
 * The default session ( obtained via { @ link # getSession ( ) } is used to execute the query .
 * @ param callback
 * { @ link ExceedMaxAsyncJobsException } will be passed to
 * { @ link FutureCallback # onFailure ( Throwable ) } if number of async - jobs exceeds
 * { @ link # getMaxAsyncJobs ( ) } .
 * @ param statements
 * @ throws ExceedMaxAsyncJobsException
 * If number of running jobs exceeds a threshold < i > and < / i > { @ code callback } is
 * { @ code null } .
 * @ since 0.4.0 */
public void executeBatchAsync ( FutureCallback < ResultSet > callback , Statement ... statements ) throws ExceedMaxAsyncJobsException { } }

implementation: if ( ! asyncSemaphore . tryAcquire ( ) ) { if ( callback == null ) { throw new ExceedMaxAsyncJobsException ( maxSyncJobs ) ; } else { callback . onFailure ( new ExceedMaxAsyncJobsException ( maxSyncJobs ) ) ; } } else { try { ResultSetFuture rsf = CqlUtils . executeBatchAsync ( getSession ( ) , statements ) ; if ( callback != null ) { Futures . addCallback ( rsf , wrapCallbackResultSet ( callback ) , asyncExecutor ) ; } } catch ( Exception e ) { asyncSemaphore . release ( ) ; LOGGER . error ( e . getMessage ( ) , e ) ; } }


signature:
public class CF { /** * Sets a jar filter .
 * @ param jarFilter new filter , use null or empty list to not filter . The list will be copied locally .
 * @ return self to allow for chaining */
public CF setJarFilter ( List < String > jarFilter ) { } }

implementation: this . locator . setJarFilter ( jarFilter ) ; this . needsReRun = true ; return this ;


signature:
public class CF { /** * Returns all subclasses found for the given class .
 * @ param clazz class to search for
 * @ return all found subclasses */
public Set < Class < ? > > getSubclasses ( Class < ? > clazz ) { } }

implementation: Set < Class < ? > > ret = new HashSet < Class < ? > > ( ) ; Set < Class < ? > > w = null ; if ( clazz != null ) { this . clear ( ) ; Map < URI , String > locations = this . locator . getCfLocations ( ) ; for ( Entry < URI , String > entry : locations . entrySet ( ) ) { try { w = search ( clazz , entry . getKey ( ) , locations . get ( entry . getKey ( ) ) ) ; if ( w != null && ( w . size ( ) > 0 ) ) { ret . addAll ( w ) ; } } catch ( MalformedURLException ex ) { } } } return ret ;


signature:
public class CF { /** * Returns all subclasses found for the given fully qualified class name .
 * @ param fqcn fully qualified class name , e . g . package and class name
 * @ return all found subclasses */
public Set < Class < ? > > getSubclasses ( String fqcn ) { } }

implementation: if ( fqcn == null ) { return new HashSet < Class < ? > > ( ) ; } else if ( StringUtils . startsWith ( fqcn , "." ) || StringUtils . endsWith ( fqcn , "." ) ) { return new HashSet < Class < ? > > ( ) ; } Class < ? > clazz = null ; try { clazz = Class . forName ( fqcn ) ; } catch ( ClassNotFoundException ex ) { this . clear ( ) ; this . errors . add ( ex ) ; return new HashSet < Class < ? > > ( ) ; } return getSubclasses ( clazz ) ;


signature:
public class CF { /** * Returns all known subclasses for a given class , location and package name
 * @ param clazz class to search for
 * @ param location a URL to look into
 * @ param packageName a package name
 * @ return all found subclasses in location , empty set of none found
 * @ throws MalformedURLException */
private final Set < Class < ? > > search ( Class < ? > clazz , URI location , String packageName ) throws MalformedURLException { } }

implementation: if ( clazz == null || location == null ) { return new HashSet < Class < ? > > ( ) ; } File directory = new File ( location . toURL ( ) . getFile ( ) ) ; if ( directory . exists ( ) ) { return this . searchDirectory ( clazz , directory , location , packageName ) . keySet ( ) ; } else { return this . searchJar ( clazz , location ) . keySet ( ) ; }


signature:
public class CF { /** * Returns all known subclasses found in a given directory .
 * @ param clazz class name to look for
 * @ param directory search directory
 * @ param location a URI location for return map
 * @ param packageName a package name to test against class name
 * @ return a map with found classes , empty if none found */
protected final Map < Class < ? > , URI > searchDirectory ( Class < ? > clazz , File directory , URI location , String packageName ) { } }

implementation: Map < Class < ? > , URI > ret = new HashMap < > ( ) ; String [ ] files = directory . list ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( files [ i ] . endsWith ( ".class" ) ) { String classname = files [ i ] . substring ( 0 , files [ i ] . length ( ) - 6 ) ; try { Class < ? > c = Class . forName ( packageName + "." + classname ) ; if ( clazz . isAssignableFrom ( c ) && ! clazz . getName ( ) . equals ( packageName + "." + classname ) ) { ret . put ( c , location ) ; } } catch ( Exception ex ) { errors . add ( ex ) ; } } } return ret ;


signature:
public class CF { /** * Returns all known subclasses found in a given location
 * @ param clazz class name to look for
 * @ param location a URI location for return map
 * @ return a map with found classes , empty if none found */
protected final Map < Class < ? > , URI > searchJar ( Class < ? > clazz , URI location ) { } }

implementation: Map < Class < ? > , URI > ret = new HashMap < > ( ) ; try { JarURLConnection conn = ( JarURLConnection ) location . toURL ( ) . openConnection ( ) ; JarFile jarFile = conn . getJarFile ( ) ; for ( Enumeration < JarEntry > e = jarFile . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry entry = e . nextElement ( ) ; String entryname = entry . getName ( ) ; if ( this . processed . contains ( entryname ) ) { continue ; } this . processed . add ( entryname ) ; if ( ! entry . isDirectory ( ) && entryname . endsWith ( ".class" ) ) { String classname = entryname . substring ( 0 , entryname . length ( ) - 6 ) ; if ( classname . startsWith ( "/" ) ) { classname = classname . substring ( 1 ) ; } classname = classname . replace ( '/' , '.' ) ; if ( ! StringUtils . startsWithAny ( classname , this . excludedNames ) ) { try { Class < ? > c = Class . forName ( classname ) ; if ( clazz . isAssignableFrom ( c ) && ! clazz . getName ( ) . equals ( classname ) ) { ret . put ( c , location ) ; } } catch ( Exception exception ) { errors . add ( exception ) ; } catch ( Error error ) { errors . add ( error ) ; } } } } } catch ( IOException ignore ) { errors . add ( ignore ) ; } return ret ;


signature:
public class Resource { /** * sets the Resource data .
 * Note ! this Object is immutable !
 * @ param resource the data to set
 * @ return the Resource */
public Resource < T > setResource ( T resource ) { } }

implementation: return new Resource < > ( resourceID , provider , resource , consumer ) ;


signature:
public class Resource { /** * sets who should or has provided the Resource Object .
 * Note ! this Object is immutable !
 * @ param provider an Identification describing the provider of the Resource
 * @ return the Resource */
public Resource < T > setProvider ( Identification provider ) { } }


signature:
public class Resource { /** * sets who should or has consumed the Resource Object .
 * Note ! this Object is immutable !
 * @ param consumer an Identification describing the consumer of the Resource
 * @ return new Resource */
public Resource < T > setConsumer ( Identification consumer ) { } }


signature:
public class Resource { /** * creates a list with this Element in it .
 * @ return a list */
public List < Resource > toList ( ) { } }

implementation: List < Resource > resourceList = new ArrayList < > ( ) ; resourceList . add ( this ) ; return resourceList ;


signature:
public class HashMap3 { /** * Returns the accumulated size of all the bottom level maps . */
public int size ( ) { } }

implementation:
int result = 0 ; // sum over all inner maps
for ( Iterator < K1 > keys1 = maps . keySet ( ) . iterator ( ) ; keys1 . hasNext ( ) ; ) { Map2 < K2 , K3 , V > inner_map = maps . get ( keys1 . next ( ) ) ; result += inner_map . size ( ) ; } return result ;


signature:
public class ContentGenerator { /** * this method is called to register for what Events it wants to provide Resources .
 * The Event has to be in the following format : It should contain only one Descriptor and and one Resource with the
 * ID " description " , which contains an description of the Event .
 * @ return a List containing ID ' s for the Events */
@ Override public List < ? extends EventModel < ? > > announceEvents ( ) { } }

implementation: return getTriggeredEvents ( ) . stream ( ) . map ( EventListener :: getEvent ) . collect ( Collectors . toList ( ) ) ;


signature:
public class ContentGenerator { /** * this method is called when an object wants to get a Resource .
 * Don ' t use the Resources provided as arguments , they are just the requests .
 * There is a timeout after 1 second .
 * @ param list a list of resources without data
 * @ param optional if an event caused the action , it gets passed . It can also be null .
 * @ return a list of resources with data */
@ Override public List < ResourceModel > provideResource ( List < ? extends ResourceModel > list , Optional < EventModel > optional ) { } }

implementation:
// TODO : check arguments and return type here ! Missing ID etc . Fail fast !
return new ArrayList < > ( triggered ( list , optional ) ) ;


signature:
public class PacketCollector { /** * Returns the next available packet . The method call will block ( not
 * return ) until a packet is available or the < tt > timeout < / tt > has elapased .
 * If the timeout elapses without a result , < tt > null < / tt > will be returned .
 * @ param timeout
 * the amount of time to wait for the next packet ( in
 * milleseconds ) .
 * @ return the next available packet . */
public Packet nextResult ( long timeout ) { } }

implementation: try { return resultQueue . poll ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; }


signature:
public class PacketCollector { /** * Processes a packet to see if it meets the criteria for this packet
 * collector . If so , the packet is added to the result queue .
 * @ param packet
 * the packet to process . */
protected void processPacket ( Packet packet ) { } }

implementation:
if ( packet == null ) { return ; } if ( packetFilter == null || packetFilter . accept ( packet ) ) { while ( ! resultQueue . offer ( packet ) ) { // Since we know the queue is full , this poll should never
// actually block .
resultQueue . poll ( ) ; } }


signature:
public class SynchronizedFilterableSet { /** * 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 < E > FilterableSet < E > decorate ( FilterableSet < E > set ) { } }

implementation: return new SynchronizedFilterableSet < E > ( set ) ;


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

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


signature:
public class XMPPUtils { /** * Logs the error and returns an IQ error response
 * @ param iq
 * @ param errorMessage
 * @ param logger
 * @ return */
public static IQ error ( IQ iq , String errorMessage , Logger logger ) { } }

implementation: logger . error ( errorMessage ) ; return error ( iq , errorMessage ) ;


signature:
public class XMPPUtils { /** * Logs the error and returns an IQ error response
 * @ param iq
 * @ param errorMessage
 * @ param logger
 * @ return */
public static IQ error ( IQ iq , String errorMessage ) { } }

implementation: return XMPPUtils . createErrorResponse ( iq , errorMessage , Condition . bad_request , Type . modify ) ;


signature:
public class XMPPUtils { /** * Logs the RSM page not found error and returns an IQ error response
 * @ param iq
 * @ param errorMessage
 * @ param logger
 * @ return */
public static IQ errorRSM ( IQ iq , Logger logger ) { } }

implementation: String rsmMessage = "RSM: Page Not Found" ; logger . error ( rsmMessage + " " + iq ) ; return XMPPUtils . createErrorResponse ( iq , rsmMessage , Condition . item_not_found , Type . cancel ) ;


signature:
public class XMPPUtils { /** * Creates an error response for a given IQ request .
 * @ param request
 * @ param message
 * @ param condition
 * @ param type
 * @ return */
public static IQ createErrorResponse ( final IQ request , final String message , Condition condition , Type type ) { } }

implementation: final IQ result = request . createCopy ( ) ; result . setID ( request . getID ( ) ) ; result . setFrom ( request . getTo ( ) ) ; result . setTo ( request . getFrom ( ) ) ; PacketError e = new PacketError ( condition , type ) ; if ( message != null ) { e . setText ( message ) ; } result . setError ( e ) ; return result ;


signature:
public class SelectorResource { /** * returns true if the identifiable is the target of the EventModel
 * @ param eventModel the EventModel to check
 * @ param identifiable the identifiable to check against
 * @ return maybe true if found */
public static Optional < Boolean > isTarget ( EventModel eventModel , Identifiable identifiable ) { } }

implementation: if ( eventModel . getListResourceContainer ( ) . providesResource ( Collections . singletonList ( SelectorResource . RESOURCE_ID ) ) ) { return Optional . of ( eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( resource -> resource instanceof Identification ) . map ( object -> ( Identification ) object ) . anyMatch ( identifiable :: isOwner ) ) ; } else { return Optional . empty ( ) ; }


signature:
public class SynchronizedSortedMap { /** * 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 > SortedMap < K , V > decorate ( SortedMap < K , V > map ) { } }

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


signature: public class SynchronizedSortedMap { public Comparator < ? super K > comparator ( ) { } }

implementation: return SyncUtils . synchronizeRead ( lock , new Callback < Comparator < ? super K > > ( ) { @ Override protected void doAction ( ) { _return ( getSortedMap ( ) . comparator ( ) ) ; } } ) ;


signature:
public class User { /** * TODO : Unit test */
public boolean allowImpersonate ( Subject impersSubject ) { } }

implementation: String impersonators = ( String ) getProperty ( IMPERSONATORS_FIELD ) ; if ( impersonators == null ) { return false ; } Set < String > impersonatorSet = ImmutableSet . copyOf ( StringUtils . split ( impersonators , ';' ) ) ; for ( Principal p : impersSubject . getPrincipals ( ) ) { if ( ADMIN_USER . equals ( p . getName ( ) ) || SYSTEM_USER . equals ( p . getName ( ) ) || impersonatorSet . contains ( p . getName ( ) ) ) { return true ; } } return false ;


signature:
public class User { /** * Sets the login enabled time
 * @ param from
 * UTC ms time after which user login is enabled . < 0 means no
 * start time .
 * @ param to
 * UTC ms time before which the user login is enabled , < 0 means
 * no end time .
 * @ param day
 * true if the time represents a day rather than a time
 * @ param timeZone
 * the timezone which both these times should be interpreted in
 * ( relevant for a day setting ) .
 * @ since 1.4 */
public void setLoginEnabled ( long from , long to , boolean day , TimeZone timeZone ) { } }

implementation: String enabledSetting = EnabledPeriod . getEnableValue ( from , to , day , timeZone ) ; if ( enabledSetting == null ) { removeProperty ( LOGIN_ENABLED_PERIOD_FIELD ) ; } else { setProperty ( LOGIN_ENABLED_PERIOD_FIELD , enabledSetting ) ; }


signature:
public class IQTypeFilter { /** * ( non - Javadoc )
 * @ see
 * org . jivesoftware . smack . filter . PacketFilter # accept ( org . jivesoftware . smack
 * . packet . Packet ) */
public boolean accept ( Packet packet ) { } }

implementation: return ( packet instanceof IQ && ( ( IQ ) packet ) . getType ( ) . equals ( type ) ) ;


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

implementation: return new SynchronizedSet < E > ( set ) ;


signature:
public class RosterEntry { /** * Sets the name associated with this entry .
 * @ param name
 * the name . */
public void setName ( String name ) { } }

implementation:
// Do nothing if the name hasn ' t changed .
if ( name != null && name . equals ( this . name ) ) { return ; } this . name = name ; Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; packet . addItem ( new JID ( user ) , name , ask , subscription , getGroupNames ( ) ) ; connection . sendPacket ( packet ) ;


signature:
public class RosterEntry { /** * Updates the state of the entry with the new values .
 * @ param name
 * the nickname for the entry .
 * @ param type
 * the subscription type .
 * @ param status
 * the subscription status ( related to subscriptions pending to
 * be approbed ) . */
void updateState ( String name , Subscription type , Ask status ) { } }

implementation: this . name = name ; this . subscription = type ; this . ask = status ;


signature:
public class RosterEntry { /** * Returns an unmodifiable collection of the roster groups that this entry
 * belongs to .
 * @ return an iterator for the groups this entry belongs to . */
public Collection < RosterGroup > getGroups ( ) { } }

implementation:
List < RosterGroup > results = new ArrayList < RosterGroup > ( ) ; // Loop through all roster groups and find the ones that contain this
// entry . This algorithm should be fine
for ( RosterGroup group : roster . getGroups ( ) ) { if ( group . contains ( this ) ) { results . add ( group ) ; } } return Collections . unmodifiableCollection ( results ) ;


signature:
public class RosterEntry { /** * Indicates whether some other object is " equal to " this by comparing all
 * members .
 * The { @ link # equals ( Object ) } method returns < code > true < / code > if the user
 * JIDs are equal .
 * @ param obj
 * the reference object with which to compare .
 * @ return < code > true < / code > if this object is the same as the obj argument ;
 * < code > false < / code > otherwise . */
public boolean equalsDeep ( Object obj ) { } }

implementation: if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; RosterEntry other = ( RosterEntry ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( ask == null ) { if ( other . ask != null ) return false ; } else if ( ! ask . equals ( other . ask ) ) return false ; if ( subscription == null ) { if ( other . subscription != null ) return false ; } else if ( ! subscription . equals ( other . subscription ) ) return false ; if ( user == null ) { if ( other . user != null ) return false ; } else if ( ! user . equals ( other . user ) ) return false ; return true ;


signature:
public class CacheImpl { /** * { @ inheritDoc }
 * @ see org . sakaiproject . nakamura . api . memory . Cache # get ( java . lang . String ) */
public V get ( String key ) { } }

implementation: Element e = cache . get ( key ) ; if ( e == null ) { return stats ( null ) ; } return stats ( e . getObjectValue ( ) ) ;


signature:
public class CacheImpl { /** * { @ inherit - doc }
 * @ see org . sakaiproject . nakamura . api . memory . Cache # put ( java . lang . String , java . lang . Object ) */
@ SuppressWarnings ( "unchecked" ) public V put ( String key , V payload ) { } }

implementation: V previous = null ; if ( cache . isKeyInCache ( key ) ) { Element e = cache . get ( key ) ; if ( e != null ) { previous = ( V ) e . getObjectValue ( ) ; } } cache . put ( new Element ( key , payload ) ) ; return previous ;


signature:
public class CacheImpl { /** * { @ inheritDoc }
 * @ see org . sakaiproject . nakamura . api . memory . Cache # removeChildren ( java . lang . String ) */
public void removeChildren ( String key ) { } }

implementation: cache . remove ( key ) ; if ( ! key . endsWith ( "/" ) ) { key = key + "/" ; } List < ? > keys = cache . getKeys ( ) ; for ( Object k : keys ) { if ( ( ( String ) k ) . startsWith ( key ) ) { cache . remove ( k ) ; } }


signature:
public class CacheImpl { /** * { @ inheritDoc }
 * @ see org . sakaiproject . nakamura . api . memory . Cache # list ( ) */
@ SuppressWarnings ( "unchecked" ) public List < V > list ( ) { } }

implementation: List < String > keys = cache . getKeys ( ) ; List < V > values = new ArrayList < V > ( ) ; for ( String k : keys ) { Element e = cache . get ( k ) ; if ( e != null ) { values . add ( ( V ) e . getObjectValue ( ) ) ; } } return values ;


signature:
public class RSMUtils { /** * Appends RSM info to query response .
 * @ param queryElement
 * @ param rsm */
public static void appendRSMElement ( Element queryElement , RSM rsm ) { } }

implementation: Element setElement = queryElement . addElement ( "set" , RSM . NAMESPACE ) ; if ( rsm . getFirst ( ) != null ) { Element firstElement = setElement . addElement ( "first" ) ; firstElement . addAttribute ( "index" , rsm . getIndex ( ) . toString ( ) ) ; firstElement . setText ( rsm . getFirst ( ) ) ; } if ( rsm . getLast ( ) != null ) { Element lastElement = setElement . addElement ( "last" ) ; lastElement . setText ( rsm . getLast ( ) ) ; } setElement . addElement ( "count" ) . setText ( String . valueOf ( rsm . getCount ( ) ) ) ;


signature:
public class RSMUtils { /** * Parses an RSM from a query XML element
 * @ param queryElement
 * @ return The parsed RSM object */
public static RSM parseRSM ( Element queryElement ) { } }

implementation: RSM rsm = new RSM ( ) ; Element setElement = queryElement . element ( "set" ) ; if ( setElement == null ) { return rsm ; } Element after = setElement . element ( "after" ) ; if ( after != null ) { rsm . setAfter ( after . getText ( ) ) ; } Element before = setElement . element ( "before" ) ; if ( before != null ) { String beforeText = before . getText ( ) ; rsm . setBefore ( beforeText == null ? "" : beforeText ) ; } Element index = setElement . element ( "index" ) ; if ( index != null ) { rsm . setIndex ( Integer . parseInt ( index . getText ( ) ) ) ; } Element max = setElement . element ( "max" ) ; if ( max != null ) { rsm . setMax ( Integer . parseInt ( max . getText ( ) ) ) ; } return rsm ;


signature:
public class RSMUtils { /** * Filters response objects based on the RSM parameters . Updates the RSM
 * object with item count , first and last jid
 * @ param objects
 * @ param rsm
 * @ return
 * @ throws IllegalArgumentException
 * If the item specified by the requesting entity via the UID in
 * the < after / > or < before / > element does not exist */
public static List < Identifiable > filterRSMResponse ( List < Identifiable > objects , RSM rsm ) throws IllegalArgumentException { } }

implementation: String after = rsm . getAfter ( ) ; String before = rsm . getBefore ( ) ; int initialIndex = rsm . getIndex ( ) ; int lastIndex = objects . size ( ) ; if ( after != null || ( before != null && ! before . isEmpty ( ) ) ) { boolean afterItemFound = false ; boolean beforeItemFound = false ; int i = 0 ; for ( Identifiable object : objects ) { if ( after != null && after . equals ( object . getId ( ) ) ) { initialIndex = i + 1 ; afterItemFound = true ; } if ( before != null && before . equals ( object . getId ( ) ) ) { lastIndex = i ; beforeItemFound = true ; } i ++ ; } if ( after != null && ! afterItemFound ) { throw new IllegalArgumentException ( ) ; } if ( before != null && ! before . isEmpty ( ) && ! beforeItemFound ) { throw new IllegalArgumentException ( ) ; } } if ( rsm . getMax ( ) != null ) { if ( before != null ) { initialIndex = lastIndex - rsm . getMax ( ) ; } else { lastIndex = initialIndex + rsm . getMax ( ) ; } } boolean outOfRange = initialIndex > lastIndex || initialIndex < 0 || lastIndex > objects . size ( ) ; List < Identifiable > filteredList = outOfRange ? new LinkedList < Identifiable > ( ) : objects . subList ( initialIndex , lastIndex ) ; rsm . setCount ( objects . size ( ) ) ; rsm . setIndex ( initialIndex ) ; if ( ! filteredList . isEmpty ( ) ) { rsm . setFirst ( filteredList . get ( 0 ) . getId ( ) ) ; rsm . setLast ( filteredList . get ( filteredList . size ( ) - 1 ) . getId ( ) ) ; } return filteredList ;


signature:
public class ContentEventListener { /** * Handles an event from OSGi and indexes it . The indexing operation should
 * only index metadata and not bodies . Indexing of bodies is performed by a
 * seperate thread .
 * @ see org . osgi . service . event . EventHandler # handleEvent ( org . osgi . service . event . Event ) */
public void handleEvent ( Event event ) { } }

implementation:
String topic = event . getTopic ( ) ; Session session = ( Session ) event . getProperty ( Session . class . getName ( ) ) ; RepositorySession repositoryRession = null ; Thread thisThread = Thread . currentThread ( ) ; ClassLoader classloader = thisThread . getContextClassLoader ( ) ; // ES might load classes so we had better set the context classloader .
try { thisThread . setContextClassLoader ( this . getClass ( ) . getClassLoader ( ) ) ; try { repositoryRession = new RepositorySessionImpl ( session , repository ) ; } catch ( ClientPoolException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } catch ( StorageClientException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } catch ( AccessDeniedException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } LOGGER . debug ( "Got Event {} {} " , event , handlers ) ; Collection < IndexingHandler > contentIndexHandler = handlers . get ( topic ) ; if ( contentIndexHandler != null && contentIndexHandler . size ( ) > 0 ) { BulkRequestBuilder bulk = client . prepareBulk ( ) ; int added = 0 ; for ( IndexingHandler indexingHandler : contentIndexHandler ) { Collection < InputDocument > documents = indexingHandler . getDocuments ( repositoryRession , event ) ; for ( InputDocument in : documents ) { LOGGER . info ( "Indexing {} " , in ) ; if ( in . isDelete ( ) ) { bulk . add ( client . prepareDelete ( in . getIndexName ( ) , in . getDocumentType ( ) , in . getDocumentId ( ) ) ) ; added ++ ; } else { try { IndexRequestBuilder r = client . prepareIndex ( in . getIndexName ( ) , in . getDocumentType ( ) , in . getDocumentId ( ) ) ; XContentBuilder d = XContentFactory . jsonBuilder ( ) ; d = d . startObject ( ) ; for ( Entry < String , Object > e : in . getKeyData ( ) ) { d = d . field ( e . getKey ( ) , e . getValue ( ) ) ; } r . setSource ( d . endObject ( ) ) ; bulk . add ( r ) ; added ++ ; } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } } } } if ( added > 0 ) { BulkResponse resp = bulk . execute ( ) . actionGet ( ) ; if ( resp . hasFailures ( ) ) { for ( BulkItemResponse br : Iterables . adaptTo ( resp . iterator ( ) ) ) { if ( br . failed ( ) ) { LOGGER . error ( "Failed {} {} " , br . getId ( ) , br . getFailureMessage ( ) ) ; // not going to retry at the moment , just log .
} } } } } } finally { if ( repositoryRession != null ) { repositoryRession . logout ( ) ; } thisThread . setContextClassLoader ( classloader ) ; }


signature:
public class LeavingEvent { /** * creates a new LeavingEvent
 * @ param source the caller
 * @ param strict whether the addon can guarantee that the user is around
 * @ param descriptors the descriptors
 * @ return the optional PresenceEvent */
public static Optional < LeavingEvent > createLeavingEvent ( Identification source , boolean strict , List < String > descriptors ) { } }

implementation: try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } descriptors . add ( ID ) ; descriptors . add ( CommonEvents . Descriptors . NOT_INTERRUPT ) ; LeavingEvent stopRequest = new LeavingEvent ( source , descriptors ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class UserRoster { /** * Reloads the entire roster from the server . This is an asynchronous
 * operation , which means the method will return immediately , and the roster
 * will be reloaded at a later point when the server responds to the reload
 * request .
 * @ throws IllegalStateException
 * if connection is not logged in or logged in anonymously */
public void reload ( ) { } }

implementation: if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } Roster packet = new Roster ( ) ; if ( rosterStore != null && connection . isRosterVersioningSupported ( ) ) { packet . getElement ( ) . element ( "query" ) . addAttribute ( "ver" , rosterStore . getRosterVersion ( ) ) ; PacketFilter filter = new PacketIDFilter ( packet . getID ( ) ) ; connection . addPacketListener ( new RosterResultListener ( ) , filter ) ; } connection . sendPacket ( packet ) ;


signature:
public class UserRoster { /** * Creates a new group .
 * Note : you must add at least one entry to the group for the group to be
 * kept after a logout / login . This is due to the way that XMPP stores group
 * information .
 * @ param name
 * the name of the group .
 * @ return a new group .
 * @ throws IllegalStateException
 * if connection is not logged in or logged in anonymously */
public RosterGroup createGroup ( String name ) { } }

implementation: if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } if ( groups . containsKey ( name ) ) { throw new IllegalArgumentException ( "Group with name " + name + " alread exists." ) ; } RosterGroup group = new RosterGroup ( name , connection ) ; groups . put ( name , group ) ; return group ;


signature:
public class UserRoster { /** * Creates a new roster entry and presence subscription . The server will
 * asynchronously update the roster with the subscription status .
 * @ param user
 * the user . ( e . g . johndoe @ jabber . org )
 * @ param name
 * the nickname of the user .
 * @ param groups
 * the list of group names the entry will belong to , or
 * < tt > null < / tt > if the the roster entry won ' t belong to a group .
 * @ throws XMPPException
 * if an XMPP exception occurs .
 * @ throws IllegalStateException
 * if connection is not logged in or logged in anonymously */
public void createEntry ( String user , String name , String [ ] groups ) throws XMPPException { } }

implementation:
if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } // Create and send roster entry creation packet .
Roster rosterPacket = new Roster ( ) ; rosterPacket . setType ( IQ . Type . set ) ; rosterPacket . addItem ( new JID ( user ) , name , null , null , Arrays . asList ( groups ) ) ; // Wait up to a certain number of seconds for a reply from the server .
PacketCollector collector = connection . createPacketCollector ( new PacketIDFilter ( rosterPacket . getID ( ) ) ) ; connection . sendPacket ( rosterPacket ) ; IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( "No response from the server." ) ; } // If the server replied with an error , throw an exception .
else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; } // Create a presence subscription packet and send .
Presence presencePacket = new Presence ( Presence . Type . subscribe ) ; presencePacket . setTo ( user ) ; connection . sendPacket ( presencePacket ) ;


signature:
public class UserRoster { /** * Removes a roster entry from the roster . The roster entry will also be
 * removed from the unfiled entries or from any roster group where it could
 * belong and will no longer be part of the roster . Note that this is an
 * asynchronous call - - Smack must wait for the server to send an updated
 * subscription status .
 * @ param entry
 * a roster entry .
 * @ throws XMPPException
 * if an XMPP error occurs .
 * @ throws IllegalStateException
 * if connection is not logged in or logged in anonymously */
public void removeEntry ( RosterEntry entry ) throws XMPPException { } }

implementation:
if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( "Not logged in to server." ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( "Anonymous users can't have a roster." ) ; } // Only remove the entry if it ' s in the entry list .
// The actual removal logic takes place in
// RosterPacketListenerprocess > > Packet ( Packet )
if ( ! entries . containsKey ( entry . getUser ( ) ) ) { return ; } Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; packet . addItem ( new JID ( entry . getUser ( ) ) , entry . getName ( ) , entry . getAsk ( ) , Subscription . remove , entry . getGroupNames ( ) ) ; PacketCollector collector = connection . createPacketCollector ( new PacketIDFilter ( packet . getID ( ) ) ) ; connection . sendPacket ( packet ) ; IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( "No response from the server." ) ; } // If the server replied with an error , throw an exception .
else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; }


signature:
public class UserRoster { /** * Returns an unmodifiable collection of all entries in the roster ,
 * including entries that don ' t belong to any groups .
 * @ return all entries in the roster . */
public Collection < RosterEntry > getEntries ( ) { } }

implementation:
Set < RosterEntry > allEntries = new HashSet < RosterEntry > ( ) ; // Loop through all roster groups and add their entries to the answer
for ( RosterGroup rosterGroup : getGroups ( ) ) { allEntries . addAll ( rosterGroup . getEntries ( ) ) ; } // Add the roster unfiled entries to the answer
allEntries . addAll ( unfiledEntries ) ; return Collections . unmodifiableCollection ( allEntries ) ;


signature:
public class UserRoster { /** * Returns the roster entry associated with the given XMPP address or
 * < tt > null < / tt > if the user is not an entry in the roster .
 * @ param user
 * the XMPP address of the user ( eg " jsmith @ example . com " ) . The
 * address could be in any valid format ( e . g . " domain / resource " ,
 * " user @ domain " or " user @ domain / resource " ) .
 * @ return the roster entry or < tt > null < / tt > if it does not exist . */
public RosterEntry getEntry ( String user ) { } }

implementation: if ( user == null ) { return null ; } return entries . get ( user . toLowerCase ( ) ) ;