signature:
public class DefaultRequestDirector { /** * non - javadoc , see interface ClientRequestDirector */
@ Override public HttpResponse execute ( HttpHost target , HttpRequest request , HttpContext context ) throws HttpException , IOException { } }

implementation:
HttpRequest orig = request ; RequestWrapper origWrapper = wrapRequest ( orig ) ; origWrapper . setParams ( params ) ; HttpRoute origRoute = determineRoute ( target , origWrapper , context ) ; virtualHost = ( HttpHost ) orig . getParams ( ) . getParameter ( ClientPNames . VIRTUAL_HOST ) ; RoutedRequest roureq = new RoutedRequest ( origWrapper , origRoute ) ; long timeout = ConnManagerParams . getTimeout ( params ) ; int execCount = 0 ; boolean reuse = false ; boolean done = false ; try { HttpResponse response = null ; while ( ! done ) { // In this loop , the RoutedRequest may be replaced by a
// followup request and route . The request and route passed
// in the method arguments will be replaced . The original
// request is still available in ' orig ' .
RequestWrapper wrapper = roureq . getRequest ( ) ; HttpRoute route = roureq . getRoute ( ) ; response = null ; // See if we have a user token bound to the execution context
Object userToken = context . getAttribute ( ClientContext . USER_TOKEN ) ; // Allocate connection if needed
if ( managedConn == null ) { ClientConnectionRequest connRequest = connManager . requestConnection ( route , userToken ) ; if ( orig instanceof AbortableHttpRequest ) { ( ( AbortableHttpRequest ) orig ) . setConnectionRequest ( connRequest ) ; } try { managedConn = connRequest . getConnection ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException interrupted ) { InterruptedIOException iox = new InterruptedIOException ( ) ; iox . initCause ( interrupted ) ; throw iox ; } if ( HttpConnectionParams . isStaleCheckingEnabled ( params ) ) { // validate connection
if ( managedConn . isOpen ( ) ) { this . log . debug ( "Stale connection check" ) ; if ( managedConn . isStale ( ) ) { this . log . debug ( "Stale connection detected" ) ; managedConn . close ( ) ; } } } } if ( orig instanceof AbortableHttpRequest ) { ( ( AbortableHttpRequest ) orig ) . setReleaseTrigger ( managedConn ) ; } // Reopen connection if needed
if ( ! managedConn . isOpen ( ) ) { managedConn . open ( route , context , params ) ; } else { managedConn . setSocketTimeout ( HttpConnectionParams . getSoTimeout ( params ) ) ; } try { establishRoute ( route , context ) ; } catch ( TunnelRefusedException ex ) { if ( this . log . isDebugEnabled ( ) ) { this . log . debug ( ex . getMessage ( ) ) ; } response = ex . getResponse ( ) ; break ; } // Reset headers on the request wrapper
wrapper . resetHeaders ( ) ; // Re - write request URI if needed
rewriteRequestURI ( wrapper , route ) ; // Use virtual host if set
target = virtualHost ; if ( target == null ) { target = route . getTargetHost ( ) ; } HttpHost proxy = route . getProxyHost ( ) ; // Populate the execution context
context . setAttribute ( ExecutionContext . HTTP_TARGET_HOST , target ) ; context . setAttribute ( ExecutionContext . HTTP_PROXY_HOST , proxy ) ; context . setAttribute ( ExecutionContext . HTTP_CONNECTION , managedConn ) ; context . setAttribute ( ClientContext . TARGET_AUTH_STATE , targetAuthState ) ; context . setAttribute ( ClientContext . PROXY_AUTH_STATE , proxyAuthState ) ; // Run request protocol interceptors
requestExec . preProcess ( wrapper , httpProcessor , context ) ; boolean retrying = true ; Exception retryReason = null ; while ( retrying ) { // Increment total exec count ( with redirects )
execCount ++ ; // Increment exec count for this particular request
wrapper . incrementExecCount ( ) ; if ( ! wrapper . isRepeatable ( ) ) { this . log . debug ( "Cannot retry non-repeatable request" ) ; if ( retryReason != null ) { throw new NonRepeatableRequestException ( "Cannot retry request " + "with a non-repeatable request entity.  The cause lists the " + "reason the original request failed: " + retryReason ) ; } else { throw new NonRepeatableRequestException ( "Cannot retry request " + "with a non-repeatable request entity." ) ; } } try { if ( this . log . isDebugEnabled ( ) ) { this . log . debug ( "Attempt " + execCount + " to execute request" ) ; } response = requestExec . execute ( wrapper , managedConn , context ) ; retrying = false ; } catch ( IOException ex ) { this . log . debug ( "Closing the connection." ) ; managedConn . close ( ) ; if ( retryHandler . retryRequest ( ex , wrapper . getExecCount ( ) , context ) ) { if ( this . log . isInfoEnabled ( ) ) { this . log . info ( "I/O exception (" + ex . getClass ( ) . getName ( ) + ") caught when processing request: " + ex . getMessage ( ) ) ; } if ( this . log . isDebugEnabled ( ) ) { this . log . debug ( ex . getMessage ( ) , ex ) ; } this . log . info ( "Retrying request" ) ; retryReason = ex ; } else { throw ex ; } // If we have a direct route to the target host
// just re - open connection and re - try the request
if ( ! route . isTunnelled ( ) ) { this . log . debug ( "Reopening the direct connection." ) ; managedConn . open ( route , context , params ) ; } else { // otherwise give up
this . log . debug ( "Proxied connection. Need to start over." ) ; retrying = false ; } } } if ( response == null ) { // Need to start over
continue ; } // Run response protocol interceptors
response . setParams ( params ) ; requestExec . postProcess ( response , httpProcessor , context ) ; // The connection is in or can be brought to a re - usable state .
reuse = reuseStrategy . keepAlive ( response , context ) ; if ( reuse ) { // Set the idle duration of this connection
long duration = keepAliveStrategy . getKeepAliveDuration ( response , context ) ; managedConn . setIdleDuration ( duration , TimeUnit . MILLISECONDS ) ; if ( this . log . isDebugEnabled ( ) ) { if ( duration >= 0 ) { this . log . debug ( "Connection can be kept alive for " + duration + " ms" ) ; } else { this . log . debug ( "Connection can be kept alive indefinitely" ) ; } } } RoutedRequest followup = handleResponse ( roureq , response , context ) ; if ( followup == null ) { done = true ; } else { if ( reuse ) { // Make sure the response body is fully consumed , if present
HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { entity . consumeContent ( ) ; } // entity consumed above is not an auto - release entity ,
// need to mark the connection re - usable explicitly
managedConn . markReusable ( ) ; } else { managedConn . close ( ) ; } // check if we can use the same connection for the followup
if ( ! followup . getRoute ( ) . equals ( roureq . getRoute ( ) ) ) { releaseConnection ( ) ; } roureq = followup ; } if ( managedConn != null && userToken == null ) { userToken = userTokenHandler . getUserToken ( context ) ; context . setAttribute ( ClientContext . USER_TOKEN , userToken ) ; if ( userToken != null ) { managedConn . setState ( userToken ) ; } } } // while not done
// check for entity , release connection if possible
if ( ( response == null ) || ( response . getEntity ( ) == null ) || ! response . getEntity ( ) . isStreaming ( ) ) { // connection not needed and ( assumed to be ) in re - usable state
if ( reuse ) managedConn . markReusable ( ) ; releaseConnection ( ) ; } else { // install an auto - release entity
HttpEntity entity = response . getEntity ( ) ; entity = new BasicManagedEntity ( entity , managedConn , reuse ) ; response . setEntity ( entity ) ; } return response ; } catch ( HttpException | RuntimeException | IOException ex ) { abortConnection ( ) ; throw ex ; }


signature:
public class DefaultRequestDirector { /** * Returns the connection back to the connection manager
 * and prepares for retrieving a new connection during
 * the next request . */
protected void releaseConnection ( ) { } }

implementation:
// Release the connection through the ManagedConnection instead of the
// ConnectionManager directly . This lets the connection control how
// it is released .
try { managedConn . releaseConnection ( ) ; } catch ( IOException ignored ) { this . log . debug ( "IOException releasing connection" , ignored ) ; } managedConn = null ;


signature:
public class DefaultRequestDirector { /** * Determines the route for a request .
 * Called by { @ link # execute }
 * to determine the route for either the original or a followup request .
 * @ param target the target host for the request .
 * Implementations may accept { @ code null }
 * if they can still determine a route , for example
 * to a default target or by inspecting the request .
 * @ param request the request to execute
 * @ param context the context to use for the execution ,
 * never { @ code null }
 * @ return the route the request should take
 * @ throws HttpException in case of a problem */
protected HttpRoute determineRoute ( HttpHost target , HttpRequest request , HttpContext context ) throws HttpException { } }

implementation: if ( target == null ) { target = ( HttpHost ) request . getParams ( ) . getParameter ( ClientPNames . DEFAULT_HOST ) ; } if ( target == null ) { throw new IllegalStateException ( "Target host must not be null, or set in parameters." ) ; } return this . routePlanner . determineRoute ( target , request , context ) ;


signature:
public class DefaultRequestDirector { /** * Establishes the target route .
 * @ param route the route to establish
 * @ param context the context for the request execution
 * @ throws HttpException in case of a problem
 * @ throws IOException in case of an IO problem */
protected void establishRoute ( HttpRoute route , HttpContext context ) throws HttpException , IOException { } }

implementation:
HttpRouteDirector rowdy = new BasicRouteDirector ( ) ; int step ; do { HttpRoute fact = managedConn . getRoute ( ) ; step = rowdy . nextStep ( route , fact ) ; switch ( step ) { case HttpRouteDirector . CONNECT_TARGET : case HttpRouteDirector . CONNECT_PROXY : managedConn . open ( route , context , this . params ) ; break ; case HttpRouteDirector . TUNNEL_TARGET : { boolean secure = createTunnelToTarget ( route , context ) ; this . log . debug ( "Tunnel to target created." ) ; managedConn . tunnelTarget ( secure , this . params ) ; } break ; case HttpRouteDirector . TUNNEL_PROXY : { // The most simple example for this case is a proxy chain
// of two proxies , where P1 must be tunnelled to P2.
// route : Source - > P1 - > P2 - > Target ( 3 hops )
// fact : Source - > P1 - > Target ( 2 hops )
final int hop = fact . getHopCount ( ) - 1 ; // the hop to establish
boolean secure = createTunnelToProxy ( route , hop , context ) ; this . log . debug ( "Tunnel to proxy created." ) ; managedConn . tunnelProxy ( route . getHopTarget ( hop ) , secure , this . params ) ; } break ; case HttpRouteDirector . LAYER_PROTOCOL : managedConn . layerProtocol ( context , this . params ) ; break ; case HttpRouteDirector . UNREACHABLE : throw new IllegalStateException ( "Unable to establish route." + "\nplanned = " + route + "\ncurrent = " + fact ) ; case HttpRouteDirector . COMPLETE : // do nothing
break ; default : throw new IllegalStateException ( "Unknown step indicator " + step + " from RouteDirector." ) ; } // switch
} while ( step > HttpRouteDirector . COMPLETE ) ;


signature:
public class DefaultRequestDirector { /** * Creates a tunnel to the target server .
 * The connection must be established to the ( last ) proxy .
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent , the response received and checked .
 * This method does < i > not < / i > update the connection with
 * information about the tunnel , that is left to the caller .
 * @ param route the route to establish
 * @ param context the context for request execution
 * @ return { @ code true } if the tunnelled route is secure ,
 * { @ code false } otherwise .
 * The implementation here always returns { @ code false } ,
 * but derived classes may override .
 * @ throws HttpException in case of a problem
 * @ throws IOException in case of an IO problem */
protected boolean createTunnelToTarget ( HttpRoute route , HttpContext context ) throws HttpException , IOException { } }

