signature:
public class SocializeLaunchManager { /** * / * ( non - Javadoc )
 * @ see com . socialize . launcher . LaunchManager # getLaucher ( java . lang . String ) */
@ Override public Launcher getLaucher ( String action ) { } }

implementation: try { return getLaucher ( LaunchAction . valueOf ( action ) ) ; } catch ( Exception e ) { if ( logger != null ) { logger . error ( "Launch action [" + action + "] provided is not a known action" , e ) ; } else { SocializeLogger . e ( e . getMessage ( ) , e ) ; } return null ; }


signature:
public class SocializeLaunchManager { /** * / * ( non - Javadoc )
 * @ see com . socialize . launcher . LaunchManager # getLaucher ( com . socialize . launcher . LaunchAction ) */
@ Override public Launcher getLaucher ( LaunchAction action ) { } }

implementation: if ( launchers != null ) { return launchers . get ( action . name ( ) ) ; } return null ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isActivityAvailable ( android . content . Context , java . lang . Class ) */
@ Override public boolean isActivityAvailable ( Context context , Class < ? > activity ) { } }

implementation: Intent intent = new Intent ( context , activity ) ; return isIntentAvailable ( context , intent ) ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isIntentAvailable ( android . content . Context , java . lang . String ) */
@ Override public boolean isIntentAvailable ( Context context , String action ) { } }

implementation: Intent intent = new Intent ( action ) ; return isIntentAvailable ( context , intent ) ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isIntentAvailable ( android . content . Context , android . content . Intent ) */
@ Override public boolean isIntentAvailable ( Context context , Intent intent ) { } }

implementation: PackageManager packageManager = context . getPackageManager ( ) ; return packageManager . queryIntentActivities ( intent , PackageManager . MATCH_DEFAULT_ONLY ) . size ( ) > 0 ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isServiceAvailable ( android . content . Context , java . lang . Class ) */
@ Override public boolean isServiceAvailable ( Context context , Class < ? > cls ) { } }

implementation: final PackageManager packageManager = context . getPackageManager ( ) ; final Intent intent = new Intent ( context , cls ) ; return packageManager . queryIntentServices ( intent , PackageManager . MATCH_DEFAULT_ONLY ) . size ( ) > 0 ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isReceiverAvailable ( android . content . Context , java . lang . Class ) */
@ Override public boolean isReceiverAvailable ( Context context , Class < ? > cls ) { } }

implementation: final PackageManager packageManager = context . getPackageManager ( ) ; final Intent intent = new Intent ( context , cls ) ; return packageManager . queryBroadcastReceivers ( intent , PackageManager . MATCH_DEFAULT_ONLY ) . size ( ) > 0 ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isLocationAvaiable ( android . content . Context ) */
@ Override public boolean isLocationAvailable ( Context context ) { } }

implementation: if ( ! locationAssessed && config != null ) { locationAvailable = config . getBooleanProperty ( SocializeConfig . SOCIALIZE_LOCATION_ENABLED , true ) && ( hasPermission ( context , "android.permission.ACCESS_FINE_LOCATION" ) || hasPermission ( context , "android.permission.ACCESS_COARSE_LOCATION" ) ) ; locationAssessed = true ; } return locationAvailable ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # isNotificationsAvaiable ( android . content . Context ) */
@ Override public boolean isNotificationsAvailable ( Context context ) { } }

implementation: if ( ! notificationsAssessed ) { String permissionString = context . getPackageName ( ) + ".permission.C2D_MESSAGE" ; boolean ok = true ; if ( config . getBooleanProperty ( SocializeConfig . SOCIALIZE_NOTIFICATIONS_ENABLED , true ) ) { if ( ! hasPermission ( context , permissionString ) ) { lastNotificationWarning = "Notifications not available, permission [" + permissionString + "] not specified in AndroidManifest.xml" ; if ( logger . isInfoEnabled ( ) ) logger . info ( lastNotificationWarning ) ; ok = false ; } if ( ! hasPermission ( context , "com.google.android.c2dm.permission.RECEIVE" ) ) { lastNotificationWarning = "Notifications not available, permission com.google.android.c2dm.permission.RECEIVE not specified in AndroidManifest.xml, or device does not include Google APIs" ; if ( logger . isInfoEnabled ( ) ) logger . info ( lastNotificationWarning ) ; ok = false ; } if ( config . isEntityLoaderCheckEnabled ( ) && getSocialize ( ) . getEntityLoader ( ) == null ) { lastNotificationWarning = "Notifications not available. Entity loader not found." ; if ( logger . isInfoEnabled ( ) ) logger . info ( lastNotificationWarning ) ; ok = false ; } } else { ok = false ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "SmartAlerts disabled in config" ) ; } } notificationsAvailable = ok ; notificationsAssessed = true ; } else if ( ! notificationsAvailable ) { if ( lastNotificationWarning != null && logger . isInfoEnabled ( ) ) { logger . info ( lastNotificationWarning ) ; } } return notificationsAvailable ;


signature:
public class DefaultAppUtils { /** * / * ( non - Javadoc )
 * @ see com . socialize . util . IAppUtils # hasPermission ( android . content . Context , java . lang . String ) */
@ Override public boolean hasPermission ( Context context , String permission ) { } }

implementation: return context . getPackageManager ( ) . checkPermission ( permission , context . getPackageName ( ) ) == PackageManager . PERMISSION_GRANTED ;


signature:
public class SocializeActivitySystem { /** * ( non - Javadoc )
 * @ see com . socialize . api . action . ActivitySystem # getAction ( com . socialize . api . SocializeSession , long , com . socialize . api . action . ActionType ) */
@ Override public SocializeAction getAction ( SocializeSession session , long id , ActionType type ) throws SocializeException { } }

implementation: String endpoint = null ; switch ( type ) { case COMMENT : endpoint = CommentSystem . ENDPOINT ; break ; case LIKE : endpoint = LikeSystem . ENDPOINT ; break ; case SHARE : endpoint = ShareSystem . ENDPOINT ; break ; case VIEW : endpoint = ViewSystem . ENDPOINT ; break ; } return get ( session , endpoint , String . valueOf ( id ) , type ) ;


signature:
public class SocializeActivitySystem { /** * ( non - Javadoc )
 * @ see com . socialize . api . action . activity . ActivitySystem # getActivityByUser ( com . socialize . api . SocializeSession , long , com . socialize . listener . activity . ActionListener ) */
@ Override public void getActivityByUser ( SocializeSession session , long id , ActionListener listener ) { } }

implementation: String userId = String . valueOf ( id ) ; String endpoint = getEndpoint ( userId ) ; listAsync ( session , endpoint , listener ) ;


signature:
public class LikeButtonSnippets { /** * begin - snippet - 0 */
@ Override protected void onCreate ( Bundle savedInstanceState ) { } }

implementation:
super . onCreate ( savedInstanceState ) ; // Define / obtain your entity
Entity entity = Entity . newInstance ( "http://getsocialize.com" , "Socialize" ) ; // Get a reference to the button you want to transform
// This can be any type of CompoundButton ( CheckBox , RadioButton , Switch , ToggleButton )
CheckBox btnCustomCheckBoxLike = ( CheckBox ) findViewById ( R . id . btnCustomCheckBoxLike ) ; // Make the button a socialize like button !
LikeUtils . makeLikeButton ( this , btnCustomCheckBoxLike , entity , new LikeButtonListener ( ) { @ Override public void onClick ( CompoundButton button ) { // You can use this callback to set any loading text or display a progress dialog
button . setText ( "--" ) ; } @ Override public void onCheckedChanged ( CompoundButton button , boolean isChecked ) { // The like was posted successfully , change the button to reflect the change
if ( isChecked ) { button . setText ( "Unlike" ) ; } else { button . setText ( "Like" ) ; } } @ Override public void onError ( CompoundButton button , Exception error ) { // An error occurred posting the like , we need to return the button to its original state
Log . e ( "Socialize" , "Error on like button" , error ) ; if ( button . isChecked ( ) ) { button . setText ( "Unlike" ) ; } else { button . setText ( "Like" ) ; } } } ) ;


signature:
public class GetAllEntitiesActivity { /** * / * ( non - Javadoc )
 * @ see com . socialize . demo . DemoActivity # executeDemo ( ) */
@ Override public void executeDemo ( String text ) { } }

implementation: EntityUtils . getEntities ( this , 0 , PAGE_SIZE , new EntityListListener ( ) { @ Override public void onList ( ListResult < Entity > entities ) { handleBasicSocializeResult ( entities ) ; } @ Override public void onError ( SocializeException error ) { handleError ( GetAllEntitiesActivity . this , error ) ; } } ) ;


signature:
public class OAuth { /** * Construct a x - www - form - urlencoded document containing the given sequence
 * of name / value pairs . Use OAuth percent encoding ( not exactly the encoding
 * mandated by x - www - form - urlencoded ) . */
public static < T extends Map . Entry < String , String > > void formEncode ( Collection < T > parameters , OutputStream into ) throws IOException { } }

implementation: if ( parameters != null ) { boolean first = true ; for ( Map . Entry < String , String > entry : parameters ) { if ( first ) { first = false ; } else { into . write ( '&' ) ; } into . write ( percentEncode ( safeToString ( entry . getKey ( ) ) ) . getBytes ( ) ) ; into . write ( '=' ) ; into . write ( percentEncode ( safeToString ( entry . getValue ( ) ) ) . getBytes ( ) ) ; } }


signature:
public class OAuth { /** * Construct a x - www - form - urlencoded document containing the given sequence
 * of name / value pairs . Use OAuth percent encoding ( not exactly the encoding
 * mandated by x - www - form - urlencoded ) . */
public static < T extends Map . Entry < String , String > > String formEncode ( Collection < T > parameters ) throws IOException { } }

implementation: ByteArrayOutputStream b = new ByteArrayOutputStream ( ) ; formEncode ( parameters , b ) ; return new String ( b . toByteArray ( ) ) ;


signature:
public class OAuth { /** * Parse a form - urlencoded document . */
public static HttpParameters decodeForm ( String form ) { } }

implementation: HttpParameters params = new HttpParameters ( ) ; if ( isEmpty ( form ) ) { return params ; } for ( String nvp : form . split ( "\\&" ) ) { int equals = nvp . indexOf ( '=' ) ; String name ; String value ; if ( equals < 0 ) { name = percentDecode ( nvp ) ; value = null ; } else { name = percentDecode ( nvp . substring ( 0 , equals ) ) ; value = percentDecode ( nvp . substring ( equals + 1 ) ) ; } params . put ( name , value ) ; } return params ;


signature:
public class OAuth { /** * Construct a Map containing a copy of the given parameters . If several
 * parameters have the same name , the Map will contain the first value ,
 * only . */
public static < T extends Map . Entry < String , String > > Map < String , String > toMap ( Collection < T > from ) { } }

implementation: HashMap < String , String > map = new HashMap < String , String > ( ) ; if ( from != null ) { for ( Map . Entry < String , String > entry : from ) { String key = entry . getKey ( ) ; if ( ! map . containsKey ( key ) ) { map . put ( key , entry . getValue ( ) ) ; } } } return map ;


signature:
public class OAuth { /** * Appends a list of key / value pairs to the given URL , e . g . :
 * < pre >
 * String url = OAuth . addQueryParameters ( & quot ; http : / / example . com ? a = 1 & quot ; , b , 2 , c , 3 ) ;
 * < / pre >
 * which yields :
 * < pre >
 * http : / / example . com ? a = 1 & b = 2 & c = 3
 * < / pre >
 * All parameters will be encoded according to OAuth ' s percent encoding
 * rules .
 * @ param url
 * the URL
 * @ param kvPairs
 * the list of key / value pairs
 * @ return */
public static String addQueryParameters ( String url , String ... kvPairs ) { } }

implementation: String queryDelim = url . contains ( "?" ) ? "&" : "?" ; StringBuilder sb = new StringBuilder ( url + queryDelim ) ; for ( int i = 0 ; i < kvPairs . length ; i += 2 ) { if ( i > 0 ) { sb . append ( "&" ) ; } sb . append ( OAuth . percentEncode ( kvPairs [ i ] ) + "=" + OAuth . percentEncode ( kvPairs [ i + 1 ] ) ) ; } return sb . toString ( ) ;


