signature:
public class LoginManager { /** * Logs a user in , requesting approval for specified { @ link Scope } s .
 * @ param activity the activity used to start the { @ link LoginActivity } . */
public void login ( final @ NonNull Activity activity ) { } }

implementation: boolean hasScopes = ( sessionConfiguration . getScopes ( ) != null && ! sessionConfiguration . getScopes ( ) . isEmpty ( ) ) || ( sessionConfiguration . getCustomScopes ( ) != null && ! sessionConfiguration . getCustomScopes ( ) . isEmpty ( ) ) ; checkState ( hasScopes , "Scopes must be set in the Session Configuration." ) ; checkNotNull ( sessionConfiguration . getRedirectUri ( ) , "Redirect URI must be set in Session Configuration." ) ; if ( ! legacyUriRedirectHandler . checkValidState ( activity , this ) ) { return ; } SsoDeeplink ssoDeeplink = getSsoDeeplink ( activity ) ; if ( ssoDeeplink . isSupported ( SsoDeeplink . FlowVersion . REDIRECT_TO_SDK ) ) { Intent intent = LoginActivity . newIntent ( activity , productFlowPriority , sessionConfiguration , ResponseType . TOKEN , false , true , true ) ; activity . startActivityForResult ( intent , requestCode ) ; } else if ( ssoDeeplink . isSupported ( SsoDeeplink . FlowVersion . DEFAULT ) ) { ssoDeeplink . execute ( SsoDeeplink . FlowVersion . DEFAULT ) ; } else if ( isAuthCodeFlowEnabled ( ) ) { loginForAuthorizationCode ( activity ) ; } else { loginForImplicitGrantWithFallback ( activity ) ; }


signature:
public class LoginManager { /** * Login using Implicit Grant ( Webview )
 * @ param activity to start Activity on . */
@ Deprecated public void loginForImplicitGrant ( @ NonNull Activity activity ) { } }

implementation: if ( ! legacyUriRedirectHandler . checkValidState ( activity , this ) ) { return ; } Intent intent = LoginActivity . newIntent ( activity , sessionConfiguration , ResponseType . TOKEN , legacyUriRedirectHandler . isLegacyMode ( ) ) ; activity . startActivityForResult ( intent , requestCode ) ;


signature:
public class LoginManager { /** * login with Authorization Code mode .
 * @ param activity to start Activity on . */
public void loginForAuthorizationCode ( @ NonNull Activity activity ) { } }

implementation: if ( ! legacyUriRedirectHandler . checkValidState ( activity , this ) ) { return ; } Intent intent = LoginActivity . newIntent ( activity , sessionConfiguration , ResponseType . CODE , legacyUriRedirectHandler . isLegacyMode ( ) ) ; activity . startActivityForResult ( intent , requestCode ) ;


signature:
public class LoginManager { /** * Login using Implicit Grant , but if requesting privileged scopes , fallback to redirecting the user to the play
 * store to install the app .
 * @ param activity to start Activity on . */
private void loginForImplicitGrantWithFallback ( @ NonNull Activity activity ) { } }

implementation: if ( ! legacyUriRedirectHandler . checkValidState ( activity , this ) ) { return ; } Intent intent = LoginActivity . newIntent ( activity , new ArrayList < SupportedAppType > ( ) , sessionConfiguration , ResponseType . TOKEN , legacyUriRedirectHandler . isLegacyMode ( ) , false , true ) ; activity . startActivityForResult ( intent , requestCode ) ;


signature:
public class LoginManager { /** * Gets session based on current { @ link SessionConfiguration } and { @ link AccessTokenStorage } .
 * @ return Session to use with API requests .
 * @ throws IllegalStateException when not logged in */
@ NonNull public Session < ? > getSession ( ) { } }

implementation: if ( sessionConfiguration . getServerToken ( ) != null ) { return new ServerTokenSession ( sessionConfiguration ) ; } else if ( accessTokenStorage . getAccessToken ( ) != null ) { return new AccessTokenSession ( sessionConfiguration , accessTokenStorage ) ; } else { throw new IllegalStateException ( "Tried to call getSession but not logged in or server token set." ) ; }


signature:
public class LoginManager { /** * { @ link Activity } result handler to be called from starting { @ link Activity } . Stores { @ link AccessToken } and
 * notifies consumer callback of login result .
 * @ param activity Activity used to start login if Uber app is unavailable .
 * @ param requestCode request code originally supplied to { @ link Activity # startActivityForResult ( Intent , int ) } .
 * @ param resultCode result code from returning { @ link Activity } .
 * @ param data data from returning { @ link Activity } . */
public void onActivityResult ( @ NonNull Activity activity , int requestCode , int resultCode , @ Nullable Intent data ) { } }

implementation: if ( requestCode != this . requestCode ) { return ; } if ( resultCode == Activity . RESULT_OK ) { handleResultOk ( data ) ; } else if ( resultCode == Activity . RESULT_CANCELED ) { handleResultCancelled ( activity , data ) ; }


signature:
public class LoginManager { /** * Generates the deeplink required to execute the SSO Flow
 * @ param activity the activity to execute the deeplink intent
 * @ return the object that executes the deeplink */
@ VisibleForTesting SsoDeeplink getSsoDeeplink ( @ NonNull Activity activity ) { } }

implementation: return new SsoDeeplink . Builder ( activity ) . clientId ( sessionConfiguration . getClientId ( ) ) . scopes ( sessionConfiguration . getScopes ( ) ) . customScopes ( sessionConfiguration . getCustomScopes ( ) ) . activityRequestCode ( requestCode ) . redirectUri ( sessionConfiguration . getRedirectUri ( ) ) . productFlowPriority ( productFlowPriority ) . build ( ) ;


signature:
public class RequestDeeplinkBehavior { /** * Requests a ride using a { @ link RideRequestDeeplink } that is constructed using the provided { @ link RideParameters } .
 * @ param context { @ link Context } to pass to launch the { @ link RideRequestDeeplink } from
 * @ param params the { @ link RideParameters } to use for building and executing the { @ link RideRequestDeeplink } */
@ Override public void requestRide ( @ NonNull Context context , @ NonNull RideParameters params ) { } }

implementation: RideRequestDeeplink deeplink = new RideRequestDeeplink . Builder ( context ) . setSessionConfiguration ( sessionConfiguration ) . setRideParameters ( params ) . build ( ) ; deeplink . execute ( ) ;


signature:
public class AccessTokenManager { /** * Gets an { @ link AccessToken } stored . */
@ Override @ Nullable public AccessToken getAccessToken ( ) { } }

implementation:
long expiresIn ; String token ; Set < String > scopesString ; String refreshToken ; String tokenType ; try { expiresIn = sharedPreferences . getLong ( accessTokenKey + DATE_KEY_SUFFIX , - 1 ) ; token = sharedPreferences . getString ( accessTokenKey + TOKEN_KEY_SUFFIX , null ) ; scopesString = sharedPreferences . getStringSet ( accessTokenKey + SCOPES_KEY_SUFFIX , null ) ; refreshToken = sharedPreferences . getString ( accessTokenKey + REFRESH_TOKEN_KEY_SUFFIX , null ) ; tokenType = sharedPreferences . getString ( accessTokenKey + TOKEN_TYPE_KEY_SUFFIX , null ) ; } catch ( ClassCastException ignored ) { return null ; } if ( expiresIn == - 1 || token == null || scopesString == null ) { // Return null , if we can ' t parse it this token is considered unsaved .
return null ; } Collection < Scope > scopes ; try { scopes = AuthUtils . stringCollectionToScopeCollection ( scopesString ) ; } catch ( IllegalArgumentException ignored ) { return null ; } return new AccessToken ( expiresIn , scopes , token , refreshToken , tokenType ) ;


signature:
public class AccessTokenManager { /** * Removes the { @ link AccessToken } stored . */
@ Override public void removeAccessToken ( ) { } }

implementation: cookieUtils . clearUberCookies ( ) ; sharedPreferences . edit ( ) . remove ( accessTokenKey + DATE_KEY_SUFFIX ) . apply ( ) ; sharedPreferences . edit ( ) . remove ( accessTokenKey + TOKEN_KEY_SUFFIX ) . apply ( ) ; sharedPreferences . edit ( ) . remove ( accessTokenKey + SCOPES_KEY_SUFFIX ) . apply ( ) ; sharedPreferences . edit ( ) . remove ( accessTokenKey + REFRESH_TOKEN_KEY_SUFFIX ) . apply ( ) ; sharedPreferences . edit ( ) . remove ( accessTokenKey + TOKEN_TYPE_KEY_SUFFIX ) . apply ( ) ;


signature:
public class AccessTokenManager { /** * Stores the { @ link AccessToken } . */
@ Override public void setAccessToken ( @ NonNull AccessToken accessToken ) { } }

implementation: sharedPreferences . edit ( ) . putLong ( accessTokenKey + DATE_KEY_SUFFIX , accessToken . getExpiresIn ( ) ) . apply ( ) ; sharedPreferences . edit ( ) . putString ( accessTokenKey + TOKEN_KEY_SUFFIX , accessToken . getToken ( ) ) . apply ( ) ; sharedPreferences . edit ( ) . putStringSet ( accessTokenKey + SCOPES_KEY_SUFFIX , AuthUtils . scopeCollectionToStringSet ( accessToken . getScopes ( ) ) ) . apply ( ) ; sharedPreferences . edit ( ) . putString ( accessTokenKey + REFRESH_TOKEN_KEY_SUFFIX , accessToken . getRefreshToken ( ) ) . apply ( ) ; sharedPreferences . edit ( ) . putString ( accessTokenKey + TOKEN_TYPE_KEY_SUFFIX , accessToken . getTokenType ( ) ) . apply ( ) ;


signature:
public class CustomTabsHelper { /** * Opens the URL on a Custom Tab if possible . Otherwise fallsback to opening it on a WebView .
 * @ param context The host context .
 * @ param customTabsIntent a CustomTabsIntent to be used if Custom Tabs is available .
 * @ param uri the Uri to be opened .
 * @ param fallback a CustomTabFallback to be used if Custom Tabs is not available . */
public void openCustomTab ( final Context context , final CustomTabsIntent customTabsIntent , final Uri uri , CustomTabFallback fallback ) { } }

implementation:
final String packageName = getPackageNameToUse ( context ) ; if ( packageName != null ) { final CustomTabsServiceConnection connection = new CustomTabsServiceConnection ( ) { @ Override public void onCustomTabsServiceConnected ( ComponentName componentName , CustomTabsClient client ) { client . warmup ( 0L ) ; // This prevents backgrounding after redirection
customTabsIntent . intent . setPackage ( packageName ) ; customTabsIntent . intent . setData ( uri ) ; customTabsIntent . launchUrl ( context , uri ) ; } @ Override public void onServiceDisconnected ( ComponentName name ) { } } ; CustomTabsClient . bindCustomTabsService ( context , packageName , connection ) ; } else if ( fallback != null ) { fallback . openUri ( context , uri ) ; } else { Log . e ( UberSdk . UBER_SDK_LOG_TAG , "Use of openCustomTab without Customtab support or a fallback set" ) ; }


signature:
public class CustomTabsHelper { /** * Goes through all apps that handle VIEW intents and have a warmup service . Picks
 * the one chosen by the user if there is one , otherwise makes a best effort to return a
 * valid package name .
 * This is < strong > not < / strong > threadsafe .
 * @ param context { @ link Context } to use for accessing { @ link PackageManager } .
 * @ return The package name recommended to use for connecting to custom tabs related components . */
@ Nullable public String getPackageNameToUse ( Context context ) { } }