implementation:
HttpHost proxy = route . getProxyHost ( ) ; HttpHost target = route . getTargetHost ( ) ; HttpResponse response = null ; boolean done = false ; while ( ! done ) { done = true ; if ( ! this . managedConn . isOpen ( ) ) { this . managedConn . open ( route , context , this . params ) ; } HttpRequest connect = createConnectRequest ( route , context ) ; connect . setParams ( this . params ) ; // Populate the execution context
context . setAttribute ( ExecutionContext . HTTP_TARGET_HOST , target ) ; context . setAttribute ( ExecutionContext . HTTP_PROXY_HOST , proxy ) ; context . setAttribute ( ExecutionContext . HTTP_CONNECTION , managedConn ) ; context . setAttribute ( ClientContext . TARGET_AUTH_STATE , targetAuthState ) ; context . setAttribute ( ClientContext . PROXY_AUTH_STATE , proxyAuthState ) ; context . setAttribute ( ExecutionContext . HTTP_REQUEST , connect ) ; this . requestExec . preProcess ( connect , this . httpProcessor , context ) ; response = this . requestExec . execute ( connect , this . managedConn , context ) ; response . setParams ( this . params ) ; this . requestExec . postProcess ( response , this . httpProcessor , context ) ; int status = response . getStatusLine ( ) . getStatusCode ( ) ; if ( status < 200 ) { throw new HttpException ( "Unexpected response to CONNECT request: " + response . getStatusLine ( ) ) ; } CredentialsProvider credsProvider = ( CredentialsProvider ) context . getAttribute ( ClientContext . CREDS_PROVIDER ) ; if ( credsProvider != null && HttpClientParams . isAuthenticating ( params ) ) { if ( this . proxyAuthHandler . isAuthenticationRequested ( response , context ) ) { this . log . debug ( "Proxy requested authentication" ) ; Map < String , Header > challenges = this . proxyAuthHandler . getChallenges ( response , context ) ; try { processChallenges ( challenges , this . proxyAuthState , this . proxyAuthHandler , response , context ) ; } catch ( AuthenticationException ex ) { if ( this . log . isWarnEnabled ( ) ) { this . log . warn ( "Authentication error: " + ex . getMessage ( ) ) ; break ; } } updateAuthState ( this . proxyAuthState , proxy , credsProvider ) ; if ( this . proxyAuthState . getCredentials ( ) != null ) { done = false ; // Retry request
if ( this . reuseStrategy . keepAlive ( response , context ) ) { this . log . debug ( "Connection kept alive" ) ; // Consume response content
HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { entity . consumeContent ( ) ; } } else { this . managedConn . close ( ) ; } } } else { // Reset proxy auth scope
this . proxyAuthState . setAuthScope ( null ) ; } } } int status = response . getStatusLine ( ) . getStatusCode ( ) ; // can ' t be null
if ( status > 299 ) { // Buffer response content
HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { response . setEntity ( new BufferedHttpEntity ( entity ) ) ; } this . managedConn . close ( ) ; throw new TunnelRefusedException ( "CONNECT refused by proxy: " + response . getStatusLine ( ) , response ) ; } this . managedConn . markReusable ( ) ; // How to decide on security of the tunnelled connection ?
// The socket factory knows only about the segment to the proxy .
// Even if that is secure , the hop to the target may be insecure .
// Leave it to derived classes , consider insecure by default here .
return false ;


signature:
public class DefaultRequestDirector { /** * Creates the CONNECT request for tunnelling .
 * Called by { @ link # createTunnelToTarget createTunnelToTarget } .
 * @ param route the route to establish
 * @ param context the context for request execution
 * @ return the CONNECT request for tunnelling */
protected HttpRequest createConnectRequest ( HttpRoute route , HttpContext context ) { } }

implementation:
// see RFC 2817 , section 5.2 and
// INTERNET - DRAFT : Tunneling TCP based protocols through
// Web proxy servers
HttpHost target = route . getTargetHost ( ) ; String host = target . getHostName ( ) ; int port = target . getPort ( ) ; if ( port < 0 ) { Scheme scheme = connManager . getSchemeRegistry ( ) . getScheme ( target . getSchemeName ( ) ) ; port = scheme . getDefaultPort ( ) ; } StringBuilder buffer = new StringBuilder ( host . length ( ) + 6 ) ; buffer . append ( host ) ; buffer . append ( ':' ) ; buffer . append ( Integer . toString ( port ) ) ; String authority = buffer . toString ( ) ; ProtocolVersion ver = HttpProtocolParams . getVersion ( params ) ; HttpRequest req = new BasicHttpRequest ( "CONNECT" , authority , ver ) ; return req ;


signature:
public class DefaultRequestDirector { /** * Analyzes a response to check need for a followup .
 * @ param roureq the request and route .
 * @ param response the response to analayze
 * @ param context the context used for the current request execution
 * @ return the followup request and route if there is a followup , or
 * { @ code null } if the response should be returned as is
 * @ throws HttpException in case of a problem
 * @ throws IOException in case of an IO problem */
protected RoutedRequest handleResponse ( RoutedRequest roureq , HttpResponse response , HttpContext context ) throws HttpException , IOException { } }

implementation:
HttpRoute route = roureq . getRoute ( ) ; RequestWrapper request = roureq . getRequest ( ) ; HttpParams params = request . getParams ( ) ; if ( HttpClientParams . isRedirecting ( params ) && this . redirectHandler . isRedirectRequested ( response , context ) ) { if ( redirectCount >= maxRedirects ) { throw new RedirectException ( "Maximum redirects (" + maxRedirects + ") exceeded" ) ; } redirectCount ++ ; // Virtual host cannot be used any longer
virtualHost = null ; URI uri = this . redirectHandler . getLocationURI ( response , context ) ; HttpHost newTarget = new HttpHost ( uri . getHost ( ) , uri . getPort ( ) , uri . getScheme ( ) ) ; // Unset auth scope
targetAuthState . setAuthScope ( null ) ; proxyAuthState . setAuthScope ( null ) ; // Invalidate auth states if redirecting to another host
if ( ! route . getTargetHost ( ) . equals ( newTarget ) ) { targetAuthState . invalidate ( ) ; AuthScheme authScheme = proxyAuthState . getAuthScheme ( ) ; if ( authScheme != null && authScheme . isConnectionBased ( ) ) { proxyAuthState . invalidate ( ) ; } } HttpRedirect redirect = new HttpRedirect ( request . getMethod ( ) , uri ) ; HttpRequest orig = request . getOriginal ( ) ; redirect . setHeaders ( orig . getAllHeaders ( ) ) ; RequestWrapper wrapper = new RequestWrapper ( redirect ) ; wrapper . setParams ( params ) ; HttpRoute newRoute = determineRoute ( newTarget , wrapper , context ) ; RoutedRequest newRequest = new RoutedRequest ( wrapper , newRoute ) ; if ( this . log . isDebugEnabled ( ) ) { this . log . debug ( "Redirecting to '" + uri + "' via " + newRoute ) ; } return newRequest ; } CredentialsProvider credsProvider = ( CredentialsProvider ) context . getAttribute ( ClientContext . CREDS_PROVIDER ) ; if ( credsProvider != null && HttpClientParams . isAuthenticating ( params ) ) { if ( this . targetAuthHandler . isAuthenticationRequested ( response , context ) ) { HttpHost target = ( HttpHost ) context . getAttribute ( ExecutionContext . HTTP_TARGET_HOST ) ; if ( target == null ) { target = route . getTargetHost ( ) ; } this . log . debug ( "Target requested authentication" ) ; Map < String , Header > challenges = this . targetAuthHandler . getChallenges ( response , context ) ; try { processChallenges ( challenges , this . targetAuthState , this . targetAuthHandler , response , context ) ; } catch ( AuthenticationException ex ) { if ( this . log . isWarnEnabled ( ) ) { this . log . warn ( "Authentication error: " + ex . getMessage ( ) ) ; return null ; } } updateAuthState ( this . targetAuthState , target , credsProvider ) ; if ( this . targetAuthState . getCredentials ( ) != null ) { // Re - try the same request via the same route
return roureq ; } else { return null ; } } else { // Reset target auth scope
this . targetAuthState . setAuthScope ( null ) ; } if ( this . proxyAuthHandler . isAuthenticationRequested ( response , context ) ) { HttpHost proxy = route . getProxyHost ( ) ; this . log . debug ( "Proxy requested authentication" ) ; Map < String , Header > challenges = this . proxyAuthHandler . getChallenges ( response , context ) ; try { processChallenges ( challenges , this . proxyAuthState , this . proxyAuthHandler , response , context ) ; } catch ( AuthenticationException ex ) { if ( this . log . isWarnEnabled ( ) ) { this . log . warn ( "Authentication error: " + ex . getMessage ( ) ) ; return null ; } } updateAuthState ( this . proxyAuthState , proxy , credsProvider ) ; if ( this . proxyAuthState . getCredentials ( ) != null ) { // Re - try the same request via the same route
return roureq ; } else { return null ; } } else { // Reset proxy auth scope
this . proxyAuthState . setAuthScope ( null ) ; } } return null ;


signature:
public class DefaultRequestDirector { /** * Shuts down the connection .
 * This method is called from a { @ code catch } block in
 * { @ link # execute execute } during exception handling . */
private void abortConnection ( ) { } }

implementation:
ManagedClientConnection mcc = managedConn ; if ( mcc != null ) { // we got here as the result of an exception
// no response will be returned , release the connection
managedConn = null ; try { mcc . abortConnection ( ) ; } catch ( IOException ex ) { if ( this . log . isDebugEnabled ( ) ) { this . log . debug ( ex . getMessage ( ) , ex ) ; } } // ensure the connection manager properly releases this connection
try { mcc . releaseConnection ( ) ; } catch ( IOException ignored ) { this . log . debug ( "Error releasing connection" , ignored ) ; } }


signature:
public class DefaultRequestDirector { /** * abortConnection */
private void processChallenges ( final Map < String , Header > challenges , final AuthState authState , final AuthenticationHandler authHandler , final HttpResponse response , final HttpContext context ) throws MalformedChallengeException , AuthenticationException { } }

implementation:
AuthScheme authScheme = authState . getAuthScheme ( ) ; if ( authScheme == null ) { // Authentication not attempted before
authScheme = authHandler . selectScheme ( challenges , response , context ) ; authState . setAuthScheme ( authScheme ) ; } String id = authScheme . getSchemeName ( ) ; Header challenge = challenges . get ( id . toLowerCase ( Locale . ENGLISH ) ) ; if ( challenge == null ) { throw new AuthenticationException ( id + " authorization challenge expected, but not found" ) ; } authScheme . processChallenge ( challenge ) ; this . log . debug ( "Authorization challenge processed" ) ;


signature:
public class TypeMapper { /** * remap android / Foo to android / Bar */
String mappedTypeName ( String internalName ) { } }

implementation: String remappedInternalName = classesToRemap . get ( internalName ) ; if ( remappedInternalName != null ) { return remappedInternalName ; } else { return internalName ; }


signature:
public class InstrumentingClassWriter { /** * Returns the common super type of the two given types without actually loading
 * the classes in the ClassLoader . */
@ Override protected String getCommonSuperClass ( final String type1 , final String type2 ) { } }

implementation:
try { ClassNode info1 = typeInfo ( type1 ) ; ClassNode info2 = typeInfo ( type2 ) ; if ( ( info1 . access & Opcodes . ACC_INTERFACE ) != 0 ) { if ( typeImplements ( type2 , info2 , type1 ) ) { return type1 ; } if ( ( info2 . access & Opcodes . ACC_INTERFACE ) != 0 ) { if ( typeImplements ( type1 , info1 , type2 ) ) { return type2 ; } } return "java/lang/Object" ; } if ( ( info2 . access & Opcodes . ACC_INTERFACE ) != 0 ) { if ( typeImplements ( type1 , info1 , type2 ) ) { return type2 ; } else { return "java/lang/Object" ; } } String b1 = typeAncestors ( type1 , info1 ) ; String b2 = typeAncestors ( type2 , info2 ) ; String result = "java/lang/Object" ; int end1 = b1 . length ( ) ; int end2 = b2 . length ( ) ; while ( true ) { int start1 = b1 . lastIndexOf ( ';' , end1 - 1 ) ; int start2 = b2 . lastIndexOf ( ';' , end2 - 1 ) ; if ( start1 != - 1 && start2 != - 1 && end1 - start1 == end2 - start2 ) { String p1 = b1 . substring ( start1 + 1 , end1 ) ; String p2 = b2 . substring ( start2 + 1 , end2 ) ; if ( p1 . equals ( p2 ) ) { result = p1 ; end1 = start1 ; end2 = start2 ; } else { return result ; } } else { return result ; } } } catch ( ClassNotFoundException e ) { return "java/lang/Object" ; // Handle classes that may be obfuscated
}


