signature:
public class TransactionalHashMap { /** * Copies all of the mappings from the specified map to this map
 * These mappings will replace any mappings that
 * this map had for any of the keys currently in the specified map .
 * @ param m mappings to be stored in this map .
 * @ throws NullPointerException if the specified map is null . */
@ Override public void putAll ( Map < ? extends K , ? extends V > m ) { } }

implementation:
int numKeysToBeAdded = m . size ( ) ; if ( numKeysToBeAdded == 0 ) return ; /* * Expand the map if the map if the number of mappings to be added
 * is greater than or equal to threshold . This is conservative ; the
 * obvious condition is ( m . size ( ) + size ) > = threshold , but this
 * condition could result in a map with twice the appropriate capacity ,
 * if the keys to be added overlap with the keys already in this map .
 * By using the conservative calculation , we subject ourself
 * to at most one extra resize . */
if ( numKeysToBeAdded > threshold ) { int targetCapacity = ( int ) ( numKeysToBeAdded / loadFactor + 1 ) ; if ( targetCapacity > MAXIMUM_CAPACITY ) targetCapacity = MAXIMUM_CAPACITY ; int newCapacity = table . length ; while ( newCapacity < targetCapacity ) newCapacity <<= 1 ; if ( newCapacity > table . length ) resize ( newCapacity ) ; } for ( Iterator < ? extends Map . Entry < ? extends K , ? extends V > > i = m . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < ? extends K , ? extends V > e = i . next ( ) ; put ( e . getKey ( ) , e . getValue ( ) ) ; }


signature:
public class TransactionalHashMap { /** * Removes the mapping for this key from this map if present .
 * @ param key key whose mapping is to be removed from the map .
 * @ return previous value associated with specified key , or < tt > null < / tt >
 * if there was no mapping for key . A < tt > null < / tt > return can
 * also indicate that the map previously associated < tt > null < / tt >
 * with the specified key . */
@ Override public V remove ( Object key ) throws ConcurrentModificationException { } }

implementation: Entry < K , V > e = removeEntryForKey ( key ) ; return ( e == null ? null : e . value ) ;


signature:
public class TransactionalHashMap { /** * Removes and returns the entry associated with the specified key
 * in the HashMap . Returns null if the HashMap contains no mapping
 * for this key . */
Entry < K , V > removeEntryForKey ( Object key ) throws ConcurrentModificationException { } }

implementation: Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) { if ( e . is ( Entry . DELETED , null ) && ! e . is ( Entry . DELETED , getCurrentThreadId ( ) ) ) throw new ConcurrentModificationException ( ) ; if ( auto_commit ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; return e ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; } prev = e ; e = next ; } return e ;


signature:
public class TransactionalHashMap { /** * Special version of remove for EntrySet . */
@ SuppressWarnings ( "unchecked" ) Entry < K , V > removeMapping ( Object o ) { } }

implementation: if ( ! ( o instanceof Map . Entry ) ) return null ; Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object k = maskNull ( entry . getKey ( ) ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . hash == hash && validEntry ( e ) && e . equals ( entry ) ) { if ( auto_commit ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; return e ; } prev = e ; e = next ; } return e ;


signature:
public class TransactionalHashMap { /** * Removes all mappings from this map . */
@ Override public void clear ( ) { } }

implementation: modCount ++ ; Entry < K , V > tab [ ] = table ; for ( int i = 0 ; i < tab . length ; i ++ ) tab [ i ] = null ; size = 0 ;


signature:
public class TransactionalHashMap { /** * Add a new entry with the specified key , value and hash code to
 * the specified bucket . It is the responsibility of this
 * method to resize the table if appropriate .
 * Subclass overrides this to alter the behavior of put method . */
void addEntry ( int hash , K key , V value , int bucketIndex ) { } }

implementation: table [ bucketIndex ] = new Entry < K , V > ( hash , key , value , table [ bucketIndex ] ) ; if ( ! auto_commit ) table [ bucketIndex ] . setStatus ( Entry . ADDED , getCurrentThreadId ( ) ) ; if ( size ++ >= threshold ) resize ( 2 * table . length ) ;


signature:
public class TransactionalHashMap { /** * Like addEntry except that this version is used when creating entries
 * as part of Map construction or " pseudo - construction " ( cloning ,
 * deserialization ) . This version needn ' t worry about resizing the table .
 * Subclass overrides this to alter the behavior of HashMap ( Map ) ,
 * clone , and readObject . */
void createEntry ( int hash , K key , V value , int bucketIndex ) { } }

implementation: table [ bucketIndex ] = new Entry < K , V > ( hash , key , value , table [ bucketIndex ] ) ; size ++ ;


signature:
public class AugmentedMap { /** * Creates map delegate .
 * @ param base Base map to augment .
 * @ param keys Keys to the augmented map .
 * @ param augmentation Function used to generate the new values .
 * @ param < K > Key
 * @ param < V > Value
 * @ return A copy of the { @ code base } map augmented with new values . */
private static < K , V > ImmutableMap < K , V > createDelegate ( final Map < K , V > base , final Set < ? extends K > keys , final Function < K , V > augmentation ) { } }

implementation: final ImmutableMap . Builder < K , V > builder = ImmutableMap . builder ( ) ; builder . putAll ( base ) ; keys . stream ( ) . filter ( key -> ! base . containsKey ( key ) ) . forEach ( key -> builder . put ( key , augmentation . apply ( key ) ) ) ; return builder . build ( ) ;


signature:
public class StringUtils { /** * Parses the given date string in either of the three profiles of < a
 * href = " http : / / xmpp . org / extensions / xep - 0082 . html " > XEP - 0082 - XMPP Date and
 * Time Profiles < / a > or < a
 * href = " http : / / xmpp . org / extensions / xep - 0091 . html " > XEP - 0091 - Legacy Delayed
 * Delivery < / a > format .
 * This method uses internal date formatters and is thus threadsafe .
 * @ param dateString
 * the date string to parse
 * @ return the parsed Date
 * @ throws ParseException
 * if the specified string cannot be parsed */
public static Date parseDate ( String dateString ) throws ParseException { } }

implementation:
Matcher matcher = xep0091Pattern . matcher ( dateString ) ; /* * if date is in XEP - 0091 format handle ambiguous dates missing the
 * leading zero in month and day */
if ( matcher . matches ( ) ) { int length = dateString . split ( "T" ) [ 0 ] . length ( ) ; if ( length < 8 ) { Date date = handleDateWithMissingLeadingZeros ( dateString , length ) ; if ( date != null ) return date ; } else { synchronized ( xep0091Formatter ) { return xep0091Formatter . parse ( dateString ) ; } } } else { for ( PatternCouplings coupling : couplings ) { matcher = coupling . pattern . matcher ( dateString ) ; if ( matcher . matches ( ) ) { if ( coupling . needToConvertTimeZone ) { dateString = coupling . convertTime ( dateString ) ; } synchronized ( coupling . formatter ) { return coupling . formatter . parse ( dateString ) ; } } } } /* * We assume it is the XEP - 0082 DateTime profile with no milliseconds at
 * this point . If it isn ' t , is is just not parseable , then we attempt to
 * parse it regardless and let it throw the ParseException . */
synchronized ( dateTimeNoMillisFormatter ) { return dateTimeNoMillisFormatter . parse ( dateString ) ; }


signature:
public class StringUtils { /** * Parses the given date string in different ways and returns the date that
 * lies in the past and / or is nearest to the current date - time .
 * @ param stampString
 * date in string representation
 * @ param dateLength
 * @ param noFuture
 * @ return the parsed date
 * @ throws ParseException
 * The date string was of an unknown format */
private static Date handleDateWithMissingLeadingZeros ( String stampString , int dateLength ) throws ParseException { } }

implementation: if ( dateLength == 6 ) { synchronized ( xep0091Date6DigitFormatter ) { return xep0091Date6DigitFormatter . parse ( stampString ) ; } } Calendar now = Calendar . getInstance ( ) ; Calendar oneDigitMonth = parseXEP91Date ( stampString , xep0091Date7Digit1MonthFormatter ) ; Calendar twoDigitMonth = parseXEP91Date ( stampString , xep0091Date7Digit2MonthFormatter ) ; List < Calendar > dates = filterDatesBefore ( now , oneDigitMonth , twoDigitMonth ) ; if ( ! dates . isEmpty ( ) ) { return determineNearestDate ( now , dates ) . getTime ( ) ; } return null ;


signature:
public class StringUtils { /** * Returns the name portion of a XMPP address . For example , for the address
 * " matt @ jivesoftware . com / Smack " , " matt " would be returned . If no username
 * is present in the address , the empty string will be returned .
 * @ param XMPPAddress
 * the XMPP address .
 * @ return the name portion of the XMPP address . */
public static String parseName ( String XMPPAddress ) { } }

implementation: if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . lastIndexOf ( "@" ) ; if ( atIndex <= 0 ) { return "" ; } else { return XMPPAddress . substring ( 0 , atIndex ) ; }


signature:
public class StringUtils { /** * Returns the server portion of a XMPP address . For example , for the
 * address " matt @ jivesoftware . com / Smack " , " jivesoftware . com " would be
 * returned . If no server is present in the address , the empty string will
 * be returned .
 * @ param XMPPAddress
 * the XMPP address .
 * @ return the server portion of the XMPP address . */
public static String parseServer ( String XMPPAddress ) { } }

implementation:
if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . lastIndexOf ( "@" ) ; // If the String ends with ' @ ' , return the empty string .
if ( atIndex + 1 > XMPPAddress . length ( ) ) { return "" ; } int slashIndex = XMPPAddress . indexOf ( "/" ) ; if ( slashIndex > 0 && slashIndex > atIndex ) { return XMPPAddress . substring ( atIndex + 1 , slashIndex ) ; } else { return XMPPAddress . substring ( atIndex + 1 ) ; }


signature:
public class StringUtils { /** * Returns the resource portion of a XMPP address . For example , for the
 * address " matt @ jivesoftware . com / Smack " , " Smack " would be returned . If no
 * resource is present in the address , the empty string will be returned .
 * @ param XMPPAddress
 * the XMPP address .
 * @ return the resource portion of the XMPP address . */
public static String parseResource ( String XMPPAddress ) { } }

implementation: if ( XMPPAddress == null ) { return null ; } int slashIndex = XMPPAddress . indexOf ( "/" ) ; if ( slashIndex + 1 > XMPPAddress . length ( ) || slashIndex < 0 ) { return "" ; } else { return XMPPAddress . substring ( slashIndex + 1 ) ; }


signature:
public class StringUtils { /** * Returns the XMPP address with any resource information removed . For
 * example , for the address " matt @ jivesoftware . com / Smack " ,
 * " matt @ jivesoftware . com " would be returned .
 * @ param XMPPAddress
 * the XMPP address .
 * @ return the bare XMPP address without resource information . */
public static String parseBareAddress ( String XMPPAddress ) { } }

implementation: if ( XMPPAddress == null ) { return null ; } int slashIndex = XMPPAddress . indexOf ( "/" ) ; if ( slashIndex < 0 ) { return XMPPAddress ; } else if ( slashIndex == 0 ) { return "" ; } else { return XMPPAddress . substring ( 0 , slashIndex ) ; }


signature:
public class StringUtils { /** * Returns true if jid is a full JID ( i . e . a JID with resource part ) .
 * @ param jid
 * @ return true if full JID , false otherwise */
public static boolean isFullJID ( String jid ) { } }

implementation: if ( parseName ( jid ) . length ( ) <= 0 || parseServer ( jid ) . length ( ) <= 0 || parseResource ( jid ) . length ( ) <= 0 ) { return false ; } return true ;