signature:
public class OAuth { /** * Builds an OAuth header from the given list of header fields . All
 * parameters starting in ' oauth _ * ' will be percent encoded .
 * < pre >
 * String authHeader = OAuth . prepareOAuthHeader ( & quot ; realm & quot ; , & quot ; http : / / example . com & quot ; , & quot ; oauth _ token & quot ; , & quot ; x % y & quot ; ) ;
 * < / pre >
 * which yields :
 * < pre >
 * OAuth realm = " http : / / example . com " , oauth _ token = " x % 25y "
 * < / pre >
 * @ param kvPairs
 * the list of key / value pairs
 * @ return a string eligible to be used as an OAuth HTTP Authorization
 * header . */
public static String prepareOAuthHeader ( String ... kvPairs ) { } }

implementation: StringBuilder sb = new StringBuilder ( "OAuth " ) ; for ( int i = 0 ; i < kvPairs . length ; i += 2 ) { if ( i > 0 ) { sb . append ( ", " ) ; } String value = kvPairs [ i ] . startsWith ( "oauth_" ) ? OAuth . percentEncode ( kvPairs [ i + 1 ] ) : kvPairs [ i + 1 ] ; sb . append ( OAuth . percentEncode ( kvPairs [ i ] ) + "=\"" + value + "\"" ) ; } return sb . toString ( ) ;


signature:
public class OAuth { /** * Helper method to concatenate a parameter and its value to a pair that can
 * be used in an HTTP header . This method percent encodes both parts before
 * joining them .
 * @ param name
 * the OAuth parameter name , e . g . oauth _ token
 * @ param value
 * the OAuth parameter value , e . g . ' hello oauth '
 * @ return a name / value pair , e . g . oauth _ token = " hello % 20oauth " */
public static String toHeaderElement ( String name , String value ) { } }

implementation: return OAuth . percentEncode ( name ) + "=\"" + OAuth . percentEncode ( value ) + "\"" ;


signature:
public class Preconditions { /** * Ensures that an { @ code Iterable } object passed as a parameter to the
 * calling method is not null and contains no null elements .
 * @ param iterable the iterable to check the contents of
 * @ return the non - null { @ code iterable } reference just validated
 * @ throws NullPointerException if { @ code iterable } is null or contains at
 * least one null element */
public static < T extends Iterable < ? > > T checkContentsNotNull ( T iterable ) { } }

implementation: if ( containsOrIsNull ( iterable ) ) { throw new NullPointerException ( ) ; } return iterable ;


signature:
public class Preconditions { /** * Ensures that an { @ code Iterable } object passed as a parameter to the
 * calling method is not null and contains no null elements .
 * @ param iterable the iterable to check the contents of
 * @ param errorMessage the exception message to use if the check fails ; will
 * be converted to a string using { @ link String # valueOf ( Object ) }
 * @ return the non - null { @ code iterable } reference just validated
 * @ throws NullPointerException if { @ code iterable } is null or contains at
 * least one null element */
public static < T extends Iterable < ? > > T checkContentsNotNull ( T iterable , Object errorMessage ) { } }

implementation: if ( containsOrIsNull ( iterable ) ) { throw new NullPointerException ( String . valueOf ( errorMessage ) ) ; } return iterable ;


signature:
public class Preconditions { /** * Ensures that an { @ code Iterable } object passed as a parameter to the
 * calling method is not null and contains no null elements .
 * @ param iterable the iterable to check the contents of
 * @ param errorMessageTemplate a template for the exception message should the
 * check fail . The message is formed by replacing each { @ code % s }
 * placeholder in the template with an argument . These are matched by
 * position - the first { @ code % s } gets { @ code errorMessageArgs [ 0 ] } , etc .
 * Unmatched arguments will be appended to the formatted message in square
 * braces . Unmatched placeholders will be left as - is .
 * @ param errorMessageArgs the arguments to be substituted into the message
 * template . Arguments are converted to strings using
 * { @ link String # valueOf ( Object ) } .
 * @ return the non - null { @ code iterable } reference just validated
 * @ throws NullPointerException if { @ code iterable } is null or contains at
 * least one null element */
public static < T extends Iterable < ? > > T checkContentsNotNull ( T iterable , String errorMessageTemplate , Object ... errorMessageArgs ) { } }

implementation: if ( containsOrIsNull ( iterable ) ) { throw new NullPointerException ( format ( errorMessageTemplate , errorMessageArgs ) ) ; } return iterable ;


signature:
public class Preconditions { /** * Ensures that { @ code index } specifies a valid < i > element < / i > in an array ,
 * list or string of size { @ code size } . An element index may range from zero ,
 * inclusive , to { @ code size } , exclusive .
 * @ param index a user - supplied index identifying an element of an array , list
 * or string
 * @ param size the size of that array , list or string
 * @ param desc the text to use to describe this index in an error message
 * @ throws IndexOutOfBoundsException if { @ code index } is negative or is not
 * less than { @ code size }
 * @ throws IllegalArgumentException if { @ code size } is negative */
public static void checkElementIndex ( int index , int size , String desc ) { } }

implementation: checkArgument ( size >= 0 , "negative size: %s" , size ) ; if ( index < 0 ) { throw new IndexOutOfBoundsException ( format ( "%s (%s) must not be negative" , desc , index ) ) ; } if ( index >= size ) { throw new IndexOutOfBoundsException ( format ( "%s (%s) must be less than size (%s)" , desc , index , size ) ) ; }


signature:
public class Preconditions { /** * Ensures that { @ code index } specifies a valid < i > position < / i > in an array ,
 * list or string of size { @ code size } . A position index may range from zero
 * to { @ code size } , inclusive .
 * @ param index a user - supplied index identifying a position in an array , list
 * or string
 * @ param size the size of that array , list or string
 * @ param desc the text to use to describe this index in an error message
 * @ throws IndexOutOfBoundsException if { @ code index } is negative or is
 * greater than { @ code size }
 * @ throws IllegalArgumentException if { @ code size } is negative */
public static void checkPositionIndex ( int index , int size , String desc ) { } }

implementation: checkArgument ( size >= 0 , "negative size: %s" , size ) ; if ( index < 0 ) { throw new IndexOutOfBoundsException ( format ( "%s (%s) must not be negative" , desc , index ) ) ; } if ( index > size ) { throw new IndexOutOfBoundsException ( format ( "%s (%s) must not be greater than size (%s)" , desc , index , size ) ) ; }


signature:
public class Preconditions { /** * Ensures that { @ code start } and { @ code end } specify a valid < i > positions < / i >
 * in an array , list or string of size { @ code size } , and are in order . A
 * position index may range from zero to { @ code size } , inclusive .
 * @ param start a user - supplied index identifying a starting position in an
 * array , list or string
 * @ param end a user - supplied index identifying a ending position in an array ,
 * list or string
 * @ param size the size of that array , list or string
 * @ throws IndexOutOfBoundsException if either index is negative or is
 * greater than { @ code size } , or if { @ code end } is less than { @ code start }
 * @ throws IllegalArgumentException if { @ code size } is negative */
public static void checkPositionIndexes ( int start , int end , int size ) { } }

implementation: checkPositionIndex ( start , size , "start index" ) ; checkPositionIndex ( end , size , "end index" ) ; if ( end < start ) { throw new IndexOutOfBoundsException ( format ( "end index (%s) must not be less than start index (%s)" , end , start ) ) ; }


signature:
public class GetActionsByUserEntityActivity { /** * / * ( non - Javadoc )
 * @ see com . socialize . demo . DemoActivity # executeDemo ( ) */
@ Override public void executeDemo ( String text ) { } }

implementation: try { ActionUtils . getActionsByUserAndEntity ( this , UserUtils . getCurrentUser ( this ) . getId ( ) , entity . getKey ( ) , 0 , PAGE_SIZE , new ActionListListener ( ) { @ Override public void onList ( ListResult < SocializeAction > result ) { handleSocializeResult ( result ) ; } @ Override public void onError ( SocializeException error ) { handleError ( GetActionsByUserEntityActivity . this , error ) ; } } ) ; } catch ( SocializeException e ) { e . printStackTrace ( ) ; }


signature:
public class SubscriptionFactory { /** * / * ( non - Javadoc )
 * @ see com . socialize . entity . SocializeObjectFactory # postFromJSON ( org . json . JSONObject , com . socialize . entity . SocializeObject ) */
@ Override protected void postFromJSON ( JSONObject from , Subscription to ) throws JSONException { } }

implementation: try { if ( from . has ( "user" ) && ! from . isNull ( "user" ) ) { JSONObject user = from . getJSONObject ( "user" ) ; if ( user != null ) { to . setUser ( userFactory . fromJSON ( user ) ) ; } } if ( from . has ( "entity" ) && ! from . isNull ( "entity" ) ) { JSONObject entity = from . getJSONObject ( "entity" ) ; if ( entity != null ) { to . setEntity ( entityFactory . fromJSON ( entity ) ) ; } } if ( from . has ( "subscribed" ) && ! from . isNull ( "subscribed" ) ) { to . setSubscribed ( from . getBoolean ( "subscribed" ) ) ; } if ( from . has ( "date" ) && ! from . isNull ( "date" ) ) { try { to . setDate ( DATE_FORMAT . parse ( from . getString ( "date" ) ) . getTime ( ) ) ; } catch ( ParseException e ) { if ( logger != null && logger . isWarnEnabled ( ) ) { logger . warn ( "Could not parse date [" + from . getString ( "date" ) + "] using format [" + DATE_FORMAT_STRING + "]" ) ; } } } if ( from . has ( "type" ) && ! from . isNull ( "type" ) ) { try { to . setNotificationType ( NotificationType . valueOf ( from . getString ( "type" ) . toUpperCase ( ) ) ) ; } catch ( Exception e ) { if ( logger != null && logger . isWarnEnabled ( ) ) { logger . warn ( "Could not parse type [" + from . getString ( "type" ) + "] into " + NotificationType . class . getName ( ) ) ; } } } } catch ( Throwable e ) { throw new JSONException ( e . getMessage ( ) ) ; }


signature:
public class SubscriptionFactory { /** * / * ( non - Javadoc )
 * @ see com . socialize . entity . SocializeObjectFactory # postToJSON ( com . socialize . entity . SocializeObject , org . json . JSONObject ) */
@ Override protected void postToJSON ( Subscription from , JSONObject to ) throws JSONException { } }

implementation: try { Entity entityObject = from . getEntity ( ) ; User userObject = from . getUser ( ) ; Long date = from . getDate ( ) ; if ( entityObject != null ) { if ( ! StringUtils . isEmpty ( entityObject . getName ( ) ) && ! StringUtils . isEmpty ( entityObject . getKey ( ) ) ) { JSONObject entity = entityFactory . toJSON ( entityObject ) ; to . put ( "entity" , entity ) ; } else if ( ! StringUtils . isEmpty ( entityObject . getKey ( ) ) ) { to . put ( "entity_key" , entityObject . getKey ( ) ) ; } } if ( userObject != null ) { JSONObject user = userFactory . toJSON ( userObject ) ; to . put ( "user" , user ) ; } if ( date != null ) { to . put ( "date" , DATE_FORMAT . format ( date ) ) ; } to . put ( "subscribed" , from . isSubscribed ( ) ) ; to . put ( "type" , from . getNotificationType ( ) . name ( ) . toLowerCase ( ) ) ; } catch ( Exception e ) { throw new JSONException ( e . getMessage ( ) ) ; }


signature:
public class SocializeDeviceRegistrationSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . DeviceRegistrationSystem # registerDevice ( com . socialize . api . SocializeSession , com . socialize . entity . DeviceRegistration ) */
@ Override public void registerDevice ( SocializeSession session , DeviceRegistration registration , DeviceRegistrationListener listener ) { } }

implementation: List < DeviceRegistration > registrations = new ArrayList < DeviceRegistration > ( 1 ) ; registrations . add ( registration ) ; postAsync ( session , ENDPOINT , registrations , listener ) ;


signature:
public class TwitterAuthProvider { /** * / * ( non - Javadoc )
 * @ see com . socialize . auth . AuthProvider # authenticate ( com . socialize . auth . AuthProviderInfo , com . socialize . listener . AuthProviderListener ) */
@ Override public void authenticate ( Context context , TwitterAuthProviderInfo info , final AuthProviderListener listener ) { } }