signature:
public class ShadowUsageCheck { /** * Renames the given { @ link Symbol } and its usages in the current compilation unit to { @ code
 * newName } . */
static VariableFixer fixVar ( Symbol symbol , VisitorState state , PossibleFixes possibleFixes ) { } }

implementation: return new VariableFixer ( symbol , state , possibleFixes ) ;


signature:
public class ShadowStorageManager { /** * Checks whether File belongs to any { @ link StorageVolume } in the list returned by { @ link
 * # getStorageVolumes ( ) } .
 * @ param File to check
 * @ return StorageVolume for the file */
@ Implementation ( minSdk = N ) public StorageVolume getStorageVolume ( File file ) { } }

implementation: for ( StorageVolume volume : storageVolumeList ) { File volumeFile = volume . getPathFile ( ) ; if ( file . getAbsolutePath ( ) . equals ( volumeFile . getAbsolutePath ( ) ) ) { return volume ; } } return null ;


signature:
public class ShadowResources { /** * Since { @ link AssetFileDescriptor } s are not yet supported by Robolectric , { @ code null } will be
 * returned if the resource is found . If the resource cannot be found , { @ link
 * Resources . NotFoundException } will be thrown . */
@ Implementation protected AssetFileDescriptor openRawResourceFd ( int id ) throws Resources . NotFoundException { } }

implementation:
if ( isLegacyAssetManager ( ) ) { InputStream inputStream = openRawResource ( id ) ; if ( ! ( inputStream instanceof FileInputStream ) ) { // todo fixme
return null ; } FileInputStream fis = ( FileInputStream ) inputStream ; try { return new AssetFileDescriptor ( ParcelFileDescriptor . dup ( fis . getFD ( ) ) , 0 , fis . getChannel ( ) . size ( ) ) ; } catch ( IOException e ) { throw newNotFoundException ( id ) ; } } else { return directlyOn ( realResources , Resources . class ) . openRawResourceFd ( id ) ; }


signature:
public class PluginFinder { /** * Returns an implementation class for the specified plugin .
 * If there is more than such one candidate , the classes will be sorted by { @ link Priority }
 * and the one with the highest priority will be returned . If multiple classes claim the same
 * priority , a { @ link ServiceConfigurationError } will be thrown . Classes without a Priority
 * are treated as ` @ Priority ( 0 ) ` .
 * @ param pluginType the class of the plugin type
 * @ param < T > the class of the plugin type
 * @ return the implementing class with the highest priority */
@ Nullable < T > Class < ? extends T > findPlugin ( Class < T > pluginType ) { } }

implementation: return best ( pluginType , findPlugins ( pluginType ) ) ;


signature:
public class PluginFinder { /** * Returns a list of implementation classes for the specified plugin , ordered from highest to
 * lowest priority . If no implementing classes can be found , an empty list is returned .
 * @ param pluginType the class of the plugin type
 * @ param < T > the class of the plugin type
 * @ return a prioritized list of implementation classes */
@ Nonnull < T > List < Class < ? extends T > > findPlugins ( Class < T > pluginType ) { } }

implementation: return prioritize ( filter ( serviceFinderAdapter . load ( pluginType ) ) ) ;


signature:
public class Strftime { /** * Format a date string .
 * @ param format The format in strftime syntax .
 * @ param date The date to format .
 * @ param locale The locale to use for formatting .
 * @ param zone The timezone to use for formatting .
 * @ return The formatted datetime . */
public static String format ( String format , final Date date , Locale locale , TimeZone zone ) { } }

implementation:
StringBuilder buffer = new StringBuilder ( ) ; class Formatter { SimpleDateFormat formatter ; public Formatter ( Date date , Locale locale , TimeZone timeZone ) { if ( locale != null ) { formatter = new SimpleDateFormat ( "" , locale ) ; } else { formatter = new SimpleDateFormat ( "" ) ; } if ( timeZone != null ) { formatter . setTimeZone ( timeZone ) ; } } public String format ( String format ) { formatter . applyPattern ( format ) ; return formatter . format ( date ) ; } } Formatter formatter = new Formatter ( date , locale , zone ) ; Boolean inside = false ; Boolean removePad = false ; Boolean zeroPad = false ; Boolean spacePad = false ; Boolean upperCase = false ; Boolean swapCase = false ; StringBuilder padWidthBuffer = new StringBuilder ( ) ; for ( int i = 0 ; i < format . length ( ) ; i ++ ) { Character c = format . charAt ( i ) ; if ( ! inside && c == '%' ) { inside = true ; removePad = false ; zeroPad = false ; spacePad = false ; upperCase = false ; swapCase = false ; padWidthBuffer = new StringBuilder ( ) ; } else if ( inside ) { inside = false ; switch ( c ) { // % a Abbreviated weekday name according to locale .
case 'a' : buffer . append ( correctCase ( formatter . format ( "EEE" ) , upperCase , swapCase ) ) ; break ; // % A Full weekday name according to locale .
case 'A' : buffer . append ( correctCase ( formatter . format ( "EEEE" ) , upperCase , swapCase ) ) ; break ; // % b Abbreviated month name according to locale .
case 'b' : buffer . append ( correctCase ( formatter . format ( "MMM" ) , upperCase , swapCase ) ) ; break ; // % B Full month name according to locale .
case 'B' : buffer . append ( correctCase ( formatter . format ( "MMMM" ) , upperCase , swapCase ) ) ; break ; // % c Preferred date and time representation for locale .
case 'c' : // NOTE : en _ US locale
buffer . append ( formatter . format ( "EEE dd MMM yyyy hh:mm:ss aa z" ) ) ; break ; // % C Year divided by 100 and truncated to integer ( 00-99 ) .
case 'C' : buffer . append ( formatter . format ( "y" ) . substring ( 0 , 2 ) ) ; break ; // % d Day of the month as decimal number ( 01-31 ) .
case 'd' : buffer . append ( formatter . format ( "dd" ) ) ; break ; // % D Same as " % m / % d / % y "
case 'D' : buffer . append ( formatter . format ( "MM/dd/yy" ) ) ; break ; // % e Day of the month as decimal number , padded with space .
case 'e' : buffer . append ( correctPad ( formatter . format ( "dd" ) , zeroPad , true , removePad , ( padWidthBuffer . length ( ) <= 0 ? new StringBuilder ( "2" ) : padWidthBuffer ) ) ) ; break ; // % E Modifier , use a locale - dependent alternative representation .
case 'E' : inside = true ; throw new UnsupportedOperationException ( "Not implemented yet" ) ; // break ;
// % F ISO 8601 date format : " % Y - % m - % d " .
case 'F' : buffer . append ( formatter . format ( "yyyy-MM-dd" ) ) ; break ; // % g 2 - digit year version of % G , ( 00-99)
case 'g' : buffer . append ( formatter . format ( "YY" ) ) ; break ; // % G ISO 8601 week - based year .
case 'G' : buffer . append ( formatter . format ( "YYYY" ) ) ; break ; // % h Like % b .
case 'h' : buffer . append ( formatter . format ( "MMM" ) ) ; break ; // % H Hour ( 24 - hour clock ) as decimal number ( 00-23 ) .
case 'H' : buffer . append ( formatter . format ( "HH" ) ) ; break ; // % I Hour ( 12 - hour clock ) as decimal number ( 01-12 ) .
case 'I' : buffer . append ( formatter . format ( "hh" ) ) ; break ; // % j Day of the year as decimal number ( 001-366 ) .
case 'j' : buffer . append ( formatter . format ( "DDD" ) ) ; break ; // % k Hour ( 24 - hour clock ) as decimal number ( 0-23 ) , space padded .
case 'k' : buffer . append ( correctPad ( formatter . format ( "HH" ) , zeroPad , spacePad , removePad , ( padWidthBuffer . length ( ) <= 0 ? new StringBuilder ( "2" ) : padWidthBuffer ) ) ) ; break ; // % l Hour ( 12 - hour clock ) as decimal number ( 1-12 ) , space padded .
case 'l' : buffer . append ( correctPad ( formatter . format ( "hh" ) , zeroPad , spacePad || ! zeroPad , removePad , ( padWidthBuffer . length ( ) <= 0 ? new StringBuilder ( "2" ) : padWidthBuffer ) ) ) ; break ; // % m Month as decimal number ( 01-12 ) .
case 'm' : buffer . append ( correctPad ( formatter . format ( "MM" ) , zeroPad , spacePad , removePad , ( padWidthBuffer . length ( ) <= 0 ? new StringBuilder ( "2" ) : padWidthBuffer ) ) ) ; break ; // % M Minute as decimal number ( 00-59 ) .
case 'M' : buffer . append ( correctCase ( formatter . format ( "mm" ) , upperCase , swapCase ) ) ; break ; // % n Newline .
case 'n' : buffer . append ( formatter . format ( "\n" ) ) ; break ; // % O Modifier , use alternative numeric symbols ( say , Roman numerals ) .
case 'O' : inside = true ; throw new UnsupportedOperationException ( "Not implemented yet" ) ; // break ;
// % p " AM " , " PM " , or locale string . Noon = " PM " , midnight = " AM " .
case 'p' : buffer . append ( correctCase ( formatter . format ( "a" ) , upperCase , swapCase ) ) ; break ; // % P " am " , " pm " , or locale string . Noon = " pm " , midnight = " am " .
case 'P' : buffer . append ( correctCase ( formatter . format ( "a" ) . toLowerCase ( ) , upperCase , swapCase ) ) ; break ; // % r 12 - hour clock time .
case 'r' : buffer . append ( formatter . format ( "hh:mm:ss a" ) ) ; break ; // % R 24 - hour clock time , " % H : % M " .
case 'R' : buffer . append ( formatter . format ( "HH:mm" ) ) ; break ; // % s Number of seconds since Epoch , 1970-01-01 00:00:00 + 0000 ( UTC ) .
case 's' : buffer . append ( ( ( Long ) ( date . getTime ( ) / 1000 ) ) . toString ( ) ) ; break ; // % S Second as decimal number ( 00-60 ) . 60 for leap seconds .
case 'S' : buffer . append ( formatter . format ( "ss" ) ) ; break ; // % t Tab .
case 't' : buffer . append ( formatter . format ( "\t" ) ) ; break ; // % T 24 - hour time , " % H : % M : % S " .
case 'T' : buffer . append ( formatter . format ( "HH:mm:ss" ) ) ; break ; // % u The day of the week as a decimal , ( 1-7 ) . Monday being 1.
case 'u' : buffer . append ( formatter . format ( "u" ) ) ; break ; // % U week number of the current year as a decimal number , ( 00-53 ) .
// Starting with the first Sunday as the first day of week 01.
case 'U' : throw new UnsupportedOperationException ( "Not implemented yet" ) ; // buffer . append (
// formatter . format ( " ww " ) ) ;
// break ;
// % V ISO 8601 week number ( 00-53 ) .
// Week 1 is the first week that has at least 4 days in the new year .
case 'V' : buffer . append ( formatter . format ( "ww" ) ) ; break ; // % w Day of the week as a decimal , ( 0-6 ) . Sunday being 0.
case 'w' : String dayNumberOfWeek = formatter . format ( "u" ) ; // (1-7)
buffer . append ( ( dayNumberOfWeek . equals ( "7" ) ? "0" : dayNumberOfWeek ) ) ; break ; // % W Week number of the current year as a decimal number , ( 00-53 ) .
// Starting with the first Monday as the first day of week 01.
case 'W' : throw new UnsupportedOperationException ( "Not implemented yet" ) ; // buffer . append (
// formatter . format ( " ww " ) ) ;
// break ;
// % x Locale date without time .
case 'x' : buffer . append ( formatter . format ( "MM/dd/yyyy" ) ) ; break ; // % X Locale time without date .
case 'X' : buffer . append ( formatter . format ( "hh:mm:ss aa" ) ) ; // buffer . append (
// formatter . format ( " HH : mm : ss " ) ) ;
break ; // % y Year as decimal number without century ( 00-99 ) .
case 'y' : buffer . append ( formatter . format ( "yy" ) ) ; break ; // % Y Year as decimal number with century .
case 'Y' : buffer . append ( formatter . format ( "yyyy" ) ) ; break ; // % z Numeric timezone as hour and minute offset from UTC " + hhmm " or " - hhmm " .
case 'z' : buffer . append ( formatter . format ( "Z" ) ) ; break ; // % Z Timezone , name , or abbreviation .
case 'Z' : buffer . append ( formatter . format ( "z" ) ) ; break ; // % % Literal ' % ' .
case '%' : buffer . append ( formatter . format ( "%" ) ) ; break ; // glibc extension
// % ^ Force upper case .
case '^' : inside = true ; upperCase = true ; break ; // % # Swap case .
case '#' : inside = true ; swapCase = true ; break ; // % - Remove padding .
case '-' : inside = true ; removePad = true ; break ; // % _ Space pad .
case '_' : inside = true ; spacePad = true ; break ; // %0 Zero pad .
// 0 Alternatively if preceded by another digit , defines padding width .
case '0' : inside = true ; if ( padWidthBuffer . length ( ) == 0 ) { zeroPad = true ; spacePad = false ; } else { padWidthBuffer . append ( c ) ; } break ; // %1 Padding width .
case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : inside = true ; // zeroPad = ! spacePad ; / / Default to zero padding .
padWidthBuffer . append ( c ) ; break ; default : buffer . append ( c . toString ( ) ) ; break ; } } else { buffer . append ( c . toString ( ) ) ; } } return buffer . toString ( ) ;


