idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
19,300
@ Deprecated public void setEmpty ( ) { mState = STATE_EMPTY ; mProgress . setVisibility ( View . GONE ) ; if ( mEmptyIcon != - 1 ) mIcon . setVisibility ( View . VISIBLE ) ; if ( ! TextUtils . isEmpty ( mEmptyMessage ) ) mMessage . setVisibility ( View . VISIBLE ) ; if ( ! TextUtils . isEmpty ( mEmptyActionText ) ) mAction . setVisibility ( View . VISIBLE ) ; }
Set this view to it s empty state showing the icon message and action if configured
111
16
19,301
private View getNextView ( RecyclerView parent ) { View firstView = parent . getChildAt ( 0 ) ; // draw the first visible child's header at the top of the view int firstPosition = parent . getChildPosition ( firstView ) ; View firstHeader = getHeaderView ( parent , firstPosition ) ; for ( int i = 0 ; i < parent . getChildCount ( ) ; i ++ ) { View child = parent . getChildAt ( i ) ; RecyclerView . LayoutParams layoutParams = ( RecyclerView . LayoutParams ) child . getLayoutParams ( ) ; if ( getOrientation ( parent ) == LinearLayoutManager . VERTICAL ) { if ( child . getTop ( ) - layoutParams . topMargin > firstHeader . getHeight ( ) ) { return child ; } } else { if ( child . getLeft ( ) - layoutParams . leftMargin > firstHeader . getWidth ( ) ) { return child ; } } } return null ; }
Returns the first item currently in the recyclerview that s not obscured by a header .
220
19
19,302
@ SuppressLint ( "NewApi" ) private void buildAndAttach ( ) { // Disable any pending transition on the activity since we are transforming it mActivity . overridePendingTransition ( 0 , 0 ) ; // Setup window flags if Lollipop if ( BuildUtils . isLollipop ( ) ) { Window window = mActivity . getWindow ( ) ; window . addFlags ( FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS ) ; window . setStatusBarColor ( Color . TRANSPARENT ) ; } // attach layout and pane to UI hiJackDecor ( ) ; // Setup setupDrawer ( ) ; // Populate and Inflate populateNavDrawer ( ) ; }
Build the nav drawer layout inflate it then attach it to the activity
156
14
19,303
private void setupDrawer ( ) { // Setup drawer background color if set int backgroundColor = UIUtils . getColorAttr ( mActivity , R . attr . drawerBackground ) ; if ( backgroundColor > 0 ) { mDrawerPane . setBackgroundColor ( backgroundColor ) ; } // Set the drawer layout statusbar color int statusBarColor = mConfig . getStatusBarColor ( mActivity ) ; if ( statusBarColor != - 1 ) mDrawerLayout . setStatusBarBackgroundColor ( statusBarColor ) ; // Populate Header View populateHeader ( ) ; // Populate Footer View populateFooter ( ) ; // Configure the scrim inset pane view final int headerHeight = mActivity . getResources ( ) . getDimensionPixelSize ( R . dimen . navdrawer_chosen_account_height ) ; mDrawerPane . setOnInsetsCallback ( new OnInsetsCallback ( ) { @ Override public void onInsetsChanged ( Rect insets ) { if ( mHeaderView != null ) { mConfig . onInsetsChanged ( mHeaderView , insets ) ; ViewGroup . LayoutParams lp2 = mDrawerHeaderFrame . getLayoutParams ( ) ; lp2 . height = headerHeight + insets . top ; mDrawerHeaderFrame . setLayoutParams ( lp2 ) ; } else { ViewGroup . LayoutParams lp2 = mDrawerHeaderFrame . getLayoutParams ( ) ; lp2 . height = insets . top ; mDrawerHeaderFrame . setLayoutParams ( lp2 ) ; } } } ) ; // Setup the drawer toggle if ( mToolbar != null ) { mDrawerToggle = new ActionBarDrawerToggle ( mActivity , mDrawerLayout , mToolbar , R . string . navigation_drawer_open , R . string . navigation_drawer_close ) { @ Override public void onDrawerClosed ( View drawerView ) { super . onDrawerClosed ( drawerView ) ; if ( mCallbacks != null ) mCallbacks . onDrawerClosed ( drawerView ) ; } @ Override public void onDrawerOpened ( View drawerView ) { super . onDrawerOpened ( drawerView ) ; if ( mCallbacks != null ) mCallbacks . onDrawerOpened ( drawerView ) ; } @ Override public void onDrawerSlide ( View drawerView , float slideOffset ) { super . onDrawerSlide ( drawerView , mConfig . shouldAnimateIndicator ( ) ? slideOffset : 0 ) ; if ( mCallbacks != null ) mCallbacks . onDrawerSlide ( drawerView , slideOffset ) ; } } ; // Defer code dependent on restoration of previous instance state. mDrawerLayout . post ( new Runnable ( ) { @ Override public void run ( ) { mDrawerToggle . syncState ( ) ; } } ) ; mDrawerLayout . setDrawerListener ( mDrawerToggle ) ; } // Setup the drawer shadow mDrawerLayout . setDrawerShadow ( R . drawable . drawer_shadow , GravityCompat . START ) ; }
Setup the navigation drawer layout and whatnot
691
8
19,304
private void createNavDrawerItems ( ) { if ( mDrawerItemsListContainer == null ) { return ; } mNavDrawerItemViews . clear ( ) ; mDrawerItemsListContainer . removeAllViews ( ) ; for ( DrawerItem item : mDrawerItems ) { item . setSelected ( item . getId ( ) == mSelectedItem ) ; View view = item . onCreateView ( mActivity . getLayoutInflater ( ) , mDrawerItemsListContainer , mConfig . getItemHighlightColor ( mActivity ) ) ; if ( ! ( item instanceof SeperatorDrawerItem ) ) { view . setId ( item . getId ( ) ) ; mNavDrawerItemViews . put ( item . getId ( ) , view ) ; mNavDrawerItems . put ( item . getId ( ) , item ) ; // Set the view's click listener if ( ! ( item instanceof SwitchDrawerItem ) ) { view . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { onNavDrawerItemClicked ( v . getId ( ) ) ; } } ) ; } } mDrawerItemsListContainer . addView ( view ) ; } }
Populate the nav drawer items into the view
277
9
19,305
private void onNavDrawerItemClicked ( final int itemId ) { if ( itemId == mSelectedItem ) { mDrawerLayout . closeDrawer ( GravityCompat . START ) ; return ; } if ( isSpecialItem ( itemId ) ) { goToNavDrawerItem ( itemId ) ; } else { // launch the target Activity after a short delay, to allow the close animation to play mHandler . postDelayed ( new Runnable ( ) { @ Override public void run ( ) { goToNavDrawerItem ( itemId ) ; } } , mConfig . getLaunchDelay ( ) ) ; // change the active item on the list so the user can see the item changed setSelectedNavDrawerItem ( itemId ) ; // fade out the main content // if (mMainContent != null && mConfig.getFadeOutDuration() != -1) { // mMainContent.animate().alpha(0).setDuration(mConfig.getFadeOutDuration()); // } } mDrawerLayout . closeDrawer ( GravityCompat . START ) ; }
Call when a nav drawer item is clicked
234
8
19,306
private void formatNavDrawerItem ( DrawerItem item , boolean selected ) { if ( item instanceof SeperatorDrawerItem || item instanceof SwitchDrawerItem ) { // not applicable return ; } // Get the associated view View view = mNavDrawerItemViews . get ( item . getId ( ) ) ; ImageView iconView = ( ImageView ) view . findViewById ( R . id . icon ) ; TextView titleView = ( TextView ) view . findViewById ( R . id . title ) ; // configure its appearance according to whether or not it's selected titleView . setTextColor ( selected ? mConfig . getItemHighlightColor ( mActivity ) : UIUtils . getColorAttr ( mActivity , android . R . attr . textColorPrimary ) ) ; iconView . setColorFilter ( selected ? mConfig . getItemHighlightColor ( mActivity ) : getResources ( ) . getColor ( R . color . navdrawer_icon_tint ) , PorterDuff . Mode . SRC_ATOP ) ; }
Format a nav drawer item based on current selected states
230
10
19,307
private DrawerLayout inflateDrawerLayout ( ViewGroup parent ) { DrawerLayout drawer = ( DrawerLayout ) mActivity . getLayoutInflater ( ) . inflate ( R . layout . material_drawer , parent , false ) ; // Find the associated views mDrawerPane = ButterKnife . findById ( drawer , R . id . navdrawer ) ; mDrawerContentFrame = ButterKnife . findById ( drawer , R . id . drawer_content_frame ) ; mDrawerHeaderFrame = ButterKnife . findById ( mDrawerPane , R . id . header_container ) ; mDrawerFooterFrame = ButterKnife . findById ( mDrawerPane , R . id . footer ) ; mDrawerItemsListContainer = ButterKnife . findById ( mDrawerPane , R . id . navdrawer_items_list ) ; // Return the drawer return drawer ; }
Build the root drawer layout
205
5
19,308
@ Override protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { Drawable drawable = getDrawable ( ) ; if ( getDrawable ( ) != null ) { if ( ratioType == RATIO_WIDTH ) { int width = MeasureSpec . getSize ( widthMeasureSpec ) ; int height = Math . round ( width * ( ( ( float ) drawable . getIntrinsicHeight ( ) ) / ( ( float ) drawable . getIntrinsicWidth ( ) ) ) ) ; setMeasuredDimension ( width , height ) ; } else if ( ratioType == RATIO_HEIGHT ) { int height = MeasureSpec . getSize ( heightMeasureSpec ) ; int width = Math . round ( height * ( ( float ) drawable . getIntrinsicWidth ( ) ) / ( ( float ) drawable . getIntrinsicHeight ( ) ) ) ; setMeasuredDimension ( width , height ) ; } } else { super . onMeasure ( widthMeasureSpec , heightMeasureSpec ) ; } }
Maintain Image Aspect Ratio no matter the size
230
10
19,309
public static int getStatusBarHeight ( Context ctx ) { int result = 0 ; int resourceId = ctx . getResources ( ) . getIdentifier ( "status_bar_height" , "dimen" , "android" ) ; if ( resourceId > 0 ) { result = ctx . getResources ( ) . getDimensionPixelSize ( resourceId ) ; } return result ; }
Get the status bar height
85
5
19,310
protected void onItemClick ( View view , int position ) { if ( itemClickListener != null ) itemClickListener . onItemClick ( view , getItem ( position ) , position ) ; }
Call this to trigger the user set item click listener
41
10
19,311
protected void onItemLongClick ( View view , int position ) { if ( itemLongClickListener != null ) itemLongClickListener . onItemLongClick ( view , getItem ( position ) , position ) ; }
Call this to trigger the user set item long click lisetner
45
14
19,312
public void setEmptyView ( View emptyView ) { if ( this . emptyView != null ) { unregisterAdapterDataObserver ( mEmptyObserver ) ; } this . emptyView = emptyView ; registerAdapterDataObserver ( mEmptyObserver ) ; }
Set the empty view to be used so that
56
9
19,313
private void checkIfEmpty ( ) { if ( emptyView != null ) { emptyView . setVisibility ( getItemCount ( ) > 0 ? View . GONE : View . VISIBLE ) ; } }
Check if we should show the empty view
44
8
19,314
public void addAll ( Collection < ? extends M > collection ) { if ( collection != null ) { items . addAll ( collection ) ; applyFilter ( ) ; } }
Add a collection of objects to this adapter
36
8
19,315
public M remove ( int index ) { M item = items . remove ( index ) ; applyFilter ( ) ; return item ; }
Remove an item at the given index
27
7
19,316
public void moveItem ( int start , int end ) { M startItem = filteredItems . get ( start ) ; M endItem = filteredItems . get ( end ) ; int realStart = items . indexOf ( startItem ) ; int realEnd = items . indexOf ( endItem ) ; Collections . swap ( items , realStart , realEnd ) ; applyFilter ( ) ; onItemMoved ( startItem , realStart , realEnd ) ; notifyItemMoved ( realStart , realEnd ) ; }
Move an item around in the underlying array
108
8
19,317
private void applyFilter ( ) { filteredItems . clear ( ) ; Filter < M > filter = getFilter ( ) ; if ( filter == null ) { filteredItems . addAll ( items ) ; } else { for ( int i = 0 ; i < items . size ( ) ; i ++ ) { M item = items . get ( i ) ; if ( filter . filter ( item , query ) ) { filteredItems . add ( item ) ; } } } onFiltered ( ) ; }
Apply the filter if possible to the adapter to update content
103
11
19,318
@ Override public void onBindViewHolder ( final VH vh , final int i ) { if ( itemClickListener != null ) { vh . itemView . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { int position = vh . getAdapterPosition ( ) ; if ( position != RecyclerView . NO_POSITION ) { itemClickListener . onItemClick ( v , getItem ( position ) , position ) ; } } } ) ; } if ( itemLongClickListener != null ) { vh . itemView . setOnLongClickListener ( new View . OnLongClickListener ( ) { @ Override public boolean onLongClick ( View v ) { int position = vh . getAdapterPosition ( ) ; if ( position != RecyclerView . NO_POSITION ) { return itemLongClickListener . onItemLongClick ( v , getItem ( position ) , position ) ; } return false ; } } ) ; } }
Intercept the bind View holder method to wire up the item click listener only if the listener is set by the user
219
23
19,319
@ Override public long getItemId ( int position ) { if ( position > RecyclerView . NO_ID && position < getItemCount ( ) ) { M item = getItem ( position ) ; if ( item != null ) return item . hashCode ( ) ; return position ; } return RecyclerView . NO_ID ; }
Get the item Id for a given position
73
8
19,320
public static Intent createIntent ( Context ctx , int logoResId , CharSequence eulaText ) { Intent intent = new Intent ( ctx , EulaActivity . class ) ; intent . putExtra ( EXTRA_LOGO , logoResId ) ; intent . putExtra ( EXTRA_EULA_TEXT , eulaText ) ; return intent ; }
Generate a pre - populated intent to launch this activity with
79
12
19,321
public String getLicenseText ( ) { if ( license != null ) { return license . getLicense ( description , year , author , email ) ; } return "N/A" ; }
Get the formatted license text for display
39
7
19,322
public static Intent getCameraCaptureIntent ( Context ctx , String authority ) { Intent intent = new Intent ( MediaStore . ACTION_IMAGE_CAPTURE ) ; try { // Get the app's local file storage mCurrentCaptureUri = createAccessibleTempFile ( ctx , authority ) ; grantPermissions ( ctx , mCurrentCaptureUri ) ; intent . putExtra ( MediaStore . EXTRA_OUTPUT , mCurrentCaptureUri ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return intent ; }
Generate the appropriate intent to launch the existing camera application to capture an image
122
15
19,323
public static Intent getChooseMediaIntent ( String mimeType ) { Intent intent = new Intent ( Intent . ACTION_GET_CONTENT ) ; intent . addCategory ( Intent . CATEGORY_OPENABLE ) ; intent . setType ( mimeType ) ; return intent ; }
Generate the appropriate intent to launch the document chooser to allow the user to pick an image to upload .
62
22
19,324
public static Observable < File > handleActivityResult ( final Context context , int resultCode , int requestCode , Intent data ) { if ( resultCode == Activity . RESULT_OK ) { switch ( requestCode ) { case CAPTURE_PHOTO_REQUEST_CODE : if ( mCurrentCaptureUri != null ) { revokePermissions ( context , mCurrentCaptureUri ) ; File file = getAccessibleTempFile ( context , mCurrentCaptureUri ) ; mCurrentCaptureUri = null ; return Observable . just ( file ) ; } return Observable . error ( new FileNotFoundException ( "Unable to find camera capture" ) ) ; case PICK_MEDIA_REQUEST_CODE : final Uri mediaUri = data . getData ( ) ; final String fileName = getFileName ( context , mediaUri ) ; if ( mediaUri != null ) { return Observable . fromCallable ( new Callable < File > ( ) { @ Override public File call ( ) throws Exception { ParcelFileDescriptor parcelFileDescriptor = null ; try { parcelFileDescriptor = context . getContentResolver ( ) . openFileDescriptor ( mediaUri , "r" ) ; // Now that we have the file description, get the associated input stream FileDescriptor fileDescriptor = parcelFileDescriptor . getFileDescriptor ( ) ; FileInputStream fis = new FileInputStream ( fileDescriptor ) ; FileOutputStream fos = null ; // Generate temporary output file and output file data to it try { File tempFile = createTempFile ( context , fileName ) ; fos = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 1024 ] ; int len ; while ( ( len = fis . read ( buffer ) ) > 0 ) { fos . write ( buffer , 0 , len ) ; } return tempFile ; } catch ( IOException e ) { throw OnErrorThrowable . from ( e ) ; } finally { try { parcelFileDescriptor . close ( ) ; fis . close ( ) ; if ( fos != null ) { fos . close ( ) ; } } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } } catch ( FileNotFoundException e ) { throw OnErrorThrowable . from ( e ) ; } } } ) . compose ( RxUtils . < File > applyWorkSchedulers ( ) ) ; } return Observable . error ( new FileNotFoundException ( "Unable to load selected file" ) ) ; default : return Observable . empty ( ) ; } } return Observable . empty ( ) ; }
Handle the activity result of an intent launched to capture a photo or choose an image
586
16
19,325
private static Uri createAccessibleTempFile ( Context ctx , String authority ) throws IOException { File dir = new File ( ctx . getCacheDir ( ) , "camera" ) ; File tmp = createTempFile ( dir ) ; // Give permissions return FileProvider . getUriForFile ( ctx , authority , tmp ) ; }
Generate an accessible temporary file URI to be used for camera captures
72
13
19,326
private static void grantPermissions ( Context ctx , Uri uri ) { Intent intent = new Intent ( MediaStore . ACTION_IMAGE_CAPTURE ) ; List < ResolveInfo > resolvedIntentActivities = ctx . getPackageManager ( ) . queryIntentActivities ( intent , PackageManager . MATCH_DEFAULT_ONLY ) ; for ( ResolveInfo resolvedIntentInfo : resolvedIntentActivities ) { String packageName = resolvedIntentInfo . activityInfo . packageName ; // Grant Permissions ctx . grantUriPermission ( packageName , uri , Intent . FLAG_GRANT_WRITE_URI_PERMISSION | Intent . FLAG_GRANT_READ_URI_PERMISSION ) ; } }
Grant URI permissions for all potential camera applications that can handle the capture intent .
164
15
19,327
private static void revokePermissions ( Context ctx , Uri uri ) { ctx . revokeUriPermission ( uri , Intent . FLAG_GRANT_WRITE_URI_PERMISSION | Intent . FLAG_GRANT_READ_URI_PERMISSION ) ; }
Revoke URI permissions to a specific URI that had been previously granted
63
13
19,328
public static String cleanFilename ( String fileName ) { int lastIndex = fileName . lastIndexOf ( "." ) ; return fileName . substring ( 0 , lastIndex ) ; }
Clean the extension off of the file name .
40
9
19,329
public static boolean isEmulator ( ) { return "google_sdk" . equals ( Build . PRODUCT ) || Build . PRODUCT . contains ( "sdk_google_phone" ) || "sdk" . equals ( Build . PRODUCT ) || "sdk_x86" . equals ( Build . PRODUCT ) || "vbox86p" . equals ( Build . PRODUCT ) ; }
Return whether or not the current device is an emulator
82
10
19,330
public static int getGMTOffset ( ) { Calendar now = Calendar . getInstance ( ) ; return ( now . get ( Calendar . ZONE_OFFSET ) + now . get ( Calendar . DST_OFFSET ) ) / 3600000 ; }
Get the Device s GMT Offset
52
7
19,331
public static String getMimeType ( String url ) { String type = null ; String extension = MimeTypeMap . getFileExtensionFromUrl ( url ) ; if ( extension != null ) { MimeTypeMap mime = MimeTypeMap . getSingleton ( ) ; type = mime . getMimeTypeFromExtension ( extension ) ; } return type ; }
Get the MIME type of a file
81
8
19,332
public static float distance ( PointF p1 , PointF p2 ) { return ( float ) Math . sqrt ( Math . pow ( ( p2 . x - p1 . x ) , 2 ) + Math . pow ( p2 . y - p1 . y , 2 ) ) ; }
Compute the distance between two points
63
7
19,333
public static float parseFloat ( String val , float defVal ) { if ( TextUtils . isEmpty ( val ) ) return defVal ; try { return Float . parseFloat ( val ) ; } catch ( NumberFormatException e ) { return defVal ; } }
Parse a float from a String in a safe manner .
56
12
19,334
public static int parseInt ( String val , int defValue ) { if ( TextUtils . isEmpty ( val ) ) return defValue ; try { return Integer . parseInt ( val ) ; } catch ( NumberFormatException e ) { return defValue ; } }
Parse a int from a String in a safe manner .
56
12
19,335
public static long parseLong ( String val , long defValue ) { if ( TextUtils . isEmpty ( val ) ) return defValue ; try { return Long . parseLong ( val ) ; } catch ( NumberFormatException e ) { return defValue ; } }
Parse a long from a String in a safe manner .
56
12
19,336
public static double parseDouble ( String val , double defValue ) { if ( TextUtils . isEmpty ( val ) ) return defValue ; try { return Double . parseDouble ( val ) ; } catch ( NumberFormatException e ) { return defValue ; } }
Parse a double from a String in a safe manner
56
11
19,337
private void configAppBar ( ) { setSupportActionBar ( mAppbar ) ; getSupportActionBar ( ) . setDisplayHomeAsUpEnabled ( true ) ; getSupportActionBar ( ) . setTitle ( R . string . changelog_activity_title ) ; mAppbar . setNavigationOnClickListener ( this ) ; }
Configure the Appbar
73
5
19,338
public static void apply ( TextView textView , Face type ) { // First check for existing typefaces Typeface typeface = getTypeface ( textView . getContext ( ) , type ) ; if ( typeface != null ) textView . setTypeface ( typeface ) ; }
Apply a typeface to a textview
60
8
19,339
public static void apply ( Face type , TextView ... textViews ) { if ( textViews . length == 0 ) return ; for ( int i = 0 ; i < textViews . length ; i ++ ) { apply ( textViews [ i ] , type ) ; } }
Apply a typeface to one or many textviews
61
10
19,340
public static Typeface getTypeface ( Context ctx , Face type ) { return getTypeface ( ctx , "fonts/" + type . getFontFileName ( ) ) ; }
Get a Roboto typeface for a given string type
40
11
19,341
public void start ( ) { eb = vertx . eventBus ( ) ; config = config ( ) ; FileResolver . getInstance ( ) . setBasePath ( config ) ; }
Start the busmod
39
4
19,342
public Plan makeSelectPlan ( ) { Plan p = makeIndexSelectPlan ( ) ; if ( p == null ) p = tp ; return addSelectPredicate ( p ) ; }
Constructs a select plan for the table . The plan will use an indexselect if possible .
39
19
19,343
public Plan makeJoinPlan ( Plan trunk ) { Schema trunkSch = trunk . schema ( ) ; Predicate joinPred = pred . joinPredicate ( sch , trunkSch ) ; if ( joinPred == null ) return null ; Plan p = makeIndexJoinPlan ( trunk , trunkSch ) ; if ( p == null ) p = makeProductJoinPlan ( trunk , trunkSch ) ; return p ; }
Constructs a join plan of the specified trunk and this table . The plan will use an indexjoin if possible ; otherwise a multi - buffer product join . The method returns null if no join is possible .
85
41
19,344
public Plan makeProductPlan ( Plan trunk ) { Plan p = makeSelectPlan ( ) ; return new MultiBufferProductPlan ( trunk , p , tx ) ; }
Constructs a product plan of the specified trunk and this table .
34
13
19,345
public AccountService getAccountService ( ) { if ( _accountService == null ) { synchronized ( CCApi2 . class ) { if ( _accountService == null ) { _accountService = _retrofit . create ( AccountService . class ) ; } } } return _accountService ; }
Gets the account service .
63
6
19,346
public CampaignService getCampaignService ( ) { if ( _campaignService == null ) { synchronized ( CCApi2 . class ) { if ( _campaignService == null ) { _campaignService = _retrofit . create ( CampaignService . class ) ; } } } return _campaignService ; }
Gets the campaign service .
63
6
19,347
public ContactService getContactService ( ) { if ( _contactService == null ) { synchronized ( CCApi2 . class ) { if ( _contactService == null ) { _contactService = _retrofit . create ( ContactService . class ) ; } } } return _contactService ; }
Gets the contact service .
63
6
19,348
public LibraryService getLibraryService ( ) { if ( _libraryService == null ) { synchronized ( CCApi2 . class ) { if ( _libraryService == null ) { _libraryService = _retrofit . create ( LibraryService . class ) ; } } } return _libraryService ; }
Gets the library service .
63
6
19,349
public CampaignTrackingService getCampaignTrackingService ( ) { if ( _campaignTrackingService == null ) { synchronized ( CCApi2 . class ) { if ( _campaignTrackingService == null ) { _campaignTrackingService = _retrofit . create ( CampaignTrackingService . class ) ; } } } return _campaignTrackingService ; }
Gets the campaign tracking service .
77
7
19,350
public ContactTrackingService getContactTrackingService ( ) { if ( _contactTrackingService == null ) { synchronized ( CCApi2 . class ) { if ( _contactTrackingService == null ) { _contactTrackingService = _retrofit . create ( ContactTrackingService . class ) ; } } } return _contactTrackingService ; }
Gets the contact tracking service .
77
7
19,351
public BulkActivitiesService getBulkActivitiesService ( ) { if ( _bulkActivitiesService == null ) { synchronized ( CCApi2 . class ) { if ( _bulkActivitiesService == null ) { _bulkActivitiesService = _retrofit . create ( BulkActivitiesService . class ) ; } } } return _bulkActivitiesService ; }
Gets the bulk activities service .
82
7
19,352
public void createTable ( String tblName , Schema sch , Transaction tx ) { if ( tblName != TCAT_TBLNAME && tblName != FCAT_TBLNAME ) formatFileHeader ( tblName , tx ) ; // Optimization: store the ti tiMap . put ( tblName , new TableInfo ( tblName , sch ) ) ; // insert one record into tblcat RecordFile tcatfile = tcatInfo . open ( tx , true ) ; tcatfile . insert ( ) ; tcatfile . setVal ( TCAT_TBLNAME , new VarcharConstant ( tblName ) ) ; tcatfile . close ( ) ; // insert a record into fldcat for each field RecordFile fcatfile = fcatInfo . open ( tx , true ) ; for ( String fldname : sch . fields ( ) ) { fcatfile . insert ( ) ; fcatfile . setVal ( FCAT_TBLNAME , new VarcharConstant ( tblName ) ) ; fcatfile . setVal ( FCAT_FLDNAME , new VarcharConstant ( fldname ) ) ; fcatfile . setVal ( FCAT_TYPE , new IntegerConstant ( sch . type ( fldname ) . getSqlType ( ) ) ) ; fcatfile . setVal ( FCAT_TYPEARG , new IntegerConstant ( sch . type ( fldname ) . getArgument ( ) ) ) ; } fcatfile . close ( ) ; }
Creates a new table having the specified name and schema .
334
12
19,353
public void dropTable ( String tblName , Transaction tx ) { // Remove the file RecordFile rf = getTableInfo ( tblName , tx ) . open ( tx , true ) ; rf . remove ( ) ; // Optimization: remove from the TableInfo map tiMap . remove ( tblName ) ; // remove the record from tblcat RecordFile tcatfile = tcatInfo . open ( tx , true ) ; tcatfile . beforeFirst ( ) ; while ( tcatfile . next ( ) ) { if ( tcatfile . getVal ( TCAT_TBLNAME ) . equals ( new VarcharConstant ( tblName ) ) ) { tcatfile . delete ( ) ; break ; } } tcatfile . close ( ) ; // remove all records whose field FCAT_TBLNAME equals to tblName from fldcat RecordFile fcatfile = fcatInfo . open ( tx , true ) ; fcatfile . beforeFirst ( ) ; while ( fcatfile . next ( ) ) { if ( fcatfile . getVal ( FCAT_TBLNAME ) . equals ( new VarcharConstant ( tblName ) ) ) fcatfile . delete ( ) ; } fcatfile . close ( ) ; // remove corresponding indices List < IndexInfo > allIndexes = new LinkedList < IndexInfo > ( ) ; Set < String > indexedFlds = VanillaDb . catalogMgr ( ) . getIndexedFields ( tblName , tx ) ; for ( String indexedFld : indexedFlds ) { List < IndexInfo > iis = VanillaDb . catalogMgr ( ) . getIndexInfo ( tblName , indexedFld , tx ) ; allIndexes . addAll ( iis ) ; } for ( IndexInfo ii : allIndexes ) VanillaDb . catalogMgr ( ) . dropIndex ( ii . indexName ( ) , tx ) ; // remove corresponding views Collection < String > vnames = VanillaDb . catalogMgr ( ) . getViewNamesByTable ( tblName , tx ) ; Iterator < String > vnameiter = vnames . iterator ( ) ; while ( vnameiter . hasNext ( ) ) VanillaDb . catalogMgr ( ) . dropView ( vnameiter . next ( ) , tx ) ; }
Remove a table with the specified name .
501
8
19,354
public TableInfo getTableInfo ( String tblName , Transaction tx ) { // Optimization: TableInfo resultTi = tiMap . get ( tblName ) ; if ( resultTi != null ) return resultTi ; RecordFile tcatfile = tcatInfo . open ( tx , true ) ; tcatfile . beforeFirst ( ) ; boolean found = false ; while ( tcatfile . next ( ) ) { String t = ( String ) tcatfile . getVal ( TCAT_TBLNAME ) . asJavaVal ( ) ; if ( t . equals ( tblName ) ) { found = true ; break ; } } tcatfile . close ( ) ; // return null if table is undefined if ( ! found ) return null ; RecordFile fcatfile = fcatInfo . open ( tx , true ) ; fcatfile . beforeFirst ( ) ; Schema sch = new Schema ( ) ; while ( fcatfile . next ( ) ) if ( ( ( String ) fcatfile . getVal ( FCAT_TBLNAME ) . asJavaVal ( ) ) . equals ( tblName ) ) { String fldname = ( String ) fcatfile . getVal ( FCAT_FLDNAME ) . asJavaVal ( ) ; int fldtype = ( Integer ) fcatfile . getVal ( FCAT_TYPE ) . asJavaVal ( ) ; int fldarg = ( Integer ) fcatfile . getVal ( FCAT_TYPEARG ) . asJavaVal ( ) ; sch . addField ( fldname , Type . newInstance ( fldtype , fldarg ) ) ; } fcatfile . close ( ) ; // Optimization: resultTi = new TableInfo ( tblName , sch ) ; tiMap . put ( tblName , resultTi ) ; return resultTi ; }
Retrieves the metadata for the specified table out of the catalog .
394
14
19,355
public static void startUp ( int port ) throws Exception { // create a registry specific for the server on the default port Registry reg = LocateRegistry . createRegistry ( port ) ; // and post the server entry in it RemoteDriver d = new RemoteDriverImpl ( ) ; reg . rebind ( "vanilladb-sp" , d ) ; }
Starts up the stored procedure call driver in server side by binding the remote driver object to local registry .
76
21
19,356
@ Override public Scan open ( ) { Scan src = p . open ( ) ; List < TempTable > runs = splitIntoRuns ( src ) ; /* * If the input source scan has no record, the temp table list will * result in size 0. Need to check the size of "runs" here. */ if ( runs . size ( ) == 0 ) return src ; src . close ( ) ; while ( runs . size ( ) > 2 ) runs = doAMergeIteration ( runs ) ; return new SortScan ( runs , comp ) ; }
This method is where most of the action is . Up to 2 sorted temporary tables are created and are passed into SortScan for final merging .
120
28
19,357
@ Override public boolean next ( ) { if ( isLhsEmpty ) return false ; if ( s2 . next ( ) ) return true ; else if ( ! ( isLhsEmpty = ! s1 . next ( ) ) ) { s2 . beforeFirst ( ) ; return s2 . next ( ) ; } else { return false ; } }
Moves the scan to the next record . The method moves to the next RHS record if possible . Otherwise it moves to the next LHS record and the first RHS record . If there are no more LHS records the method returns false .
75
50
19,358
void sLock ( Object obj , long txNum ) { Object anchor = getAnchor ( obj ) ; txWaitMap . put ( txNum , anchor ) ; synchronized ( anchor ) { Lockers lks = prepareLockers ( obj ) ; if ( hasSLock ( lks , txNum ) ) return ; try { long timestamp = System . currentTimeMillis ( ) ; while ( ! sLockable ( lks , txNum ) && ! waitingTooLong ( timestamp ) ) { avoidDeadlock ( lks , txNum , S_LOCK ) ; lks . requestSet . add ( txNum ) ; anchor . wait ( MAX_TIME ) ; lks . requestSet . remove ( txNum ) ; } if ( ! sLockable ( lks , txNum ) ) throw new LockAbortException ( ) ; lks . sLockers . add ( txNum ) ; getObjectSet ( txNum ) . add ( obj ) ; } catch ( InterruptedException e ) { throw new LockAbortException ( "abort tx." + txNum + " by interrupted" ) ; } } txWaitMap . remove ( txNum ) ; }
Grants an slock on the specified item . If any conflict lock exists when the method is called then the calling thread will be placed on a wait list until the lock is released . If the thread remains on the wait list for a certain amount of time then an exception is thrown .
246
57
19,359
void xLock ( Object obj , long txNum ) { Object anchor = getAnchor ( obj ) ; txWaitMap . put ( txNum , anchor ) ; synchronized ( anchor ) { Lockers lks = prepareLockers ( obj ) ; if ( hasXLock ( lks , txNum ) ) return ; try { long timestamp = System . currentTimeMillis ( ) ; while ( ! xLockable ( lks , txNum ) && ! waitingTooLong ( timestamp ) ) { avoidDeadlock ( lks , txNum , X_LOCK ) ; lks . requestSet . add ( txNum ) ; anchor . wait ( MAX_TIME ) ; lks . requestSet . remove ( txNum ) ; } if ( ! xLockable ( lks , txNum ) ) throw new LockAbortException ( ) ; lks . xLocker = txNum ; getObjectSet ( txNum ) . add ( obj ) ; } catch ( InterruptedException e ) { throw new LockAbortException ( ) ; } } txWaitMap . remove ( txNum ) ; }
Grants an xlock on the specified item . If any conflict lock exists when the method is called then the calling thread will be placed on a wait list until the lock is released . If the thread remains on the wait list for a certain amount of time then an exception is thrown .
230
57
19,360
void sixLock ( Object obj , long txNum ) { Object anchor = getAnchor ( obj ) ; txWaitMap . put ( txNum , anchor ) ; synchronized ( anchor ) { Lockers lks = prepareLockers ( obj ) ; if ( hasSixLock ( lks , txNum ) ) return ; try { long timestamp = System . currentTimeMillis ( ) ; while ( ! sixLockable ( lks , txNum ) && ! waitingTooLong ( timestamp ) ) { avoidDeadlock ( lks , txNum , SIX_LOCK ) ; lks . requestSet . add ( txNum ) ; anchor . wait ( MAX_TIME ) ; lks . requestSet . remove ( txNum ) ; } if ( ! sixLockable ( lks , txNum ) ) throw new LockAbortException ( ) ; lks . sixLocker = txNum ; getObjectSet ( txNum ) . add ( obj ) ; } catch ( InterruptedException e ) { throw new LockAbortException ( ) ; } } txWaitMap . remove ( txNum ) ; }
Grants an sixlock on the specified item . If any conflict lock exists when the method is called then the calling thread will be placed on a wait list until the lock is released . If the thread remains on the wait list for a certain amount of time then an exception is thrown .
231
57
19,361
void isLock ( Object obj , long txNum ) { Object anchor = getAnchor ( obj ) ; txWaitMap . put ( txNum , anchor ) ; synchronized ( anchor ) { Lockers lks = prepareLockers ( obj ) ; if ( hasIsLock ( lks , txNum ) ) return ; try { long timestamp = System . currentTimeMillis ( ) ; while ( ! isLockable ( lks , txNum ) && ! waitingTooLong ( timestamp ) ) { avoidDeadlock ( lks , txNum , IS_LOCK ) ; lks . requestSet . add ( txNum ) ; anchor . wait ( MAX_TIME ) ; lks . requestSet . remove ( txNum ) ; } if ( ! isLockable ( lks , txNum ) ) throw new LockAbortException ( ) ; lks . isLockers . add ( txNum ) ; getObjectSet ( txNum ) . add ( obj ) ; } catch ( InterruptedException e ) { throw new LockAbortException ( ) ; } } txWaitMap . remove ( txNum ) ; }
Grants an islock on the specified item . If any conflict lock exists when the method is called then the calling thread will be placed on a wait list until the lock is released . If the thread remains on the wait list for a certain amount of time then an exception is thrown .
233
57
19,362
void ixLock ( Object obj , long txNum ) { Object anchor = getAnchor ( obj ) ; txWaitMap . put ( txNum , anchor ) ; synchronized ( anchor ) { Lockers lks = prepareLockers ( obj ) ; if ( hasIxLock ( lks , txNum ) ) return ; try { long timestamp = System . currentTimeMillis ( ) ; while ( ! ixLockable ( lks , txNum ) && ! waitingTooLong ( timestamp ) ) { avoidDeadlock ( lks , txNum , IX_LOCK ) ; lks . requestSet . add ( txNum ) ; anchor . wait ( MAX_TIME ) ; lks . requestSet . remove ( txNum ) ; } if ( ! ixLockable ( lks , txNum ) ) throw new LockAbortException ( ) ; lks . ixLockers . add ( txNum ) ; getObjectSet ( txNum ) . add ( obj ) ; } catch ( InterruptedException e ) { throw new LockAbortException ( ) ; } } txWaitMap . remove ( txNum ) ; }
Grants an ixlock on the specified item . If any conflict lock exists when the method is called then the calling thread will be placed on a wait list until the lock is released . If the thread remains on the wait list for a certain amount of time then an exception is thrown .
238
58
19,363
void release ( Object obj , long txNum , int lockType ) { Object anchor = getAnchor ( obj ) ; synchronized ( anchor ) { Lockers lks = lockerMap . get ( obj ) ; /* * In some situation, tx will release the lock of the object that * have been released. */ if ( lks != null ) { releaseLock ( lks , anchor , txNum , lockType ) ; // Check if this transaction have any other lock on this object if ( ! hasSLock ( lks , txNum ) && ! hasXLock ( lks , txNum ) && ! hasSixLock ( lks , txNum ) && ! hasIsLock ( lks , txNum ) && ! hasIxLock ( lks , txNum ) ) { getObjectSet ( txNum ) . remove ( obj ) ; // Remove the locker, if there is no other transaction // having it if ( ! sLocked ( lks ) && ! xLocked ( lks ) && ! sixLocked ( lks ) && ! isLocked ( lks ) && ! ixLocked ( lks ) && lks . requestSet . isEmpty ( ) ) lockerMap . remove ( obj ) ; } } } }
Releases the specified type of lock on an item holding by a transaction . If a lock is the last lock on that block then the waiting transactions are notified .
262
32
19,364
void releaseAll ( long txNum , boolean sLockOnly ) { Set < Object > objectsToRelease = getObjectSet ( txNum ) ; for ( Object obj : objectsToRelease ) { Object anchor = getAnchor ( obj ) ; synchronized ( anchor ) { Lockers lks = lockerMap . get ( obj ) ; if ( lks != null ) { if ( hasSLock ( lks , txNum ) ) releaseLock ( lks , anchor , txNum , S_LOCK ) ; if ( hasXLock ( lks , txNum ) && ! sLockOnly ) releaseLock ( lks , anchor , txNum , X_LOCK ) ; if ( hasSixLock ( lks , txNum ) ) releaseLock ( lks , anchor , txNum , SIX_LOCK ) ; while ( hasIsLock ( lks , txNum ) ) releaseLock ( lks , anchor , txNum , IS_LOCK ) ; while ( hasIxLock ( lks , txNum ) && ! sLockOnly ) releaseLock ( lks , anchor , txNum , IX_LOCK ) ; // Remove the locker, if there is no other transaction // having it if ( ! sLocked ( lks ) && ! xLocked ( lks ) && ! sixLocked ( lks ) && ! isLocked ( lks ) && ! ixLocked ( lks ) && lks . requestSet . isEmpty ( ) ) lockerMap . remove ( obj ) ; } } } txWaitMap . remove ( txNum ) ; txnsToBeAborted . remove ( txNum ) ; lockByMap . remove ( txNum ) ; }
Releases all locks held by a transaction . If a lock is the last lock on that block then the waiting transactions are notified .
352
26
19,365
public void close ( ) { if ( blk != null ) { tx . bufferMgr ( ) . unpin ( currentBuff ) ; blk = null ; currentBuff = null ; } }
Closes the header manager by unpinning the block .
41
11
19,366
public boolean hasDataRecords ( ) { long blkNum = ( Long ) getVal ( OFFSET_TS_BLOCKID , BIGINT ) . asJavaVal ( ) ; return blkNum != NO_SLOT_BLOCKID ? true : false ; }
Return true if this file has inserted data records .
59
10
19,367
public boolean hasDeletedSlots ( ) { long blkNum = ( Long ) getVal ( OFFSET_LDS_BLOCKID , BIGINT ) . asJavaVal ( ) ; return blkNum != NO_SLOT_BLOCKID ? true : false ; }
Return true if this file has deleted data records .
61
10
19,368
public RecordId getLastDeletedSlot ( ) { Constant blkNum = getVal ( OFFSET_LDS_BLOCKID , BIGINT ) ; Constant rid = getVal ( OFFSET_LDS_RID , INTEGER ) ; BlockId bid = new BlockId ( fileName , ( Long ) blkNum . asJavaVal ( ) ) ; return new RecordId ( bid , ( Integer ) rid . asJavaVal ( ) ) ; }
Returns the id of last deleted record .
100
8
19,369
public RecordId getTailSolt ( ) { Constant blkNum = getVal ( OFFSET_TS_BLOCKID , BIGINT ) ; Constant rid = getVal ( OFFSET_TS_RID , INTEGER ) ; BlockId bid = new BlockId ( fileName , ( Long ) blkNum . asJavaVal ( ) ) ; return new RecordId ( bid , ( Integer ) rid . asJavaVal ( ) ) ; }
Returns the id of tail slot .
98
7
19,370
public void setLastDeletedSlot ( RecordId rid ) { setVal ( OFFSET_LDS_BLOCKID , new BigIntConstant ( rid . block ( ) . number ( ) ) ) ; setVal ( OFFSET_LDS_RID , new IntegerConstant ( rid . id ( ) ) ) ; }
Set the id of last deleted record .
72
8
19,371
public void setTailSolt ( RecordId rid ) { setVal ( OFFSET_TS_BLOCKID , new BigIntConstant ( rid . block ( ) . number ( ) ) ) ; setVal ( OFFSET_TS_RID , new IntegerConstant ( rid . id ( ) ) ) ; }
Set the id of last tail slot .
70
8
19,372
public static Integer getInteger ( Object object ) { try { if ( object instanceof Integer ) return ( Integer ) object ; if ( object instanceof String ) return Integer . valueOf ( ( String ) object ) ; } catch ( NumberFormatException nfe ) { } return null ; }
Return an integer if it is an Integer or can get Integer from String else null
59
16
19,373
public Plan createQueryPlan ( String qry , Transaction tx ) { Parser parser = new Parser ( qry ) ; QueryData data = parser . queryCommand ( ) ; Verifier . verifyQueryData ( data , tx ) ; return qPlanner . createPlan ( data , tx ) ; }
Creates a plan for an SQL select statement using the supplied planner .
63
14
19,374
public int executeUpdate ( String cmd , Transaction tx ) { if ( tx . isReadOnly ( ) ) throw new UnsupportedOperationException ( ) ; Parser parser = new Parser ( cmd ) ; Object obj = parser . updateCommand ( ) ; if ( obj . getClass ( ) . equals ( InsertData . class ) ) { Verifier . verifyInsertData ( ( InsertData ) obj , tx ) ; return uPlanner . executeInsert ( ( InsertData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( DeleteData . class ) ) { Verifier . verifyDeleteData ( ( DeleteData ) obj , tx ) ; return uPlanner . executeDelete ( ( DeleteData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( ModifyData . class ) ) { Verifier . verifyModifyData ( ( ModifyData ) obj , tx ) ; return uPlanner . executeModify ( ( ModifyData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( CreateTableData . class ) ) { Verifier . verifyCreateTableData ( ( CreateTableData ) obj , tx ) ; return uPlanner . executeCreateTable ( ( CreateTableData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( CreateViewData . class ) ) { Verifier . verifyCreateViewData ( ( CreateViewData ) obj , tx ) ; return uPlanner . executeCreateView ( ( CreateViewData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( CreateIndexData . class ) ) { Verifier . verifyCreateIndexData ( ( CreateIndexData ) obj , tx ) ; return uPlanner . executeCreateIndex ( ( CreateIndexData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( DropTableData . class ) ) { Verifier . verifyDropTableData ( ( DropTableData ) obj , tx ) ; return uPlanner . executeDropTable ( ( DropTableData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( DropViewData . class ) ) { Verifier . verifyDropViewData ( ( DropViewData ) obj , tx ) ; return uPlanner . executeDropView ( ( DropViewData ) obj , tx ) ; } else if ( obj . getClass ( ) . equals ( DropIndexData . class ) ) { Verifier . verifyDropIndexData ( ( DropIndexData ) obj , tx ) ; return uPlanner . executeDropIndex ( ( DropIndexData ) obj , tx ) ; } else throw new UnsupportedOperationException ( ) ; }
Executes an SQL insert delete modify or create statement . The method dispatches to the appropriate method of the supplied update planner depending on what the parser returns .
574
31
19,375
public void addField ( String fldName , Type type ) { fields . put ( fldName , type ) ; if ( myFieldSet != null ) myFieldSet . add ( fldName ) ; }
Adds a field to this schema having a specified name and type .
45
13
19,376
public void add ( String fldName , Schema sch ) { Type type = sch . type ( fldName ) ; addField ( fldName , type ) ; }
Adds a field in another schema having the specified name to this schema .
37
14
19,377
public void addAll ( Schema sch ) { fields . putAll ( sch . fields ) ; if ( myFieldSet != null ) myFieldSet = new TreeSet < String > ( fields . keySet ( ) ) ; }
Adds all of the fields in the specified schema to this schema .
48
13
19,378
public SortedSet < String > fields ( ) { // Optimization: Materialize the fields set if ( myFieldSet == null ) myFieldSet = new TreeSet < String > ( fields . keySet ( ) ) ; return myFieldSet ; }
Returns a sorted set containing the field names in this schema sorted by their natural ordering .
53
17
19,379
@ Override public Scan open ( ) { Scan s = p1 . open ( ) ; // throws an exception if p2 is not a tableplan TableScan ts = ( TableScan ) tp2 . open ( ) ; Index idx = ii . open ( tx ) ; return new IndexJoinScan ( s , idx , joinFields , ts ) ; }
Opens an index - join scan for this query
77
10
19,380
@ Override public Scan open ( ) { // throws an exception if p is not a tableplan. TableScan ts = ( TableScan ) tp . open ( ) ; Index idx = ii . open ( tx ) ; return new IndexSelectScan ( idx , new SearchRange ( ii . fieldNames ( ) , schema ( ) , searchRanges ) , ts ) ; }
Creates a new index - select scan for this query
80
11
19,381
@ Override public long blocksAccessed ( ) { return Index . searchCost ( ii . indexType ( ) , new SearchKeyType ( schema ( ) , ii . fieldNames ( ) ) , tp . recordsOutput ( ) , recordsOutput ( ) ) + recordsOutput ( ) ; }
Estimates the number of block accesses to compute the index selection which is the same as the index traversal cost plus the number of matching data records .
61
31
19,382
public static void init ( String dirName , StoredProcedureFactory factory ) { if ( inited ) { if ( logger . isLoggable ( Level . WARNING ) ) logger . warning ( "discarding duplicated init request" ) ; return ; } // Set the stored procedure factory spFactory = factory ; /* * Note: We read properties file here before, but we moved it to a * utility class, PropertiesFetcher, for safety reason. */ // read classes queryPlannerCls = CoreProperties . getLoader ( ) . getPropertyAsClass ( VanillaDb . class . getName ( ) + ".QUERYPLANNER" , HeuristicQueryPlanner . class , QueryPlanner . class ) ; updatePlannerCls = CoreProperties . getLoader ( ) . getPropertyAsClass ( VanillaDb . class . getName ( ) + ".UPDATEPLANNER" , IndexUpdatePlanner . class , UpdatePlanner . class ) ; // initialize storage engine initFileAndLogMgr ( dirName ) ; initTaskMgr ( ) ; initTxMgr ( ) ; // the first transaction for initializing the system Transaction initTx = txMgr . newTransaction ( Connection . TRANSACTION_SERIALIZABLE , false ) ; /* * initialize the catalog manager to ensure the recovery process can get * the index info (required for index logical recovery) */ boolean isDbNew = fileMgr . isNew ( ) ; initCatalogMgr ( isDbNew , initTx ) ; if ( isDbNew ) { if ( logger . isLoggable ( Level . INFO ) ) logger . info ( "creating new database..." ) ; } else { if ( logger . isLoggable ( Level . INFO ) ) logger . info ( "recovering existing database" ) ; // add a checkpoint record to limit rollback RecoveryMgr . initializeSystem ( initTx ) ; } // initialize the statistics manager to build the histogram initStatMgr ( initTx ) ; // create a checkpoint txMgr . createCheckpoint ( initTx ) ; // commit the initializing transaction initTx . commit ( ) ; // initializing checkpointing task boolean doCheckpointing = CoreProperties . getLoader ( ) . getPropertyAsBoolean ( VanillaDb . class . getName ( ) + ".DO_CHECKPOINT" , true ) ; if ( doCheckpointing ) initCheckpointingTask ( ) ; // finish initialization inited = true ; }
Initializes the system . This method is called during system startup .
522
13
19,383
public static Planner newPlanner ( ) { QueryPlanner qplanner ; UpdatePlanner uplanner ; try { qplanner = ( QueryPlanner ) queryPlannerCls . newInstance ( ) ; uplanner = ( UpdatePlanner ) updatePlannerCls . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { e . printStackTrace ( ) ; return null ; } return new Planner ( qplanner , uplanner ) ; }
Creates a planner for SQL commands . To change how the planner works modify this method .
107
18
19,384
public static void stopProfilerAndReport ( ) { profiler . stopCollecting ( ) ; // Write a report file try { // Get path from property file String path = CoreProperties . getLoader ( ) . getPropertyAsString ( VanillaDb . class . getName ( ) + ".PROFILE_OUTPUT_DIR" , System . getProperty ( "user.home" ) ) ; File out = new File ( path , System . currentTimeMillis ( ) + "_profile.txt" ) ; FileWriter wrFile = new FileWriter ( out ) ; BufferedWriter bwrFile = new BufferedWriter ( wrFile ) ; // Write Profiling Report bwrFile . write ( profiler . getTopPackages ( 30 ) ) ; bwrFile . newLine ( ) ; bwrFile . write ( profiler . getTopMethods ( 30 ) ) ; bwrFile . newLine ( ) ; bwrFile . write ( profiler . getTopLines ( 30 ) ) ; /* * I should write a more careful code here. I didn't do it, because * of the same reason above. */ bwrFile . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Stop profiler and generate report file .
265
8
19,385
void read ( BlockId blk , IoBuffer buffer ) { try { IoChannel fileChannel = getFileChannel ( blk . fileName ( ) ) ; // clear the buffer buffer . clear ( ) ; // read a block from file fileChannel . read ( buffer , blk . number ( ) * BLOCK_SIZE ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "cannot read block " + blk ) ; } }
Reads the contents of a disk block into a byte buffer .
104
13
19,386
void write ( BlockId blk , IoBuffer buffer ) { try { IoChannel fileChannel = getFileChannel ( blk . fileName ( ) ) ; // rewind the buffer buffer . rewind ( ) ; // write the block to the file fileChannel . write ( buffer , blk . number ( ) * BLOCK_SIZE ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "cannot write block" + blk ) ; } }
Writes the contents of a byte buffer into a disk block .
107
13
19,387
BlockId append ( String fileName , IoBuffer buffer ) { try { IoChannel fileChannel = getFileChannel ( fileName ) ; // Rewind the buffer for writing buffer . rewind ( ) ; // Append the block to the file long newSize = fileChannel . append ( buffer ) ; // Return the new block id return new BlockId ( fileName , newSize / BLOCK_SIZE - 1 ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } }
Appends the contents of a byte buffer to the end of the specified file .
109
16
19,388
public long size ( String fileName ) { try { IoChannel fileChannel = getFileChannel ( fileName ) ; return fileChannel . size ( ) / BLOCK_SIZE ; } catch ( IOException e ) { throw new RuntimeException ( "cannot access " + fileName ) ; } }
Returns the number of blocks in the specified file .
62
10
19,389
private IoChannel getFileChannel ( String fileName ) throws IOException { synchronized ( prepareAnchor ( fileName ) ) { IoChannel fileChannel = openFiles . get ( fileName ) ; if ( fileChannel == null ) { File dbFile = fileName . equals ( DEFAULT_LOG_FILE ) ? new File ( logDirectory , fileName ) : new File ( dbDirectory , fileName ) ; fileChannel = IoAllocator . newIoChannel ( dbFile ) ; openFiles . put ( fileName , fileChannel ) ; } return fileChannel ; } }
Returns the file channel for the specified filename . The file channel is stored in a map keyed on the filename . If the file is not open then it is opened and the file channel is added to the map .
122
43
19,390
public static Histogram productHistogram ( Histogram hist1 , Histogram hist2 ) { Set < String > prodFlds = new HashSet < String > ( hist1 . fields ( ) ) ; prodFlds . addAll ( hist2 . fields ( ) ) ; Histogram prodHist = new Histogram ( prodFlds ) ; double numRec1 = hist1 . recordsOutput ( ) ; double numRec2 = hist2 . recordsOutput ( ) ; if ( Double . compare ( numRec1 , 1.0 ) < 0 || Double . compare ( numRec2 , 1.0 ) < 0 ) return prodHist ; for ( String fld : hist1 . fields ( ) ) for ( Bucket bkt : hist1 . buckets ( fld ) ) prodHist . addBucket ( fld , new Bucket ( bkt . valueRange ( ) , bkt . frequency ( ) * numRec2 , bkt . distinctValues ( ) , bkt . valuePercentiles ( ) ) ) ; for ( String fld : hist2 . fields ( ) ) for ( Bucket bkt : hist2 . buckets ( fld ) ) prodHist . addBucket ( fld , new Bucket ( bkt . valueRange ( ) , bkt . frequency ( ) * numRec1 , bkt . distinctValues ( ) , bkt . valuePercentiles ( ) ) ) ; return prodHist ; }
Returns a histogram that for each field approximates the value distribution of products from the specified histograms .
299
21
19,391
@ Override public Scan open ( ) { Scan s1 = p1 . open ( ) ; Scan s2 = p2 . open ( ) ; return new ProductScan ( s1 , s2 ) ; }
Creates a product scan for this query .
44
9
19,392
@ Override public boolean next ( ) { boolean ok = idx . next ( ) ; if ( ok ) { RecordId rid = idx . getDataRecordId ( ) ; ts . moveToRecordId ( rid ) ; } return ok ; }
Moves to the next record which in this case means moving the index to the next record satisfying the selection constant and returning false if there are no more such index records . If there is a next record the method moves the tablescan to the corresponding data record .
53
52
19,393
@ Override public void beforeFirst ( ) { currentScan = null ; s1 . beforeFirst ( ) ; hasMore1 = s1 . next ( ) ; if ( s2 != null ) { s2 . beforeFirst ( ) ; hasMore2 = s2 . next ( ) ; } }
Positions the scan before the first record in sorted order . Internally it moves to the first record of each underlying scan . The variable currentScan is set to null indicating that there is no current scan .
63
41
19,394
@ Override public boolean next ( ) { if ( currentScan != null ) { if ( currentScan == s1 ) hasMore1 = s1 . next ( ) ; else if ( currentScan == s2 ) hasMore2 = s2 . next ( ) ; } if ( ! hasMore1 && ! hasMore2 ) return false ; else if ( hasMore1 && hasMore2 ) { // update currentScan currentScan = comp . compare ( s1 , s2 ) < 0 ? s1 : s2 ; } else if ( hasMore1 ) currentScan = s1 ; else if ( hasMore2 ) currentScan = s2 ; return true ; }
Moves to the next record in sorted order . First the current scan is moved to the next record . Then the lowest record of the two scans is found and that scan is chosen to be the new current scan .
141
43
19,395
public void savePosition ( ) { RecordId rid1 = s1 . getRecordId ( ) ; RecordId rid2 = ( s2 == null ) ? null : s2 . getRecordId ( ) ; savedPosition = Arrays . asList ( rid1 , rid2 ) ; }
Saves the position of the current record so that it can be restored at a later time .
61
19
19,396
public void restorePosition ( ) { RecordId rid1 = savedPosition . get ( 0 ) ; RecordId rid2 = savedPosition . get ( 1 ) ; s1 . moveToRecordId ( rid1 ) ; if ( rid2 != null ) s2 . moveToRecordId ( rid2 ) ; }
Moves the scan to its previously - saved position .
65
11
19,397
public void createCheckpoint ( Transaction checkpointTx ) { // stop access new tx request and find out active txs by using a write // lock on threadTxNums List < Long > txNums ; // for (Transaction tx : activeTxs) // if (tx.getTransactionNumber() != checkpointTx // .getTransactionNumber()) // txNums.add(tx.getTransactionNumber()); // activeTxsLock.writeLock().lock(); // try { // for (Long l : threadTxNums) { // if (l >= 0) { // txNums.add(l); // } // } // // // flush all buffers // // CT : Pick a tx and call its bufferMgr flushAll, or get // // bufferPoolMgr (init it at VanillaDb) // checkpointTx.bufferMgr().flushAll(); // // wrtie a checkpoint record and flush to disk // LogSeqNum lsn = checkpointTx.recoveryMgr().checkpoint(txNums); // VanillaDb.logMgr().flush(lsn); // System.out.println("Chkpnt :" + txNums); // } finally { // activeTxsLock.writeLock().unlock(); // } // Old method synchronized ( this ) { txNums = new LinkedList < Long > ( activeTxs ) ; checkpointTx . bufferMgr ( ) . flushAll ( ) ; LogSeqNum lsn = checkpointTx . recoveryMgr ( ) . checkpoint ( txNums ) ; VanillaDb . logMgr ( ) . flush ( lsn ) ; } }
Creates non - quiescent checkpoint record .
341
10
19,398
@ Override public Plan createPlan ( QueryData data , Transaction tx ) { // Step 1: Create a plan for each mentioned table or view List < Plan > plans = new ArrayList < Plan > ( ) ; for ( String tblname : data . tables ( ) ) { String viewdef = VanillaDb . catalogMgr ( ) . getViewDef ( tblname , tx ) ; if ( viewdef != null ) plans . add ( VanillaDb . newPlanner ( ) . createQueryPlan ( viewdef , tx ) ) ; else plans . add ( new TablePlan ( tblname , tx ) ) ; } // Step 2: Create the product of all table plans Plan p = plans . remove ( 0 ) ; for ( Plan nextplan : plans ) p = new ProductPlan ( p , nextplan ) ; // Step 3: Add a selection plan for the predicate p = new SelectPlan ( p , data . pred ( ) ) ; // Step 4: Add a group-by plan if specified if ( data . groupFields ( ) != null ) { p = new GroupByPlan ( p , data . groupFields ( ) , data . aggregationFn ( ) , tx ) ; } // Step 5: Project onto the specified fields p = new ProjectPlan ( p , data . projectFields ( ) ) ; // Step 6: Add a sort plan if specified if ( data . sortFields ( ) != null ) p = new SortPlan ( p , data . sortFields ( ) , data . sortDirections ( ) , tx ) ; // Step 7: Add a explain plan if the query is explain statement if ( data . isExplain ( ) ) p = new ExplainPlan ( p ) ; return p ; }
Creates a query plan as follows . It first takes the product of all tables and views ; it then selects on the predicate ; and finally it projects on the field list .
364
35
19,399
@ Override public Plan createPlan ( QueryData data , Transaction tx ) { // Step 1: Create a TablePlanner object for each mentioned table/view int id = 0 ; for ( String tbl : data . tables ( ) ) { String viewdef = VanillaDb . catalogMgr ( ) . getViewDef ( tbl , tx ) ; if ( viewdef != null ) views . add ( VanillaDb . newPlanner ( ) . createQueryPlan ( viewdef , tx ) ) ; else { TablePlanner tp = new TablePlanner ( tbl , data . pred ( ) , tx , id ) ; tablePlanners . add ( tp ) ; id += 1 ; } } // step 2: Use Selinger optimization to find join access path Plan trunk = getAccessPath ( ) ; // Step 3: Add a group by plan if specified if ( data . groupFields ( ) != null ) trunk = new GroupByPlan ( trunk , data . groupFields ( ) , data . aggregationFn ( ) , tx ) ; // Step 4. Project on the field names trunk = new ProjectPlan ( trunk , data . projectFields ( ) ) ; // Step 5: Add a sort plan if specified if ( data . sortFields ( ) != null ) trunk = new SortPlan ( trunk , data . sortFields ( ) , data . sortDirections ( ) , tx ) ; // Step 6: Add a explain plan if the query is explain statement if ( data . isExplain ( ) ) trunk = new ExplainPlan ( trunk ) ; return trunk ; }
Creates a left - deep query plan using the Selinger optimization . Main idea is to find all permutation of table join order and to choose the cheapest plan . However all permutation can be too much for us to go through all . So we use DP and left - deep only to optimize this process .
332
62