implementation:
if ( packageNameToUse != null ) return packageNameToUse ; PackageManager pm = context . getPackageManager ( ) ; // Get default VIEW intent handler .
Intent activityIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( "http://www.example.com" ) ) ; ResolveInfo defaultViewHandlerInfo = pm . resolveActivity ( activityIntent , 0 ) ; String defaultViewHandlerPackageName = null ; if ( defaultViewHandlerInfo != null ) { defaultViewHandlerPackageName = defaultViewHandlerInfo . activityInfo . packageName ; } // Get all apps that can handle VIEW intents .
List < ResolveInfo > resolvedActivityList = pm . queryIntentActivities ( activityIntent , 0 ) ; List < String > packagesSupportingCustomTabs = new ArrayList < > ( ) ; for ( ResolveInfo info : resolvedActivityList ) { Intent serviceIntent = new Intent ( ) ; serviceIntent . setAction ( ACTION_CUSTOM_TABS_CONNECTION ) ; serviceIntent . setPackage ( info . activityInfo . packageName ) ; if ( pm . resolveService ( serviceIntent , 0 ) != null ) { packagesSupportingCustomTabs . add ( info . activityInfo . packageName ) ; } } // Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
// and service calls .
if ( packagesSupportingCustomTabs . isEmpty ( ) ) { packageNameToUse = null ; } else if ( packagesSupportingCustomTabs . size ( ) == 1 ) { packageNameToUse = packagesSupportingCustomTabs . get ( 0 ) ; } else if ( ! TextUtils . isEmpty ( defaultViewHandlerPackageName ) && ! hasSpecializedHandlerIntents ( context , activityIntent ) && packagesSupportingCustomTabs . contains ( defaultViewHandlerPackageName ) ) { packageNameToUse = defaultViewHandlerPackageName ; } else if ( packagesSupportingCustomTabs . contains ( STABLE_PACKAGE ) ) { packageNameToUse = STABLE_PACKAGE ; } else if ( packagesSupportingCustomTabs . contains ( BETA_PACKAGE ) ) { packageNameToUse = BETA_PACKAGE ; } else if ( packagesSupportingCustomTabs . contains ( DEV_PACKAGE ) ) { packageNameToUse = DEV_PACKAGE ; } else if ( packagesSupportingCustomTabs . contains ( LOCAL_PACKAGE ) ) { packageNameToUse = LOCAL_PACKAGE ; } return packageNameToUse ;


signature:
public class CustomTabsHelper { /** * Used to check whether there is a specialized handler for a given intent .
 * @ param intent The intent to check with .
 * @ return Whether there is a specialized handler for the given intent . */
private boolean hasSpecializedHandlerIntents ( Context context , Intent intent ) { } }

implementation: try { PackageManager pm = context . getPackageManager ( ) ; List < ResolveInfo > handlers = pm . queryIntentActivities ( intent , PackageManager . GET_RESOLVED_FILTER ) ; if ( handlers == null || handlers . size ( ) == 0 ) { return false ; } for ( ResolveInfo resolveInfo : handlers ) { IntentFilter filter = resolveInfo . filter ; if ( filter == null ) continue ; if ( filter . countDataAuthorities ( ) == 0 || filter . countDataPaths ( ) == 0 ) continue ; if ( resolveInfo . activityInfo == null ) continue ; return true ; } } catch ( RuntimeException e ) { Log . e ( TAG , "Runtime exception while getting specialized handlers" ) ; } return false ;


signature:
public class LoginButton { /** * { @ link Activity } result handler to be called from starting { @ link Activity } . Stores
 * { @ link com . uber . sdk . core . auth . AccessToken } and notifies consumer callback of login result .
 * @ param requestCode request code originally supplied to { @ link Activity # startActivityForResult ( Intent , int ) } .
 * @ param resultCode result code from returning { @ link Activity } .
 * @ param data data from returning { @ link Activity } . */
public void onActivityResult ( int requestCode , int resultCode , @ Nullable Intent data ) { } }

implementation: if ( requestCode == this . requestCode ) { getOrCreateLoginManager ( ) . onActivityResult ( getActivity ( ) , requestCode , resultCode , data ) ; }


signature:
public class PackageManagers { /** * A safe method to obtain { @ link PackageInfo } from { @ link android . content . pm . PackageManager }
 * If package is not available , it would just return null .
 * @ param context to be used for looking
 * @ param packageName to look up against context
 * @ return { @ link PackageInfo } retrieved from Context . */
@ Nullable public static PackageInfo getPackageInfo ( @ NonNull Context context , @ NonNull String packageName ) { } }

implementation: try { return context . getPackageManager ( ) . getPackageInfo ( packageName , PackageManager . GET_META_DATA ) ; } catch ( PackageManager . NameNotFoundException e ) { return null ; }


signature:
public class PackageManagers { /** * A safe method to check if an app is installed .
 * @ param context to be used to check for package
 * @ param packageName of the app to be checked .
 * @ return true only if app using packageName is installed . */
public static boolean isPackageAvailable ( @ NonNull Context context , @ NonNull String packageName ) { } }

implementation: return ( getPackageInfo ( context , packageName ) != null ) ;


signature:
public class Utility { /** * Logs error and when debug is enabled , shows Alert Dialog with debug instructions .
 * @ param activity
 * @ param logMessage
 * @ param alertTitle
 * @ param alertMessage
 * @ return true if developer error is shown , false otherwise . */
public static boolean logAndShowBlockingDebugUIAlert ( @ NonNull Activity activity , final @ NonNull String logMessage , final @ NonNull String alertTitle , final @ NonNull String alertMessage , final @ NonNull RuntimeException exception ) { } }

implementation: Log . e ( UberSdk . UBER_SDK_LOG_TAG , logMessage , exception ) ; if ( Utility . isDebugable ( activity ) ) { new AlertDialog . Builder ( activity ) . setTitle ( alertTitle ) . setMessage ( alertMessage ) . setNeutralButton ( R . string . ub__alert_dialog_ok , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { } } ) . show ( ) ; return true ; } return false ;


signature:
public class RideRequestView { /** * Loads the ride widget .
 * Requires that the { @ link AccessToken } has been retrieved . */
public void load ( ) { } }

implementation: final SessionConfiguration config ; final AccessTokenStorage storage ; if ( accessTokenSession == null && UberSdk . isInitialized ( ) ) { config = UberSdk . getDefaultSessionConfiguration ( ) ; storage = new AccessTokenManager ( getContext ( ) ) ; accessTokenSession = new AccessTokenSession ( config , storage ) ; } else if ( accessTokenSession != null ) { config = accessTokenSession . getAuthenticator ( ) . getSessionConfiguration ( ) ; storage = accessTokenSession . getAuthenticator ( ) . getTokenStorage ( ) ; } else { config = null ; storage = null ; } if ( config == null || storage == null || storage . getAccessToken ( ) == null ) { if ( rideRequestViewCallback != null ) { rideRequestViewCallback . onErrorReceived ( RideRequestViewError . NO_ACCESS_TOKEN ) ; } return ; } webView . loadUrl ( buildUrlFromRideParameters ( getContext ( ) , rideParameters , config ) , RideRequestView . getHeaders ( storage . getAccessToken ( ) ) ) ;


signature:
public class RideRequestView { /** * Builds a URL with necessary query parameters to load in the { @ link WebView } .
 * @ param rideParameters the { @ link RideParameters } to build into the query
 * @ return the URL { @ link String } to load in the { @ link WebView } */
@ NonNull @ VisibleForTesting static String buildUrlFromRideParameters ( @ NonNull Context context , @ NonNull RideParameters rideParameters , @ NonNull SessionConfiguration loginConfiguration ) { } }

implementation: final String ENDPOINT = "components" ; final String ENVIRONMENT_KEY = "env" ; final String HTTPS = "https" ; final String PATH = "rides/" ; final String SANDBOX = "sandbox" ; Uri . Builder builder = new Uri . Builder ( ) ; builder . scheme ( HTTPS ) . authority ( ENDPOINT + "." + loginConfiguration . getEndpointRegion ( ) . getDomain ( ) ) . appendEncodedPath ( PATH ) ; if ( rideParameters . getUserAgent ( ) == null ) { rideParameters . setUserAgent ( USER_AGENT_RIDE_VIEW ) ; } RideRequestDeeplink deeplink = new RideRequestDeeplink . Builder ( context ) . setSessionConfiguration ( loginConfiguration ) . setRideParameters ( rideParameters ) . build ( ) ; Uri uri = deeplink . getUri ( ) ; builder . encodedQuery ( uri . getEncodedQuery ( ) ) ; if ( loginConfiguration . getEnvironment ( ) == SessionConfiguration . Environment . SANDBOX ) { builder . appendQueryParameter ( ENVIRONMENT_KEY , SANDBOX ) ; } return builder . build ( ) . toString ( ) ;


signature:
public class RideRequestView { /** * Creates a { @ link Map } of the headers needed to pass to the { @ link WebView } .
 * @ param accessToken the { @ link AccessToken } to use for the Authorization header .
 * @ return a { @ link Map } containing headers to pass to { @ link WebView } . */
@ NonNull @ VisibleForTesting static Map < String , String > getHeaders ( @ NonNull AccessToken accessToken ) { } }

implementation: final String AUTH_HEADER = "Authorization" ; final String BEARER = "Bearer" ; Map < String , String > headers = new HashMap < String , String > ( ) ; headers . put ( AUTH_HEADER , BEARER + " " + accessToken . getToken ( ) ) ; return headers ;


signature:
public class RideRequestView { /** * Initialize the layout , properties , and inner web view . */
private void init ( @ NonNull Context context ) { } }

implementation: inflate ( getContext ( ) , R . layout . ub__ride_request_view , this ) ; webView = ( WebView ) findViewById ( R . id . ub__ride_request_webview ) ; webView . getSettings ( ) . setJavaScriptEnabled ( true ) ; webView . getSettings ( ) . setGeolocationEnabled ( true ) ; webView . getSettings ( ) . setAppCacheEnabled ( true ) ; webView . getSettings ( ) . setCacheMode ( WebSettings . LOAD_CACHE_ELSE_NETWORK ) ; webView . setWebChromeClient ( new RideRequestWebChromeClient ( ) ) ; webView . setWebViewClient ( new RideRequestWebViewClient ( new RideRequestWebViewClientCallback ( ) { @ Override public void onErrorParsed ( @ NonNull RideRequestViewError error ) { if ( rideRequestViewCallback != null ) { rideRequestViewCallback . onErrorReceived ( error ) ; } } } ) ) ;


signature:
public class Preconditions { /** * Ensures the value is not null .
 * @ param value value to be validated .
 * @ param errorMessage error message thrown if value is null .
 * @ param < T > type of value .
 * @ return value passed in if not null . */
@ NonNull public static < T > T checkNotNull ( T value , @ NonNull String errorMessage ) { } }

implementation: if ( value == null ) { throw new NullPointerException ( errorMessage ) ; } return value ;


signature:
public class RideRequestActivity { /** * Creates a new { @ link Intent } to be passed in to this activity with all the required information .
 * @ param context the { @ link Context } that will be launching this activity
 * @ param rideParameters the optional { @ link RideParameters } containing information to populate the { @ link RideRequestView }
 * @ param loginConfiguration required when RideRequestActivity needs to start authentication flow
 * @ param accessTokenStorageKey optional key to lookup access token from { @ link com . uber . sdk . core . auth . AccessTokenStorage }
 * @ return new { @ link Intent } with the necessary parameters for this activity */
@ NonNull public static Intent newIntent ( @ NonNull Context context , @ Nullable RideParameters rideParameters , @ NonNull SessionConfiguration loginConfiguration , @ Nullable String accessTokenStorageKey ) { } }

implementation: Intent data = new Intent ( context , RideRequestActivity . class ) ; if ( rideParameters == null ) { rideParameters = new RideParameters . Builder ( ) . build ( ) ; } data . putExtra ( RIDE_PARAMETERS , rideParameters ) ; data . putExtra ( EXTRA_LOGIN_CONFIGURATION , loginConfiguration ) ; data . putExtra ( EXTRA_ACCESS_TOKEN_STORAGE_KEY , accessTokenStorageKey ) ; return data ;


signature:
public class RideRequestActivity { /** * Loads the appropriate view in the activity based on whether user is successfully authorized or not . */
private void load ( ) { } }

implementation: AccessToken accessToken = accessTokenStorage . getAccessToken ( ) ; if ( accessToken != null ) { AccessTokenSession session = new AccessTokenSession ( sessionConfiguration , accessTokenStorage ) ; rideRequestView . setSession ( session ) ; loadRideRequestView ( ) ; } else { login ( ) ; }


signature:
public class RideRequestActivity { /** * Builds an { @ link AlertDialog } to the user to indicate an error and dismisses activity .
 * @ param messageTextId the message content { @ link StringRes } text ID
 * @ param positiveButtonTextId the positive button { @ link StringRes } text ID
 * @ param intent the { @ link Intent } to pass in the result
 * @ return an { @ link AlertDialog } to show */
@ NonNull private AlertDialog buildErrorAlert ( @ StringRes int messageTextId , @ StringRes int positiveButtonTextId , final Intent intent ) { } }