signature:
public class XmlResourceParserImpl { /** * / * package */
public boolean isWhitespace ( String text ) throws XmlPullParserException { } }

implementation: if ( text == null ) { return false ; } return text . split ( "\\s" ) . length == 0 ;


signature:
public class XmlResourceParserImpl { /** * for testing only . . . */
public String qualify ( String value ) { } }

implementation: if ( value == null ) return null ; if ( AttributeResource . isResourceReference ( value ) ) { return "@" + ResName . qualifyResourceName ( value . trim ( ) . substring ( 1 ) . replace ( "+" , "" ) , packageName , "attr" ) ; } else if ( AttributeResource . isStyleReference ( value ) ) { return "?" + ResName . qualifyResourceName ( value . trim ( ) . substring ( 1 ) , packageName , "attr" ) ; } else { return StringResources . processStringResources ( value ) ; }


signature:
public class XmlResourceParserImpl { /** * A twin implementation of the native android nativeNext ( status )
 * @ throws XmlPullParserException */
private int nativeNext ( ) throws XmlPullParserException { } }

implementation:
switch ( mEventType ) { case ( CDSECT ) : { throw new IllegalArgumentException ( "CDSECT is not handled by Android" ) ; } case ( COMMENT ) : { throw new IllegalArgumentException ( "COMMENT is not handled by Android" ) ; } case ( DOCDECL ) : { throw new IllegalArgumentException ( "DOCDECL is not handled by Android" ) ; } case ( ENTITY_REF ) : { throw new IllegalArgumentException ( "ENTITY_REF is not handled by Android" ) ; } case ( END_DOCUMENT ) : { // The end document event should have been filtered
// from the invoker . This should never happen .
throw new IllegalArgumentException ( "END_DOCUMENT should not be found here." ) ; } case ( END_TAG ) : { return navigateToNextNode ( currentNode ) ; } case ( IGNORABLE_WHITESPACE ) : { throw new IllegalArgumentException ( "IGNORABLE_WHITESPACE" ) ; } case ( PROCESSING_INSTRUCTION ) : { throw new IllegalArgumentException ( "PROCESSING_INSTRUCTION" ) ; } case ( START_DOCUMENT ) : { currentNode = document . getDocumentElement ( ) ; return START_TAG ; } case ( START_TAG ) : { if ( currentNode . hasChildNodes ( ) ) { // The node has children , navigate down
return processNextNodeType ( currentNode . getFirstChild ( ) ) ; } else { // The node has no children
return END_TAG ; } } case ( TEXT ) : { return navigateToNextNode ( currentNode ) ; } default : { // This can only happen if mEventType is
// assigned with an unmapped integer .
throw new RuntimeException ( "Robolectric-> Uknown XML event type: " + mEventType ) ; } }


signature:
public class XmlResourceParserImpl { /** * / * protected */
int processNextNodeType ( Node node ) throws XmlPullParserException { } }

implementation:
switch ( node . getNodeType ( ) ) { case ( Node . ATTRIBUTE_NODE ) : { throw new IllegalArgumentException ( "ATTRIBUTE_NODE" ) ; } case ( Node . CDATA_SECTION_NODE ) : { return navigateToNextNode ( node ) ; } case ( Node . COMMENT_NODE ) : { return navigateToNextNode ( node ) ; } case ( Node . DOCUMENT_FRAGMENT_NODE ) : { throw new IllegalArgumentException ( "DOCUMENT_FRAGMENT_NODE" ) ; } case ( Node . DOCUMENT_NODE ) : { throw new IllegalArgumentException ( "DOCUMENT_NODE" ) ; } case ( Node . DOCUMENT_TYPE_NODE ) : { throw new IllegalArgumentException ( "DOCUMENT_TYPE_NODE" ) ; } case ( Node . ELEMENT_NODE ) : { currentNode = node ; return START_TAG ; } case ( Node . ENTITY_NODE ) : { throw new IllegalArgumentException ( "ENTITY_NODE" ) ; } case ( Node . ENTITY_REFERENCE_NODE ) : { throw new IllegalArgumentException ( "ENTITY_REFERENCE_NODE" ) ; } case ( Node . NOTATION_NODE ) : { throw new IllegalArgumentException ( "DOCUMENT_TYPE_NODE" ) ; } case ( Node . PROCESSING_INSTRUCTION_NODE ) : { throw new IllegalArgumentException ( "DOCUMENT_TYPE_NODE" ) ; } case ( Node . TEXT_NODE ) : { if ( isWhitespace ( node . getNodeValue ( ) ) ) { // Skip whitespaces
return navigateToNextNode ( node ) ; } else { currentNode = node ; return TEXT ; } } default : { throw new RuntimeException ( "Robolectric -> Unknown node type: " + node . getNodeType ( ) + "." ) ; } }


signature:
public class XmlResourceParserImpl { /** * Navigate to the next node after a node and all of his
 * children have been explored .
 * If the node has unexplored siblings navigate to the
 * next sibling . Otherwise return to its parent .
 * @ param node the node which was just explored .
 * @ return { @ link XmlPullParserException # START _ TAG } if the given
 * node has siblings , { @ link XmlPullParserException # END _ TAG }
 * if the node has no unexplored siblings or
 * { @ link XmlPullParserException # END _ DOCUMENT } if the explored
 * was the root document .
 * @ throws XmlPullParserException if the parser fails to
 * parse the next node . */
int navigateToNextNode ( Node node ) throws XmlPullParserException { } }

implementation:
Node nextNode = node . getNextSibling ( ) ; if ( nextNode != null ) { // Move to the next siblings
return processNextNodeType ( nextNode ) ; } else { // Goes back to the parent
if ( document . getDocumentElement ( ) . equals ( node ) ) { currentNode = null ; return END_DOCUMENT ; } currentNode = node . getParentNode ( ) ; return END_TAG ; }


signature:
public class XmlResourceParserImpl { /** * Tell is a given feature is supported by android .
 * @ param name Feature name .
 * @ return True if the feature is supported . */
private static boolean isAndroidSupportedFeature ( String name ) { } }

implementation: if ( name == null ) { return false ; } for ( String feature : AVAILABLE_FEATURES ) { if ( feature . equals ( name ) ) { return true ; } } return false ;


signature:
public class ResTable { /** * bool appAsLib = false , bool isSystemAsset = false ) ; */
int add ( Asset asset , Asset idmapAsset , final int cookie , boolean copyData , boolean appAsLib , boolean isSystemAsset ) { } }

implementation: final byte [ ] data = asset . getBuffer ( true ) ; if ( data == NULL ) { ALOGW ( "Unable to get buffer of resource asset file" ) ; return UNKNOWN_ERROR ; } int idmapSize = 0 ; Object idmapData = NULL ; if ( idmapAsset != NULL ) { idmapData = idmapAsset . getBuffer ( true ) ; if ( idmapData == NULL ) { ALOGW ( "Unable to get buffer of idmap asset file" ) ; return UNKNOWN_ERROR ; } idmapSize = ( int ) idmapAsset . getLength ( ) ; } return addInternal ( data , ( int ) asset . getLength ( ) , idmapData , idmapSize , appAsLib , cookie , copyData , isSystemAsset ) ;


signature:
public class ResTable { /** * bool appAsLib , const int32 _ t cookie , bool copyData , bool isSystemAsset = false ) ; */
int addInternal ( byte [ ] data , int dataSize , final Object idmapData , int idmapDataSize , boolean appAsLib , final int cookie , boolean copyData , boolean isSystemAsset ) { } }

implementation:
if ( ! isTruthy ( data ) ) { return NO_ERROR ; } if ( dataSize < ResTable_header . SIZEOF ) { ALOGE ( "Invalid data. Size(%d) is smaller than a ResTable_header(%d)." , ( int ) dataSize , ( int ) ResTable_header . SIZEOF ) ; return UNKNOWN_ERROR ; } Header header = new Header ( this ) ; header . index = mHeaders . size ( ) ; header . cookie = cookie ; if ( idmapData != NULL ) { header . resourceIDMap = new int [ idmapDataSize / 4 ] ; if ( header . resourceIDMap == NULL ) { // delete header ;
return ( mError = NO_MEMORY ) ; } // memcpy ( header . resourceIDMap , idmapData , idmapDataSize ) ;
// header . resourceIDMapSize = idmapDataSize ;
} mHeaders . add ( header ) ; final boolean notDeviceEndian = htods ( ( short ) 0xf0 ) != 0xf0 ; if ( kDebugLoadTableNoisy ) { ALOGV ( "Adding resources to ResTable: data=%s, size=0x%x, cookie=%d, copy=%d " + "idmap=%s\n" , data , dataSize , cookie , copyData , idmapData ) ; } if ( copyData || notDeviceEndian ) { header . ownedData = data ; // malloc ( dataSize ) ;
if ( header . ownedData == NULL ) { return ( mError = NO_MEMORY ) ; } // memcpy ( header . ownedData , data , dataSize ) ;
data = header . ownedData ; } ByteBuffer buf = ByteBuffer . wrap ( data ) . order ( ByteOrder . LITTLE_ENDIAN ) ; // header - > header = ( const ResTable _ header * ) data ;
header . header = new ResTable_header ( buf , 0 ) ; header . size = dtohl ( header . header . header . size ) ; if ( kDebugLoadTableSuperNoisy ) { ALOGI ( "Got size 0x%x, again size 0x%x, raw size 0x%x\n" , header . size , dtohl ( header . header . header . size ) , header . header . header . size ) ; } if ( kDebugLoadTableNoisy ) { ALOGV ( "Loading ResTable @%s:\n" , header . header ) ; } if ( dtohs ( header . header . header . headerSize ) > header . size || header . size > dataSize ) { ALOGW ( "Bad resource table: header size 0x%x or total size 0x%x is larger than data size 0x%x\n" , ( int ) dtohs ( header . header . header . headerSize ) , ( int ) header . size , ( int ) dataSize ) ; return ( mError = BAD_TYPE ) ; } if ( ( ( dtohs ( header . header . header . headerSize ) | header . size ) & 0x3 ) != 0 ) { ALOGW ( "Bad resource table: header size 0x%x or total size 0x%x is not on an integer boundary\n" , ( int ) dtohs ( header . header . header . headerSize ) , ( int ) header . size ) ; return ( mError = BAD_TYPE ) ; } // header - > dataEnd = ( ( const uint8 _ t * ) header - > header ) + header - > size ;
header . dataEnd = header . size ; // Iterate through all chunks .
int curPackage = 0 ; // const ResChunk _ header * chunk =
// ( const ResChunk _ header * ) ( ( ( const uint8 _ t * ) header - > header )
// + dtohs ( header - > header - > header . headerSize ) ) ;
ResChunk_header chunk = new ResChunk_header ( buf , dtohs ( header . header . header . headerSize ) ) ; while ( chunk != null && ( chunk . myOffset ( ) ) <= ( header . dataEnd - ResChunk_header . SIZEOF ) && ( chunk . myOffset ( ) ) <= ( header . dataEnd - dtohl ( chunk . size ) ) ) { int err = validate_chunk ( chunk , ResChunk_header . SIZEOF , header . dataEnd , "ResTable" ) ; if ( err != NO_ERROR ) { return ( mError = err ) ; } if ( kDebugTableNoisy ) { ALOGV ( "Chunk: type=0x%x, headerSize=0x%x, size=0x%x, pos=%s\n" , dtohs ( chunk . type ) , dtohs ( chunk . headerSize ) , dtohl ( chunk . size ) , ( Object ) ( ( chunk . myOffset ( ) ) - ( header . header . myOffset ( ) ) ) ) ; } final int csize = dtohl ( chunk . size ) ; final int ctype = dtohs ( chunk . type ) ; if ( ctype == RES_STRING_POOL_TYPE ) { if ( header . values . getError ( ) != NO_ERROR ) { // Only use the first string chunk ; ignore any others that
// may appear .
err = header . values . setTo ( chunk . myBuf ( ) , chunk . myOffset ( ) , csize , false ) ; if ( err != NO_ERROR ) { return ( mError = err ) ; } } else { ALOGW ( "Multiple string chunks found in resource table." ) ; } } else if ( ctype == RES_TABLE_PACKAGE_TYPE ) { if ( curPackage >= dtohl ( header . header . packageCount ) ) { ALOGW ( "More package chunks were found than the %d declared in the header." , dtohl ( header . header . packageCount ) ) ; return ( mError = BAD_TYPE ) ; } if ( parsePackage ( new ResTable_package ( chunk . myBuf ( ) , chunk . myOffset ( ) ) , header , appAsLib , isSystemAsset ) != NO_ERROR ) { return mError ; } curPackage ++ ; } else { ALOGW ( "Unknown chunk type 0x%x in table at 0x%x.\n" , ctype , ( chunk . myOffset ( ) ) - ( header . header . myOffset ( ) ) ) ; } chunk = chunk . myOffset ( ) + csize < header . dataEnd ? new ResChunk_header ( chunk . myBuf ( ) , chunk . myOffset ( ) + csize ) : null ; } if ( curPackage < dtohl ( header . header . packageCount ) ) { ALOGW ( "Fewer package chunks (%d) were found than the %d declared in the header." , ( int ) curPackage , dtohl ( header . header . packageCount ) ) ; return ( mError = BAD_TYPE ) ; } mError = header . values . getError ( ) ; if ( mError != NO_ERROR ) { ALOGW ( "No string values found in resource table!" ) ; } if ( kDebugTableNoisy ) { ALOGV ( "Returning from add with mError=%d\n" , mError ) ; } return mError ;