signature:
public class StringUtils { /** * Escapes the node portion of a JID according to " JID Escaping " ( JEP - 0106 ) .
 * Escaping replaces characters prohibited by node - prep with escape
 * sequences , as follows :
 * < table border = " 1 " >
 * < tr >
 * < td > < b > Unescaped Character < / b > < / td >
 * < td > < b > Encoded Sequence < / b > < / td >
 * < / tr >
 * < tr >
 * < td > & lt ; space & gt ; < / td >
 * < td > \ 20 < / td >
 * < / tr >
 * < tr >
 * < td > " < / td >
 * < td > \ 22 < / td >
 * < / tr >
 * < tr >
 * < td > & < / td >
 * < td > \ 26 < / td >
 * < / tr >
 * < tr >
 * < td > ' < / td >
 * < td > \ 27 < / td >
 * < / tr >
 * < tr >
 * < td > / < / td >
 * < td > \ 2f < / td >
 * < / tr >
 * < tr >
 * < td > : < / td >
 * < td > \ 3a < / td >
 * < / tr >
 * < tr >
 * < td > & lt ; < / td >
 * < td > \ 3c < / td >
 * < / tr >
 * < tr >
 * < td > & gt ; < / td >
 * < td > \ 3e < / td >
 * < / tr >
 * < tr >
 * < td > @ < / td >
 * < td > \ 40 < / td >
 * < / tr >
 * < tr >
 * < td > \ < / td >
 * < td > \ 5c < / td >
 * < / tr >
 * < / table >
 * This process is useful when the node comes from an external source that
 * doesn ' t conform to nodeprep . For example , a username in LDAP may be
 * " Joe Smith " . Because the & lt ; space & gt ; character isn ' t a valid part of a
 * node , the username should be escaped to " Joe \ 20Smith " before being made
 * into a JID ( e . g . " joe \ 20smith @ example . com " after case - folding , etc . has
 * been applied ) .
 * All node escaping and un - escaping must be performed manually at the
 * appropriate time ; the JID class will not escape or un - escape
 * automatically .
 * @ param node
 * the node .
 * @ return the escaped version of the node . */
public static String escapeNode ( String node ) { } }

implementation: if ( node == null ) { return null ; } StringBuilder buf = new StringBuilder ( node . length ( ) + 8 ) ; for ( int i = 0 , n = node . length ( ) ; i < n ; i ++ ) { char c = node . charAt ( i ) ; switch ( c ) { case '"' : buf . append ( "\\22" ) ; break ; case '&' : buf . append ( "\\26" ) ; break ; case '\'' : buf . append ( "\\27" ) ; break ; case '/' : buf . append ( "\\2f" ) ; break ; case ':' : buf . append ( "\\3a" ) ; break ; case '<' : buf . append ( "\\3c" ) ; break ; case '>' : buf . append ( "\\3e" ) ; break ; case '@' : buf . append ( "\\40" ) ; break ; case '\\' : buf . append ( "\\5c" ) ; break ; default : { if ( Character . isWhitespace ( c ) ) { buf . append ( "\\20" ) ; } else { buf . append ( c ) ; } } } } return buf . toString ( ) ;


signature:
public class StringUtils { /** * Un - escapes the node portion of a JID according to " JID Escaping "
 * ( JEP - 0106 ) .
 * Escaping replaces characters prohibited by node - prep with escape
 * sequences , as follows :
 * < table border = " 1 " >
 * < tr >
 * < td > < b > Unescaped Character < / b > < / td >
 * < td > < b > Encoded Sequence < / b > < / td >
 * < / tr >
 * < tr >
 * < td > & lt ; space & gt ; < / td >
 * < td > \ 20 < / td >
 * < / tr >
 * < tr >
 * < td > " < / td >
 * < td > \ 22 < / td >
 * < / tr >
 * < tr >
 * < td > & < / td >
 * < td > \ 26 < / td >
 * < / tr >
 * < tr >
 * < td > ' < / td >
 * < td > \ 27 < / td >
 * < / tr >
 * < tr >
 * < td > / < / td >
 * < td > \ 2f < / td >
 * < / tr >
 * < tr >
 * < td > : < / td >
 * < td > \ 3a < / td >
 * < / tr >
 * < tr >
 * < td > & lt ; < / td >
 * < td > \ 3c < / td >
 * < / tr >
 * < tr >
 * < td > & gt ; < / td >
 * < td > \ 3e < / td >
 * < / tr >
 * < tr >
 * < td > @ < / td >
 * < td > \ 40 < / td >
 * < / tr >
 * < tr >
 * < td > \ < / td >
 * < td > \ 5c < / td >
 * < / tr >
 * < / table >
 * This process is useful when the node comes from an external source that
 * doesn ' t conform to nodeprep . For example , a username in LDAP may be
 * " Joe Smith " . Because the & lt ; space & gt ; character isn ' t a valid part of a
 * node , the username should be escaped to " Joe \ 20Smith " before being made
 * into a JID ( e . g . " joe \ 20smith @ example . com " after case - folding , etc . has
 * been applied ) .
 * All node escaping and un - escaping must be performed manually at the
 * appropriate time ; the JID class will not escape or un - escape
 * automatically .
 * @ param node
 * the escaped version of the node .
 * @ return the un - escaped version of the node . */
public static String unescapeNode ( String node ) { } }

implementation: if ( node == null ) { return null ; } char [ ] nodeChars = node . toCharArray ( ) ; StringBuilder buf = new StringBuilder ( nodeChars . length ) ; for ( int i = 0 , n = nodeChars . length ; i < n ; i ++ ) { compare : { char c = node . charAt ( i ) ; if ( c == '\\' && i + 2 < n ) { char c2 = nodeChars [ i + 1 ] ; char c3 = nodeChars [ i + 2 ] ; if ( c2 == '2' ) { switch ( c3 ) { case '0' : buf . append ( ' ' ) ; i += 2 ; break compare ; case '2' : buf . append ( '"' ) ; i += 2 ; break compare ; case '6' : buf . append ( '&' ) ; i += 2 ; break compare ; case '7' : buf . append ( '\'' ) ; i += 2 ; break compare ; case 'f' : buf . append ( '/' ) ; i += 2 ; break compare ; } } else if ( c2 == '3' ) { switch ( c3 ) { case 'a' : buf . append ( ':' ) ; i += 2 ; break compare ; case 'c' : buf . append ( '<' ) ; i += 2 ; break compare ; case 'e' : buf . append ( '>' ) ; i += 2 ; break compare ; } } else if ( c2 == '4' ) { if ( c3 == '0' ) { buf . append ( "@" ) ; i += 2 ; break compare ; } } else if ( c2 == '5' ) { if ( c3 == 'c' ) { buf . append ( "\\" ) ; i += 2 ; break compare ; } } } buf . append ( c ) ; } } return buf . toString ( ) ;


signature:
public class StringUtils { /** * Encodes a string for use in an XML attribute by escaping characters with
 * a special meaning . In particular , white spaces are encoded as character
 * references , such that they are not replaced by ' ' on parsing . */
private static String xmlAttribEncodeBinary ( String value ) { } }