implementation: return new AlertDialog . Builder ( this ) . setMessage ( messageTextId ) . setPositiveButton ( positiveButtonTextId , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { setResult ( RESULT_CANCELED , intent ) ; finish ( ) ; } } ) . setOnCancelListener ( new DialogInterface . OnCancelListener ( ) { @ Override public void onCancel ( DialogInterface dialog ) { setResult ( RESULT_CANCELED , intent ) ; finish ( ) ; } } ) . create ( ) ;


signature:
public class RideRequestActivity { /** * Builds an { @ link AlertDialog } to the user to indicate a { @ link RideRequestViewError # CONNECTIVITY _ ISSUE }
 * and allow the retry of the button .
 * @ param messageTextId the message content { @ link StringRes } text ID
 * @ param positiveButtonTextId the positive button { @ link StringRes } text ID
 * @ param negativeButtonTextId the negative button { @ link StringRes } text ID
 * @ param intent the { @ link Intent } to pass in the result
 * @ return an { @ link AlertDialog } to show */
@ NonNull private AlertDialog buildRetryAlert ( @ StringRes int messageTextId , @ StringRes int positiveButtonTextId , @ StringRes int negativeButtonTextId , final Intent intent ) { } }

implementation: return new AlertDialog . Builder ( this ) . setMessage ( messageTextId ) . setPositiveButton ( positiveButtonTextId , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { load ( ) ; } } ) . setNegativeButton ( negativeButtonTextId , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialogInterface , int i ) { setResult ( RESULT_CANCELED , intent ) ; finish ( ) ; } } ) . setOnCancelListener ( new DialogInterface . OnCancelListener ( ) { @ Override public void onCancel ( DialogInterface dialog ) { setResult ( RESULT_CANCELED , intent ) ; finish ( ) ; } } ) . create ( ) ;


signature:
public class RideRequestDeeplink { /** * Executes the deeplink to launch the Uber app . If the app is not installed redirects to the play store . */
public void execute ( ) { } }

implementation: final CustomTabsIntent intent = new CustomTabsIntent . Builder ( ) . build ( ) ; customTabsHelper . openCustomTab ( context , intent , uri , new CustomTabsHelper . BrowserFallback ( ) ) ;


signature:
public class AppProtocol { /** * Validates minimum version of app required or returns true if in debug . */
public boolean validateMinimumVersion ( @ NonNull Context context , @ NonNull PackageInfo packageInfo , int minimumVersion ) { } }

implementation: if ( isDebug ( context ) ) { return true ; } return packageInfo . versionCode >= minimumVersion ;


signature:
public class AppProtocol { /** * Verify if any version of the app has been installed on this device .
 * @ param context A { @ link Context } .
 * @ param supportedApp The { @ link SupportedAppType } .
 * @ return { @ code true } if any version of the app is installed ( min version of 0 ) . */
public boolean isInstalled ( @ NonNull Context context , @ NonNull SupportedAppType supportedApp ) { } }

implementation: return isInstalled ( context , supportedApp , DEFAULT_MIN_VERSION ) ;


signature:
public class AppProtocol { /** * Check if the minimum version of { @ link SupportedAppType } is installed .
 * @ param context A { @ link Context } .
 * @ param supportedApp The { @ link SupportedAppType } .
 * @ param minimumVersion The minimum version of { @ link SupportedAppType } that must be installed .
 * @ return { @ code true } if any valid package for the app is installed . */
public boolean isInstalled ( @ NonNull Context context , @ NonNull SupportedAppType supportedApp , int minimumVersion ) { } }

implementation: return ! getInstalledPackages ( context , supportedApp , minimumVersion ) . isEmpty ( ) ;


signature:
public class AppProtocol { /** * Find the installed and validated packages for a { @ link SupportedAppType } .
 * This will validate the signature and minimum version of the installed package or exclude it from returned list .
 * @ param context A { @ link Context } .
 * @ param supportedApp The { @ link SupportedAppType } .
 * @ param minimumVersion The minimum version of { @ link SupportedAppType } that must be installed .
 * @ return A list of { @ link PackageInfo } which is installed and has been validated . */
@ NonNull public List < PackageInfo > getInstalledPackages ( @ NonNull Context context , @ NonNull SupportedAppType supportedApp , int minimumVersion ) { } }

implementation: List < PackageInfo > packageInfos = new ArrayList < > ( ) ; List < Pair < SupportedAppType , PackageInfo > > installedApps = getInstalledPackagesByApp ( context , supportedApp ) ; for ( Pair < SupportedAppType , PackageInfo > installedApp : installedApps ) { PackageInfo packageInfo = installedApp . second ; if ( packageInfo != null && validateSignature ( context , packageInfo . packageName ) && validateMinimumVersion ( context , packageInfo , minimumVersion ) ) { packageInfos . add ( packageInfo ) ; } } return packageInfos ;


signature:
public class AppProtocol { /** * Validates the app signature required or returns true if in debug . */
public boolean validateSignature ( @ NonNull Context context , @ NonNull String packageName ) { } }

implementation: if ( isDebug ( context ) ) { return true ; } PackageInfo packageInfo ; try { packageInfo = context . getPackageManager ( ) . getPackageInfo ( packageName , PackageManager . GET_SIGNATURES ) ; } catch ( PackageManager . NameNotFoundException e ) { return false ; } for ( Signature signature : packageInfo . signatures ) { String hashedSignature = Utility . sha1hash ( signature . toByteArray ( ) ) ; if ( ! validAppSignatureHashes . contains ( hashedSignature ) ) { return false ; } } return true ;


signature:
public class LoginSampleActivity { /** * Validates the local variables needed by the Uber SDK used in the sample project
 * @ param configuration */
private void validateConfiguration ( SessionConfiguration configuration ) { } }

implementation: String nullError = "%s must not be null" ; String sampleError = "Please update your %s in the gradle.properties of the project before " + "using the Uber SDK Sample app. For a more secure storage location, " + "please investigate storing in your user home gradle.properties " ; checkNotNull ( configuration , String . format ( nullError , "SessionConfiguration" ) ) ; checkNotNull ( configuration . getClientId ( ) , String . format ( nullError , "Client ID" ) ) ; checkNotNull ( configuration . getRedirectUri ( ) , String . format ( nullError , "Redirect URI" ) ) ; checkState ( ! configuration . getClientId ( ) . equals ( "insert_your_client_id_here" ) , String . format ( sampleError , "Client ID" ) ) ; checkState ( ! configuration . getRedirectUri ( ) . equals ( "insert_your_redirect_uri_here" ) , String . format ( sampleError , "Redirect URI" ) ) ;


signature:
public class SsoDeeplink { /** * Starts the deeplink with the configuration options specified by this object . Use { @ link Builder } to construct
 * an instance .
 * @ param flowVersion specifies which client implementation to use for handling the response to the SSO request
 * @ throws IllegalStateException if compatible Uber app is not installed or the deeplink is incorrectly configured .
 * Use { @ link # isSupported ( ) } to check . */
void execute ( @ NonNull FlowVersion flowVersion ) { } }

implementation: checkState ( isSupported ( flowVersion ) , "Single sign on is not supported on the device. " + "Please install or update to the latest version of Uber app." ) ; Intent intent = new Intent ( Intent . ACTION_VIEW ) ; final Uri deepLinkUri = createSsoUri ( flowVersion ) ; intent . setData ( deepLinkUri ) ; List < PackageInfo > validatedPackages = new ArrayList < > ( ) ; if ( productFlowPriority . isEmpty ( ) ) { validatedPackages . addAll ( appProtocol . getInstalledPackages ( activity , UBER , getSupportedAppVersion ( UBER , flowVersion ) ) ) ; } else { for ( SupportedAppType supportedAppType : productFlowPriority ) { validatedPackages . addAll ( appProtocol . getInstalledPackages ( activity , supportedAppType , getSupportedAppVersion ( supportedAppType , flowVersion ) ) ) ; } } if ( ! validatedPackages . isEmpty ( ) ) { intent . setPackage ( validatedPackages . get ( 0 ) . packageName ) ; } if ( flowVersion == FlowVersion . DEFAULT ) { activity . startActivityForResult ( intent , requestCode ) ; } else { activity . startActivity ( intent ) ; }


signature:
public class SsoDeeplink { /** * Check if SSO deep linking is supported in this device .
 * @ param flowVersion specifies which client implementation to validate
 * @ return true if package name , minimum version , and redirect uri requirements for flowVersion are met */
boolean isSupported ( @ NonNull FlowVersion flowVersion ) { } }

implementation: if ( flowVersion == FlowVersion . REDIRECT_TO_SDK ) { Intent redirectIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( redirectUri ) ) ; redirectIntent . setPackage ( activity . getPackageName ( ) ) ; List < ResolveInfo > resolveInfoList = activity . getPackageManager ( ) . queryIntentActivities ( redirectIntent , PackageManager . MATCH_DEFAULT_ONLY ) ; if ( resolveInfoList . isEmpty ( ) ) { return false ; } } if ( productFlowPriority . isEmpty ( ) ) { return appProtocol . isInstalled ( activity , UBER , getSupportedAppVersion ( UBER , flowVersion ) ) ; } else { for ( SupportedAppType supportedAppType : productFlowPriority ) { if ( appProtocol . isInstalled ( activity , supportedAppType , getSupportedAppVersion ( supportedAppType , flowVersion ) ) ) { return true ; } } return false ; }


signature:
public class LoginActivity { /** * Create an { @ link Intent } to pass to this activity
 * @ param context the { @ link Context } for the intent
 * @ param sessionConfiguration to be used for gather clientId
 * @ param responseType that is expected
 * @ return an intent that can be passed to this activity */
@ NonNull public static Intent newIntent ( @ NonNull Context context , @ NonNull SessionConfiguration sessionConfiguration , @ NonNull ResponseType responseType ) { } }

implementation: return newIntent ( context , sessionConfiguration , responseType , false ) ;


signature:
public class LoginActivity { /** * Create an { @ link Intent } to pass to this activity
 * @ param context the { @ link Context } for the intent
 * @ param sessionConfiguration to be used for gather clientId
 * @ param responseType that is expected
 * @ param forceWebview Forced to use old webview instead of chrometabs
 * @ return an intent that can be passed to this activity */
@ NonNull public static Intent newIntent ( @ NonNull Context context , @ NonNull SessionConfiguration sessionConfiguration , @ NonNull ResponseType responseType , boolean forceWebview ) { } }

implementation: return newIntent ( context , new ArrayList < SupportedAppType > ( ) , sessionConfiguration , responseType , forceWebview , false , false ) ;


signature:
public class LoginActivity { /** * Create an { @ link Intent } to pass to this activity
 * @ param context the { @ link Context } for the intent
 * @ param productPriority dictates the order of which Uber applications should be used for SSO .
 * @ param sessionConfiguration to be used for gather clientId
 * @ param responseType that is expected
 * @ param forceWebview Forced to use old webview instead of chrometabs
 * @ param isSsoEnabled specifies whether to attempt login with SSO
 * @ return an intent that can be passed to this activity */
@ NonNull static Intent newIntent ( @ NonNull Context context , @ NonNull ArrayList < SupportedAppType > productPriority , @ NonNull SessionConfiguration sessionConfiguration , @ NonNull ResponseType responseType , boolean forceWebview , boolean isSsoEnabled , boolean isRedirectToPlayStoreEnabled ) { } }

implementation: final Intent data = new Intent ( context , LoginActivity . class ) . putExtra ( EXTRA_PRODUCT_PRIORITY , productPriority ) . putExtra ( EXTRA_SESSION_CONFIGURATION , sessionConfiguration ) . putExtra ( EXTRA_RESPONSE_TYPE , responseType ) . putExtra ( EXTRA_FORCE_WEBVIEW , forceWebview ) . putExtra ( EXTRA_SSO_ENABLED , isSsoEnabled ) . putExtra ( EXTRA_REDIRECT_TO_PLAY_STORE_ENABLED , isRedirectToPlayStoreEnabled ) ; return data ;


signature:
public class LoginActivity { /** * Used to handle Redirect URI response from customtab or browser
 * @ param context
 * @ param responseUri
 * @ return */
public static Intent newResponseIntent ( Context context , Uri responseUri ) { } }

implementation: Intent intent = new Intent ( context , LoginActivity . class ) ; intent . setData ( responseUri ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP | Intent . FLAG_ACTIVITY_SINGLE_TOP ) ; return intent ;


signature:
public class LoginActivity { /** * Handler for both AccessToken and AuthorizationCode redirects .
 * @ param uri The redirect Uri . */
private void handleResponse ( @ NonNull Uri uri ) { } }