signature:
public class ShadowCanvas { /** * Returns a textual representation of the appearance of the object .
 * @ param canvas the canvas to visualize
 * @ return The textual representation of the appearance of the object . */
public static String visualize ( Canvas canvas ) { } }

implementation: ShadowCanvas shadowCanvas = Shadow . extract ( canvas ) ; return shadowCanvas . getDescription ( ) ;


signature:
public class ShadowSystem { /** * Implements { @ link System # nanoTime } through ShadowWrangler .
 * @ return Current time with nanos . */
@ SuppressWarnings ( "unused" ) public static long nanoTime ( ) { } }

implementation: if ( ShadowLooper . looperMode ( ) == LooperMode . Mode . PAUSED ) { return TimeUnit . MILLISECONDS . toNanos ( SystemClock . uptimeMillis ( ) ) ; } else { return ShadowLegacySystemClock . nanoTime ( ) ; }


signature:
public class ShadowSystem { /** * Implements { @ link System # currentTimeMillis } through ShadowWrangler .
 * @ return Current time with millis . */
@ SuppressWarnings ( "unused" ) public static long currentTimeMillis ( ) { } }

implementation: if ( ShadowLooper . looperMode ( ) == LooperMode . Mode . PAUSED ) { return SystemClock . uptimeMillis ( ) ; } else { return ShadowLegacySystemClock . currentTimeMillis ( ) ; }


signature:
public class RuntimeEnvironment { /** * Returns a qualifier string describing the current { @ link Configuration } of the system resources .
 * @ return a qualifier string as described ( https : / / developer . android . com / guide / topics / resources / providing - resources . html # QualifierRules ) [ here ] . */
public static String getQualifiers ( ) { } }

implementation: Resources systemResources = Resources . getSystem ( ) ; return getQualifiers ( systemResources . getConfiguration ( ) , systemResources . getDisplayMetrics ( ) ) ;


signature:
public class RuntimeEnvironment { /** * Returns a qualifier string describing the given configuration and display metrics .
 * @ param configuration the configuration .
 * @ param displayMetrics the display metrics .
 * @ return a qualifier string as described ( https : / / developer . android . com / guide / topics / resources / providing - resources . html # QualifierRules ) [ here ] . */
public static String getQualifiers ( Configuration configuration , DisplayMetrics displayMetrics ) { } }

implementation: return ConfigurationV25 . resourceQualifierString ( configuration , displayMetrics ) ;


signature:
public class RuntimeEnvironment { /** * Overrides the current device configuration .
 * If ` newQualifiers ` starts with a plus ( ` + ` ) , the prior configuration is used as the base
 * configuration , with the given changes applied additively . Otherwise , default values are used
 * for unspecified properties , as described [ here ] ( http : / / robolectric . org / device - configuration / ) .
 * @ param newQualifiers the qualifiers to apply */
public static void setQualifiers ( String newQualifiers ) { } }

implementation: Configuration configuration ; DisplayMetrics displayMetrics = new DisplayMetrics ( ) ; if ( newQualifiers . startsWith ( "+" ) ) { configuration = new Configuration ( Resources . getSystem ( ) . getConfiguration ( ) ) ; displayMetrics . setTo ( Resources . getSystem ( ) . getDisplayMetrics ( ) ) ; } else { configuration = new Configuration ( ) ; } Bootstrap . applyQualifiers ( newQualifiers , getApiLevel ( ) , configuration , displayMetrics ) ; Resources systemResources = Resources . getSystem ( ) ; systemResources . updateConfiguration ( configuration , displayMetrics ) ; if ( application != null ) { application . getResources ( ) . updateConfiguration ( configuration , displayMetrics ) ; }


signature:
public class ResourceString { /** * Given a buffer and an offset into the buffer , returns a String . The { @ code offset } is the
 * 0 - based byte offset from the start of the buffer where the string resides . This should be the
 * location in memory where the string ' s character count , followed by its byte count , and then
 * followed by the actual string is located .
 * < p > Here ' s an example UTF - 8 - encoded string of ab © :
 * < pre >
 * 03 04 61 62 C2 A9 00
 * ^ Offset should be here
 * < / pre >
 * @ param buffer The buffer containing the string to decode .
 * @ param offset Offset into the buffer where the string resides .
 * @ param type The encoding type that the { @ link ResourceString } is encoded in .
 * @ return The decoded string . */
public static String decodeString ( ByteBuffer buffer , int offset , Type type ) { } }

implementation:
int length ; int characterCount = decodeLength ( buffer , offset , type ) ; offset += computeLengthOffset ( characterCount , type ) ; // UTF - 8 strings have 2 lengths : the number of characters , and then the encoding length .
// UTF - 16 strings , however , only have 1 length : the number of characters .
if ( type == Type . UTF8 ) { length = decodeLength ( buffer , offset , type ) ; offset += computeLengthOffset ( length , type ) ; } else { length = characterCount * 2 ; } return new String ( buffer . array ( ) , offset , length , type . charset ( ) ) ;


signature:
public class ResourceString { /** * Encodes a string in either UTF - 8 or UTF - 16 and returns the bytes of the encoded string .
 * Strings are prefixed by 2 values . The first is the number of characters in the string .
 * The second is the encoding length ( number of bytes in the string ) .
 * < p > Here ' s an example UTF - 8 - encoded string of ab © :
 * < pre > 03 04 61 62 C2 A9 00 < / pre >
 * @ param str The string to be encoded .
 * @ param type The encoding type that the { @ link ResourceString } should be encoded in .
 * @ return The encoded string . */
public static byte [ ] encodeString ( String str , Type type ) { } }

implementation:
byte [ ] bytes = str . getBytes ( type . charset ( ) ) ; // The extra 5 bytes is for metadata ( character count + byte count ) and the NULL terminator .
ByteArrayDataOutput output = ByteStreams . newDataOutput ( bytes . length + 5 ) ; encodeLength ( output , str . length ( ) , type ) ; if ( type == Type . UTF8 ) { // Only UTF - 8 strings have the encoding length .
encodeLength ( output , bytes . length , type ) ; } output . write ( bytes ) ; // NULL - terminate the string
if ( type == Type . UTF8 ) { output . write ( 0 ) ; } else { output . writeShort ( 0 ) ; } return output . toByteArray ( ) ;


signature:
public class ResourceString { /** * Builds a string from a null - terminated char data . */
public static String buildString ( char [ ] data ) { } }

implementation: int count = 0 ; for ( count = 0 ; count < data . length ; count ++ ) { if ( data [ count ] == 0 ) { break ; } } return new String ( data , 0 , count ) ;


signature:
public class ServiceFinder { /** * Creates a new service loader for the given service type and class
 * loader .
 * @ param < S > the class of the service type
 * @ param service
 * The interface or abstract class representing the service
 * @ param loader
 * The class loader to be used to load provider - configuration files
 * and provider classes , or < tt > null < / tt > if the system class
 * loader ( or , failing that , the bootstrap class loader ) is to be
 * used
 * @ return A new service loader */
public static < S > ServiceFinder < S > load ( Class < S > service , ClassLoader loader ) { } }

implementation: return new ServiceFinder < > ( service , loader ) ;


signature:
public class ServiceFinder { /** * Creates a new service loader for the given service type , using the
 * extension class loader .
 * < p > This convenience method simply locates the extension class loader ,
 * call it < tt > < i > extClassLoader < / i > < / tt > , and then returns
 * < blockquote > < pre >
 * ServiceFinder . load ( < i > service < / i > , < i > extClassLoader < / i > ) < / pre > < / blockquote >
 * < p > If the extension class loader cannot be found then the system class
 * loader is used ; if there is no system class loader then the bootstrap
 * class loader is used .
 * < p > This method is intended for use when only installed providers are
 * desired . The resulting service will only find and load providers that
 * have been installed into the current Java virtual machine ; providers on
 * the application ' s class path will be ignored .
 * @ param < S > the class of the service type
 * @ param service
 * The interface or abstract class representing the service
 * @ return A new service loader */
public static < S > ServiceFinder < S > loadInstalled ( Class < S > service ) { } }

implementation: ClassLoader cl = ClassLoader . getSystemClassLoader ( ) ; ClassLoader prev = null ; while ( cl != null ) { prev = cl ; cl = cl . getParent ( ) ; } return load ( service , prev ) ;


signature:
public class ServiceFinder { /** * Internal API to support built - in SPIs that check a system property first .
 * Returns an instance specified by a property with the class ' binary name , or null if
 * no such property is set .
 * @ hide */
public static < S > S loadFromSystemProperty ( final Class < S > service ) { } }

implementation: try { final String className = System . getProperty ( service . getName ( ) ) ; if ( className != null ) { Class < ? > c = ClassLoader . getSystemClassLoader ( ) . loadClass ( className ) ; return ( S ) c . newInstance ( ) ; } return null ; } catch ( Exception e ) { throw new Error ( e ) ; }


signature:
public class PackagePropertiesLoader { /** * Return a { @ link Properties } file for the given package name , or { @ code null } if none is
 * available .
 * @ since 3.2 */
public Properties getConfigProperties ( @ Nonnull String packageName ) { } }

