idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
23,800 | public M put ( Map < String , Object > map ) { attrs . putAll ( map ) ; return ( M ) this ; } | Put map to the model without check attribute name . |
23,801 | public < T > T get ( String attr , Object defaultValue ) { Object result = attrs . get ( attr ) ; return ( T ) ( result != null ? result : defaultValue ) ; } | Get attribute of any mysql type . Returns defaultValue if null . |
23,802 | public boolean save ( ) { filter ( FILTER_BY_SAVE ) ; Config config = _getConfig ( ) ; Table table = _getTable ( ) ; StringBuilder sql = new StringBuilder ( ) ; List < Object > paras = new ArrayList < Object > ( ) ; config . dialect . forModelSave ( table , attrs , sql , paras ) ; Connection conn = null ; PreparedStatement pst = null ; int result = 0 ; try { conn = config . getConnection ( ) ; if ( config . dialect . isOracle ( ) ) { pst = conn . prepareStatement ( sql . toString ( ) , table . getPrimaryKey ( ) ) ; } else { pst = conn . prepareStatement ( sql . toString ( ) , Statement . RETURN_GENERATED_KEYS ) ; } config . dialect . fillStatement ( pst , paras ) ; result = pst . executeUpdate ( ) ; config . dialect . getModelGeneratedKey ( this , pst , table ) ; _getModifyFlag ( ) . clear ( ) ; return result >= 1 ; } catch ( Exception e ) { throw new ActiveRecordException ( e ) ; } finally { config . close ( pst , conn ) ; } } | Save model . |
23,803 | public boolean deleteByIds ( Object ... idValues ) { Table table = _getTable ( ) ; if ( idValues == null || idValues . length != table . getPrimaryKey ( ) . length ) throw new IllegalArgumentException ( "Primary key nubmer must equals id value number and can not be null" ) ; return deleteById ( table , idValues ) ; } | Delete model by composite id values . |
23,804 | public boolean update ( ) { filter ( FILTER_BY_UPDATE ) ; if ( _getModifyFlag ( ) . isEmpty ( ) ) { return false ; } Table table = _getTable ( ) ; String [ ] pKeys = table . getPrimaryKey ( ) ; for ( String pKey : pKeys ) { Object id = attrs . get ( pKey ) ; if ( id == null ) throw new ActiveRecordException ( "You can't update model without Primary Key, " + pKey + " can not be null." ) ; } Config config = _getConfig ( ) ; StringBuilder sql = new StringBuilder ( ) ; List < Object > paras = new ArrayList < Object > ( ) ; config . dialect . forModelUpdate ( table , attrs , _getModifyFlag ( ) , sql , paras ) ; if ( paras . size ( ) <= 1 ) { return false ; } Connection conn = null ; try { conn = config . getConnection ( ) ; int result = Db . update ( config , conn , sql . toString ( ) , paras . toArray ( ) ) ; if ( result >= 1 ) { _getModifyFlag ( ) . clear ( ) ; return true ; } return false ; } catch ( Exception e ) { throw new ActiveRecordException ( e ) ; } finally { config . close ( conn ) ; } } | Update model . |
23,805 | public M remove ( String attr ) { attrs . remove ( attr ) ; _getModifyFlag ( ) . remove ( attr ) ; return ( M ) this ; } | Remove attribute of this model . |
23,806 | public M remove ( String ... attrs ) { if ( attrs != null ) for ( String a : attrs ) { this . attrs . remove ( a ) ; this . _getModifyFlag ( ) . remove ( a ) ; } return ( M ) this ; } | Remove attributes of this model . |
23,807 | public M removeNullValueAttrs ( ) { for ( Iterator < Entry < String , Object > > it = attrs . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Entry < String , Object > e = it . next ( ) ; if ( e . getValue ( ) == null ) { it . remove ( ) ; _getModifyFlag ( ) . remove ( e . getKey ( ) ) ; } } return ( M ) this ; } | Remove attributes if it is null . |
23,808 | public M keep ( String ... attrs ) { if ( attrs != null && attrs . length > 0 ) { Config config = _getConfig ( ) ; if ( config == null ) { config = DbKit . brokenConfig ; } Map < String , Object > newAttrs = config . containerFactory . getAttrsMap ( ) ; Set < String > newModifyFlag = config . containerFactory . getModifyFlagSet ( ) ; for ( String a : attrs ) { if ( this . attrs . containsKey ( a ) ) newAttrs . put ( a , this . attrs . get ( a ) ) ; if ( this . _getModifyFlag ( ) . contains ( a ) ) newModifyFlag . add ( a ) ; } this . attrs = newAttrs ; this . modifyFlag = newModifyFlag ; } else { this . attrs . clear ( ) ; this . _getModifyFlag ( ) . clear ( ) ; } return ( M ) this ; } | Keep attributes of this model and remove other attributes . |
23,809 | public M keep ( String attr ) { if ( attrs . containsKey ( attr ) ) { Object keepIt = attrs . get ( attr ) ; boolean keepFlag = _getModifyFlag ( ) . contains ( attr ) ; attrs . clear ( ) ; _getModifyFlag ( ) . clear ( ) ; attrs . put ( attr , keepIt ) ; if ( keepFlag ) _getModifyFlag ( ) . add ( attr ) ; } else { attrs . clear ( ) ; _getModifyFlag ( ) . clear ( ) ; } return ( M ) this ; } | Keep attribute of this model and remove other attributes . |
23,810 | public List < M > findByCache ( String cacheName , Object key , String sql , Object ... paras ) { Config config = _getConfig ( ) ; ICache cache = config . getCache ( ) ; List < M > result = cache . get ( cacheName , key ) ; if ( result == null ) { result = find ( config , sql , paras ) ; cache . put ( cacheName , key , result ) ; } return result ; } | Find model by cache . |
23,811 | public M findFirstByCache ( String cacheName , Object key , String sql , Object ... paras ) { ICache cache = _getConfig ( ) . getCache ( ) ; M result = cache . get ( cacheName , key ) ; if ( result == null ) { result = findFirst ( sql , paras ) ; cache . put ( cacheName , key , result ) ; } return result ; } | Find first model by cache . I recommend add limit 1 in your sql . |
23,812 | public static Res use ( String baseName , String locale ) { String resKey = baseName + locale ; Res res = resMap . get ( resKey ) ; if ( res == null ) { res = new Res ( baseName , locale ) ; resMap . put ( resKey , res ) ; } return res ; } | Using the base name and locale to get the Res object which is used to get i18n message value from the resource file . |
23,813 | public static String generateSalt ( int saltLength ) { StringBuilder salt = new StringBuilder ( saltLength ) ; for ( int i = 0 ; i < saltLength ; i ++ ) { salt . append ( CHAR_ARRAY [ random . nextInt ( CHAR_ARRAY . length ) ] ) ; } return salt . toString ( ) ; } | md5 128bit 16bytes sha1 160bit 20bytes sha256 256bit 32bytes sha384 384bit 48bytes sha512 512bit 64bytes |
23,814 | public void startAutoCycle ( long delay , long duration , boolean autoRecover ) { if ( mCycleTimer != null ) mCycleTimer . cancel ( ) ; if ( mCycleTask != null ) mCycleTask . cancel ( ) ; if ( mResumingTask != null ) mResumingTask . cancel ( ) ; if ( mResumingTimer != null ) mResumingTimer . cancel ( ) ; mSliderDuration = duration ; mCycleTimer = new Timer ( ) ; mAutoRecover = autoRecover ; mCycleTask = new TimerTask ( ) { public void run ( ) { mh . sendEmptyMessage ( 0 ) ; } } ; mCycleTimer . schedule ( mCycleTask , delay , mSliderDuration ) ; mCycling = true ; mAutoCycle = true ; } | start auto cycle . |
23,815 | private void pauseAutoCycle ( ) { if ( mCycling ) { mCycleTimer . cancel ( ) ; mCycleTask . cancel ( ) ; mCycling = false ; } else { if ( mResumingTimer != null && mResumingTask != null ) { recoverCycle ( ) ; } } } | pause auto cycle . |
23,816 | public void stopAutoCycle ( ) { if ( mCycleTask != null ) { mCycleTask . cancel ( ) ; } if ( mCycleTimer != null ) { mCycleTimer . cancel ( ) ; } if ( mResumingTimer != null ) { mResumingTimer . cancel ( ) ; } if ( mResumingTask != null ) { mResumingTask . cancel ( ) ; } mAutoCycle = false ; mCycling = false ; } | stop the auto circle |
23,817 | private void recoverCycle ( ) { if ( ! mAutoRecover || ! mAutoCycle ) { return ; } if ( ! mCycling ) { if ( mResumingTask != null && mResumingTimer != null ) { mResumingTimer . cancel ( ) ; mResumingTask . cancel ( ) ; } mResumingTimer = new Timer ( ) ; mResumingTask = new TimerTask ( ) { public void run ( ) { startAutoCycle ( ) ; } } ; mResumingTimer . schedule ( mResumingTask , 6000 ) ; } } | when paused cycle this method can weak it up . |
23,818 | public void setPagerTransformer ( boolean reverseDrawingOrder , BaseTransformer transformer ) { mViewPagerTransformer = transformer ; mViewPagerTransformer . setCustomAnimationInterface ( mCustomAnimation ) ; mViewPager . setPageTransformer ( reverseDrawingOrder , mViewPagerTransformer ) ; } | set ViewPager transformer . |
23,819 | public void setSliderTransformDuration ( int period , Interpolator interpolator ) { try { Field mScroller = ViewPagerEx . class . getDeclaredField ( "mScroller" ) ; mScroller . setAccessible ( true ) ; FixedSpeedScroller scroller = new FixedSpeedScroller ( mViewPager . getContext ( ) , interpolator , period ) ; mScroller . set ( mViewPager , scroller ) ; } catch ( Exception e ) { } } | set the duration between two slider changes . |
23,820 | public void setPresetTransformer ( int transformerId ) { for ( Transformer t : Transformer . values ( ) ) { if ( t . ordinal ( ) == transformerId ) { setPresetTransformer ( t ) ; break ; } } } | set a preset viewpager transformer by id . |
23,821 | public void setPresetTransformer ( String transformerName ) { for ( Transformer t : Transformer . values ( ) ) { if ( t . equals ( transformerName ) ) { setPresetTransformer ( t ) ; return ; } } } | set preset PagerTransformer via the name of transforemer . |
23,822 | public BaseSliderView getCurrentSlider ( ) { if ( getRealAdapter ( ) == null ) throw new IllegalStateException ( "You did not set a slider adapter" ) ; int count = getRealAdapter ( ) . getCount ( ) ; int realCount = mViewPager . getCurrentItem ( ) % count ; return getRealAdapter ( ) . getSliderView ( realCount ) ; } | get current slider . |
23,823 | public void setCurrentPosition ( int position , boolean smooth ) { if ( getRealAdapter ( ) == null ) throw new IllegalStateException ( "You did not set a slider adapter" ) ; if ( position >= getRealAdapter ( ) . getCount ( ) ) { throw new IllegalStateException ( "Item position is not exist" ) ; } int p = mViewPager . getCurrentItem ( ) % getRealAdapter ( ) . getCount ( ) ; int n = ( position - p ) + mViewPager . getCurrentItem ( ) ; mViewPager . setCurrentItem ( n , smooth ) ; } | set current slider |
23,824 | public void movePrevPosition ( boolean smooth ) { if ( getRealAdapter ( ) == null ) throw new IllegalStateException ( "You did not set a slider adapter" ) ; mViewPager . setCurrentItem ( mViewPager . getCurrentItem ( ) - 1 , smooth ) ; } | move to prev slide . |
23,825 | public void moveNextPosition ( boolean smooth ) { if ( getRealAdapter ( ) == null ) throw new IllegalStateException ( "You did not set a slider adapter" ) ; mViewPager . setCurrentItem ( mViewPager . getCurrentItem ( ) + 1 , smooth ) ; } | move to next slide . |
23,826 | public void setOffscreenPageLimit ( int limit ) { if ( limit < DEFAULT_OFFSCREEN_PAGES ) { Log . w ( TAG , "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES ) ; limit = DEFAULT_OFFSCREEN_PAGES ; } if ( limit != mOffscreenPageLimit ) { mOffscreenPageLimit = limit ; populate ( ) ; } } | Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state . Pages beyond this limit will be recreated from the adapter when needed . |
23,827 | public void setPageMarginDrawable ( Drawable d ) { mMarginDrawable = d ; if ( d != null ) refreshDrawableState ( ) ; setWillNotDraw ( d == null ) ; invalidate ( ) ; } | Set a drawable that will be used to fill the margin between pages . |
23,828 | public void addTouchables ( ArrayList < View > views ) { for ( int i = 0 ; i < getChildCount ( ) ; i ++ ) { final View child = getChildAt ( i ) ; if ( child . getVisibility ( ) == VISIBLE ) { ItemInfo ii = infoForChild ( child ) ; if ( ii != null && ii . position == mCurItem ) { child . addTouchables ( views ) ; } } } } | We only want the current page that is being shown to be touchable . |
23,829 | public void onEnd ( boolean result , BaseSliderView target ) { if ( target . isErrorDisappear ( ) == false || result == true ) { return ; } for ( BaseSliderView slider : mImageContents ) { if ( slider . equals ( target ) ) { removeSlider ( target ) ; break ; } } } | When image download error then remove . |
23,830 | public void onPrepareNextItemShowInScreen ( View next ) { View descriptionLayout = next . findViewById ( R . id . description_layout ) ; if ( descriptionLayout != null ) { next . findViewById ( R . id . description_layout ) . setVisibility ( View . INVISIBLE ) ; } } | When next item is coming to show let s hide the description layout . |
23,831 | public void onNextItemAppear ( View view ) { View descriptionLayout = view . findViewById ( R . id . description_layout ) ; if ( descriptionLayout != null ) { float layoutY = ViewHelper . getY ( descriptionLayout ) ; view . findViewById ( R . id . description_layout ) . setVisibility ( View . VISIBLE ) ; ValueAnimator animator = ObjectAnimator . ofFloat ( descriptionLayout , "y" , layoutY + descriptionLayout . getHeight ( ) , layoutY ) . setDuration ( 500 ) ; animator . start ( ) ; } } | When next item show in ViewPagerEx let s make an animation to show the description layout . |
23,832 | public void setDefaultIndicatorShape ( Shape shape ) { if ( mUserSetSelectedIndicatorResId == 0 ) { if ( shape == Shape . Oval ) { mSelectedGradientDrawable . setShape ( GradientDrawable . OVAL ) ; } else { mSelectedGradientDrawable . setShape ( GradientDrawable . RECTANGLE ) ; } } if ( mUserSetUnSelectedIndicatorResId == 0 ) { if ( shape == Shape . Oval ) { mUnSelectedGradientDrawable . setShape ( GradientDrawable . OVAL ) ; } else { mUnSelectedGradientDrawable . setShape ( GradientDrawable . RECTANGLE ) ; } } resetDrawable ( ) ; } | if you are using the default indicator this method will help you to set the shape of indicator there are two kind of shapes you can set oval and rect . |
23,833 | public void setIndicatorStyleResource ( int selected , int unselected ) { mUserSetSelectedIndicatorResId = selected ; mUserSetUnSelectedIndicatorResId = unselected ; if ( selected == 0 ) { mSelectedDrawable = mSelectedLayerDrawable ; } else { mSelectedDrawable = mContext . getResources ( ) . getDrawable ( mUserSetSelectedIndicatorResId ) ; } if ( unselected == 0 ) { mUnselectedDrawable = mUnSelectedLayerDrawable ; } else { mUnselectedDrawable = mContext . getResources ( ) . getDrawable ( mUserSetUnSelectedIndicatorResId ) ; } resetDrawable ( ) ; } | Set Indicator style . |
23,834 | public void setDefaultIndicatorColor ( int selectedColor , int unselectedColor ) { if ( mUserSetSelectedIndicatorResId == 0 ) { mSelectedGradientDrawable . setColor ( selectedColor ) ; } if ( mUserSetUnSelectedIndicatorResId == 0 ) { mUnSelectedGradientDrawable . setColor ( unselectedColor ) ; } resetDrawable ( ) ; } | if you are using the default indicator this method will help you to set the selected status and the unselected status color . |
23,835 | public void setIndicatorVisibility ( IndicatorVisibility visibility ) { if ( visibility == IndicatorVisibility . Visible ) { setVisibility ( View . VISIBLE ) ; } else { setVisibility ( View . INVISIBLE ) ; } resetDrawable ( ) ; } | set the visibility of indicator . |
23,836 | public void setViewPager ( ViewPagerEx pager ) { if ( pager . getAdapter ( ) == null ) { throw new IllegalStateException ( "Viewpager does not have adapter instance" ) ; } mPager = pager ; mPager . addOnPageChangeListener ( this ) ; ( ( InfinitePagerAdapter ) mPager . getAdapter ( ) ) . getRealAdapter ( ) . registerDataSetObserver ( dataChangeObserver ) ; } | bind indicator with viewpagerEx . |
23,837 | public void redraw ( ) { mItemCount = getShouldDrawCount ( ) ; mPreviousSelectedIndicator = null ; for ( View i : mIndicators ) { removeView ( i ) ; } for ( int i = 0 ; i < mItemCount ; i ++ ) { ImageView indicator = new ImageView ( mContext ) ; indicator . setImageDrawable ( mUnselectedDrawable ) ; indicator . setPadding ( ( int ) mUnSelectedPadding_Left , ( int ) mUnSelectedPadding_Top , ( int ) mUnSelectedPadding_Right , ( int ) mUnSelectedPadding_Bottom ) ; addView ( indicator ) ; mIndicators . add ( indicator ) ; } setItemAsSelected ( mPreviousSelectedPosition ) ; } | redraw the indicators . |
23,838 | private int getShouldDrawCount ( ) { if ( mPager . getAdapter ( ) instanceof InfinitePagerAdapter ) { return ( ( InfinitePagerAdapter ) mPager . getAdapter ( ) ) . getRealCount ( ) ; } else { return mPager . getAdapter ( ) . getCount ( ) ; } } | since we used a adapter wrapper so we can t getCount directly from wrapper . |
23,839 | public BaseSliderView image ( String url ) { if ( mFile != null || mRes != 0 ) { throw new IllegalStateException ( "Call multi image function," + "you only have permission to call it once" ) ; } mUrl = url ; return this ; } | set a url as a image that preparing to load |
23,840 | public BaseSliderView image ( File file ) { if ( mUrl != null || mRes != 0 ) { throw new IllegalStateException ( "Call multi image function," + "you only have permission to call it once" ) ; } mFile = file ; return this ; } | set a file as a image that will to load |
23,841 | public Object remove ( Object key ) { Object underlying = this . underlyingObjectGetter . getUnderlyingObject ( key ) ; return removeUsingUnderlying ( underlying ) ; } | Removes and returns the entry associated with the specified key in the HashMap . Returns null if the HashMap contains no mapping for this key . |
23,842 | public static final int hash ( double d , boolean isNull ) { if ( isNull ) return NULL_HASH ; long longVal = Double . doubleToLongBits ( d ) ; return ( int ) ( longVal ^ ( longVal >>> 32 ) ) ; } | need to mix the value but have to keep it compatible with Double . hashcode !! |
23,843 | public void shutdown ( ) { while ( true ) { long cur = combinedState . get ( ) ; long newValue = cur | 0x8000000000000000L ; if ( combinedState . compareAndSet ( cur , newValue ) ) { break ; } } } | Initiates an orderly shutdown in which previously submitted tasks are executed but no new tasks will be accepted . Invocation has no additional effect if already shut down . |
23,844 | public void shutdownAndWaitUntilDone ( ) { shutdown ( ) ; while ( true ) { synchronized ( endSignal ) { try { if ( ( combinedState . get ( ) & 0x7FFFFFFFFFFFFFFFL ) == 0 ) break ; endSignal . wait ( 100 ) ; } catch ( InterruptedException e ) { } } } } | Shuts down the executor and blocks until all tasks have completed execution |
23,845 | public synchronized void checkAndWaitForSyslogSynchronized ( Object sourceAttribute , String schema , MithraDatabaseObject databaseObject ) { long now = System . currentTimeMillis ( ) ; if ( now > nextTimeToCheck ) { this . checkAndWaitForSyslog ( sourceAttribute , schema , databaseObject ) ; } } | synchronized so it does one check for all involved threads . |
23,846 | private ReladomoTxIdInterface initializeTransactionXidRange ( String flowId , int xidId ) { ReladomoTxIdInterface transactionXid = null ; MithraTransactionalList list = null ; try { DeserializationClassMetaData deserializationClassMetaData = new DeserializationClassMetaData ( this . txIdFinder ) ; transactionXid = ( ReladomoTxIdInterface ) deserializationClassMetaData . constructObject ( null , null ) ; transactionXid . setId ( xidId ) ; transactionXid . setFlowId ( flowId ) ; list = ( MithraTransactionalList ) this . txIdFinder . constructEmptyList ( ) ; list . add ( transactionXid ) ; for ( int i = xidId - 80 ; i < xidId ; i ++ ) { ReladomoTxIdInterface filler = ( ReladomoTxIdInterface ) deserializationClassMetaData . constructObject ( null , null ) ; filler . setId ( i ) ; filler . setFlowId ( i + " Padding" ) ; list . add ( filler ) ; } for ( int i = xidId + 1 ; i < xidId + 80 ; i ++ ) { ReladomoTxIdInterface filler = ( ReladomoTxIdInterface ) deserializationClassMetaData . constructObject ( null , null ) ; filler . setId ( i ) ; filler . setFlowId ( i + " Padding" ) ; list . add ( filler ) ; } } catch ( DeserializationException e ) { throw new RuntimeException ( "Could not construct transactionId class" , e ) ; } list . insertAll ( ) ; return transactionXid ; } | real records . |
23,847 | protected boolean matchesWithoutDeleteCheck ( Object o , Extractor extractor ) { String s = ( ( StringExtractor ) extractor ) . stringValueOf ( o ) ; return s != null && s . indexOf ( this . getParameter ( ) ) < 0 ; } | null must not match anything exactly as in SQL |
23,848 | private boolean linkFirst ( Node < E > node ) { if ( count >= capacity ) return false ; Node < E > f = first ; node . next = f ; first = node ; if ( last == null ) last = node ; else f . prev = node ; ++ count ; notEmpty . signal ( ) ; return true ; } | Links node as first element or returns false if full . |
23,849 | private boolean linkLast ( Node < E > node ) { if ( count >= capacity ) return false ; Node < E > l = last ; node . prev = l ; last = node ; if ( first == null ) first = node ; else l . next = node ; ++ count ; notEmpty . signal ( ) ; return true ; } | Links node as last element or returns false if full . |
23,850 | void unlink ( Node < E > x ) { Node < E > p = x . prev ; Node < E > n = x . next ; if ( p == null ) { unlinkFirst ( ) ; } else if ( n == null ) { unlinkLast ( ) ; } else { p . next = n ; n . prev = p ; x . item = null ; -- count ; notFull . signal ( ) ; } } | Unlinks x . |
23,851 | private Object getEntryAfterMiss ( TransactionLocal key , int i , Entry e ) { Entry [ ] tab = table ; int len = tab . length ; while ( e != null ) { if ( e . key == key ) return e . value ; i = nextIndex ( i , len ) ; e = tab [ i ] ; } return null ; } | Version of getEntry method for use when key is not found in its direct hash slot . |
23,852 | public void put ( TransactionLocal key , Object value ) { Entry [ ] tab = table ; int len = tab . length ; int i = key . hashCode & ( len - 1 ) ; for ( Entry e = tab [ i ] ; e != null ; e = tab [ i = nextIndex ( i , len ) ] ) { if ( e . key == key ) { e . value = value ; return ; } } tab [ i ] = new Entry ( key , value ) ; int sz = ++ size ; if ( sz >= threshold ) rehash ( ) ; } | Set the value associated with key . |
23,853 | public void remove ( TransactionLocal key ) { Entry [ ] tab = table ; int len = tab . length ; int i = key . hashCode & ( len - 1 ) ; for ( Entry e = tab [ i ] ; e != null ; e = tab [ i = nextIndex ( i , len ) ] ) { if ( e . key == key ) { expungeStaleEntry ( i ) ; return ; } } } | Remove the entry for key . |
23,854 | private int expungeStaleEntry ( int staleSlot ) { Entry [ ] tab = table ; int len = tab . length ; tab [ staleSlot ] . value = null ; tab [ staleSlot ] = null ; size -- ; Entry e ; int i ; for ( i = nextIndex ( staleSlot , len ) ; ( e = tab [ i ] ) != null ; i = nextIndex ( i , len ) ) { int h = e . key . hashCode & ( len - 1 ) ; if ( h != i ) { tab [ i ] = null ; while ( tab [ h ] != null ) h = nextIndex ( h , len ) ; tab [ h ] = e ; } } return i ; } | Expunge a stale entry by rehashing any possibly colliding entries lying between staleSlot and the next null slot . This also expunges any other stale entries encountered before the trailing null . See Knuth Section 6 . 4 |
23,855 | private void resize ( ) { Entry [ ] oldTab = table ; int oldLen = oldTab . length ; int newLen = oldLen * 2 ; Entry [ ] newTab = new Entry [ newLen ] ; int count = 0 ; for ( int j = 0 ; j < oldLen ; ++ j ) { Entry e = oldTab [ j ] ; if ( e != null ) { int h = e . key . hashCode & ( newLen - 1 ) ; while ( newTab [ h ] != null ) h = nextIndex ( h , newLen ) ; newTab [ h ] = e ; count ++ ; } } setThreshold ( newLen ) ; size = count ; table = newTab ; } | Double the capacity of the table . |
23,856 | private List applyOperationAndCheck ( Operation op , MithraTransaction tx ) { boolean oldEvaluationMode = tx . zIsInOperationEvaluationMode ( ) ; List resultList = null ; try { tx . zSetOperationEvaluationMode ( true ) ; if ( this . isPureHome ( ) || ( ! this . isOperationPartiallyCached ( op ) && ! this . txParticipationRequired ( tx , op ) ) ) { resultList = this . resolveOperationOnCache ( op ) ; } else { resultList = op . applyOperationToPartialCache ( ) ; if ( resultList == null && ! this . isOperationPartiallyCached ( op ) && this . getTxParticipationMode ( tx ) . mustParticipateInTxOnRead ( ) ) { List untrustworthyResult = op . applyOperationToFullCache ( ) ; checkTransactionParticipationAndWaitForOtherTransactions ( untrustworthyResult , tx ) ; } resultList = checkTransactionParticipationAndWaitForOtherTransactions ( resultList , tx ) ; } } finally { tx . zSetOperationEvaluationMode ( oldEvaluationMode ) ; } if ( this . isPureHome ( ) ) { checkTransactionParticipationForPureObject ( resultList , tx ) ; } return resultList ; } | the transaction is getting 100% correct data |
23,857 | private static boolean timestampToAsofAttributeRelationiship ( Map . Entry < Attribute , Attribute > each ) { return ( each . getValue ( ) != null && each . getValue ( ) . isAsOfAttribute ( ) ) && ! each . getKey ( ) . isAsOfAttribute ( ) ; } | unsupported combination of businessDate timestamp - > businessDate asOf mapping . requires custom index |
23,858 | public int ifRetriableWaitElseThrow ( String msg , int retriesLeft , Logger logger ) { if ( this . isRetriable ( ) && -- retriesLeft > 0 ) { logger . warn ( msg + " " + this . getMessage ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "find failed with retriable error. retrying." , this ) ; } cleanupAndRecreateTempContexts ( ) ; this . waitBeforeRetrying ( ) ; } else throw this ; return retriesLeft ; } | must not be called from within a transaction unless the work is being done async in a non - tx thread . |
23,859 | public void prepareTables ( ) throws Exception { Path ddlPath = Paths . get ( ClassLoader . getSystemResource ( "sql" ) . toURI ( ) ) ; try ( Connection conn = xaConnectionManager . getConnection ( ) ; ) { Files . walk ( ddlPath , 1 ) . filter ( path -> ! Files . isDirectory ( path ) && ( path . toString ( ) . endsWith ( "ddl" ) || path . toString ( ) . endsWith ( "idx" ) ) ) . forEach ( path -> { try { RunScript . execute ( conn , Files . newBufferedReader ( path ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Exception at table initialization" , e ) ; } } ) ; } } | This is not typically done in production app . |
23,860 | public MergeOptions < E > doNotUpdate ( Attribute ... attributes ) { if ( this . doNotUpdate == null ) { this . doNotUpdate = attributes ; } else { List < Attribute > all = FastList . newListWith ( this . doNotUpdate ) ; for ( Attribute a : attributes ) all . add ( a ) ; this . doNotUpdate = new Attribute [ all . size ( ) ] ; all . toArray ( this . doNotUpdate ) ; } return this ; } | Do not update these attributes |
23,861 | private void extractMithraInterfaces ( Map < String , MithraInterfaceType > mithraInterfaces , List < String > errors ) { for ( String mithraInterfaceType : this . getWrapped ( ) . getMithraInterfaces ( ) ) { MithraInterfaceType mithraInterfaceObject = mithraInterfaces . get ( mithraInterfaceType ) ; if ( mithraInterfaceObject != null ) { boolean hasAllInterfaceAttributes = validateObjectHasAllMithraInterfaceAttributes ( mithraInterfaceObject , errors ) ; boolean hasAllInterfaceRelationships = validateObjectHasAllMithraInterfaceRelationships ( mithraInterfaceObject , mithraInterfaces , errors ) ; if ( hasAllInterfaceAttributes && hasAllInterfaceRelationships ) { this . mithraInterfaces . add ( mithraInterfaceObject ) ; this . addToRequiredClasses ( mithraInterfaceObject . getPackageName ( ) , mithraInterfaceObject . getClassName ( ) ) ; this . addToRequiredClasses ( mithraInterfaceObject . getPackageName ( ) , mithraInterfaceObject . getClassName ( ) + "Finder" ) ; } } } } | For each finder interface validate the |
23,862 | public void addRelationshipFilter ( RelatedFinder relatedFinder , Operation filter ) { Operation existing = this . filters . get ( relatedFinder ) ; this . filters . put ( relatedFinder , existing == null ? filter : existing . or ( filter ) ) ; } | Add a filter to be applied to the result of a traversed relationship . |
23,863 | public void extract ( ) { ExecutorService executor = Executors . newFixedThreadPool ( this . extractorConfig . getThreadPoolSize ( ) ) ; try { Map < Pair < RelatedFinder , Object > , List < MithraDataObject > > extract = extractData ( executor ) ; writeToFiles ( executor , extract ) ; } finally { executor . shutdown ( ) ; try { executor . awaitTermination ( extractorConfig . getTimeoutSeconds ( ) , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { } } } | Extract data and related data from the root operations added and write extracted data to text files as defined by OutputStrategy . |
23,864 | public Object getFromSemiUnique ( Object dataHolder , List extractors ) { Object result = null ; TransactionLocalStorage txStorage = ( TransactionLocalStorage ) perTransactionStorage . get ( MithraManagerProvider . getMithraManager ( ) . zGetCurrentTransactionWithNoCheck ( ) ) ; FullSemiUniqueDatedIndex perThreadAdded = this . getPerThreadAddedIndex ( txStorage ) ; if ( perThreadAdded != null ) { result = perThreadAdded . getFromSemiUnique ( dataHolder , extractors ) ; } if ( result != null ) { int startIndex = this . semiUniqueExtractors . length ; int length = extractors . size ( ) - startIndex ; boolean matchMoreThanOne = false ; for ( int i = 0 ; i < length ; i ++ ) { AsOfExtractor extractor = ( AsOfExtractor ) extractors . get ( startIndex + i ) ; matchMoreThanOne = matchMoreThanOne || extractor . matchesMoreThanOne ( ) ; } if ( matchMoreThanOne ) { Object mainIndexResult = this . mainIndex . getFromSemiUnique ( dataHolder , extractors ) ; result = checkDeleted ( result , txStorage , mainIndexResult ) ; } } else { result = this . mainIndex . getFromSemiUnique ( dataHolder , extractors ) ; result = this . checkDeletedIndex ( result , txStorage ) ; } return result ; } | new to differentiate |
23,865 | public int execute ( ) throws IOException { Runtime runtime = Runtime . getRuntime ( ) ; int exitCode = - 1 ; TerminateProcessThread terminateProcess = null ; Process process = null ; try { String [ ] command = ( String [ ] ) this . command . toArray ( new String [ this . command . size ( ) ] ) ; if ( this . workingDirectory != null ) { process = runtime . exec ( command , null , this . workingDirectory ) ; } else { process = runtime . exec ( command ) ; } this . handler . setErrorStream ( process . getErrorStream ( ) ) ; this . handler . setInputStream ( process . getInputStream ( ) ) ; this . handler . setOutputStream ( process . getOutputStream ( ) ) ; this . handler . start ( ) ; if ( this . terminateOnJvmExit ) { terminateProcess = new TerminateProcessThread ( process ) ; runtime . addShutdownHook ( terminateProcess ) ; } exitCode = process . waitFor ( ) ; } catch ( InterruptedException e ) { process . destroy ( ) ; } finally { this . handler . stop ( ) ; if ( terminateProcess != null ) { runtime . removeShutdownHook ( terminateProcess ) ; } if ( process != null ) { closeStreams ( process ) ; } } return exitCode ; } | Executes the process . |
23,866 | protected long scanPagesToSend ( long maxClientReplicatedPageVersion , FastUnsafeOffHeapIntList pagesToSend ) { long maxPageVersion = 0 ; boolean upgraded = false ; for ( int i = 0 ; i < this . pageVersionList . size ( ) ; i ++ ) { if ( pageVersionList . get ( i ) == 0 && ! upgraded ) { boolean originalLockWasReleased = this . readWriteLock . upgradeToWriteLock ( ) ; this . currentPageVersion ++ ; if ( originalLockWasReleased ) { pagesToSend . clear ( ) ; for ( int j = 0 ; j < i ; j ++ ) { maxPageVersion = markAndAddPageIfRequired ( maxClientReplicatedPageVersion , pagesToSend , maxPageVersion , j ) ; } } upgraded = true ; } maxPageVersion = markAndAddPageIfRequired ( maxClientReplicatedPageVersion , pagesToSend , maxPageVersion , i ) ; } return maxPageVersion ; } | Method is protected for testing purposes only |
23,867 | private synchronized void expungeStaleEntries ( ) { if ( size == 0 ) return ; Object r ; while ( ( r = queue . poll ( ) ) != null ) { Entry e = ( Entry ) r ; unlink ( e ) ; int h = e . hash ; int i = indexFor ( h , table . length ) ; Entry prev = table [ i ] ; Entry p = prev ; while ( p != null ) { Entry next = p . next ; if ( p == e ) { if ( prev == e ) table [ i ] = next ; else prev . next = next ; e . next = null ; size -- ; break ; } prev = p ; p = next ; } } } | Expunge stale entries from the table . |
23,868 | public String getReverseRelationshipName ( ) { String ret = "" ; if ( tableAB == null ) { if ( multipleRelationsBetweenTables ) { ret = concatenateColumnNames ( this ) ; ret = ret . substring ( 1 ) + "_" ; } ret += StringUtility . firstLetterToLower ( tableA . getClassName ( ) ) ; } else { ForeignKey [ ] fks = tableAB . getForeignKeys ( ) . values ( ) . toArray ( new ForeignKey [ 2 ] ) ; ret = ForeignKey . concatenateColumnNames ( fks [ 0 ] ) . substring ( 1 ) ; } String multiplicity = getTableAMultiplicity ( ) ; if ( ! multiplicity . equals ( "one" ) ) ret = StringUtility . englishPluralize ( ret ) ; return ret ; } | TableA as property name in TableB |
23,869 | public String getRelationshipName ( ) { String ret ; if ( tableAB == null ) { ret = concatenateColumnNames ( this ) ; ret = ret . substring ( 1 ) ; } else { ForeignKey [ ] fks = tableAB . getForeignKeys ( ) . values ( ) . toArray ( new ForeignKey [ 2 ] ) ; ret = ForeignKey . concatenateColumnNames ( fks [ 1 ] ) . substring ( 1 ) ; } String multiplicity = getTableBMultiplicity ( ) ; if ( ! multiplicity . equals ( "one" ) ) ret = StringUtility . englishPluralize ( ret ) ; return ret ; } | TableB as property name in TableA |
23,870 | public String getTableAMultiplicity ( ) { String ret = "many" ; List < ColumnInfo > tableAPKs = tableA . getPkList ( ) ; if ( tableAPKs . size ( ) == 0 || tableA . getTableName ( ) . equals ( tableB . getTableName ( ) ) ) { return ret ; } if ( tableAB == null ) { List < ColumnInfo > fkColumns = this . getColumns ( ) ; Set < ColumnInfo > columnSet = new HashSet < ColumnInfo > ( ) ; columnSet . addAll ( fkColumns ) ; columnSet . removeAll ( tableAPKs ) ; if ( fkColumns . size ( ) == tableAPKs . size ( ) && columnSet . isEmpty ( ) ) { ret = "one" ; return ret ; } } for ( ForeignKey tableBFK : tableB . getForeignKeys ( ) . values ( ) ) { if ( ! tableBFK . getTableB ( ) . getTableName ( ) . equals ( tableA . getTableName ( ) ) ) continue ; List < ColumnInfo > tableBRefCols = tableBFK . getRefColumns ( ) ; Set < ColumnInfo > columns = new HashSet < ColumnInfo > ( ) ; columns . addAll ( tableBRefCols ) ; columns . removeAll ( tableAPKs ) ; if ( columns . isEmpty ( ) ) { ret = "one" ; break ; } } return ret ; } | Otherwise it is a 1 - 1 relationship . |
23,871 | public MutableIntSet asSet ( List < T > list , MutableIntSet setToAppend ) { asSet ( list , this , setToAppend ) ; return setToAppend ; } | extracts the int values represented by this attribute from the list and adds them to the setToAppend . If the int attribute is null it s ignored . |
23,872 | public < R > R executeTransactionalCommandInSeparateThread ( final TransactionalCommand < R > command ) throws MithraBusinessException { return this . executeTransactionalCommandInSeparateThread ( command , this . defaultTransactionStyle ) ; } | Use this method very carefully . It can easily lead to a deadlock . executes the transactional command in a separate thread . Using a separate thread creates a brand new transactional context and therefore this transaction will not join the context of any outer transactions . For example if the outer transaction rolls back this command will not . Calling this method will lead to deadlock if the outer transaction has locked any object that will be accessed in this transaction . It can also lead to deadlock if the same table is accessed in the outer transaction as this command . It can also lead to a deadlock if the connection pool is tied up in the outer transaction and has nothing left for this command . |
23,873 | public < R > R executeTransactionalCommand ( final TransactionalCommand < R > command , final int retryCount ) throws MithraBusinessException { return this . executeTransactionalCommand ( command , new TransactionStyle ( this . transactionTimeout , retryCount ) ) ; } | executes the given transactional command with the custom number of retries |
23,874 | public < R > R executeTransactionalCommand ( final TransactionalCommand < R > command , final TransactionStyle style ) throws MithraBusinessException { String commandName = command . getClass ( ) . getName ( ) ; MithraTransaction tx = this . getCurrentTransaction ( ) ; if ( tx != null ) { try { return command . executeTransaction ( tx ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Throwable throwable ) { getLogger ( ) . error ( commandName + " rolled back tx, will not retry." , throwable ) ; tx . expectRollbackWithCause ( throwable ) ; throw new MithraBusinessException ( commandName + " transaction failed" , throwable ) ; } } R result = null ; int retryCount = style . getRetries ( ) + 1 ; do { try { tx = this . startOrContinueTransaction ( style ) ; tx . setTransactionName ( "Transactional Command: " + commandName ) ; result = command . executeTransaction ( tx ) ; tx . commit ( ) ; retryCount = 0 ; } catch ( Throwable throwable ) { retryCount = MithraTransaction . handleTransactionException ( tx , throwable , retryCount , style ) ; } } while ( retryCount > 0 ) ; return result ; } | executes the given transactional command with the custom transaction style . |
23,875 | public void zLazyInitObjectsWithCallback ( MithraRuntimeType mithraRuntimeType , MithraConfigurationManager . PostInitializeHook hook ) { configManager . lazyInitObjectsWithCallback ( mithraRuntimeType , hook ) ; } | only used for MithraTestResource . Do not use . use readConfiguration instead . |
23,876 | public synchronized void clear ( ) { pool . forEachUntil ( new DoUntilProcedure < E > ( ) { public boolean execute ( E object ) { destroyObject ( object ) ; return false ; } } ) ; pool . clear ( ) ; numActive = 0 ; notifyAll ( ) ; } | Clears any objects sitting idle in the pool . |
23,877 | public void evict ( ) throws Exception { assertOpen ( ) ; boolean isEmpty ; synchronized ( this ) { isEmpty = pool . isEmpty ( ) ; } if ( ! isEmpty ) { if ( softMinEvictableIdleTimeMillis > 0 ) { int numToEvict = getNumIdle ( ) - getMinIdle ( ) ; evict ( System . currentTimeMillis ( ) - softMinEvictableIdleTimeMillis , numToEvict ) ; } if ( minEvictableIdleTimeMillis > 0 ) { int numToEvict = getNumIdle ( ) ; evict ( System . currentTimeMillis ( ) - minEvictableIdleTimeMillis , numToEvict ) ; } } } | Make one pass of the idle object evictor . |
23,878 | protected List convertToBusinessObjectAndWrapInList ( Object o , Extractor [ ] extractors , Timestamp [ ] asOfDates , boolean weak , boolean isLocked ) { if ( ! ( o instanceof List ) ) { if ( o == null ) { return ListFactory . EMPTY_LIST ; } MithraDataObject data = ( MithraDataObject ) o ; this . extractTimestampsFromData ( data , extractors , asOfDates ) ; return ListFactory . create ( this . getBusinessObjectFromData ( data , asOfDates , getNonDatedPkHashCode ( data ) , weak , isLocked ) ) ; } else { List result = ( List ) o ; boolean perData = isExtractorPerData ( extractors , asOfDates ) ; if ( ! perData && MithraCpuBoundThreadPool . isParallelizable ( result . size ( ) ) ) { convertToBusinessObjectsInParallel ( result , asOfDates , weak ) ; } else { for ( int i = 0 ; i < result . size ( ) ; i ++ ) { MithraDataObject data = ( MithraDataObject ) result . get ( i ) ; if ( perData ) this . extractTimestampsFromData ( data , extractors , asOfDates ) ; result . set ( i , this . getBusinessObjectFromData ( data , asOfDates , getNonDatedPkHashCode ( data ) , weak , isLocked ) ) ; } } return result ; } } | if o is a list we do the conversion in place |
23,879 | public Timestamp getOrAddToCache ( Timestamp newValue , boolean hard ) { if ( newValue == null || newValue instanceof CachedImmutableTimestamp || newValue == NullDataTimestamp . getInstance ( ) ) { return newValue ; } return ( Timestamp ) weakPool . getIfAbsentPut ( newValue , hard ) ; } | return the pooled value |
23,880 | public void clear ( ) { emptyReferenceQueue ( ) ; for ( int i = 0 ; i < table . length ; i ++ ) { Entry e = table [ i ] ; Entry first = null ; Entry prev = null ; while ( e != null ) { Object candidate = e . get ( ) ; if ( candidate != null ) { Entry dirty = e . makeDirtyAndWeak ( queue ) ; if ( first == null ) { first = dirty ; } if ( prev != null ) { prev . setNext ( dirty ) ; } prev = dirty ; } else { if ( prev != null ) { prev . setNext ( e . getState ( ) . next ) ; } size -- ; } e = e . getState ( ) . next ; } table [ i ] = first ; } expungeStaleEntries ( ) ; } | we don t actually clear anything just make things weak and dirty |
23,881 | public void addMithraNotificationEventForUpdate ( String databaseIdentifier , String classname , byte databaseOperation , MithraDataObject mithraDataObject , List updateWrappers , Object sourceAttribute ) { MithraDataObject [ ] dataObjects = new MithraDataObject [ 1 ] ; dataObjects [ 0 ] = mithraDataObject ; createAndAddNotificationEvent ( databaseIdentifier , classname , databaseOperation , dataObjects , updateWrappers , null , sourceAttribute ) ; } | This is called from single insert update or delete . |
23,882 | private RegistrationEntryList getRegistrationEntryList ( String subject , RelatedFinder finder ) { RegistrationEntryList registrationEntryList ; RegistrationKey key = new RegistrationKey ( subject , finder . getFinderClassName ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "**************Adding application notification registration with key: " + key . toString ( ) ) ; } registrationEntryList = mithraApplicationNotificationSubscriber . get ( key ) ; if ( registrationEntryList == null ) { registrationEntryList = new RegistrationEntryList ( ) ; mithraApplicationNotificationSubscriber . put ( key , registrationEntryList ) ; } return registrationEntryList ; } | Must only be called from the thread which is used for registration |
23,883 | public Connection makeObject ( ObjectPoolWithThreadAffinity < Connection > pool ) throws Exception { Connection conn = connectionFactory . createConnection ( ) ; return new PooledConnection ( conn , pool , this . statementsToPool ) ; } | overriding to remove synchronized . We never mutate any state that affects this method |
23,884 | public void initialisePool ( ) { Properties loginProperties = createLoginProperties ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "about to create pool with user-id : " + this . getJdbcUser ( ) ) ; } ConnectionFactory connectionFactory = createConnectionFactory ( loginProperties ) ; PoolableObjectFactory objectFactoryForConnectionPool = getObjectFactoryForConnectionPool ( connectionFactory , connectionPool ) ; connectionPool = new ObjectPoolWithThreadAffinity ( objectFactoryForConnectionPool , this . getPoolSize ( ) , this . getMaxWait ( ) , this . getPoolSize ( ) , this . getInitialSize ( ) , true , false , this . timeBetweenEvictionRunsMillis , this . minEvictableIdleTimeMillis , this . softMinEvictableIdleTimeMillis ) ; dataSource = createPoolingDataSource ( connectionPool ) ; if ( this . getInitialSize ( ) > 0 ) { try { this . getConnection ( ) . close ( ) ; } catch ( Exception e ) { logger . error ( "Error initializing pool " + this , e ) ; } } } | This method must be called after all the connection pool properties have been set . |
23,885 | public void setDriverClassName ( String driver ) { try { this . driver = ( Driver ) Class . forName ( driver ) . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to load driver: " + driver , e ) ; } } | sets the driver class name . This is used in conjunction with the JDBC connection string |
23,886 | public void setMaxRetriesBeforeRequeue ( int maxRetriesBeforeRequeue ) { this . maxRetriesBeforeRequeue = maxRetriesBeforeRequeue ; this . transactionStyle = new TransactionStyle ( MithraManagerProvider . getMithraManager ( ) . getTransactionTimeout ( ) , maxRetriesBeforeRequeue , this . retryOnTimeout ) ; } | default value is 3 . |
23,887 | private void validateOrderByAttribute ( String attributeName ) { if ( ( ! nameToAggregateAttributeMap . containsKey ( attributeName ) ) && ( ! nameToGroupByAttributeMap . containsKey ( attributeName ) ) ) { throw new MithraBusinessException ( "Aggregate list cannot be order by attribute with name: " + attributeName + ".\n" + "An AggregateList can only be ordered by an attribute which is either a AggregateAttribute or a GroupByAttribute" ) ; } } | The attribute to group by should be either a aggregate attribute or a group by attribute . |
23,888 | public MithraRuntimeType parseConfiguration ( InputStream mithraFileIs ) { if ( mithraFileIs == null ) { throw new MithraBusinessException ( "Could not parse Mithra configuration, because the input stream is null." ) ; } try { MithraRuntimeUnmarshaller unmarshaller = new MithraRuntimeUnmarshaller ( ) ; unmarshaller . setValidateAttributes ( false ) ; return unmarshaller . parse ( mithraFileIs , "" ) ; } catch ( IOException e ) { throw new MithraBusinessException ( "unable to parse " , e ) ; } finally { try { mithraFileIs . close ( ) ; } catch ( IOException e ) { getLogger ( ) . error ( "Could not close Mithra XML input stream" , e ) ; } } } | Parses the configuration file . Should only be called by MithraTestResource . Use readConfiguration to parse and initialize the configuration . |
23,889 | private synchronized boolean expungeStaleEntries ( ) { if ( this . size == 0 ) return false ; Object r ; boolean result = false ; while ( ( r = queue . poll ( ) ) != null ) { result = true ; SingleEntry e = ( SingleEntry ) r ; this . size -= e . cleanupPkTable ( this . table ) ; this . nonDatedEntryCount -= e . cleanupSemiUniqueTable ( this . nonDatedTable ) ; } return result ; } | Expunge stale entries from the nonDatedTable . |
23,890 | private void resizeSemiUnique ( int newCapacity ) { SemiUniqueEntry [ ] oldTable = getNonDatedTable ( ) ; int oldCapacity = oldTable . length ; if ( oldCapacity == MAXIMUM_CAPACITY ) { semiUniqueThreshold = Integer . MAX_VALUE ; return ; } SemiUniqueEntry [ ] newTable = new SemiUniqueEntry [ newCapacity ] ; transferSemiUnique ( oldTable , newTable ) ; nonDatedTable = newTable ; if ( nonDatedEntryCount >= semiUniqueThreshold / 2 ) { semiUniqueThreshold = ( int ) ( newCapacity * loadFactor ) ; } else { expungeStaleEntries ( ) ; transferSemiUnique ( newTable , oldTable ) ; nonDatedTable = oldTable ; } } | Rehashes the contents of this map into a new array with a larger capacity . This method is called automatically when the number of keys in this map reaches its semiUniqueThreshold . |
23,891 | private void resize ( Object [ ] oldTable , int newSize ) { int oldCapacity = oldTable . length ; int end = oldCapacity - 1 ; Object last = arrayAt ( oldTable , end ) ; if ( this . size ( ) < ( ( end * 3 ) >> 2 ) && last == RESIZE_SENTINEL ) { return ; } if ( oldCapacity >= MAXIMUM_CAPACITY ) { throw new RuntimeException ( "max capacity of map exceeded" ) ; } ResizeContainer resizeContainer = null ; boolean ownResize = false ; if ( last == null || last == RESIZE_SENTINEL ) { synchronized ( oldTable ) { if ( arrayAt ( oldTable , end ) == null ) { setArrayAt ( oldTable , end , RESIZE_SENTINEL ) ; resizeContainer = new ResizeContainer ( allocateTable ( newSize ) , oldTable . length - 2 ) ; setArrayAt ( oldTable , end , resizeContainer ) ; ownResize = true ; } } } if ( ownResize ) { this . transfer ( oldTable , resizeContainer ) ; Object [ ] src = this . table ; while ( ! TABLE_UPDATER . compareAndSet ( this , oldTable , resizeContainer . nextArray ) ) { if ( src != oldTable ) { this . helpWithResize ( src ) ; } } } else { this . helpWithResize ( oldTable ) ; } } | newSize must be a power of 2 + 1 |
23,892 | public void forAllInParallel ( final ParallelProcedure procedure ) { MithraCpuBoundThreadPool pool = MithraCpuBoundThreadPool . getInstance ( ) ; final Object [ ] set = this . table ; ThreadChunkSize threadChunkSize = new ThreadChunkSize ( pool . getThreads ( ) , set . length - 2 , 1 ) ; final ArrayBasedQueue queue = new ArrayBasedQueue ( set . length - 2 , threadChunkSize . getChunkSize ( ) ) ; int threads = threadChunkSize . getThreads ( ) ; procedure . setThreads ( threads , this . size ( ) / threads ) ; CpuBoundTask [ ] tasks = new CpuBoundTask [ threads ] ; for ( int i = 0 ; i < threads ; i ++ ) { final int thread = i ; tasks [ i ] = new CpuBoundTask ( ) { public void execute ( ) { ArrayBasedQueue . Segment segment = queue . borrow ( null ) ; while ( segment != null ) { for ( int i = segment . getStart ( ) ; i < segment . getEnd ( ) ; i ++ ) { Object e = arrayAt ( set , i ) ; if ( e != null ) { procedure . execute ( e , thread ) ; } } segment = queue . borrow ( segment ) ; } } } ; } new FixedCountTaskFactory ( tasks ) . startAndWorkUntilFinished ( ) ; } | does not allow concurrent iteration with additions to the index |
23,893 | public DependentKeyIndex createDependentKeyIndex ( CacheLoaderEngine cacheLoaderEngine , Extractor [ ] keyExtractors , Operation ownerObjectFilter ) { DependentKeyIndex dependentKeyIndex = null ; for ( DependentKeyIndex each : this . dependentKeyIndexes ) { if ( Arrays . equals ( each . getKeyExtractors ( ) , keyExtractors ) ) { dependentKeyIndex = each ; break ; } } if ( dependentKeyIndex == null ) { dependentKeyIndex = ( keyExtractors . length > 1 ) ? new DependentTupleKeyIndex ( cacheLoaderEngine , this , keyExtractors ) : new DependentSingleKeyIndex ( cacheLoaderEngine , this , keyExtractors ) ; dependentKeyIndex . setOwnerObjectFilter ( ownerObjectFilter ) ; final LoadingTaskThreadPoolHolder threadPoolHolder = cacheLoaderEngine . getOrCreateThreadPool ( this . getThreadPoolName ( ) ) ; dependentKeyIndex . setLoadingTaskThreadPoolHolder ( threadPoolHolder ) ; threadPoolHolder . addDependentKeyIndex ( dependentKeyIndex ) ; this . dependentKeyIndexes . add ( dependentKeyIndex ) ; } else { dependentKeyIndex . orOwnerObjectFilter ( ownerObjectFilter ) ; } return dependentKeyIndex ; } | executed from a single thread during the cacheloader startup . |
23,894 | public Operation createMappedOperationForDeepFetch ( Mapper mapper ) { Operation rootOperation = this . getRootOperation ( ) ; if ( rootOperation == null ) return null ; return mapper . createMappedOperationForDeepFetch ( rootOperation ) ; } | mapper is not necessarily this . relatedFinder . mapper . chained mapper and linked mapper s callbacks . |
23,895 | public Operation getSimplifiedJoinOp ( Mapper mapper , List parentList ) { int maxSimplifiedIn = DeepRelationshipUtility . MAX_SIMPLIFIED_IN ; boolean differentPersisterThanParent = differentPersisterIdThanParent ( mapper ) ; if ( differentPersisterThanParent ) { maxSimplifiedIn = Integer . MAX_VALUE ; } return mapper . getSimplifiedJoinOp ( parentList , maxSimplifiedIn , this , differentPersisterThanParent ) ; } | mapper is not necessarily this . relatedFinder . mapper . chained mapper |
23,896 | protected void zSetData ( MithraDataObject data ) { this . currentData = data ; this . persistenceState = PersistenceState . PERSISTED ; MithraTransaction currentTransaction = MithraManagerProvider . getMithraManager ( ) . getCurrentTransaction ( ) ; if ( currentTransaction != null && zGetPortal ( ) . getTxParticipationMode ( currentTransaction ) . mustParticipateInTxOnRead ( ) ) { this . transactionalState = currentTransaction . getReadLockedTransactionalState ( null , PersistenceState . PERSISTED ) ; } } | also called after constructing a new object for remote insert non - persistent copy and detached copy |
23,897 | public static int calculateQuotientScale ( int precision1 , int scale1 , int precision2 , int scale2 ) { return Math . max ( scale1 + precision2 - scale2 + 1 , 6 ) ; } | From the Sybase Transact - SQL user guide |
23,898 | protected void onSizeChanged ( int w , int h , int oldw , int oldh ) { super . onSizeChanged ( w , h , oldw , oldh ) ; mAreDimensionsInvalid = true ; } | fix rotation changes |
23,899 | private Calendar getTimeFromPoint ( float x , float y ) { int leftDaysWithGaps = ( int ) - ( Math . ceil ( mCurrentOrigin . x / ( mWidthPerDay + mColumnGap ) ) ) ; float startPixel = mCurrentOrigin . x + ( mWidthPerDay + mColumnGap ) * leftDaysWithGaps + mHeaderColumnWidth ; for ( int dayNumber = leftDaysWithGaps + 1 ; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1 ; dayNumber ++ ) { float start = ( startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel ) ; if ( mWidthPerDay + startPixel - start > 0 && x > start && x < startPixel + mWidthPerDay ) { Calendar day = today ( ) ; day . add ( Calendar . DATE , dayNumber - 1 ) ; float pixelsFromZero = y - mCurrentOrigin . y - mHeaderHeight - mHeaderRowPadding * 2 - mTimeTextHeight / 2 - mHeaderMarginBottom ; int hour = ( int ) ( pixelsFromZero / mHourHeight ) ; int minute = ( int ) ( 60 * ( pixelsFromZero - hour * mHourHeight ) / mHourHeight ) ; day . add ( Calendar . HOUR , hour ) ; day . set ( Calendar . MINUTE , minute ) ; return day ; } startPixel += mWidthPerDay + mColumnGap ; } return null ; } | Get the time and date where the user clicked on . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.