implementation: if ( AuthUtils . isAuthorizationCodePresent ( uri ) ) { onCodeReceived ( uri ) ; } else { handleAccessTokenResponse ( uri ) ; }


signature:
public class LoginActivity { /** * Process the callback for AccessToken .
 * @ param uri Redirect URI containing AccessToken values . */
private void handleAccessTokenResponse ( @ NonNull Uri uri ) { } }

implementation:
final String fragment = uri . getFragment ( ) ; if ( TextUtils . isEmpty ( fragment ) ) { onError ( AuthenticationError . INVALID_RESPONSE ) ; return ; } final Uri fragmentUri = new Uri . Builder ( ) . encodedQuery ( fragment ) . build ( ) ; // In case fragment contains error , we want to handle that too .
final String error = fragmentUri . getQueryParameter ( ERROR ) ; if ( ! TextUtils . isEmpty ( error ) ) { onError ( AuthenticationError . fromString ( error ) ) ; } else { onTokenReceived ( fragmentUri ) ; }


signature:
public class LegacyUriRedirectHandler { /** * Will validate that the Redirect URI mode is valid { @ link Mode # OFF } and return true
 * If false , then the app should terminate codeflow , this will happen in Debug mode for
 * unhandled migration scenarios .
 * See https : / / github . com / uber / rides - android - sdk # authentication - migration - version .
 * @ param activity to lookup package info and launch blocking dialog
 * @ param loginManager to validate old auth code flow
 * @ return true if valid , false if invalid */
boolean checkValidState ( @ NonNull Activity activity , @ NonNull LoginManager loginManager ) { } }

implementation: initState ( activity , loginManager ) ; boolean validToContinueExecution = true ; if ( isLegacyMode ( ) ) { String logMessage = activity . getString ( getLegacyModeErrorMessage ( ) ) ; String uiTitle = activity . getString ( R . string . ub__misconfigured_redirect_uri_title ) ; String uiMessage = activity . getString ( R . string . ub__misconfigured_redirect_uri_message ) ; validToContinueExecution = ! Utility . logAndShowBlockingDebugUIAlert ( activity , logMessage , uiTitle , uiMessage , new IllegalStateException ( logMessage ) ) ; } return validToContinueExecution ;


signature:
public class AuthUtils { /** * Converts a { @ link Collection } of { @ link Scope } s to a { @ link Set } of { @ link String } s .
 * @ param scopeCollection the { @ link Collection } of { @ link Scope } s to convert .
 * @ return a { @ link Set } of { @ link String } s . */
@ NonNull static Set < String > scopeCollectionToStringSet ( @ NonNull Collection < Scope > scopeCollection ) { } }

implementation: Set < String > stringCollection = new HashSet < > ( ) ; for ( Scope scope : scopeCollection ) { stringCollection . add ( scope . name ( ) ) ; } return stringCollection ;


signature:
public class AuthUtils { /** * Converts a { @ link String } representing space delimited { @ link Scope } s to a { @ link Collection < Scope > } .
 * @ param scopesString the { @ link String } to convert .
 * @ return a { @ link Collection } of { @ link Scope } s .
 * @ throws IllegalArgumentException if a part of the string doesn ' t match a scope name . */
@ NonNull static Collection < Scope > stringToScopeCollection ( @ NonNull String scopesString ) throws IllegalArgumentException { } }

implementation:
Set < Scope > scopeCollection = new HashSet < > ( ) ; if ( scopesString . isEmpty ( ) ) { return scopeCollection ; } String [ ] scopeStrings = scopesString . split ( " " ) ; for ( String scopeName : scopeStrings ) { try { scopeCollection . add ( Scope . valueOf ( scopeName . toUpperCase ( ) ) ) ; } catch ( IllegalArgumentException e ) { // do nothing , will omit custom or bad scopes
} } return scopeCollection ;


signature:
public class AuthUtils { /** * Converts a { @ link Set } of { @ link String } s to { @ link Collection } of { @ link Scope } s .
 * @ param stringSet the { @ link Set } of { @ link String } s to convert .
 * @ return a { @ link Collection } of { @ link Scope } s . */
@ NonNull static Collection < Scope > stringCollectionToScopeCollection ( @ NonNull Collection < String > stringSet ) throws IllegalArgumentException { } }

implementation: Set < Scope > scopeCollection = new HashSet < > ( ) ; for ( String scopeName : stringSet ) { scopeCollection . add ( Scope . valueOf ( scopeName ) ) ; } return scopeCollection ;


signature:
public class AuthUtils { /** * Converts a { @ link Collection } of { @ link Scope } s into a space - delimited { @ link String } .
 * @ param scopes the { @ link Collection } of { @ link Scope } s to convert
 * @ return a space - delimited { @ link String } of { @ link Scope } s */
@ NonNull public static String scopeCollectionToString ( @ NonNull Collection < Scope > scopes ) { } }

implementation: Set < String > stringSet = scopeCollectionToStringSet ( scopes ) ; return TextUtils . join ( " " , stringSet ) . toLowerCase ( ) ;


signature:
public class AuthUtils { /** * Converts a { @ link Collection } of { @ link String } s into a space - delimited { @ link String } .
 * @ param scopes the { @ link Collection } of { @ link String } s to convert
 * @ return a space - delimited { @ link String } of { @ link Scope } s */
public static String customScopeCollectionToString ( @ NonNull Collection < String > scopes ) { } }

implementation: return TextUtils . join ( " " , scopes ) . toLowerCase ( ) ;


signature:
public class AuthUtils { /** * Builds a URL { @ link String } using the necessary parameters to load in the { @ link WebView } .
 * @ return the URL to load in the { @ link WebView } */
@ NonNull static String buildUrl ( @ NonNull String redirectUri , @ NonNull ResponseType responseType , @ NonNull SessionConfiguration configuration ) { } }