implementation: twitterAuthUtils . showAuthDialog ( context , info , newTwitterAuthListener ( listener ) ) ;


signature:
public class TTLCache { /** * Adds an object to cache with the given time - to - live
 * @ param strKey
 * @ param object
 * @ param ttl */
public boolean put ( K strKey , E object , long ttl ) { } }

implementation: return put ( strKey , object , ttl , false ) ;


signature:
public class TTLCache { /** * Adds an object to cache that optionally lives forever .
 * @ param strKey
 * @ param object
 * @ param eternal
 * @ return */
public boolean put ( K strKey , E object , boolean eternal ) { } }

implementation: return put ( strKey , object , defaultTTL , eternal ) ;


signature:
public class TTLCache { /** * Adds an object to cache with the given Time To Live in milliseconds
 * @ param k
 * @ param object
 * @ param ttl milliseconds
 * @ param eternal */
protected synchronized boolean put ( K k , E object , long ttl , boolean eternal ) { } }

implementation:
// Check the key map first
if ( exists ( k ) ) { TTLObject < K , E > ttlObject = getTTLObject ( k ) ; Key < K > key = keys . get ( k ) ; key . setTime ( System . currentTimeMillis ( ) ) ; ttlObject . setEternal ( eternal ) ; ttlObject . extendLife ( ttl ) ; ttlObject . setObject ( object ) ; if ( eventListener != null ) { eventListener . onPut ( object ) ; } return true ; } else { TTLObject < K , E > t = new TTLObject < K , E > ( object , k , ttl ) ; t . setEternal ( eternal ) ; long addedSize = object . getSizeInBytes ( ) ; long newSize = currentSizeInBytes + addedSize ; boolean oversize = false ; oversize = ( hardByteLimit && maxCapacityBytes > 0 && newSize > maxCapacityBytes ) ; if ( ! oversize ) { Key < K > key = new Key < K > ( k , System . currentTimeMillis ( ) ) ; keys . put ( k , key ) ; objects . put ( key , t ) ; t . getObject ( ) . onPut ( k ) ; // Increment size
currentSizeInBytes = newSize ; if ( eventListener != null ) { eventListener . onPut ( object ) ; } return true ; } } return false ;


signature:
public class TTLCache { /** * Ignores proxy and always returns raw object
 * @ param strKey
 * @ return */
public synchronized E getRaw ( K strKey ) { } }

implementation: TTLObject < K , E > obj = getTTLObject ( strKey ) ; if ( obj != null && ! isExpired ( obj ) ) { return obj . getObject ( ) ; } return null ;


signature:
public class TTLCache { /** * Gets an object from cache . Returns null if the object does not exist , or has expired .
 * @ param key
 * @ return */
public synchronized E get ( K key ) { } }

implementation:
TTLObject < K , E > obj = getTTLObject ( key ) ; if ( obj != null && ! isExpired ( obj ) ) { if ( extendOnGet ) { extendTTL ( key ) ; } if ( eventListener != null ) { eventListener . onGet ( obj . getObject ( ) ) ; } obj . getObject ( ) . onGet ( ) ; return obj . getObject ( ) ; } else if ( obj != null ) { // Expired
destroy ( obj . getKey ( ) ) ; obj = null ; } if ( obj == null ) { if ( objectFactory != null ) { E object = objectFactory . create ( key ) ; if ( object != null ) { if ( ! put ( key , object ) && logger != null ) { // We couldn ' t put this record . . just log a warning
logger . warn ( "Failed to put object into cache. Cache size exceeded" ) ; } } return object ; } } return null ;


signature:
public class TTLCache { /** * Returns the internal values of the cache .
 * < br / >
 * Proxy objects are returned if gets are proxied within the cache .
 * @ return */
public Collection < E > values ( ) { } }

implementation: Collection < E > values = null ; Collection < TTLObject < K , E > > ttls = objects . values ( ) ; if ( ttls != null ) { values = new ArrayList < E > ( ttls . size ( ) ) ; for ( TTLObject < K , E > t : ttls ) { if ( ! isExpired ( t ) ) { values . add ( t . getObject ( ) ) ; } } } return values ;


signature:
public class TTLCache { /** * Returns true if the object with the given key resides in the cache .
 * @ param k
 * @ return true if the object with the given key resides in the cache . */
public boolean exists ( K k ) { } }

implementation: Key < K > key = keys . get ( k ) ; if ( key != null ) { return objects . get ( key ) != null ; } return false ;


signature:
public class TTLCache { /** * Extends the ttl of the object with the given key with the current system time .
 * @ param strKey */
public synchronized void extendTTL ( K strKey ) { } }

implementation: TTLObject < K , E > object = getTTLObject ( strKey ) ; if ( object != null ) { object . setLifeExpectancy ( System . currentTimeMillis ( ) + object . getTtl ( ) ) ; }


signature:
public class ImageLoader { /** * Loads an image based on Base64 encoded bytes .
 * @ param id The id to give the request
 * @ param name The name to give the image in cache .
 * @ param encodedData The encoded image data .
 * @ param listener A listener to handle the callback . */
public void loadImageByData ( final String name , final String encodedData , int width , int height , final ImageLoadListener listener ) { } }

implementation: ImageLoadRequest request = makeRequest ( ) ; request . setUrl ( name ) ; request . setEncodedImageData ( encodedData ) ; request . setType ( ImageLoadType . ENCODED ) ; loadImage ( request , listener ) ;


signature:
public class ImageLoader { /** * Asynchronously loads the image at the given url and calls the listener when it is loaded .
 * @ param id The id to give the request
 * @ param url The url to be loaded
 * @ param listener A listener to handle the callback . */
public void loadImageByUrl ( final String url , int width , int height , final ImageLoadListener listener ) { } }

implementation: ImageLoadRequest request = makeRequest ( ) ; request . setUrl ( url ) ; request . setType ( ImageLoadType . URL ) ; request . setScaleWidth ( width ) ; request . setScaleHeight ( height ) ; loadImage ( request , listener ) ;


signature:
public class SocializeLikeSystem { /** * ( non - Javadoc )
 * @ see com . socialize . api . action . LikeSystem # addLike ( com . socialize . api . SocializeSession , com . socialize . entity . Entity , android . location . Location , com . socialize . networks . ShareOptions , com . socialize . listener . like . LikeListener ) */
@ Override public void addLike ( SocializeSession session , Entity entity , LikeOptions shareOptions , LikeListener listener , SocialNetwork ... networks ) { } }

implementation: Like c = new Like ( ) ; c . setEntitySafe ( entity ) ; setPropagationData ( c , shareOptions , networks ) ; setLocation ( c ) ; List < Like > list = new ArrayList < Like > ( 1 ) ; list . add ( c ) ; postAsync ( session , ENDPOINT , list , listener ) ;


signature:
public class SocializeLikeSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . action . LikeSystem # deleteLike ( com . socialize . api . SocializeSession , long , com . socialize . listener . like . LikeListener ) */
@ Override public void deleteLike ( SocializeSession session , long id , LikeListener listener ) { } }

implementation: deleteAsync ( session , ENDPOINT , String . valueOf ( id ) , listener ) ;


signature:
public class SocializeLikeSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . action . LikeSystem # getLikesByEntity ( com . socialize . api . SocializeSession , java . lang . String , com . socialize . listener . like . LikeListener ) */
@ Override public void getLikesByEntity ( SocializeSession session , String key , LikeListener listener ) { } }

implementation: listAsync ( session , ENDPOINT , key , listener ) ;


signature:
public class SocializeLikeSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . action . LikeSystem # getLikesByEntity ( com . socialize . api . SocializeSession , java . lang . String , int , int , com . socialize . listener . like . LikeListener ) */
@ Override public void getLikesByEntity ( SocializeSession session , String key , int startIndex , int endIndex , LikeListener listener ) { } }

implementation: listAsync ( session , ENDPOINT , key , null , null , startIndex , endIndex , listener ) ;


signature:
public class SocializeLikeSystem { /** * ( non - Javadoc )
 * @ see com . socialize . api . action . like . LikeSystem # getLikesByApplication ( com . socialize . api . SocializeSession , int , int , com . socialize . listener . like . LikeListener ) */
@ Override public void getLikesByApplication ( SocializeSession session , int startIndex , int endIndex , LikeListener listener ) { } }

implementation: listAsync ( session , ENDPOINT , null , null , null , startIndex , endIndex , listener ) ;


signature:
public class SocializeLikeSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . action . LikeSystem # getLike ( com . socialize . api . SocializeSession , java . lang . String , com . socialize . listener . like . LikeListener ) */
@ Override public void getLike ( SocializeSession session , final String entityUrl , final LikeListener listener ) { } }

implementation: final User user = session . getUser ( ) ; if ( user != null ) { final Long userId = user . getId ( ) ; String endpoint = "/user/" + userId . toString ( ) + ENDPOINT ; listAsync ( session , endpoint , entityUrl , null , null , 0 , 1 , new LikeListListener ( ) { @ Override public void onList ( List < Like > items , int totalSize ) { boolean is404 = false ; if ( items != null ) { if ( items != null && items . size ( ) > 0 ) { Like like = items . get ( 0 ) ; if ( like != null ) { listener . onGet ( like ) ; } else { is404 = true ; } } else { is404 = true ; } } else { is404 = true ; } if ( is404 ) { onError ( new SocializeApiError ( 404 , "No likes found for entity with key [" + entityUrl + "] for user [" + userId + "]" ) ) ; } } @ Override public void onError ( SocializeException error ) { listener . onError ( error ) ; } } ) ; } else { if ( listener != null ) { listener . onError ( new SocializeException ( "No user found in current session" ) ) ; } }


signature:
public class SocializeLikeSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . action . LikeSystem # getLike ( com . socialize . api . SocializeSession , long , com . socialize . listener . like . LikeListener ) */
@ Override public void getLike ( SocializeSession session , long id , LikeListener listener ) { } }

implementation: getAsync ( session , ENDPOINT , String . valueOf ( id ) , listener ) ;


signature:
public class HttpMultipart { /** * Determines the total length of the multipart content ( content length of
 * individual parts plus that of extra elements required to delimit the
 * parts from one another ) . If any of the @ { link BodyPart } s contained in
 * this object is of a streaming entity of unknown length the total length
 * is also unknown .
 * This method buffers only a small amount of data in order to determine the
 * total length of the entire entity . The content of individual parts is not
 * buffered .
 * @ return total length of the multipart entity if known , < code > - 1 < / code >
 * otherwise . */
public long getTotalLength ( ) { } }

implementation:
long contentLen = 0 ; for ( FormBodyPart part : this . parts ) { ContentBody body = part . getBody ( ) ; long len = body . getContentLength ( ) ; if ( len >= 0 ) { contentLen += len ; } else { return - 1 ; } } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try { doWriteTo ( this . mode , out , false ) ; byte [ ] extra = out . toByteArray ( ) ; return contentLen + extra . length ; } catch ( IOException ex ) { // Should never happen
return - 1 ; }


signature:
public class SocializeViewSystem { /** * / * ( non - Javadoc )
 * @ see com . socialize . api . action . ViewSystem # addView ( com . socialize . api . SocializeSession , com . socialize . entity . Entity , android . location . Location , com . socialize . listener . view . ViewListener ) */
@ Override public void addView ( SocializeSession session , Entity entity , Location location , ViewListener listener ) { } }

implementation: View c = new View ( ) ; c . setEntitySafe ( entity ) ; setLocation ( c ) ; List < View > list = new ArrayList < View > ( 1 ) ; list . add ( c ) ; postAsync ( session , ENDPOINT , list , listener ) ;


signature:
public class OpenTsdbTelnet { /** * send a set of metrics to opentsdb
 * @ param metrics */
@ Override public void send ( Set < OpenTsdbMetric > metrics ) { } }

implementation: if ( metrics . isEmpty ( ) ) return ; Writer writer = null ; try { writer = this . writerFactory . getWriter ( ) ; write ( metrics , writer ) ; } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Error writing codahale metrics" , e ) ; } else { logger . warn ( "Error writing codahale metrics: {}" , e . getMessage ( ) ) ; } } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException e ) { logger . error ( "Error while closing writer:" , e ) ; } } }


signature:
public class OpenTsdb { /** * send a set of metrics to opentsdb
 * @ param metrics */
public void send ( Set < OpenTsdbMetric > metrics ) { } }