implementation: return cache . computeIfAbsent ( packageName , s -> { StringBuilder buf = new StringBuilder ( ) ; if ( ! packageName . isEmpty ( ) ) { buf . append ( packageName . replace ( '.' , '/' ) ) ; buf . append ( '/' ) ; } buf . append ( RobolectricTestRunner . CONFIG_PROPERTIES ) ; final String resourceName = buf . toString ( ) ; try ( InputStream resourceAsStream = getResourceAsStream ( resourceName ) ) { if ( resourceAsStream == null ) { return null ; } Properties properties = new Properties ( ) ; properties . load ( resourceAsStream ) ; return properties ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } ) ;


signature:
public class ShadowUsbManager { /** * Returns true if the given package has permission to access the device . */
public boolean hasPermissionForPackage ( UsbDevice device , String packageName ) { } }

implementation: List < UsbDevice > usbDevices = grantedPermissions . get ( packageName ) ; return usbDevices != null && usbDevices . contains ( device ) ;


signature:
public class ShadowUsbManager { /** * Revokes permission to a USB device granted to a package . This method does nothing if the
 * package doesn ' t have permission to access the device . */
public void revokePermission ( UsbDevice device , String packageName ) { } }

implementation: List < UsbDevice > usbDevices = grantedPermissions . get ( packageName ) ; if ( usbDevices != null ) { usbDevices . remove ( device ) ; }


signature:
public class ShadowUsbManager { /** * Adds a USB device into available USB devices map with permission value . If the USB device
 * already exists , updates the USB device with new permission value . */
public void addOrUpdateUsbDevice ( UsbDevice usbDevice , boolean hasPermission ) { } }

implementation: Preconditions . checkNotNull ( usbDevice ) ; Preconditions . checkNotNull ( usbDevice . getDeviceName ( ) ) ; usbDevices . put ( usbDevice . getDeviceName ( ) , usbDevice ) ; if ( hasPermission ) { grantPermission ( usbDevice ) ; } else { revokePermission ( usbDevice , RuntimeEnvironment . application . getPackageName ( ) ) ; }


signature:
public class ShadowUsbManager { /** * Removes a USB device from available USB devices map . */
public void removeUsbDevice ( UsbDevice usbDevice ) { } }

implementation: Preconditions . checkNotNull ( usbDevice ) ; usbDevices . remove ( usbDevice . getDeviceName ( ) ) ; revokePermission ( usbDevice , RuntimeEnvironment . application . getPackageName ( ) ) ;


signature:
public class ShadowUsbManager { /** * Adds a USB port to UsbManager . */
public void addPort ( String portId ) { } }

implementation: if ( RuntimeEnvironment . getApiLevel ( ) >= Build . VERSION_CODES . Q ) { usbPorts . put ( ( UsbPort ) createUsbPort ( realUsbManager , portId , UsbPortStatus . MODE_DUAL ) , ( UsbPortStatus ) createUsbPortStatus ( UsbPortStatus . MODE_DUAL , UsbPortStatus . POWER_ROLE_SINK , UsbPortStatus . DATA_ROLE_DEVICE , 0 ) ) ; return ; } usbPorts . put ( callConstructor ( UsbPort . class , from ( String . class , portId ) , from ( int . class , getStaticField ( UsbPort . class , "MODE_DUAL" ) ) ) , ( UsbPortStatus ) createUsbPortStatus ( getStaticField ( UsbPort . class , "MODE_DUAL" ) , getStaticField ( UsbPort . class , "POWER_ROLE_SINK" ) , getStaticField ( UsbPort . class , "DATA_ROLE_DEVICE" ) , 0 ) ) ;


signature:
public class ShadowUsbManager { /** * Opens a file descriptor from a temporary file . */
@ Implementation protected ParcelFileDescriptor openAccessory ( UsbAccessory accessory ) { } }

implementation: try { File tmpUsbDir = RuntimeEnvironment . getTempDirectory ( ) . createIfNotExists ( "usb-accessory" ) . toFile ( ) ; return ParcelFileDescriptor . open ( new File ( tmpUsbDir , "usb-accessory-file" ) , ParcelFileDescriptor . MODE_READ_WRITE ) ; } catch ( FileNotFoundException error ) { throw new RuntimeException ( "Error shadowing openAccessory" , error ) ; }


signature:
public class ShadowUsbManager { /** * Helper method for creating a { @ link UsbPortStatus } .
 * Returns Object to avoid referencing the API M + UsbPortStatus when running on older platforms . */
private static Object createUsbPortStatus ( int currentMode , int currentPowerRole , int currentDataRole , int supportedRoleCombinations ) { } }

implementation: if ( RuntimeEnvironment . getApiLevel ( ) >= Build . VERSION_CODES . Q ) { return new UsbPortStatus ( currentMode , currentPowerRole , currentDataRole , supportedRoleCombinations , 0 , 0 ) ; } return callConstructor ( UsbPortStatus . class , from ( int . class , currentMode ) , from ( int . class , currentPowerRole ) , from ( int . class , currentDataRole ) , from ( int . class , supportedRoleCombinations ) ) ;


signature:
public class ShadowUsbManager { /** * Helper method for creating a { @ link UsbPort } .
 * Returns Object to avoid referencing the API M + UsbPort when running on older platforms . */
private static Object createUsbPort ( UsbManager usbManager , String id , int supportedModes ) { } }

implementation: if ( RuntimeEnvironment . getApiLevel ( ) >= Build . VERSION_CODES . Q ) { return new UsbPort ( usbManager , id , supportedModes , 0 , false , false ) ; } return callConstructor ( UsbPort . class , from ( UsbManager . class , usbManager ) , from ( String . class , id ) , from ( int . class , supportedModes ) ) ;


signature:
public class ShadowWindowManagerImpl { /** * internal only */
public static void configureDefaultDisplayForJBOnly ( Configuration configuration , DisplayMetrics displayMetrics ) { } }

implementation: Class < ? > arg2Type = ReflectionHelpers . loadClass ( ShadowWindowManagerImpl . class . getClassLoader ( ) , "android.view.CompatibilityInfoHolder" ) ; defaultDisplayJB = ReflectionHelpers . callConstructor ( Display . class , ClassParameter . from ( int . class , 0 ) , ClassParameter . from ( arg2Type , null ) ) ; ShadowDisplay shadowDisplay = Shadow . extract ( defaultDisplayJB ) ; shadowDisplay . configureForJBOnly ( configuration , displayMetrics ) ;


signature:
public class ShadowFingerprintManager { /** * Simulates a successful fingerprint authentication . An authentication request must have been
 * issued with { @ link FingerprintManager # authenticate ( CryptoObject , CancellationSignal , int , AuthenticationCallback , Handler ) } and not cancelled . */
public void authenticationSucceeds ( ) { } }

implementation: if ( pendingCallback == null ) { throw new IllegalStateException ( "No active fingerprint authentication request." ) ; } AuthenticationResult result ; if ( RuntimeEnvironment . getApiLevel ( ) >= N_MR1 ) { result = new AuthenticationResult ( pendingCryptoObject , null , 0 ) ; } else { result = ReflectionHelpers . callConstructor ( AuthenticationResult . class , ClassParameter . from ( CryptoObject . class , pendingCryptoObject ) , ClassParameter . from ( Fingerprint . class , null ) ) ; } pendingCallback . onAuthenticationSucceeded ( result ) ;


signature:
public class ShadowFingerprintManager { /** * Success or failure can be simulated with a subsequent call to { @ link # authenticationSucceeds ( ) }
 * or { @ link # authenticationFails ( ) } . */
@ Implementation ( minSdk = M ) protected void authenticate ( CryptoObject crypto , CancellationSignal cancel , int flags , AuthenticationCallback callback , Handler handler ) { } }

implementation: if ( callback == null ) { throw new IllegalArgumentException ( "Must supply an authentication callback" ) ; } if ( cancel != null ) { if ( cancel . isCanceled ( ) ) { Log . w ( TAG , "authentication already canceled" ) ; return ; } else { cancel . setOnCancelListener ( ( ) -> { this . pendingCallback = null ; this . pendingCryptoObject = null ; } ) ; } } this . pendingCryptoObject = crypto ; this . pendingCallback = callback ;


signature:
public class ShadowFingerprintManager { /** * Enrolls the given number of fingerprints , which will be returned in { @ link
 * # getEnrolledFingerprints } .
 * @ param num the quantity of fingerprint item . */
public void setDefaultFingerprints ( int num ) { } }

implementation:
setEnrolledFingerprints ( IntStream . range ( 0 , num ) . mapToObj ( i -> new Fingerprint ( /* name = */
"Fingerprint " + i , /* groupId = */
0 , /* fingerId = */
i , /* deviceId = */
0 ) ) . toArray ( Fingerprint [ ] :: new ) ) ;


signature:
public class ShadowToast { /** * Discards the recorded { @ code Toast } s . Shown toasts are automatically cleared between
 * tests . This method allows the user to discard recorded toasts during the test in order to make assertions clearer
 * e . g :
 * < pre >
 * / / Show a single toast
 * myClass . showToast ( ) ;
 * assertThat ( ShadowToast . shownToastCount ( ) ) . isEqualTo ( 1 ) ;
 * ShadowToast . reset ( ) ;
 * / / Show another toast
 * myClass . showToast ( ) ;
 * assertThat ( ShadowToast . shownToastCount ( ) ) . isEqualTo ( 1 ) ;
 * < / pre > */
public static void reset ( ) { } }

implementation: ShadowApplication shadowApplication = Shadow . extract ( RuntimeEnvironment . application ) ; shadowApplication . getShownToasts ( ) . clear ( ) ;


signature:
public class ShadowToast { /** * Returns the number of { @ code Toast } requests that have been made during this test run
 * or since { @ link # reset ( ) } has been called .
 * @ return the number of { @ code Toast } requests that have been made during this test run
 * or since { @ link # reset ( ) } has been called . */
public static int shownToastCount ( ) { } }

implementation: ShadowApplication shadowApplication = Shadow . extract ( RuntimeEnvironment . application ) ; return shadowApplication . getShownToasts ( ) . size ( ) ;


signature:
public class ShadowToast { /** * Returns whether or not a particular custom { @ code Toast } has been shown .
 * @ param message the message to search for
 * @ param layoutResourceIdToCheckForMessage
 * the id of the resource that contains the toast messages
 * @ return whether the { @ code Toast } was requested */
public static boolean showedCustomToast ( CharSequence message , int layoutResourceIdToCheckForMessage ) { } }

implementation: ShadowApplication shadowApplication = Shadow . extract ( RuntimeEnvironment . application ) ; for ( Toast toast : shadowApplication . getShownToasts ( ) ) { String text = ( ( TextView ) toast . getView ( ) . findViewById ( layoutResourceIdToCheckForMessage ) ) . getText ( ) . toString ( ) ; if ( text . equals ( message . toString ( ) ) ) { return true ; } } return false ;


signature:
public class ShadowToast { /** * query method that returns whether or not a particular { @ code Toast } has been shown .
 * @ param message the message to search for
 * @ return whether the { @ code Toast } was requested */
public static boolean showedToast ( CharSequence message ) { } }

implementation: ShadowApplication shadowApplication = Shadow . extract ( RuntimeEnvironment . application ) ; for ( Toast toast : shadowApplication . getShownToasts ( ) ) { ShadowToast shadowToast = Shadow . extract ( toast ) ; String text = shadowToast . text ; if ( text != null && text . equals ( message . toString ( ) ) ) { return true ; } } return false ;


signature:
public class ShadowAlertDialog { /** * Resets the tracking of the most recently created { @ code AlertDialog } */
public static void reset ( ) { } }

implementation: ShadowApplication shadowApplication = Shadow . extract ( RuntimeEnvironment . application ) ; shadowApplication . setLatestAlertDialog ( null ) ;


signature:
public class ShadowAlertDialog { /** * Simulates a click on the { @ code Dialog } item indicated by { @ code index } . Handles both multi - and single - choice dialogs , tracks which items are currently
 * checked and calls listeners appropriately .
 * @ param index the index of the item to click on */
public void clickOnItem ( int index ) { } }

implementation: ShadowListView shadowListView = Shadow . extract ( realAlertDialog . getListView ( ) ) ; shadowListView . performItemClick ( index ) ;


signature:
public class Asset { /** * Create a new Asset from a file on disk . There is a fair chance that
 * the file doesn ' t actually exist .
 * We can use " mode " to decide how we want to go about it . */
static Asset createFromFile ( final String fileName , AccessMode mode ) { } }

implementation:
File file = new File ( fileName ) ; if ( ! file . exists ( ) ) { return null ; } throw new UnsupportedOperationException ( ) ; // _ FileAsset pAsset ;
// int result ;
// long length ;
// int fd ;
// fd = open ( fileName , O _ RDONLY | O _ BINARY ) ;
// if ( fd < 0)
// return null ;
// * Under Linux , the lseek fails if we actually opened a directory . To
// * be correct we should test the file type explicitly , but since we
// * always open things read - only it doesn ' t really matter , so there ' s
// * no value in incurring the extra overhead of an fstat ( ) call .
// / / TODO ( kroot ) : replace this with fstat despite the plea above .
// # if 1
// length = lseek64 ( fd , 0 , SEEK _ END ) ;
// if ( length < 0 ) {
// : : close ( fd ) ;
// return null ;
// ( void ) lseek64 ( fd , 0 , SEEK _ SET ) ;
// # else
// struct stat st ;
// if ( fstat ( fd , & st ) < 0 ) {
// : : close ( fd ) ;
// return null ;
// if ( ! S _ ISREG ( st . st _ mode ) ) {
// : : close ( fd ) ;
// return null ;
// # endif
// pAsset = new _ FileAsset ;
// result = pAsset . openChunk ( fileName , fd , 0 , length ) ;
// if ( result ! = NO _ ERROR ) {
// delete pAsset ;
// return null ;
// pAsset . mAccessMode = mode ;
// return pAsset ;


signature:
public class Asset { /** * Create a new Asset from a memory mapping . */
static Asset createFromUncompressedMap ( FileMap dataMap , AccessMode mode ) { } }

implementation: _FileAsset pAsset ; int result ; pAsset = new _FileAsset ( ) ; result = pAsset . openChunk ( dataMap ) ; if ( result != NO_ERROR ) return null ; pAsset . mAccessMode = mode ; return pAsset ;


signature:
public class Asset { /** * Create a new Asset from compressed data in a memory mapping . */
static Asset createFromCompressedMap ( FileMap dataMap , int uncompressedLen , AccessMode mode ) { } }

implementation: _CompressedAsset pAsset ; int result ; pAsset = new _CompressedAsset ( ) ; result = pAsset . openChunk ( dataMap , uncompressedLen ) ; if ( result != NO_ERROR ) return null ; pAsset . mAccessMode = mode ; return pAsset ;


signature:
public class Asset { /** * Do generic seek ( ) housekeeping . Pass in the offset / whence values from
 * the seek request , along with the current chunk offset and the chunk
 * length .
 * Returns the new chunk offset , or - 1 if the seek is illegal . */
long handleSeek ( long offset , int whence , long curPosn , long maxPosn ) { } }

implementation:
long newOffset ; switch ( whence ) { case SEEK_SET : newOffset = offset ; break ; case SEEK_CUR : newOffset = curPosn + offset ; break ; case SEEK_END : newOffset = maxPosn + offset ; break ; default : ALOGW ( "unexpected whence %d\n" , whence ) ; // this was happening due to an long size mismatch
assert ( false ) ; return ( long ) - 1 ; } if ( newOffset < 0 || newOffset > maxPosn ) { ALOGW ( "seek out of range: want %ld, end=%ld\n" , ( long ) newOffset , ( long ) maxPosn ) ; return ( long ) - 1 ; } return newOffset ;


signature:
public class ShadowDropBoxManager { /** * Adds entry to the DropboxManager with the flag indicating data is text .
 * < p > The existing { @ link DropBoxManager # addData } , { @ link DropBoxManager # addFile } , and { @ link
 * DropBoxManager # addText } methods in DropBoxManager are not shadowed . This method is a
 * convenience for quickly adding multiple historical entries . The entries can be added in any
 * order since this shadow will sort the entries by the specified timestamp .
 * < p > The flag will be set to { @ link DropBoxManager # IS _ TEXT } so that { @ link
 * DropBoxManager . Entry # getText } can be used .
 * @ param tag can be any arbitrary string
 * @ param timestamp is an arbitrary timestamp that must be unique from all other entries
 * @ param data must not be null */
void addData ( String tag , long timestamp , byte [ ] data ) { } }

implementation: entries . put ( timestamp , new DropBoxManager . Entry ( tag , timestamp , data , DropBoxManager . IS_TEXT ) ) ;


signature:
public class ShadowMediaBrowserCompat { /** * This differs from real Android search logic . Search results will contain all { @ link
 * MediaItem } ' s with a title that { @ param query } is a substring of . */
@ Implementation protected void search ( @ NonNull final String query , final Bundle extras , @ NonNull SearchCallback callback ) { } }

implementation: if ( isConnected ) { final List < MediaItem > searchResults = new ArrayList < > ( ) ; for ( MediaItem item : mediaItems . values ( ) ) { final String mediaTitle = item . getDescription ( ) . getTitle ( ) . toString ( ) . toLowerCase ( ) ; if ( mediaTitle . contains ( query . toLowerCase ( ) ) ) { searchResults . add ( item ) ; } } handler . post ( ( ) -> callback . onSearchResult ( query , extras , searchResults ) ) ; } else { handler . post ( ( ) -> callback . onError ( query , extras ) ) ; }


signature:
public class ShadowMediaBrowserCompat { /** * Creates a MediaItem and returns it .
 * @ param parentId the id of the parent MediaItem . If the MediaItem to be created will be the
 * root , parentId should be null .
 * @ param mediaId the id of the MediaItem to be created .
 * @ param title the title of the MediaItem to be created .
 * @ param flag says if the MediaItem to be created is browsable and / or playable .
 * @ return the newly created MediaItem . */
public MediaItem createMediaItem ( String parentId , String mediaId , String title , int flag ) { } }

implementation:
final MediaMetadataCompat metadataCompat = new MediaMetadataCompat . Builder ( ) . putString ( MediaMetadataCompat . METADATA_KEY_MEDIA_ID , mediaId ) . putString ( MediaMetadataCompat . METADATA_KEY_TITLE , title ) . putString ( MediaMetadataCompat . METADATA_KEY_MEDIA_URI , Uri . parse ( mediaId ) . toString ( ) ) . build ( ) ; final MediaItem mediaItem = new MediaItem ( metadataCompat . getDescription ( ) , flag ) ; mediaItems . put ( mediaId , mediaItem ) ; // If this MediaItem is the child of a MediaItem that has already been created . This applies to
// all MediaItems except the root .
if ( parentId != null ) { final MediaItem parentItem = mediaItems . get ( parentId ) ; List < MediaItem > children = mediaItemChildren . get ( parentItem ) ; if ( children == null ) { children = new ArrayList < > ( ) ; mediaItemChildren . put ( parentItem , children ) ; } children . add ( mediaItem ) ; } return mediaItem ;


signature:
public class ShadowDecorator { /** * For non - invokedynamic JVMs , generates this code :
 * ` ` ` java
 * if ( _ _ robo _ data _ _ instanceof ThisClass ) {
 * try {
 * return _ _ robo _ data _ _ . $ $ robo $ $ originalMethod ( params ) ;
 * } ( Throwable t ) {
 * throw RobolectricInternals . cleanStackTrace ( t ) ;
 * Note that this method is only called by { @ link OldClassInstrumentor } . */
@ Override public void decorateMethodPreClassHandler ( MutableClass mutableClass , MethodNode originalMethod , String originalMethodName , RobolectricGeneratorAdapter generator ) { } }

implementation:
boolean isNormalInstanceMethod = ! generator . isStatic && ! originalMethodName . equals ( ShadowConstants . CONSTRUCTOR_METHOD_NAME ) ; // maybe perform direct call . . .
if ( isNormalInstanceMethod ) { int exceptionLocalVar = generator . newLocal ( THROWABLE_TYPE ) ; Label notInstanceOfThis = new Label ( ) ; generator . loadThis ( ) ; // this
generator . getField ( mutableClass . classType , ShadowConstants . CLASS_HANDLER_DATA_FIELD_NAME , OBJECT_TYPE ) ; // contents of this . _ _ robo _ data _ _
generator . instanceOf ( mutableClass . classType ) ; // _ _ robo _ data _ _ , is instance of same class ?
generator . visitJumpInsn ( Opcodes . IFEQ , notInstanceOfThis ) ; // jump if no ( is not instance )
TryCatch tryCatchForProxyCall = generator . tryStart ( THROWABLE_TYPE ) ; generator . loadThis ( ) ; // this
generator . getField ( mutableClass . classType , ShadowConstants . CLASS_HANDLER_DATA_FIELD_NAME , OBJECT_TYPE ) ; // contents of this . _ _ robo _ data _ _
generator . checkCast ( mutableClass . classType ) ; // _ _ robo _ data _ _ but cast to my class
generator . loadArgs ( ) ; // _ _ robo _ data _ _ instance , [ args ]
generator . visitMethodInsn ( Opcodes . INVOKESPECIAL , mutableClass . internalClassName , originalMethod . name , originalMethod . desc , false ) ; tryCatchForProxyCall . end ( ) ; generator . returnValue ( ) ; // catch ( Throwable )
tryCatchForProxyCall . handler ( ) ; generator . storeLocal ( exceptionLocalVar ) ; generator . loadLocal ( exceptionLocalVar ) ; generator . invokeStatic ( ROBOLECTRIC_INTERNALS_TYPE , HANDLE_EXCEPTION_METHOD ) ; generator . throwException ( ) ; // callClassHandler . . .
generator . mark ( notInstanceOfThis ) ; }


signature:
public class ReflectionHelpers { /** * Create a proxy for the given class which returns other deep proxies from all it ' s methods .
 * < p > The returned object will be an instance of the given class , but all methods will return
 * either the " default " value for primitives , or another deep proxy for non - primitive types .
 * < p > This should be used rarely , for cases where we need to create deep proxies in order not
 * to crash . The inner proxies are impossible to configure , so there is no way to create
 * meaningful behavior from a deep proxy . It serves mainly to prevent Null Pointer Exceptions .
 * @ param clazz the class to provide a proxy instance of .
 * @ return a new " Deep Proxy " instance of the given class . */
public static < T > T createDeepProxy ( Class < T > clazz ) { } }

implementation: return ( T ) Proxy . newProxyInstance ( clazz . getClassLoader ( ) , new Class [ ] { clazz } , new InvocationHandler ( ) { @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( PRIMITIVE_RETURN_VALUES . containsKey ( method . getReturnType ( ) . getName ( ) ) ) { return PRIMITIVE_RETURN_VALUES . get ( method . getReturnType ( ) . getName ( ) ) ; } else if ( method . getReturnType ( ) . isInterface ( ) ) { return createDeepProxy ( method . getReturnType ( ) ) ; } else { return null ; } } } ) ;