implementation: final String CLIENT_ID_PARAM = "client_id" ; final String ENDPOINT = "login" ; final String HTTPS = "https" ; final String PATH = "oauth/v2/authorize" ; final String REDIRECT_PARAM = "redirect_uri" ; final String RESPONSE_TYPE_PARAM = "response_type" ; final String SCOPE_PARAM = "scope" ; final String SHOW_FB_PARAM = "show_fb" ; final String SIGNUP_PARAMS = "signup_params" ; final String REDIRECT_LOGIN = "{\"redirect_to_login\":true}" ; Uri . Builder builder = new Uri . Builder ( ) ; builder . scheme ( HTTPS ) . authority ( ENDPOINT + "." + configuration . getEndpointRegion ( ) . getDomain ( ) ) . appendEncodedPath ( PATH ) . appendQueryParameter ( CLIENT_ID_PARAM , configuration . getClientId ( ) ) . appendQueryParameter ( REDIRECT_PARAM , redirectUri ) . appendQueryParameter ( RESPONSE_TYPE_PARAM , responseType . toString ( ) . toLowerCase ( Locale . US ) ) . appendQueryParameter ( SCOPE_PARAM , getScopes ( configuration ) ) . appendQueryParameter ( SHOW_FB_PARAM , "false" ) . appendQueryParameter ( SIGNUP_PARAMS , AuthUtils . createEncodedParam ( REDIRECT_LOGIN ) ) ; return builder . build ( ) . toString ( ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . GET request ( URL : . . . / getUsers ) .
 * @ return ResponseEntity with string in JSON format with all users . */
@ RequestMapping ( "/getUsers" ) public ResponseEntity < String > getUsers ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForGetUsers ( ) ; return new ResponseEntity < > ( response . getBodyAnswer ( ) , httpHeaders , HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . GET request ( URL : . . . / getUser ) .
 * @ return ResponseEntity with string in JSON format with specified user or ' user no found ' error . */
@ RequestMapping ( "/getUser" ) public ResponseEntity < String > getUser ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForGetUser ( ) ; return new ResponseEntity < > ( response . getBodyAnswer ( ) , httpHeaders , HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . POST request ( URL : . . . / registerUser ) .
 * @ return ResponseEntity with string in JSON format with http status result ( success or not ) and user id . */
@ RequestMapping ( method = RequestMethod . POST , value = "/registerUser" ) public ResponseEntity < String > registerUser ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForRegisterUser ( ) ; return new ResponseEntity < > ( response . getBodyAnswer ( ) , httpHeaders , HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . PUT request ( URL : . . . / updateUser ) .
 * @ return ResponseEntity with http status result ( success or not ) . */
@ RequestMapping ( method = RequestMethod . PUT , value = "/updateUser" ) public ResponseEntity < Void > updateUser ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForUpdateUser ( ) ; return new ResponseEntity < > ( HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . PATCH request ( URL : . . . / updateUserField ) .
 * @ return ResponseEntity with http status result ( success or not ) . */
@ RequestMapping ( method = RequestMethod . PATCH , value = "/updateUserField" ) public ResponseEntity < Void > updateUserField ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForUpdateUserField ( ) ; return new ResponseEntity < > ( HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . DELETE request ( URL : . . . / clearUser ) .
 * @ return ResponseEntity with http status result ( success or not ) . */
@ RequestMapping ( method = RequestMethod . DELETE , value = "/clearUser" ) public ResponseEntity < Void > deleteUser ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForDeleteUser ( ) ; return new ResponseEntity < > ( HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Processes HTTP . DELETE request ( URL : . . . / clearAll ) .
 * @ return ResponseEntity with http status result ( success or not ) . */
@ RequestMapping ( method = RequestMethod . DELETE , value = "/clearAll" ) public ResponseEntity < Void > deleteUsers ( ) { } }

implementation: ConfigurationHandler response = configurationHandlerService . getConfigForDeleteUsers ( ) ; return new ResponseEntity < > ( HttpStatus . valueOf ( response . getResult ( ) ) ) ;


signature:
public class ConfigurationHandlerController { /** * Edit representation for method specified in sent parameter after processing HTTP . POST request ( URL : . . . / manage ) .
 * @ param configurationHandler Representation of response .
 * @ return HttpStatus . OK if contains sent method , HttpStatus . BAD _ REQUEST otherwise . */
@ RequestMapping ( method = RequestMethod . POST , value = "/manage" ) public ResponseEntity < Void > manage ( @ RequestBody ConfigurationHandler configurationHandler ) { } }

implementation: return configurationHandlerService . editMap ( configurationHandler ) ? new ResponseEntity < > ( HttpStatus . OK ) : new ResponseEntity < > ( HttpStatus . BAD_REQUEST ) ;


signature:
public class ConfigurationHandlerService { /** * Edit representation for method specified in sent parameter after controller calls for it .
 * @ param configurationHandler Our representation of response .
 * @ return True if mock - service contains sent method , false otherwise . */
public boolean editMap ( ConfigurationHandler configurationHandler ) { } }

implementation: String method = configurationHandler . getMethod ( ) . toUpperCase ( ) ; if ( configurationHandlerMap . containsKey ( Method . valueOf ( method ) ) ) { configurationHandlerMap . put ( Method . valueOf ( method ) , configurationHandler ) ; return true ; } return false ;


signature:
public class InMemoryTriggerDao { /** * @ warn method description missing
 * @ warn parameter descriptions missing
 * @ param triggerGroup
 * @ param trigger
 * @ return */
@ Override public String createTrigger ( String triggerGroup , Trigger trigger ) { } }

implementation: trigger . setId ( createId ( triggerGroup , UUID . randomUUID ( ) . toString ( ) ) ) ; create ( triggerGroup , trigger . getId ( ) , trigger ) ; return trigger . getId ( ) ;


signature:
public class InMemoryTriggerDao { /** * @ warn method description missing
 * @ warn parameter triggerId description missing
 * @ param triggerId
 * @ return */
@ Override public Trigger getTrigger ( String triggerId ) { } }

implementation: String triggerGroup = extractGroupFromId ( triggerId ) ; return read ( triggerGroup , triggerId ) ;


signature:
public class InMemoryTriggerDao { /** * @ warn method description missing
 * @ warn parameter trigger description missing
 * @ param trigger */
@ Override public void updateTrigger ( Trigger trigger ) { } }

implementation: String triggerGroup = extractGroupFromId ( trigger . getId ( ) ) ; update ( triggerGroup , trigger . getId ( ) , trigger ) ;


signature:
public class InMemoryTriggerDao { /** * @ warn method description missing
 * @ warn parameter descriptions missing
 * @ param triggerGroup
 * @ param trigger */
@ Override public void deleteTrigger ( String triggerGroup , Trigger trigger ) { } }

implementation: delete ( triggerGroup , trigger . getId ( ) ) ;


signature:
public class TaskSchedulingService { /** * / * package */
Map < String , Integer > requestPseudoScheduling ( final InternalTaskQueue pTaskQueue , Map < String , Integer > groupCounts ) { } }

implementation:
Map < String , Integer > pseudoSchedulingResult = new HashMap < > ( ) ; try { logger . debug ( "Creating pseudo hosts" ) ; final Map < String , List < String > > pseudoHosts = taskScheduler . createPseudoHosts ( groupCounts ) ; logger . debug ( "Created " + pseudoHosts . size ( ) + " pseudoHost groups" ) ; int pHostsAdded = 0 ; for ( Map . Entry < String , List < String > > entry : pseudoHosts . entrySet ( ) ) { logger . debug ( "Pseudo hosts for group " + entry . getKey ( ) + ": " + entry . getValue ( ) ) ; pHostsAdded += entry . getValue ( ) == null ? 0 : entry . getValue ( ) . size ( ) ; } try { Map < String , String > hostnameToGrpMap = new HashMap < > ( ) ; for ( Map . Entry < String , List < String > > entry : pseudoHosts . entrySet ( ) ) { for ( String h : entry . getValue ( ) ) hostnameToGrpMap . put ( h , entry . getKey ( ) ) ; } try { pTaskQueue . reset ( ) ; } catch ( TaskQueueMultiException e ) { final List < Exception > exceptions = e . getExceptions ( ) ; if ( exceptions == null || exceptions . isEmpty ( ) ) { logger . error ( "Error with pseudo queue, no details available" ) ; } else { logger . error ( "Error with pseudo queue, details:" ) ; for ( Exception pe : exceptions ) { logger . error ( "pseudo queue error detail: " + pe . getMessage ( ) ) ; } } } // temporarily replace usage tracker in taskTracker to the pseudoQ and then put back the original one
taskScheduler . getTaskTracker ( ) . setUsageTrackedQueue ( pTaskQueue . getUsageTracker ( ) ) ; logger . debug ( "Scheduling with pseudoQ" ) ; final SchedulingResult schedulingResult = taskScheduler . pseudoScheduleOnce ( pTaskQueue ) ; final Map < String , VMAssignmentResult > resultMap = schedulingResult . getResultMap ( ) ; Map < String , Integer > result = new HashMap < > ( ) ; if ( ! resultMap . isEmpty ( ) ) { for ( String h : resultMap . keySet ( ) ) { final String grp = hostnameToGrpMap . get ( h ) ; if ( grp != null ) { Integer count = result . get ( grp ) ; if ( count == null ) result . put ( grp , 1 ) ; else result . put ( grp , count + 1 ) ; } } } else if ( pHostsAdded > 0 ) { logger . debug ( "No pseudo assignments made, looking for failures" ) ; final Map < TaskRequest , List < TaskAssignmentResult > > failures = schedulingResult . getFailures ( ) ; if ( failures == null || failures . isEmpty ( ) ) { logger . debug ( "No failures found for pseudo assignments" ) ; } else { for ( Map . Entry < TaskRequest , List < TaskAssignmentResult > > entry : failures . entrySet ( ) ) { final List < TaskAssignmentResult > tars = entry . getValue ( ) ; if ( tars == null || tars . isEmpty ( ) ) logger . debug ( "No pseudo assignment failures for task " + entry . getKey ( ) ) ; else { StringBuilder b = new StringBuilder ( "Pseudo assignment failures for task " ) . append ( entry . getKey ( ) ) . append ( ": " ) ; for ( TaskAssignmentResult r : tars ) { b . append ( "HOST: " ) . append ( r . getHostname ( ) ) . append ( ":" ) ; final List < AssignmentFailure > afs = r . getFailures ( ) ; if ( afs != null && ! afs . isEmpty ( ) ) afs . forEach ( af -> b . append ( af . getMessage ( ) ) . append ( "; " ) ) ; else b . append ( "None" ) . append ( ";" ) ; } logger . debug ( b . toString ( ) ) ; } } } } pseudoSchedulingResult = result ; } catch ( Exception e ) { logger . error ( "Error in pseudo scheduling" , e ) ; throw e ; } finally { taskScheduler . removePseudoHosts ( pseudoHosts ) ; taskScheduler . removePseudoAssignments ( ) ; taskScheduler . getTaskTracker ( ) . setUsageTrackedQueue ( taskQueue . getUsageTracker ( ) ) ; } } catch ( Exception e ) { logger . error ( "Error in pseudo scheduling" , e ) ; } return pseudoSchedulingResult ;


signature:
public class TaskSchedulingService { /** * Add new leases to be used for next scheduling iteration . Leases with IDs previously added cannot be added
 * again . If duplicates are found , the scheduling iteration throws an exception and is available via the
 * scheduling result callback . See { @ link TaskScheduler # scheduleOnce ( List , List ) } for details on behavior upon
 * encountering an exception . This method can be called anytime without impacting any currently running scheduling
 * iterations . The leases will be used in the next scheduling iteration .
 * @ param leases New leases to use for scheduling . */
public void addLeases ( List < ? extends VirtualMachineLease > leases ) { } }

implementation: if ( leases != null && ! leases . isEmpty ( ) ) { for ( VirtualMachineLease l : leases ) leaseBlockingQueue . offer ( l ) ; }


signature:
public class TaskSchedulingService { /** * Get all of the tasks in the scheduling service ' s queue and call the given action when it is available . The
 * list of queues returned is in a consistent state , that is , transitionary actions from ongoing scheduling
 * iterations do not affect the returned collection of tasks . Although an ongoing scheduling iteration is
 * unaffected by this call , onset of the next scheduling iteration may be delayed until the call to the given
 * { @ code action } returns . Therefore , it is expected that the { @ code action } callback return quickly .
 * @ param action The action to call with task collection .
 * @ throws TaskQueueException if too many actions are pending to get tasks collection . */
public void requestAllTasks ( Action1 < Map < TaskQueue . TaskState , Collection < QueuableTask > > > action ) throws TaskQueueException { } }

implementation: if ( ! taskMapRequest . offer ( action ) ) throw new TaskQueueException ( "Too many pending actions submitted for getting tasks collection" ) ;


signature:
public class TaskSchedulingService { /** * Get resource status information and call the given action when available . Although an ongoing scheduling
 * iteration is unaffected by this call , onset of the next scheduling iteration may be delayed until the call to the
 * given { @ code action } returns . Therefore , it is expected that the { @ code action } callback return quickly .
 * @ param action The action to call with resource status .
 * @ throws TaskQueueException if too many actions are pending to get resource status . */
public void requestResourceStatus ( Action1 < Map < String , Map < VMResource , Double [ ] > > > action ) throws TaskQueueException { } }

implementation: if ( ! resStatusRequest . offer ( action ) ) throw new TaskQueueException ( "Too many pending actions submitted for getting resource status" ) ;


signature:
public class TaskSchedulingService { /** * Get the current states of all known VMs and call the given action when available . Although an ongoing scheduling
 * iteration is unaffected by this call , onset of the next scheduling iteration may be delayed until the call to the
 * given { @ code action } returns . Therefore , it is expected that the { @ code action } callback return quickly .
 * @ param action The action to call with VM states .
 * @ throws TaskQueueException if too many actions are pending to get VM states . */
public void requestVmCurrentStates ( Action1 < List < VirtualMachineCurrentState > > action ) throws TaskQueueException { } }

implementation: if ( ! vmCurrStateRequest . offer ( action ) ) throw new TaskQueueException ( "Too many pending actions submitted for getting VM current state" ) ;


signature:
public class TaskSchedulingService { /** * Mark the given tasks as running . This is expected to be called for all tasks that were already running from before
 * { @ link com . netflix . fenzo . TaskSchedulingService } started running . For example , when the scheduling service
 * is being started after a restart of the system and there were some tasks launched in the previous run of
 * the system . Any tasks assigned resources during scheduling invoked by this service will be automatically marked
 * as running .
 * @ param task The task to mark as running
 * @ param hostname The name of the VM that the task is running on . */
public void initializeRunningTask ( QueuableTask task , String hostname ) { } }

implementation: addRunningTasksQueue . offer ( Collections . singletonMap ( hostname , task ) ) ;


signature:
public class TaskSchedulingService { /** * Mark the task to be removed . This is expected to be called for all tasks that were added to the queue , whether or
 * not the task is already running . If the task is running , the < code > hostname < / code > parameter must be set , otherwise ,
 * it can be < code > null < / code > . The actual remove operation is performed before the start of the next scheduling
 * iteration .
 * @ param taskId The Id of the task to be removed .
 * @ param qAttributes The queue attributes of the queue that the task belongs to
 * @ param hostname The name of the VM where the task was assigned resources from , or , < code > null < / code > if it was
 * not assigned any resources . */
public void removeTask ( String taskId , QAttributes qAttributes , String hostname ) { } }

implementation: removeTasksQueue . offer ( new RemoveTaskRequest ( taskId , qAttributes , hostname ) ) ;


signature:
public class TaskSchedulingService { /** * Set the wall clock time when this task is ready for consideration for resource allocation . Calling this method
 * is safer than directly calling { @ link QueuableTask # safeSetReadyAt ( long ) } since this scheduling service will
 * call the latter when it is safe to do so .
 * @ see QueuableTask # getReadyAt ( )
 * @ param taskId The Id of the task .
 * @ param attributes The queue attributes of the queue that the task belongs to .
 * @ param when The wall clock time in millis when the task is ready for consideration for assignment . */
public void setTaskReadyTime ( String taskId , QAttributes attributes , long when ) { } }

implementation: setReadyTimeQueue . offer ( new SetReadyTimeRequest ( taskId , attributes , when ) ) ;


signature:
public class CronTrigger { /** * @ warn method description missing
 * @ return */
@ Override @ JsonIgnore public ScheduleBuilder getScheduleBuilder ( ) { } }

implementation: return cronSchedule ( cronExpression ) . withMisfireHandlingInstructionDoNothing ( ) . inTimeZone ( TimeZone . getTimeZone ( timeZoneId ) ) ;


signature:
public class TaskGenerator { /** * Main method to run the task generator .
 * @ param args Arguments to the program . Provide as the only argument , the mesos connection string . */
public static void main ( String [ ] args ) { } }

implementation:
if ( args . length != 1 ) { System . err . println ( "Must provide one argument - Mesos master location string" ) ; System . exit ( 1 ) ; } int numTasks = 10 ; int numIters = 5 ; BlockingQueue < TaskRequest > taskQueue = new LinkedBlockingQueue < > ( ) ; final TaskGenerator taskGenerator = new TaskGenerator ( taskQueue , numIters , numTasks ) ; final SampleFramework framework = new SampleFramework ( taskQueue , args [ 0 ] , // mesos master location string
new Action1 < String > ( ) { @ Override public void call ( String s ) { taskGenerator . tasksCompleted . incrementAndGet ( ) ; } } , new Func1 < String , String > ( ) { @ Override public String call ( String s ) { return "sleep 2" ; } } ) ; long start = System . currentTimeMillis ( ) ; ( new Thread ( taskGenerator ) ) . start ( ) ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { framework . runAll ( ) ; } } ) . start ( ) ; while ( taskGenerator . tasksCompleted . get ( ) < ( numIters * numTasks ) ) { System . out . println ( "NUM TASKS COMPLETED: " + taskGenerator . tasksCompleted . get ( ) + " of " + ( numIters * numTasks ) ) ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { } } System . out . println ( "Took " + ( System . currentTimeMillis ( ) - start ) + " mS to complete " + ( numIters * numTasks ) + " tasks" ) ; framework . shutdown ( ) ; System . exit ( 0 ) ;


signature:
public class SampleFramework { /** * Shuts down the Mesos driver . */
public void shutdown ( ) { } }

implementation: System . out . println ( "Stopping down mesos driver" ) ; Protos . Status status = mesosSchedulerDriver . stop ( ) ; isShutdown . set ( true ) ;


signature:
public class SampleFramework { /** * Run scheduling loop until shutdown is called .
 * This sample implementation shows the general pattern of using Fenzo ' s task scheduler . Scheduling occurs in a
 * continuous loop , iteratively calling { @ link TaskScheduler # scheduleOnce ( List , List ) } method , passing in the
 * list of tasks currently pending launch , and a list of any new resource offers obtained from mesos since the last
 * time the lease queue was drained . The call returns an assignments result object from which any tasks assigned
 * can be launched via the mesos driver . The result contains a map with hostname as the key and assignment result
 * as the value . The assignment result contains the resource offers of the host that were used for the assignments
 * and a list of tasks assigned resources from the host . The resource offers were removed from the internal state in
 * Fenzo . However , the task assignments are not updated , yet . If the returned assignments are being used to launch
 * the tasks in mesos , call Fenzo ' s task assigner for each task launched to indicate that the task is being launched .
 * If the returned assignments are not being used , the resource offers in the assignment results must either be
 * rejected in mesos , or added back into Fenzo explicitly . */
void runAll ( ) { } }

implementation:
System . out . println ( "Running all" ) ; List < VirtualMachineLease > newLeases = new ArrayList < > ( ) ; while ( true ) { if ( isShutdown . get ( ) ) return ; newLeases . clear ( ) ; List < TaskRequest > newTaskRequests = new ArrayList < > ( ) ; System . out . println ( "#Pending tasks: " + pendingTasksMap . size ( ) ) ; TaskRequest taskRequest = null ; try { taskRequest = pendingTasksMap . size ( ) == 0 ? taskQueue . poll ( 5 , TimeUnit . SECONDS ) : taskQueue . poll ( 1 , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException ie ) { System . err . println ( "Error polling task queue: " + ie . getMessage ( ) ) ; } if ( taskRequest != null ) { taskQueue . drainTo ( newTaskRequests ) ; newTaskRequests . add ( 0 , taskRequest ) ; for ( TaskRequest request : newTaskRequests ) pendingTasksMap . put ( request . getId ( ) , request ) ; } leasesQueue . drainTo ( newLeases ) ; SchedulingResult schedulingResult = scheduler . scheduleOnce ( new ArrayList < > ( pendingTasksMap . values ( ) ) , newLeases ) ; System . out . println ( "result=" + schedulingResult ) ; Map < String , VMAssignmentResult > resultMap = schedulingResult . getResultMap ( ) ; if ( ! resultMap . isEmpty ( ) ) { for ( VMAssignmentResult result : resultMap . values ( ) ) { List < VirtualMachineLease > leasesUsed = result . getLeasesUsed ( ) ; List < Protos . TaskInfo > taskInfos = new ArrayList < > ( ) ; StringBuilder stringBuilder = new StringBuilder ( "Launching on VM " + leasesUsed . get ( 0 ) . hostname ( ) + " tasks " ) ; final Protos . SlaveID slaveId = leasesUsed . get ( 0 ) . getOffer ( ) . getSlaveId ( ) ; for ( TaskAssignmentResult t : result . getTasksAssigned ( ) ) { stringBuilder . append ( t . getTaskId ( ) ) . append ( ", " ) ; taskInfos . add ( getTaskInfo ( slaveId , t . getTaskId ( ) , taskCmdGetter . call ( t . getTaskId ( ) ) ) ) ; // unqueueTask task from pending tasks map and put into launched tasks map
// ( in real world , transition the task state )
pendingTasksMap . remove ( t . getTaskId ( ) ) ; launchedTasks . put ( t . getTaskId ( ) , leasesUsed . get ( 0 ) . hostname ( ) ) ; scheduler . getTaskAssigner ( ) . call ( t . getRequest ( ) , leasesUsed . get ( 0 ) . hostname ( ) ) ; } List < Protos . OfferID > offerIDs = new ArrayList < > ( ) ; for ( VirtualMachineLease l : leasesUsed ) offerIDs . add ( l . getOffer ( ) . getId ( ) ) ; System . out . println ( stringBuilder . toString ( ) ) ; mesosSchedulerDriver . launchTasks ( offerIDs , taskInfos ) ; } } // insert a short delay before scheduling any new tasks or tasks from before that haven ' t been launched yet .
try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ie ) { } }


signature:
public class AutoScaler { /** * make scaling activity happen after a fixed delayed time for the first time encountered ( e . g . , server start ) */
private long getInitialCoolDown ( long coolDownSecs ) { } }

implementation: long initialCoolDownInPastSecs = 120 ; initialCoolDownInPastSecs = Math . min ( coolDownSecs , initialCoolDownInPastSecs ) ; return System . currentTimeMillis ( ) - coolDownSecs * 1000 + initialCoolDownInPastSecs * 1000 ;


signature:
public class Scheduler { /** * @ warn method description missing
 * @ warn parameter threadPoolSize description missing
 * @ warn exception SchedulerException description missing
 * @ param threadPoolSize
 * @ throws SchedulerException */
synchronized void startScheduler ( int threadPoolSize ) throws SchedulerException { } }

implementation: if ( quartzScheduler == null ) { Properties props = new Properties ( ) ; props . setProperty ( "org.quartz.threadPool.threadCount" , String . format ( "%d" , threadPoolSize ) ) ; StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory ( props ) ; quartzScheduler = stdSchedulerFactory . getScheduler ( ) ; quartzScheduler . start ( ) ; }


signature:
public class Scheduler { /** * @ warn method description missing
 * @ warn parameter descriptions missing
 * @ warn exception SchedulerException description missing
 * @ param jobId
 * @ param jobGroup
 * @ param jobClass
 * @ param trigger
 * @ throws SchedulerException */
void scheduleQuartzJob ( String jobId , String jobGroup , Class < ? extends Job > jobClass , Trigger trigger ) throws SchedulerException { } }

implementation: JobDetail job = newJob ( jobClass ) . withIdentity ( jobId , jobGroup ) . build ( ) ; quartzScheduler . scheduleJob ( job , trigger ) ;


signature:
public class Scheduler { /** * @ warn method description missing
 * @ warn parameter descriptions missing
 * @ warn exception SchedulerException description missing
 * @ param jobId
 * @ param jobGroup
 * @ throws SchedulerException */
void unscheduleQuartzJob ( String jobId , String jobGroup ) throws SchedulerException { } }

implementation: quartzScheduler . unscheduleJob ( TriggerKey . triggerKey ( jobId , jobGroup ) ) ;


signature:
public class Scheduler { /** * @ warn method description missing
 * @ warn parameter descriptions missing
 * @ warn exception SchedulerException description missing
 * @ param jobId
 * @ param jobGroup
 * @ throws SchedulerException
 * @ return */
boolean isScheduled ( String jobId , String jobGroup ) throws SchedulerException { } }

implementation: return quartzScheduler . checkExists ( new JobKey ( jobId , jobGroup ) ) ;


signature:
public class ExclusiveHostConstraint { /** * Determines whether the prospective host already has tasks either running on it or assigned to be run on
 * it , and returns a false Result if either of those things is the case .
 * @ param taskRequest describes the task to be considered for assignment to the host
 * @ param targetVM describes the host to be considered for accepting the task
 * @ param taskTrackerState describes the state of tasks assigned to or running on hosts throughout the
 * system
 * @ return an unsuccessful Result if the target already has running tasks or assigned tasks , or a successful
 * Result otherwise */
@ Override public Result evaluate ( TaskRequest taskRequest , VirtualMachineCurrentState targetVM , TaskTrackerState taskTrackerState ) { } }

implementation: Collection < TaskRequest > runningTasks = targetVM . getRunningTasks ( ) ; if ( runningTasks != null && ! runningTasks . isEmpty ( ) ) return new Result ( false , "Already has " + runningTasks . size ( ) + " tasks running on it" ) ; Collection < TaskAssignmentResult > tasksCurrentlyAssigned = targetVM . getTasksCurrentlyAssigned ( ) ; if ( tasksCurrentlyAssigned != null && ! tasksCurrentlyAssigned . isEmpty ( ) ) return new Result ( false , "Already has " + tasksCurrentlyAssigned . size ( ) + " assigned on it" ) ; return new Result ( true , "" ) ;


signature:
public class BalancedHostAttrConstraint { /** * Converts this constraint into a " soft " constraint . By default , a balanced host attribute constraint is a
 * " hard " constraint , which is to say that Fenzo will guarantee that the constraint is applied and will fail
 * to place a task if the only way it can do so is to violate the constraint . This method returns a
 * { @ link VMTaskFitnessCalculator } that represents this constraint as a " soft " constraint that will permit
 * Fenzo to place a task in violation of the constraint if it cannot do so otherwise .
 * @ return a task fitness calculator that represents the balanced host attribute constraint as a soft
 * constraint */
public VMTaskFitnessCalculator asSoftConstraint ( ) { } }

implementation: return new VMTaskFitnessCalculator ( ) { @ Override public String getName ( ) { return name ; } @ Override public double calculateFitness ( TaskRequest taskRequest , VirtualMachineCurrentState targetVM , TaskTrackerState taskTrackerState ) { String targetHostAttrVal = AttributeUtilities . getAttrValue ( targetVM . getCurrAvailableResources ( ) , hostAttributeName ) ; if ( targetHostAttrVal == null || targetHostAttrVal . isEmpty ( ) ) { return 0.0 ; } Set < String > coTasks = coTasksGetter . call ( taskRequest . getId ( ) ) ; Map < String , Integer > usedAttribsMap = null ; try { usedAttribsMap = getUsedAttributesMap ( coTasks , taskTrackerState ) ; } catch ( Exception e ) { return 0.0 ; } final Integer integer = usedAttribsMap . get ( targetHostAttrVal ) ; if ( integer == null ) return 1.0 ; if ( usedAttribsMap . isEmpty ( ) ) return 1.0 ; double avg = 0.0 ; for ( Integer i : usedAttribsMap . values ( ) ) avg += i ; avg = Math . ceil ( avg + 1 / Math . max ( expectedValues , usedAttribsMap . size ( ) ) ) ; if ( integer <= avg ) return ( avg - ( double ) integer ) / avg ; return 0.0 ; } } ;


signature:
public class TierSla { /** * Evaluate the allocation share of a bucket among all the buckets for which allocations are defined . If there are
 * no allocations setup , return 1.0 , implying 100 % . If no allocation is setup for the given < code > bucket < / code > ,
 * return a small value . Otherwise , calculate the share percentage of each resource cpu , memory , network , and disk
 * from the total and return the maximum of these shares .
 * @ param bucket Name of the bucket .
 * @ return Allocation share for the bucket . */
double evalAllocationShare ( String bucket ) { } }

implementation:
if ( allocsMap . isEmpty ( ) ) { return 1.0 ; // special case if there are no allocations setup
} final ResAllocs resAllocs = allocsMap . get ( bucket ) ; if ( resAllocs == null ) return totalCpu < ( 1.0 / eps ) ? eps : 1.0 / totalCpu ; // arbitrarily base it on cpus
double val = totalCpu < 1.0 ? eps : resAllocs . getCores ( ) / totalCpu ; val = Math . max ( val , totalMem < 1.0 ? eps : resAllocs . getMemory ( ) / totalMem ) ; val = Math . max ( val , totalNetwork < 1.0 ? eps : resAllocs . getNetworkMbps ( ) / totalNetwork ) ; return Math . max ( val , totalDisk < 1.0 ? eps : resAllocs . getDisk ( ) / totalDisk ) ;


signature:
public class InternalVMCloner { /** * / * package */
VirtualMachineLease getClonedMaxResourcesLease ( Collection < AssignableVirtualMachine > avms ) { } }

implementation: double cpus = 0.0 ; double mem = 0.0 ; double disk = 0.0 ; double network = 0.0 ; double ports = 0.0 ; final Map < String , Double > scalars = new HashMap < > ( ) ; final Map < String , Protos . Attribute > attributeMap = new HashMap < > ( ) ; if ( avms != null ) { for ( AssignableVirtualMachine avm : avms ) { Map < VMResource , Double > maxResources = avm . getMaxResources ( ) ; Double value = maxResources . get ( VMResource . CPU ) ; if ( value != null ) { cpus = Math . max ( cpus , value ) ; } value = maxResources . get ( VMResource . Memory ) ; if ( value != null ) { mem = Math . max ( mem , value ) ; } value = maxResources . get ( VMResource . Disk ) ; if ( value != null ) { disk = Math . max ( disk , value ) ; } value = maxResources . get ( VMResource . Network ) ; if ( value != null ) { network = Math . max ( network , value ) ; } value = maxResources . get ( VMResource . Ports ) ; if ( value != null ) { ports = Math . max ( ports , value ) ; } final Map < String , Double > maxScalars = avm . getMaxScalars ( ) ; if ( maxScalars != null && ! maxScalars . isEmpty ( ) ) { for ( String k : maxScalars . keySet ( ) ) scalars . compute ( k , ( s , oldVal ) -> { if ( oldVal == null ) { oldVal = 0.0 ; } Double aDouble = maxScalars . get ( k ) ; if ( aDouble == null ) { aDouble = 0.0 ; } return oldVal + aDouble ; } ) ; } final Map < String , Protos . Attribute > attrs = avm . getCurrTotalLease ( ) . getAttributeMap ( ) ; if ( attrs != null && ! attrs . isEmpty ( ) ) { for ( Map . Entry < String , Protos . Attribute > e : attrs . entrySet ( ) ) attributeMap . putIfAbsent ( e . getKey ( ) , e . getValue ( ) ) ; } } } final double fcpus = cpus ; final double fmem = mem ; final double fdisk = disk ; final double fnetwork = network ; final List < VirtualMachineLease . Range > fports = Collections . singletonList ( new VirtualMachineLease . Range ( 100 , 100 + ( int ) ports ) ) ; return new VirtualMachineLease ( ) { @ Override public String getId ( ) { return "NoID" ; } @ Override public long getOfferedTime ( ) { return 0 ; } @ Override public String hostname ( ) { return "NoHostname" ; } @ Override public String getVMID ( ) { return "NoID" ; } @ Override public double cpuCores ( ) { return fcpus ; } @ Override public double memoryMB ( ) { return fmem ; } @ Override public double networkMbps ( ) { return fnetwork ; } @ Override public double diskMB ( ) { return fdisk ; } @ Override public List < Range > portRanges ( ) { return fports ; } @ Override public Protos . Offer getOffer ( ) { return null ; } @ Override public Map < String , Protos . Attribute > getAttributeMap ( ) { return attributeMap ; } @ Override public Double getScalarValue ( String name ) { return scalars . get ( name ) ; } @ Override public Map < String , Double > getScalarValues ( ) { return scalars ; } } ;


signature:
public class InternalVMCloner { /** * / * package */
VirtualMachineLease cloneLease ( VirtualMachineLease lease , final String hostname , long now ) { } }

implementation: final List < VirtualMachineLease . Range > ports = new LinkedList < > ( ) ; final List < VirtualMachineLease . Range > ranges = lease . portRanges ( ) ; if ( ranges != null && ! ranges . isEmpty ( ) ) { for ( VirtualMachineLease . Range r : ranges ) ports . add ( new VirtualMachineLease . Range ( r . getBeg ( ) , r . getEnd ( ) ) ) ; } final double cpus = lease . cpuCores ( ) ; final double memory = lease . memoryMB ( ) ; final double network = lease . networkMbps ( ) ; final double disk = lease . diskMB ( ) ; final Map < String , Protos . Attribute > attributes = new HashMap < > ( lease . getAttributeMap ( ) ) ; final Map < String , Double > scalarValues = new HashMap < > ( lease . getScalarValues ( ) ) ; return new VirtualMachineLease ( ) { @ Override public String getId ( ) { return hostname ; } @ Override public long getOfferedTime ( ) { return now ; } @ Override public String hostname ( ) { return hostname ; } @ Override public String getVMID ( ) { return hostname ; } @ Override public double cpuCores ( ) { return cpus ; } @ Override public double memoryMB ( ) { return memory ; } @ Override public double networkMbps ( ) { return network ; } @ Override public double diskMB ( ) { return disk ; } @ Override public List < Range > portRanges ( ) { return ports ; } @ Override public Protos . Offer getOffer ( ) { return null ; } @ Override public Map < String , Protos . Attribute > getAttributeMap ( ) { return attributes ; } @ Override public Double getScalarValue ( String name ) { return scalarValues . get ( name ) ; } @ Override public Map < String , Double > getScalarValues ( ) { return scalarValues ; } } ; }


signature:
public class HostAttrValueConstraint { /** * Tests a host to determine whether it has an attribute of the required value for this task request .
 * @ param taskRequest describes the task being evaluated for assignment to the host
 * @ param targetVM describes the host being evaluated as a target for the task
 * @ param taskTrackerState describes the state of tasks already assigned or running on hosts throughout the
 * system
 * @ return a successful Result if the host has an attribute with the required value , or an unsuccessful
 * Result otherwise */
@ Override public Result evaluate ( TaskRequest taskRequest , VirtualMachineCurrentState targetVM , TaskTrackerState taskTrackerState ) { } }

implementation: String targetHostAttrVal = getAttrValue ( targetVM . getCurrAvailableResources ( ) ) ; if ( targetHostAttrVal == null || targetHostAttrVal . isEmpty ( ) ) { return new Result ( false , hostAttributeName + " attribute unavailable on host " + targetVM . getCurrAvailableResources ( ) . hostname ( ) ) ; } String requiredAttrVal = hostAttributeValueGetter . call ( taskRequest . getId ( ) ) ; return targetHostAttrVal . equals ( requiredAttrVal ) ? new Result ( true , "" ) : new Result ( false , "Host attribute " + hostAttributeName + ": required=" + requiredAttrVal + ", got=" + targetHostAttrVal ) ;


signature:
public class SampleQbasedScheduling { /** * This is the main method of this sample framework . It showcases how to use Fenzo queues for scheduling . It creates
 * some number of tasks and launches them into Mesos using the Mesos built - in command executor . The tasks launched
 * are simple sleep commands that sleep for 3 seconds each .
 * @ param args Requires one argument for the location of Mesos master to connect to .
 * @ throws Exception Upon catching any exceptions within the program . */
public static void main ( String [ ] args ) throws Exception { } }

implementation:
if ( args . length != 1 ) { System . err . println ( "Must provide one argument - Mesos master location string" ) ; System . exit ( 1 ) ; } int numTasks = 10 ; final AtomicInteger numTasksCompleted = new AtomicInteger ( ) ; // create Fenzo TaskScheduler object .
final TaskScheduler taskScheduler = new TaskScheduler . Builder ( ) . withFitnessCalculator ( BinPackingFitnessCalculators . cpuMemBinPacker ) . withLeaseOfferExpirySecs ( 1000000 ) . withLeaseRejectAction ( new Action1 < VirtualMachineLease > ( ) { @ Override public void call ( VirtualMachineLease v ) { System . out . println ( "Unexpected to reject lease on " + v . hostname ( ) ) ; } } ) . build ( ) ; // Create a queue from Fenzo provided queue implementations .
final TaskQueue queue = TaskQueues . createTieredQueue ( 2 ) ; // Create our Mesos scheduler callback implementation
AtomicReference < TaskSchedulingService > schedSvcGetter = new AtomicReference < > ( ) ; final MesosScheduler mesosSchedulerCallback = new MesosScheduler ( numTasksCompleted , schedSvcGetter ) ; // create Mesos driver
Protos . FrameworkInfo framework = Protos . FrameworkInfo . newBuilder ( ) . setName ( "Sample Fenzo Framework" ) . setUser ( "" ) . build ( ) ; final MesosSchedulerDriver driver = new MesosSchedulerDriver ( mesosSchedulerCallback , framework , args [ 0 ] ) ; // Build Fenzo task scheduling service using the TaskScheduler and TaskQueue objects created above
final AtomicInteger schedCounter = new AtomicInteger ( ) ; final TaskSchedulingService schedulingService = new TaskSchedulingService . Builder ( ) . withLoopIntervalMillis ( 1000 ) . withMaxDelayMillis ( 1500 ) . withPreSchedulingLoopHook ( new Action0 ( ) { @ Override public void call ( ) { System . out . println ( "Starting scheduling iteration " + schedCounter . incrementAndGet ( ) ) ; } } ) . withTaskQueue ( queue ) . withTaskScheduler ( taskScheduler ) // TaskSchedulingService will call us back when there are task assignments . Handle them by launching
// tasks using MesosDriver
. withSchedulingResultCallback ( new Action1 < SchedulingResult > ( ) { @ Override public void call ( SchedulingResult schedulingResult ) { final List < Exception > exceptions = schedulingResult . getExceptions ( ) ; if ( exceptions != null && ! exceptions . isEmpty ( ) ) { System . out . println ( "Exceptions from scheduling iteration:" ) ; for ( Exception e : exceptions ) e . printStackTrace ( ) ; } else { for ( Map . Entry < String , VMAssignmentResult > e : schedulingResult . getResultMap ( ) . entrySet ( ) ) { List < Protos . OfferID > offers = new ArrayList < Protos . OfferID > ( ) ; for ( VirtualMachineLease l : e . getValue ( ) . getLeasesUsed ( ) ) offers . add ( l . getOffer ( ) . getId ( ) ) ; List < Protos . TaskInfo > taskInfos = new ArrayList < Protos . TaskInfo > ( ) ; for ( TaskAssignmentResult r : e . getValue ( ) . getTasksAssigned ( ) ) { taskInfos . add ( SampleFramework . getTaskInfo ( e . getValue ( ) . getLeasesUsed ( ) . iterator ( ) . next ( ) . getOffer ( ) . getSlaveId ( ) , r . getTaskId ( ) , "sleep 2" ) ) ; tasksToHostnameMap . put ( r . getTaskId ( ) , r . getHostname ( ) ) ; } driver . launchTasks ( offers , taskInfos ) ; } } } } ) . build ( ) ; schedSvcGetter . set ( schedulingService ) ; // set up action in our scheduler callback to send resource offers into our scheduling service
mesosSchedulerCallback . leaseAction = new Action1 < List < Protos . Offer > > ( ) { @ Override public void call ( List < Protos . Offer > offers ) { List < VirtualMachineLease > leases = new ArrayList < > ( ) ; for ( Protos . Offer o : offers ) leases . add ( new VMLeaseObject ( o ) ) ; // Fenzo lease object adapter for Mesos Offer object
schedulingService . addLeases ( leases ) ; } } ; schedulingService . start ( ) ; // start Mesos driver
new Thread ( ) { @ Override public void run ( ) { driver . run ( ) ; } } . start ( ) ; // submit some tasks
for ( int i = 0 ; i < numTasks ; i ++ ) { final QueuableTask task = getTask ( i ) ; allTasks . put ( task . getId ( ) , task ) ; queue . queueTask ( task ) ; } // wait for tasks to complete
while ( numTasksCompleted . get ( ) < numTasks ) { Thread . sleep ( 1000 ) ; System . out . println ( "        #tasks completed: " + numTasksCompleted . get ( ) + " of " + numTasks ) ; } // verify that Fenzo has no tasks in its queue
final CountDownLatch latch = new CountDownLatch ( 1 ) ; schedulingService . requestAllTasks ( new Action1 < Map < TaskQueue . TaskState , Collection < QueuableTask > > > ( ) { @ Override public void call ( Map < TaskQueue . TaskState , Collection < QueuableTask > > taskStateCollectionMap ) { System . out . println ( "Fenzo queue has " + taskStateCollectionMap . size ( ) + " items" ) ; latch . countDown ( ) ; } } ) ; if ( ! latch . await ( 5 , TimeUnit . SECONDS ) ) System . err . println ( "Timeout waiting for listing all tasks in Fenzo queues" ) ; System . out . println ( "ALL DONE" ) ; System . exit ( 0 ) ; } private static QueuableTask getTask ( final int i ) { return new QueuableTask ( ) { @ Override public QAttributes getQAttributes ( ) { return qAttribs ; } @ Override public String getId ( ) { return "Task-" + i ; } @ Override public String taskGroupName ( ) { return "groupA" ; } @ Override public double getCPUs ( ) { return 1 ; } @ Override public double getMemory ( ) { return 100 ; } @ Override public double getNetworkMbps ( ) { return 0 ; } @ Override public double getDisk ( ) { return 0 ; } @ Override public int getPorts ( ) { return 0 ; } @ Override public Map < String , Double > getScalarRequests ( ) { return null ; } @ Override public Map < String , NamedResourceSetRequest > getCustomNamedResources ( ) { return null ; } @ Override public List < ? extends ConstraintEvaluator > getHardConstraints ( ) { return null ; } @ Override public List < ? extends VMTaskFitnessCalculator > getSoftConstraints ( ) { return null ; } @ Override public void setAssignedResources ( AssignedResources assignedResources ) { // no - op , unexpected for this sample
} @ Override public AssignedResources getAssignedResources ( ) { return null ; } } ; }


signature:
public class UniqueHostAttrConstraint { /** * Determines whether a particular target host is appropriate for a particular task request by rejecting any
 * host that has the same value for the unique constraint attribute as another host that is already assigned
 * a co - task of the specified task request .
 * @ param taskRequest describes the task being considered for assignment to the host
 * @ param targetVM describes the host being considered as a target for the task
 * @ param taskTrackerState describes the state of tasks previously assigned or already running throughout
 * the system
 * @ return a successful Result if the target does not have the same value for its unique constraint
 * attribute as another host that has already been assigned a co - task of { @ code taskRequest } , or an
 * unsuccessful Result otherwise */
@ Override public Result evaluate ( TaskRequest taskRequest , VirtualMachineCurrentState targetVM , TaskTrackerState taskTrackerState ) { } }

implementation: Set < String > coTasks = coTasksGetter . call ( taskRequest . getId ( ) ) ; String targetHostAttrVal = AttributeUtilities . getAttrValue ( targetVM . getCurrAvailableResources ( ) , hostAttributeName ) ; if ( targetHostAttrVal == null || targetHostAttrVal . isEmpty ( ) ) { return new Result ( false , hostAttributeName + " attribute unavailable on host " + targetVM . getCurrAvailableResources ( ) . hostname ( ) ) ; } for ( String coTask : coTasks ) { TaskTracker . ActiveTask activeTask = taskTrackerState . getAllRunningTasks ( ) . get ( coTask ) ; if ( activeTask == null ) activeTask = taskTrackerState . getAllCurrentlyAssignedTasks ( ) . get ( coTask ) ; if ( activeTask != null ) { String usedAttrVal = AttributeUtilities . getAttrValue ( activeTask . getTotalLease ( ) , hostAttributeName ) ; if ( usedAttrVal == null || usedAttrVal . isEmpty ( ) ) return new Result ( false , hostAttributeName + " attribute unavailable on host " + activeTask . getTotalLease ( ) . hostname ( ) + " running co-task " + coTask ) ; if ( usedAttrVal . equals ( targetHostAttrVal ) ) { return new Result ( false , hostAttributeName + " " + targetHostAttrVal + " already used for another co-task " + coTask ) ; } } } return new Result ( true , "" ) ;


signature:
public class TriggerOperator { /** * Users of this class must call { @ code initialize ( ) } before they use this class .
 * @ warn exception SchedulerException description missing
 * @ throws SchedulerException */
@ PostConstruct public void initialize ( ) throws SchedulerException { } }

implementation: if ( initialized . compareAndSet ( false , true ) ) { try { this . scheduler . startScheduler ( threadPoolSize ) ; } catch ( org . quartz . SchedulerException se ) { throw new SchedulerException ( "Exception occurred while initializing TriggerOperator" , se ) ; } for ( Iterator < Trigger > iterator = getTriggers ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Trigger trigger = iterator . next ( ) ; if ( ! trigger . isDisabled ( ) && trigger instanceof ScheduledTrigger ) { scheduleTrigger ( ( ScheduledTrigger ) trigger ) ; } } }


signature:
public class TriggerOperator { /** * Registers a { @ code Trigger } with trigger service .
 * @ warn parameter descriptions missing
 * @ warn exception SchedulerException description missing
 * @ param triggerGroup
 * @ param trigger
 * @ throws SchedulerException
 * @ return */
public String registerTrigger ( String triggerGroup , Trigger trigger ) throws SchedulerException { } }

implementation: String triggerId = triggerDao . createTrigger ( triggerGroup , trigger ) ; if ( trigger instanceof ScheduledTrigger ) { scheduleTrigger ( ( ScheduledTrigger ) trigger ) ; } return triggerId ;


signature:
public class TriggerOperator { /** * Disables the { @ code Trigger } . If the { @ code Trigger } is disabled it will < em > not < / em > execute .
 * @ warn exception SchedulerException description missing
 * @ param triggerId the string that uniquely identifies the { @ code Trigger } to be disabled
 * @ throws TriggerNotFoundException if there is no { @ code Trigger } that matches { @ code triggerId }
 * @ throws SchedulerException */
public void disableTrigger ( String triggerId ) throws TriggerNotFoundException , SchedulerException { } }

implementation: Trigger trigger = getTrigger ( triggerId ) ; if ( trigger != null ) { disableTrigger ( trigger ) ; } else { throw new TriggerNotFoundException ( "No trigger found with trigger id: " + triggerId ) ; }


signature:
public class TriggerOperator { /** * Disables the { @ code Trigger } . If the { @ code Trigger } is disabled it will < em > not < / em > execute .
 * @ warn exception SchedulerException description missing
 * @ param trigger the { @ code Trigger } to be disabled
 * @ throws SchedulerException */
public void disableTrigger ( Trigger trigger ) throws SchedulerException { } }

implementation: trigger . setDisabled ( true ) ; triggerDao . updateTrigger ( trigger ) ; if ( trigger instanceof ScheduledTrigger ) { unscheduleTrigger ( ( ScheduledTrigger ) trigger ) ; }


signature:
public class TriggerOperator { /** * Enables the { @ code Trigger }
 * @ warn exception SchedulerException description missing
 * @ param trigger the { @ code Trigger } to be enabled
 * @ throws SchedulerException */
public void enableTrigger ( Trigger trigger ) throws SchedulerException { } }

implementation: trigger . setDisabled ( false ) ; triggerDao . updateTrigger ( trigger ) ; if ( trigger instanceof ScheduledTrigger ) { scheduleTrigger ( ( ScheduledTrigger ) trigger ) ; }


signature:
public class TriggerOperator { /** * Deletes / Removes the { @ code Trigger } . If it is a { @ code ScheduledTrigger } then it is also un - scheduled from
 * scheduler .
 * @ param triggerId the string that uniquely identifies the { @ code Trigger } to be removed
 * @ throws TriggerNotFoundException if there is no { @ code Trigger } that matches { @ code triggerId }
 * @ throws SchedulerException */
public void deleteTrigger ( String triggerGroup , String triggerId ) throws TriggerNotFoundException , SchedulerException { } }

implementation: Trigger trigger = getTrigger ( triggerId ) ; if ( trigger != null ) { deleteTrigger ( triggerGroup , trigger ) ; } else { throw new TriggerNotFoundException ( "No trigger found for trigger id: " + triggerId ) ; }


signature:
public class TriggerOperator { /** * Deletes / Removes the { @ code Trigger } . If it is a { @ code ScheduledTrigger } then it is also un - scheduled from
 * scheduler .
 * @ warn exception SchedulerException description missing
 * @ param trigger the { @ code Trigger } to be removed */
public void deleteTrigger ( String triggerGroup , Trigger trigger ) throws SchedulerException { } }

implementation: triggerDao . deleteTrigger ( triggerGroup , trigger ) ; if ( trigger instanceof ScheduledTrigger ) { unscheduleTrigger ( ( ScheduledTrigger ) trigger ) ; }


signature:
public class TriggerOperator { /** * Schedules the { @ code Trigger } using the scheduler .
 * @ warn exception SchedulerException description missing
 * @ warn parameter scheduledTrigger description missing
 * @ param scheduledTrigger
 * @ throws SchedulerException */
public void scheduleTrigger ( ScheduledTrigger scheduledTrigger ) throws SchedulerException { } }

implementation: if ( ! initialized . get ( ) ) throw new SchedulerException ( "Trigger service is not initialized. initialize() must be called before calling scheduleTrigger() method" ) ; Map jobDataMap = new HashMap ( ) ; jobDataMap . put ( TRIGGER_OPERATOR_KEY , this ) ; jobDataMap . put ( TRIGGER_KEY , scheduledTrigger ) ; try { org . quartz . Trigger quartzTrigger = newTrigger ( ) . withIdentity ( triggerKey ( scheduledTrigger . getId ( ) , Scheduler . DEFAULT_GROUP ) ) . withSchedule ( scheduledTrigger . getScheduleBuilder ( ) ) . usingJobData ( new JobDataMap ( jobDataMap ) ) . startAt ( scheduledTrigger . getStartAt ( ) ) . endAt ( scheduledTrigger . getEndAt ( ) ) . build ( ) ; scheduler . scheduleQuartzJob ( scheduledTrigger . getId ( ) , Scheduler . DEFAULT_GROUP , ScheduledTriggerJob . class , quartzTrigger ) ; scheduledTrigger . setQuartzTrigger ( quartzTrigger ) ; logger . info ( "Successfully scheduled {}" , scheduledTrigger ) ; } catch ( org . quartz . SchedulerException e ) { throw new SchedulerException ( "Exception occurred while scheduling trigger: " + scheduledTrigger , e ) ; }


signature:
public class TriggerOperator { /** * Checks if a { @ code ScheduledTrigger } is scheduled in the scheduler or not .
 * @ warn exception SchedulerException description missing
 * @ warn parameter scheduledTrigger description missing
 * @ param scheduledTrigger
 * @ return
 * @ throws SchedulerException */
public boolean isScheduled ( ScheduledTrigger scheduledTrigger ) throws SchedulerException { } }

implementation: try { return scheduler . isScheduled ( scheduledTrigger . getId ( ) , Scheduler . DEFAULT_GROUP ) ; } catch ( org . quartz . SchedulerException e ) { throw new SchedulerException ( "Exception occurred while checking isScheduled() for: " + scheduledTrigger , e ) ; }


signature:
public class TriggerOperator { /** * Un - schedules the { @ code Trigger } .
 * @ warn exception SchedulerException description missing
 * @ warn parameter scheduledTrigger description missing
 * @ param scheduledTrigger
 * @ throws SchedulerException */
public void unscheduleTrigger ( ScheduledTrigger scheduledTrigger ) throws SchedulerException { } }

implementation: if ( ! initialized . get ( ) ) throw new SchedulerException ( "Trigger service is not initialized. initialize() must be called before calling unscheduleTrigger() method" ) ; try { scheduler . unscheduleQuartzJob ( scheduledTrigger . getId ( ) , Scheduler . DEFAULT_GROUP ) ; scheduledTrigger . setQuartzTrigger ( null ) ; logger . info ( "Successfully unscheduled {}" , scheduledTrigger ) ; } catch ( org . quartz . SchedulerException e ) { throw new SchedulerException ( "Exception occurred while unscheduling trigger: " + scheduledTrigger , e ) ; }


signature:
public class TriggerOperator { /** * Executes the { @ code Trigger } .
 * @ param triggerId the string that uniquely identifies the { @ code Trigger } to be executed
 * @ throws TriggerNotFoundException if there is no { @ code Trigger } that matches { @ code triggerId }
 * @ throws Exception if an exception occurred during the execution of the { @ code Trigger } */
public void execute ( String triggerId ) throws Exception { } }

implementation: Trigger trigger = getTrigger ( triggerId ) ; if ( trigger != null ) { execute ( trigger ) ; } else { throw new TriggerNotFoundException ( String . format ( "No trigger found with id: %s" , triggerId ) ) ; }


signature:
public class TriggerOperator { /** * Executes the { @ code Trigger } .
 * @ param trigger the { @ code Trigger } to be executed
 * @ throws Exception if an exception occurred during the execution of the { @ code Trigger } */
public void execute ( Trigger trigger ) throws Exception { } }

implementation: if ( trigger . isDisabled ( ) ) return ; try { ( ( Action1 ) trigger . getAction ( ) . newInstance ( ) ) . call ( trigger . getData ( ) ) ; } catch ( Exception e ) { throw new Exception ( String . format ( "Exception occurred while executing trigger '%s'" , trigger ) , e ) ; }


signature:
public class TaskScheduler { /** * Set the autoscale call back action . The callback you pass to this method receives an indication when an
 * autoscale action is to be performed , telling it which autoscale rule prompted the action and whether the
 * action is to scale up or scale down the autoscale group . The callback then initiates the appropriate
 * scaling actions .
 * @ param callback the callback to invoke for autoscale actions
 * @ throws IllegalStateException if no autoscaler was established
 * @ see < a href = " https : / / github . com / Netflix / Fenzo / wiki / Autoscaling " > Autoscaling < / a > */
public void setAutoscalerCallback ( Action1 < AutoScaleAction > callback ) throws IllegalStateException { } }

implementation: checkIfShutdown ( ) ; if ( autoScaler == null ) { throw new IllegalStateException ( "No autoScaler setup" ) ; } autoScaler . setCallback ( callback ) ;


signature:
public class TaskScheduler { /** * / * package */
void setTaskToClusterAutoScalerMapGetter ( Func1 < QueuableTask , List < String > > getter ) { } }

implementation: if ( autoScaler != null ) { autoScaler . setTaskToClustersGetter ( getter ) ; }