implementation:
// we set the patch size because of existing issue in opentsdb where large batch of metrics failed
// see at https : / / groups . google . com / forum / # ! topic / opentsdb / U - 0ak _ v8qu0
// we recommend batch size of 5 - 10 will be safer
// alternatively you can enable chunked request
if ( batchSizeLimit > 0 && metrics . size ( ) > batchSizeLimit ) { final Set < OpenTsdbMetric > smallMetrics = new HashSet < OpenTsdbMetric > ( ) ; for ( final OpenTsdbMetric metric : metrics ) { smallMetrics . add ( metric ) ; if ( smallMetrics . size ( ) >= batchSizeLimit ) { sendHelper ( smallMetrics ) ; smallMetrics . clear ( ) ; } } sendHelper ( smallMetrics ) ; } else { sendHelper ( metrics ) ; }


signature:
public class OpenTsdbMetric { /** * Convert a tag string into a tag map .
 * @ param tagString a space - delimited string of key - value pairs . For example , { @ code " key1 = value1 key _ n = value _ n " }
 * @ return a tag { @ link Map }
 * @ throws IllegalArgumentException if the tag string is corrupted . */
public static Map < String , String > parseTags ( final String tagString ) throws IllegalArgumentException { } }

implementation:
// delimit by whitespace or ' = '
Scanner scanner = new Scanner ( tagString ) . useDelimiter ( "\\s+|=" ) ; Map < String , String > tagMap = new HashMap < String , String > ( ) ; try { while ( scanner . hasNext ( ) ) { String tagName = scanner . next ( ) ; String tagValue = scanner . next ( ) ; tagMap . put ( tagName , tagValue ) ; } } catch ( NoSuchElementException e ) { // The tag string is corrupted .
throw new IllegalArgumentException ( "Invalid tag string '" + tagString + "'" ) ; } finally { scanner . close ( ) ; } return tagMap ;


signature:
public class OpenTsdbMetric { /** * Convert a tag map into a space - delimited string .
 * @ param tagMap
 * @ return a space - delimited string of key - value pairs . For example , { @ code " key1 = value1 key _ n = value _ n " } */
public static String formatTags ( final Map < String , String > tagMap ) { } }

implementation: StringBuilder stringBuilder = new StringBuilder ( ) ; String delimeter = "" ; for ( Map . Entry < String , String > tag : tagMap . entrySet ( ) ) { stringBuilder . append ( delimeter ) . append ( sanitize ( tag . getKey ( ) ) ) . append ( "=" ) . append ( sanitize ( tag . getValue ( ) ) ) ; delimeter = " " ; } return stringBuilder . toString ( ) ;


signature:
public class OpenTsdbMetric { /** * Add TSDB tags to a CodaHale metric name .
 * A CodaHale metric name is a single string , so there is no natural way to encode TSDB tags .
 * This function formats the tags into the metric name so they can later be parsed by the
 * Builder . The name is formatted such that it can be appended to create sub - metric names , as
 * happens with Meter and Histogram .
 * @ param name CodaHale metric name
 * @ param tags A space - delimited string of TSDB key - value pair tags
 * @ return A metric name encoded with tags .
 * @ throws IllegalArgumentException if the tag string is invalid */
public static String encodeTagsInName ( final String name , final String tags ) throws IllegalArgumentException { } }

implementation: return encodeTagsInName ( name , parseTags ( tags ) ) ;


signature:
public class OpenTsdbMetric { /** * Add TSDB tags to a CodaHale metric name .
 * A CodaHale metric name is a single string , so there is no natural way to encode TSDB tags .
 * This function formats the tags into the metric name so they can later be parsed by the
 * Builder . The name is formatted such that it can be appended to create sub - metric names , as
 * happens with Meter and Histogram .
 * @ param name CodaHale metric name
 * @ param tags a { @ link Map } of TSDB tags
 * @ return A metric name encoded with tags . */
public static String encodeTagsInName ( final String name , final Map < String , String > tags ) { } }

implementation: return String . format ( "TAG(%s)%s" , formatTags ( tags ) , sanitize ( name ) ) ;


signature:
public class OpenTsdbMetric { /** * Call this function whenever a potentially tag - encoded name is prefixed .
 * @ param name a metric name with encoded tag strings that has been prefixed .
 * @ return a fixed metric name */
public static String fixEncodedTagsInNameAfterPrefix ( final String name ) { } }

implementation:
if ( name == null ) return name ; int tagStart = name . indexOf ( "TAG(" ) ; if ( tagStart == - 1 ) return name ; // no tags in this name
if ( tagStart == 0 ) return name ; // tag string is already correct
// extract the " TAG ( . . . ) " string from the middle of the name and put it at the front .
int tagEnd = name . lastIndexOf ( ')' ) ; if ( tagEnd == - 1 ) { throw new IllegalArgumentException ( "Tag definition missing closing parenthesis for metric '" + name + "'" ) ; } String tagString = name . substring ( tagStart , tagEnd + 1 ) ; return tagString + name . substring ( 0 , tagStart ) + name . substring ( tagEnd + 1 ) ;


signature:
public class OpenTsdbMetric { /** * Creates a Builder for a metric name .
 * @ param name name can contain either a pure CodaHale metric name , or a string returned by { @ code encodeTagsInName } .
 * If it ' s the latter , the tags are parsed out and passed to { @ code withTags } .
 * @ return a { @ link Builder } */
public static Builder named ( String name ) { } }

implementation:
/* A name can contain either a pure metric name , or a string returned by encodeTagsInName ( ) .
 If it ' s the latter , it looks like " TAG ( tag1 = value1 tag2 = value2 ) metricname " . */
if ( ! hasEncodedTagInName ( name ) ) { return new Builder ( name ) ; } // parse out the tags
int tagEnd = name . lastIndexOf ( ')' ) ; if ( tagEnd == - 1 ) { throw new IllegalArgumentException ( "Tag definition missing closing parenthesis for metric '" + name + "'" ) ; } String tagString = name . substring ( 4 , tagEnd ) ; name = name . substring ( tagEnd + 1 ) ; return new Builder ( name ) . withTags ( parseTags ( tagString ) ) ;


signature:
public class OpenTsdbMetric { /** * Returns a put string version of this metric compatible with the telnet - style reporter .
 * Format :
 * < pre > < code >
 * put ( metric - name ) ( timestamp ) ( value ) ( tags )
 * < / code > < / pre >
 * Example :
 * < pre > < code >
 * put sys . cpu . nice 1346846400 18 host = web01 dc = lga
 * < / code > < / pre >
 * @ return a string version of this metric compatible with the telnet reporter . */
public String toTelnetPutString ( ) { } }

implementation: String tagString = formatTags ( tags ) ; return String . format ( "put %s %d %s %s%n" , metric , timestamp , value , tagString ) ;


signature:
public class Domain { /** * Converts the domain to a Unicode representation suitable for human interpretation . It does IDNA conversion .
 * @ see Host # toHumanString ( )
 * @ return unicode string */
@ Override public String toHumanString ( ) { } }

implementation: if ( unicode ) { return domain ; } final IDNA . Info idnaInfo = new IDNA . Info ( ) ; final StringBuilder idnaOutput = new StringBuilder ( ) ; IDNA . getUTS46Instance ( IDNA . DEFAULT ) . nameToUnicode ( domain , idnaOutput , idnaInfo ) ; return idnaOutput . toString ( ) ;


signature:
public class FormURLEncodedParser { /** * Implements the application / x - www - form - urlencoded byte serializer . */
private static String serialize ( final byte [ ] bytes , final int offset , final int length ) { } }

implementation: if ( bytes == null ) { throw new NullPointerException ( "bytes" ) ; } final StringBuilder sb = new StringBuilder ( length ) ; for ( int i = offset ; i < offset + length ; i ++ ) { final byte b = bytes [ i ] ; if ( 0x20 == b ) { sb . append ( ( char ) 0x20 ) ; } else if ( 0x2A == b || 0x2D == b || 0x2E == b || ( 0x30 <= b && b <= 0x39 ) || ( 0x41 <= b && b <= 0x5A ) || 0x5F == b || ( 0x61 <= b && b <= 0x7A ) ) { sb . appendCodePoint ( b ) ; } else { URLUtils . percentEncode ( b , sb ) ; } } return sb . toString ( ) ;


signature:
public class FormURLEncodedParser { /** * Replacement for { @ link java . net . URLEncoder # encode ( String , String ) } .
 * @ see { @ link # encode ( java . util . List , java . nio . charset . Charset ) }
 * @ param input
 * @ param charset
 * @ return */
public static String encode ( final String input , final Charset charset ) { } }

implementation: return encode ( parse ( input ) , charset ) ;


signature:
public class FormURLEncodedParser { /** * Implements the application / x - www - form - urlencoded serializer .
 * @ param input
 * @ param charset
 * @ return */
public static String encode ( final List < NameValue > input , final Charset charset ) { } }

implementation:
if ( input == null ) { throw new NullPointerException ( "input" ) ; } if ( charset == null ) { throw new NullPointerException ( "charset" ) ; } // 2 . Let output be the empty string .
final StringBuilder sb = new StringBuilder ( ) ; // 3 . For each pair in pairs , run these substeps :
for ( int i = 0 ; i < input . size ( ) ; i ++ ) { final NameValue pair = input . get ( i ) ; // 1 . Let outputPair be a copy of pair .
// N / A
// 2 . Replace outputPair ' s name and value with the result of running encode on them using
// encoding override , respectively .
// 3 . Replace outputPair ' s name and value with their serialization .
final String outputName = serialize ( charset . encode ( pair . name ( ) ) ) ; final String outputValue = serialize ( charset . encode ( pair . value ( ) ) ) ; // 4 . If pair is not the first pair in pairs , append " & " to output .
if ( i != 0 ) { sb . append ( '&' ) ; } // 5 . Append outputPair ' s name , followed by " = " , followed by outputPair ' s value to output .
sb . append ( outputName ) . append ( '=' ) . append ( outputValue ) ; } // 4 . Return output .
return sb . toString ( ) ;


signature:
public class URLUtils { /** * Percent - decodes a string .
 * Percent - encoded bytes are assumed to represent UTF - 8 characters .
 * @ see < a href = " http : / / url . spec . whatwg . org / # percent - encoded - bytes " > WHATWG URL Standard : Percent - encoded bytes < / a >
 * @ param input
 * @ return */
public static String percentDecode ( final String input ) { } }

implementation:
if ( input . isEmpty ( ) ) { return input ; } try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream ( ) ; int idx = 0 ; while ( idx < input . length ( ) ) { boolean isEOF = idx >= input . length ( ) ; int c = ( isEOF ) ? 0x00 : input . codePointAt ( idx ) ; while ( ! isEOF && c != '%' ) { if ( c <= 0x7F ) { // String . getBytes is slow , so do not perform encoding
// if not needed
bytes . write ( ( byte ) c ) ; idx ++ ; } else { bytes . write ( new String ( Character . toChars ( c ) ) . getBytes ( UTF_8 ) ) ; idx += Character . charCount ( c ) ; } isEOF = idx >= input . length ( ) ; c = ( isEOF ) ? 0x00 : input . codePointAt ( idx ) ; } if ( c == '%' && ( input . length ( ) <= idx + 2 || ! isASCIIHexDigit ( input . charAt ( idx + 1 ) ) || ! isASCIIHexDigit ( input . charAt ( idx + 2 ) ) ) ) { if ( c <= 0x7F ) { // String . getBytes is slow , so do not perform encoding
// if not needed
bytes . write ( ( byte ) c ) ; idx ++ ; } else { bytes . write ( new String ( Character . toChars ( c ) ) . getBytes ( UTF_8 ) ) ; idx += Character . charCount ( c ) ; } } else { while ( c == '%' && input . length ( ) > idx + 2 && isASCIIHexDigit ( input . charAt ( idx + 1 ) ) && isASCIIHexDigit ( input . charAt ( idx + 2 ) ) ) { bytes . write ( hexToInt ( input . charAt ( idx + 1 ) , input . charAt ( idx + 2 ) ) ) ; idx += 3 ; c = ( input . length ( ) <= idx ) ? 0x00 : input . codePointAt ( idx ) ; } } } return new String ( bytes . toByteArray ( ) , UTF_8 ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; }