signature:
public class ReflectionHelpers { /** * Reflectively get the value of a field .
 * @ param object Target object .
 * @ param fieldName The field name .
 * @ param < R > The return type .
 * @ return Value of the field on the object . */
@ SuppressWarnings ( "unchecked" ) public static < R > R getField ( final Object object , final String fieldName ) { } }

implementation: try { return traverseClassHierarchy ( object . getClass ( ) , NoSuchFieldException . class , new InsideTraversal < R > ( ) { @ Override public R run ( Class < ? > traversalClass ) throws Exception { Field field = traversalClass . getDeclaredField ( fieldName ) ; field . setAccessible ( true ) ; return ( R ) field . get ( object ) ; } } ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively set the value of a field .
 * @ param object Target object .
 * @ param fieldName The field name .
 * @ param fieldNewValue New value . */
public static void setField ( final Object object , final String fieldName , final Object fieldNewValue ) { } }

implementation: try { traverseClassHierarchy ( object . getClass ( ) , NoSuchFieldException . class , new InsideTraversal < Void > ( ) { @ Override public Void run ( Class < ? > traversalClass ) throws Exception { Field field = traversalClass . getDeclaredField ( fieldName ) ; field . setAccessible ( true ) ; field . set ( object , fieldNewValue ) ; return null ; } } ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively set the value of a field .
 * @ param type Target type .
 * @ param object Target object .
 * @ param fieldName The field name .
 * @ param fieldNewValue New value . */
public static void setField ( Class < ? > type , final Object object , final String fieldName , final Object fieldNewValue ) { } }

implementation: try { Field field = type . getDeclaredField ( fieldName ) ; field . setAccessible ( true ) ; field . set ( object , fieldNewValue ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively get the value of a static field .
 * @ param field Field object .
 * @ param < R > The return type .
 * @ return Value of the field . */
@ SuppressWarnings ( "unchecked" ) public static < R > R getStaticField ( Field field ) { } }

implementation: try { makeFieldVeryAccessible ( field ) ; return ( R ) field . get ( null ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively get the value of a static field .
 * @ param clazz Target class .
 * @ param fieldName The field name .
 * @ param < R > The return type .
 * @ return Value of the field . */
public static < R > R getStaticField ( Class < ? > clazz , String fieldName ) { } }

implementation: try { return getStaticField ( clazz . getDeclaredField ( fieldName ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively set the value of a static field .
 * @ param field Field object .
 * @ param fieldNewValue The new value . */
public static void setStaticField ( Field field , Object fieldNewValue ) { } }

implementation: try { makeFieldVeryAccessible ( field ) ; field . set ( null , fieldNewValue ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively set the value of a static field .
 * @ param clazz Target class .
 * @ param fieldName The field name .
 * @ param fieldNewValue The new value . */
public static void setStaticField ( Class < ? > clazz , String fieldName , Object fieldNewValue ) { } }

implementation: try { setStaticField ( clazz . getDeclaredField ( fieldName ) , fieldNewValue ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively call an instance method on an object .
 * @ param instance Target object .
 * @ param methodName The method name to call .
 * @ param classParameters Array of parameter types and values .
 * @ param < R > The return type .
 * @ return The return value of the method . */
public static < R > R callInstanceMethod ( final Object instance , final String methodName , ClassParameter < ? > ... classParameters ) { } }

implementation: try { final Class < ? > [ ] classes = ClassParameter . getClasses ( classParameters ) ; final Object [ ] values = ClassParameter . getValues ( classParameters ) ; return traverseClassHierarchy ( instance . getClass ( ) , NoSuchMethodException . class , new InsideTraversal < R > ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public R run ( Class < ? > traversalClass ) throws Exception { Method declaredMethod = traversalClass . getDeclaredMethod ( methodName , classes ) ; declaredMethod . setAccessible ( true ) ; return ( R ) declaredMethod . invoke ( instance , values ) ; } } ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively call an instance method on an object on a specific class .
 * @ param cl The class .
 * @ param instance Target object .
 * @ param methodName The method name to call .
 * @ param classParameters Array of parameter types and values .
 * @ param < R > The return type .
 * @ return The return value of the method . */
public static < R > R callInstanceMethod ( Class < ? > cl , final Object instance , final String methodName , ClassParameter < ? > ... classParameters ) { } }

implementation: try { final Class < ? > [ ] classes = ClassParameter . getClasses ( classParameters ) ; final Object [ ] values = ClassParameter . getValues ( classParameters ) ; Method method = cl . getDeclaredMethod ( methodName , classes ) ; method . setAccessible ( true ) ; if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { throw new IllegalArgumentException ( method + " is static" ) ; } return ( R ) method . invoke ( instance , values ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Helper method for calling a static method using a class from a custom class loader
 * @ param classLoader
 * @ param fullyQualifiedClassName
 * @ param methodName
 * @ param classParameters
 * @ param < R >
 * @ return */
public static < R > R callStaticMethod ( ClassLoader classLoader , String fullyQualifiedClassName , String methodName , ClassParameter < ? > ... classParameters ) { } }

implementation: Class < ? > clazz = loadClass ( classLoader , fullyQualifiedClassName ) ; return callStaticMethod ( clazz , methodName , classParameters ) ;


signature:
public class ReflectionHelpers { /** * Reflectively call a static method on a class .
 * @ param clazz Target class .
 * @ param methodName The method name to call .
 * @ param classParameters Array of parameter types and values .
 * @ param < R > The return type .
 * @ return The return value of the method . */
@ SuppressWarnings ( "unchecked" ) public static < R > R callStaticMethod ( Class < ? > clazz , String methodName , ClassParameter < ? > ... classParameters ) { } }

implementation: try { Class < ? > [ ] classes = ClassParameter . getClasses ( classParameters ) ; Object [ ] values = ClassParameter . getValues ( classParameters ) ; Method method = clazz . getDeclaredMethod ( methodName , classes ) ; method . setAccessible ( true ) ; if ( ! Modifier . isStatic ( method . getModifiers ( ) ) ) { throw new IllegalArgumentException ( method + " is not static" ) ; } return ( R ) method . invoke ( null , values ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "no such method " + clazz + "." + methodName , e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Create a new instance of a class
 * @ param cl The class object .
 * @ param < T > The class type .
 * @ return New class instance . */
public static < T > T newInstance ( Class < T > cl ) { } }

implementation: try { return cl . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionHelpers { /** * Reflectively call the constructor of an object .
 * @ param clazz Target class .
 * @ param classParameters Array of parameter types and values .
 * @ param < R > The return type .
 * @ return The return value of the method . */
public static < R > R callConstructor ( Class < ? extends R > clazz , ClassParameter < ? > ... classParameters ) { } }

implementation: try { final Class < ? > [ ] classes = ClassParameter . getClasses ( classParameters ) ; final Object [ ] values = ClassParameter . getValues ( classParameters ) ; Constructor < ? extends R > constructor = clazz . getDeclaredConstructor ( classes ) ; constructor . setAccessible ( true ) ; return constructor . newInstance ( values ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( "error instantiating " + clazz . getName ( ) , e ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } if ( e . getTargetException ( ) instanceof Error ) { throw ( Error ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ShadowCrossProfileApps { /** * Returns a { @ link Drawable } that can be shown for profile switching , which is guaranteed to
 * always be the same for a particular user and to be distinct between users . */
@ Implementation protected Drawable getProfileSwitchingIconDrawable ( UserHandle userHandle ) { } }

implementation: verifyCanAccessUser ( userHandle ) ; return new ColorDrawable ( userHandle . getIdentifier ( ) ) ;


signature:
public class ShadowCrossProfileApps { /** * Simulates starting the main activity specified in the specified profile , performing the same
 * security checks done by the real { @ link CrossProfileApps } .
 * < p > The most recent main activity started can be queried by { @ link
 * # peekNextStartedMainActivity ( ) } . */
@ Implementation protected void startMainActivity ( ComponentName componentName , UserHandle targetUser ) { } }

implementation: verifyCanAccessUser ( targetUser ) ; verifyMainActivityInManifest ( componentName ) ; startedMainActivities . add ( new StartedMainActivity ( componentName , targetUser ) ) ;


signature:
public class ShadowCrossProfileApps { /** * Adds { @ code userHandle } to the list of accessible handles . */
public void addTargetUserProfile ( UserHandle userHandle ) { } }

implementation: if ( userHandle . equals ( Process . myUserHandle ( ) ) ) { throw new IllegalArgumentException ( "Cannot target current user" ) ; } targetUserProfiles . add ( userHandle ) ;


signature:
public class ShadowCrossProfileApps { /** * Removes { @ code userHandle } from the list of accessible handles , if present . */
public void removeTargetUserProfile ( UserHandle userHandle ) { } }

implementation: if ( userHandle . equals ( Process . myUserHandle ( ) ) ) { throw new IllegalArgumentException ( "Cannot target current user" ) ; } targetUserProfiles . remove ( userHandle ) ;


signature:
public class ShadowCrossProfileApps { /** * Ensures that { @ code component } is present in the manifest as an exported and enabled launcher
 * activity . This check and the error thrown are the same as the check done by the real { @ link
 * CrossProfileApps } . */
private void verifyMainActivityInManifest ( ComponentName component ) { } }

implementation: Intent launchIntent = new Intent ( Intent . ACTION_MAIN ) . addCategory ( Intent . CATEGORY_LAUNCHER ) . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK | Intent . FLAG_ACTIVITY_RESET_TASK_IF_NEEDED ) . setPackage ( component . getPackageName ( ) ) ; boolean existsMatchingActivity = Iterables . any ( packageManager . queryIntentActivities ( launchIntent , MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE ) , resolveInfo -> { ActivityInfo activityInfo = resolveInfo . activityInfo ; return TextUtils . equals ( activityInfo . packageName , component . getPackageName ( ) ) && TextUtils . equals ( activityInfo . name , component . getClassName ( ) ) && activityInfo . exported ; } ) ; if ( ! existsMatchingActivity ) { throw new SecurityException ( "Attempt to launch activity without " + " category Intent.CATEGORY_LAUNCHER or activity is not exported" + component ) ; }


signature:
public class ShadowWifiRttManager { /** * If there are RangingResults set by the setRangeResults method of this shadow class , this method
 * will call the onRangingResults method of the callback on the executor thread and pass the list
 * of RangingResults . If there are no ranging results set , it will pass
 * RangingResultCallback . STATUS _ CODE _ FAIL to the onRangingFailure method of the callback , also
 * called on the executor thread . */
@ Implementation ( minSdk = P ) protected void startRanging ( RangingRequest request , Executor executor , RangingResultCallback callback ) { } }

implementation: if ( ! rangingResults . isEmpty ( ) ) { executor . execute ( ( ) -> callback . onRangingResults ( this . rangingResults ) ) ; } else { executor . execute ( ( ) -> callback . onRangingFailure ( RangingResultCallback . STATUS_CODE_FAIL ) ) ; }


signature:
public class ShadowLauncherApps { /** * Adds a dynamic shortcut to be returned by { @ link # getShortcuts ( ShortcutQuery , UserHandle ) } .
 * @ param shortcutInfo the shortcut to add . */
public void addDynamicShortcut ( ShortcutInfo shortcutInfo ) { } }

implementation: shortcuts . add ( shortcutInfo ) ; shortcutsChanged ( shortcutInfo . getPackage ( ) , Lists . newArrayList ( shortcutInfo ) ) ;


signature:
public class ShadowLauncherApps { /** * Fires { @ link LauncherApps . Callback # onPackageAdded ( String , UserHandle ) } on all of the registered
 * callbacks , with the provided packageName .
 * @ param packageName the package the was added . */
public void notifyPackageAdded ( String packageName ) { } }

implementation: for ( Pair < LauncherApps . Callback , Handler > callbackPair : callbacks ) { callbackPair . second . post ( ( ) -> callbackPair . first . onPackageAdded ( packageName , Process . myUserHandle ( ) ) ) ; }


signature:
public class ShadowLauncherApps { /** * Fires { @ link LauncherApps . Callback # onPackageRemoved ( String , UserHandle ) } on all of the
 * registered callbacks , with the provided packageName .
 * @ param packageName the package the was removed . */
public void notifyPackageRemoved ( String packageName ) { } }

implementation: for ( Pair < LauncherApps . Callback , Handler > callbackPair : callbacks ) { callbackPair . second . post ( ( ) -> callbackPair . first . onPackageRemoved ( packageName , Process . myUserHandle ( ) ) ) ; }


signature:
public class ShadowLauncherApps { /** * This method is an incomplete implementation of this API that only supports querying for pinned
 * dynamic shortcuts . It also doesn ' t not support { @ link ShortcutQuery # setChangedSince ( long ) } . */
@ Implementation ( minSdk = N_MR1 ) @ Nullable protected List < ShortcutInfo > getShortcuts ( @ NonNull ShortcutQuery query , @ NonNull UserHandle user ) { } }

implementation: if ( reflector ( ReflectorShortcutQuery . class , query ) . getChangedSince ( ) != 0 ) { throw new UnsupportedOperationException ( "Robolectric does not currently support ShortcutQueries that filter on time since" + " change." ) ; } int flags = reflector ( ReflectorShortcutQuery . class , query ) . getQueryFlags ( ) ; if ( ( flags & ShortcutQuery . FLAG_MATCH_PINNED ) == 0 || ( flags & ShortcutQuery . FLAG_MATCH_DYNAMIC ) == 0 ) { throw new UnsupportedOperationException ( "Robolectric does not currently support ShortcutQueries that match non-dynamic" + " Shortcuts." ) ; } Iterable < ShortcutInfo > shortcutsItr = shortcuts ; List < String > ids = reflector ( ReflectorShortcutQuery . class , query ) . getShortcutIds ( ) ; if ( ids != null ) { shortcutsItr = Iterables . filter ( shortcutsItr , shortcut -> ids . contains ( shortcut . getId ( ) ) ) ; } ComponentName activity = reflector ( ReflectorShortcutQuery . class , query ) . getActivity ( ) ; if ( activity != null ) { shortcutsItr = Iterables . filter ( shortcutsItr , shortcut -> shortcut . getActivity ( ) . equals ( activity ) ) ; } String packageName = reflector ( ReflectorShortcutQuery . class , query ) . getPackage ( ) ; if ( packageName != null && ! packageName . isEmpty ( ) ) { shortcutsItr = Iterables . filter ( shortcutsItr , shortcut -> shortcut . getPackage ( ) . equals ( packageName ) ) ; } return Lists . newArrayList ( shortcutsItr ) ;


signature:
public class ShadowIntent { /** * Returns the { @ code Class } object set by
 * { @ link Intent # setClass ( android . content . Context , Class ) }
 * @ return the { @ code Class } object set by
 * { @ link Intent # setClass ( android . content . Context , Class ) } */
public Class < ? > getIntentClass ( ) { } }

implementation: try { return Class . forName ( realIntent . getComponent ( ) . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; }


signature:
public class ShadowFontsContract { /** * Returns a stub typeface immediately . */
@ Implementation public static Typeface getFontSync ( FontRequest request ) { } }

implementation: return Typeface . create ( request . getQuery ( ) , Typeface . NORMAL ) ;