idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
40,500
static String getAppVersion ( Context context ) { String appVersion = "" ; if ( context != null ) { try { final PackageInfo packageInfo = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) ; appVersion = packageInfo . versionName ; } catch ( Exception e ) { PrefHelper . LogException ( "Error obtaining AppVersion" , e ) ; } } return ( TextUtils . isEmpty ( appVersion ) ? BLANK : appVersion ) ; }
Get the App Version Name of the current application that the SDK is integrated with .
40,501
static long getFirstInstallTime ( Context context ) { long firstTime = 0L ; if ( context != null ) { try { final PackageInfo packageInfo = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) ; firstTime = packageInfo . firstInstallTime ; } catch ( Exception e ) { PrefHelper . LogException ( "Error obtaining FirstInstallTime" , e ) ; } } return firstTime ; }
Get the time at which the app was first installed in milliseconds .
40,502
static boolean isPackageInstalled ( Context context ) { boolean isInstalled = false ; if ( context != null ) { try { final PackageManager packageManager = context . getPackageManager ( ) ; Intent intent = context . getPackageManager ( ) . getLaunchIntentForPackage ( context . getPackageName ( ) ) ; if ( intent == null ) { return false ; } List < ResolveInfo > list = packageManager . queryIntentActivities ( intent , PackageManager . MATCH_DEFAULT_ONLY ) ; isInstalled = ( list != null && list . size ( ) > 0 ) ; } catch ( Exception e ) { PrefHelper . LogException ( "Error obtaining PackageInfo" , e ) ; } } return isInstalled ; }
Determine if the package is installed .
40,503
static long getLastUpdateTime ( Context context ) { long lastTime = 0L ; if ( context != null ) { try { final PackageInfo packageInfo = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) ; lastTime = packageInfo . lastUpdateTime ; } catch ( Exception e ) { PrefHelper . LogException ( "Error obtaining LastUpdateTime" , e ) ; } } return lastTime ; }
Get the time at which the app was last updated in milliseconds .
40,504
boolean prefetchGAdsParams ( Context context , GAdsParamsFetchEvents callback ) { boolean isPrefetchStarted = false ; if ( TextUtils . isEmpty ( GAIDString_ ) ) { isPrefetchStarted = true ; new GAdsPrefetchTask ( context , callback ) . executeTask ( ) ; } return isPrefetchStarted ; }
Method to prefetch the GAID and LAT values .
40,505
static String getLocalIPAddress ( ) { String ipAddress = "" ; try { List < NetworkInterface > netInterfaces = Collections . list ( NetworkInterface . getNetworkInterfaces ( ) ) ; for ( NetworkInterface netInterface : netInterfaces ) { List < InetAddress > addresses = Collections . list ( netInterface . getInetAddresses ( ) ) ; for ( InetAddress address : addresses ) { if ( ! address . isLoopbackAddress ( ) ) { String ip = address . getHostAddress ( ) ; boolean isIPv4 = ip . indexOf ( ':' ) < 0 ; if ( isIPv4 ) { ipAddress = ip ; break ; } } } } } catch ( Throwable ignore ) { } return ipAddress ; }
Get IP address from first non local net Interface
40,506
public Dialog shareLink ( Branch . ShareLinkBuilder builder ) { builder_ = builder ; context_ = builder . getActivity ( ) ; callback_ = builder . getCallback ( ) ; channelPropertiesCallback_ = builder . getChannelPropertiesCallback ( ) ; shareLinkIntent_ = new Intent ( Intent . ACTION_SEND ) ; shareLinkIntent_ . setType ( "text/plain" ) ; shareDialogThemeID_ = builder . getStyleResourceID ( ) ; includeInShareSheet = builder . getIncludedInShareSheet ( ) ; excludeFromShareSheet = builder . getExcludedFromShareSheet ( ) ; iconSize_ = builder . getIconSize ( ) ; try { createShareDialog ( builder . getPreferredOptions ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; if ( callback_ != null ) { callback_ . onLinkShareResponse ( null , null , new BranchError ( "Trouble sharing link" , BranchError . ERR_BRANCH_NO_SHARE_OPTION ) ) ; } else { PrefHelper . Debug ( "Unable create share options. Couldn't find applications on device to share the link." ) ; } } return shareDlg_ ; }
Creates an application selector and shares a link on user selecting the application .
40,507
public void cancelShareLinkDialog ( boolean animateClose ) { if ( shareDlg_ != null && shareDlg_ . isShowing ( ) ) { if ( animateClose ) { shareDlg_ . cancel ( ) ; } else { shareDlg_ . dismiss ( ) ; } } }
Dismiss the share dialog if showing . Should be called on activity stopping .
40,508
private void invokeSharingClient ( final ResolveInfo selectedResolveInfo ) { isShareInProgress_ = true ; final String channelName = selectedResolveInfo . loadLabel ( context_ . getPackageManager ( ) ) . toString ( ) ; BranchShortLinkBuilder shortLinkBuilder = builder_ . getShortLinkBuilder ( ) ; shortLinkBuilder . generateShortUrlInternal ( new Branch . BranchLinkCreateListener ( ) { public void onLinkCreate ( String url , BranchError error ) { if ( error == null ) { shareWithClient ( selectedResolveInfo , url , channelName ) ; } else { String defaultUrl = builder_ . getDefaultURL ( ) ; if ( defaultUrl != null && defaultUrl . trim ( ) . length ( ) > 0 ) { shareWithClient ( selectedResolveInfo , defaultUrl , channelName ) ; } else { if ( callback_ != null ) { callback_ . onLinkShareResponse ( url , channelName , error ) ; } else { PrefHelper . Debug ( "Unable to share link " + error . getMessage ( ) ) ; } if ( error . getErrorCode ( ) == BranchError . ERR_BRANCH_NO_CONNECTIVITY || error . getErrorCode ( ) == BranchError . ERR_BRANCH_TRACKING_DISABLED ) { shareWithClient ( selectedResolveInfo , url , channelName ) ; } else { cancelShareLinkDialog ( false ) ; isShareInProgress_ = false ; } } } } } , true ) ; }
Invokes a sharing client with a link created by the given json objects .
40,509
@ SuppressWarnings ( "deprecation" ) @ SuppressLint ( "NewApi" ) private void addLinkToClipBoard ( String url , String label ) { int sdk = android . os . Build . VERSION . SDK_INT ; if ( sdk < android . os . Build . VERSION_CODES . HONEYCOMB ) { android . text . ClipboardManager clipboard = ( android . text . ClipboardManager ) context_ . getSystemService ( Context . CLIPBOARD_SERVICE ) ; clipboard . setText ( url ) ; } else { android . content . ClipboardManager clipboard = ( android . content . ClipboardManager ) context_ . getSystemService ( Context . CLIPBOARD_SERVICE ) ; android . content . ClipData clip = android . content . ClipData . newPlainText ( label , url ) ; clipboard . setPrimaryClip ( clip ) ; } Toast . makeText ( context_ , builder_ . getUrlCopiedMessage ( ) , Toast . LENGTH_SHORT ) . show ( ) ; }
Adds a given link to the clip board .
40,510
void setInstallOrOpenCallback ( Branch . BranchReferralInitListener callback ) { synchronized ( reqQueueLockObject ) { for ( ServerRequest req : queue ) { if ( req != null ) { if ( req instanceof ServerRequestRegisterInstall ) { ( ( ServerRequestRegisterInstall ) req ) . setInitFinishedCallback ( callback ) ; } else if ( req instanceof ServerRequestRegisterOpen ) { ( ( ServerRequestRegisterOpen ) req ) . setInitFinishedCallback ( callback ) ; } } } } }
Sets the given callback to the existing open or install request in the queue
40,511
void setStrongMatchWaitLock ( ) { synchronized ( reqQueueLockObject ) { for ( ServerRequest req : queue ) { if ( req != null ) { if ( req instanceof ServerRequestInitSession ) { req . addProcessWaitLock ( ServerRequest . PROCESS_WAIT_LOCK . STRONG_MATCH_PENDING_WAIT_LOCK ) ; } } } } }
Sets the strong match wait for any init session request in the queue
40,512
public String getFailReason ( ) { String causeMsg = "" ; try { JSONObject postObj = getObject ( ) ; if ( postObj != null && postObj . has ( "error" ) && postObj . getJSONObject ( "error" ) . has ( "message" ) ) { causeMsg = postObj . getJSONObject ( "error" ) . getString ( "message" ) ; if ( causeMsg != null && causeMsg . trim ( ) . length ( ) > 0 ) { causeMsg = causeMsg + "." ; } } } catch ( Exception ignore ) { } return causeMsg ; }
Get the reason for failure if there any
40,513
static JSONObject addSource ( JSONObject params ) { if ( params == null ) { params = new JSONObject ( ) ; } try { params . put ( "source" , "android" ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return params ; }
Convert the given JSONObject to string and adds source value as
40,514
public JSONObject getLinkDataJsonObject ( ) { JSONObject linkDataJson = new JSONObject ( ) ; try { if ( ! TextUtils . isEmpty ( channel ) ) { linkDataJson . put ( "~" + Defines . LinkParam . Channel . getKey ( ) , channel ) ; } if ( ! TextUtils . isEmpty ( alias ) ) { linkDataJson . put ( "~" + Defines . LinkParam . Alias . getKey ( ) , alias ) ; } if ( ! TextUtils . isEmpty ( feature ) ) { linkDataJson . put ( "~" + Defines . LinkParam . Feature . getKey ( ) , feature ) ; } if ( ! TextUtils . isEmpty ( stage ) ) { linkDataJson . put ( "~" + Defines . LinkParam . Stage . getKey ( ) , stage ) ; } if ( ! TextUtils . isEmpty ( campaign ) ) { linkDataJson . put ( "~" + Defines . LinkParam . Campaign . getKey ( ) , campaign ) ; } if ( has ( Defines . LinkParam . Tags . getKey ( ) ) ) { linkDataJson . put ( Defines . LinkParam . Tags . getKey ( ) , getJSONArray ( Defines . LinkParam . Tags . getKey ( ) ) ) ; } linkDataJson . put ( "~" + Defines . LinkParam . Type . getKey ( ) , type ) ; linkDataJson . put ( "~" + Defines . LinkParam . Duration . getKey ( ) , duration ) ; } catch ( JSONException ignore ) { } return linkDataJson ; }
Creates the Json object with link params and link properties .
40,515
public BranchEvent setAdType ( AdType adType ) { return addStandardProperty ( Defines . Jsonkey . AdType . getKey ( ) , adType . getName ( ) ) ; }
Set the Ad Type associated with the event .
40,516
public BranchEvent setTransactionID ( String transactionID ) { return addStandardProperty ( Defines . Jsonkey . TransactionID . getKey ( ) , transactionID ) ; }
Set the transaction id associated with this event if there in any
40,517
public BranchEvent setCurrency ( CurrencyType currency ) { return addStandardProperty ( Defines . Jsonkey . Currency . getKey ( ) , currency . toString ( ) ) ; }
Set the currency related with this transaction event
40,518
public BranchEvent setCoupon ( String coupon ) { return addStandardProperty ( Defines . Jsonkey . Coupon . getKey ( ) , coupon ) ; }
Set any coupons associated with this transaction event
40,519
public BranchEvent setAffiliation ( String affiliation ) { return addStandardProperty ( Defines . Jsonkey . Affiliation . getKey ( ) , affiliation ) ; }
Set any affiliation for this transaction event
40,520
public BranchEvent setDescription ( String description ) { return addStandardProperty ( Defines . Jsonkey . Description . getKey ( ) , description ) ; }
Set description for this transaction event
40,521
public BranchEvent setSearchQuery ( String searchQuery ) { return addStandardProperty ( Defines . Jsonkey . SearchQuery . getKey ( ) , searchQuery ) ; }
Set any search query associated with the event
40,522
public BranchEvent addCustomDataProperty ( String propertyName , String propertyValue ) { try { this . customProperties . put ( propertyName , propertyValue ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return this ; }
Adds a custom data property associated with this Branch Event
40,523
public boolean logEvent ( Context context ) { boolean isReqQueued = false ; String reqPath = isStandardEvent ? Defines . RequestPath . TrackStandardEvent . getPath ( ) : Defines . RequestPath . TrackCustomEvent . getPath ( ) ; if ( Branch . getInstance ( ) != null ) { Branch . getInstance ( ) . handleNewRequest ( new ServerRequestLogEvent ( context , reqPath ) ) ; isReqQueued = true ; } return isReqQueued ; }
Logs this BranchEvent to Branch for tracking and analytics
40,524
public boolean setBranchKey ( String key ) { Branch_Key = key ; String currentBranchKey = getString ( KEY_BRANCH_KEY ) ; if ( key == null || currentBranchKey == null || ! currentBranchKey . equals ( key ) ) { clearPrefOnBranchKeyChange ( ) ; setString ( KEY_BRANCH_KEY , key ) ; return true ; } return false ; }
Set the given Branch Key to preference . Clears the preference data if the key is a new key .
40,525
private ArrayList < String > getBuckets ( ) { String bucketList = getString ( KEY_BUCKETS ) ; if ( bucketList . equals ( NO_STRING_VALUE ) ) { return new ArrayList < > ( ) ; } else { return deserializeString ( bucketList ) ; } }
REWARD TRACKING CALLS
40,526
private ArrayList < String > getActions ( ) { String actionList = getString ( KEY_ACTIONS ) ; if ( actionList . equals ( NO_STRING_VALUE ) ) { return new ArrayList < > ( ) ; } else { return deserializeString ( actionList ) ; } }
EVENT REFERRAL INSTALL CALLS
40,527
private String serializeArrayList ( ArrayList < String > strings ) { String retString = "" ; for ( String value : strings ) { retString = retString + value + "," ; } retString = retString . substring ( 0 , retString . length ( ) - 1 ) ; return retString ; }
ALL GENERIC CALLS
40,528
public void onUrlAvailable ( String url ) { if ( callback_ != null ) { callback_ . onLinkCreate ( url , null ) ; } updateShareEventToFabric ( url ) ; }
Calls the callback with the URL . This should be called on finding an existing url up on trying to create a URL asynchronously
40,529
public JSONObject convertToJson ( ) { JSONObject buoJsonModel = new JSONObject ( ) ; try { JSONObject metadataJsonObject = metadata_ . convertToJson ( ) ; Iterator < String > keys = metadataJsonObject . keys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; buoJsonModel . put ( key , metadataJsonObject . get ( key ) ) ; } if ( ! TextUtils . isEmpty ( title_ ) ) { buoJsonModel . put ( Defines . Jsonkey . ContentTitle . getKey ( ) , title_ ) ; } if ( ! TextUtils . isEmpty ( canonicalIdentifier_ ) ) { buoJsonModel . put ( Defines . Jsonkey . CanonicalIdentifier . getKey ( ) , canonicalIdentifier_ ) ; } if ( ! TextUtils . isEmpty ( canonicalUrl_ ) ) { buoJsonModel . put ( Defines . Jsonkey . CanonicalUrl . getKey ( ) , canonicalUrl_ ) ; } if ( keywords_ . size ( ) > 0 ) { JSONArray keyWordJsonArray = new JSONArray ( ) ; for ( String keyword : keywords_ ) { keyWordJsonArray . put ( keyword ) ; } buoJsonModel . put ( Defines . Jsonkey . ContentKeyWords . getKey ( ) , keyWordJsonArray ) ; } if ( ! TextUtils . isEmpty ( description_ ) ) { buoJsonModel . put ( Defines . Jsonkey . ContentDesc . getKey ( ) , description_ ) ; } if ( ! TextUtils . isEmpty ( imageUrl_ ) ) { buoJsonModel . put ( Defines . Jsonkey . ContentImgUrl . getKey ( ) , imageUrl_ ) ; } if ( expirationInMilliSec_ > 0 ) { buoJsonModel . put ( Defines . Jsonkey . ContentExpiryTime . getKey ( ) , expirationInMilliSec_ ) ; } buoJsonModel . put ( Defines . Jsonkey . PublicallyIndexable . getKey ( ) , isPublicallyIndexable ( ) ) ; buoJsonModel . put ( Defines . Jsonkey . LocallyIndexable . getKey ( ) , isLocallyIndexable ( ) ) ; buoJsonModel . put ( Defines . Jsonkey . CreationTimestamp . getKey ( ) , creationTimeStamp_ ) ; } catch ( JSONException ignore ) { } return buoJsonModel ; }
Convert the BUO to corresponding Json representation
40,530
static void shutDown ( ) { ServerRequestQueue . shutDown ( ) ; PrefHelper . shutDown ( ) ; BranchUtil . shutDown ( ) ; DeviceInfo . shutDown ( ) ; if ( branchReferral_ != null ) { branchReferral_ . context_ = null ; branchReferral_ . currentActivityReference_ = null ; } branchReferral_ = null ; customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS . USE_DEFAULT ; bypassCurrentActivityIntentState_ = false ; disableInstantDeepLinking = false ; isActivityLifeCycleCallbackRegistered_ = false ; isAutoSessionMode_ = false ; isForcedSession_ = false ; isSimulatingInstalls_ = false ; checkInstallReferrer_ = true ; }
For Unit Testing we need to reset the Branch state
40,531
String getSessionReferredLink ( ) { String link = prefHelper_ . getExternalIntentUri ( ) ; return ( link . equals ( PrefHelper . NO_STRING_VALUE ) ? null : link ) ; }
Package Private .
40,532
private JSONObject appendDebugParams ( JSONObject originalParams ) { try { if ( originalParams != null && deeplinkDebugParams_ != null ) { if ( deeplinkDebugParams_ . length ( ) > 0 ) { PrefHelper . Debug ( "You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link" ) ; } Iterator < String > keys = deeplinkDebugParams_ . keys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; originalParams . put ( key , deeplinkDebugParams_ . get ( key ) ) ; } } } catch ( Exception ignore ) { } return originalParams ; }
Append the deep link debug params to the original params
40,533
private void registerAppInit ( BranchReferralInitListener callback , ServerRequest . PROCESS_WAIT_LOCK lock ) { ServerRequest request = getInstallOrOpenRequest ( callback ) ; request . addProcessWaitLock ( lock ) ; if ( isGAParamsFetchInProgress_ ) { request . addProcessWaitLock ( ServerRequest . PROCESS_WAIT_LOCK . GAID_FETCH_WAIT_LOCK ) ; } if ( intentState_ != INTENT_STATE . READY && ! isForceSessionEnabled ( ) ) { request . addProcessWaitLock ( ServerRequest . PROCESS_WAIT_LOCK . INTENT_PENDING_WAIT_LOCK ) ; } if ( checkInstallReferrer_ && request instanceof ServerRequestRegisterInstall && ! InstallListener . unReportedReferrerAvailable ) { request . addProcessWaitLock ( ServerRequest . PROCESS_WAIT_LOCK . INSTALL_REFERRER_FETCH_WAIT_LOCK ) ; InstallListener . captureInstallReferrer ( context_ , playStoreReferrerFetchTime , this ) ; } registerInstallOrOpen ( request , callback ) ; }
Registers app init with params filtered from the intent . This will wait on the wait locks to complete any pending operations
40,534
protected void addGetParam ( String paramKey , String paramValue ) { try { params_ . put ( paramKey , paramValue ) ; } catch ( JSONException ignore ) { } }
Adds a param and its value to the get request
40,535
private void updateGAdsParams ( ) { BRANCH_API_VERSION version = getBranchRemoteAPIVersion ( ) ; int LATVal = DeviceInfo . getInstance ( ) . getSystemObserver ( ) . getLATVal ( ) ; String gaid = DeviceInfo . getInstance ( ) . getSystemObserver ( ) . getGAID ( ) ; if ( ! TextUtils . isEmpty ( gaid ) ) { try { if ( version == BRANCH_API_VERSION . V2 ) { JSONObject userDataObj = params_ . optJSONObject ( Defines . Jsonkey . UserData . getKey ( ) ) ; if ( userDataObj != null ) { userDataObj . put ( Defines . Jsonkey . AAID . getKey ( ) , gaid ) ; userDataObj . put ( Defines . Jsonkey . LimitedAdTracking . getKey ( ) , LATVal ) ; userDataObj . remove ( Defines . Jsonkey . UnidentifiedDevice . getKey ( ) ) ; } } else { params_ . put ( Defines . Jsonkey . GoogleAdvertisingID . getKey ( ) , gaid ) ; params_ . put ( Defines . Jsonkey . LATVal . getKey ( ) , LATVal ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; } } else { if ( version == BRANCH_API_VERSION . V2 ) { try { if ( version == BRANCH_API_VERSION . V2 ) { JSONObject userDataObj = params_ . optJSONObject ( Defines . Jsonkey . UserData . getKey ( ) ) ; if ( userDataObj != null ) { if ( ! userDataObj . has ( Defines . Jsonkey . AndroidID . getKey ( ) ) ) { userDataObj . put ( Defines . Jsonkey . UnidentifiedDevice . getKey ( ) , true ) ; } } } } catch ( JSONException ignore ) { } } } }
Updates the google ads parameters . This should be called only from a background thread since it involves GADS method invocation using reflection
40,536
private long [ ] getUsersListMembers ( String [ ] tUserlists ) { logger . debug ( "Fetching user id of given lists" ) ; List < Long > listUserIdToFollow = new ArrayList < Long > ( ) ; Configuration cb = buildTwitterConfiguration ( ) ; Twitter twitterImpl = new TwitterFactory ( cb ) . getInstance ( ) ; for ( String listId : tUserlists ) { logger . debug ( "Adding users of list {} " , listId ) ; String [ ] splitListId = listId . split ( "/" ) ; try { long cursor = - 1 ; PagableResponseList < User > itUserListMembers ; do { itUserListMembers = twitterImpl . getUserListMembers ( splitListId [ 0 ] , splitListId [ 1 ] , cursor ) ; for ( User member : itUserListMembers ) { long userId = member . getId ( ) ; listUserIdToFollow . add ( userId ) ; } } while ( ( cursor = itUserListMembers . getNextCursor ( ) ) != 0 ) ; } catch ( TwitterException te ) { logger . error ( "Failed to get list members for : {}" , listId , te ) ; } } long ret [ ] = new long [ listUserIdToFollow . size ( ) ] ; int pos = 0 ; for ( Long userId : listUserIdToFollow ) { ret [ pos ] = userId ; pos ++ ; } return ret ; }
Get users id of each list to stream them .
40,537
private Configuration buildTwitterConfiguration ( ) { logger . debug ( "creating twitter configuration" ) ; ConfigurationBuilder cb = new ConfigurationBuilder ( ) ; cb . setOAuthConsumerKey ( oauthConsumerKey ) . setOAuthConsumerSecret ( oauthConsumerSecret ) . setOAuthAccessToken ( oauthAccessToken ) . setOAuthAccessTokenSecret ( oauthAccessTokenSecret ) ; if ( proxyHost != null ) cb . setHttpProxyHost ( proxyHost ) ; if ( proxyPort != null ) cb . setHttpProxyPort ( Integer . parseInt ( proxyPort ) ) ; if ( proxyUser != null ) cb . setHttpProxyUser ( proxyUser ) ; if ( proxyPassword != null ) cb . setHttpProxyPassword ( proxyPassword ) ; if ( raw ) cb . setJSONStoreEnabled ( true ) ; logger . debug ( "twitter configuration created" ) ; return cb . build ( ) ; }
Build configuration object with credentials and proxy settings
40,538
private void startTwitterStream ( ) { logger . info ( "starting {} twitter stream" , streamType ) ; if ( stream == null ) { logger . debug ( "creating twitter stream" ) ; stream = new TwitterStreamFactory ( buildTwitterConfiguration ( ) ) . getInstance ( ) ; if ( streamType . equals ( "user" ) ) { stream . addListener ( new UserStreamHandler ( ) ) ; } else { stream . addListener ( new StatusHandler ( ) ) ; } logger . debug ( "twitter stream created" ) ; } if ( riverStatus != RiverStatus . STOPPED && riverStatus != RiverStatus . STOPPING ) { if ( streamType . equals ( "filter" ) || filterQuery != null ) { stream . filter ( filterQuery ) ; } else if ( streamType . equals ( "firehose" ) ) { stream . firehose ( 0 ) ; } else if ( streamType . equals ( "user" ) ) { stream . user ( ) ; } else { stream . sample ( ) ; } } logger . debug ( "{} twitter stream started!" , streamType ) ; }
Start twitter stream
40,539
public void insertArchive ( JarScriptArchive jarScriptArchive ) throws IOException { Objects . requireNonNull ( jarScriptArchive , "jarScriptArchive" ) ; ScriptModuleSpec moduleSpec = jarScriptArchive . getModuleSpec ( ) ; ModuleId moduleId = moduleSpec . getModuleId ( ) ; Path jarFilePath ; try { jarFilePath = Paths . get ( jarScriptArchive . getRootUrl ( ) . toURI ( ) ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } int shardNum = calculateShardNum ( moduleId ) ; byte [ ] jarBytes = Files . readAllBytes ( jarFilePath ) ; byte [ ] hash = calculateHash ( jarBytes ) ; Map < String , Object > columns = new HashMap < String , Object > ( ) ; columns . put ( Columns . module_id . name ( ) , moduleId . toString ( ) ) ; columns . put ( Columns . module_name . name ( ) , moduleId . getName ( ) ) ; columns . put ( Columns . module_version . name ( ) , moduleId . getVersion ( ) ) ; columns . put ( Columns . shard_num . name ( ) , shardNum ) ; columns . put ( Columns . last_update . name ( ) , jarScriptArchive . getCreateTime ( ) ) ; columns . put ( Columns . archive_content_hash . name ( ) , hash ) ; columns . put ( Columns . archive_content . name ( ) , jarBytes ) ; String serialized = getConfig ( ) . getModuleSpecSerializer ( ) . serialize ( moduleSpec ) ; columns . put ( Columns . module_spec . name ( ) , serialized ) ; try { cassandra . upsert ( moduleId . toString ( ) , columns ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } }
insert a Jar into the script archive
40,540
public void deleteArchive ( ModuleId moduleId ) throws IOException { Objects . requireNonNull ( moduleId , "moduleId" ) ; cassandra . deleteRow ( moduleId . toString ( ) ) ; }
Delete an archive by ID
40,541
protected Iterable < Row < String , String > > getRows ( EnumSet < ? > columns ) throws Exception { int shardCount = config . getShardCount ( ) ; List < Future < Rows < String , String > > > futures = new ArrayList < Future < Rows < String , String > > > ( ) ; for ( int i = 0 ; i < shardCount ; i ++ ) { futures . add ( cassandra . selectAsync ( generateSelectByShardCql ( columns , i ) ) ) ; } List < Row < String , String > > rows = new LinkedList < Row < String , String > > ( ) ; for ( Future < Rows < String , String > > f : futures ) { Rows < String , String > shardRows = f . get ( ) ; Iterables . addAll ( rows , shardRows ) ; } return rows ; }
Get all of the rows in in the table . Attempts to reduce the load on cassandra by splitting up the query into smaller sub - queries
40,542
public static ScriptCompilerPluginSpec getCompilerSpec ( ) { Path groovyRuntimePath = ClassPathUtils . findRootPathForResource ( "META-INF/groovy-release-info.properties" , Groovy2PluginUtils . class . getClassLoader ( ) ) ; if ( groovyRuntimePath == null ) { throw new IllegalStateException ( "couldn't find groovy-all.n.n.n.jar in the classpath." ) ; } String resourceName = ClassPathUtils . classNameToResourceName ( Groovy2CompilerPlugin . class . getName ( ) ) ; Path nicobarGroovyPluginPath = ClassPathUtils . findRootPathForResource ( resourceName , Groovy2PluginUtils . class . getClassLoader ( ) ) ; if ( nicobarGroovyPluginPath == null ) { throw new IllegalStateException ( "couldn't find nicobar-groovy2 in the classpath." ) ; } ScriptCompilerPluginSpec compilerSpec = new ScriptCompilerPluginSpec . Builder ( Groovy2CompilerPlugin . PLUGIN_ID ) . withPluginClassName ( Groovy2CompilerPlugin . class . getName ( ) ) . addRuntimeResource ( groovyRuntimePath ) . addRuntimeResource ( nicobarGroovyPluginPath ) . build ( ) ; return compilerSpec ; }
Helper method to orchestrate commonly required setup of nicobar - groovy2 and return a groovy2 compiler spec .
40,543
protected Path getModuleJarPath ( ModuleId moduleId ) { Path moduleJarPath = rootDir . resolve ( moduleId + ".jar" ) ; return moduleJarPath ; }
Translated a module id to an absolute path of the module jar
40,544
protected ModuleSpec createModuleSpec ( ScriptArchive archive , ModuleIdentifier moduleId , Map < ModuleId , ModuleIdentifier > moduleIdMap , Path moduleCompilationRoot ) throws ModuleLoadException { ScriptModuleSpec archiveSpec = archive . getModuleSpec ( ) ; ModuleSpec . Builder moduleSpecBuilder = ModuleSpec . build ( moduleId ) ; JBossModuleUtils . populateModuleSpecWithResources ( moduleSpecBuilder , archive ) ; JBossModuleUtils . populateModuleSpecWithCoreDependencies ( moduleSpecBuilder , archive ) ; JBossModuleUtils . populateModuleSpecWithAppImports ( moduleSpecBuilder , appClassLoader , archiveSpec . getAppImportFilterPaths ( ) == null ? appPackagePaths : archiveSpec . getAppImportFilterPaths ( ) ) ; JBossModuleUtils . populateModuleSpecWithCompilationRoot ( moduleSpecBuilder , moduleCompilationRoot ) ; for ( ModuleId dependencyModuleId : archiveSpec . getModuleDependencies ( ) ) { ScriptModule dependencyModule = getScriptModule ( dependencyModuleId ) ; Set < String > exportPaths = dependencyModule . getSourceArchive ( ) . getModuleSpec ( ) . getModuleExportFilterPaths ( ) ; JBossModuleUtils . populateModuleSpecWithModuleDependency ( moduleSpecBuilder , archiveSpec . getModuleImportFilterPaths ( ) , exportPaths , moduleIdMap . get ( dependencyModuleId ) ) ; } return moduleSpecBuilder . create ( ) ; }
Create a JBoss module spec for an about to be created script module .
40,545
protected void compileModule ( Module module , Path moduleCompilationRoot ) throws ScriptCompilationException , IOException { ModuleClassLoader moduleClassLoader = module . getClassLoader ( ) ; if ( moduleClassLoader instanceof JBossModuleClassLoader ) { JBossModuleClassLoader jBossModuleClassLoader = ( JBossModuleClassLoader ) moduleClassLoader ; ScriptArchive scriptArchive = jBossModuleClassLoader . getScriptArchive ( ) ; List < ScriptArchiveCompiler > candidateCompilers = findCompilers ( scriptArchive ) ; if ( candidateCompilers . size ( ) == 0 ) { throw new ScriptCompilationException ( "Could not find a suitable compiler for this archive." ) ; } for ( ScriptArchiveCompiler compiler : candidateCompilers ) { compiler . compile ( scriptArchive , jBossModuleClassLoader , moduleCompilationRoot ) ; } } }
Compiles and links the scripts within the module by locating the correct compiler and delegating the compilation . the classes will be loaded into the module s classloader upon completion .
40,546
public synchronized void addCompilerPlugin ( ScriptCompilerPluginSpec pluginSpec ) throws ModuleLoadException { Objects . requireNonNull ( pluginSpec , "pluginSpec" ) ; ModuleIdentifier pluginModuleId = JBossModuleUtils . getPluginModuleId ( pluginSpec ) ; ModuleSpec . Builder moduleSpecBuilder = ModuleSpec . build ( pluginModuleId ) ; Map < ModuleId , ModuleIdentifier > latestRevisionIds = jbossModuleLoader . getLatestRevisionIds ( ) ; JBossModuleUtils . populateCompilerModuleSpec ( moduleSpecBuilder , pluginSpec , latestRevisionIds ) ; JBossModuleUtils . populateModuleSpecWithAppImports ( moduleSpecBuilder , appClassLoader , appPackagePaths ) ; ModuleSpec moduleSpec = moduleSpecBuilder . create ( ) ; String providerClassName = pluginSpec . getPluginClassName ( ) ; if ( providerClassName != null ) { jbossModuleLoader . addModuleSpec ( moduleSpec ) ; Module pluginModule = jbossModuleLoader . loadModule ( pluginModuleId ) ; ModuleClassLoader pluginClassLoader = pluginModule . getClassLoader ( ) ; Class < ? > compilerProviderClass ; try { compilerProviderClass = pluginClassLoader . loadClass ( providerClassName ) ; ScriptCompilerPlugin pluginBootstrap = ( ScriptCompilerPlugin ) compilerProviderClass . newInstance ( ) ; Set < ? extends ScriptArchiveCompiler > pluginCompilers = pluginBootstrap . getCompilers ( pluginSpec . getCompilerParams ( ) ) ; compilers . addAll ( pluginCompilers ) ; } catch ( Exception e ) { throw new ModuleLoadException ( e ) ; } compilerClassLoaders . put ( pluginSpec . getPluginId ( ) , pluginModule . getClassLoader ( ) ) ; } }
Add a language plugin to this module
40,547
public synchronized void removeScriptModule ( ModuleId scriptModuleId ) { jbossModuleLoader . unloadAllModuleRevision ( scriptModuleId . toString ( ) ) ; ScriptModule oldScriptModule = loadedScriptModules . remove ( scriptModuleId ) ; if ( oldScriptModule != null ) { notifyModuleUpdate ( null , oldScriptModule ) ; } }
Remove a module from being served by this instance . Note that any instances of the module cached outside of this module loader will remain un - effected and will continue to operate .
40,548
public void addListeners ( Set < ScriptModuleListener > listeners ) { Objects . requireNonNull ( listeners ) ; this . listeners . addAll ( listeners ) ; }
Add listeners to this module loader . Listeners will only be notified of events that occurred after they were added .
40,549
protected List < ScriptArchiveCompiler > findCompilers ( ScriptArchive archive ) { List < ScriptArchiveCompiler > candidateCompilers = new ArrayList < ScriptArchiveCompiler > ( ) ; for ( ScriptArchiveCompiler compiler : compilers ) { if ( compiler . shouldCompile ( archive ) ) { candidateCompilers . add ( compiler ) ; } } return candidateCompilers ; }
Select a set of compilers to compile this archive .
40,550
public static Path createModulePath ( ModuleIdentifier moduleIdentifier ) { return Paths . get ( moduleIdentifier . getName ( ) + "-" + moduleIdentifier . getSlot ( ) ) ; }
Create module path from module moduleIdentifier .
40,551
public static Set < Class < ? > > findAssignableClasses ( ScriptModule module , Class < ? > targetClass ) { Set < Class < ? > > result = new LinkedHashSet < Class < ? > > ( ) ; for ( Class < ? > candidateClass : module . getLoadedClasses ( ) ) { if ( targetClass . isAssignableFrom ( candidateClass ) ) { result . add ( candidateClass ) ; } } return result ; }
Find all of the classes in the module that are subclasses or equal to the target class
40,552
public static Class < ? > findAssignableClass ( ScriptModule module , Class < ? > targetClass ) { for ( Class < ? > candidateClass : module . getLoadedClasses ( ) ) { if ( targetClass . isAssignableFrom ( candidateClass ) ) { return candidateClass ; } } return null ; }
Find the first class in the module that is a subclasses or equal to the target class
40,553
public static Class < ? > findClass ( ScriptModule module , String className ) { Set < Class < ? > > classes = module . getLoadedClasses ( ) ; Class < ? > targetClass = null ; for ( Class < ? > clazz : classes ) { if ( clazz . getName ( ) . equals ( className ) ) { targetClass = clazz ; break ; } } return targetClass ; }
Find a class in the module that matches the given className
40,554
public List < V > executeModules ( List < String > moduleIds , ScriptModuleExecutable < V > executable , ScriptModuleLoader moduleLoader ) { Objects . requireNonNull ( moduleIds , "moduleIds" ) ; Objects . requireNonNull ( executable , "executable" ) ; Objects . requireNonNull ( moduleLoader , "moduleLoader" ) ; List < ScriptModule > modules = new ArrayList < ScriptModule > ( moduleIds . size ( ) ) ; for ( String moduleId : moduleIds ) { ScriptModule module = moduleLoader . getScriptModule ( ModuleId . create ( moduleId ) ) ; if ( module != null ) { modules . add ( module ) ; } } return executeModules ( modules , executable ) ; }
Execute a collection of ScriptModules identified by moduleId .
40,555
public List < V > executeModules ( List < ScriptModule > modules , ScriptModuleExecutable < V > executable ) { Objects . requireNonNull ( modules , "modules" ) ; Objects . requireNonNull ( executable , "executable" ) ; List < Future < V > > futureResults = new ArrayList < Future < V > > ( modules . size ( ) ) ; for ( ScriptModule module : modules ) { Future < V > future = new ScriptModuleExecutionCommand < V > ( executorId , executable , module ) . queue ( ) ; futureResults . add ( future ) ; ExecutionStatistics moduleStats = getOrCreateModuleStatistics ( module . getModuleId ( ) ) ; moduleStats . executionCount . incrementAndGet ( ) ; moduleStats . lastExecutionTime . set ( System . currentTimeMillis ( ) ) ; } List < V > results = new ArrayList < V > ( modules . size ( ) ) ; for ( int i = 0 ; i < futureResults . size ( ) ; i ++ ) { Future < V > futureResult = futureResults . get ( i ) ; try { V result = futureResult . get ( ) ; results . add ( result ) ; } catch ( Exception e ) { ScriptModule failedModule = modules . get ( i ) ; logger . error ( "moduleId {} with creationTime: {} failed execution. see hystrix command log for deatils." , failedModule . getModuleId ( ) , failedModule . getCreateTime ( ) ) ; continue ; } } return results ; }
Execute a collection of modules .
40,556
public ExecutionStatistics getModuleStatistics ( ModuleId moduleId ) { ExecutionStatistics moduleStats = statistics . get ( moduleId ) ; return moduleStats ; }
Get the statistics for the given moduleId
40,557
protected ExecutionStatistics getOrCreateModuleStatistics ( ModuleId moduleId ) { ExecutionStatistics moduleStats = statistics . get ( moduleId ) ; if ( moduleStats == null ) { moduleStats = new ExecutionStatistics ( ) ; ExecutionStatistics existing = statistics . put ( moduleId , moduleStats ) ; if ( existing != null ) { moduleStats = existing ; } } return moduleStats ; }
Helper method to get or create a ExecutionStatistics instance
40,558
@ Path ( "/repositorysummaries" ) public List < RepositorySummary > getRepositorySummaries ( ) { List < RepositorySummary > result = new ArrayList < RepositorySummary > ( repositories . size ( ) ) ; for ( String repositoryId : repositories . keySet ( ) ) { RepositorySummary repositorySummary = getScriptRepo ( repositoryId ) . getRepositorySummary ( ) ; result . add ( repositorySummary ) ; } return result ; }
Get a list of all of the repository summaries
40,559
@ Path ( "/archivesummaries" ) public Map < String , List < ArchiveSummary > > getArchiveSummaries ( @ QueryParam ( "repositoryIds" ) Set < String > repositoryIds ) { if ( CollectionUtils . isEmpty ( repositoryIds ) ) { repositoryIds = repositories . keySet ( ) ; } Map < String , List < ArchiveSummary > > result = new LinkedHashMap < String , List < ArchiveSummary > > ( ) ; for ( String repositoryId : repositoryIds ) { List < ArchiveSummary > repoSummaries = getScriptRepo ( repositoryId ) . getSummaries ( ) ; result . put ( repositoryId , repoSummaries ) ; } return result ; }
Get a map of summaries from different repositories .
40,560
public static < V > void swapVertices ( DirectedGraph < V , DefaultEdge > graph , Map < V , Set < V > > alternates ) { Objects . requireNonNull ( graph , "graph" ) ; Objects . requireNonNull ( alternates , "alternates" ) ; addAllVertices ( graph , alternates . keySet ( ) ) ; for ( Entry < V , Set < V > > entry : alternates . entrySet ( ) ) { V alternateVertex = entry . getKey ( ) ; Set < V > dependencies = entry . getValue ( ) ; if ( ! graph . vertexSet ( ) . containsAll ( dependencies ) ) { continue ; } Set < V > dependents = Collections . emptySet ( ) ; if ( graph . containsVertex ( alternateVertex ) ) { dependents = getIncomingVertices ( graph , alternateVertex ) ; graph . removeVertex ( alternateVertex ) ; } graph . addVertex ( alternateVertex ) ; addIncomingEdges ( graph , alternateVertex , dependents ) ; addOutgoingEdges ( graph , alternateVertex , dependencies ) ; } }
replace the vertices in the graph with an alternate set of vertices .
40,561
public static < V > void addAllVertices ( DirectedGraph < V , DefaultEdge > graph , Set < V > vertices ) { for ( V vertex : vertices ) { graph . addVertex ( vertex ) ; } }
Add all of the vertices to the graph without any edges . If the the graph already contains any one of the vertices that vertex is not added .
40,562
public static < V > Set < V > getIncomingVertices ( DirectedGraph < V , DefaultEdge > graph , V target ) { Set < DefaultEdge > edges = graph . incomingEdgesOf ( target ) ; Set < V > sources = new LinkedHashSet < V > ( ) ; for ( DefaultEdge edge : edges ) { sources . add ( graph . getEdgeSource ( edge ) ) ; } return sources ; }
Fetch all of the dependents of the given target vertex
40,563
public static < V > Set < V > getOutgoingVertices ( DirectedGraph < V , DefaultEdge > graph , V source ) { Set < DefaultEdge > edges = graph . outgoingEdgesOf ( source ) ; Set < V > targets = new LinkedHashSet < V > ( ) ; for ( DefaultEdge edge : edges ) { targets . add ( graph . getEdgeTarget ( edge ) ) ; } return targets ; }
Fetch all of the dependencies of the given source vertex
40,564
public static < V > void copyGraph ( DirectedGraph < V , DefaultEdge > sourceGraph , DirectedGraph < V , DefaultEdge > targetGraph ) { addAllVertices ( targetGraph , sourceGraph . vertexSet ( ) ) ; for ( DefaultEdge edge : sourceGraph . edgeSet ( ) ) { targetGraph . addEdge ( sourceGraph . getEdgeSource ( edge ) , sourceGraph . getEdgeTarget ( edge ) ) ; } }
Copy the source graph into the target graph
40,565
public static < V > Set < V > getLeafVertices ( DirectedGraph < V , DefaultEdge > graph ) { Set < V > vertexSet = graph . vertexSet ( ) ; Set < V > leaves = new HashSet < V > ( vertexSet . size ( ) * 2 ) ; for ( V vertex : vertexSet ) { if ( graph . outgoingEdgesOf ( vertex ) . isEmpty ( ) ) { leaves . add ( vertex ) ; } } return leaves ; }
Find the leave vertices in the graph . I . E . Vertices that have no outgoing edges
40,566
public static < V > void removeVertices ( DirectedGraph < V , DefaultEdge > graph , Set < V > vertices ) { for ( V vertex : vertices ) { if ( graph . containsVertex ( vertex ) ) { graph . removeVertex ( vertex ) ; } } }
Removes vertices from graph
40,567
public static Path findRootPathForResource ( String resourceName , ClassLoader classLoader ) { Objects . requireNonNull ( resourceName , "resourceName" ) ; Objects . requireNonNull ( classLoader , "classLoader" ) ; URL resource = classLoader . getResource ( resourceName ) ; if ( resource != null ) { String protocol = resource . getProtocol ( ) ; if ( protocol . equals ( "jar" ) ) { return getJarPathFromUrl ( resource ) ; } else if ( protocol . equals ( "file" ) ) { return getRootPathFromDirectory ( resourceName , resource ) ; } else { throw new IllegalStateException ( "Unsupported URL protocol: " + protocol ) ; } } return null ; }
Find the root path for the given resource . If the resource is found in a Jar file then the result will be an absolute path to the jar file . If the resource is found in a directory then the result will be the parent path of the given resource .
40,568
public static Path findRootPathForClass ( Class < ? > clazz ) { Objects . requireNonNull ( clazz , "resourceName" ) ; String resourceName = classToResourceName ( clazz ) ; return findRootPathForResource ( resourceName , clazz . getClassLoader ( ) ) ; }
Find the root path for the given class . If the class is found in a Jar file then the result will be an absolute path to the jar file . If the resource is found in a directory then the result will be the parent path of the given resource .
40,569
public static Path getJarPathFromUrl ( URL jarUrl ) { try { String pathString = jarUrl . getPath ( ) ; int endIndex = pathString . lastIndexOf ( "!" ) ; return Paths . get ( new URI ( pathString . substring ( 0 , endIndex ) ) ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( "Unsupported URL syntax: " + jarUrl . getPath ( ) , e ) ; } }
Find the jar containing the given resource .
40,570
public static Set < String > scanClassPath ( final String classPath , final Set < String > excludeJarSet ) { final Set < String > pathSet = new HashSet < String > ( ) ; __JDKPaths . processClassPathItem ( classPath , excludeJarSet , pathSet ) ; return pathSet ; }
Scan the classpath string provided and collect a set of package paths found in jars and classes on the path .
40,571
public static Set < String > scanClassPath ( final String classPath , final Set < String > excludeJarSet , final Set < String > excludePrefixes , final Set < String > includePrefixes ) { final Set < String > pathSet = new HashSet < String > ( ) ; __JDKPaths . processClassPathItem ( classPath , excludeJarSet , pathSet ) ; return filterPathSet ( pathSet , excludePrefixes , includePrefixes ) ; }
Scan the classpath string provided and collect a set of package paths found in jars and classes on the path . On the resulting path set first exclude those that match any exclude prefixes and then include those that match a set of include prefixes .
40,572
public static Set < String > scanClassPathWithExcludes ( final String classPath , final Set < String > excludeJarSet , final Set < String > excludePrefixes ) { final Set < String > pathSet = new HashSet < String > ( ) ; __JDKPaths . processClassPathItem ( classPath , excludeJarSet , pathSet ) ; return filterPathSet ( pathSet , excludePrefixes , Collections . < String > emptySet ( ) ) ; }
Scan the classpath string provided and collect a set of package paths found in jars and classes on the path excluding any that match a set of exclude prefixes .
40,573
public static Set < String > scanClassPathWithIncludes ( final String classPath , final Set < String > excludeJarSet , final Set < String > includePrefixes ) { final Set < String > pathSet = new HashSet < String > ( ) ; __JDKPaths . processClassPathItem ( classPath , excludeJarSet , pathSet ) ; return filterPathSet ( pathSet , Collections . < String > emptySet ( ) , includePrefixes ) ; }
Scan the classpath string provided and collect a set of package paths found in jars and classes on the path including only those that match a set of include prefixes .
40,574
public void addClasses ( Set < Class < ? > > classes ) { for ( Class < ? > classToAdd : classes ) { localClassCache . put ( classToAdd . getName ( ) , classToAdd ) ; } }
Manually add the compiled classes to this classloader . This method will not redefine the class so that the class s classloader will continue to be compiler s classloader .
40,575
public Class < ? > addClassBytes ( String name , byte [ ] classBytes ) { Class < ? > newClass = defineClass ( name , classBytes , 0 , classBytes . length ) ; resolveClass ( newClass ) ; localClassCache . put ( newClass . getName ( ) , newClass ) ; return newClass ; }
Manually add the compiled classes to this classloader . This method will define and resolve the class binding this classloader to the class .
40,576
public boolean addRepository ( final ArchiveRepository archiveRepository , final int pollInterval , TimeUnit timeUnit , boolean waitForInitialPoll ) { if ( pollInterval <= 0 ) { throw new IllegalArgumentException ( "invalid pollInterval " + pollInterval ) ; } Objects . requireNonNull ( timeUnit , "timeUnit" ) ; RepositoryPollerContext pollerContext = new RepositoryPollerContext ( ) ; RepositoryPollerContext oldContext = repositoryContexts . putIfAbsent ( archiveRepository , pollerContext ) ; if ( oldContext != null ) { return false ; } final CountDownLatch initialPollLatch = new CountDownLatch ( 1 ) ; ScheduledFuture < ? > future = pollerThreadPool . scheduleWithFixedDelay ( new Runnable ( ) { public void run ( ) { try { pollRepository ( archiveRepository ) ; initialPollLatch . countDown ( ) ; } catch ( Throwable t ) { logger . error ( "Excecution exception on poll" , t ) ; } } } , 0 , pollInterval , timeUnit ) ; pollerContext . future = future ; if ( waitForInitialPoll ) { try { initialPollLatch . await ( ) ; } catch ( Exception e ) { logger . error ( "Excecution exception on poll" , e ) ; } } return true ; }
Add a repository and schedule polling
40,577
public static Path getGroovyRuntime ( ) { Path path = ClassPathUtils . findRootPathForResource ( "META-INF/groovy-release-info.properties" , ExampleResourceLocator . class . getClassLoader ( ) ) ; if ( path == null ) { throw new IllegalStateException ( "couldn't find groovy-all.n.n.n.jar in the classpath." ) ; } return path ; }
Locate the groovy - all - n . n . n . jar file on the classpath .
40,578
public static Path getGroovyPluginLocation ( ) { String resourceName = ClassPathUtils . classNameToResourceName ( GROOVY2_COMPILER_PLUGIN_CLASS ) ; Path path = ClassPathUtils . findRootPathForResource ( resourceName , ExampleResourceLocator . class . getClassLoader ( ) ) ; if ( path == null ) { throw new IllegalStateException ( "couldn't find groovy2 plugin jar in the classpath." ) ; } return path ; }
Locate the classpath root which contains the groovy2 plugin .
40,579
public static void populateModuleSpecWithCoreDependencies ( ModuleSpec . Builder moduleSpecBuilder , ScriptArchive scriptArchive ) throws ModuleLoadException { Objects . requireNonNull ( moduleSpecBuilder , "moduleSpecBuilder" ) ; Objects . requireNonNull ( scriptArchive , "scriptArchive" ) ; Set < String > compilerPlugins = scriptArchive . getModuleSpec ( ) . getCompilerPluginIds ( ) ; for ( String compilerPluginId : compilerPlugins ) { moduleSpecBuilder . addDependency ( DependencySpec . createModuleDependencySpec ( getPluginModuleId ( compilerPluginId ) , false ) ) ; } moduleSpecBuilder . addDependency ( JRE_DEPENDENCY_SPEC ) ; moduleSpecBuilder . addDependency ( NICOBAR_CORE_DEPENDENCY_SPEC ) ; moduleSpecBuilder . addDependency ( DependencySpec . createLocalDependencySpec ( ) ) ; }
Populates a module spec builder with core dependencies on JRE Nicobar itself and compiler plugins .
40,580
public static ModuleIdentifier createRevisionId ( ModuleId scriptModuleId , long revisionNumber ) { Objects . requireNonNull ( scriptModuleId , "scriptModuleId" ) ; return ModuleIdentifier . create ( scriptModuleId . toString ( ) , Long . toString ( revisionNumber ) ) ; }
Helper method to create a revisionId in a consistent manner
40,581
private static PathFilter buildFilters ( Set < String > filterPaths , boolean failedMatchValue ) { if ( filterPaths == null ) return PathFilters . acceptAll ( ) ; else if ( filterPaths . isEmpty ( ) ) { return PathFilters . rejectAll ( ) ; } else { MultiplePathFilterBuilder builder = PathFilters . multiplePathFilterBuilder ( failedMatchValue ) ; for ( String importPathGlob : filterPaths ) builder . addFilter ( PathFilters . match ( importPathGlob ) , ! failedMatchValue ) ; return builder . create ( ) ; } }
Build a PathFilter for a set of filter paths
40,582
public void unloadAllModuleRevision ( String scriptModuleId ) { for ( ModuleIdentifier revisionId : getAllRevisionIds ( scriptModuleId ) ) { if ( revisionId . getName ( ) . equals ( scriptModuleId ) ) { unloadModule ( revisionId ) ; } } }
Unload all module revisions with the give script module id
40,583
public void unloadModule ( ModuleIdentifier revisionId ) { Objects . requireNonNull ( revisionId , "revisionId" ) ; Module module = findLoadedModule ( revisionId ) ; if ( module != null ) { unloadModule ( module ) ; } }
Unload the given revision of a module from the local repository .
40,584
public Set < ModuleIdentifier > getAllRevisionIds ( String scriptModuleId ) { Objects . requireNonNull ( scriptModuleId , "scriptModuleId" ) ; Set < ModuleIdentifier > revisionIds = new LinkedHashSet < ModuleIdentifier > ( ) ; for ( ModuleIdentifier revisionId : moduleSpecs . keySet ( ) ) { if ( revisionId . getName ( ) . equals ( scriptModuleId ) ) { revisionIds . add ( revisionId ) ; } } return Collections . unmodifiableSet ( revisionIds ) ; }
Find all module revisionIds with a common name
40,585
public DirectedGraph < ModuleId , DefaultEdge > getModuleNameGraph ( ) { SimpleDirectedGraph < ModuleId , DefaultEdge > graph = new SimpleDirectedGraph < ModuleId , DefaultEdge > ( DefaultEdge . class ) ; Map < ModuleId , ModuleIdentifier > moduleIdentifiers = getLatestRevisionIds ( ) ; GraphUtils . addAllVertices ( graph , moduleIdentifiers . keySet ( ) ) ; for ( Entry < ModuleId , ModuleIdentifier > entry : moduleIdentifiers . entrySet ( ) ) { ModuleId scriptModuleId = entry . getKey ( ) ; ModuleIdentifier revisionID = entry . getValue ( ) ; ModuleSpec moduleSpec = moduleSpecs . get ( revisionID ) ; Set < ModuleId > dependencyNames = getDependencyScriptModuleIds ( moduleSpec ) ; GraphUtils . addOutgoingEdges ( graph , scriptModuleId , dependencyNames ) ; } return graph ; }
Construct the Module dependency graph of a module loader where each vertex is the module name
40,586
public static Set < ModuleId > getDependencyScriptModuleIds ( ModuleSpec moduleSpec ) { Objects . requireNonNull ( moduleSpec , "moduleSpec" ) ; if ( ! ( moduleSpec instanceof ConcreteModuleSpec ) ) { throw new IllegalArgumentException ( "Unsupported ModuleSpec implementation: " + moduleSpec . getClass ( ) . getName ( ) ) ; } Set < ModuleId > dependencyNames = new LinkedHashSet < ModuleId > ( ) ; ConcreteModuleSpec concreteSpec = ( ConcreteModuleSpec ) moduleSpec ; for ( DependencySpec dependencSpec : concreteSpec . getDependencies ( ) ) { if ( dependencSpec instanceof ModuleDependencySpec ) { ModuleIdentifier revisionId = ( ( ModuleDependencySpec ) dependencSpec ) . getIdentifier ( ) ; dependencyNames . add ( ModuleId . fromString ( revisionId . getName ( ) ) ) ; } } return dependencyNames ; }
Extract the Module dependencies for the given module in the form of ScriptModule ids .
40,587
private static char [ ] encode ( final byte [ ] data , final char [ ] toDigits ) { final int l = data . length ; final char [ ] out = new char [ l << 1 ] ; for ( int i = 0 , j = 0 ; i < l ; i ++ ) { out [ j ++ ] = toDigits [ ( 0xF0 & data [ i ] ) >>> 4 ] ; out [ j ++ ] = toDigits [ 0x0F & data [ i ] ] ; } return out ; }
Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order . The returned array will be double the length of the passed array as it takes two characters to represent any given byte .
40,588
public void trackers ( List < String > value ) { string_vector v = new string_vector ( ) ; for ( String s : value ) { v . push_back ( s ) ; } p . set_trackers ( v ) ; }
If the torrent doesn t have a tracker but relies on the DHT to find peers this method can specify tracker URLs for the torrent .
40,589
public static AddTorrentParams parseMagnetUri ( String uri ) { error_code ec = new error_code ( ) ; add_torrent_params params = add_torrent_params . parse_magnet_uri ( uri , ec ) ; if ( ec . value ( ) != 0 ) { throw new IllegalArgumentException ( "Invalid magnet uri: " + ec . message ( ) ) ; } return new AddTorrentParams ( params ) ; }
Helper function to parse a magnet uri and fill the parameters .
40,590
public void stop ( ) { if ( session == null ) { return ; } sync . lock ( ) ; try { if ( session == null ) { return ; } onBeforeStop ( ) ; session s = session ; session = null ; s . post_session_stats ( ) ; try { Thread . sleep ( ALERTS_LOOP_WAIT_MILLIS + 250 ) ; } catch ( InterruptedException ignore ) { } if ( alertsLoop != null ) { try { alertsLoop . join ( ) ; } catch ( Throwable e ) { } } resetState ( ) ; s . delete ( ) ; onAfterStop ( ) ; } finally { sync . unlock ( ) ; } }
This method blocks during the destruction of the native session it could take some time don t call this from the UI thread or other sensitive multithreaded code .
40,591
public void restart ( ) { sync . lock ( ) ; try { stop ( ) ; Thread . sleep ( 1000 ) ; start ( ) ; } catch ( InterruptedException e ) { } finally { sync . unlock ( ) ; } }
This method blocks for at least a second plus the time needed to destroy the native session don t call it from the UI thread .
40,592
public void download ( String magnetUri , File saveDir ) { if ( session == null ) { return ; } error_code ec = new error_code ( ) ; add_torrent_params p = add_torrent_params . parse_magnet_uri ( magnetUri , ec ) ; if ( ec . value ( ) != 0 ) { throw new IllegalArgumentException ( ec . message ( ) ) ; } sha1_hash info_hash = p . getInfo_hash ( ) ; torrent_handle th = session . find_torrent ( info_hash ) ; if ( th != null && th . is_valid ( ) ) { return ; } if ( saveDir != null ) { p . setSave_path ( saveDir . getAbsolutePath ( ) ) ; } torrent_flags_t flags = p . getFlags ( ) ; flags = flags . and_ ( TorrentFlags . AUTO_MANAGED . inv ( ) ) ; p . setFlags ( flags ) ; session . async_add_torrent ( p ) ; }
Downloads a magnet uri .
40,593
public ArrayList < TcpEndpoint > peers ( ) { tcp_endpoint_vector v = alert . peers ( ) ; int size = ( int ) v . size ( ) ; ArrayList < TcpEndpoint > peers = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { tcp_endpoint endp = v . get ( i ) ; String ip = new Address ( endp . address ( ) ) . toString ( ) ; peers . add ( new TcpEndpoint ( ip , endp . port ( ) ) ) ; } return peers ; }
This method creates a new list each time is called .
40,594
public ArrayList < Pair < String , String > > extraHeaders ( ) { string_string_pair_vector v = e . getExtra_headers ( ) ; int size = ( int ) v . size ( ) ; ArrayList < Pair < String , String > > l = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { string_string_pair p = v . get ( i ) ; l . add ( new Pair < > ( p . getFirst ( ) , p . getSecond ( ) ) ) ; } return l ; }
Any extra HTTP headers that need to be passed to the web seed .
40,595
private void tick ( long tickIntervalMs ) { for ( int i = 0 ; i < NUM_AVERAGES ; ++ i ) { stat [ i ] . tick ( tickIntervalMs ) ; } }
should be called once every second
40,596
public List < TorrentHandle > torrents ( ) { torrent_handle_vector v = s . get_torrents ( ) ; int size = ( int ) v . size ( ) ; ArrayList < TorrentHandle > l = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { l . add ( new TorrentHandle ( v . get ( i ) ) ) ; } return l ; }
Returns a list of torrent handles to all the torrents currently in the session .
40,597
public void dhtPutItem ( byte [ ] publicKey , byte [ ] privateKey , Entry entry , byte [ ] salt ) { s . dht_put_item ( Vectors . bytes2byte_vector ( publicKey ) , Vectors . bytes2byte_vector ( privateKey ) , entry . swig ( ) , Vectors . bytes2byte_vector ( salt ) ) ; }
calling the callback in between is convenient .
40,598
public String filePath ( int index , String savePath ) { return savePath + File . separator + fs . file_path ( index ) ; }
returns the full path to a file .
40,599
public ArrayList < DhtRoutingBucket > routingTable ( ) { dht_routing_bucket_vector v = alert . getRouting_table ( ) ; int size = ( int ) v . size ( ) ; ArrayList < DhtRoutingBucket > l = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { l . add ( new DhtRoutingBucket ( v . get ( i ) ) ) ; } return l ; }
Contains information about every bucket in the DHT routing table .