signature:
public class URLUtils { /** * Gets the default port for a given schema . That is :
 * < ol >
 * < li > ftp - 21 < / li >
 * < li > file - null < / li >
 * < li > gopher - 70 < / li >
 * < li > http - 80 < / li >
 * < li > https - 443 < / li >
 * < li > ws - 80 < / li >
 * < li > wss - 433 < / li >
 * < / ol >
 * @ param scheme
 * @ return */
public static String getDefaultPortForScheme ( final String scheme ) { } }

implementation: if ( "ftp" . equals ( scheme ) ) { return "21" ; } if ( "file" . equals ( scheme ) ) { return null ; } if ( "gopher" . equals ( scheme ) ) { return "70" ; } if ( "http" . equals ( scheme ) ) { return "80" ; } if ( "https" . equals ( scheme ) ) { return "443" ; } if ( "ws" . equals ( scheme ) ) { return "80" ; } if ( "wss" . equals ( scheme ) ) { return "443" ; } return null ;


signature:
public class IPv6Address { /** * Convert to @ { java . net . InetAddress } .
 * @ return The IPv6 address as a @ { java . net . InetAddress } . */
public InetAddress toInetAddress ( ) { } }

implementation:
final byte [ ] bytes = new byte [ 16 ] ; for ( int i = 0 ; i < pieces . length ; i ++ ) { bytes [ i * 2 ] = ( byte ) ( ( pieces [ i ] >> 8 ) & 0xFF ) ; bytes [ i * 2 + 1 ] = ( byte ) ( pieces [ i ] & 0xFF ) ; } try { return InetAddress . getByAddress ( bytes ) ; } catch ( UnknownHostException e ) { // Can ' t happen if we pass the right amount of bytes
throw new RuntimeException ( "BUG" , e ) ; }


signature:
public class IPv6Address { /** * Convert from @ { java . net . Inet6Address } .
 * @ param inet6Address The IPv6 address as a @ { java . net . Inet6Address } .
 * @ return The IPv6 address as a @ { IPv6Address } . */
public static IPv6Address fromInet6Address ( final Inet6Address inet6Address ) { } }

implementation: final byte [ ] bytes = inet6Address . getAddress ( ) ; final short [ ] pieces = new short [ 8 ] ; for ( int i = 0 ; i < pieces . length ; i ++ ) { pieces [ i ] = ( short ) ( ( ( bytes [ i * 2 ] & 0xFF ) << 8 ) | ( bytes [ i * 2 + 1 ] & 0x00FF ) ) ; } return new IPv6Address ( pieces ) ;


signature:
public class Host { /** * Parses a host as found in URLs . IPv6 literals are expected
 * enclosed in square brackets ( i . e . [ ipv6 - literal ] ) .
 * @ param input
 * @ return
 * @ throws GalimatiasParseException */
public static Host parseHost ( final String input ) throws GalimatiasParseException { } }

implementation: if ( input == null ) { throw new NullPointerException ( "null host" ) ; } if ( input . isEmpty ( ) ) { throw new GalimatiasParseException ( "empty host" , - 1 ) ; } if ( input . charAt ( 0 ) == '[' ) { if ( input . charAt ( input . length ( ) - 1 ) != ']' ) { throw new GalimatiasParseException ( "Unmatched '['" , - 1 ) ; } return IPv6Address . parseIPv6Address ( input . substring ( 1 , input . length ( ) - 1 ) ) ; } final Domain domain = Domain . parseDomain ( input ) ; try { return IPv4Address . parseIPv4Address ( domain . toString ( ) ) ; } catch ( GalimatiasParseException e ) { return domain ; }


signature:
public class URL { /** * Gets the first query parameter value for a given name .
 * @ see { @ link # queryParameters ( String ) }
 * @ param name Parameter name .
 * @ return The first parameter value or null if there parameter is not present . */
public String queryParameter ( final String name ) { } }

implementation: if ( name == null ) { throw new NullPointerException ( "name is null" ) ; } if ( query == null || query . isEmpty ( ) ) { return null ; } int start = 0 ; do { final int nextAmpersand = query . indexOf ( '&' , start ) ; final int end = ( nextAmpersand == - 1 ) ? query . length ( ) : nextAmpersand ; int nextEquals = query . indexOf ( '=' , start ) ; if ( nextEquals == - 1 || nextEquals > end ) { nextEquals = end ; } final int thisNameLength = nextEquals - start ; final int thisValueLength = end - nextEquals ; if ( thisNameLength == name . length ( ) && query . regionMatches ( start , name , 0 , name . length ( ) ) ) { if ( thisValueLength == 0 ) { return "" ; } return query . substring ( nextEquals + 1 , end ) ; } if ( nextAmpersand == - 1 ) { break ; } start = nextAmpersand + 1 ; } while ( true ) ; return null ;


signature:
public class URL { /** * Gets all query parameter values for a given name .
 * @ param name Parameter name .
 * @ return A { @ link java . util . List } with all parameter values or null if the parameter is not present . */
public List < String > queryParameters ( final String name ) { } }

implementation: if ( name == null ) { throw new NullPointerException ( "name is null" ) ; } if ( query == null || query . isEmpty ( ) ) { return null ; } int start = 0 ; final List < String > result = new ArrayList < String > ( ) ; do { final int nextAmpersand = query . indexOf ( '&' , start ) ; final int end = ( nextAmpersand == - 1 ) ? query . length ( ) : nextAmpersand ; int nextEquals = query . indexOf ( '=' , start ) ; if ( nextEquals == - 1 || nextEquals > end ) { nextEquals = end ; } final int thisNameLength = nextEquals - start ; final int thisValueLength = end - nextEquals ; if ( thisNameLength == name . length ( ) && query . regionMatches ( start , name , 0 , name . length ( ) ) ) { if ( thisValueLength == 0 ) { result . add ( "" ) ; } else { result . add ( query . substring ( nextEquals + 1 , end ) ) ; } } if ( nextAmpersand == - 1 ) { break ; } start = nextAmpersand + 1 ; } while ( true ) ; return result ;


signature:
public class URL { /** * Returns a relative URL reference for the given URL .
 * Behaves as @ { link java . net . URI # relativize ( URL ) } .
 * @ param url Absolute URL .
 * @ return Relative reference . */
public String relativize ( final URL url ) { } }

implementation: if ( this . isOpaque ( ) || url . isOpaque ( ) ) { return url . toString ( ) ; } if ( ! this . scheme ( ) . equals ( url . scheme ( ) ) ) { return url . toString ( ) ; } if ( this . authority ( ) == null ^ url . authority ( ) == null ) { return url . toString ( ) ; } if ( this . authority ( ) != null && ! this . authority ( ) . equals ( url . authority ( ) ) ) { return url . toString ( ) ; } String prefixPath = ( this . path ( ) . endsWith ( "/" ) ) ? this . path : this . path ( ) + "/" ; if ( ! url . path ( ) . startsWith ( prefixPath ) && ! this . path ( ) . equals ( url . path ( ) ) ) { return url . toString ( ) ; } StringBuilder output = new StringBuilder ( ) ; if ( ! this . path ( ) . equals ( url . path ( ) ) ) { output . append ( url . path ( ) . replaceFirst ( prefixPath , "" ) ) ; } if ( url . query ( ) != null ) { output . append ( '?' ) . append ( url . query ( ) ) ; } if ( url . fragment ( ) != null ) { output . append ( '#' ) . append ( url . fragment ( ) ) ; } return output . toString ( ) ;


signature:
public class URL { /** * Gets a URL object from a relative scheme and a host .
 * @ param scheme
 * @ param host
 * @ return
 * @ throws GalimatiasParseException */
public static URL buildHierarchical ( final String scheme , final String host ) throws GalimatiasParseException { } }

implementation: if ( ! URLUtils . isRelativeScheme ( scheme ) ) { throw new GalimatiasParseException ( "Scheme is not relative: " + scheme ) ; } return new URLParser ( scheme + "://" + host ) . parse ( ) ;


signature:
public class URL { /** * Gets a URL object from a non - relative scheme .
 * @ param scheme
 * @ return
 * @ throws GalimatiasParseException */
public static URL buildOpaque ( final String scheme ) throws GalimatiasParseException { } }

implementation: if ( URLUtils . isRelativeScheme ( scheme ) ) { throw new GalimatiasParseException ( "Scheme is relative: " + scheme ) ; } return new URLParser ( scheme + ":" ) . parse ( ) ;


signature:
public class URL { /** * Converts to { @ link java . net . URI } .
 * Conversion to { @ link java . net . URI } will throw
 * { @ link java . net . URISyntaxException } if the URL contains
 * unescaped unsafe characters as defined in RFC 2396.
 * In order to prevent this , force RFC 2396 compliance when
 * parsing the URL . For example :
 * NOTE 1 : This will not make distinction between no user and password and just empty
 * user and no password .
 * < pre >
 * < code >
 * URL . parse ( " http : / / example . com " ) . toJavaURI ( ) . toString ( ) - > " http : / / example . com "
 * URL . parse ( " http : / / @ example . com " ) . toJavaURI ( ) . toString ( ) - > " http : / / example . com "
 * < / code >
 * < / pre >
 * TODO : Check if this exception can actually be thrown
 * @ return */
public java . net . URI toJavaURI ( ) throws URISyntaxException { } }

implementation: if ( isHierarchical ) { return new URI ( scheme ( ) , ( ! "" . equals ( userInfo ( ) ) ) ? URLUtils . percentDecode ( userInfo ( ) ) : null , ( host ( ) != null ) ? host ( ) . toString ( ) : null , port , ( path ( ) != null ) ? URLUtils . percentDecode ( path ( ) ) : null , ( query ( ) != null ) ? URLUtils . percentDecode ( query ( ) ) : null , ( fragment ( ) != null ) ? URLUtils . percentDecode ( fragment ( ) ) : null ) ; } return new URI ( scheme ( ) , URLUtils . percentDecode ( schemeData ( ) ) + ( ( query ( ) == null ) ? "" : "?" + URLUtils . percentDecode ( query ( ) ) ) , ( fragment ( ) != null ) ? URLUtils . percentDecode ( fragment ( ) ) : null ) ;


signature:
public class URL { /** * Construct a URL from a { @ link java . net . URI } .
 * @ param uri
 * @ return */
public static URL fromJavaURI ( java . net . URI uri ) { } }

implementation:
// TODO : Let ' s do this more efficient .
try { return new URLParser ( uri . toString ( ) ) . parse ( ) ; } catch ( GalimatiasParseException e ) { // This should not happen .
throw new RuntimeException ( "BUG" , e ) ; }


signature:
public class URL { /** * Construct a URL from a { @ link java . net . URL } .
 * @ param url
 * @ return */
public static URL fromJavaURL ( java . net . URL url ) { } }

implementation:
// TODO : Let ' s do this more efficient .
try { return new URLParser ( url . toString ( ) ) . parse ( ) ; } catch ( GalimatiasParseException e ) { // This should not happen .
throw new RuntimeException ( "BUG" , e ) ; }


signature:
public class URL { /** * Serializes the URL to a human - readable representation . That is ,
 * percent - decoded and with IDN domains in its Unicode representation .
 * @ return */
public String toHumanString ( ) { } }

implementation: final StringBuilder output = new StringBuilder ( ) ; output . append ( scheme ) . append ( ':' ) ; if ( isHierarchical ) { output . append ( "//" ) ; final String userInfo = userInfo ( ) ; if ( ! userInfo . isEmpty ( ) ) { output . append ( URLUtils . percentDecode ( userInfo ) ) . append ( '@' ) ; } if ( host != null ) { if ( host instanceof IPv6Address ) { output . append ( host . toHostString ( ) ) ; } else { output . append ( host . toHumanString ( ) ) ; } } if ( port != - 1 ) { output . append ( ':' ) . append ( port ) ; } if ( path != null ) { output . append ( URLUtils . percentDecode ( path ) ) ; } } else { output . append ( URLUtils . percentDecode ( schemeData ) ) ; } if ( query != null ) { output . append ( '?' ) . append ( URLUtils . percentDecode ( query ) ) ; } if ( fragment != null ) { output . append ( '#' ) . append ( URLUtils . percentDecode ( fragment ) ) ; } return output . toString ( ) ;


