idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
3,400
public static void main ( String [ ] args ) throws Exception { for ( String arg : args ) { Class clazz = Class . forName ( arg ) ; System . out . println ( "Examining: " + clazz . getName ( ) ) ; try { examine ( clazz ) ; System . out . println ( "Passed" ) ; } catch ( MalformedTypeException e ) { System . out . println ( "Malformed type: " + e . getMalformedType ( ) . getName ( ) ) ; for ( String message : e . getMessages ( ) ) { System . out . println ( message ) ; } } } }
Test program which examines candidate Storable classes . If any fail an exception is thrown .
3,401
@ SuppressWarnings ( "unchecked" ) private static void checkTypeParameter ( List < String > errorMessages , Class type ) { if ( type != null && Storable . class . isAssignableFrom ( type ) ) { if ( Storable . class == type ) { return ; } } else { return ; } checkTypeParameter ( errorMessages , type . getSuperclass ( ) ) ; for ( Class c : type . getInterfaces ( ) ) { checkTypeParameter ( errorMessages , c ) ; } for ( Type t : type . getGenericInterfaces ( ) ) { if ( t instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) t ; if ( pt . getRawType ( ) == Storable . class ) { Type arg = pt . getActualTypeArguments ( ) [ 0 ] ; Class param ; if ( arg instanceof ParameterizedType ) { Type raw = ( ( ParameterizedType ) arg ) . getRawType ( ) ; if ( raw instanceof Class ) { param = ( Class ) raw ; } else { continue ; } } else if ( arg instanceof Class ) { param = ( Class ) arg ; } else if ( arg instanceof TypeVariable ) { continue ; } else { continue ; } if ( Storable . class . isAssignableFrom ( param ) ) { if ( ! param . isAssignableFrom ( type ) ) { errorMessages . add ( "Type parameter passed from " + type + " to Storable must be a " + type . getName ( ) + ": " + param ) ; return ; } } else { errorMessages . add ( "Type parameter passed from " + type + " to Storable must be a Storable: " + param ) ; return ; } } } } }
Make sure that the parameter type that is specified to Storable can be assigned to a Storable and that the given type can be assigned to it . Put another way the upper bound is Storable and the lower bound is the given type . type < = parameterized type < = Storable
3,402
private static Map < String , Method > gatherAllDeclaredMethods ( Class clazz ) { Map < String , Method > methods = new HashMap < String , Method > ( ) ; gatherAllDeclaredMethods ( methods , clazz ) ; return methods ; }
Returns a new modifiable mapping of method signatures to methods .
3,403
private static String createSig ( Method m ) { return m . getName ( ) + ':' + MethodDesc . forMethod ( m ) . getDescriptor ( ) ; }
Create a representation of the signature which includes the method name . This uniquely identifies the method .
3,404
private void ensureLengthForWrite ( int ilength ) { if ( ilength > mLength ) { if ( ilength <= mData . length ) { mLength = ilength ; } else { int newLength = mData . length * 2 ; if ( newLength < ilength ) { newLength = ilength ; } byte [ ] newData = new byte [ newLength ] ; System . arraycopy ( mData , 0 , newData , 0 , mLength ) ; mData = newData ; } mLength = ilength ; } }
Caller must be synchronized
3,405
@ SuppressWarnings ( "unchecked" ) static < S extends Storable > Class < ? extends S > getStorableClass ( Class < S > type , boolean isMaster ) throws SupportException { synchronized ( cCache ) { Class < ? extends S > storableClass ; RawStorableGenerator . Flavors < S > flavors = ( RawStorableGenerator . Flavors < S > ) cCache . get ( type ) ; if ( flavors == null ) { flavors = new RawStorableGenerator . Flavors < S > ( ) ; cCache . put ( type , flavors ) ; } else if ( ( storableClass = flavors . getClass ( isMaster ) ) != null ) { return storableClass ; } storableClass = generateStorableClass ( type , isMaster ) ; flavors . setClass ( storableClass , isMaster ) ; return storableClass ; } }
Returns a storable implementation that calls into CustomStorableCodec implementation for encoding and decoding .
3,406
@ SuppressWarnings ( "unchecked" ) public StorableIndex < S > buildPkIndex ( String ... propertyNames ) { Map < String , ? extends StorableProperty < S > > map = getAllProperties ( ) ; int length = propertyNames . length ; StorableProperty < S > [ ] properties = new StorableProperty [ length ] ; Direction [ ] directions = new Direction [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { String name = propertyNames [ i ] ; char c = name . charAt ( 0 ) ; Direction dir = Direction . fromCharacter ( c ) ; if ( dir != Direction . UNSPECIFIED || c == Direction . UNSPECIFIED . toCharacter ( ) ) { name = name . substring ( 1 ) ; } else { dir = Direction . ASCENDING ; } if ( ( properties [ i ] = map . get ( name ) ) == null ) { throw new IllegalArgumentException ( "Unknown property: " + name ) ; } directions [ i ] = dir ; } return new StorableIndex < S > ( properties , directions , true , true ) ; }
Convenient way to define the clustered primary key index descriptor . Direction can be specified by prefixing the property name with a + or - . If unspecified direction is assumed to be ascending .
3,407
public int getPreviousRemaining ( ) { int remaining = mPrevRemaining ; if ( remaining < 0 ) { mPrevRemaining = remaining = ( ( mPrev == null ) ? 0 : ( mPrev . getPreviousRemaining ( ) + 1 ) ) ; } return remaining ; }
Returns the amount of previous remaining list nodes .
3,408
public int getBlankCount ( ) { int count = mBlankCount ; if ( count < 0 ) { mBlankCount = count = ( mPropFilter . isConstant ( ) ? 0 : 1 ) + ( ( mPrev == null ) ? 0 : mPrev . getBlankCount ( ) ) ; } return count ; }
Returns the amount of non - constant list nodes up to this node .
3,409
public boolean contains ( PropertyFilter < S > propFilter ) { if ( mPropFilter == propFilter ) { return true ; } if ( mNext == null ) { return false ; } return mNext . contains ( propFilter ) ; }
Searches list for given PropertyFilter .
3,410
PropertyFilterList < S > prepend ( PropertyFilter < S > propFilter ) { PropertyFilterList < S > head = new PropertyFilterList < S > ( propFilter , this ) ; mPrev = head ; return head ; }
Prepend a node to the head of the list .
3,411
public boolean printNative ( Appendable app , int indentLevel , FilterValues < S > values ) throws IOException { return mExecutor . printNative ( app , indentLevel , values ) ; }
Prints native query of the wrapped executor .
3,412
@ SuppressWarnings ( "unchecked" ) static < S extends Storable > Factory < S > getFactory ( Filter < S > filter ) { if ( filter == null ) { throw new IllegalArgumentException ( ) ; } synchronized ( cCache ) { Factory < S > factory = ( Factory < S > ) cCache . get ( filter ) ; if ( factory != null ) { return factory ; } Class < Cursor < S > > clazz = generateClass ( filter ) ; factory = QuickConstructorGenerator . getInstance ( clazz , Factory . class ) ; cCache . put ( filter , factory ) ; return factory ; } }
Returns a factory for creating new filtered cursor instances .
3,413
public void appendTableNameAndAliasTo ( SQLStatementBuilder fromClause ) { appendTableNameTo ( fromClause ) ; fromClause . append ( ' ' ) ; fromClause . append ( mAlias ) ; }
Appends table name and alias to the given FROM clause builder .
3,414
static int compareWithNullHigh ( Object a , Object b ) { return a == null ? ( b == null ? 0 : - 1 ) : ( b == null ? 1 : ( ( Comparable ) a ) . compareTo ( b ) ) ; }
Compares two objects which are assumed to be Comparable . If one value is null it is treated as being higher . This consistent with all other property value comparisons in carbonado .
3,415
private void inflateView ( ) { parentView = createParentView ( ) ; view = createView ( ) ; view . setOnFocusChangeListener ( createFocusChangeListener ( ) ) ; view . setBackgroundResource ( R . drawable . validateable_view_background ) ; setLineColor ( getAccentColor ( ) ) ; if ( parentView != null ) { parentView . addView ( view , LayoutParams . MATCH_PARENT , LayoutParams . WRAP_CONTENT ) ; addView ( parentView , LayoutParams . MATCH_PARENT , LayoutParams . WRAP_CONTENT ) ; } else { addView ( view , LayoutParams . MATCH_PARENT , LayoutParams . WRAP_CONTENT ) ; } }
Inflates the view whose value should be able to be validated .
3,416
private void inflateErrorMessageTextViews ( ) { View parent = View . inflate ( getContext ( ) , R . layout . error_messages , null ) ; addView ( parent , LayoutParams . MATCH_PARENT , LayoutParams . WRAP_CONTENT ) ; leftMessage = parent . findViewById ( R . id . left_error_message ) ; leftMessage . setTag ( false ) ; rightMessage = parent . findViewById ( R . id . right_error_message ) ; rightMessage . setTag ( false ) ; }
Inflates the text views which are used to show validation errors .
3,417
private OnFocusChangeListener createFocusChangeListener ( ) { return new OnFocusChangeListener ( ) { public final void onFocusChange ( final View view , final boolean hasFocus ) { if ( ! hasFocus && isValidatedOnFocusLost ( ) ) { validate ( ) ; } } } ; }
Creates and returns a listener which allows to validate the value of the view when the view loses its focus .
3,418
private void notifyOnValidationFailure ( final Validator < ValueType > validator ) { for ( ValidationListener < ValueType > listener : listeners ) { listener . onValidationFailure ( this , validator ) ; } }
Notifies all registered listeners that a validation failed .
3,419
private Validator < ValueType > validateLeft ( ) { Validator < ValueType > result = null ; Collection < Validator < ValueType > > subValidators = onGetLeftErrorMessage ( ) ; if ( subValidators != null ) { for ( Validator < ValueType > validator : subValidators ) { notifyOnValidationFailure ( validator ) ; if ( result == null ) { result = validator ; } } } for ( Validator < ValueType > validator : validators ) { if ( ! validator . validate ( getValue ( ) ) ) { notifyOnValidationFailure ( validator ) ; if ( result == null ) { result = validator ; } } } return result ; }
Validates the current value of the view in order to retrieve the error message and icon which should be shown at the left edge of the view if a validation fails .
3,420
private Validator < ValueType > validateRight ( ) { Validator < ValueType > result = null ; Collection < Validator < ValueType > > subValidators = onGetRightErrorMessage ( ) ; if ( subValidators != null ) { for ( Validator < ValueType > validator : subValidators ) { notifyOnValidationFailure ( validator ) ; if ( result == null ) { result = validator ; } } } return result ; }
Validates the current value of the view in order to retrieve the error message and icon which should be shown at the right edge of the view if a validation fails .
3,421
private void setLineColor ( final int color ) { view . getBackground ( ) . setColorFilter ( color , PorterDuff . Mode . SRC_ATOP ) ; }
Sets the color of the view s line .
3,422
private void setEnabledOnViewGroup ( final ViewGroup viewGroup , final boolean enabled ) { viewGroup . setEnabled ( enabled ) ; for ( int i = 0 ; i < viewGroup . getChildCount ( ) ; i ++ ) { View child = viewGroup . getChildAt ( i ) ; if ( child instanceof ViewGroup ) { setEnabledOnViewGroup ( ( ViewGroup ) child , enabled ) ; } else { child . setEnabled ( enabled ) ; } } }
Adapts the enable state of all children of a specific view group .
3,423
private void setActivatedOnViewGroup ( final ViewGroup viewGroup , final boolean activated ) { viewGroup . setActivated ( activated ) ; for ( int i = 0 ; i < viewGroup . getChildCount ( ) ; i ++ ) { View child = viewGroup . getChildAt ( i ) ; if ( child instanceof ViewGroup ) { setActivatedOnViewGroup ( ( ViewGroup ) child , activated ) ; } else { child . setActivated ( activated ) ; } } }
Adapts the activated state of all children of a specific view group .
3,424
protected final void setLeftMessage ( final CharSequence message , final Drawable icon ) { setLeftMessage ( message , icon , true ) ; }
Shows a specific message which is marked as an error at the left edge of the view .
3,425
protected final void setLeftMessage ( final CharSequence message , final Drawable icon , final boolean error ) { if ( message != null ) { leftMessage . setText ( message ) ; leftMessage . setCompoundDrawablesWithIntrinsicBounds ( icon , null , null , null ) ; leftMessage . setTextColor ( error ? getErrorColor ( ) : getHelperTextColor ( ) ) ; leftMessage . setTag ( error ) ; leftMessage . setVisibility ( View . VISIBLE ) ; } else if ( getHelperText ( ) != null ) { setLeftMessage ( getHelperText ( ) , null , false ) ; } else { leftMessage . setTag ( false ) ; leftMessage . setVisibility ( View . GONE ) ; } }
Shows a specific message at the left edge of the view .
3,426
protected final void setRightMessage ( final CharSequence message , final boolean error ) { if ( message != null ) { rightMessage . setVisibility ( View . VISIBLE ) ; rightMessage . setText ( message ) ; rightMessage . setTextColor ( error ? getErrorColor ( ) : getHelperTextColor ( ) ) ; rightMessage . setTag ( error ) ; } else { rightMessage . setTag ( false ) ; rightMessage . setVisibility ( View . GONE ) ; } }
Shows a specific message at the right edge of the view .
3,427
public final void setHelperText ( final CharSequence helperText ) { this . helperText = helperText ; if ( getError ( ) == null ) { setLeftMessage ( helperText , null , false ) ; } }
Sets the helper text which should be shown when no validation error is currently shown .
3,428
public final void setErrorColor ( final int color ) { this . errorColor = color ; if ( ( Boolean ) leftMessage . getTag ( ) ) { leftMessage . setTextColor ( color ) ; } if ( ( Boolean ) rightMessage . getTag ( ) ) { rightMessage . setTextColor ( color ) ; } }
Sets the color which should be used to indicate validation errors .
3,429
public final void setHelperTextColor ( final int color ) { this . helperTextColor = color ; if ( ! ( Boolean ) leftMessage . getTag ( ) ) { leftMessage . setTextColor ( color ) ; } if ( ! ( Boolean ) rightMessage . getTag ( ) ) { rightMessage . setTextColor ( color ) ; } }
Sets the color of the helper text .
3,430
public final CharSequence getError ( ) { if ( leftMessage . getVisibility ( ) == View . VISIBLE && ( Boolean ) leftMessage . getTag ( ) ) { return leftMessage . getText ( ) ; } return null ; }
Returns the error message which has been previously set to be displayed .
3,431
public void setError ( final CharSequence error , final Drawable icon ) { setLeftMessage ( error , icon ) ; setActivated ( error != null ) ; }
Sets an error message and an icon which should be displayed .
3,432
public static boolean closeDataSource ( DataSource ds ) throws SQLException { try { Method closeMethod = ds . getClass ( ) . getMethod ( "close" ) ; try { closeMethod . invoke ( ds ) ; } catch ( Throwable e ) { ThrowUnchecked . fireFirstDeclaredCause ( e , SQLException . class ) ; } return true ; } catch ( NoSuchMethodException e ) { return false ; } }
Attempts to close a DataSource by searching for a close method . For some reason there s no standard way to close a DataSource .
3,433
< S extends Storable > JDBCStorableProperty < S > getJDBCStorableProperty ( StorableProperty < S > property ) throws RepositoryException , SupportException { JDBCStorableInfo < S > info = examineStorable ( property . getEnclosingType ( ) ) ; JDBCStorableProperty < S > jProperty = info . getAllProperties ( ) . get ( property . getName ( ) ) ; if ( ! jProperty . isSupported ( ) ) { throw new UnsupportedOperationException ( "Property is not supported: " + property . getName ( ) ) ; } return jProperty ; }
Convenience method to convert a regular StorableProperty into a JDBCStorableProperty .
3,434
public Connection getConnection ( ) throws FetchException { try { if ( mOpenConnections == null ) { throw new FetchException ( "Repository is closed" ) ; } JDBCTransaction txn = localTransactionScope ( ) . getTxn ( ) ; if ( txn != null ) { return txn . getConnection ( ) ; } Connection con = mDataSource . getConnection ( ) ; con . setAutoCommit ( true ) ; mOpenConnectionsLock . lock ( ) ; try { if ( mOpenConnections == null ) { con . close ( ) ; throw new FetchException ( "Repository is closed" ) ; } mOpenConnections . put ( con , null ) ; } finally { mOpenConnectionsLock . unlock ( ) ; } return con ; } catch ( Exception e ) { throw toFetchException ( e ) ; } }
Any connection returned by this method must be closed by calling yieldConnection on this repository .
3,435
Connection getConnectionForTxn ( IsolationLevel level ) throws FetchException { try { if ( mOpenConnections == null ) { throw new FetchException ( "Repository is closed" ) ; } Connection con = mDataSource . getConnection ( ) ; if ( level == IsolationLevel . NONE ) { con . setAutoCommit ( true ) ; } else { con . setAutoCommit ( false ) ; if ( level != mDefaultIsolationLevel ) { con . setTransactionIsolation ( mapIsolationLevelToJdbc ( level ) ) ; } } mOpenConnectionsLock . lock ( ) ; try { if ( mOpenConnections == null ) { con . close ( ) ; throw new FetchException ( "Repository is closed" ) ; } mOpenConnections . put ( con , null ) ; } finally { mOpenConnectionsLock . unlock ( ) ; } return con ; } catch ( Exception e ) { throw toFetchException ( e ) ; } }
Called by JDBCTransactionManager .
3,436
public void yieldConnection ( Connection con ) throws FetchException { try { if ( con . getAutoCommit ( ) ) { closeConnection ( con ) ; } } catch ( Exception e ) { throw toFetchException ( e ) ; } }
Gives up a connection returned from getConnection . Connection must be yielded in same thread that retrieved it .
3,437
public Object beforeInsert ( S storable ) throws PersistException { int length = mLobProperties . length ; Object [ ] userLobs = new Object [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { LobProperty < Lob > prop = mLobProperties [ i ] ; Object userLob = storable . getPropertyValue ( prop . mName ) ; userLobs [ i ] = userLob ; if ( userLob != null ) { Object lob = prop . createNewLob ( mBlockSize ) ; storable . setPropertyValue ( prop . mName , lob ) ; } } return userLobs ; }
Returns user specified Lob values
3,438
public Object beforeDelete ( S storable ) throws PersistException { S existing = ( S ) storable . copy ( ) ; try { if ( ! existing . tryLoad ( ) ) { existing = null ; } return existing ; } catch ( FetchException e ) { throw e . toPersistException ( ) ; } }
Returns existing Storable or null
3,439
public final void setRegex ( final Pattern regex ) { Condition . INSTANCE . ensureNotNull ( regex , "The regular expression may not be null" ) ; this . regex = regex ; }
Sets the regular expression which should be used to verify the texts .
3,440
Filter < S > parseRoot ( ) { Filter < S > filter = parseFilter ( ) ; int c = nextCharIgnoreWhitespace ( ) ; if ( c >= 0 ) { mPos -- ; throw error ( "Unexpected trailing characters" ) ; } return filter ; }
all rolled into one . This is okay since the grammar is so simple .
3,441
private int nextChar ( ) { String filter = mFilter ; int pos = mPos ; int c = ( pos >= filter . length ( ) ) ? - 1 : mFilter . charAt ( pos ) ; mPos = pos + 1 ; return c ; }
Returns - 1 if no more characters .
3,442
protected static byte [ ] getData ( byte [ ] data , int size ) { if ( data == null ) { return NO_DATA ; } if ( data . length <= size ) { return data ; } byte [ ] newData = new byte [ size ] ; System . arraycopy ( data , 0 , newData , 0 , size ) ; return newData ; }
If the given byte array is less than or equal to given size it is simply returned . Otherwise a new array is allocated and the data is copied .
3,443
protected static byte [ ] getDataCopy ( byte [ ] data , int size ) { if ( data == null ) { return NO_DATA ; } byte [ ] newData = new byte [ size ] ; System . arraycopy ( data , 0 , newData , 0 , size ) ; return newData ; }
Returns a copy of the data array .
3,444
public final void setEditText ( final EditText editText ) { Condition . INSTANCE . ensureNotNull ( editText , "The edit text widget may not be null" ) ; this . editText = editText ; }
Sets the edit text widget which contains the content the texts should be equal to .
3,445
public static boolean increment ( byte [ ] value ) { for ( int i = value . length ; -- i >= 0 ; ) { byte newValue = ( byte ) ( ( value [ i ] & 0xff ) + 1 ) ; value [ i ] = newValue ; if ( newValue != 0 ) { return true ; } } return false ; }
Adds one to an unsigned integer represented as a byte array . If overflowed value in byte array is 0x00 0x00 0x00 ...
3,446
public static boolean decrement ( byte [ ] value ) { for ( int i = value . length ; -- i >= 0 ; ) { byte newValue = ( byte ) ( ( value [ i ] & 0xff ) + - 1 ) ; value [ i ] = newValue ; if ( newValue != - 1 ) { return true ; } } return false ; }
Subtracts one from an unsigned integer represented as a byte array . If overflowed value in byte array is 0xff 0xff 0xff ...
3,447
public static < S extends Storable > CompositeScore < S > evaluate ( StorableIndex < S > index , Filter < S > filter , OrderingList < S > ordering ) { if ( index == null ) { throw new IllegalArgumentException ( "Index required" ) ; } return evaluate ( index . getOrderedProperties ( ) , index . isUnique ( ) , index . isClustered ( ) , filter , ordering ) ; }
Evaluates the given index for its filtering and ordering capabilities against the given filter and order - by properties .
3,448
public static < S extends Storable > CompositeScore < S > evaluate ( OrderedProperty < S > [ ] indexProperties , boolean unique , boolean clustered , Filter < S > filter , OrderingList < S > ordering ) { FilteringScore < S > filteringScore = FilteringScore . evaluate ( indexProperties , unique , clustered , filter ) ; OrderingScore < S > orderingScore = OrderingScore . evaluate ( indexProperties , unique , clustered , filter , ordering ) ; return new CompositeScore < S > ( filteringScore , orderingScore ) ; }
Evaluates the given index properties for its filtering and ordering capabilities against the given filter and order - by properties .
3,449
public boolean canMergeRemainder ( CompositeScore < S > other ) { return getFilteringScore ( ) . canMergeRemainderFilter ( other . getFilteringScore ( ) ) && getOrderingScore ( ) . canMergeRemainderOrdering ( other . getOrderingScore ( ) ) ; }
Returns true if the filtering score can merge its remainder filter and the ordering score can merge its remainder orderings .
3,450
public Filter < S > mergeRemainderFilter ( CompositeScore < S > other ) { return getFilteringScore ( ) . mergeRemainderFilter ( other . getFilteringScore ( ) ) ; }
Merges the remainder filter of this score with the one given using an or operation . Call canMergeRemainder first to verify if the merge makes any sense .
3,451
public OrderingList < S > mergeRemainderOrdering ( CompositeScore < S > other ) { return getOrderingScore ( ) . mergeRemainderOrdering ( other . getOrderingScore ( ) ) ; }
Merges the remainder orderings of this score with the one given . Call canMergeRemainder first to verify if the merge makes any sense .
3,452
public CompositeScore < S > withRemainderFilter ( Filter < S > filter ) { return new CompositeScore < S > ( mFilteringScore . withRemainderFilter ( filter ) , mOrderingScore ) ; }
Returns a new CompositeScore with the filtering remainder replaced and covering matches recalculated . Other matches are not recalculated .
3,453
public CompositeScore < S > withRemainderOrdering ( OrderingList < S > ordering ) { return new CompositeScore < S > ( mFilteringScore , mOrderingScore . withRemainderOrdering ( ordering ) ) ; }
Returns a new CompositeScore with the ordering remainder replaced . Handled count is not recalculated .
3,454
protected QueryExecutor < S > executor ( ) throws RepositoryException { QueryExecutor < S > executor = mExecutor ; if ( executor == null ) { mExecutor = executor = executorFactory ( ) . executor ( mFilter , mOrdering , null ) ; } return executor ; }
Returns the executor in use by this query .
3,455
protected void resetExecutor ( ) throws RepositoryException { if ( mExecutor != null ) { mExecutor = executorFactory ( ) . executor ( mFilter , mOrdering , null ) ; } }
Resets any cached reference to a query executor . If a reference is available it is replaced but a clear reference is not set .
3,456
public Cursor < S > fetchSlice ( FilterValues < S > values , long from , Long to ) throws FetchException { Cursor < S > cursor = fetch ( values ) ; if ( from > 0 ) { cursor = new SkipCursor < S > ( cursor , from ) ; } if ( to != null ) { cursor = new LimitCursor < S > ( cursor , to - from ) ; } return cursor ; }
Produces a slice via skip and limit cursors . Subclasses are encouraged to override with a more efficient implementation .
3,457
public long count ( FilterValues < S > values ) throws FetchException { Cursor < S > cursor = fetch ( values ) ; try { long count = cursor . skipNext ( Integer . MAX_VALUE ) ; if ( count == Integer . MAX_VALUE ) { int amt ; while ( ( amt = cursor . skipNext ( Integer . MAX_VALUE ) ) > 0 ) { count += amt ; } } return count ; } finally { cursor . close ( ) ; } }
Counts results by opening a cursor and skipping entries . Subclasses are encouraged to override with a more efficient implementation .
3,458
protected void indent ( Appendable app , int indentLevel ) throws IOException { for ( int i = 0 ; i < indentLevel ; i ++ ) { app . append ( ' ' ) ; } }
Appends spaces to the given appendable . Useful for implementing printNative and printPlan .
3,459
public final void lockForReadInterruptibly ( L locker ) throws InterruptedException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } if ( ! tryLockForRead ( locker ) ) { lockForReadQueuedInterruptibly ( locker , addReadWaiter ( ) ) ; } }
Acquire a shared read lock possibly blocking until interrupted .
3,460
public final boolean tryLockForRead ( L locker ) { int state = mState ; if ( state >= 0 ) { if ( isReadWriteFirst ( ) || isReadLockHeld ( locker ) ) { do { if ( incrementReadLocks ( state ) ) { adjustReadLockCount ( locker , 1 ) ; return true ; } } while ( ( state = mState ) >= 0 ) ; } } else if ( mOwner == locker ) { while ( ! incrementReadLocks ( state ) ) { state = mState ; } adjustReadLockCount ( locker , 1 ) ; return true ; } return false ; }
Attempt to immediately acquire a shared read lock .
3,461
public final boolean tryLockForRead ( L locker , long timeout , TimeUnit unit ) throws InterruptedException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } if ( ! tryLockForRead ( locker ) ) { return lockForReadQueuedInterruptibly ( locker , addReadWaiter ( ) , unit . toNanos ( timeout ) ) ; } return true ; }
Attempt to acquire a shared read lock waiting a maximum amount of time .
3,462
public final void unlockFromRead ( L locker ) { adjustReadLockCount ( locker , - 1 ) ; int readLocks ; while ( ( readLocks = decrementReadLocks ( mState ) ) < 0 ) { } if ( readLocks == 0 ) { Node h = mRWHead ; if ( h != null && h . mWaitStatus != 0 ) { unparkReadWriteSuccessor ( h ) ; } } }
Release a previously acquired read lock .
3,463
private final Result lockForUpgrade_ ( L locker ) { Result result ; if ( ( result = tryLockForUpgrade_ ( locker ) ) == Result . FAILED ) { result = lockForUpgradeQueued ( locker , addUpgradeWaiter ( ) ) ; } return result ; }
Acquire an upgrade lock possibly blocking indefinitely .
3,464
private final Result lockForUpgradeInterruptibly_ ( L locker ) throws InterruptedException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } Result result ; if ( ( result = tryLockForUpgrade_ ( locker ) ) == Result . FAILED ) { result = lockForUpgradeQueuedInterruptibly ( locker , addUpgradeWaiter ( ) ) ; } return result ; }
Acquire an upgrade lock possibly blocking until interrupted .
3,465
private final Result tryLockForUpgrade_ ( L locker ) { int state = mState ; if ( ( state & LOCK_STATE_MASK ) == 0 ) { if ( isUpgradeFirst ( ) ) { do { if ( setUpgradeLock ( state ) ) { mOwner = locker ; incrementUpgradeCount ( ) ; return Result . ACQUIRED ; } } while ( ( ( state = mState ) & LOCK_STATE_MASK ) == 0 ) ; } } else if ( mOwner == locker ) { incrementUpgradeCount ( ) ; return Result . OWNED ; } return Result . FAILED ; }
Attempt to immediately acquire an upgrade lock .
3,466
public final void unlockFromUpgrade ( L locker ) { int upgradeCount = mUpgradeCount - 1 ; if ( upgradeCount < 0 ) { throw new IllegalMonitorStateException ( "Too many upgrade locks released" ) ; } if ( upgradeCount == 0 && mWriteCount > 0 ) { clearUpgradeLock ( mState ) ; return ; } mUpgradeCount = upgradeCount ; if ( upgradeCount > 0 ) { return ; } mOwner = null ; while ( ! clearUpgradeLock ( mState ) ) { } Node h = mUHead ; if ( h != null && h . mWaitStatus != 0 ) { unparkUpgradeSuccessor ( h ) ; } }
Release a previously acquired upgrade lock .
3,467
public final void lockForWrite ( L locker ) { if ( ! tryLockForWrite ( locker ) ) { Result upgradeResult = lockForUpgrade_ ( locker ) ; if ( ! tryLockForWrite ( locker ) ) { lockForWriteQueued ( locker , addWriteWaiter ( ) ) ; } if ( upgradeResult == Result . ACQUIRED ) { while ( ! clearUpgradeLock ( mState ) ) { } } else { mUpgradeCount -- ; } } }
Acquire an exclusive write lock possibly blocking indefinitely .
3,468
public final void lockForWriteInterruptibly ( L locker ) throws InterruptedException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } if ( ! tryLockForWrite ( locker ) ) { Result upgradeResult = lockForUpgradeInterruptibly_ ( locker ) ; if ( ! tryLockForWrite ( locker ) ) { lockForWriteQueuedInterruptibly ( locker , addWriteWaiter ( ) ) ; } if ( upgradeResult == Result . ACQUIRED ) { while ( ! clearUpgradeLock ( mState ) ) { } } else { mUpgradeCount -- ; } } }
Acquire an exclusive write lock possibly blocking until interrupted .
3,469
public final boolean tryLockForWrite ( L locker ) { int state = mState ; if ( state == 0 ) { if ( isUpgradeOrReadWriteFirst ( ) && setWriteLock ( state ) ) { mOwner = locker ; incrementUpgradeCount ( ) ; incrementWriteCount ( ) ; return true ; } } else if ( state == LOCK_STATE_UPGRADE ) { if ( mOwner == locker && setWriteLock ( state ) ) { incrementWriteCount ( ) ; return true ; } } else if ( state < 0 ) { if ( mOwner == locker ) { incrementWriteCount ( ) ; return true ; } } return false ; }
Attempt to immediately acquire an exclusive lock .
3,470
public final boolean tryLockForWrite ( L locker , long timeout , TimeUnit unit ) throws InterruptedException { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } if ( ! tryLockForWrite ( locker ) ) { long start = System . nanoTime ( ) ; Result upgradeResult = tryLockForUpgrade_ ( locker , timeout , unit ) ; if ( upgradeResult == Result . FAILED ) { return false ; } if ( ! tryLockForWrite ( locker ) ) { unlockFromUpgrade ( locker ) ; if ( ( timeout = unit . toNanos ( timeout ) - ( System . nanoTime ( ) - start ) ) <= 0 ) { return false ; } if ( ! lockForWriteQueuedInterruptibly ( locker , addWriteWaiter ( ) , timeout ) ) { return false ; } } if ( upgradeResult == Result . ACQUIRED ) { while ( ! clearUpgradeLock ( mState ) ) { } } else { mUpgradeCount -- ; } } return true ; }
Attempt to acquire an exclusive lock waiting a maximum amount of time .
3,471
public final void unlockFromWrite ( L locker ) { int writeCount = mWriteCount - 1 ; if ( writeCount < 0 ) { throw new IllegalMonitorStateException ( "Too many write locks released" ) ; } mWriteCount = writeCount ; if ( writeCount > 0 ) { return ; } final int state = mState ; mState = LOCK_STATE_UPGRADE ; Node h = mRWHead ; if ( h != null && h . mWaitStatus != 0 ) { unparkReadWriteSuccessor ( h ) ; } if ( state == LOCK_STATE_WRITE ) { unlockFromUpgrade ( locker ) ; } }
Release a previously acquired write lock .
3,472
private void loadPropertyAnnotation ( CodeBuilder b , StorableProperty property , StorablePropertyAnnotation annotation ) { String methodName = annotation . getAnnotatedMethod ( ) . getName ( ) ; boolean isAccessor = ! methodName . startsWith ( "set" ) ; b . loadConstant ( TypeDesc . forClass ( property . getEnclosingType ( ) ) ) ; b . loadConstant ( methodName ) ; if ( isAccessor ) { b . loadNull ( ) ; } else { b . loadConstant ( 1 ) ; b . newObject ( TypeDesc . forClass ( Class [ ] . class ) ) ; b . dup ( ) ; b . loadConstant ( 0 ) ; b . loadConstant ( TypeDesc . forClass ( property . getType ( ) ) ) ; b . storeToArray ( TypeDesc . forClass ( Class [ ] . class ) ) ; } b . invokeVirtual ( Class . class . getName ( ) , "getMethod" , TypeDesc . forClass ( Method . class ) , new TypeDesc [ ] { TypeDesc . STRING , TypeDesc . forClass ( Class [ ] . class ) } ) ; b . loadConstant ( TypeDesc . forClass ( annotation . getAnnotationType ( ) ) ) ; b . invokeVirtual ( Method . class . getName ( ) , "getAnnotation" , TypeDesc . forClass ( Annotation . class ) , new TypeDesc [ ] { TypeDesc . forClass ( Class . class ) } ) ; b . checkCast ( TypeDesc . forClass ( annotation . getAnnotationType ( ) ) ) ; }
Generates code that loads a property annotation to the stack .
3,473
private void loadStorageForFetch ( CodeBuilder b , TypeDesc type ) { b . loadThis ( ) ; b . loadField ( SUPPORT_FIELD_NAME , mSupportType ) ; TypeDesc storageType = TypeDesc . forClass ( Storage . class ) ; TypeDesc repositoryType = TypeDesc . forClass ( Repository . class ) ; b . invokeInterface ( mSupportType , "getRootRepository" , repositoryType , null ) ; b . loadConstant ( type ) ; Label tryStart = b . createLabel ( ) . setLocation ( ) ; b . invokeInterface ( repositoryType , STORAGE_FOR_METHOD_NAME , storageType , new TypeDesc [ ] { TypeDesc . forClass ( Class . class ) } ) ; Label tryEnd = b . createLabel ( ) . setLocation ( ) ; Label noException = b . createLabel ( ) ; b . branch ( noException ) ; b . exceptionHandler ( tryStart , tryEnd , RepositoryException . class . getName ( ) ) ; b . invokeVirtual ( RepositoryException . class . getName ( ) , "toFetchException" , TypeDesc . forClass ( FetchException . class ) , null ) ; b . throwObject ( ) ; noException . setLocation ( ) ; }
Generates code that loads a Storage instance on the stack throwing a FetchException if Storage request fails .
3,474
private void markOrdinaryPropertyDirty ( CodeBuilder b , StorableProperty ordinaryProperty ) { int count = mAllProperties . size ( ) ; int ordinal = 0 ; int andMask = 0xffffffff ; int orMask = 0 ; boolean anyNonDerived = false ; for ( StorableProperty property : mAllProperties . values ( ) ) { if ( ! property . isDerived ( ) ) { anyNonDerived = true ; if ( property == ordinaryProperty ) { orMask |= PROPERTY_STATE_DIRTY << ( ( ordinal & 0xf ) * 2 ) ; } else if ( property . isJoin ( ) ) { for ( int i = property . getJoinElementCount ( ) ; -- i >= 0 ; ) { if ( ordinaryProperty == property . getInternalJoinElement ( i ) ) { andMask &= ~ ( PROPERTY_STATE_DIRTY << ( ( ordinal & 0xf ) * 2 ) ) ; } } } } ordinal ++ ; if ( ( ordinal & 0xf ) == 0 || ordinal >= count ) { if ( anyNonDerived && ( andMask != 0xffffffff || orMask != 0 ) ) { String stateFieldName = PROPERTY_STATE_FIELD_NAME + ( ( ordinal - 1 ) >> 4 ) ; b . loadThis ( ) ; b . loadThis ( ) ; b . loadField ( stateFieldName , TypeDesc . INT ) ; if ( andMask != 0xffffffff ) { b . loadConstant ( andMask ) ; b . math ( Opcode . IAND ) ; } if ( orMask != 0 ) { b . loadConstant ( orMask ) ; b . math ( Opcode . IOR ) ; } b . storeField ( stateFieldName , TypeDesc . INT ) ; } andMask = 0xffffffff ; orMask = 0 ; anyNonDerived = false ; } } }
For the given ordinary key property marks all of its dependent join element properties as uninitialized and marks given property as dirty .
3,475
private void branchIfDirty ( CodeBuilder b , boolean includePk , Label label ) { int count = mAllProperties . size ( ) ; int ordinal = 0 ; int andMask = 0 ; boolean anyNonDerived = false ; for ( StorableProperty property : mAllProperties . values ( ) ) { if ( ! property . isDerived ( ) ) { anyNonDerived = true ; if ( ! property . isJoin ( ) && ( ! property . isPrimaryKeyMember ( ) || includePk ) ) { andMask |= 2 << ( ( ordinal & 0xf ) * 2 ) ; } } ordinal ++ ; if ( ( ordinal & 0xf ) == 0 || ordinal >= count ) { if ( anyNonDerived ) { String stateFieldName = PROPERTY_STATE_FIELD_NAME + ( ( ordinal - 1 ) >> 4 ) ; b . loadThis ( ) ; b . loadField ( stateFieldName , TypeDesc . INT ) ; b . loadConstant ( andMask ) ; b . math ( Opcode . IAND ) ; b . ifZeroComparisonBranch ( label , "!=" ) ; } andMask = 0 ; anyNonDerived = false ; } } }
Generates code that branches to the given label if any properties are dirty .
3,476
private void requirePkInitialized ( CodeBuilder b , String methodName ) { b . loadThis ( ) ; b . invokeVirtual ( methodName , null , null ) ; b = new CodeBuilder ( mClassFile . addMethod ( Modifiers . PROTECTED , methodName , null , null ) ) ; b . loadThis ( ) ; b . invokeVirtual ( IS_REQUIRED_PK_INITIALIZED_METHOD_NAME , TypeDesc . BOOLEAN , null ) ; Label pkInitialized = b . createLabel ( ) ; b . ifZeroComparisonBranch ( pkInitialized , "!=" ) ; CodeBuilderUtil . throwException ( b , IllegalStateException . class , "Primary key not fully specified" ) ; pkInitialized . setLocation ( ) ; b . returnVoid ( ) ; }
Generates code that verifies that all primary keys are initialized .
3,477
private void addPropertyStateExtractMethod ( ) { MethodInfo mi = mClassFile . addMethod ( Modifiers . PRIVATE , PROPERTY_STATE_EXTRACT_METHOD_NAME , TypeDesc . INT , new TypeDesc [ ] { TypeDesc . STRING } ) ; addPropertySwitch ( new CodeBuilder ( mi ) , SWITCH_FOR_STATE ) ; }
Generates a private method which accepts a property name and returns PROPERTY_STATE_UNINITIALIZED PROPERTY_STATE_DIRTY or PROPERTY_STATE_CLEAN .
3,478
private List < StorableProperty < ? > > [ ] caseMatches ( int caseCount ) { List < StorableProperty < ? > > [ ] cases = new List [ caseCount ] ; for ( StorableProperty < ? > prop : mAllProperties . values ( ) ) { int hashCode = prop . getName ( ) . hashCode ( ) ; int caseValue = ( hashCode & 0x7fffffff ) % caseCount ; List matches = cases [ caseValue ] ; if ( matches == null ) { matches = cases [ caseValue ] = new ArrayList < StorableProperty < ? > > ( ) ; } matches . add ( prop ) ; } return cases ; }
Returns the properties that match on a given case . The array length is the same as the case count . Each list represents the matches . The lists themselves may be null if no matches for that case .
3,479
private void addPropertyStateCheckMethod ( String name , int state ) { MethodInfo mi = addMethodIfNotFinal ( Modifiers . PUBLIC , name , TypeDesc . BOOLEAN , new TypeDesc [ ] { TypeDesc . STRING } ) ; if ( mi == null ) { return ; } CodeBuilder b = new CodeBuilder ( mi ) ; b . loadThis ( ) ; b . loadLocal ( b . getParameter ( 0 ) ) ; b . invokePrivate ( PROPERTY_STATE_EXTRACT_METHOD_NAME , TypeDesc . INT , new TypeDesc [ ] { TypeDesc . STRING } ) ; Label isFalse = b . createLabel ( ) ; if ( state == 0 ) { b . ifZeroComparisonBranch ( isFalse , "!=" ) ; } else { b . loadConstant ( state ) ; b . ifComparisonBranch ( isFalse , "!=" ) ; } b . loadConstant ( true ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; isFalse . setLocation ( ) ; b . loadConstant ( false ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; }
Generates public method which accepts a property name and returns a boolean true if the given state matches the property s actual state .
3,480
private void addHashCodeMethod ( ) { Modifiers modifiers = Modifiers . PUBLIC . toSynchronized ( true ) ; MethodInfo mi = addMethodIfNotFinal ( modifiers , "hashCode" , TypeDesc . INT , null ) ; if ( mi == null ) { return ; } CodeBuilder b = new CodeBuilder ( mi ) ; boolean mixIn = false ; for ( StorableProperty property : mAllProperties . values ( ) ) { if ( property . isDerived ( ) || property . isJoin ( ) ) { continue ; } TypeDesc fieldType = TypeDesc . forClass ( property . getType ( ) ) ; b . loadThis ( ) ; b . loadField ( property . getName ( ) , fieldType ) ; CodeBuilderUtil . addValueHashCodeCall ( b , fieldType , true , mixIn ) ; mixIn = true ; } b . returnValue ( TypeDesc . INT ) ; }
Defines a hashCode method .
3,481
private void addEqualsMethod ( int equalityType ) { TypeDesc [ ] objectParam = { TypeDesc . OBJECT } ; String equalsMethodName ; switch ( equalityType ) { default : throw new IllegalArgumentException ( ) ; case EQUAL_KEYS : equalsMethodName = EQUAL_PRIMARY_KEYS_METHOD_NAME ; break ; case EQUAL_PROPERTIES : equalsMethodName = EQUAL_PROPERTIES_METHOD_NAME ; break ; case EQUAL_FULL : equalsMethodName = EQUALS_METHOD_NAME ; } Modifiers modifiers = Modifiers . PUBLIC . toSynchronized ( true ) ; MethodInfo mi = addMethodIfNotFinal ( modifiers , equalsMethodName , TypeDesc . BOOLEAN , objectParam ) ; if ( mi == null ) { return ; } CodeBuilder b = new CodeBuilder ( mi ) ; b . loadThis ( ) ; b . loadLocal ( b . getParameter ( 0 ) ) ; Label notEqual = b . createLabel ( ) ; b . ifEqualBranch ( notEqual , false ) ; b . loadConstant ( true ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; notEqual . setLocation ( ) ; TypeDesc userStorableTypeDesc = TypeDesc . forClass ( mStorableType ) ; b . loadLocal ( b . getParameter ( 0 ) ) ; b . instanceOf ( userStorableTypeDesc ) ; Label fail = b . createLabel ( ) ; b . ifZeroComparisonBranch ( fail , "==" ) ; LocalVariable other = b . createLocalVariable ( null , userStorableTypeDesc ) ; b . loadLocal ( b . getParameter ( 0 ) ) ; b . checkCast ( userStorableTypeDesc ) ; b . storeLocal ( other ) ; for ( StorableProperty property : mAllProperties . values ( ) ) { if ( property . isDerived ( ) || property . isJoin ( ) ) { continue ; } if ( ( equalityType == EQUAL_KEYS ) && ! property . isPrimaryKeyMember ( ) ) { continue ; } Label skipCheck = b . createLabel ( ) ; if ( equalityType != EQUAL_KEYS && property . isIndependent ( ) ) { addSkipIndependent ( b , other , property , skipCheck ) ; } TypeDesc fieldType = TypeDesc . forClass ( property . getType ( ) ) ; loadThisProperty ( b , property ) ; b . loadLocal ( other ) ; b . invoke ( property . getReadMethod ( ) ) ; CodeBuilderUtil . addValuesEqualCall ( b , fieldType , true , fail , false ) ; skipCheck . setLocation ( ) ; } b . loadConstant ( true ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; fail . setLocation ( ) ; b . loadConstant ( false ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; }
Defines an equals method .
3,482
private void addToStringMethod ( boolean keyOnly ) { TypeDesc stringBuilder = TypeDesc . forClass ( StringBuilder . class ) ; Modifiers modifiers = Modifiers . PUBLIC . toSynchronized ( true ) ; MethodInfo mi = addMethodIfNotFinal ( modifiers , keyOnly ? TO_STRING_KEY_ONLY_METHOD_NAME : TO_STRING_METHOD_NAME , TypeDesc . STRING , null ) ; if ( mi == null ) { return ; } CodeBuilder b = new CodeBuilder ( mi ) ; b . newObject ( stringBuilder ) ; b . dup ( ) ; b . invokeConstructor ( stringBuilder , null ) ; b . loadConstant ( mStorableType . getName ( ) ) ; invokeAppend ( b , TypeDesc . STRING ) ; String detail ; if ( keyOnly ) { detail = " (key only) {" ; } else { detail = " {" ; } b . loadConstant ( detail ) ; invokeAppend ( b , TypeDesc . STRING ) ; LocalVariable commaCountVar = b . createLocalVariable ( null , TypeDesc . INT ) ; b . loadConstant ( - 1 ) ; b . storeLocal ( commaCountVar ) ; for ( StorableProperty property : mInfo . getPrimaryKeyProperties ( ) . values ( ) ) { addPropertyAppendCall ( b , property , commaCountVar ) ; } if ( ! keyOnly ) { for ( StorableProperty property : mAllProperties . values ( ) ) { if ( ! property . isPrimaryKeyMember ( ) && ( ! property . isDerived ( ) ) && ( ! property . isJoin ( ) ) ) { addPropertyAppendCall ( b , property , commaCountVar ) ; } } } b . loadConstant ( '}' ) ; invokeAppend ( b , TypeDesc . CHAR ) ; if ( keyOnly ) { int altKeyCount = mInfo . getAlternateKeyCount ( ) ; for ( int i = 0 ; i < altKeyCount ; i ++ ) { b . loadConstant ( - 1 ) ; b . storeLocal ( commaCountVar ) ; b . loadConstant ( ", {" ) ; invokeAppend ( b , TypeDesc . STRING ) ; StorableKey < S > key = mInfo . getAlternateKey ( i ) ; for ( OrderedProperty < S > op : key . getProperties ( ) ) { StorableProperty < S > property = op . getChainedProperty ( ) . getPrimeProperty ( ) ; addPropertyAppendCall ( b , property , commaCountVar ) ; } b . loadConstant ( '}' ) ; invokeAppend ( b , TypeDesc . CHAR ) ; } } b . invokeVirtual ( stringBuilder , TO_STRING_METHOD_NAME , TypeDesc . STRING , null ) ; b . returnValue ( TypeDesc . STRING ) ; }
Defines a toString method which assumes that the ClassFile is targeting version 1 . 5 of Java .
3,483
private Label addGetTriggerAndEnterTxn ( CodeBuilder b , String opType , LocalVariable forTryVar , boolean forTry , LocalVariable triggerVar , LocalVariable txnVar , LocalVariable stateVar ) { b . loadThis ( ) ; b . loadField ( SUPPORT_FIELD_NAME , mSupportType ) ; Method m = lookupMethod ( mSupportType . toClass ( ) , "get" + opType + "Trigger" ) ; b . invoke ( m ) ; b . storeLocal ( triggerVar ) ; b . loadNull ( ) ; b . storeLocal ( stateVar ) ; b . loadLocal ( triggerVar ) ; Label hasTrigger = b . createLabel ( ) ; b . ifNullBranch ( hasTrigger , false ) ; b . loadNull ( ) ; b . storeLocal ( txnVar ) ; Label cont = b . createLabel ( ) ; b . branch ( cont ) ; hasTrigger . setLocation ( ) ; TypeDesc repositoryType = TypeDesc . forClass ( Repository . class ) ; TypeDesc transactionType = TypeDesc . forClass ( Transaction . class ) ; b . loadThis ( ) ; b . loadField ( SUPPORT_FIELD_NAME , mSupportType ) ; b . invokeInterface ( mSupportType , "getRootRepository" , repositoryType , null ) ; b . invokeInterface ( repositoryType , ENTER_TRANSACTION_METHOD_NAME , transactionType , null ) ; b . storeLocal ( txnVar ) ; Label tryStart = b . createLabel ( ) . setLocation ( ) ; b . loadLocal ( triggerVar ) ; b . loadLocal ( txnVar ) ; b . loadThis ( ) ; if ( forTryVar == null ) { if ( forTry ) { b . invokeVirtual ( triggerVar . getType ( ) , "beforeTry" + opType , TypeDesc . OBJECT , new TypeDesc [ ] { transactionType , TypeDesc . OBJECT } ) ; } else { b . invokeVirtual ( triggerVar . getType ( ) , "before" + opType , TypeDesc . OBJECT , new TypeDesc [ ] { transactionType , TypeDesc . OBJECT } ) ; } b . storeLocal ( stateVar ) ; } else { b . loadLocal ( forTryVar ) ; Label isForTry = b . createLabel ( ) ; b . ifZeroComparisonBranch ( isForTry , "!=" ) ; b . invokeVirtual ( triggerVar . getType ( ) , "before" + opType , TypeDesc . OBJECT , new TypeDesc [ ] { transactionType , TypeDesc . OBJECT } ) ; b . storeLocal ( stateVar ) ; b . branch ( cont ) ; isForTry . setLocation ( ) ; b . invokeVirtual ( triggerVar . getType ( ) , "beforeTry" + opType , TypeDesc . OBJECT , new TypeDesc [ ] { transactionType , TypeDesc . OBJECT } ) ; b . storeLocal ( stateVar ) ; } cont . setLocation ( ) ; return tryStart ; }
Generates code to get a trigger forcing a transaction if trigger is not null . Also if there is a trigger the before method is called .
3,484
private void addTriggerAfterAndExitTxn ( CodeBuilder b , String opType , LocalVariable forTryVar , boolean forTry , LocalVariable triggerVar , LocalVariable txnVar , LocalVariable stateVar ) { b . loadLocal ( triggerVar ) ; Label cont = b . createLabel ( ) ; b . ifNullBranch ( cont , true ) ; b . loadLocal ( triggerVar ) ; b . loadThis ( ) ; b . loadLocal ( stateVar ) ; if ( forTryVar == null ) { if ( forTry ) { b . invokeVirtual ( TypeDesc . forClass ( Trigger . class ) , "afterTry" + opType , null , new TypeDesc [ ] { TypeDesc . OBJECT , TypeDesc . OBJECT } ) ; } else { b . invokeVirtual ( TypeDesc . forClass ( Trigger . class ) , "after" + opType , null , new TypeDesc [ ] { TypeDesc . OBJECT , TypeDesc . OBJECT } ) ; } } else { b . loadLocal ( forTryVar ) ; Label isForTry = b . createLabel ( ) ; b . ifZeroComparisonBranch ( isForTry , "!=" ) ; b . invokeVirtual ( TypeDesc . forClass ( Trigger . class ) , "after" + opType , null , new TypeDesc [ ] { TypeDesc . OBJECT , TypeDesc . OBJECT } ) ; Label commitAndExit = b . createLabel ( ) ; b . branch ( commitAndExit ) ; isForTry . setLocation ( ) ; b . invokeVirtual ( TypeDesc . forClass ( Trigger . class ) , "afterTry" + opType , null , new TypeDesc [ ] { TypeDesc . OBJECT , TypeDesc . OBJECT } ) ; commitAndExit . setLocation ( ) ; } TypeDesc transactionType = TypeDesc . forClass ( Transaction . class ) ; b . loadLocal ( txnVar ) ; b . invokeInterface ( transactionType , COMMIT_METHOD_NAME , null , null ) ; b . loadLocal ( txnVar ) ; b . invokeInterface ( transactionType , EXIT_METHOD_NAME , null , null ) ; cont . setLocation ( ) ; }
Generates code to call a trigger after the persistence operation has been invoked .
3,485
private void addTriggerFailedAndExitTxn ( CodeBuilder b , String opType , LocalVariable triggerVar , LocalVariable txnVar , LocalVariable stateVar ) { TypeDesc transactionType = TypeDesc . forClass ( Transaction . class ) ; b . loadLocal ( triggerVar ) ; Label isNull = b . createLabel ( ) ; b . ifNullBranch ( isNull , true ) ; Label tryStart = b . createLabel ( ) . setLocation ( ) ; b . loadLocal ( triggerVar ) ; b . loadThis ( ) ; b . loadLocal ( stateVar ) ; b . invokeVirtual ( TypeDesc . forClass ( Trigger . class ) , "failed" + opType , null , new TypeDesc [ ] { TypeDesc . OBJECT , TypeDesc . OBJECT } ) ; Label tryEnd = b . createLabel ( ) . setLocation ( ) ; Label cont = b . createLabel ( ) ; b . branch ( cont ) ; b . exceptionHandler ( tryStart , tryEnd , Throwable . class . getName ( ) ) ; b . invokeStatic ( UNCAUGHT_METHOD_NAME , null , new TypeDesc [ ] { TypeDesc . forClass ( Throwable . class ) } ) ; cont . setLocation ( ) ; b . loadLocal ( txnVar ) ; b . invokeInterface ( transactionType , EXIT_METHOD_NAME , null , null ) ; isNull . setLocation ( ) ; }
Generates code to call a trigger after the persistence operation has failed .
3,486
private void addTriggerFailedAndExitTxn ( CodeBuilder b , String opType , LocalVariable forTryVar , boolean forTry , LocalVariable triggerVar , LocalVariable txnVar , LocalVariable stateVar , Label tryStart ) { if ( tryStart == null ) { addTriggerFailedAndExitTxn ( b , opType , triggerVar , txnVar , stateVar ) ; return ; } Label tryEnd = b . createLabel ( ) . setLocation ( ) ; b . exceptionHandler ( tryStart , tryEnd , null ) ; LocalVariable exceptionVar = b . createLocalVariable ( null , TypeDesc . OBJECT ) ; b . storeLocal ( exceptionVar ) ; addTriggerFailedAndExitTxn ( b , opType , triggerVar , txnVar , stateVar ) ; b . loadLocal ( exceptionVar ) ; TypeDesc abortException = TypeDesc . forClass ( Trigger . Abort . class ) ; b . instanceOf ( abortException ) ; Label nextCheck = b . createLabel ( ) ; b . ifZeroComparisonBranch ( nextCheck , "==" ) ; if ( forTryVar == null ) { if ( forTry ) { b . loadConstant ( false ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; } else { b . loadLocal ( exceptionVar ) ; b . checkCast ( abortException ) ; b . invokeVirtual ( abortException , "withStackTrace" , abortException , null ) ; b . throwObject ( ) ; } } else { b . loadLocal ( forTryVar ) ; Label isForTry = b . createLabel ( ) ; b . ifZeroComparisonBranch ( isForTry , "!=" ) ; b . loadLocal ( exceptionVar ) ; b . checkCast ( abortException ) ; b . invokeVirtual ( abortException , "withStackTrace" , abortException , null ) ; b . throwObject ( ) ; isForTry . setLocation ( ) ; b . loadConstant ( false ) ; b . returnValue ( TypeDesc . BOOLEAN ) ; } nextCheck . setLocation ( ) ; b . loadLocal ( exceptionVar ) ; TypeDesc repException = TypeDesc . forClass ( RepositoryException . class ) ; b . instanceOf ( repException ) ; Label throwAny = b . createLabel ( ) ; b . ifZeroComparisonBranch ( throwAny , "==" ) ; b . loadLocal ( exceptionVar ) ; b . checkCast ( repException ) ; b . invokeVirtual ( repException , "toPersistException" , TypeDesc . forClass ( PersistException . class ) , null ) ; b . throwObject ( ) ; throwAny . setLocation ( ) ; b . loadLocal ( exceptionVar ) ; b . throwObject ( ) ; }
Generates exception handler code to call a trigger after the persistence operation has failed .
3,487
private void defineUncaughtExceptionHandler ( ) { MethodInfo mi = mClassFile . addMethod ( Modifiers . PRIVATE . toStatic ( true ) , UNCAUGHT_METHOD_NAME , null , new TypeDesc [ ] { TypeDesc . forClass ( Throwable . class ) } ) ; CodeBuilder b = new CodeBuilder ( mi ) ; TypeDesc threadType = TypeDesc . forClass ( Thread . class ) ; b . invokeStatic ( Thread . class . getName ( ) , "currentThread" , threadType , null ) ; LocalVariable threadVar = b . createLocalVariable ( null , threadType ) ; b . storeLocal ( threadVar ) ; b . loadLocal ( threadVar ) ; TypeDesc handlerType = TypeDesc . forClass ( Thread . UncaughtExceptionHandler . class ) ; b . invokeVirtual ( threadType , "getUncaughtExceptionHandler" , handlerType , null ) ; b . loadLocal ( threadVar ) ; b . loadLocal ( b . getParameter ( 0 ) ) ; b . invokeInterface ( handlerType , "uncaughtException" , null , new TypeDesc [ ] { threadType , TypeDesc . forClass ( Throwable . class ) } ) ; b . returnVoid ( ) ; }
Generates method which passes exception to uncaught exception handler .
3,488
@ SuppressWarnings ( "unchecked" ) static JDBCSupportStrategy createStrategy ( JDBCRepository repo ) { String databaseProductName = repo . getDatabaseProductName ( ) . trim ( ) ; if ( databaseProductName != null && databaseProductName . length ( ) > 0 ) { String strategyName = Character . toUpperCase ( databaseProductName . charAt ( 0 ) ) + databaseProductName . substring ( 1 ) . toLowerCase ( ) ; if ( strategyName . indexOf ( ' ' ) > 0 ) { strategyName = strategyName . substring ( 0 , strategyName . indexOf ( ' ' ) ) ; } strategyName = strategyName . replaceAll ( "[^A-Za-z0-9]" , "" ) ; String className = "com.amazon.carbonado.repo.jdbc." + strategyName + "SupportStrategy" ; try { Class < JDBCSupportStrategy > clazz = ( Class < JDBCSupportStrategy > ) Class . forName ( className ) ; return clazz . getDeclaredConstructor ( JDBCRepository . class ) . newInstance ( repo ) ; } catch ( ClassNotFoundException e ) { } catch ( Exception e ) { ThrowUnchecked . fireFirstDeclaredCause ( e ) ; } } return new JDBCSupportStrategy ( repo ) ; }
Create a strategy based on the name of the database product . If one can t be found by product name the default will be used .
3,489
public Blob createNewBlob ( int blockSize ) throws PersistException { StoredLob lob = mLobStorage . prepare ( ) ; lob . setLocator ( mLocatorSequence . nextLongValue ( ) ) ; lob . setBlockSize ( blockSize ) ; lob . setLength ( 0 ) ; lob . insert ( ) ; return new BlobImpl ( lob . getLocator ( ) ) ; }
Returns a new Blob whose length is zero .
3,490
public Clob createNewClob ( int blockSize ) throws PersistException { StoredLob lob = mLobStorage . prepare ( ) ; lob . setLocator ( mLocatorSequence . nextLongValue ( ) ) ; lob . setBlockSize ( blockSize ) ; lob . setLength ( 0 ) ; lob . insert ( ) ; return new ClobImpl ( lob . getLocator ( ) ) ; }
Returns a new Clob whose length is zero .
3,491
public long getLocator ( Lob lob ) { if ( lob == null ) { return 0 ; } Long locator = ( Long ) lob . getLocator ( ) ; return locator == null ? 0 : locator ; }
Returns the locator for the given Lob or zero if null .
3,492
public void deleteLob ( long locator ) throws PersistException { if ( locator == 0 ) { return ; } Transaction txn = mRepo . enterTransaction ( IsolationLevel . READ_COMMITTED ) ; try { StoredLob lob = mLobStorage . prepare ( ) ; lob . setLocator ( locator ) ; if ( lob . tryDelete ( ) ) { try { mLobBlockStorage . query ( "locator = ?" ) . with ( lob . getLocator ( ) ) . deleteAll ( ) ; } catch ( FetchException e ) { throw e . toPersistException ( ) ; } } txn . commit ( ) ; } finally { txn . exit ( ) ; } }
Deletes Lob data freeing up all space consumed by it .
3,493
public synchronized < S extends Storable > Trigger < S > getSupportTrigger ( Class < S > type , int blockSize ) { Object key = KeyFactory . createKey ( new Object [ ] { type , blockSize } ) ; Trigger < S > trigger = ( mTriggers == null ) ? null : ( Trigger < S > ) mTriggers . get ( key ) ; if ( trigger == null ) { StorableInfo < S > info = StorableIntrospector . examine ( type ) ; List < LobProperty < ? > > lobProperties = null ; for ( StorableProperty < ? extends S > prop : info . getAllProperties ( ) . values ( ) ) { if ( Blob . class . isAssignableFrom ( prop . getType ( ) ) ) { if ( lobProperties == null ) { lobProperties = new ArrayList < LobProperty < ? > > ( ) ; } lobProperties . add ( new BlobProperty ( this , prop . getName ( ) ) ) ; } else if ( Clob . class . isAssignableFrom ( prop . getType ( ) ) ) { if ( lobProperties == null ) { lobProperties = new ArrayList < LobProperty < ? > > ( ) ; } lobProperties . add ( new ClobProperty ( this , prop . getName ( ) ) ) ; } } if ( lobProperties != null ) { trigger = new LobEngineTrigger < S > ( this , type , blockSize , lobProperties ) ; } if ( mTriggers == null ) { mTriggers = SoftValuedCache . newCache ( 7 ) ; } mTriggers . put ( key , trigger ) ; } return trigger ; }
Returns a Trigger for binding to this LobEngine . Storage implementations which use LobEngine must install this Trigger . Trigger instances are cached so subsequent calls for the same trigger return the same instance .
3,494
public boolean isConstraintError ( SQLException e ) { if ( e != null ) { String sqlstate = e . getSQLState ( ) ; if ( sqlstate != null ) { return sqlstate . startsWith ( SQLSTATE_CONSTRAINT_VIOLATION_CLASS_CODE ) ; } } return false ; }
Examines the SQLSTATE code of the given SQL exception and determines if it is a generic constaint violation .
3,495
public boolean isUniqueConstraintError ( SQLException e ) { if ( isConstraintError ( e ) ) { String sqlstate = e . getSQLState ( ) ; return SQLSTATE_UNIQUE_CONSTRAINT_VIOLATION . equals ( sqlstate ) ; } return false ; }
Examines the SQLSTATE code of the given SQL exception and determines if it is a unique constaint violation .
3,496
public final PersistException toPersistException ( final String message ) { Throwable cause ; if ( this instanceof PersistException ) { cause = this ; } else { cause = getCause ( ) ; } if ( cause == null ) { cause = this ; } else if ( cause instanceof PersistException && message == null ) { return ( PersistException ) cause ; } String causeMessage = cause . getMessage ( ) ; if ( causeMessage == null ) { causeMessage = message ; } else if ( message != null ) { causeMessage = message + " : " + causeMessage ; } return makePersistException ( causeMessage , cause ) ; }
Converts RepositoryException into an appropriate PersistException prepending the specified message . If message is null original exception message is preserved .
3,497
public final FetchException toFetchException ( final String message ) { Throwable cause ; if ( this instanceof FetchException ) { cause = this ; } else { cause = getCause ( ) ; } if ( cause == null ) { cause = this ; } else if ( cause instanceof FetchException && message == null ) { return ( FetchException ) cause ; } String causeMessage = cause . getMessage ( ) ; if ( causeMessage == null ) { causeMessage = message ; } else if ( message != null ) { causeMessage = message + " : " + causeMessage ; } return makeFetchException ( causeMessage , cause ) ; }
Converts RepositoryException into an appropriate FetchException prepending the specified message . If message is null original exception message is preserved .
3,498
public Object getAdapterInstance ( ) { if ( mAdapterInstance == null ) { try { mAdapterInstance = mConstructor . newInstance ( mEnclosingType , mPropertyName , mAnnotation . getAnnotation ( ) ) ; } catch ( Exception e ) { ThrowUnchecked . fireFirstDeclaredCause ( e ) ; } } return mAdapterInstance ; }
Returns an instance of the adapter for which an adapt method is applied to .
3,499
@ SuppressWarnings ( "unchecked" ) public Method findAdaptMethod ( Class from , Class to ) { Method [ ] methods = mAdaptMethods ; List < Method > candidates = new ArrayList < Method > ( methods . length ) ; for ( int i = methods . length ; -- i >= 0 ; ) { Method method = methods [ i ] ; if ( to . isAssignableFrom ( method . getReturnType ( ) ) && method . getParameterTypes ( ) [ 0 ] . isAssignableFrom ( from ) ) { candidates . add ( method ) ; } } reduceCandidates ( candidates , to ) ; if ( candidates . size ( ) == 0 ) { return null ; } return candidates . get ( 0 ) ; }
Returns an adapt method that supports the given conversion or null if none .