implementation:
StringBuilder s = new StringBuilder ( ) ; char buf [ ] = value . toCharArray ( ) ; for ( char c : buf ) { switch ( c ) { case '<' : s . append ( "<" ) ; break ; case '>' : s . append ( ">" ) ; break ; case '&' : s . append ( "&" ) ; break ; case '"' : s . append ( """ ) ; break ; case '\'' : s . append ( "'" ) ; break ; default : if ( c <= 0x1f || ( 0x7f <= c && c <= 0x9f ) ) { // includes \ t , \ n ,
s . append ( "&#x" ) ; s . append ( String . format ( "%X" , ( int ) c ) ) ; s . append ( ';' ) ; } else { s . append ( c ) ; } } } return s . toString ( ) ;


signature:
public class StringUtils { /** * Hashes a String using the SHA - 1 algorithm and returns the result as a
 * String of hexadecimal numbers . This method is synchronized to avoid
 * excessive MessageDigest object creation . If calling this method becomes a
 * bottleneck in your code , you may wish to maintain a pool of MessageDigest
 * objects instead of using this method .
 * A hash is a one - way function - - that is , given an input , an output is
 * easily computed . However , given the output , the input is almost
 * impossible to compute . This is useful for passwords since we can store
 * the hash and a hacker will then have a very hard time determining the
 * original password .
 * @ param data
 * the String to compute the hash of .
 * @ return a hashed version of the passed - in String */
public synchronized static String hash ( String data ) { } }

implementation:
if ( digest == null ) { try { digest = MessageDigest . getInstance ( "SHA-1" ) ; } catch ( NoSuchAlgorithmException nsae ) { log . log ( Level . ERROR , "Failed to load the SHA-1 MessageDigest. Smack will be unable to function normally." , nsae ) ; } } // Now , compute hash .
try { digest . update ( data . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { log . log ( Level . ERROR , "Error computing hash" , e ) ; } return encodeHex ( digest . digest ( ) ) ;


signature:
public class StringUtils { /** * Encodes an array of bytes as String representation of hexadecimal .
 * @ param bytes
 * an array of bytes to convert to a hex string .
 * @ return generated hex string . */
public static String encodeHex ( byte [ ] bytes ) { } }

implementation: StringBuilder hex = new StringBuilder ( bytes . length * 2 ) ; for ( byte aByte : bytes ) { if ( ( ( int ) aByte & 0xff ) < 0x10 ) { hex . append ( "0" ) ; } hex . append ( Integer . toString ( ( int ) aByte & 0xff , 16 ) ) ; } return hex . toString ( ) ;


signature:
public class StringUtils { /** * Encodes a String as a base64 String .
 * @ param data
 * a String to encode .
 * @ return a base64 encoded String . */
public static String encodeBase64 ( String data ) { } }

implementation: byte [ ] bytes = null ; try { bytes = data . getBytes ( "ISO-8859-1" ) ; } catch ( UnsupportedEncodingException uee ) { throw new IllegalStateException ( uee ) ; } return encodeBase64 ( bytes ) ;


signature:
public class StringUtils { /** * Encodes a byte array into a bse64 String .
 * @ param data
 * The byte arry to encode .
 * @ param offset
 * the offset of the bytearray to begin encoding at .
 * @ param len
 * the length of bytes to encode .
 * @ param lineBreaks
 * True if the encoding should contain line breaks and false if
 * it should not .
 * @ return A base64 encoded String . */
public static String encodeBase64 ( byte [ ] data , int offset , int len , boolean lineBreaks ) { } }

implementation: return Base64 . encodeBytes ( data , offset , len , ( lineBreaks ? Base64 . NO_OPTIONS : Base64 . DONT_BREAK_LINES ) ) ;


signature:
public class StringUtils { /** * Decodes a base64 String . Unlike Base64 . decode ( ) this method does not try
 * to detect and decompress a gzip - compressed input .
 * @ param data
 * a base64 encoded String to decode .
 * @ return the decoded String . */
public static byte [ ] decodeBase64 ( String data ) { } }

implementation: byte [ ] bytes ; try { bytes = data . getBytes ( "UTF-8" ) ; } catch ( java . io . UnsupportedEncodingException uee ) { bytes = data . getBytes ( ) ; } bytes = Base64 . decode ( bytes , 0 , bytes . length , Base64 . NO_OPTIONS ) ; return bytes ;


signature:
public class StringUtils { /** * Returns a random String of numbers and letters ( lower and upper case ) of
 * the specified length . The method uses the Random class that is built - in
 * to Java which is suitable for low to medium grade security uses . This
 * means that the output is only pseudo random , i . e . , each number is
 * mathematically generated so is not truly random .
 * The specified length must be at least one . If not , the method will return
 * null .
 * @ param length
 * the desired length of the random String to return .
 * @ return a random String of numbers and letters of the specified length . */
public static String randomString ( int length ) { } }

implementation:
if ( length < 1 ) { return null ; } // Create a char buffer to put random letters and numbers in .
char [ ] randBuffer = new char [ length ] ; for ( int i = 0 ; i < randBuffer . length ; i ++ ) { randBuffer [ i ] = numbersAndLetters [ randGen . nextInt ( 71 ) ] ; } return new String ( randBuffer ) ;


signature:
public class CounterIterativeCallback { /** * Overridden to just get the count , and nothing else . */
@ Override public Integer iterate ( final FilterableCollection < ? extends T > c ) { } }

implementation:
checkUsed ( ) ; // No point doing the iteration . Just return size of collection .
count = c . size ( ) ; return count ;


signature:
public class CommandHandler { /** * adds the ability for the Play / Pause requests
 * @ param controller the controller for callback */
public void setPlayPauseController ( Consumer < String > controller ) { } }

implementation: if ( controller == null ) return ; this . playPause = controller ; capabilities . setPlayPauseControl ( true ) ;


signature:
public class CommandHandler { /** * adds the ability to select tracks
 * @ param controller the controller for callback */
public void setTrackSelectorController ( Consumer < TrackInfo > controller ) { } }

implementation: if ( controller == null ) return ; selectTrack = controller ; capabilities . setAbleToSelectTrack ( true ) ;


signature:
public class CommandHandler { /** * adds the ability to select the next / previous track
 * @ param controller the controller for callback */
public void setNextPreviousController ( Consumer < String > controller ) { } }

implementation: if ( controller == null ) return ; nextPrevious = controller ; capabilities . setNextPrevious ( true ) ;


signature:
public class CommandHandler { /** * adds the ability to jump to a specified position of the current track
 * @ param controller the controller for callback */
public void setJumpProgressController ( Consumer < Progress > controller ) { } }

implementation: if ( controller == null ) return ; jumpProgress = controller ; capabilities . setAbleToJump ( true ) ;


signature:
public class CommandHandler { /** * adds the ability to change the playback
 * @ param controller the controller for callback */
public void setPlaybackChangeableController ( Consumer < String > controller ) { } }

implementation: if ( controller == null ) return ; changePlayback = controller ; capabilities . setPlaybackChangeable ( true ) ;


signature:
public class CommandHandler { /** * adds the ability to change the volume from outside the player
 * @ param controller the controller for callback */
public void setVolumeChangeableController ( Consumer < Volume > controller ) { } }

implementation: if ( controller == null ) return ; changeVolume = controller ; capabilities . setChangeVolume ( true ) ;


signature:
public class CommandHandler { /** * adds the ability to return the available playlists on request .
 * @ param availablePlaylist retruns a List of Strings which represent the Playlists
 * @ param playlistForNameFunction takes a String from the List and returns the Playlist */
public void broadcastAvailablePlaylists ( Supplier < List < String > > availablePlaylist , Function < String , Playlist > playlistForNameFunction ) { } }

implementation: if ( availablePlaylist == null || playlistForNameFunction == null ) return ; this . availablePlaylist = availablePlaylist ; this . playlistForNameFunction = playlistForNameFunction ; capabilities . setBroadcasting ( true ) ;


signature:
public class CommandHandler { /** * this method gets called when a new Command was found . It automatically fires the update Event or an error
 * @ param eventModel the event with the Commands */
public void handleCommandResources ( EventModel eventModel ) { } }

implementation:
List < ResourceModel < String > > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( CommandResource . ResourceID ) . stream ( ) . filter ( resourceModel -> resourceModel . getResource ( ) instanceof String ) . map ( resourceModel -> { try { // noinspection unchecked
return ( ResourceModel < String > ) resourceModel ; } catch ( ClassCastException e ) { return null ; } } ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; for ( ResourceModel < String > resourceModel : resourceModels ) { if ( ! CommandResource . verifyCommand ( resourceModel . getResource ( ) ) ) continue ; if ( ! CommandResource . verifyCapabilities ( resourceModel . getResource ( ) , capabilities ) ) { musicHelper . playerError ( PlayerError . ERROR_NOT_ABLE + "command: " + resourceModel . getResource ( ) , resourceModel . getProvider ( ) ) ; continue ; } switch ( resourceModel . getResource ( ) ) { case CommandResource . PLAY : if ( ! musicProvider . isPlaying ( ) ) playPause . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . PAUSE : if ( musicProvider . isPlaying ( ) ) playPause . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . SELECT_TRACK : handleSelectTrack ( eventModel , resourceModel ) ; break ; case CommandResource . NEXT : nextPrevious . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . PREVIOUS : nextPrevious . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . JUMP : handleJump ( eventModel , resourceModel ) ; break ; case CommandResource . CHANGE_PLAYBACK : changePlayback . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . CHANGE_VOLUME : handleVolume ( eventModel , resourceModel ) ; break ; case CommandResource . STOP : stopCallback . run ( ) ; break ; } }


signature:
public class CommandHandler { /** * handles the volume - command
 * @ param eventModel the event
 * @ param resourceModel the resourcemodel */
private void handleVolume ( EventModel eventModel , ResourceModel < String > resourceModel ) { } }

implementation: Optional < Volume > volumeResource = VolumeResource . getVolume ( eventModel ) ; if ( ! volumeResource . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + "command: " + resourceModel . getResource ( ) + "missing resource" , resourceModel . getProvider ( ) ) ; } changeVolume . accept ( volumeResource . get ( ) ) ;


signature:
public class CommandHandler { /** * handles the jump - command
 * @ param eventModel the event
 * @ param resourceModel the resourcemodel */
private void handleJump ( EventModel eventModel , ResourceModel < String > resourceModel ) { } }

implementation: Optional < Progress > progress = ProgressResource . getProgress ( eventModel ) ; if ( ! progress . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + "command: " + resourceModel . getResource ( ) + "missing resource" , resourceModel . getProvider ( ) ) ; } jumpProgress . accept ( progress . get ( ) ) ;


signature:
public class CommandHandler { /** * handles the select Track command
 * @ param eventModel the event
 * @ param resourceModel the resource */
private void handleSelectTrack ( EventModel eventModel , ResourceModel < String > resourceModel ) { } }

implementation: Optional < TrackInfo > trackInfo = TrackInfoResource . getTrackInfo ( eventModel ) ; if ( ! trackInfo . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + "command: " + resourceModel . getResource ( ) + "missing resource" , resourceModel . getProvider ( ) ) ; } selectTrack . accept ( trackInfo . get ( ) ) ;


signature:
public class CacheManagerServiceImpl { /** * { @ inheritDoc }
 * @ see org . sakaiproject . nakamura . api . memory . CacheManagerService # getCache ( java . lang . String ) */
public < V > Cache < V > getCache ( String name , CacheScope scope ) { } }

implementation: switch ( scope ) { case INSTANCE : return getInstanceCache ( name ) ; case CLUSTERINVALIDATED : return getInstanceCache ( name ) ; case CLUSTERREPLICATED : return getInstanceCache ( name ) ; case REQUEST : return getRequestCache ( name ) ; case THREAD : return getThreadCache ( name ) ; default : return getInstanceCache ( name ) ; }


signature:
public class CacheManagerServiceImpl { /** * Generate a cache bound to the thread .
 * @ param name
 * @ return */
@ SuppressWarnings ( "unchecked" ) private < V > Cache < V > getThreadCache ( String name ) { } }

implementation: Map < String , Cache < ? > > threadCacheMap = threadCacheMapHolder . get ( ) ; Cache < V > threadCache = ( Cache < V > ) threadCacheMap . get ( name ) ; if ( threadCache == null ) { threadCache = new MapCacheImpl < V > ( ) ; threadCacheMap . put ( name , threadCache ) ; } return threadCache ;


signature:
public class CacheManagerServiceImpl { /** * Generate a cache bound to the request
 * @ param name
 * @ return */
@ SuppressWarnings ( "unchecked" ) private < V > Cache < V > getRequestCache ( String name ) { } }

implementation: Map < String , Cache < ? > > requestCacheMap = requestCacheMapHolder . get ( ) ; Cache < V > requestCache = ( Cache < V > ) requestCacheMap . get ( name ) ; if ( requestCache == null ) { requestCache = new MapCacheImpl < V > ( ) ; requestCacheMap . put ( name , requestCache ) ; } return requestCache ;


signature:
public class OSGiStoreListener { /** * { @ inheritDoc } */
public void onDelete ( String zone , String path , String user , String resourceType , Map < String , Object > beforeEvent , String ... attributes ) { } }

implementation: String topic = DEFAULT_DELETE_TOPIC ; if ( deleteTopics . containsKey ( zone ) ) { topic = deleteTopics . get ( zone ) ; } postEvent ( topic , path , user , resourceType , beforeEvent , attributes ) ;


signature:
public class OSGiStoreListener { /** * { @ inheritDoc } */
public void onUpdate ( String zone , String path , String user , String resourceType , boolean isNew , Map < String , Object > beforeEvent , String ... attributes ) { } }

implementation: String topic = DEFAULT_UPDATE_TOPIC ; if ( isNew ) { topic = DEFAULT_CREATE_TOPIC ; if ( deleteTopics . containsKey ( zone ) ) { topic = createTopics . get ( zone ) ; } } else { if ( deleteTopics . containsKey ( zone ) ) { topic = updateTopics . get ( zone ) ; } } postEvent ( topic , path , user , resourceType , beforeEvent , attributes ) ;


signature:
public class StorageClientUtils { /** * Get the name of an alternative field for an alternative stream .
 * @ param field
 * the fieldname
 * @ param streamId
 * the alternative stream name
 * @ return the alternative field name . */
public static String getAltField ( String field , String streamId ) { } }

implementation: if ( streamId == null ) { return field ; } return field + "/" + streamId ;


signature:
public class StorageClientUtils { /** * TODO : Unit test */
public static String insecureHash ( String naked ) { } }

implementation: try { return insecureHash ( naked . getBytes ( UTF8 ) ) ; } catch ( UnsupportedEncodingException e3 ) { LOGGER . error ( "no UTF-8 Envoding, get a real JVM, nothing will work here. NPE to come" ) ; return null ; }


signature:
public class StorageClientUtils { /** * Converts to an Immutable map , with keys that are in the filter not
 * transfered . Nested maps are also transfered .
 * @ param < K > the type of the key
 * @ param < V > the type of the value
 * @ param source a map of values to start with
 * @ param modified a map to oveeride values in source
 * @ param include if not null , only include these keys in the returned map
 * @ param exclude if not null , exclude these keys from the returned map
 * @ return a map with the modifications applied and filtered by the includes and excludes */
@ SuppressWarnings ( "unchecked" ) public static < K , V > Map < K , V > getFilterMap ( Map < K , V > source , Map < K , V > modified , Set < K > include , Set < K > exclude , boolean includingRemoveProperties ) { } }

implementation:
if ( ( modified == null || modified . size ( ) == 0 ) && ( include == null ) && ( exclude == null || exclude . size ( ) == 0 ) ) { if ( source instanceof ImmutableMap ) { return source ; } else { return ImmutableMap . copyOf ( source ) ; } } Builder < K , V > filteredMap = new ImmutableMap . Builder < K , V > ( ) ; for ( Entry < K , V > e : source . entrySet ( ) ) { K k = e . getKey ( ) ; if ( include == null || include . contains ( k ) ) { if ( exclude == null || ! exclude . contains ( k ) ) { if ( modified != null && modified . containsKey ( k ) ) { V o = modified . get ( k ) ; if ( o instanceof Map ) { filteredMap . put ( k , ( V ) getFilterMap ( ( Map < K , V > ) o , null , null , exclude , includingRemoveProperties ) ) ; } else if ( includingRemoveProperties ) { filteredMap . put ( k , o ) ; } else if ( ! ( o instanceof RemoveProperty ) ) { filteredMap . put ( k , o ) ; } } else { Object o = e . getValue ( ) ; if ( o instanceof Map ) { filteredMap . put ( k , ( V ) getFilterMap ( ( Map < K , V > ) e . getValue ( ) , null , null , exclude , includingRemoveProperties ) ) ; } else { filteredMap . put ( k , e . getValue ( ) ) ; } } } } } if ( modified != null ) { // process additions
for ( Entry < K , V > e : modified . entrySet ( ) ) { K k = e . getKey ( ) ; if ( ! source . containsKey ( k ) ) { V v = e . getValue ( ) ; if ( ! ( v instanceof RemoveProperty ) && v != null ) { filteredMap . put ( k , v ) ; } } } } return filteredMap . build ( ) ;


signature:
public class StorageClientUtils { /** * Converts a map into Map or byte [ ] values with String keys . No control
 * over depth of nesting . Keys in the filter set are not transfered
 * Resulting map is mutable .
 * @ param source a map of values to modify
 * @ param filter a map of values to remove by key from source
 * @ return the map less any keys from filter */
@ SuppressWarnings ( "unchecked" ) public static Map < String , Object > getFilteredAndEcodedMap ( Map < String , Object > source , Set < String > filter ) { } }

implementation: Map < String , Object > filteredMap = Maps . newHashMap ( ) ; for ( Entry < String , Object > e : source . entrySet ( ) ) { if ( ! filter . contains ( e . getKey ( ) ) ) { Object o = e . getValue ( ) ; if ( o instanceof Map ) { filteredMap . put ( e . getKey ( ) , getFilteredAndEcodedMap ( ( Map < String , Object > ) o , filter ) ) ; } else { filteredMap . put ( e . getKey ( ) , o ) ; } } } return filteredMap ;


signature:
public class StorageClientUtils { /** * For instance the SparsePrincipal uses it . */
public static String shardPath ( String id ) { } }

implementation: String hash = insecureHash ( id ) ; return hash . substring ( 0 , 2 ) + "/" + hash . substring ( 2 , 4 ) + "/" + hash . substring ( 4 , 6 ) + "/" + id ;


signature:
public class StorageClientUtils { /** * TODO : Unit test */
public static String arrayEscape ( String string ) { } }

implementation: string = string . replaceAll ( "%" , "%1" ) ; string = string . replaceAll ( "," , "%2" ) ; return string ;


signature:
public class StorageClientUtils { /** * TODO : Unit test */
public static String arrayUnEscape ( String string ) { } }

implementation: string = string . replaceAll ( "%2" , "," ) ; string = string . replaceAll ( "%1" , "%" ) ; return string ;


signature:
public class StorageClientUtils { /** * Adapt an object to a session . I haven ' t used typing here becuase I don ' t
 * want to bind to the Jars in question and create dependencies .
 * @ param source
 * the input object that the method
 * @ return */
public static Session adaptToSession ( Object source ) { } }

implementation:
if ( source instanceof SessionAdaptable ) { return ( ( SessionAdaptable ) source ) . getSession ( ) ; } else { // assume this is a JCR session of someform , in which case there
// should be a SparseUserManager
Object userManager = safeMethod ( source , "getUserManager" , new Object [ 0 ] , new Class [ 0 ] ) ; if ( userManager != null ) { return ( Session ) safeMethod ( userManager , "getSession" , new Object [ 0 ] , new Class [ 0 ] ) ; } return null ; }


signature:
public class StorageClientUtils { /** * Make the method on the target object accessible and then invoke it .
 * @ param target the object with the method to invoke
 * @ param methodName the name of the method to invoke
 * @ param args the arguments to pass to the invoked method
 * @ param argsTypes the types of the arguments being passed to the method
 * @ return */
private static Object safeMethod ( Object target , String methodName , Object [ ] args , @ SuppressWarnings ( "rawtypes" ) Class [ ] argsTypes ) { } }

implementation: if ( target != null ) { try { Method m = target . getClass ( ) . getMethod ( methodName , argsTypes ) ; if ( ! m . isAccessible ( ) ) { m . setAccessible ( true ) ; } return m . invoke ( target , args ) ; } catch ( Throwable e ) { LOGGER . info ( "Failed to invoke method " + methodName + " " + target , e ) ; } } return null ;


signature:
public class StorageClientUtils { /** * Delete an entire tree starting from the deepest part of the tree and
 * working back up . Will stop the moment a permission denied is encountered
 * either for read or for delete .
 * @ param contentManager
 * @ param path
 * @ throws AccessDeniedException
 * @ throws StorageClientException */
public static void deleteTree ( ContentManager contentManager , String path ) throws AccessDeniedException , StorageClientException { } }

implementation: Content content = contentManager . get ( path ) ; if ( content != null ) { for ( String childPath : content . listChildPaths ( ) ) { deleteTree ( contentManager , childPath ) ; } } contentManager . delete ( path ) ;


signature:
public class HashMap4Template { /** * Method to get existing [ key1 , key2 , key3 , key4 ] value or create new one if it ' s
 * absent . Needs implementation of create ( key1 , key2 , key3 , key4 ) in order to work */
public V getOrCreate ( K1 key1 , K2 key2 , K3 key3 , K4 key4 ) { } }

implementation:
// already got it ?
MultiKey multi_key = new MultiKey ( key1 , key2 , key3 , key4 ) ; if ( containsKey ( multi_key ) ) return get ( multi_key ) ; // if not , create and add it
V result = create ( key1 , key2 , key3 , key4 ) ; put ( multi_key , result ) ; return result ;


signature:
public class AbstractDao { /** * Only update specified properties of the Object
 * @ param object
 * An dirty object .
 * @ param properties
 * array of property names . for now Collection properties in not
 * supported . */
@ Override public void updateOne ( E object , String ... properties ) { } }

implementation:
if ( object . getId ( ) == null ) { throw new RuntimeException ( "Not a Persisted entity" ) ; } if ( properties == null || properties . length == 0 ) { entityManager . merge ( object ) ; return ; } // for performance reason its better to mix getting fields , their values
// and making query all in one loop
// in one iteration
StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Update " + clazz . getName ( ) + " SET " ) ; // cache of fieldName - - > value
Map < String , Object > cache = new HashMap < String , Object > ( ) ; for ( String prop : properties ) { try { Field field = object . getClass ( ) . getDeclaredField ( prop ) ; field . setAccessible ( true ) ; Object value = field . get ( object ) ; if ( value instanceof Collection ) { // value = new LinkedList < > ( ( Collection < ? extends Object > ) value ) ;
throw new RuntimeException ( "Collection property is not suppotred." ) ; } cache . put ( prop , value ) ; // ignore first comma
if ( cache . size ( ) > 1 ) { sb . append ( " ," ) ; } sb . append ( prop ) ; sb . append ( " = :" ) ; sb . append ( prop ) ; } catch ( Exception e ) { // TODO : use fine grain exceptions
// FIX : NEXT RELEASE I hope : )
throw new RuntimeException ( e ) ; } } // this means nothing will be updated so hitting db is unnecessary
if ( cache . size ( ) == 0 ) return ; sb . append ( " WHERE id = " + object . getId ( ) ) ; Query query = entityManager . createQuery ( sb . toString ( ) ) ; for ( Entry < String , Object > entry : cache . entrySet ( ) ) { query . setParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } query . executeUpdate ( ) ;


signature:
public class KeepAliveManager { /** * Retrieves a { @ link KeepAliveManager } for the specified { @ link Connection }
 * , creating one if it doesn ' t already exist .
 * @ param connection
 * The connection the manager is attached to .
 * @ return The new or existing manager . */
public synchronized static KeepAliveManager getInstanceFor ( Connection connection ) { } }

implementation: KeepAliveManager pingManager = instances . get ( connection ) ; if ( pingManager == null ) { pingManager = new KeepAliveManager ( connection ) ; instances . put ( connection , pingManager ) ; } return pingManager ;


signature:
public class KeepAliveManager { /** * Start the executor service if it hasn ' t been started yet . */
private synchronized static void enableExecutorService ( ) { } }

implementation: if ( periodicPingExecutorService == null ) { periodicPingExecutorService = new ScheduledThreadPoolExecutor ( 1 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread pingThread = new Thread ( runnable , "Smack Keepalive" ) ; pingThread . setDaemon ( true ) ; return pingThread ; } } ) ; }


signature:
public class KeepAliveManager { /** * Stop the executor service if all monitored connections are disconnected . */
private synchronized static void handleDisconnect ( Connection con ) { } }

implementation: if ( periodicPingExecutorService != null ) { instances . remove ( con ) ; if ( instances . isEmpty ( ) ) { periodicPingExecutorService . shutdownNow ( ) ; periodicPingExecutorService = null ; } }


signature:
public class KeepAliveManager { /** * Call after every connection to add the packet listener . */
private void handleConnect ( ) { } }

implementation:
Connection connection = weakRefConnection . get ( ) ; // Listen for all incoming packets and reset the scheduled ping whenever
// one arrives .
connection . addPacketListener ( new PacketListener ( ) { @ Override public void processPacket ( Packet packet ) { // reschedule the ping based on this last server contact
lastSuccessfulContact = System . currentTimeMillis ( ) ; schedulePingServerTask ( ) ; } } , null ) ;


signature:
public class KeepAliveManager { /** * Sets the ping interval .
 * @ param pingInterval
 * The new ping time interval in milliseconds . */
public void setPingInterval ( long newPingInterval ) { } }

implementation:
if ( pingInterval == newPingInterval ) return ; // Enable the executor service
if ( newPingInterval > 0 ) enableExecutorService ( ) ; pingInterval = newPingInterval ; if ( pingInterval < 0 ) { stopPinging ( ) ; } else { schedulePingServerTask ( ) ; }


signature:
public class KeepAliveManager { /** * Cancels any existing periodic ping task if there is one and schedules a
 * new ping task if pingInterval is greater then zero .
 * This is designed so only one executor is used for scheduling all pings on
 * all connections . This results in only 1 thread used for pinging . */
private synchronized void schedulePingServerTask ( ) { } }

implementation:
enableExecutorService ( ) ; stopPingServerTask ( ) ; if ( pingInterval > 0 ) { periodicPingTask = periodicPingExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { Ping ping = new Ping ( ) ; PacketFilter responseFilter = new PacketIDFilter ( ping . getID ( ) ) ; Connection connection = weakRefConnection . get ( ) ; final PacketCollector response = pingFailedListeners . isEmpty ( ) ? null : connection . createPacketCollector ( responseFilter ) ; connection . sendPacket ( ping ) ; if ( response != null ) { // Schedule a collector for the ping reply ,
// notify listeners if none is received .
periodicPingExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { Packet result = response . nextResult ( 1 ) ; // Stop queuing results
response . cancel ( ) ; // The actual result of the
// reply can be ignored since we
// only care if we actually got
// one .
if ( result == null ) { for ( PingFailedListener listener : pingFailedListeners ) { listener . pingFailed ( ) ; } } } } , SmackConfiguration . getPacketReplyTimeout ( ) , TimeUnit . MILLISECONDS ) ; } } } , getPingInterval ( ) , TimeUnit . MILLISECONDS ) ; }


signature:
public class ThreadObjectFactory { /** * / * ( non - Javadoc )
 * @ see org . apache . commons . pool . PoolableObjectFactory # makeObject ( ) */
public final Object makeObject ( ) { } }

implementation: log . debug ( " makeObject..." ) ; WorkerThread thread = new WorkerThread ( ) ; initialiseThread ( thread ) ; thread . start ( ) ; return thread ;


signature:
public class ThreadObjectFactory { /** * / * ( non - Javadoc )
 * @ see org . apache . commons . pool . PoolableObjectFactory # destroyObject ( java . lang . Object ) */
public final void destroyObject ( Object obj ) { } }

implementation: log . debug ( " !!! destroyObject... !!!" + obj ) ; if ( obj instanceof WorkerThread ) { WorkerThread rt = ( WorkerThread ) obj ; rt . setStopped ( ) ; }


signature:
public class ThreadObjectFactory { /** * / * ( non - Javadoc )
 * @ see org . apache . commons . pool . PoolableObjectFactory # validateObject ( java . lang . Object ) */
public final boolean validateObject ( Object obj ) { } }

implementation:
log . debug ( " validateObject..." + obj ) ; if ( obj instanceof WorkerThread ) { WorkerThread rt = ( WorkerThread ) obj ; if ( ! rt . isDone ( ) ) { // if the thread is running the previous task , get another one .
return false ; } if ( rt . isRunning ( ) ) { if ( rt . getThreadGroup ( ) == null ) { return false ; } return true ; } } return true ;


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

implementation: V o = super . remove ( key ) ; if ( o instanceof ThreadBound ) { ( ( ThreadBound ) o ) . unbind ( ) ; }


signature:
public class MapCacheImpl { /** * { @ inheritDoc }
 * @ see java . util . HashMap # clear ( ) */
@ Override public void clear ( ) { } }

implementation: for ( String k : super . keySet ( ) ) { Object o = get ( k ) ; if ( o instanceof ThreadBound ) { ( ( ThreadBound ) o ) . unbind ( ) ; } } super . clear ( ) ;


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

implementation: super . remove ( key ) ; if ( ! key . endsWith ( "/" ) ) { key = key + "/" ; } Set < String > keys = super . keySet ( ) ; for ( String k : keys ) { if ( ( k ) . startsWith ( key ) ) { super . remove ( k ) ; } }


signature:
public class ExecS_CliParser { /** * Adds a CLI option to the parser .
 * @ param option new CLI option , ignored if the option is null or getOption ( ) on the option is null
 * @ throws IllegalArgumentException if the option uses short / long options already in use
 * @ return self to allow for chaining */
public ExecS_CliParser addOption ( ApplicationOption < ? > option ) { } }

implementation: if ( option != null && option . getCliOption ( ) != null ) { this . _addOption ( option . getCliOption ( ) ) ; } return this ;


signature:
public class ExecS_CliParser { /** * Adds all given option ignoring null elements .
 * @ param options array of options
 * @ return self to allow for chaining */
public ExecS_CliParser addAllOptions ( ApplicationOption < ? > [ ] options ) { } }

implementation: if ( options != null ) { for ( ApplicationOption < ? > option : options ) { this . addOption ( option ) ; } } return this ;


signature:
public class ExecS_CliParser { /** * Adds a CLI option to the parser .
 * @ param option new CLI option , ignored if the option is null or getOption ( ) on the option is null
 * @ throws IllegalArgumentException if short or long option was in use already */
protected void _addOption ( Option option ) { } }

implementation: if ( option == null ) { return ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { throw new IllegalArgumentException ( "ExecS Cli: short option <" + option . getOpt ( ) + "> already in use" ) ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { throw new IllegalArgumentException ( "ExecS Cli: long option <" + option . getLongOpt ( ) + "> already in use" ) ; } this . options . addOption ( option ) ; if ( option . getOpt ( ) != null ) { this . usedOptions . add ( option . getOpt ( ) ) ; } if ( option . getLongOpt ( ) != null ) { this . usedOptions . add ( option . getLongOpt ( ) ) ; }


signature:
public class ExecS_CliParser { /** * Tests if an option is already added to the parser .
 * @ param option the option to test for
 * @ return false if option was null or n short and long version of this option is used , true otherwise */
public boolean hasOption ( Option option ) { } }

implementation: if ( option == null ) { return false ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { return true ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { return true ; } return false ;


signature:
public class ExecS_CliParser { /** * Parses command line arguments and fills set options .
 * @ param args command line arguments
 * @ return null on success , an exception with message on parsing error */
public ParseException parse ( String [ ] args ) { } }

implementation: ParseException ret = null ; CommandLineParser parser = new DefaultParser ( ) ; try { this . cmdLine = parser . parse ( this . options , args ) ; } catch ( ParseException pe ) { ret = pe ; } return ret ;


signature:
public class ExecS_CliParser { /** * Prints a usage screen based on set options .
 * @ param appName name of the application to be used for the usage screen */
public void usage ( String appName ) { } }

implementation: HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( appName , null , this . options , null , false ) ;


signature:
public class ExecS_CliParser { /** * Parses command line arguments for a given CLI parser .
 * @ param args command line arguments to parse
 * @ param cli CLI object with options to parse for
 * @ param appName application name for error messages
 * @ return 0 on success , - 1 on error with error being logged */
static int doParse ( String [ ] args , ExecS_CliParser cli , String appName ) { } }

implementation: Exception err = cli . parse ( args ) ; if ( err != null ) { System . err . println ( appName + ": error parsing command line -> " + err . getMessage ( ) ) ; return - 1 ; } return 0 ;


signature:
public class XMPPConnection { /** * Closes the connection by setting presence to unavailable then closing the
 * stream to the XMPP server . The shutdown logic will be used during a
 * planned disconnection or when dealing with an unexpected disconnection .
 * Unlike { @ link # disconnect ( ) } the connection ' s packet reader , packet
 * writer , and { @ link UserRoster } will not be removed ; thus connection ' s
 * state is kept .
 * @ param unavailablePresence
 * the presence packet to send during shutdown . */
protected void shutdown ( Presence unavailablePresence ) { } }

implementation:
// Set presence to offline .
if ( packetWriter != null ) { packetWriter . sendPacket ( unavailablePresence ) ; } this . setWasAuthenticated ( authenticated ) ; authenticated = false ; if ( packetReader != null ) { packetReader . shutdown ( ) ; } if ( packetWriter != null ) { packetWriter . shutdown ( ) ; } // Wait 150 ms for processes to clean - up , then shutdown .
try { Thread . sleep ( 150 ) ; } catch ( Exception e ) { // Ignore .
} // Set socketClosed to true . This will cause the PacketReader
// and PacketWriter to ignore any Exceptions that are thrown
// because of a read / write from / to a closed stream .
// It is * important * that this is done before socket . close ( ) !
socketClosed = true ; try { socket . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } for ( Plugin plugin : plugins ) { plugin . shutdown ( ) ; } // In most cases the close ( ) should be successful , so set
// connected to false here .
connected = false ; reader = null ; writer = null ; saslAuthentication . init ( ) ;


signature:
public class XMPPConnection { /** * Initializes the connection by creating a packet reader and writer and
 * opening a XMPP stream to the server .
 * @ throws XMPPException
 * if establishing a connection to the server fails . */
private void initConnection ( ) throws XMPPException { } }

implementation:
boolean isFirstInitialization = packetReader == null || packetWriter == null ; compressionHandler = null ; serverAckdCompression = false ; // Set the reader and writer instance variables
initReaderAndWriter ( ) ; try { if ( isFirstInitialization ) { packetWriter = new PacketWriter ( this ) ; packetReader = new PacketReader ( this ) ; // If debugging is enabled , we should start the thread that will
// listen for
// all packets and then log them .
if ( config . isDebuggerEnabled ( ) ) { addPacketListener ( debugger . getReaderListener ( ) , null ) ; if ( debugger . getWriterListener ( ) != null ) { addPacketSendingListener ( debugger . getWriterListener ( ) , null ) ; } } } else { packetWriter . init ( ) ; packetReader . init ( ) ; } // Start the packet writer . This will open a XMPP stream to the
// server
packetWriter . startup ( ) ; // Start the packet reader . The startup ( ) method will block until we
// get an opening stream packet back from server .
packetReader . startup ( ) ; // Make note of the fact that we ' re now connected .
connected = true ; if ( isFirstInitialization ) { // Notify listeners that a new connection has been established
for ( ConnectionCreationListener listener : getConnectionCreationListeners ( ) ) { listener . connectionCreated ( this ) ; } } } catch ( XMPPException ex ) { // An exception occurred in setting up the connection . Make sure we
// shut down the
// readers and writers and close the socket .
if ( packetWriter != null ) { try { packetWriter . shutdown ( ) ; } catch ( Throwable ignore ) { /* ignore */
} packetWriter = null ; } if ( packetReader != null ) { try { packetReader . shutdown ( ) ; } catch ( Throwable ignore ) { /* ignore */
} packetReader = null ; } if ( reader != null ) { try { reader . close ( ) ; } catch ( Throwable ignore ) { /* ignore */
} reader = null ; } if ( writer != null ) { try { writer . close ( ) ; } catch ( Throwable ignore ) { /* ignore */
} writer = null ; } if ( socket != null ) { try { socket . close ( ) ; } catch ( Exception e ) { /* ignore */
} socket = null ; } this . setWasAuthenticated ( authenticated ) ; authenticated = false ; connected = false ; throw ex ; // Everything stoppped . Now throw the exception .
}


signature:
public class XMPPConnection { /** * Notification message saying that the server supports TLS so confirm the
 * server that we want to secure the connection .
 * @ param required
 * true when the server indicates that TLS is required . */
void startTLSReceived ( boolean required ) { } }

implementation:
if ( required && config . getSecurityMode ( ) == ConnectionConfiguration . SecurityMode . disabled ) { notifyConnectionError ( new IllegalStateException ( "TLS required by server but not allowed by connection configuration" ) ) ; return ; } if ( config . getSecurityMode ( ) == ConnectionConfiguration . SecurityMode . disabled ) { // Do not secure the connection using TLS since TLS was disabled
return ; } try { writer . write ( "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>" ) ; writer . flush ( ) ; } catch ( IOException e ) { notifyConnectionError ( e ) ; }


signature:
public class XMPPConnection { /** * The server has indicated that TLS negotiation can start . We now need to
 * secure the existing plain connection and perform a handshake . This method
 * won ' t return until the connection has finished the handshake or an error
 * occured while securing the connection .
 * @ throws Exception
 * if an exception occurs . */
void proceedTLSReceived ( ) throws Exception { } }

implementation:
SSLContext context = this . config . getCustomSSLContext ( ) ; KeyStore ks = null ; KeyManager [ ] kms = null ; PasswordCallback pcb = null ; if ( config . getCallbackHandler ( ) == null ) { ks = null ; } else if ( context == null ) { if ( config . getKeystoreType ( ) . equals ( "NONE" ) ) { ks = null ; pcb = null ; } else if ( config . getKeystoreType ( ) . equals ( "PKCS11" ) ) { try { Constructor < ? > c = Class . forName ( "sun.security.pkcs11.SunPKCS11" ) . getConstructor ( InputStream . class ) ; String pkcs11Config = "name = SmartCard\nlibrary = " + config . getPKCS11Library ( ) ; ByteArrayInputStream config = new ByteArrayInputStream ( pkcs11Config . getBytes ( ) ) ; Provider p = ( Provider ) c . newInstance ( config ) ; Security . addProvider ( p ) ; ks = KeyStore . getInstance ( "PKCS11" , p ) ; pcb = new PasswordCallback ( "PKCS11 Password: " , false ) ; this . config . getCallbackHandler ( ) . handle ( new Callback [ ] { pcb } ) ; ks . load ( null , pcb . getPassword ( ) ) ; } catch ( Exception e ) { ks = null ; pcb = null ; } } else if ( config . getKeystoreType ( ) . equals ( "Apple" ) ) { ks = KeyStore . getInstance ( "KeychainStore" , "Apple" ) ; ks . load ( null , null ) ; // pcb = new PasswordCallback ( " Apple Keychain " , false ) ;
// pcb . setPassword ( null ) ;
} else { ks = KeyStore . getInstance ( config . getKeystoreType ( ) ) ; try { pcb = new PasswordCallback ( "Keystore Password: " , false ) ; config . getCallbackHandler ( ) . handle ( new Callback [ ] { pcb } ) ; ks . load ( new FileInputStream ( config . getKeystorePath ( ) ) , pcb . getPassword ( ) ) ; } catch ( Exception e ) { ks = null ; pcb = null ; } } KeyManagerFactory kmf = KeyManagerFactory . getInstance ( "SunX509" ) ; try { if ( pcb == null ) { kmf . init ( ks , null ) ; } else { kmf . init ( ks , pcb . getPassword ( ) ) ; pcb . clearPassword ( ) ; } kms = kmf . getKeyManagers ( ) ; } catch ( NullPointerException npe ) { kms = null ; } } // Verify certificate presented by the server
if ( context == null ) { context = SSLContext . getInstance ( "TLS" ) ; context . init ( kms , null , new java . security . SecureRandom ( ) ) ; } Socket plain = socket ; // Secure the plain connection
socket = context . getSocketFactory ( ) . createSocket ( plain , plain . getInetAddress ( ) . getHostAddress ( ) , plain . getPort ( ) , true ) ; socket . setSoTimeout ( 0 ) ; socket . setKeepAlive ( true ) ; // Initialize the reader and writer with the new secured version
initReaderAndWriter ( ) ; // Proceed to do the handshake
( ( SSLSocket ) socket ) . startHandshake ( ) ; // if ( ( ( SSLSocket ) socket ) . getWantClientAuth ( ) ) {
// System . err . println ( " Connection wants client auth " ) ;
// else if ( ( ( SSLSocket ) socket ) . getNeedClientAuth ( ) ) {
// System . err . println ( " Connection needs client auth " ) ;
// else {
// System . err . println ( " Connection does not require client auth " ) ;
// Set that TLS was successful
usingTLS = true ; // Set the new writer to use
packetWriter . setWriter ( writer ) ; // Send a new opening stream to the server
packetWriter . openStream ( ) ;


signature:
public class XMPPConnection { /** * Returns the compression handler that can be used for one compression
 * methods offered by the server .
 * @ return a instance of XMPPInputOutputStream or null if no suitable
 * instance was found */
private XMPPInputOutputStream maybeGetCompressionHandler ( ) { } }

implementation: if ( compressionMethods != null ) { for ( XMPPInputOutputStream handler : compressionHandlers ) { if ( ! handler . isSupported ( ) ) continue ; String method = handler . getCompressionMethod ( ) ; if ( compressionMethods . contains ( method ) ) return handler ; } } return null ;


signature:
public class XMPPConnection { /** * Starts using stream compression that will compress network traffic .
 * Traffic can be reduced up to 90 % . Therefore , stream compression is ideal
 * when using a slow speed network connection . However , the server and the
 * client will need to use more CPU time in order to un / compress network
 * data so under high load the server performance might be affected .
 * Stream compression has to have been previously offered by the server .
 * Currently only the zlib method is supported by the client . Stream
 * compression negotiation has to be done before authentication took place .
 * Note : to use stream compression the smackx . jar file has to be present in
 * the classpath .
 * @ return true if stream compression negotiation was successful . */
private boolean useCompression ( ) { } }

implementation:
// If stream compression was offered by the server and we want to use
// compression then send compression request to the server
if ( authenticated ) { throw new IllegalStateException ( "Compression should be negotiated before authentication." ) ; } if ( ( compressionHandler = maybeGetCompressionHandler ( ) ) != null ) { requestStreamCompression ( compressionHandler . getCompressionMethod ( ) ) ; // Wait until compression is being used or a timeout happened
synchronized ( this ) { try { this . wait ( SmackConfiguration . getPacketReplyTimeout ( ) * 5 ) ; } catch ( InterruptedException e ) { // Ignore .
} } return isUsingCompression ( ) ; } return false ;


signature:
public class XMPPConnection { /** * Request the server that we want to start using stream compression . When
 * using TLS then negotiation of stream compression can only happen after
 * TLS was negotiated . If TLS compression is being used the stream
 * compression should not be used . */
private void requestStreamCompression ( String method ) { } }

implementation: try { writer . write ( "<compress xmlns='http://jabber.org/protocol/compress'>" ) ; writer . write ( "<method>" + method + "</method></compress>" ) ; writer . flush ( ) ; } catch ( IOException e ) { notifyConnectionError ( e ) ; }


signature:
public class XMPPConnection { /** * Start using stream compression since the server has acknowledged stream
 * compression .
 * @ throws Exception
 * if there is an exception starting stream compression . */
void startStreamCompression ( ) throws Exception { } }

implementation:
serverAckdCompression = true ; // Initialize the reader and writer with the new secured version
initReaderAndWriter ( ) ; // Set the new writer to use
packetWriter . setWriter ( writer ) ; // Send a new opening stream to the server
packetWriter . openStream ( ) ; // Notify that compression is being used
synchronized ( this ) { this . notify ( ) ; }


signature:
public class XMPPConnection { /** * Establishes a connection to the XMPP server and performs an automatic
 * login only if the previous connection state was logged ( authenticated ) .
 * It basically creates and maintains a socket connection to the server .
 * Listeners will be preserved from a previous connection if the
 * reconnection occurs after an abrupt termination .
 * @ throws XMPPException
 * if an error occurs while trying to establish the connection .
 * Two possible errors can occur which will be wrapped by an
 * XMPPException - - UnknownHostException ( XMPP error code 504 ) ,
 * and IOException ( XMPP error code 502 ) . The error codes and
 * wrapped exceptions can be used to present more appropriate
 * error messages to end - users . */
public void connect ( ) throws XMPPException { } }

implementation:
// Establishes the connection , readers and writers
connectUsingConfiguration ( config ) ; // Automatically makes the login if the user was previously connected
// successfully
// to the server and the connection was terminated abruptly
if ( connected && wasAuthenticated ) { // Make the login
if ( isAnonymous ( ) ) { // Make the anonymous login
loginAnonymously ( ) ; } else { login ( config . getUsername ( ) , config . getPassword ( ) , config . getResource ( ) ) ; } notifyReconnection ( ) ; }


signature:
public class XMPPConnection { /** * Sends out a notification that there was an error with the connection and
 * closes the connection . Also prints the stack trace of the given exception
 * @ param e
 * the exception that causes the connection close event . */
synchronized void notifyConnectionError ( Exception e ) { } }

implementation:
// Listeners were already notified of the exception , return right here .
if ( ( packetReader == null || packetReader . done ) && ( packetWriter == null || packetWriter . done ) ) return ; if ( packetReader != null ) packetReader . done = true ; if ( packetWriter != null ) packetWriter . done = true ; // Closes the connection temporary . A reconnection is possible
shutdown ( new Presence ( Presence . Type . unavailable ) ) ; // Notify connection listeners of the error .
for ( ConnectionListener listener : getConnectionListeners ( ) ) { try { listener . connectionClosedOnError ( e ) ; } catch ( Exception e2 ) { // Catch and print any exception so we can recover
// from a faulty listener
e2 . printStackTrace ( ) ; } }


signature:
public class XMPPConnection { /** * Sends a notification indicating that the connection was reconnected
 * successfully . */
protected void notifyReconnection ( ) { } }

implementation:
// Notify connection listeners of the reconnection .
for ( ConnectionListener listener : getConnectionListeners ( ) ) { try { listener . reconnectionSuccessful ( ) ; } catch ( Exception e ) { // Catch and print any exception so we can recover
// from a faulty listener
e . printStackTrace ( ) ; } }


signature:
public class SASLAuthentication { /** * Registers a new SASL mechanism
 * @ param name
 * common name of the SASL mechanism . E . g . : PLAIN , DIGEST - MD5 or
 * KERBEROS _ V4.
 * @ param mClass
 * a SASLMechanism subclass . */
public static void registerSASLMechanism ( String name , Class < ? extends SASLMechanism > mClass ) { } }

implementation: implementedMechanisms . put ( name , mClass ) ;


signature:
public class SASLAuthentication { /** * Returns the registerd SASLMechanism classes sorted by the level of
 * preference .
 * @ return the registerd SASLMechanism classes sorted by the level of
 * preference . */
public static List < Class < ? extends SASLMechanism > > getRegisterSASLMechanisms ( ) { } }

implementation: List < Class < ? extends SASLMechanism > > answer = new ArrayList < Class < ? extends SASLMechanism > > ( ) ; for ( String mechanismsPreference : mechanismsPreferences ) { answer . add ( implementedMechanisms . get ( mechanismsPreference ) ) ; } return answer ;


signature:
public class SASLAuthentication { /** * Performs SASL authentication of the specified user . If SASL
 * authentication was successful then resource binding and session
 * establishment will be performed . This method will return the full JID
 * provided by the server while binding a resource to the connection .
 * The server may assign a full JID with a username or resource different
 * than the requested by this method .
 * @ param username
 * the username that is authenticating with the server .
 * @ param resource
 * the desired resource .
 * @ param cbh
 * the CallbackHandler used to get information from the user
 * @ return the full JID provided by the server while binding a resource to
 * the connection .
 * @ throws XMPPException
 * if an error occures while authenticating . */
public String authenticate ( String username , String resource , CallbackHandler cbh ) throws XMPPException { } }

implementation:
// Locate the SASLMechanism to use
String selectedMechanism = null ; for ( String mechanism : mechanismsPreferences ) { if ( implementedMechanisms . containsKey ( mechanism ) && serverMechanisms . contains ( mechanism ) ) { selectedMechanism = mechanism ; break ; } } if ( selectedMechanism != null ) { // A SASL mechanism was found . Authenticate using the selected
// mechanism and then
// proceed to bind a resource
try { Class < ? extends SASLMechanism > mechanismClass = implementedMechanisms . get ( selectedMechanism ) ; Constructor < ? extends SASLMechanism > constructor = mechanismClass . getConstructor ( SASLAuthentication . class ) ; currentMechanism = constructor . newInstance ( this ) ; // Trigger SASL authentication with the selected mechanism . We
// use
// connection . getHost ( ) since GSAPI requires the FQDN of the
// server , which
// may not match the XMPP domain .
currentMechanism . authenticate ( username , connection . getHost ( ) , cbh ) ; // Wait until SASL negotiation finishes
synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 30000 ) ; } catch ( InterruptedException e ) { // Ignore
} } } if ( saslFailed ) { // SASL authentication failed and the server may have closed
// the connection
// so throw an exception
if ( errorCondition != null ) { throw new XMPPException ( "SASL authentication " + selectedMechanism + " failed: " + errorCondition ) ; } else { throw new XMPPException ( "SASL authentication failed using mechanism " + selectedMechanism ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and
return bindResourceAndEstablishSession ( resource ) ; } else { // SASL authentication failed
} } catch ( XMPPException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { throw new XMPPException ( "SASL Authentication failed. No known authentication mechanisims." ) ; } throw new XMPPException ( "SASL authentication failed" ) ;


signature:
public class SASLAuthentication { /** * Performs SASL authentication of the specified user . If SASL
 * authentication was successful then resource binding and session
 * establishment will be performed . This method will return the full JID
 * provided by the server while binding a resource to the connection .
 * The server may assign a full JID with a username or resource different
 * than the requested by this method .
 * @ param username
 * the username that is authenticating with the server .
 * @ param password
 * the password to send to the server .
 * @ param resource
 * the desired resource .
 * @ return the full JID provided by the server while binding a resource to
 * the connection .
 * @ throws XMPPException
 * if an error occures while authenticating . */
public String authenticate ( String username , String password , String resource ) throws XMPPException { } }

implementation:
// Locate the SASLMechanism to use
String selectedMechanism = null ; for ( String mechanism : mechanismsPreferences ) { if ( implementedMechanisms . containsKey ( mechanism ) && serverMechanisms . contains ( mechanism ) ) { selectedMechanism = mechanism ; break ; } } if ( selectedMechanism != null ) { // A SASL mechanism was found . Authenticate using the selected
// mechanism and then
// proceed to bind a resource
try { Class < ? extends SASLMechanism > mechanismClass = implementedMechanisms . get ( selectedMechanism ) ; Constructor < ? extends SASLMechanism > constructor = mechanismClass . getConstructor ( SASLAuthentication . class ) ; currentMechanism = constructor . newInstance ( this ) ; // Trigger SASL authentication with the selected mechanism . We
// use
// connection . getHost ( ) since GSAPI requires the FQDN of the
// server , which
// may not match the XMPP domain .
// The serviceName is basically the value that XMPP server sends
// to the client as being the location
// of the XMPP service we are trying to connect to . This should
// have the format : host [ " / " serv - name ]
// as per RFC - 2831 guidelines
String serviceName = connection . getServiceName ( ) ; currentMechanism . authenticate ( username , connection . getHost ( ) , serviceName , password ) ; // Wait until SASL negotiation finishes
synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 30000 ) ; } catch ( InterruptedException e ) { // Ignore
} } } if ( saslFailed ) { // SASL authentication failed and the server may have closed
// the connection
// so throw an exception
if ( errorCondition != null ) { throw new XMPPException ( "SASL authentication " + selectedMechanism + " failed: " + errorCondition ) ; } else { throw new XMPPException ( "SASL authentication failed using mechanism " + selectedMechanism ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and
return bindResourceAndEstablishSession ( resource ) ; } else { // SASL authentication failed so try a Non - SASL
// authentication
return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } } catch ( XMPPException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; // SASL authentication failed so try a Non - SASL authentication
return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } } else { // No SASL method was found so try a Non - SASL authentication
return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; }


signature:
public class SASLAuthentication { /** * Performs ANONYMOUS SASL authentication . If SASL authentication was
 * successful then resource binding and session establishment will be
 * performed . This method will return the full JID provided by the server
 * while binding a resource to the connection .
 * The server will assign a full JID with a randomly generated resource and
 * possibly with no username .
 * @ return the full JID provided by the server while binding a resource to
 * the connection .
 * @ throws XMPPException
 * if an error occures while authenticating . */
public String authenticateAnonymously ( ) throws XMPPException { } }

implementation:
try { currentMechanism = new SASLAnonymous ( this ) ; currentMechanism . authenticate ( null , null , null , "" ) ; // Wait until SASL negotiation finishes
synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 5000 ) ; } catch ( InterruptedException e ) { // Ignore
} } } if ( saslFailed ) { // SASL authentication failed and the server may have closed the
// connection
// so throw an exception
if ( errorCondition != null ) { throw new XMPPException ( "SASL authentication failed: " + errorCondition ) ; } else { throw new XMPPException ( "SASL authentication failed" ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and
return bindResourceAndEstablishSession ( null ) ; } else { return new NonSASLAuthentication ( connection ) . authenticateAnonymously ( ) ; } } catch ( IOException e ) { return new NonSASLAuthentication ( connection ) . authenticateAnonymously ( ) ; }


signature:
public class SparseMiltonContentResource { /** * = = = = = PROPFIND PROPPATCH Support = = = = = */
public Object getProperty ( QName name ) { } }

implementation: String n = getFullName ( name ) ; Object o = content . getProperty ( n ) ; LOGGER . debug ( "-------------- GETTING {} as {} --------------" , n , o ) ; return o ;


signature:
public class SparseMiltonContentResource { /** * = = = = = LOCK Support = = = = = */
public LockToken createAndLock ( String name , LockTimeout timeout , LockInfo lockInfo ) throws NotAuthorizedException { } }

implementation: LOGGER . debug ( "Create And Lock {} {} " , timeout , lockInfo ) ; try { String newPath = StorageClientUtils . newPath ( path , name ) ; LockHolder lockHolder = new LockHolder ( lockInfo , timeout ) ; String token = session . getLockManager ( ) . lock ( newPath , lockHolder . getTimeoutInSeconds ( ) , lockHolder . toString ( ) ) ; return new LockToken ( token , lockInfo , timeout ) ; } catch ( StorageClientException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new NotAuthorizedException ( this ) ; } catch ( AlreadyLockedException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new NotAuthorizedException ( this ) ; }


signature:
public class EventBehaviourController { /** * this method sets the controls for the Output - Plugin Behaviour .
 * Supply a Function , which controls the OutputPlugin - Behaviour . You can set Priorities .
 * The output - plugin with the highest POSITIVE priority ( in int ) will be processed first . Negative priorities
 * are processed last ( so outputPlugins with no priorities will be processed in between positive and negative
 * priorities )
 * This function returns an HashMap , where the keys represent the associated Behaviour
 * and the values the Identification ;
 * @ param outputPluginBehaviour all the registered outputPlugins */
public void controlOutputPluginBehaviour ( Function < List < Identification > , HashMap < Integer , List < Identification > > > outputPluginBehaviour ) { } }

implementation: this . outputPluginBehaviour = outputPluginBehaviour ;


signature:
public class EventBehaviourController { /** * generates the data to control the Event
 * @ param identifications the Identifications of the OutputPlugins
 * @ return a HashMap , where the keys represent the associated Behaviour and the values the Identification ; */
@ Override public HashMap < Integer , List < Identification > > getOutputPluginBehaviour ( List < Identification > identifications ) { } }

implementation: if ( outputPluginBehaviour == null ) return new HashMap < > ( ) ; return outputPluginBehaviour . apply ( identifications ) ;


signature:
public class NakamuraMain { /** * Define the sling . home parameter implementing the algorithme defined on
 * the wiki page to find the setting according to this algorithm :
 * < ol >
 * < li > Command line option < code > - c < / code > < / li >
 * < li > System property < code > sling . home < / code > < / li >
 * < li > Environment variable < code > SLING _ HOME < / code > < / li >
 * < li > Default value < code > sling < / code > < / li >
 * < / ol >
 * @ param args
 * The command line arguments
 * @ return The value to use for sling . home */
private static String getSlingHome ( Map < String , String > commandLine ) { } }

implementation: String source = null ; String slingHome = commandLine . get ( "c" ) ; if ( slingHome != null ) { source = "command line" ; } else { slingHome = System . getProperty ( SharedConstants . SLING_HOME ) ; if ( slingHome != null ) { source = "system property sling.home" ; } else { slingHome = System . getenv ( ENV_SLING_HOME ) ; if ( slingHome != null ) { source = "environment variable SLING_HOME" ; } else { source = "default" ; slingHome = SharedConstants . SLING_HOME_DEFAULT ; } } } System . setProperty ( SharedConstants . SLING_HOME , slingHome ) ; info ( "Setting sling.home=" + slingHome + " (" + source + ")" , null ) ; return slingHome ;


signature:
public class NakamuraMain { /** * Parses the command line arguments into a map of strings indexed by
 * strings . This method suppports single character option names only at the
 * moment . Each pair of an option name and its value is stored into the map .
 * If a single dash ' - ' character is encountered the rest of the command
 * line are interpreted as option names and are stored in the map unmodified
 * as entries with the same key and value .
 * < table >
 * < tr >
 * < th > Command Line < / th >
 * < th > Mapping < / th >
 * < / tr >
 * < tr >
 * < td > x < / td >
 * < td > x - > x < / td >
 * < / tr >
 * < tr >
 * < td > - y z < / td >
 * < td > y - > z < / td >
 * < / tr >
 * < tr >
 * < td > - yz < / td >
 * < td > y - > z < / td >
 * < / tr >
 * < tr >
 * < td > - y - z < / td >
 * < td > y - > y , z - > z < / td >
 * < / tr >
 * < tr >
 * < td > - y x - - z a < / td >
 * < td > y - > x , - z - > - z , a - > a < / td >
 * < / tr >
 * < / table >
 * @ param args
 * The command line to parse
 * @ return The map of command line options and their values */
static Map < String , String > parseCommandLine ( String [ ] args ) { } }

implementation: Map < String , String > commandLine = new HashMap < String , String > ( ) ; boolean readUnparsed = false ; for ( int argc = 0 ; args != null && argc < args . length ; argc ++ ) { String arg = args [ argc ] ; if ( readUnparsed ) { commandLine . put ( arg , arg ) ; } else if ( arg . startsWith ( "-" ) ) { if ( arg . length ( ) == 1 ) { readUnparsed = true ; } else { String key = String . valueOf ( arg . charAt ( 1 ) ) ; if ( arg . length ( ) > 2 ) { commandLine . put ( key , arg . substring ( 2 ) ) ; } else { argc ++ ; if ( argc < args . length && ( args [ argc ] . equals ( "-" ) || ! args [ argc ] . startsWith ( "-" ) ) ) { commandLine . put ( key , args [ argc ] ) ; } else { commandLine . put ( key , key ) ; argc -- ; } } } } else { commandLine . put ( arg , arg ) ; } } return commandLine ;


signature:
public class NakamuraMain { /** * emit an informational message to standard out */
static void info ( String message , Throwable t ) { } }

implementation: log ( System . out , "*INFO*" , message , t ) ;


signature:
public class NakamuraMain { /** * emit an error message to standard err */
static void error ( String message , Throwable t ) { } }

implementation: log ( System . err , "*ERROR*" , message , t ) ;


signature:
public class NakamuraMain { /** * the throwable if not - null is also prefixed line by line with the prefix */
private static void log ( PrintStream out , String prefix , String message , Throwable t ) { } }

implementation: final StringBuilder linePrefixBuilder = new StringBuilder ( ) ; synchronized ( fmt ) { linePrefixBuilder . append ( fmt . format ( new Date ( ) ) ) ; } linePrefixBuilder . append ( prefix ) ; linePrefixBuilder . append ( " [" ) ; linePrefixBuilder . append ( Thread . currentThread ( ) . getName ( ) ) ; linePrefixBuilder . append ( "] " ) ; final String linePrefix = linePrefixBuilder . toString ( ) ; out . print ( linePrefix ) ; out . println ( message ) ; if ( t != null ) { t . printStackTrace ( new PrintStream ( out ) { @ Override public void println ( String x ) { synchronized ( this ) { print ( linePrefix ) ; super . println ( x ) ; flush ( ) ; } } } ) ; }


signature:
public class StartEvent { /** * creates a new StartEvent .
 * Assumes the Output is using the java - sound output .
 * @ param source the caller
 * @ return the optional StartMusicRequest */
public static Optional < StartEvent > createStartEvent ( Identification source ) { } }

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


signature:
public class StartEvent { /** * creates a new StartEvent
 * @ param source the caller
 * @ param isUsingJava true if using java , false if not ( and for example a C - library )
 * @ return the optional StartMusicRequest */
public static Optional < StartEvent > createStartEvent ( Identification source , boolean isUsingJava ) { } }

implementation: try { StartEvent startEvent ; if ( isUsingJava ) { startEvent = new StartEvent ( source ) ; } else { startEvent = new StartEvent ( source , IS_USING_NON_JAVA_OUTPUT ) ; } return Optional . of ( startEvent ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; }


signature:
public class ObservableWriter { /** * Notify that a new string has been written .
 * @ param str
 * the written String to notify */
private void notifyListeners ( String str ) { } }

implementation: WriterListener [ ] writerListeners = null ; synchronized ( listeners ) { writerListeners = new WriterListener [ listeners . size ( ) ] ; listeners . toArray ( writerListeners ) ; } for ( int i = 0 ; i < writerListeners . length ; i ++ ) { writerListeners [ i ] . write ( str ) ; }


signature:
public class ListResourceProviderImpl { /** * checks whether it can provide the resource
 * @ param resource the resource to provide
 * @ return true if the container can provide the resource */
@ Override public boolean providesResource ( ResourceModel resource ) { } }

implementation: return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourceS -> resourceS . equals ( resource . getResourceID ( ) ) ) ;


signature:
public class ListResourceProviderImpl { /** * checks whether there are any resources registered from the source
 * @ param sourceID the ID of the source
 * @ return true if the container has resources from the source */
@ Override public boolean containsResourcesFromSource ( String sourceID ) { } }

implementation: return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( source -> source . equals ( sourceID ) ) ;


signature:
public class ListResourceProviderImpl { /** * checks whether the ResourceContainer can provide at least ONE resource
 * @ param resourcesIDs a list containing sources
 * @ return true if the ResourceContainer can provide at least one resource */
@ Override public boolean providesResource ( List < String > resourcesIDs ) { } }

implementation: return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourcesIDs :: contains ) ;


signature:
public class ListResourceProviderImpl { /** * returns all EXISTING resources for the ID .
 * If there are no resources for the ID the ID will get skipped
 * @ param resourceIDs an Array containing the resources
 * @ return a list of resources found */
@ Override public List < ResourceModel > provideResource ( String [ ] resourceIDs ) { } }

implementation: return resources . stream ( ) . filter ( resource -> Arrays . stream ( resourceIDs ) . anyMatch ( resourceID -> resourceID . equals ( resource . getResourceID ( ) ) ) ) . collect ( Collectors . toList ( ) ) ;


signature:
public class ListResourceProviderImpl { /** * returns the resource ( if existing ) from the source
 * @ param sourceID the ID of the source
 * @ return a list containing all the found resources */
@ Override public List < ResourceModel > provideResourceFromSource ( String sourceID ) { } }

implementation: return resources . stream ( ) . filter ( resource -> resource . getProvider ( ) . getID ( ) . equals ( sourceID ) ) . collect ( Collectors . toList ( ) ) ;


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

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


signature:
public class CachingManagerImpl { /** * Try to retrieve an object from the cache . Has the side - effect of loading
 * an uncached object into cache the first time .
 * @ param keySpace
 * the key space we ' re operating in .
 * @ param columnFamily
 * the column family for the object
 * @ param key
 * the object key
 * @ return the object or null if not cached and not found
 * @ throws StorageClientException */
protected Map < String , Object > getCached ( String keySpace , String columnFamily , String key ) throws StorageClientException { } }

implementation: Map < String , Object > m = null ; String cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; CacheHolder cacheHolder = getFromCacheInternal ( cacheKey ) ; if ( cacheHolder != null ) { m = cacheHolder . get ( ) ; if ( m != null ) { LOGGER . debug ( "Cache Hit {} {} {} " , new Object [ ] { cacheKey , cacheHolder , m } ) ; } } if ( m == null ) { m = client . get ( keySpace , columnFamily , key ) ; if ( m != null ) { LOGGER . debug ( "Cache Miss, Found Map {} {}" , cacheKey , m ) ; } putToCacheInternal ( cacheKey , new CacheHolder ( m ) , true ) ; } return m ;


signature:
public class CachingManagerImpl { /** * Combine the parameters into a key suitable for storage and lookup in the
 * cache .
 * @ param keySpace
 * @ param columnFamily
 * @ param key
 * @ return the cache key
 * @ throws StorageClientException */
private String getCacheKey ( String keySpace , String columnFamily , String key ) throws StorageClientException { } }

implementation: if ( client instanceof RowHasher ) { return ( ( RowHasher ) client ) . rowHash ( keySpace , columnFamily , key ) ; } return keySpace + ":" + columnFamily + ":" + key ;


signature:
public class CachingManagerImpl { /** * Remove this object from the cache . Note , StorageClient uses the word
 * remove to mean delete . This method should do the same .
 * @ param keySpace
 * @ param columnFamily
 * @ param key
 * @ throws StorageClientException */
protected void removeCached ( String keySpace , String columnFamily , String key ) throws StorageClientException { } }

implementation:
if ( sharedCache != null ) { // insert a replacement . This should cause an invalidation message
// to propagate in the cluster .
final String cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; putToCacheInternal ( cacheKey , new CacheHolder ( null , managerId ) , false ) ; LOGGER . debug ( "Marked as deleted in Cache {} " , cacheKey ) ; if ( client instanceof Disposer ) { // we might want to change this to register the action as a
// commit handler rather than a disposable .
// it depends on if we think the delete is a transactional thing
// or a operational cache thing .
// at the moment , I am leaning towards an operational cache
// thing , since regardless of if
// the session commits or not , we want this to dispose when the
// session is closed , or commits .
( ( Disposer ) client ) . registerDisposable ( new Disposable ( ) { @ Override public void setDisposer ( Disposer disposer ) { } @ Override public void close ( ) { CacheHolder ch = sharedCache . get ( cacheKey ) ; if ( ch != null && ch . wasLockedTo ( managerId ) ) { sharedCache . remove ( cacheKey ) ; LOGGER . debug ( "Removed deleted marker from Cache {} " , cacheKey ) ; } } } ) ; } } client . remove ( keySpace , columnFamily , key ) ;


signature:
public class CachingManagerImpl { /** * Put an object in the cache
 * @ param keySpace
 * @ param columnFamily
 * @ param key
 * @ param encodedProperties
 * the object to be stored
 * @ param probablyNew
 * whether or not this object is new .
 * @ throws StorageClientException */
protected void putCached ( String keySpace , String columnFamily , String key , Map < String , Object > encodedProperties , boolean probablyNew ) throws StorageClientException { } }

implementation:
String cacheKey = null ; if ( sharedCache != null ) { cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; } if ( sharedCache != null && ! probablyNew ) { CacheHolder ch = getFromCacheInternal ( cacheKey ) ; if ( ch != null && ch . isLocked ( this . managerId ) ) { LOGGER . debug ( "Is Locked {} " , ch ) ; return ; // catch the case where another method creates while
// something is in the cache .
// this is a big assumption since if the item is not in the
// cache it will get updated
// there is no difference in sparsemap between create and
// update , they are all insert operations
// what we are really saying here is that inorder to update the
// item you have to have just got it
// and if you failed to get it , your update must have been a
// create operation . As long as the dwell time
// in the cache is longer than the lifetime of an active session
// then this will be true .
// if the lifetime of an active session is longer ( like with a
// long running background operation )
// then you should expect to see race conditions at this point
// since the marker in the cache will have
// gone , and the marker in the database has gone , so the put
// operation , must be a create operation .
// To change this behavior we would need to differentiate more
// strongly between new and update and change
// probablyNew into certainlyNew , but that would probably break
// the BASIC assumption of the whole system .
// Update 2011-12-06 related to issue 136
// I am not certain this code is correct . What happens if the
// session wants to remove and then add items .
// the session will never get past this point , since sitting in
// the cache is a null CacheHolder preventing the session
// removing then adding .
// also , how long should the null cache holder be placed in
// there for ?
// I think the solution is to bind the null Cache holder to the
// instance of the caching manager that created it ,
// let the null Cache holder last for 10s , and during that time
// only the CachingManagerImpl that created it can remove it .
} } LOGGER . debug ( "Saving {} {} {} {} " , new Object [ ] { keySpace , columnFamily , key , encodedProperties } ) ; client . insert ( keySpace , columnFamily , key , encodedProperties , probablyNew ) ; if ( sharedCache != null ) { // if we just added a value in , remove the key so that any stale
// state ( including a previously deleted object is removed )
sharedCache . remove ( cacheKey ) ; }


signature:
public class CF_Locator { /** * 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_Locator setJarFilter ( List < String > jarFilter ) { } }

implementation: this . jarFilter . clear ( ) ; if ( jarFilter != null ) { this . jarFilter . addAll ( jarFilter ) ; } this . needsReRun = true ; return this ;


signature:
public class CF_Locator { /** * Runs the locator and collects all locations using the filters if set .
 * The method can be called multiple times and will only result in a new map if any of the filters have been changed .
 * If no filter has been changed , the current map will be returned .
 * @ return returns a map with all found locations , empty if none found */
public Map < URI , String > getCfLocations ( ) { } }

implementation: if ( this . needsReRun == true ) { this . locationMap . clear ( ) ; String pathSep = System . getProperty ( "path.separator" ) ; String classpath = System . getProperty ( "java.class.path" ) ; StringTokenizer st = new StringTokenizer ( classpath , pathSep ) ; File file = null ; while ( st . hasMoreTokens ( ) ) { String path = st . nextToken ( ) ; file = new File ( path ) ; this . include ( file ) ; } } this . needsReRun = false ; return this . locationMap ;


signature:
public class CF_Locator { /** * Include a name and file
 * @ param name name to be included , if null will be set to empty
 * @ param file file to be included */
protected final void include ( String name , File file ) { } }

implementation: if ( ! file . exists ( ) ) { return ; } if ( ! file . isDirectory ( ) ) { if ( this . jarFilter . size ( ) > 0 ) { boolean ok = false ; for ( String s : this . jarFilter ) { if ( file . getName ( ) . startsWith ( s ) ) { ok = true ; } } if ( ok == false ) { return ; } } this . includeJar ( file ) ; return ; } if ( name == null ) { name = "" ; } else { name += "." ; } File [ ] dirs = file . listFiles ( CF_Utils . DIRECTORIES_ONLY ) ; for ( int i = 0 ; i < dirs . length ; i ++ ) { try { this . locationMap . put ( new URI ( "file://" + dirs [ i ] . getCanonicalPath ( ) ) , name + dirs [ i ] . getName ( ) ) ; } catch ( IOException ignore ) { return ; } catch ( URISyntaxException ignore ) { return ; } this . include ( name + dirs [ i ] . getName ( ) , dirs [ i ] ) ; }


signature:
public class CF_Locator { /** * Include from a jar file
 * @ param file jar file */
private void includeJar ( File file ) { } }

implementation: if ( file . isDirectory ( ) ) { return ; } URL jarURL = null ; JarFile jar = null ; try { jarURL = new URL ( "jar:" + new URL ( "file:/" + file . getCanonicalPath ( ) ) . toExternalForm ( ) + "!/" ) ; JarURLConnection conn = ( JarURLConnection ) jarURL . openConnection ( ) ; jar = conn . getJarFile ( ) ; } catch ( MalformedURLException ignore ) { return ; } catch ( IOException ignore ) { return ; } if ( jar == null ) { return ; } try { this . locationMap . put ( jarURL . toURI ( ) , "" ) ; } catch ( URISyntaxException ignore ) { } for ( Enumeration < JarEntry > e = jar . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry entry = e . nextElement ( ) ; if ( this . pkgFilter != null && entry . getName ( ) . startsWith ( this . pkgFilter ) ) { continue ; } if ( entry . isDirectory ( ) ) { if ( entry . getName ( ) . toUpperCase ( Locale . ENGLISH ) . equals ( "META-INF/" ) ) { continue ; } try { this . locationMap . put ( new URI ( jarURL . toExternalForm ( ) + entry . getName ( ) ) , CF_Utils . getPkgName ( entry ) ) ; } catch ( URISyntaxException ignore ) { continue ; } } }


signature:
public class SmackConfiguration { /** * Add a SASL mechanism to the list to be used .
 * @ param mech
 * the SASL mechanism to be added */
public static void addSaslMech ( String mech ) { } }

implementation: initialize ( ) ; if ( ! defaultMechs . contains ( mech ) ) { defaultMechs . add ( mech ) ; }