signature:
public class SqlTemplate { /** * Executes a query , passing the row objects to { @ code handleStream } as a stream .
 * < p > Example usage : < / p >
 * < pre >
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , Emp . class ,
 * ( Stream & lt ; Emp & gt ; empStream ) - & gt ; empStream . mapToInt ( Emp : : getSalary ) . sum ( ) ) ;
 * < / pre >
 * @ param fileName SQL specifier
 * @ param clazz the row object class
 * @ param handleStream the function which is applied to the stream
 * @ param < T > the row object type
 * @ param < U > the result type
 * @ return the result of { @ code handleStream }
 * @ throws org . springframework . dao . DataAccessException if there is any problem */
public < T , U > U forStream ( String fileName , Class < T > clazz , Function < ? super Stream < T > , U > handleStream ) { } }

implementation: String sql = getTemplate ( fileName , EMPTY_ARGS ) ; PreparedStatementSetter pss = paramBuilder . byArgs ( new Object [ 0 ] ) ; RowMapper < T > mapper = mapperBuilder . mapper ( clazz ) ; return queryStreamWithOrdinalParams ( sql , pss , mapper , handleStream ) ;


signature:
public class SqlTemplate { /** * Executes a query using { @ code params } as the named parameters ,
 * passing the row objects to { @ code handleStream } as a stream .
 * < p > Example usage : < / p >
 * < pre >
 * Map & lt ; String , Object & gt ; params = new HashMap & gt ; & lt ; ( ) ;
 * params . put ( " deptno " , 30 ) ;
 * params . put ( " job " , " SALESMAN " ) ;
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , Emp . class , params ,
 * empStream - & gt ; empStream . mapToInt ( Emp : : getSalary ) . sum ( ) ) ;
 * < / pre >
 * @ param fileName parameterized SQL specifier
 * @ param clazz the result object class
 * @ param params the named parameters
 * @ param handleStream the function which is applied to the stream
 * @ param < T > the row object type
 * @ param < U > the result type
 * @ return the result of { @ code handleStream }
 * @ throws org . springframework . dao . DataAccessException if there is any problem */
public < T , U > U forStream ( String fileName , Class < T > clazz , Map < String , Object > params , Function < ? super Stream < T > , U > handleStream ) { } }

implementation: String sql = getTemplate ( fileName , params ) ; SqlParameterSource sps = paramBuilder . byMap ( params ) ; RowMapper < T > mapper = mapperBuilder . mapper ( clazz ) ; return queryStreamWithNamedParams ( sql , sps , mapper , handleStream ) ;


signature:
public class SqlTemplate { /** * Executes a query , passing the row objects to { @ code handleStream } as a stream .
 * < p > { @ code entity } is used as the single parameter if it is a simple value ,
 * or as the container of the named parameters if it is a bean . < / p >
 * < p > Example usage with a simple value parameter : < / p >
 * < pre >
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , Emp . class , " SALESMAN " ,
 * empStream - & gt ; empStream . mapToInt ( Emp : : getSalary ) . sum ( ) ) ;
 * < / pre >
 * < p > Example usage with a bean parameter : < / p >
 * < pre >
 * emp . setDeptno ( 30 ) ;
 * emp . setJob ( " SALESMAN " ) ;
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , Emp . class , emp ,
 * empStream - & gt ; empStream . mapToInt ( Emp : : getSalary ) . sum ( ) ) ;
 * < / pre >
 * @ param fileName parameterized SQL specifier
 * @ param clazz the result object class
 * @ param entity the single parameter , or the container of the named parameters
 * @ param handleStream the function which is applied to the stream
 * @ param < T > the row object type
 * @ param < U > the result type
 * @ return the result of { @ code handleStream }
 * @ throws org . springframework . dao . DataAccessException if there is any problem */
public < T , U > U forStream ( String fileName , Class < T > clazz , Object entity , Function < ? super Stream < T > , U > handleStream ) { } }

implementation: String sql = getTemplate ( fileName , entity ) ; RowMapper < T > mapper = mapperBuilder . mapper ( clazz ) ; SQLExceptionTranslator excTranslator = jdbcTemplate . getExceptionTranslator ( ) ; if ( TypeUtils . isSimpleValueType ( entity . getClass ( ) ) ) { PreparedStatementSetter pss = paramBuilder . byArgs ( entity ) ; return queryStreamWithOrdinalParams ( sql , pss , mapper , handleStream ) ; } else { SqlParameterSource sps = paramBuilder . byBean ( entity ) ; return queryStreamWithNamedParams ( sql , sps , mapper , handleStream ) ; }


signature:
public class SqlTemplate { /** * Executes a query ,
 * passing the column maps to { @ code handleStream } as a stream .
 * < p > Example usage : < / p >
 * < pre >
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " ,
 * mapStream - & gt ; mapStream . mapToInt ( map - & gt ; ( Integer ) map . get ( " salary " ) ) . sum ( ) ) ;
 * < / pre >
 * @ param fileName SQL specifier
 * @ param handleStream the function which is applied to the stream
 * @ param < U > the result type
 * @ return the result of { @ code handleStream }
 * @ throws org . springframework . dao . DataAccessException if there is any problem */
public < U > U forStream ( String fileName , Function < ? super Stream < Map < String , Object > > , U > handleStream ) { } }

implementation: String sql = getTemplate ( fileName , EMPTY_ARGS ) ; PreparedStatementSetter pss = paramBuilder . byArgs ( new Object [ 0 ] ) ; RowMapper < Map < String , Object > > mapper = new ColumnMapRowMapper ( ) ; return queryStreamWithOrdinalParams ( sql , pss , mapper , handleStream ) ;


signature:
public class SqlTemplate { /** * Executes a query using { @ code params } as the named parameters ,
 * passing the column maps to { @ code handleStream } as a stream .
 * < p > Example usage : < / p >
 * < pre >
 * Map & lt ; String , Object & gt ; params = new HashMap & gt ; & lt ; ( ) ;
 * params . put ( " deptno " , 30 ) ;
 * params . put ( " job " , " SALESMAN " ) ;
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , params ,
 * mapStream - & gt ; mapStream . mapToInt ( map - & gt ; ( Integer ) map . get ( " salary " ) ) . sum ( ) ) ;
 * < / pre >
 * @ param fileName parameterized SQL specifier
 * @ param params the named parameters
 * @ param handleStream the function which is applied to the stream
 * @ param < U > the result type
 * @ return the result of { @ code handleStream }
 * @ throws org . springframework . dao . DataAccessException if there is any problem */
public < U > U forStream ( String fileName , Map < String , Object > params , Function < ? super Stream < Map < String , Object > > , U > handleStream ) { } }

implementation: String sql = getTemplate ( fileName , params ) ; SqlParameterSource sps = paramBuilder . byMap ( params ) ; RowMapper < Map < String , Object > > mapper = new ColumnMapRowMapper ( ) ; return queryStreamWithNamedParams ( sql , sps , mapper , handleStream ) ;


signature:
public class SqlTemplate { /** * Executes a query , passing the column maps to { @ code handleStream } as a stream .
 * < p > { @ code entity } is used as the single parameter if it is a simple value ,
 * or as the container of the named parameters if it is a bean . < / p >
 * < p > Example usage with a simple value parameter : < / p >
 * < pre >
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , " SALESMAN " ,
 * mapStream - & gt ; mapStream . mapToInt ( map - & gt ; ( Integer ) map . get ( " salary " ) ) . sum ( ) ) ;
 * < / pre >
 * < p > Example usage with a bean parameter : < / p >
 * < pre >
 * emp . setDeptno ( 30 ) ;
 * emp . setJob ( " SALESMAN " ) ;
 * int totalSalary = sqlTemplate . forStream ( " / path / to / query . sql " , emp ,
 * mapStream - & gt ; mapStream . mapToInt ( map - & gt ; ( Integer ) map . get ( " salary " ) ) . sum ( ) ) ;
 * < / pre >
 * @ param fileName parameterized SQL specifier
 * @ param entity the single parameter or the container of the named parameters
 * @ param handleStream the function which is applied to the stream
 * @ param < U > the result type
 * @ return the result of { @ code handleStream }
 * @ throws org . springframework . dao . DataAccessException if there is any problem */
public < U > U forStream ( String fileName , Object entity , Function < ? super Stream < Map < String , Object > > , U > handleStream ) { } }

implementation: String sql = getTemplate ( fileName , entity ) ; RowMapper < Map < String , Object > > mapper = new ColumnMapRowMapper ( ) ; if ( TypeUtils . isSimpleValueType ( entity . getClass ( ) ) ) { PreparedStatementSetter pss = paramBuilder . byArgs ( entity ) ; return queryStreamWithOrdinalParams ( sql , pss , mapper , handleStream ) ; } else { SqlParameterSource sps = paramBuilder . byBean ( entity ) ; return queryStreamWithNamedParams ( sql , sps , mapper , handleStream ) ; }


signature:
public class SqlTemplate { /** * Executes a quey for stream with ordinal parameters . */
private < T , U > U queryStreamWithOrdinalParams ( String sql , PreparedStatementSetter pss , RowMapper < T > mapper , Function < ? super Stream < T > , U > handleStream ) { } }

implementation: SQLExceptionTranslator excTranslator = jdbcTemplate . getExceptionTranslator ( ) ; ResultSetExtractor < U > extractor = new StreamResultSetExtractor ( sql , mapper , handleStream , excTranslator ) ; return jdbcTemplate . query ( sql , pss , extractor ) ;


signature:
public class SqlTemplate { /** * Executes a query for stream with named parameters . */
private < T , U > U queryStreamWithNamedParams ( String sql , SqlParameterSource sps , RowMapper < T > mapper , Function < ? super Stream < T > , U > handleStream ) { } }

implementation: SQLExceptionTranslator excTranslator = jdbcTemplate . getExceptionTranslator ( ) ; ResultSetExtractor < U > extractor = new StreamResultSetExtractor ( sql , mapper , handleStream , excTranslator ) ; return namedJdbcTemplate . query ( sql , sps , extractor ) ;


signature:
public class BeanFields { /** * Get fields of the given class .
 * @ param clazz the class
 * @ return the fields of the given class */
public static Field [ ] get ( Class < ? > clazz ) { } }

implementation: Field [ ] fields = CACHED_FIELDS . get ( clazz ) ; if ( fields == null ) { fields = clazz . getFields ( ) ; CACHED_FIELDS . putIfAbsent ( clazz , fields ) ; } return fields ;


signature:
public class TypeUtils { /** * Check if the given type represents a " simple " value type :
 * a primitive , a String or other CharSequence , a Number , a Date ,
 * a URI , a URL , a Locale or a Class .
 * @ param clazz the type to check
 * @ return whether the given type represents a " simple " value type */
public static boolean isSimpleValueType ( Class < ? > clazz ) { } }

implementation: return ClassUtils . isPrimitiveOrWrapper ( clazz ) || clazz . isEnum ( ) || CharSequence . class . isAssignableFrom ( clazz ) || Number . class . isAssignableFrom ( clazz ) || Date . class . isAssignableFrom ( clazz ) || Temporal . class . isAssignableFrom ( clazz ) || clazz . equals ( URI . class ) || clazz . equals ( URL . class ) || clazz . equals ( Locale . class ) || clazz . equals ( Class . class ) ;


signature:
public class MapParameter { /** * { @ inheritDoc } */
@ Override public Object getValue ( String paramName ) { } }

implementation: Object value = values . get ( paramName ) ; if ( value == null ) { return null ; } return Jsr310JdbcUtils . convertIfNecessary ( value , zoneId ) ;


signature:
public class ResultSetIterator { /** * Fetches a row if not fetched yet . */
private Optional < T > fetchRow ( ) { } }

implementation:
if ( this . row != null ) { // already fetched
return Optional . of ( this . row ) ; } this . hasReachedEos = hasReachedEos || ! wrapSqlException ( ( ) -> rs . next ( ) ) ; if ( this . hasReachedEos ) { return Optional . empty ( ) ; } this . row = wrapSqlException ( ( ) -> mapper . mapRow ( rs , 1 ) ) ; return Optional . ofNullable ( this . row ) ;


signature:
public class ResultSetIterator { /** * Performs an action which may throw an { @ link SQLException } .
 * If SQLException is thrown , it converts the exception to
 * { @ link org . springframework . dao . DataAccessException } . */
< R > R wrapSqlException ( SqlAction < R > action ) { } }

