idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
40,500
public void onRowViewAdded ( NotificationBoard board , RowView rowView , NotificationEntry entry ) { if ( DBG ) Log . v ( TAG , "onRowViewAdded - " + entry . ID ) ; if ( entry . hasActions ( ) ) { ArrayList < Action > actions = entry . getActions ( ) ; ViewGroup vg = ( ViewGroup ) rowView . findViewById ( R . id . actions ) ; vg . setVisibility ( View . VISIBLE ) ; vg = ( ViewGroup ) vg . getChildAt ( 0 ) ; final View . OnClickListener onClickListener = new View . OnClickListener ( ) { public void onClick ( View view ) { Action act = ( Action ) view . getTag ( ) ; onClickActionView ( act . entry , act , view ) ; act . execute ( view . getContext ( ) ) ; } } ; for ( int i = 0 , count = actions . size ( ) ; i < count ; i ++ ) { Action act = actions . get ( i ) ; Button actionBtn = ( Button ) vg . getChildAt ( i ) ; actionBtn . setVisibility ( View . VISIBLE ) ; actionBtn . setTag ( act ) ; actionBtn . setText ( act . title ) ; actionBtn . setOnClickListener ( onClickListener ) ; actionBtn . setCompoundDrawablesWithIntrinsicBounds ( act . icon , 0 , 0 , 0 ) ; } } }
Called when a row view is added to the board .
40,501
public void onRowViewUpdate ( NotificationBoard board , RowView rowView , NotificationEntry entry ) { if ( DBG ) Log . v ( TAG , "onRowViewUpdate - " + entry . ID ) ; ImageView iconView = ( ImageView ) rowView . findViewById ( R . id . icon ) ; TextView titleView = ( TextView ) rowView . findViewById ( R . id . title ) ; TextView textView = ( TextView ) rowView . findViewById ( R . id . text ) ; TextView whenView = ( TextView ) rowView . findViewById ( R . id . when ) ; ProgressBar bar = ( ProgressBar ) rowView . findViewById ( R . id . progress ) ; if ( entry . iconDrawable != null ) { iconView . setImageDrawable ( entry . iconDrawable ) ; } else if ( entry . smallIconRes != 0 ) { iconView . setImageResource ( entry . smallIconRes ) ; } else if ( entry . largeIconBitmap != null ) { iconView . setImageBitmap ( entry . largeIconBitmap ) ; } titleView . setText ( entry . title ) ; textView . setText ( entry . text ) ; if ( entry . showWhen ) { whenView . setText ( entry . whenFormatted ) ; } if ( entry . progressMax != 0 || entry . progressIndeterminate ) { bar . setVisibility ( View . VISIBLE ) ; bar . setIndeterminate ( entry . progressIndeterminate ) ; if ( ! entry . progressIndeterminate ) { bar . setMax ( entry . progressMax ) ; bar . setProgress ( entry . progress ) ; } } else { bar . setVisibility ( View . GONE ) ; } }
Called when a row view is being updated .
40,502
public void onClickRowView ( NotificationBoard board , RowView rowView , NotificationEntry entry ) { if ( DBG ) Log . v ( TAG , "onClickRowView - " + entry . ID ) ; }
Called when a row view has been clicked .
40,503
public static float getAlphaForOffset ( float alphaStart , float alphaEnd , float posStart , float posEnd , float posOffset ) { return alphaStart + posOffset * ( alphaEnd - alphaStart ) / ( posEnd - posStart ) ; }
Calculate the alpha value for a position offset .
40,504
private Collection < DependencyInfo > createDependencyInfos ( Collection < PhpPackage > phpPackages , Collection < DependencyInfo > dependencyInfos , Collection < String > directDependencies ) { HashMap < DependencyInfo , Collection < String > > parentToChildMap = new HashMap < > ( ) ; HashMap < String , DependencyInfo > packageDependencyMap = new HashMap < > ( ) ; for ( PhpPackage phpPackage : phpPackages ) { DependencyInfo dependencyInfo = createDependencyInfo ( phpPackage ) ; if ( dependencyInfo != null ) { parentToChildMap . put ( dependencyInfo , phpPackage . getPackageRequire ( ) . keySet ( ) ) ; packageDependencyMap . put ( phpPackage . getName ( ) , dependencyInfo ) ; } else { logger . debug ( "Didn't succeed to create dependencyInfo for {}" , phpPackage . getName ( ) ) ; } } if ( ! packageDependencyMap . isEmpty ( ) ) { for ( String directDependency : directDependencies ) { DependencyInfo dependencyInfo = packageDependencyMap . get ( directDependency ) ; if ( dependencyInfo != null ) { collectChildren ( dependencyInfo , packageDependencyMap , parentToChildMap ) ; dependencyInfos . add ( dependencyInfo ) ; } else { logger . debug ( "Didn't found {} in map {}" , directDependency , packageDependencyMap . getClass ( ) . getName ( ) ) ; } } } else { logger . debug ( "The map {} is empty " , packageDependencyMap . getClass ( ) . getName ( ) ) ; } return dependencyInfos ; }
create dependencyInfo objects from each direct dependency
40,505
private DependencyInfo createDependencyInfo ( PhpPackage phpPackage ) { String groupId = getGroupIdFromName ( phpPackage ) ; String artifactId = phpPackage . getName ( ) ; String version = phpPackage . getVersion ( ) ; String commit = phpPackage . getPackageSource ( ) . getReference ( ) ; if ( StringUtils . isNotBlank ( version ) || StringUtils . isNotBlank ( commit ) ) { DependencyInfo dependencyInfo = new DependencyInfo ( groupId , artifactId , version ) ; dependencyInfo . setCommit ( commit ) ; dependencyInfo . setDependencyType ( getDependencyType ( ) ) ; if ( this . addSha1 ) { String sha1 = null ; String sha1Source = StringUtils . isNotBlank ( version ) ? version : commit ; try { sha1 = this . hashCalculator . calculateSha1ByNameVersionAndType ( artifactId , sha1Source , DependencyType . PHP ) ; } catch ( IOException e ) { logger . debug ( "Failed to calculate sha1 of: {}" , artifactId ) ; } if ( sha1 != null ) { dependencyInfo . setSha1 ( sha1 ) ; } } return dependencyInfo ; } else { logger . debug ( "The parameters version and commit of {} are null" , phpPackage . getName ( ) ) ; return null ; } }
convert phpPackage to dependencyInfo object
40,506
private void collectChildren ( DependencyInfo dependencyInfo , HashMap < String , DependencyInfo > packageDependencyMap , HashMap < DependencyInfo , Collection < String > > requireDependenciesMap ) { Collection < String > requires = requireDependenciesMap . get ( dependencyInfo ) ; if ( dependencyInfo . getChildren ( ) . isEmpty ( ) ) { for ( String require : requires ) { DependencyInfo dependencyChild = packageDependencyMap . get ( require ) ; if ( dependencyChild != null ) { dependencyInfo . getChildren ( ) . add ( dependencyChild ) ; collectChildren ( dependencyChild , packageDependencyMap , requireDependenciesMap ) ; } } } }
collect children s recursively for each dependencyInfo object
40,507
private String getGroupIdFromName ( PhpPackage phpPackage ) { String groupId = null ; if ( StringUtils . isNotBlank ( phpPackage . getName ( ) ) ) { String packageName = phpPackage . getName ( ) ; String [ ] gavCoordinates = packageName . split ( FORWARD_SLASH ) ; groupId = gavCoordinates [ 0 ] ; } return groupId ; }
get the groupId from the name of package
40,508
private String getArtifactIdFromName ( PhpPackage phpPackage ) { String artifactId = null ; if ( StringUtils . isNotBlank ( phpPackage . getName ( ) ) ) { String packageName = phpPackage . getName ( ) ; String [ ] gavCoordinates = packageName . split ( FORWARD_SLASH ) ; artifactId = gavCoordinates [ 1 ] ; } return artifactId ; }
get the artifactId from the name of package
40,509
protected boolean loginToRemoteRegistry ( ) { Pair < Integer , InputStream > result ; try { isUserLoggedIn ( ) ; if ( ! loggedInToAzure ) { Process process = Runtime . getRuntime ( ) . exec ( azureCli . getLoginCommand ( config . getAzureUserName ( ) , config . getAzureUserPassword ( ) ) ) ; int resultValue = process . waitFor ( ) ; if ( resultValue == 0 ) { logger . info ( "Log in to Azure account {} - Succeeded" , config . getAzureUserName ( ) ) ; } else { logger . info ( "Log in to Azure account {} - Failed" , config . getAzureUserName ( ) ) ; String errorMessage = IOUtils . toString ( process . getInputStream ( ) , StandardCharsets . UTF_8 . name ( ) ) ; logger . error ( "Failed to log in to Azure account {} - {}" , config . getAzureUserName ( ) , errorMessage ) ; return false ; } } for ( String registryName : config . getAzureRegistryNames ( ) ) { if ( registryName != null && ! registryName . trim ( ) . equals ( Constants . EMPTY_STRING ) ) { logger . info ( "Log in to Azure container registry {}" , registryName ) ; result = executeCommand ( azureCli . getLoginContainerRegistryCommand ( registryName ) ) ; if ( result . getKey ( ) == 0 ) { logger . info ( "Login to registry : {} - Succeeded" , registryName ) ; loggedInRegistries . add ( registryName ) ; } else { logger . info ( "Login to registry {} - Failed" , registryName ) ; logger . error ( "Failed to login registry {} - {}" , registryName , IOUtils . toString ( result . getValue ( ) , StandardCharsets . UTF_8 . name ( ) ) ) ; } } } return true ; } catch ( InterruptedException interruptedException ) { logger . debug ( "Failed to login to Azure account, Exception: {}" , interruptedException . getMessage ( ) ) ; } catch ( IOException ioException ) { logger . debug ( "Failed to parse command error result, Exception: {}" , ioException . getMessage ( ) ) ; } return false ; }
Log in to container registry in Azure cloud . If login succeeded docker obtains authentication to pull images from this registry .
40,510
public void setWhen ( CharSequence format , long when ) { if ( format == null ) format = DEFAULT_DATE_FORMAT ; this . whenFormatted = DateFormat . format ( format , when ) ; }
Set a timestamp pertaining to this notification .
40,511
public void setProgress ( int max , int progress , boolean indeterminate ) { this . progressMax = max ; this . progress = progress ; this . progressIndeterminate = indeterminate ; }
Set the progress this notification represents .
40,512
public void setRingtone ( Context context , int resId ) { if ( resId > 0 ) { this . ringtoneUri = Uri . parse ( "android.resource://" + context . getPackageName ( ) + "/" + resId ) ; } }
Set ringtone resource .
40,513
public void setRingtone ( String filepath ) { if ( filepath != null ) { File file = new File ( filepath ) ; if ( file . exists ( ) ) { this . ringtoneUri = Uri . fromFile ( file ) ; } else { Log . e ( TAG , "ringtone file not found." ) ; } } }
Set ringtone file path .
40,514
public PendingIntent getDeleteIntent ( NotificationEntry entry ) { Intent intent = new Intent ( ACTION_CANCEL ) ; intent . putExtra ( KEY_ENTRY_ID , entry . ID ) ; return PendingIntent . getBroadcast ( mContext , genIdForPendingIntent ( ) , intent , 0 ) ; }
Create an PendingIntent to execute when the notification is explicitly dismissed by the user .
40,515
public PendingIntent getContentIntent ( NotificationEntry entry ) { Intent intent = new Intent ( ACTION_CONTENT ) ; intent . putExtra ( KEY_ENTRY_ID , entry . ID ) ; return PendingIntent . getBroadcast ( mContext , genIdForPendingIntent ( ) , intent , 0 ) ; }
Create an PendingIntent to execute when the notification is clicked by the user .
40,516
public PendingIntent getActionIntent ( NotificationEntry entry , NotificationEntry . Action act ) { Intent intent = new Intent ( ACTION_ACTION ) ; intent . putExtra ( KEY_ENTRY_ID , entry . ID ) ; intent . putExtra ( KEY_ACTION_ID , entry . mActions . indexOf ( act ) ) ; return PendingIntent . getBroadcast ( mContext , genIdForPendingIntent ( ) , intent , 0 ) ; }
Create an PendingIntent to be fired when the notification action is invoked .
40,517
private String collectDependenciesWithoutDefinedManager ( String rootDirectory , List < DependencyInfo > dependencyInfos ) { String error = null ; try { collectDepDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . DEP ; } catch ( Exception e ) { try { collectGoDepDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . GO_DEP ; } catch ( Exception e1 ) { try { collectVndrDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . VNDR ; } catch ( Exception e2 ) { try { collectGoGradleDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . GO_GRADLE ; } catch ( Exception e3 ) { try { collectGlideDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . GLIDE ; } catch ( Exception e4 ) { try { collectGoVendorDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . GO_VENDOR ; } catch ( Exception e5 ) { try { collectGoPMDependencies ( rootDirectory , dependencyInfos ) ; goDependencyManager = GoDependencyManager . GOPM ; } catch ( Exception e6 ) { error = "Couldn't collect dependencies - no dependency manager is installed" ; } } } } } } } return error ; }
when no dependency manager is defined - trying to run one manager after the other till one succeeds . if not - returning an error
40,518
private void printErrors ( ) { if ( errorLog . isFile ( ) ) { FileReader fileReader ; try { fileReader = new FileReader ( errorLog ) ; BufferedReader bufferedReader = new BufferedReader ( fileReader ) ; String currLine ; while ( ( currLine = bufferedReader . readLine ( ) ) != null ) { logger . debug ( currLine ) ; } fileReader . close ( ) ; } catch ( Exception e ) { logger . warn ( "Error printing cmd command errors {} " , e . getMessage ( ) ) ; logger . debug ( "Error: {}" , e . getStackTrace ( ) ) ; } finally { try { FileUtils . forceDelete ( errorLog ) ; } catch ( IOException e ) { logger . warn ( "Error closing cmd command errors file {} " , e . getMessage ( ) ) ; logger . debug ( "Error: {}" , e . getStackTrace ( ) ) ; } } } }
if you find a better way - go ahead and replace it
40,519
private String getShortPath ( String rootPath ) { File file = new File ( rootPath ) ; String lastPathAfterSeparator = null ; String shortPath = getWindowsShortPath ( file . getAbsolutePath ( ) ) ; if ( StringUtils . isNotEmpty ( shortPath ) ) { return getWindowsShortPath ( file . getAbsolutePath ( ) ) ; } else { while ( StringUtils . isEmpty ( getWindowsShortPath ( file . getAbsolutePath ( ) ) ) ) { String filePath = file . getAbsolutePath ( ) ; if ( StringUtils . isNotEmpty ( lastPathAfterSeparator ) ) { lastPathAfterSeparator = file . getAbsolutePath ( ) . substring ( filePath . lastIndexOf ( WINDOWS_SEPARATOR ) , filePath . length ( ) ) + lastPathAfterSeparator ; } else { lastPathAfterSeparator = file . getAbsolutePath ( ) . substring ( filePath . lastIndexOf ( WINDOWS_SEPARATOR ) , filePath . length ( ) ) ; } file = file . getParentFile ( ) ; } return getWindowsShortPath ( file . getAbsolutePath ( ) ) + lastPathAfterSeparator ; } }
get windows short path
40,520
private Collection < DependencyInfo > collectPackageJsonDependencies ( Collection < BomFile > packageJsons ) { Collection < DependencyInfo > dependencies = new LinkedList < > ( ) ; ConcurrentHashMap < DependencyInfo , BomFile > dependencyPackageJsonMap = new ConcurrentHashMap < > ( ) ; ExecutorService executorService = Executors . newWorkStealingPool ( NUM_THREADS ) ; Collection < EnrichDependency > threadsCollection = new LinkedList < > ( ) ; for ( BomFile packageJson : packageJsons ) { if ( packageJson != null && packageJson . isValid ( ) ) { DependencyInfo dependency = new DependencyInfo ( ) ; dependencies . add ( dependency ) ; threadsCollection . add ( new EnrichDependency ( packageJson , dependency , dependencyPackageJsonMap , npmAccessToken ) ) ; logger . debug ( "Collect package.json of the dependency in the file: {}" , dependency . getFilename ( ) ) ; } } runThreadCollection ( executorService , threadsCollection ) ; logger . debug ( "set hierarchy of the dependencies" ) ; Map < String , DependencyInfo > existDependencies = new HashMap < > ( ) ; Map < DependencyInfo , BomFile > dependencyPackageJsonMapWithoutDuplicates = new HashMap < > ( ) ; for ( Map . Entry < DependencyInfo , BomFile > entry : dependencyPackageJsonMap . entrySet ( ) ) { DependencyInfo keyDep = entry . getKey ( ) ; String key = keyDep . getSha1 ( ) + keyDep . getVersion ( ) + keyDep . getArtifactId ( ) ; if ( ! existDependencies . containsKey ( key ) ) { existDependencies . put ( key , keyDep ) ; dependencyPackageJsonMapWithoutDuplicates . put ( keyDep , entry . getValue ( ) ) ; } } setHierarchy ( dependencyPackageJsonMapWithoutDuplicates , existDependencies ) ; return existDependencies . values ( ) ; }
Collect dependencies from package . json files - without npm ls
40,521
private void removeDependenciesWithoutSha1 ( Collection < DependencyInfo > dependencies ) { Collection < DependencyInfo > childDependencies = new ArrayList < > ( ) ; for ( Iterator < DependencyInfo > iterator = dependencies . iterator ( ) ; iterator . hasNext ( ) ; ) { DependencyInfo dependencyInfo = iterator . next ( ) ; if ( dependencyInfo . getSha1 ( ) . isEmpty ( ) ) { childDependencies . addAll ( dependencyInfo . getChildren ( ) ) ; iterator . remove ( ) ; } } dependencies . addAll ( childDependencies ) ; }
currently deprecated - not relevant
40,522
private String getPackageVersion ( String packageInfoString ) { try { String firstDotString = packageInfoString . substring ( 0 , packageInfoString . indexOf ( Constants . DOT ) ) ; int lastIndexOfHyphen = firstDotString . lastIndexOf ( Constants . DASH ) ; int lastIndexOfDot = packageInfoString . lastIndexOf ( Constants . DOT ) ; String packVersion = packageInfoString . substring ( lastIndexOfHyphen + 1 , lastIndexOfDot ) ; if ( StringUtils . isNotBlank ( packVersion ) ) { return packVersion ; } } catch ( Exception e ) { logger . warn ( "Failed to create package version : {}" , e . getMessage ( ) ) ; } return null ; }
get rpm package version
40,523
public File checkFolders ( Collection < String > yumDbFolders , String yumDbFolderPath ) { if ( ! yumDbFolders . isEmpty ( ) ) { for ( String folderPath : yumDbFolders ) { File file = new File ( folderPath ) ; if ( file . listFiles ( ) . length > 0 && folderPath . contains ( yumDbFolderPath ) ) { return file ; } } } return null ; }
find yumdb folder from collection
40,524
private boolean checkAppPathsForVia ( Set < String > keySet , List < String > errors ) { for ( String key : keySet ) { if ( ! key . equals ( "defaultKey" ) ) { File file = new File ( key ) ; if ( ! file . exists ( ) ) { errors . add ( "Effective Usage Analysis will not run if the -appPath parameter references an invalid file path. Check that the -appPath parameter specifies a valid path" ) ; return false ; } else if ( ! file . isFile ( ) ) { errors . add ( "Effective Usage Analysis will not run if the -appPath parameter references an invalid file path. Check that the -appPath parameter specifies a valid path" ) ; return false ; } else { return true ; } } } return false ; }
check validation for appPath property first check if the path is exist and then if this path is not a directory
40,525
public static String [ ] parseProxy ( String proxy , List < String > errors ) { String [ ] parsedProxyInfo = new String [ 4 ] ; if ( proxy != null ) { try { URL proxyAsUrl = new URL ( proxy ) ; parsedProxyInfo [ 0 ] = proxyAsUrl . getHost ( ) ; parsedProxyInfo [ 1 ] = String . valueOf ( proxyAsUrl . getPort ( ) ) ; if ( proxyAsUrl . getUserInfo ( ) != null ) { String [ ] parsedCred = proxyAsUrl . getUserInfo ( ) . split ( COLON ) ; parsedProxyInfo [ 2 ] = parsedCred [ 0 ] ; if ( parsedCred . length > 1 ) { parsedProxyInfo [ 3 ] = parsedCred [ 1 ] ; } } } catch ( MalformedURLException e ) { errors . add ( "Malformed proxy url : {}" + e . getMessage ( ) ) ; } } return parsedProxyInfo ; }
returns data of proxy url from command line parameter proxy
40,526
private DependencyFile getSha1FromLocalRepo ( DependencyInfo dependencyInfo ) { File localRepo = new File ( gradleLocalRepositoryPath ) ; DependencyFile dependencyFile = null ; if ( localRepo . exists ( ) && localRepo . isDirectory ( ) ) { String artifactId = dependencyInfo . getArtifactId ( ) ; String version = dependencyInfo . getVersion ( ) ; String dependencyName = artifactId + Constants . DASH + version ; logger . debug ( "Looking for " + dependencyName + " in {}" , localRepo . getPath ( ) ) ; dependencyFile = findDependencySha1 ( dependencyName , gradleLocalRepositoryPath ) ; } else { logger . warn ( "Could not find path {}" , localRepo . getPath ( ) ) ; } return dependencyFile ; }
get sha1 form local repository
40,527
public void onClickRemote ( NotificationRemote remote , NotificationEntry entry ) { if ( DBG ) Log . v ( TAG , "onClickRemote - " + entry . ID ) ; }
Called when notification is clicked .
40,528
public void onClickRemoteAction ( NotificationRemote remote , NotificationEntry entry , NotificationEntry . Action act ) { if ( DBG ) Log . v ( TAG , "onClickRemoteAction - " + entry . ID + ", " + act ) ; }
Called when notification action view is clicked .
40,529
public void onReceive ( NotificationRemote remote , NotificationEntry entry , Intent intent , String intentAction ) { if ( DBG ) Log . d ( TAG , "onReceive - " + entry . ID + ", " + intentAction ) ; }
Called when receiving a broadcast .
40,530
private Collection < DockerImage > filterDockerImagesToScan ( Collection < DockerImage > dockerImages , String [ ] dockerImageIncludes , String [ ] dockerImageExcludes ) { logger . info ( "Filtering docker images list by includes and excludes lists" ) ; Collection < DockerImage > dockerImagesToScan = new LinkedList < > ( ) ; Collection < String > imageIncludesList = Arrays . asList ( dockerImageIncludes ) ; Collection < String > imageExcludesList = Arrays . asList ( dockerImageExcludes ) ; for ( DockerImage dockerImage : dockerImages ) { String dockerImageString = dockerImage . getRepository ( ) + Constants . WHITESPACE + dockerImage . getTag ( ) + Constants . WHITESPACE + dockerImage . getId ( ) ; if ( isMatchingPattern ( dockerImageString , imageIncludesList ) ) { dockerImagesToScan . add ( dockerImage ) ; } if ( isMatchingPattern ( dockerImageString , imageExcludesList ) ) { dockerImagesToScan . remove ( dockerImage ) ; } } return dockerImagesToScan ; }
Filter the images using includes and excludes lists
40,531
private void saveDockerImages ( Collection < DockerImage > dockerImages , Collection < AgentProjectInfo > projects ) throws IOException { logger . info ( "Saving {} docker images" , dockerImages . size ( ) ) ; int counter = 1 ; int imagesCount = dockerImages . size ( ) ; for ( DockerImage dockerImage : dockerImages ) { logger . info ( "Image {} of {} Images" , counter , imagesCount ) ; manageDockerImage ( dockerImage , projects ) ; counter ++ ; } }
Save docker images and scan files
40,532
public void cancel ( int entryId ) { NotificationEntry entry = mCenter . getEntry ( ID , entryId ) ; if ( entry != null ) { cancel ( entry ) ; } }
Cancel notification by its id .
40,533
public void cancel ( String tag ) { List < NotificationEntry > entries = mCenter . getEntries ( ID , tag ) ; if ( entries != null && ! entries . isEmpty ( ) ) { for ( NotificationEntry entry : entries ) { cancel ( entry ) ; } } }
Cancel notifications by its tag .
40,534
public void cancelAll ( ) { if ( DBG ) Log . v ( TAG , "prepare to cancel all" ) ; cancelSchedule ( ARRIVE ) ; schedule ( CANCEL_ALL , 0 , 0 , null , 0 ) ; }
Cancel all notifications .
40,535
public boolean open ( boolean anim ) { if ( ! mEnabled ) { return false ; } if ( mOpened ) { return true ; } if ( ! mShowing ) { show ( ) ; } if ( anim ) { animateOpen ( ) ; } else { onEndOpen ( ) ; } return true ; }
Open the board .
40,536
public void setInitialTouchArea ( int l , int t , int r , int b ) { mContentView . setTouchToOpen ( l , t , r , b ) ; }
Set the touch area where the user can touch to pull the board down .
40,537
public void setHeaderMargin ( int l , int t , int r , int b ) { mHeader . setMargin ( l , t , r , b ) ; }
Set the margin of the header .
40,538
public void setFooterMargin ( int l , int t , int r , int b ) { mFooter . setMargin ( l , t , r , b ) ; }
Set the margin of the footer .
40,539
public void setBodyMargin ( int l , int t , int r , int b ) { mBody . setMargin ( l , t , r , b ) ; }
Set the margin of the body .
40,540
public void setRowMargin ( int l , int t , int r , int b ) { mRowMargin [ 0 ] = l ; mRowMargin [ 1 ] = t ; mRowMargin [ 2 ] = r ; mRowMargin [ 3 ] = b ; }
Set the margin of each row .
40,541
public void addHeaderView ( View view , int index , ViewGroup . LayoutParams lp ) { mHeader . addView ( view , index , lp ) ; }
Add header view .
40,542
public void addFooterView ( View view , int index , ViewGroup . LayoutParams lp ) { mFooter . addView ( view , index , lp ) ; }
Add footer view .
40,543
public void addBodyView ( View view , int index , ViewGroup . LayoutParams lp ) { mBody . addView ( view , index , lp ) ; }
Add body view .
40,544
public void setHeaderDivider ( Drawable drawable ) { mHeaderDivider = drawable ; if ( drawable != null ) { mHeaderDividerHeight = drawable . getIntrinsicHeight ( ) ; } else { mHeaderDividerHeight = 0 ; } mContentView . setWillNotDraw ( drawable == null ) ; mContentView . invalidate ( ) ; }
Set header divider .
40,545
public void setFooterDivider ( Drawable drawable ) { mFooterDivider = drawable ; if ( drawable != null ) { mFooterDividerHeight = drawable . getIntrinsicHeight ( ) ; } else { mFooterDividerHeight = 0 ; } mContentView . setWillNotDraw ( drawable == null ) ; mContentView . invalidate ( ) ; }
Set footer divider .
40,546
public void setClearView ( View view ) { mClearView = view ; if ( view != null ) { view . setVisibility ( mOpened ? VISIBLE : INVISIBLE ) ; view . setOnClickListener ( mOnClickListenerClearView ) ; } }
Set clear view . If clicked all notifications will be canceled .
40,547
public void setBoardPadding ( int l , int t , int r , int b ) { mContentView . setPadding ( l , t , r , b ) ; }
Set the margin of the entire board .
40,548
public void setBoardTranslationX ( float x ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardTranslationX ( this , x ) ; } } mContentView . setTranslationX ( x ) ; }
Set the x translation of this board .
40,549
public void setBoardTranslationY ( float y ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardTranslationY ( this , y ) ; } } mContentView . setTranslationY ( y ) ; }
Set the y translation of this board .
40,550
public void setBoardPivotX ( float x ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardPivotX ( this , x ) ; } } mContentView . setPivotX ( x ) ; }
Set the x location of pivot point around which this board is rotated .
40,551
public void setBoardPivotY ( float y ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardPivotY ( this , y ) ; } } mContentView . setPivotY ( y ) ; }
Set the y location of pivot point around which this board is rotated .
40,552
public void setBoardRotationX ( float x ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardRotationX ( this , x ) ; } } mContentView . setRotationX ( x ) ; }
Set the x degree that this board is rotated .
40,553
public void setBoardRotationY ( float y ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardRotationY ( this , y ) ; } } mContentView . setRotationY ( y ) ; }
Set the y degree that this board is rotated .
40,554
public void setBoardAlpha ( float alpha ) { if ( mListeners != null ) { for ( StateListener l : mListeners ) { l . onBoardAlpha ( this , alpha ) ; } } mContentView . setAlpha ( alpha ) ; }
Set the opacity of this board .
40,555
public void dimAt ( float alpha ) { if ( ! mDimEnabled ) { return ; } if ( mDimView == null ) { mDimView = makeDimView ( ) ; } if ( ! mDimView . isShown ( ) ) { mDimView . setVisibility ( VISIBLE ) ; mDimView . setBackgroundColor ( mDimColor ) ; } mDimView . setAlpha ( alpha ) ; }
Set the dim - behind layer a specific opacity .
40,556
public void dim ( int duration ) { if ( ! mDimEnabled ) { return ; } if ( mDimView == null ) { mDimView = makeDimView ( ) ; } if ( ! mDimView . isShown ( ) ) { mDimView . setVisibility ( VISIBLE ) ; mDimView . setBackgroundColor ( mDimColor ) ; } mDimView . animate ( ) . cancel ( ) ; mDimView . animate ( ) . alpha ( mDimAlpha ) . setListener ( null ) . setDuration ( duration ) . start ( ) ; }
Start the dim animation .
40,557
public void undim ( int duration ) { if ( mDimView != null && mDimView . isShown ( ) && mDimView . getAlpha ( ) != 0 ) { mDimView . animate ( ) . cancel ( ) ; mDimView . animate ( ) . alpha ( 0.0f ) . setListener ( mDimAnimatorListener ) . setDuration ( duration ) . start ( ) ; } }
Start the undim animation .
40,558
private boolean isDescendant ( DependencyInfo ancestor , DependencyInfo descendant ) { for ( DependencyInfo child : ancestor . getChildren ( ) ) { if ( child . equals ( descendant ) ) { return true ; } if ( isDescendant ( child , descendant ) ) { return true ; } } return false ; }
preventing circular dependencies by making sure the dependency is not a descendant of its own
40,559
private boolean copyProjectFolder ( String projectFolder , File buildGradleTempDirectory ) { try { FileUtils . copyDirectory ( new File ( projectFolder ) , buildGradleTempDirectory ) ; } catch ( IOException e ) { logger . error ( "Could not copy the folder {} to {} , the cause {}" , projectFolder , buildGradleTempDirectory . getPath ( ) , e . getMessage ( ) ) ; return false ; } logger . debug ( "copied folder {} to temp folder successfully" , projectFolder ) ; return true ; }
copy project to local temp directory
40,560
private boolean appendTaskToBomFile ( File buildGradleTmp ) { FileReader fileReader ; BufferedReader bufferedReader = null ; InputStream inputStream = null ; boolean hasDependencies = false ; try { fileReader = new FileReader ( buildGradleTmp ) ; bufferedReader = new BufferedReader ( fileReader ) ; String currLine ; while ( ( currLine = bufferedReader . readLine ( ) ) != null ) { if ( currLine . indexOf ( DEPENDENCIES + Constants . WHITESPACE + CURLY_BRACKETS_OPEN ) == 0 || currLine . indexOf ( DEPENDENCIES + CURLY_BRACKETS_OPEN ) == 0 ) { hasDependencies = true ; break ; } } if ( hasDependencies ) { byte [ ] bytes ; List < String > lines = getDependenciesTree ( buildGradleTmp . getParent ( ) , buildGradleTmp . getParentFile ( ) . getName ( ) ) ; if ( lines != null ) { List < String > scopes = getScopes ( lines ) ; String copyDependenciesTask = Constants . NEW_LINE + TASK_COPY_DEPENDENCIES_HEADER + Constants . NEW_LINE ; for ( String scope : scopes ) { copyDependenciesTask = copyDependenciesTask . concat ( " from configurations." + scope + Constants . NEW_LINE ) ; } copyDependenciesTask = copyDependenciesTask . concat ( TASK_COPY_DEPENDENCIES_FOOTER + Constants . NEW_LINE + CURLY_BRACKTES_CLOSE ) ; bytes = copyDependenciesTask . getBytes ( ) ; } else { ClassLoader classLoader = Main . class . getClassLoader ( ) ; inputStream = classLoader . getResourceAsStream ( COPY_DEPENDENCIES_TASK_TXT ) ; bytes = IOUtils . toByteArray ( inputStream ) ; } if ( bytes . length > 0 ) { Files . write ( Paths . get ( buildGradleTmp . getPath ( ) ) , bytes , StandardOpenOption . APPEND ) ; } else if ( lines == null ) { logger . warn ( "Could not read {}" , COPY_DEPENDENCIES_TASK_TXT ) ; } else { logger . warn ( "Could not read dependencies' tree" ) ; } } } catch ( IOException e ) { logger . error ( "Could not write into the file {}, the cause {}" , buildGradleTmp . getPath ( ) , e . getMessage ( ) ) ; hasDependencies = false ; } try { if ( inputStream != null ) { inputStream . close ( ) ; } if ( bufferedReader != null ) { bufferedReader . close ( ) ; } } catch ( IOException e ) { logger . error ( "Could close the file, cause" , e . getMessage ( ) ) ; } return hasDependencies ; }
append new task to bom file
40,561
private void runPreStepCommand ( File bomFile ) { String directory = bomFile . getParent ( ) ; String [ ] gradleCommandParams = gradleCli . getGradleCommandParams ( GradleMvnCommand . COPY_DEPENDENCIES ) ; if ( StringUtils . isNotEmpty ( directory ) && gradleCommandParams . length > 0 ) { gradleCli . runGradleCmd ( directory , gradleCommandParams , true ) ; } else { logger . warn ( "Could not run gradle command" ) ; } }
run pre step command gradle copyDependencies
40,562
private void removeTaskFromBomFile ( File buildGradleTmp ) { FileReader fileReader ; BufferedReader bufferedReader = null ; try { fileReader = new FileReader ( buildGradleTmp ) ; bufferedReader = new BufferedReader ( fileReader ) ; String currLine ; String originalLines = "" ; while ( ( currLine = bufferedReader . readLine ( ) ) != null ) { if ( currLine . equals ( TASK_COPY_DEPENDENCIES_HEADER ) ) { break ; } else { originalLines = originalLines . concat ( currLine + Constants . NEW_LINE ) ; } } if ( ! originalLines . isEmpty ( ) ) { byte [ ] bytes = originalLines . getBytes ( ) ; Files . write ( Paths . get ( buildGradleTmp . getPath ( ) ) , bytes , StandardOpenOption . WRITE , StandardOpenOption . TRUNCATE_EXISTING ) ; } } catch ( IOException e ) { logger . warn ( "Couldn't remove 'copyDependencies' task from {}, error: {}" , buildGradleTmp . getPath ( ) , e . getMessage ( ) ) ; logger . debug ( "Error: {}" , e . getStackTrace ( ) ) ; } finally { try { if ( bufferedReader != null ) { bufferedReader . close ( ) ; } } catch ( IOException e ) { logger . error ( "Could close the file, cause" , e . getMessage ( ) ) ; } } }
therefore after running the copy - dependencies task removing it from the build . gradle file
40,563
private String getSha1 ( String name , String version ) { if ( dotHexCachePath == null || name == null || version == null ) { logger . warn ( "Can't calculate SHA1, missing information: .hex-cache = {}, name = {}, version = {}" , dotHexCachePath , name , version ) ; return null ; } File tarFile = new File ( dotHexCachePath + fileSeparator + name + Constants . DASH + version + TAR_EXTENSION ) ; try { return ChecksumUtils . calculateSHA1 ( tarFile ) ; } catch ( IOException e ) { logger . warn ( "Failed calculating SHA1 of {}. Make sure HEX is installed" , tarFile . getPath ( ) ) ; logger . debug ( "Error: {}" , e . getStackTrace ( ) ) ; return null ; } }
this method is used when there s a known version
40,564
private boolean isDescendant ( DependencyInfo parentDependency , DependencyInfo childDependency ) { for ( DependencyInfo dependencyInfo : childDependency . getChildren ( ) ) { if ( dependencyInfo . equals ( parentDependency ) ) return true ; return isDescendant ( dependencyInfo , childDependency ) ; } return false ; }
avoiding circular - dependencies
40,565
public void pause ( ) { if ( hasState ( TICKING ) && ! hasState ( PAUSED ) ) { if ( DBG ) Log . v ( TAG , "pause. " + mEntries . size ( ) ) ; mContentView . animate ( ) . cancel ( ) ; addState ( PAUSED ) ; cancel ( - 1 ) ; } }
Pause . Any notification delivered here will be suspended .
40,566
public void setContentPadding ( int l , int t , int r , int b ) { mContentPadding [ 0 ] = l ; mContentPadding [ 1 ] = t ; mContentPadding [ 2 ] = r ; mContentPadding [ 3 ] = b ; }
Set padding .
40,567
public void setContentMargin ( int l , int t , int r , int b ) { mContentMargin [ 0 ] = l ; mContentMargin [ 1 ] = t ; mContentMargin [ 2 ] = r ; mContentMargin [ 3 ] = b ; }
Set margin .
40,568
public void setContentViewVisibility ( int vis ) { if ( DBG ) Log . v ( TAG , "setContentVisibility - vis=" + vis ) ; mContentView . setVisibility ( vis ) ; }
Set visibility of the contentView .
40,569
public void setContentView ( int resId ) { if ( mCurrentLayoutId != resId ) { View view = inflate ( mContext , resId , null ) ; if ( mDefaultContentView == null && resId == mCallback . getContentViewDefaultLayoutId ( this ) ) { mDefaultContentView = view ; mDefaultLayoutId = resId ; } mCurrentLayoutId = resId ; setContentView ( view ) ; } }
Set contentView .
40,570
public void setContentViewPivotX ( float x ) { if ( DBG ) Log . v ( TAG , "setContentViewPivotX - x=" + x ) ; mContentView . setPivotY ( x ) ; }
Set the x location of pivot point around which the contentView is rotated .
40,571
public void setContentViewPivotY ( float y ) { if ( DBG ) Log . v ( TAG , "setContentViewPivotY - y=" + y ) ; mContentView . setPivotY ( y ) ; }
Set the y location of pivot point around which the contentView is rotated .
40,572
public void animateContentViewRotationY ( float degree , float alpha , Animator . AnimatorListener listener , int duration ) { if ( DBG ) Log . v ( TAG , "animateContentViewRotationY - " + "degree=" + degree + ", alpha=" + alpha ) ; mContentView . animate ( ) . cancel ( ) ; mContentView . animate ( ) . alpha ( alpha ) . rotationY ( degree ) . setListener ( listener ) . setDuration ( duration ) . start ( ) ; }
Rotate the contentView to y degree with animation .
40,573
public void animateContentViewTranslationX ( float x , float alpha , Animator . AnimatorListener listener , int duration ) { if ( DBG ) Log . v ( TAG , "animateContentViewTranslationX - " + "x=" + x + ", alpha=" + alpha ) ; mContentView . animate ( ) . cancel ( ) ; mContentView . animate ( ) . alpha ( alpha ) . translationX ( x ) . setListener ( listener ) . setDuration ( duration ) . start ( ) ; }
Move the contentView to x position with animation .
40,574
public void animateContentViewTranslationY ( float y , float alpha , Animator . AnimatorListener listener , int duration ) { if ( DBG ) Log . v ( TAG , "animateContentViewTranslationY - " + "y=" + y + ", alpha=" + alpha ) ; mContentView . animate ( ) . cancel ( ) ; mContentView . animate ( ) . alpha ( alpha ) . translationY ( y ) . setListener ( listener ) . setDuration ( duration ) . start ( ) ; }
Move the contentView to y position with animation .
40,575
private void runPreStep ( String folderPath ) { Cli cli = new Cli ( ) ; boolean success = false ; List < String > compileOutput = cli . runCmd ( folderPath , cli . getCommandParams ( SBT , COMPILE ) ) ; if ( ! compileOutput . isEmpty ( ) ) { if ( compileOutput . get ( compileOutput . size ( ) - 1 ) . contains ( SUCCESS ) ) { success = true ; } } if ( ! success ) { logger . warn ( "Can't run '{} {}'" , SBT , COMPILE ) ; } }
creating the xml report using sbt compile command
40,576
private Collection < String > findTargetFolders ( String folderPath ) { logger . debug ( "Scanning target folder {}" , folderPath ) ; Cli cli = new Cli ( ) ; List < String > lines ; List < String > targetFolders = new LinkedList < > ( ) ; lines = cli . runCmd ( folderPath , cli . getCommandParams ( SBT , TARGET ) ) ; if ( lines != null && ! lines . isEmpty ( ) ) { for ( String line : lines ) { if ( DependencyCollector . isWindows ( ) ) { if ( line . endsWith ( TARGET ) && line . contains ( fileSeparator ) ) { String [ ] split = line . split ( windowsPattern ) ; targetFolders . add ( split [ 1 ] ) ; } } else { if ( line . contains ( TARGET ) && line . contains ( fileSeparator ) ) { Matcher matcher = linuxPattern . matcher ( line ) ; if ( matcher . find ( ) ) { targetFolders . add ( matcher . group ( 0 ) ) ; } } } } for ( int i = 0 ; i < targetFolders . size ( ) ; i ++ ) { String targetFolder = targetFolders . get ( i ) ; Path path = Paths . get ( targetFolder ) ; if ( ! Files . exists ( path ) ) { targetFolders . remove ( targetFolder ) ; logger . warn ( "The target folder {} path doesn't exist" , sbtTargetFolder ) ; } } } return targetFolders ; }
Trying to get all the paths of target folders
40,577
public String [ ] getDirectoryContent ( String scannerBaseDir , String [ ] includes , String [ ] excludes , boolean followSymlinks , boolean globCaseSensitive , boolean scanDirectories ) { File file = new File ( scannerBaseDir ) ; String [ ] fileNames ; if ( file . exists ( ) && file . isDirectory ( ) ) { DirectoryScanner scanner = new DirectoryScanner ( ) ; scanner . setBasedir ( scannerBaseDir ) ; scanner . setIncludes ( includes ) ; scanner . setExcludes ( excludes ) ; scanner . setFollowSymlinks ( followSymlinks ) ; scanner . setCaseSensitive ( globCaseSensitive ) ; scanner . scan ( ) ; if ( ! scanDirectories ) { fileNames = scanner . getIncludedFiles ( ) ; } else { fileNames = scanner . getIncludedDirectories ( ) ; } return fileNames ; } else { logger . debug ( "{} is not a folder" , scannerBaseDir ) ; return new String [ 0 ] ; } }
get the content of directory by includes excludes followSymlinks and globCaseSensitive the scanDirectories property define if the scanner will scan to find directories
40,578
final LoggerConfig get ( String name ) { final LoggerConfig config = new LoggerConfig ( ) ; if ( categories . isEmpty ( ) ) { config . merge ( LoggerConfig . DEFAULT ) ; return config ; } if ( name == null ) { name = "" ; } while ( true ) { final int index = name . lastIndexOf ( '.' ) ; if ( config . merge ( categories . get ( name ) ) ) return config ; if ( index != - 1 ) { name = name . substring ( 0 , index ) ; } else { if ( ! config . merge ( categories . get ( "" ) ) ) { config . merge ( LoggerConfig . DEFAULT ) ; } return config ; } } }
Returns the merged config of all matching category names for the given input using the defaults if no categories match .
40,579
final void put ( final String name , final LoggerConfig value ) { LoggerConfig config = categories . get ( name ) ; if ( config != null ) { config . merge ( value ) ; } else { categories . put ( name , value ) ; } }
Add a category to the config map .
40,580
static final String createTag ( final String name ) { if ( name . length ( ) <= MAX_TAG_LEN ) { return name ; } final char [ ] tag = name . toCharArray ( ) ; final int arrayLen = tag . length ; int len = 0 ; int mark = 0 ; for ( int i = 0 ; i < arrayLen ; i ++ , len ++ ) { if ( tag [ i ] == '.' ) { len = mark ; if ( tag [ len ] != '.' ) { len ++ ; } mark = len ; if ( i + 1 < arrayLen && tag [ i + 1 ] != '.' ) { mark ++ ; } } tag [ len ] = tag [ i ] ; } if ( len > MAX_TAG_LEN ) { int i = 0 ; mark -- ; for ( int j = 0 ; j < len ; j ++ ) { if ( tag [ j ] == '.' && ( ( j != mark ) || ( i >= MAX_TAG_LEN - 1 ) ) ) { continue ; } tag [ i ++ ] = tag [ j ] ; } len = i ; if ( len > MAX_TAG_LEN ) { len = MAX_TAG_LEN ; } } return new String ( tag , 0 , len ) ; }
Create a compatible logging tag for Android based on the logger name .
40,581
public static Batch [ ] all ( ) throws AuthenticationException , InvalidRequestException , APIConnectionException , APIException , UnsupportedEncodingException , MalformedURLException { List < Batch > all_batches = new ArrayList < Batch > ( ) ; Map < String , String > params = new HashMap < String , String > ( ) ; while ( true ) { Map < String , Object > reqParams = new HashMap < String , Object > ( params ) ; BatchCollection coll = request ( RequestMethod . GET , classURL ( Batch . class ) , reqParams , BatchCollection . class , null ) ; if ( coll . array . length == 0 ) { break ; } all_batches . addAll ( Arrays . asList ( coll . array ) ) ; if ( coll . next == null ) { break ; } params = HttpUtil . queryToParams ( new URL ( coll . next ) . getQuery ( ) ) ; } Batch [ ] array = new Batch [ all_batches . size ( ) ] ; all_batches . toArray ( array ) ; return array ; }
Get all batches created in the account .
40,582
private boolean isSchemaValid ( ) throws SQLException { logger . entering ( CLASSNAME , "isSchemaValid" ) ; Connection conn = getConnectionToDefaultSchema ( ) ; DatabaseMetaData dbmd = conn . getMetaData ( ) ; ResultSet rs = dbmd . getSchemas ( ) ; while ( rs . next ( ) ) { if ( schema . equalsIgnoreCase ( rs . getString ( "TABLE_SCHEM" ) ) ) { cleanupConnection ( conn , rs , null ) ; logger . exiting ( CLASSNAME , "isSchemaValid" , true ) ; return true ; } } cleanupConnection ( conn , rs , null ) ; logger . exiting ( CLASSNAME , "isSchemaValid" , false ) ; return false ; }
Checks if the default schema JBATCH or the schema defined in batch - config exists .
40,583
private void createSchema ( ) throws SQLException { logger . entering ( CLASSNAME , "createSchema" ) ; Connection conn = getConnectionToDefaultSchema ( ) ; logger . log ( Level . INFO , schema + " schema does not exists. Trying to create it." ) ; PreparedStatement ps = null ; ps = conn . prepareStatement ( "CREATE SCHEMA " + schema ) ; ps . execute ( ) ; cleanupConnection ( conn , null , ps ) ; logger . exiting ( CLASSNAME , "createSchema" ) ; }
Creates the default schema JBATCH or the schema defined in batch - config .
40,584
private void checkAllTables ( ) throws SQLException { logger . entering ( CLASSNAME , "checkAllTables" ) ; createIfNotExists ( CHECKPOINTDATA_TABLE , CREATE_TAB_CHECKPOINTDATA ) ; executeStatement ( CREATE_CHECKPOINTDATA_INDEX ) ; createIfNotExists ( JOBINSTANCEDATA_TABLE , CREATE_TAB_JOBINSTANCEDATA ) ; createIfNotExists ( EXECUTIONINSTANCEDATA_TABLE , CREATE_TAB_EXECUTIONINSTANCEDATA ) ; createIfNotExists ( STEPEXECUTIONINSTANCEDATA_TABLE , CREATE_TAB_STEPEXECUTIONINSTANCEDATA ) ; createIfNotExists ( JOBSTATUS_TABLE , CREATE_TAB_JOBSTATUS ) ; createIfNotExists ( STEPSTATUS_TABLE , CREATE_TAB_STEPSTATUS ) ; logger . exiting ( CLASSNAME , "checkAllTables" ) ; }
Checks if all the runtime batch table exists . If not it creates them .
40,585
private void createIfNotExists ( String tableName , String createTableStatement ) throws SQLException { logger . entering ( CLASSNAME , "createIfNotExists" , new Object [ ] { tableName , createTableStatement } ) ; Connection conn = getConnection ( ) ; DatabaseMetaData dbmd = conn . getMetaData ( ) ; ResultSet rs = dbmd . getTables ( null , schema , tableName , null ) ; PreparedStatement ps = null ; if ( ! rs . next ( ) ) { logger . log ( Level . INFO , tableName + " table does not exists. Trying to create it." ) ; ps = conn . prepareStatement ( createTableStatement ) ; ps . executeUpdate ( ) ; } cleanupConnection ( conn , rs , ps ) ; logger . exiting ( CLASSNAME , "createIfNotExists" ) ; }
Creates tableName using the createTableStatement DDL .
40,586
private void executeStatement ( String statement ) throws SQLException { logger . entering ( CLASSNAME , "executeStatement" , statement ) ; Connection conn = getConnection ( ) ; PreparedStatement ps = null ; ps = conn . prepareStatement ( statement ) ; ps . executeUpdate ( ) ; cleanupConnection ( conn , ps ) ; logger . exiting ( CLASSNAME , "executeStatement" ) ; }
Executes the provided SQL statement
40,587
private void setSchemaOnConnection ( Connection connection ) throws SQLException { logger . finest ( "Entering " + CLASSNAME + ".setSchemaOnConnection()" ) ; String dbProductName = connection . getMetaData ( ) . getDatabaseProductName ( ) ; if ( ! "Oracle" . equals ( dbProductName ) && ! "Microsoft SQL Server" . equals ( dbProductName ) ) { PreparedStatement ps = null ; if ( "MySQL" . equals ( dbProductName ) ) { ps = connection . prepareStatement ( "USE " + schema ) ; } else { ps = connection . prepareStatement ( "SET SCHEMA ?" ) ; ps . setString ( 1 , schema ) ; } ps . executeUpdate ( ) ; ps . close ( ) ; } logger . finest ( "Exiting " + CLASSNAME + ".setSchemaOnConnection()" ) ; }
Set the default schema JBATCH or the schema defined in batch - config on the connection object .
40,588
private CheckpointData queryCheckpointData ( Object key ) { logger . entering ( CLASSNAME , "queryCheckpointData" , new Object [ ] { key , SELECT_CHECKPOINTDATA } ) ; Connection conn = null ; PreparedStatement statement = null ; ResultSet rs = null ; ObjectInputStream objectIn = null ; CheckpointData data = null ; try { conn = getConnection ( ) ; statement = conn . prepareStatement ( SELECT_CHECKPOINTDATA ) ; statement . setObject ( 1 , key ) ; rs = statement . executeQuery ( ) ; if ( rs . next ( ) ) { byte [ ] buf = rs . getBytes ( "obj" ) ; data = ( CheckpointData ) deserializeObject ( buf ) ; } } catch ( SQLException e ) { throw new PersistenceException ( e ) ; } catch ( IOException e ) { throw new PersistenceException ( e ) ; } catch ( ClassNotFoundException e ) { throw new PersistenceException ( e ) ; } finally { if ( objectIn != null ) { try { objectIn . close ( ) ; } catch ( IOException e ) { throw new PersistenceException ( e ) ; } } cleanupConnection ( conn , rs , statement ) ; } logger . exiting ( CLASSNAME , "queryCheckpointData" ) ; return data ; }
select data from DB table
40,589
private < T > void insertCheckpointData ( Object key , T value ) { logger . entering ( CLASSNAME , "insertCheckpointData" , new Object [ ] { key , value } ) ; Connection conn = null ; PreparedStatement statement = null ; ByteArrayOutputStream baos = null ; ObjectOutputStream oout = null ; byte [ ] b ; try { conn = getConnection ( ) ; statement = conn . prepareStatement ( INSERT_CHECKPOINTDATA ) ; baos = new ByteArrayOutputStream ( ) ; oout = new ObjectOutputStream ( baos ) ; oout . writeObject ( value ) ; b = baos . toByteArray ( ) ; statement . setObject ( 1 , key ) ; statement . setBytes ( 2 , b ) ; statement . executeUpdate ( ) ; } catch ( SQLException e ) { throw new PersistenceException ( e ) ; } catch ( IOException e ) { throw new PersistenceException ( e ) ; } finally { if ( baos != null ) { try { baos . close ( ) ; } catch ( IOException e ) { throw new PersistenceException ( e ) ; } } if ( oout != null ) { try { oout . close ( ) ; } catch ( IOException e ) { throw new PersistenceException ( e ) ; } } cleanupConnection ( conn , null , statement ) ; } logger . exiting ( CLASSNAME , "insertCheckpointData" ) ; }
insert data to DB table
40,590
private void cleanupConnection ( Connection conn , ResultSet rs , PreparedStatement statement ) { logger . logp ( Level . FINEST , CLASSNAME , "cleanupConnection" , "Entering" , new Object [ ] { conn , rs == null ? "<null>" : rs , statement == null ? "<null>" : statement } ) ; if ( statement != null ) { try { statement . close ( ) ; } catch ( SQLException e ) { throw new PersistenceException ( e ) ; } } if ( rs != null ) { try { rs . close ( ) ; } catch ( SQLException e ) { throw new PersistenceException ( e ) ; } } if ( conn != null ) { try { conn . close ( ) ; } catch ( SQLException e ) { throw new PersistenceException ( e ) ; } finally { try { conn . close ( ) ; } catch ( SQLException e ) { throw new PersistenceException ( e ) ; } } } logger . logp ( Level . FINEST , CLASSNAME , "cleanupConnection" , "Exiting" ) ; }
closes connection result set and statement
40,591
private String getPartitionLevelJobInstanceWildCard ( long rootJobInstanceId , String stepName ) { StringBuilder sb = new StringBuilder ( ":" ) ; sb . append ( Long . toString ( rootJobInstanceId ) ) ; sb . append ( ":" ) ; sb . append ( stepName ) ; sb . append ( ":%" ) ; return sb . toString ( ) ; }
Obviously would be nice if the code writing this special format were in the same place as this code reading it .
40,592
private static String unwrapFutureString ( CompletionStage < String > future ) throws GetBytesException { try { return future . toCompletableFuture ( ) . get ( ) ; } catch ( Throwable e ) { if ( e . getCause ( ) instanceof GetBytesException ) { throw ( GetBytesException ) e . getCause ( ) ; } throw new RuntimeException ( e . getCause ( ) ) ; } }
Waits for a CompletionStage for non - async methods .
40,593
public CompletionStage < String > detectMimeTypeAsync ( String filename , Supplier < CompletionStage < byte [ ] > > getBytesAsync ) { Set < WeightedMimeType > weightedMimeTypes = filenameToWmts ( filename ) ; Set < String > globMimeTypes = findBestMimeTypes ( weightedMimeTypes ) ; if ( globMimeTypes . size ( ) == 1 ) { return CompletableFuture . completedFuture ( globMimeTypes . iterator ( ) . next ( ) ) ; } return getBytesAsync . get ( ) . thenApply ( bytes -> { for ( String magicMimeType : bytesToMimeTypes ( bytes ) ) { if ( globMimeTypes . isEmpty ( ) ) { return magicMimeType ; } else { for ( String globMimeType : globMimeTypes ) { if ( isMimeTypeEqualOrSubclass ( globMimeType , magicMimeType ) ) { return globMimeType ; } } } } if ( isText ( bytes ) ) { return "text/plain" ; } return "application/octet-stream" ; } ) . exceptionally ( ex -> { throw new CompletionException ( new GetBytesException ( ex ) ) ; } ) ; }
Detects a MIME type from a filename and bytes .
40,594
public String detectMimeType ( String filename , Callable < byte [ ] > getBytes ) throws GetBytesException { Supplier < CompletionStage < byte [ ] > > supplier = ( ) -> { try { return CompletableFuture . completedFuture ( getBytes . call ( ) ) ; } catch ( Exception ex ) { throw new CompletionException ( ex ) ; } } ; return unwrapFutureString ( detectMimeTypeAsync ( filename , supplier ) ) ; }
Synchronously detects a MIME type from a filename and bytes .
40,595
public String detectMimeType ( String filename , final InputStream is ) throws GetBytesException { Callable < byte [ ] > getBytes = new Callable < byte [ ] > ( ) { public byte [ ] call ( ) throws IOException { return inputStreamToFirstBytes ( is ) ; } } ; return detectMimeType ( filename , getBytes ) ; }
Determines the MIME type of a file with a given input stream .
40,596
public CompletionStage < String > detectMimeTypeAsync ( final Path path ) { String filename = path . getFileName ( ) . toString ( ) ; Supplier < CompletionStage < byte [ ] > > supplier = ( ) -> { final CompletableFuture < byte [ ] > futureBytes = new CompletableFuture < byte [ ] > ( ) ; AsynchronousFileChannel channel ; try { channel = AsynchronousFileChannel . open ( path , StandardOpenOption . READ ) ; } catch ( IOException e ) { futureBytes . completeExceptionally ( new GetBytesException ( e ) ) ; return futureBytes ; } final ByteBuffer buf = ByteBuffer . allocate ( getMaxGetBytesLength ( ) ) ; channel . read ( buf , 0 , futureBytes , new CompletionHandler < Integer , CompletableFuture < byte [ ] > > ( ) { public void completed ( Integer nBytes , CompletableFuture < byte [ ] > f ) { if ( nBytes == - 1 ) nBytes = 0 ; byte [ ] bytes = new byte [ nBytes ] ; buf . rewind ( ) ; buf . get ( bytes , 0 , nBytes ) ; f . complete ( bytes ) ; } public void failed ( Throwable exc , CompletableFuture < byte [ ] > f ) { f . completeExceptionally ( new GetBytesException ( exc ) ) ; } } ) ; return futureBytes ; } ; return detectMimeTypeAsync ( filename , supplier ) ; }
Determines the MIME type of a file .
40,597
private boolean matchletMagicCompareOr ( int nMatchlets , int firstMatchletOffset , byte [ ] data ) { for ( int i = 0 , matchletOffset = firstMatchletOffset ; i < nMatchlets ; i ++ , matchletOffset += 32 ) { if ( matchletMagicCompare ( matchletOffset , data ) ) { return true ; } } return false ; }
Returns whether one of the specified matchlets matches the data .
40,598
private boolean subArraysEqual ( byte [ ] a , int aStart , byte [ ] b , int bStart , int len ) { for ( int i = aStart , j = bStart ; len > 0 ; i ++ , j ++ , len -- ) { if ( a [ i ] != b [ j ] ) { return false ; } } return true ; }
Returns true if subarrays are equal .
40,599
private boolean subArraysEqualWithMask ( byte [ ] a , int aStart , byte [ ] b , int bStart , byte [ ] mask , int maskStart , int len ) { for ( int i = aStart , j = bStart , k = maskStart ; len > 0 ; i ++ , j ++ , k ++ , len -- ) { if ( ( a [ i ] & mask [ k ] ) != ( b [ j ] & mask [ k ] ) ) { return false ; } } return true ; }
Returns true if subarrays are equal with the given mask .