implementation: try { return action . perform ( ) ; } catch ( SQLException sqlException ) { throw excTranslator . translate ( "StreamResultSetExtractor" , sql , sqlException ) ; }


signature:
public class Jsr310JdbcUtils { /** * Get the column value as LocalDateTime .
 * @ param rs ResultSet
 * @ param index column index
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected static LocalDateTime getAsLocalDateTime ( ResultSet rs , int index ) throws SQLException { } }

implementation: Timestamp timestamp = rs . getTimestamp ( index ) ; if ( timestamp != null ) { return timestamp . toLocalDateTime ( ) ; } return null ;


signature:
public class Jsr310JdbcUtils { /** * Get the column value as LocalDate .
 * @ param rs ResultSet
 * @ param index column index
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected static LocalDate getAsLocalDate ( ResultSet rs , int index ) throws SQLException { } }

implementation: Date date = rs . getDate ( index ) ; if ( date != null ) { return date . toLocalDate ( ) ; } return null ;


signature:
public class Jsr310JdbcUtils { /** * Get the column value as LocalTime .
 * @ param rs ResultSet
 * @ param index column index
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected static LocalTime getAsLocalTime ( ResultSet rs , int index ) throws SQLException { } }

implementation: Time time = rs . getTime ( index ) ; if ( time != null ) { return time . toLocalTime ( ) ; } return null ;


signature:
public class Jsr310JdbcUtils { /** * Get the column value as ZonedDateTime .
 * @ param rs ResultSet
 * @ param index column index
 * @ param zoneId zoneId
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected static ZonedDateTime getAsZonedDateTime ( ResultSet rs , int index , ZoneId zoneId ) throws SQLException { } }

implementation: Timestamp timestamp = rs . getTimestamp ( index ) ; if ( timestamp != null ) { return timestamp . toLocalDateTime ( ) . atZone ( zoneId ) ; } return null ;


signature:
public class Jsr310JdbcUtils { /** * Get the column value as OffsetDateTime .
 * @ param rs ResultSet
 * @ param index column index
 * @ param zoneId zoneId
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected static OffsetDateTime getAsOffsetDateTime ( ResultSet rs , int index , ZoneId zoneId ) throws SQLException { } }

implementation: Timestamp timestamp = rs . getTimestamp ( index ) ; if ( timestamp != null ) { return timestamp . toLocalDateTime ( ) . atZone ( zoneId ) . toOffsetDateTime ( ) ; } return null ;


signature:
public class Jsr310JdbcUtils { /** * Get the column value as OffsetTime .
 * @ param rs ResultSet
 * @ param index column index
 * @ param zoneId zoneId
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected static OffsetTime getAsOffsetTime ( ResultSet rs , int index , ZoneId zoneId ) throws SQLException { } }

implementation: Time time = rs . getTime ( index ) ; if ( time != null ) { return time . toLocalTime ( ) . atOffset ( zoneId . getRules ( ) . getOffset ( Instant . now ( ) ) ) ; } return null ;


signature:
public class BeanParameter { /** * { @ inheritDoc } */
@ Override public boolean hasValue ( String paramName ) { } }

implementation: return privateFields . contains ( paramName ) || publicFeilds . containsKey ( paramName ) ;


signature:
public class BeanParameter { /** * { @ inheritDoc } */
@ Override public Object getValue ( String paramName ) { } }

implementation: Object value = null ; if ( privateFields . contains ( paramName ) ) { value = beanWrapper . getPropertyValue ( paramName ) ; } else if ( publicFeilds . containsKey ( paramName ) ) { Field field = publicFeilds . get ( paramName ) ; try { value = field . get ( entity ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( e ) ; } } if ( value == null ) { return null ; } return Jsr310JdbcUtils . convertIfNecessary ( value , zoneId ) ;


signature:
public class BeanMapper { /** * { @ see org . springframework . jdbc . core . BeanPropertyRowMapper # un }
 * Convert a name in camelCase to an underscored name in lower case .
 * Any upper case letters are converted to lower case with a preceding underscore .
 * @ param name the string containing original name
 * @ return the converted name */
private String underscoreName ( String name ) { } }

implementation: if ( ! StringUtils . hasLength ( name ) ) { return "" ; } StringBuilder result = new StringBuilder ( ) ; result . append ( name . substring ( 0 , 1 ) . toLowerCase ( ) ) ; for ( int i = 1 ; i < name . length ( ) ; i ++ ) { String s = name . substring ( i , i + 1 ) ; String slc = s . toLowerCase ( ) ; if ( ! s . equals ( slc ) ) { result . append ( "_" ) . append ( slc ) ; } else { result . append ( s ) ; } } return result . toString ( ) ;


signature:
public class BeanMapper { /** * { @ inheritDoc } */
@ Override public T mapRow ( ResultSet rs , int rowNumber ) throws SQLException { } }

implementation:
Assert . state ( this . mappedClass != null , "Mapped class was not specified" ) ; T mappedObject = BeanUtils . instantiate ( this . mappedClass ) ; BeanWrapper bw = PropertyAccessorFactory . forBeanPropertyAccess ( mappedObject ) ; ResultSetMetaData metaData = rs . getMetaData ( ) ; int columnCount = metaData . getColumnCount ( ) ; for ( int index = 1 ; index <= columnCount ; index ++ ) { String column = JdbcUtils . lookupColumnName ( metaData , index ) ; String name = column . replaceAll ( " " , "" ) . toLowerCase ( ) ; Object value = null ; if ( privateFields . containsKey ( name ) ) { PropertyDescriptor pd = privateFields . get ( name ) ; value = getColumnValue ( rs , index , pd . getPropertyType ( ) ) ; if ( logger . isDebugEnabled ( ) && rowNumber == 0 ) { logger . debug ( "Mapping column '" + column + "' to property '" + pd . getName ( ) + "' of type " + pd . getPropertyType ( ) ) ; } // TODO : care about assign null to primitive field . See BeanPropertyRowMapper
bw . setPropertyValue ( pd . getName ( ) , value ) ; } else if ( publicFields . containsKey ( name ) ) { Field field = this . publicFields . get ( name ) ; value = getColumnValue ( rs , index , field . getType ( ) ) ; if ( logger . isDebugEnabled ( ) && rowNumber == 0 ) { logger . debug ( "Mapping column '" + column + "' to property '" + field . getName ( ) + "' of type " + field . getType ( ) ) ; } try { field . set ( mappedObject , value ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } } return mappedObject ;


signature:
public class BeanMapper { /** * Get the column value .
 * @ param rs ResultSet
 * @ param index column index
 * @ param requiredType the required value type
 * @ return column value
 * @ throws SQLException in case of extraction failure */
protected Object getColumnValue ( ResultSet rs , int index , Class < ? > requiredType ) throws SQLException { } }

implementation: return Jsr310JdbcUtils . getResultSetValue ( rs , index , requiredType , zoneId ) ;


signature:
public class ArgsParameter { /** * { @ inheritDoc } */
protected void doSetValue ( PreparedStatement ps , int parameterPosition , Object argValue ) throws SQLException { } }

implementation: super . doSetValue ( ps , parameterPosition , Jsr310JdbcUtils . convertIfNecessary ( argValue , zoneId ) ) ;


signature:
public class StreamResultSetExtractor { /** * Applies { @ code handleStream } to the row stream converted from the ResultSet
 * to extract a result .
 * @ param rs the ResultSet
 * @ return the result of { @ code handleStream } */
@ Override public U extractData ( ResultSet rs ) { } }

implementation: Iterable < T > iterable = ( ) -> new ResultSetIterator ( sql , rs , mapper , excTranslator ) ; Stream < T > stream = StreamSupport . stream ( iterable . spliterator ( ) , false ) ; return handleStream . apply ( stream ) ;


signature:
public class UrlUploader { /** * Synchronously uploads the file to Uploadcare .
 * The calling thread will be busy until the upload is finished .
 * @ param pollingInterval Progress polling interval in ms
 * @ return An Uploadcare file
 * @ throws UploadFailureException */
public File upload ( int pollingInterval ) throws UploadFailureException { } }

implementation: RequestHelper requestHelper = client . getRequestHelper ( ) ; URI uploadUrl = Urls . uploadFromUrl ( sourceUrl , client . getPublicKey ( ) , store ) ; String token = requestHelper . executeQuery ( new HttpGet ( uploadUrl ) , false , UploadFromUrlData . class ) . token ; URI statusUrl = Urls . uploadFromUrlStatus ( token ) ; while ( true ) { sleep ( pollingInterval ) ; HttpGet request = new HttpGet ( statusUrl ) ; UploadFromUrlStatusData data = requestHelper . executeQuery ( request , false , UploadFromUrlStatusData . class ) ; if ( data . status . equals ( "success" ) ) { return client . getFile ( data . fileId ) ; } else if ( data . status . equals ( "error" ) || data . status . equals ( "failed" ) ) { throw new UploadFailureException ( ) ; } }


signature:
public class CdnPathBuilder { /** * Adds top - left - aligned crop .
 * @ param width Crop width
 * @ param height Crop height */
public CdnPathBuilder crop ( int width , int height ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/crop/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ;


signature:
public class CdnPathBuilder { /** * Adds center - aligned crop .
 * @ param width Crop width
 * @ param height Crop height */
public CdnPathBuilder cropCenter ( int width , int height ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/crop/" ) . append ( width ) . append ( "x" ) . append ( height ) . append ( "/center" ) ; return this ;


signature:
public class CdnPathBuilder { /** * Adds top - left - aligned crop with a filled background .
 * @ param width Crop width
 * @ param height Crop height
 * @ param color Background color */
public CdnPathBuilder cropColor ( int width , int height , Color color ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/crop/" ) . append ( width ) . append ( "x" ) . append ( height ) . append ( "/" ) . append ( colorToHex ( color ) ) ; return this ;


signature:
public class CdnPathBuilder { /** * Resizes width , keeping the aspect ratio .
 * @ param width New width */
public CdnPathBuilder resizeWidth ( int width ) { } }

implementation: dimensionGuard ( width ) ; sb . append ( "/-/resize/" ) . append ( width ) . append ( "x" ) ; return this ;


signature:
public class CdnPathBuilder { /** * Resizes width and height
 * @ param width New width
 * @ param height New height */
public CdnPathBuilder resize ( int width , int height ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/resize/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ;


signature:
public class CdnPathBuilder { /** * Scales the image until one of the dimensions fits ,
 * then crops the bottom or right side .
 * @ param width New width
 * @ param height New height */
public CdnPathBuilder scaleCrop ( int width , int height ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/scale_crop/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ;


signature:
public class CdnPathBuilder { /** * Scales the image until one of the dimensions fits ,
 * centers it , then crops the rest .
 * @ param width New width
 * @ param height New height */
public CdnPathBuilder scaleCropCenter ( int width , int height ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/scale_crop/" ) . append ( width ) . append ( "x" ) . append ( height ) . append ( "/center" ) ; return this ;


signature:
public class CdnPathBuilder { /** * Performs Gaussian blur on result image .
 * @ param strength Strength is standard deviation ( aka blur radius ) multiplied by ten . Strength
 * can be up to 5000 . Default is 10. */
public CdnPathBuilder blur ( int strength ) { } }

implementation: if ( strength < 0 || strength > 5000 ) { strength = 10 ; } sb . append ( "/-/blur/" ) . append ( strength ) ; return this ;


signature:
public class CdnPathBuilder { /** * Performs sharpening on result image . This can be useful after scaling down .
 * @ param strength Strength can be from 0 to 20 . Default is 5. */
public CdnPathBuilder sharp ( int strength ) { } }

implementation: if ( strength < 0 || strength > 20 ) { strength = 5 ; } sb . append ( "/-/sharp/" ) . append ( strength ) ; return this ;


signature:
public class CdnPathBuilder { /** * Reduces an image proportionally in order to fit it into given dimensions .
 * @ param width New width
 * @ param height New height */
public CdnPathBuilder preview ( int width , int height ) { } }

implementation: dimensionsGuard ( width , height ) ; sb . append ( "/-/preview/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ;


signature:
public class Client { /** * Requests project info from the API .
 * @ return Project resource */
public Project getProject ( ) { } }

implementation: URI url = Urls . apiProject ( ) ; RequestHelper requestHelper = getRequestHelper ( ) ; ProjectData projectData = requestHelper . executeQuery ( new HttpGet ( url ) , true , ProjectData . class ) ; return new Project ( this , projectData ) ;


signature:
public class Client { /** * Requests file data .
 * @ param fileId Resource UUID
 * @ return File resource */
public File getFile ( String fileId ) { } }

implementation: URI url = Urls . apiFile ( fileId ) ; RequestHelper requestHelper = getRequestHelper ( ) ; FileData fileData = requestHelper . executeQuery ( new HttpGet ( url ) , true , FileData . class ) ; return new File ( this , fileData ) ;


signature:
public class Client { /** * Marks a file as deleted .
 * @ param fileId Resource UUID */
public void deleteFile ( String fileId ) { } }

implementation: URI url = Urls . apiFile ( fileId ) ; RequestHelper requestHelper = getRequestHelper ( ) ; requestHelper . executeCommand ( new HttpDelete ( url ) , true ) ;


signature:
public class Client { /** * Marks a file as saved .
 * This has to be done for all files you want to keep .
 * Unsaved files are eventually purged .
 * @ param fileId Resource UUID */
public void saveFile ( String fileId ) { } }

implementation: URI url = Urls . apiFileStorage ( fileId ) ; RequestHelper requestHelper = getRequestHelper ( ) ; requestHelper . executeCommand ( new HttpPost ( url ) , true ) ;


signature:
public class FileUploader { /** * Synchronously uploads the file to Uploadcare .
 * The calling thread will be busy until the upload is finished .
 * @ return An Uploadcare file */
public File upload ( ) throws UploadFailureException { } }

implementation: URI uploadUrl = Urls . uploadBase ( ) ; HttpPost request = new HttpPost ( uploadUrl ) ; MultipartEntityBuilder entityBuilder = MultipartEntityBuilder . create ( ) ; entityBuilder . addTextBody ( "UPLOADCARE_PUB_KEY" , client . getPublicKey ( ) ) ; entityBuilder . addTextBody ( "UPLOADCARE_STORE" , store ) ; if ( file != null ) { entityBuilder . addPart ( "file" , new FileBody ( file ) ) ; } else if ( stream != null ) { entityBuilder . addBinaryBody ( "file" , stream ) ; } else { entityBuilder . addPart ( "file" , new ByteArrayBody ( bytes , filename ) ) ; } request . setEntity ( entityBuilder . build ( ) ) ; String fileId = client . getRequestHelper ( ) . executeQuery ( request , false , UploadBaseData . class ) . file ; return client . getFile ( fileId ) ;


signature:
public class RequestHelper { /** * Executes the request et the Uploadcare API and return the HTTP Response object .
 * The existence of this method ( and it ' s return type ) enables the end user to extend the
 * functionality of the
 * Uploadcare API client by creating a subclass of { @ link com . uploadcare . api . Client } .
 * @ param request request to be sent to the API
 * @ param apiHeaders TRUE if the default API headers should be set
 * @ return HTTP Response object */
public HttpResponse executeCommand ( HttpUriRequest request , boolean apiHeaders ) { } }

implementation: if ( apiHeaders ) { setApiHeaders ( request ) ; } try { CloseableHttpResponse response = client . getHttpClient ( ) . execute ( request ) ; try { checkResponseStatus ( response ) ; return response ; } finally { response . close ( ) ; } } catch ( IOException e ) { throw new UploadcareNetworkException ( e ) ; }


signature:
public class RequestHelper { /** * Verifies that the response status codes are within acceptable boundaries and throws
 * corresponding exceptions
 * otherwise .
 * @ param response The response object to be checked */
private void checkResponseStatus ( HttpResponse response ) throws IOException { } }

implementation: int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode >= 200 && statusCode < 300 ) { return ; } else if ( statusCode == 401 || statusCode == 403 ) { throw new UploadcareAuthenticationException ( streamToString ( response . getEntity ( ) . getContent ( ) ) ) ; } else if ( statusCode == 400 || statusCode == 404 ) { throw new UploadcareInvalidRequestException ( streamToString ( response . getEntity ( ) . getContent ( ) ) ) ; } else { throw new UploadcareApiException ( "Unknown exception during an API call, response:" + streamToString ( response . getEntity ( ) . getContent ( ) ) ) ; }


signature:
public class RequestHelper { /** * Convert an InputStream into a String object . Method taken from http : / / stackoverflow . com / a / 5445161/521535
 * @ param is The stream to be converted
 * @ return The resulting String */
private static String streamToString ( InputStream is ) { } }

implementation: java . util . Scanner s = new java . util . Scanner ( is , "UTF-8" ) . useDelimiter ( "\\A" ) ; return s . hasNext ( ) ? s . next ( ) : "" ;


signature:
public class Urls { /** * Creates a URL for URL upload .
 * @ param sourceUrl URL to upload from
 * @ param pubKey Public key
 * @ param store Store the file upon uploading .
 * @ see com . uploadcare . upload . UrlUploader */
public static URI uploadFromUrl ( String sourceUrl , String pubKey , String store ) { } }

implementation: URIBuilder builder = new URIBuilder ( URI . create ( UPLOAD_BASE ) ) ; builder . setPath ( "/from_url/" ) . setParameter ( "source_url" , sourceUrl ) . setParameter ( "pub_key" , pubKey ) . setParameter ( "store" , store ) ; return trustedBuild ( builder ) ;


signature:
public class Urls { /** * Creates a URL for URL upload status ( e . g . progress ) .
 * @ param token Token , received after a URL upload request
 * @ see com . uploadcare . upload . UrlUploader */
public static URI uploadFromUrlStatus ( String token ) { } }

implementation: URIBuilder builder = new URIBuilder ( URI . create ( UPLOAD_BASE ) ) ; builder . setPath ( "/from_url/status/" ) . setParameter ( "token" , token ) ; return trustedBuild ( builder ) ;


signature:
public class InjectingActionBarActivity { /** * Injects a target object using this ActionBarActivity ' s object graph .
 * @ param target the target object */
@ Override public void inject ( Object target ) { } }

implementation: checkState ( mObjectGraph != null , "object graph must be assigned prior to calling inject" ) ; mObjectGraph . inject ( target ) ;


signature:
public class InjectingActionBarActivity { /** * Creates an object graph for this ActionBarActivity by extending the application - scope object graph with the
 * modules returned by { @ link # getModules ( ) } .
 * Injects this ActionBarActivity using the created graph . */
@ Override protected void onCreate ( android . os . Bundle savedInstanceState ) { } }

implementation:
// expand the application graph with the activity - specific module ( s )
ObjectGraph appGraph = ( ( Injector ) getApplication ( ) ) . getObjectGraph ( ) ; List < Object > activityModules = getModules ( ) ; mObjectGraph = appGraph . plus ( activityModules . toArray ( ) ) ; // now we can inject ourselves
inject ( this ) ; // note : we do the graph setup and injection before calling super . onCreate so that InjectingFragments
// associated with this InjectingActivity can do their graph setup and injection in their
// onAttach override .
super . onCreate ( savedInstanceState ) ;


signature:
public class InjectingActionBarActivity { /** * Returns the list of dagger modules to be included in this ActionBarActivity ' s object graph . Subclasses that
 * override this method should add to the list returned by super . getModules ( ) .
 * @ return the list of modules */
protected List < Object > getModules ( ) { } }

implementation: List < Object > result = new ArrayList < Object > ( ) ; result . add ( new InjectingActivityModule ( this , this ) ) ; return result ;


signature:
public class InjectingBroadcastReceiver { /** * Returns the list of dagger modules to be included in this BroadcastReceiver ' s object graph . Subclasses that
 * override this method should add to the list returned by super . getModules ( ) .
 * @ return the list of modules */
protected List < Object > getModules ( ) { } }

implementation: List < Object > result = new ArrayList < Object > ( ) ; result . add ( new InjectingBroadcastReceiverModule ( mContext , this , this ) ) ; return result ;


signature:
public class InjectingService { /** * Creates an object graph for this Service by extending the application - scope object graph with the modules
 * returned by { @ link # getModules ( ) } .
 * Injects this Service using the created graph . */
@ Override public void onCreate ( ) { } }

implementation:
super . onCreate ( ) ; // extend the application - scope object graph with the modules for this service
mObjectGraph = ( ( Injector ) getApplication ( ) ) . getObjectGraph ( ) . plus ( getModules ( ) . toArray ( ) ) ; // then inject ourselves
mObjectGraph . inject ( this ) ;


signature:
public class InjectingActivity { /** * Creates an object graph for this Activity by extending the application - scope object graph with the modules
 * returned by { @ link # getModules ( ) } .
 * Injects this Activity using the created graph . */
@ Override protected void onCreate ( android . os . Bundle savedInstanceState ) { } }

implementation:
// extend the application - scope object graph with the modules for this activity
mObjectGraph = ( ( Injector ) getApplication ( ) ) . getObjectGraph ( ) . plus ( getModules ( ) . toArray ( ) ) ; // now we can inject ourselves
inject ( this ) ; // note : we do the graph setup and injection before calling super . onCreate so that InjectingFragments
// associated with this InjectingActivity can do their graph setup and injection in their
// onAttach override .
super . onCreate ( savedInstanceState ) ;


signature:
public class InjectingListFragment { /** * Returns the list of dagger modules to be included in this ListFragment ' s object graph . Subclasses that override
 * this method should add to the list returned by super . getModules ( ) .
 * @ return the list of modules */
protected List < Object > getModules ( ) { } }

implementation: List < Object > result = new ArrayList < Object > ( ) ; result . add ( new InjectingFragmentModule ( this , this ) ) ; return result ;


signature:
public class InjectingApplication { /** * Creates an object graph for this Application using the modules returned by { @ link # getModules ( ) } .
 * Injects this Application using the created graph . */
@ Override public void onCreate ( ) { } }

implementation:
super . onCreate ( ) ; // initialize object graph and inject this
mObjectGraph = ObjectGraph . create ( getModules ( ) . toArray ( ) ) ; mObjectGraph . inject ( this ) ; // debug mode stuff
if ( ( getApplicationInfo ( ) . flags & ApplicationInfo . FLAG_DEBUGGABLE ) == 1 ) { mObjectGraph . validate ( ) ; // validate dagger ' s object graph
}


signature:
public class InjectingApplication { /** * Returns the list of dagger modules to be included in this Application ' s object graph . Subclasses that override
 * this method should add to the list returned by super . getModules ( ) .
 * @ return the list of modules */
protected List < Object > getModules ( ) { } }

implementation: List < Object > result = new ArrayList < Object > ( ) ; result . addAll ( mSeedModules ) ; result . add ( new InjectingApplicationModule ( this , this ) ) ; return result ;


signature:
public class InjectingFragment { /** * Creates an object graph for this Fragment by extending the hosting Activity ' s object graph with the modules
 * returned by { @ link # getModules ( ) } .
 * Injects this Fragment using the created graph . */
@ Override public void onAttach ( Activity activity ) { } }

implementation:
super . onAttach ( activity ) ; // expand the activity graph with the fragment - specific module ( s )
ObjectGraph appGraph = ( ( Injector ) activity ) . getObjectGraph ( ) ; List < Object > fragmentModules = getModules ( ) ; mObjectGraph = appGraph . plus ( fragmentModules . toArray ( ) ) ; // make sure it ' s the first time through ; we don ' t want to re - inject a retained fragment that is going
// through a detach / attach sequence .
if ( mFirstAttach ) { inject ( this ) ; mFirstAttach = false ; }


signature:
public class InjectingAppWidgetProvider { /** * Creates an object graph for this AppWidgetProvider by extending the application - scope object graph with the
 * modules returned by { @ link # getModules ( ) } .
 * Injects this AppWidgetProvider using the created graph . */
@ Override public void onReceive ( Context context , Intent intent ) { } }

implementation:
mContext = context ; // extend the application - scope object graph with the modules for this AppWidgetProvider
mObjectGraph = ( ( Injector ) context . getApplicationContext ( ) ) . getObjectGraph ( ) . plus ( getModules ( ) . toArray ( ) ) ; // then inject ourselves
mObjectGraph . inject ( this ) ; super . onReceive ( context , intent ) ;