idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
4,700
public String getBindMapperName ( BindTypeContext context , TypeName typeName ) { Converter < String , String > format = CaseFormat . UPPER_CAMEL . converterTo ( CaseFormat . LOWER_CAMEL ) ; TypeName bindMapperName = TypeUtility . mergeTypeNameWithSuffix ( typeName , BindTypeBuilder . SUFFIX ) ; String simpleName = for...
Gets the bind mapper name .
4,701
public static void generateJavaDocReturnType ( MethodSpec . Builder methodBuilder , TypeName returnType ) { if ( returnType == TypeName . VOID ) { } else if ( TypeUtility . isTypeIncludedIn ( returnType , Boolean . TYPE , Boolean . class ) ) { methodBuilder . addJavadoc ( "\n" ) ; methodBuilder . addJavadoc ( "@return ...
Generate javadoc about return type of method .
4,702
static boolean modifierIsAcceptable ( Element item ) { Object [ ] values = { Modifier . NATIVE , Modifier . STATIC , Modifier . ABSTRACT } ; for ( Object i : values ) { if ( item . getModifiers ( ) . contains ( i ) ) return false ; } return true ; }
Modifier is acceptable .
4,703
public static ConflictAlgorithmType getConflictAlgorithmType ( SQLiteModelMethod method ) { ModelAnnotation annotation = method . getAnnotation ( BindSqlInsert . class ) ; String value = annotation . getAttribute ( AnnotationAttributeType . CONFLICT_ALGORITHM_TYPE ) ; if ( value != null && value . indexOf ( "." ) > - 1...
Gets the conflict algorithm type .
4,704
private boolean readln1 ( String strExpected , String strAlternative ) { String sX = scanner . next ( ) ; if ( sX . equals ( strExpected ) ) { return true ; } if ( sX . equals ( strAlternative ) ) { return false ; } throw new IllegalStateException ( "Expected: " + strAlternative + " but got: " + sX ) ; }
Reads 1 token .
4,705
public int getNextPage ( int prevPage ) { reportFreePage ( prevPage ) ; if ( iter . hasNextULL ( ) ) { LongLongIndex . LLEntry e = iter . nextULL ( ) ; long pageId = e . getKey ( ) ; long value = e . getValue ( ) ; while ( ( value > maxFreeTxId || value < 0 ) && iter . hasNextULL ( ) ) { if ( value < 0 && ( ( - value )...
Get a new free page .
4,706
public final void offer ( DataDeSerializer e ) { lock ( ) ; try { if ( count < items . length ) { items [ count ++ ] = e ; } } finally { unlock ( ) ; } }
Return an object . The object may be discarded if the pool is full .
4,707
public List < QueryAdvice > determineIndexToUse ( QueryTreeNode queryTree ) { List < QueryAdvice > advices = new LinkedList < QueryAdvice > ( ) ; List < ZooFieldDef > availableIndices = new LinkedList < ZooFieldDef > ( ) ; for ( ZooFieldDef f : clsDef . getAllFields ( ) ) { if ( f . isIndexed ( ) ) { availableIndices ....
Determine index to use .
4,708
int getPagePosition ( AbstractIndexPage indexPage ) { for ( int i = 0 ; i < subPages . length ; i ++ ) { if ( subPages [ i ] == indexPage ) { return i ; } } throw DBLogger . newFatalInternal ( "Leaf page not found in parent page: " + indexPage . pageId + " " + Arrays . toString ( subPageIds ) ) ; }
This method will fail if called on the first page in the tree . However this should not happen because when called we already have a reference to a previous page .
4,709
private void loadAllInstances ( ZooClassProxy def , boolean subClasses , MergingIterator < ZooPC > iter , boolean loadFromCache ) { for ( Node n : nodes ) { iter . add ( n . loadAllInstances ( def , loadFromCache ) ) ; } if ( subClasses ) { for ( ZooClassProxy sub : def . getSubProxies ( ) ) { loadAllInstances ( sub , ...
This method avoids nesting MergingIterators .
4,710
private ZooPC checkObjectForRefresh ( Object pc ) { if ( ! ( pc instanceof ZooPC ) ) { throw DBLogger . newUser ( "The object is not persistent capable: " + pc . getClass ( ) ) ; } ZooPC pci = ( ZooPC ) pc ; if ( ! pci . jdoZooIsPersistent ( ) ) { return pci ; } if ( pci . jdoZooGetContext ( ) . getSession ( ) != this ...
For refresh we can ignore things like deletion or transience .
4,711
public final void jdoReplaceStateManager ( javax . jdo . spi . StateManager sm ) { if ( jdoStateManager != null ) { jdoStateManager = jdoStateManager . replacingStateManager ( this , sm ) ; } else { JDOImplHelper . checkAuthorizedStateManager ( sm ) ; jdoStateManager = sm ; this . jdoFlags = LOAD_REQUIRED ; } }
The generated method asks the current StateManager to approve the change or validates the caller s authority to set the state .
4,712
public void jdoCopyKeyFieldsFromObjectId ( ObjectIdFieldConsumer fc , Object oid ) { fc . storeIntField ( 2 , ( ( IntIdentity ) oid ) . getKey ( ) ) ; }
The generated methods copy key fields from the object id instance to the PersistenceCapable instance or to the ObjectIdFieldConsumer .
4,713
private void writeMainPage ( int userPage , int oidPage , int schemaPage , int indexPage , int freeSpaceIndexPage , int pageCount , StorageChannelOutput out , long lastUsedOid , long txId ) { rootPageID = ( rootPageID + 1 ) % 2 ; out . seekPageForWrite ( PAGE_TYPE . ROOT_PAGE , rootPages [ rootPageID ] ) ; out . writeL...
Writes the main page .
4,714
public void refresh ( Object pc ) { DBTracer . logCall ( this , pc ) ; checkOpen ( ) ; nativeConnection . refreshObject ( pc ) ; }
Refreshes and places a ReadLock on the object .
4,715
public void refreshAll ( Object ... pcs ) { DBTracer . logCall ( this , pcs ) ; checkOpen ( ) ; for ( Object o : pcs ) { nativeConnection . refreshObject ( o ) ; } }
Refreshes and places a ReadLock on the objects .
4,716
public static void main ( String [ ] args ) { String dbName ; if ( args . length == 0 ) { dbName = DB_NAME ; } else { dbName = args [ 0 ] ; } if ( ! ZooHelper . getDataStoreManager ( ) . dbExists ( dbName ) ) { err . println ( "ERROR Database not found: " + dbName ) ; return ; } out . println ( "Checking database: " + ...
private static final String DB_NAME = StackServerFault ;
4,717
public ZooPC readObject ( int page , int offs , boolean skipIfCached ) { long clsOid = in . startReading ( page , offs ) ; long ts = in . getHeaderTimestamp ( ) ; long oid = in . readLong ( ) ; ZooPC pc = cache . findCoByOID ( oid ) ; if ( skipIfCached && pc != null ) { if ( pc . jdoZooIsDeleted ( ) || ! pc . jdoZooIsS...
This method returns an object that is read from the input stream .
4,718
public void addColl ( Collection < E > collection ) { if ( current == null ) { current = collection . iterator ( ) ; } else { collections . add ( collection ) ; } }
Adds a collection to the merged iterator . The iterator of the collection is only requested after other iterators are exhausted . This can help avoiding concurrent modification exceptions .
4,719
public void ensureValidity ( long oid ) { if ( oids == null ) { return ; } if ( oid >= oids [ oids . length - 1 ] ) { nextValidOidPos = - 1 ; return ; } while ( oid >= oids [ nextValidOidPos ] ) { nextValidOidPos ++ ; } }
This needs to be called when users provide their own OIDs . The OID buffer needs to ensure that it will never return an OID that has been previously used by a user .
4,720
public final void traverse ( ) { if ( ! traversalRequired && ! cache . hasDirtyPojos ( ) ) { return ; } try { traverseCache ( ) ; traverseWorkList ( ) ; } finally { workList . clear ( ) ; toBecomePersistent . clear ( ) ; seenObjects . clear ( ) ; } traversalRequired = false ; }
This class is only public so it can be accessed by the test harness . Please do not use .
4,721
public final void traverse ( ZooPC pc ) { try { traverseObject ( pc ) ; traverseWorkList ( ) ; } finally { workList . clear ( ) ; toBecomePersistent . clear ( ) ; seenObjects . clear ( ) ; } }
This can be used to enforce traversal of an object even if it is PERSITENT_CLEAN . This can be necessary for objects that transition from DETACHED_CLEAN to PERSITENT_CLEAN and whose children need to make this transition transitively .
4,722
@ SuppressWarnings ( "rawtypes" ) private final void doPersistentContainer ( Object container ) { if ( container instanceof DBArrayList ) { doCollection ( ( DBArrayList ) container ) ; } else if ( container instanceof DBLargeVector ) { doCollection ( ( ( DBLargeVector ) container ) ) ; } else if ( container instanceof ...
Handles persistent Collection classes .
4,723
private final Field [ ] getFields ( Class < ? extends Object > cls ) { Field [ ] ret = SEEN_CLASSES . get ( cls ) ; if ( ret != null ) { return ret ; } List < Field > retL = new ArrayList < Field > ( ) ; for ( Field f : cls . getDeclaredFields ( ) ) { if ( ! isSimpleType ( f ) ) { retL . add ( f ) ; f . setAccessible (...
Returns a List containing all of the Field objects for the given class . The fields include all public and private fields from the given class and its super classes .
4,724
public static ZooFieldDef create ( ZooClassDef declaringType , String fieldName , ZooClassDef fieldType , int arrayDim ) { String typeName = fieldType . getClassName ( ) ; JdoType jdoType ; if ( arrayDim > 0 ) { jdoType = JdoType . ARRAY ; } else { jdoType = JdoType . REFERENCE ; } long fieldOid = declaringType . jdoZo...
Creates references and reference arrays to persistent classes .
4,725
@ SuppressWarnings ( "unchecked" ) private void queryForCoursesByTeacher ( String name ) { System . out . println ( ">> Query for courses by teacher " + name + " returned:" ) ; Query q = pm . newQuery ( Course . class , "teacher.name == '" + name + "'" ) ; Collection < Course > courses = ( Collection < Course > ) q . e...
Example for a path query on Course . teacher . name == myName .
4,726
@ SuppressWarnings ( "unchecked" ) private void queryForCoursesWithXStudents ( int studentCount ) { System . out . println ( ">> Query for courses with " + studentCount + " students:" ) ; Query q = pm . newQuery ( Course . class , "students.size() == " + studentCount + "" ) ; Collection < Course > courses = ( Collectio...
This example demonstrates how many Java methods of Java SE classes can be used in queries . Not that not all methods can be used .
4,727
@ SuppressWarnings ( "unchecked" ) private void queryForCoursesWithTeachersWithFirstAndLastName ( ) { System . out . println ( ">> Query for courses whose teacher have a frist and last name:" ) ; Query q = pm . newQuery ( Course . class , "teacher.name.indexOf(' ') >= 1" ) ; Collection < Course > courses = ( Collection...
This example combines a path query with a Java method call on the String class .
4,728
public ZooPC readObject ( DataDeSerializer dds , long oid ) { FilePos oie = oidIndex . findOid ( oid ) ; if ( oie == null ) { throw DBLogger . newObjectNotFoundException ( "OID not found: " + Util . oidToString ( oid ) ) ; } return dds . readObject ( oie . getPage ( ) , oie . getOffs ( ) , false ) ; }
Locate an object . This version allows providing a data de - serializer . This will be handy later if we want to implement some concurrency which requires using multiple of the stateful DeSerializers .
4,729
public void defineIndex ( ZooClassDef def , ZooFieldDef field , boolean isUnique ) { SchemaIndexEntry se = schemaIndex . getSchema ( def ) ; LongLongIndex fieldInd = se . defineIndex ( field , isUnique ) ; PagedPosIndex ind = se . getObjectIndexLatestSchemaVersion ( ) ; PagedPosIndex . ObjectPosIterator iter = ind . it...
Defines an index and populates it . All objects are put into the cache . This is not necessarily useful but it is a one - off operation . Otherwise we would need a special purpose implementation of the deserializer which would have the need for a cache removed .
4,730
public long getObjectClass ( long oid ) { FilePos oie = oidIndex . findOid ( oid ) ; if ( oie == null ) { throw DBLogger . newObjectNotFoundException ( "OID not found: " + Util . oidToString ( oid ) ) ; } try { fileInAP . seekPage ( PAGE_TYPE . DATA , oie . getPage ( ) , oie . getOffs ( ) ) ; return DataDeSerializerNoC...
Get the class of a given object .
4,731
public static RuntimeException newFatalDataStore ( String msg , Throwable t ) { return newEx ( FATAL_DATA_STORE_EXCEPTION , msg , t ) ; }
THese always result in the session being closed!
4,732
final void preallocatePagesForWriteMap ( Map < AbstractIndexPage , Integer > map , FreeSpaceManager fsm ) { getRoot ( ) . createWriteMap ( map , fsm ) ; }
Method to preallocate pages for a write command .
4,733
final int writeToPreallocated ( StorageChannelOutput out , Map < AbstractIndexPage , Integer > map ) { return getRoot ( ) . writeToPreallocated ( out , map ) ; }
Special write method that uses only pre - allocated pages .
4,734
static GenericObject newEmptyInstance ( ZooClassDef def , AbstractCache cache ) { long oid = def . getProvidedContext ( ) . getNode ( ) . getOidBuffer ( ) . allocateOid ( ) ; return newEmptyInstance ( oid , def , cache ) ; }
Creates new instances .
4,735
public void evolve ( SchemaOperation op ) { ArrayList < Object > fV = new ArrayList < Object > ( Arrays . asList ( fixedValues ) ) ; ArrayList < Object > vV = new ArrayList < Object > ( Arrays . asList ( variableValues ) ) ; if ( op instanceof SchemaOperation . SchemaFieldDefine ) { SchemaOperation . SchemaFieldDefine ...
Schema evolution of in - memory objects operation by operation .
4,736
public void setDbCollection ( Object collection ) { if ( collection != null ) { dbCollectionData = collection ; isDbCollection = true ; } else { dbCollectionData = null ; isDbCollection = false ; } }
This is used to represent DBCollection objects as GenericObjects .
4,737
void verifyPcNotDirty ( ) { if ( handle == null || handle . internalGetPCI ( ) == null || ! handle . internalGetPCI ( ) . jdoZooIsDirty ( ) ) { ZooPC pc = jdoZooGetContext ( ) . getSession ( ) . internalGetCache ( ) . findCoByOID ( jdoZooGetOid ( ) ) ; if ( pc == null || ! pc . jdoZooIsDirty ( ) ) { return ; } } throw ...
This method verifies that this GO has no PCI representation or that the PCI representation is not dirty or new . Otherwise it will throw an exception in order to prevent the dirty state of the GO and the PC to result in conflicting updates in the database .
4,738
public E pop ( ) { modCount ++ ; if ( size == 0 ) { throw new NoSuchElementException ( ) ; } size -- ; if ( cntInBucket == 1 ) { cntInBucket = bucketSize ; return buckets . removeLast ( ) [ 0 ] ; } return buckets . getLast ( ) [ -- cntInBucket ] ; }
Removes the element at the specified position in this list . Only the last element in the list can be removed .
4,739
private static int compare ( long v1 , long v2 ) { int pos = 0 ; if ( v1 != v2 ) { long x = v1 ^ v2 ; pos += Long . numberOfLeadingZeros ( x ) ; return pos ; } return - 1 ; }
Compares two values .
4,740
public boolean contains ( long key ) { if ( size == 0 ) { return false ; } if ( size == 1 ) { int posDiff = compare ( key , rootKey ) ; if ( posDiff == - 1 ) { return true ; } return false ; } Node < V > n = root ; while ( true ) { if ( ! doesInfixMatch ( n , key ) ) { return false ; } if ( getBit ( key , n . posDiff )...
Check whether a given key exists in the tree .
4,741
public V get ( long key ) { if ( size == 0 ) { return null ; } if ( size == 1 ) { int posDiff = compare ( key , rootKey ) ; if ( posDiff == - 1 ) { return rootVal ; } return null ; } Node < V > n = root ; while ( true ) { if ( ! doesInfixMatch ( n , key ) ) { return null ; } if ( getBit ( key , n . posDiff ) ) { if ( n...
Get the value for a given key .
4,742
public V remove ( long key ) { if ( size == 0 ) { return null ; } if ( size == 1 ) { int posDiff = compare ( key , rootKey ) ; if ( posDiff == - 1 ) { size -- ; rootKey = 0 ; V prev = rootVal ; rootVal = null ; return prev ; } return null ; } Node < V > n = root ; Node < V > parent = null ; boolean isParentHigh = false...
Remove a key and its value
4,743
public static PersistenceManager openDB ( String dbName ) { DBTracer . logCall ( ZooJdoHelper . class , dbName ) ; ZooJdoProperties props = new ZooJdoProperties ( dbName ) ; PersistenceManagerFactory pmf = JDOHelper . getPersistenceManagerFactory ( props ) ; PersistenceManager pm = pmf . getPersistenceManager ( ) ; ret...
Open a database .
4,744
public static PersistenceManager openOrCreateDB ( String dbName ) { DBTracer . logCall ( ZooJdoHelper . class , dbName ) ; if ( ! dbExists ( dbName ) ) { createDb ( dbName ) ; } return openDB ( dbName ) ; }
Open a database . Create the database file if it doesn t exist .
4,745
public static ZooSchema schema ( PersistenceManager pm ) { DBTracer . logCall ( ZooJdoHelper . class , pm ) ; return ( ( PersistenceManagerImpl ) pm ) . getSession ( ) . schema ( ) ; }
Get access to ZooDB schema management methods .
4,746
public static void createIndex ( PersistenceManager pm , Class < ? > cls , String fieldName , boolean isUnique ) { DBTracer . logCall ( ZooJdoHelper . class , pm , cls , fieldName , isUnique ) ; ZooSchema s = schema ( pm ) ; ZooClass c = s . getClass ( cls ) ; if ( c == null ) { c = s . addClass ( cls ) ; } c . createI...
A convenience method for creating indices . Creates an index on the specified field for the current class and all sub - classes . The method will create a schema for the class if none exists .
4,747
public static DBStatistics getStatistics ( PersistenceManager pm ) { DBTracer . logCall ( ZooJdoHelper . class , pm ) ; Session s = ( Session ) pm . getDataStoreConnection ( ) . getNativeConnection ( ) ; return new DBStatistics ( s ) ; }
Get access to the statistics API of ZooDB .
4,748
public ZooClass addClass ( Class < ? > cls ) { DBTracer . logCall ( this , cls ) ; checkValidity ( true ) ; return sm . createSchema ( null , cls ) ; }
Define a new database class schema based on the given Java class .
4,749
public ZooClass defineEmptyClass ( String className ) { DBTracer . logCall ( this , className ) ; checkValidity ( true ) ; if ( ! checkJavaClassNameConformity ( className ) ) { throw new IllegalArgumentException ( "Not a valid class name: \"" + className + "\"" ) ; } return sm . declareSchema ( className , null ) ; }
This declares a new database class schema . This method creates an empty class with no attributes . It does not consider any existing Java classes of the same name .
4,750
public FormattedStringBuilder append ( Throwable t ) { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; PrintStream p = new PrintStream ( os ) ; t . printStackTrace ( p ) ; p . close ( ) ; return append ( os . toString ( ) ) ; }
Appends the stack trace of the Throwable argument to this sequence .
4,751
@ SuppressWarnings ( "unchecked" ) private static void readDB ( String dbName ) { PersistenceManager pm = ZooJdoHelper . openDB ( dbName ) ; pm . currentTransaction ( ) . begin ( ) ; System . out . println ( "Person extent: " ) ; Extent < Person > ext = pm . getExtent ( Person . class ) ; for ( Person p : ext ) { Syste...
Read data from a database . Extents are fast but allow filtering only on the class . Queries are a bit more powerful than Extents .
4,752
private static void populateDB ( String dbName ) { PersistenceManager pm = ZooJdoHelper . openDB ( dbName ) ; pm . currentTransaction ( ) . begin ( ) ; Person lisa = new Person ( "Lisa" ) ; pm . makePersistent ( lisa ) ; Person bart = new Person ( "Bart" ) ; lisa . addFriend ( bart ) ; pm . currentTransaction ( ) . com...
Populate a database .
4,753
private static void createDB ( String dbName ) { if ( ZooHelper . dbExists ( dbName ) ) { ZooHelper . removeDb ( dbName ) ; } ZooHelper . createDb ( dbName ) ; }
Create a database .
4,754
private static void closeDB ( PersistenceManager pm ) { if ( pm . currentTransaction ( ) . isActive ( ) ) { pm . currentTransaction ( ) . rollback ( ) ; } pm . close ( ) ; pm . getPersistenceManagerFactory ( ) . close ( ) ; }
Close the database connection .
4,755
public void seekPageForWrite ( PAGE_TYPE type , int pageId ) { writeData ( ) ; isWriting = true ; currentPage = pageId ; buf . clear ( ) ; currentDataType = type ; if ( type != PAGE_TYPE . DB_HEADER ) { writeHeader ( ) ; } }
Assumes autoPaging = false ;
4,756
public int allocateAndSeekAP ( PAGE_TYPE type , int prevPage , long header ) { currentDataType = type ; classOid = header ; int pageId = allocateAndSeekPage ( prevPage ) ; return pageId ; }
Assumes autoPaging = true ;
4,757
public void noCheckWrite ( long [ ] array ) { LongBuffer lb = buf . asLongBuffer ( ) ; lb . put ( array ) ; buf . position ( buf . position ( ) + S_LONG * array . length ) ; }
The no - check methods are thought to be faster because they don t need range checking . Furthermore they ensure that a page can be filled to the last byte . without a new page being allocated .
4,758
public ZooJdoProperties setOptimistic ( boolean flag ) { DBTracer . logCall ( this , flag ) ; put ( Constants . PROPERTY_OPTIMISTIC , Boolean . toString ( flag ) ) ; if ( flag ) { throw new UnsupportedOperationException ( ) ; } return this ; }
Whether the transactions should be optimistic that means whether objects should become non - transactional during commit . This is for example useful when objects should be accessible outside transactions . This is optimistic because less consistency guarantees are given .
4,759
public ZooJdoProperties setIgnoreCache ( boolean flag ) { DBTracer . logCall ( this , flag ) ; put ( Constants . PROPERTY_IGNORE_CACHE , Boolean . toString ( flag ) ) ; return this ; }
Whether queries should ignore objects in the cache . Default is false .
4,760
public ZooJdoProperties setZooFailOnEmptyQueries ( boolean flag ) { DBTracer . logCall ( this , flag ) ; put ( ZooConstants . PROPERTY_FAIL_ON_CLOSED_QUERIES , Boolean . toString ( flag ) ) ; return this ; }
Property that defines how access to closed Queries and Extent should be handled . Queries and Extents are automatically closed at transaction boundaries . y default as specified in JDO 3 . 1 closed queries and extents behave as if they were empty .
4,761
public void associateSuperDef ( ZooClassDef superDef ) { if ( this . superDef != null ) { throw new IllegalStateException ( ) ; } if ( superDef == null ) { throw new IllegalArgumentException ( ) ; } if ( superDef . getOid ( ) != oidSuper ) { throw new IllegalStateException ( "s-oid= " + oidSuper + " / " + superDef . ge...
Only to be used during database startup to load the schema - tree .
4,762
private ZooClassDef locateClassDefinition ( Class < ? > cls , Node node ) { ZooClassDef def = cache . getSchema ( cls , node ) ; if ( def == null || def . jdoZooIsDeleted ( ) ) { return null ; } return def ; }
Checks class and disk for class definition .
4,763
private void addMissingSchemas ( Set < String > missingSchemas ) { if ( missingSchemas . isEmpty ( ) ) { return ; } for ( String className : missingSchemas ) { Class < ? > cls ; try { cls = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw DBLogger . newFatal ( "Invalid field type in schema" ...
This method add all schemata that were found missing when checking all known schemata .
4,764
private void checkSchemaFields ( ZooClassDef schema , Collection < ZooClassDef > cachedSchemata , Set < String > missingSchemas ) { schema . associateFCOs ( cachedSchemata , isSchemaAutoCreateMode , missingSchemas ) ; }
Check the fields defined in this class .
4,765
private void applyOp ( SchemaOperation op , ZooClassDef def ) { ops . add ( op ) ; for ( GenericObject o : cache . getAllGenericObjects ( ) ) { if ( o . jdoZooGetClassDef ( ) == def ) { o . evolve ( op ) ; } } }
Apply an operation to all objects in the cache .
4,766
public boolean evaluate ( DataDeSerializerNoClass dds , long pos ) { boolean first = ( n1 != null ? n1 . evaluate ( dds , pos ) : t1 . evaluate ( dds , pos ) ) ; if ( op == null ) { return first ; } if ( ! first && op == LOG_OP . AND ) { return false ; } if ( first && op == LOG_OP . OR ) { return true ; } return ( n2 !...
Evaluate the query directly on a byte buffer rather than on materialized objects .
4,767
public void createSubs ( List < QueryTreeNode > subQueries ) { if ( ! isBranchIndexed ( ) ) { return ; } if ( LOG_OP . OR . equals ( op ) ) { QueryTreeNode node1 ; if ( n1 != null ) { node1 = n1 ; } else { n1 = node1 = new QueryTreeNode ( null , t1 , null , null , null , false ) ; t1 = null ; } QueryTreeNode node2 ; if...
This method splits a query into multiple queries for every occurrence of OR . It walks down the query tree recursively always doubling the tree when encountering an OR in an indexed branch . A branch is indexed if one of it s terms references an indexed field .
4,768
private QueryTreeNode cloneTrunk ( QueryTreeNode stop , QueryTreeNode stopClone ) { QueryTreeNode node1 = null ; if ( n1 != null ) { node1 = ( n1 == stop ? stopClone : n1 . cloneBranch ( ) ) ; } QueryTreeNode node2 = null ; if ( n2 != null ) { node2 = n2 == stop ? stopClone : n2 . cloneBranch ( ) ; } QueryTreeNode ret ...
Clones a tree upwards to the root except for the branch that starts with stop which is replaced by stopClone .
4,769
private final void setPersNew ( ) { status = ObjectState . PERSISTENT_NEW ; stateFlags = PS_PERSISTENT | PS_TRANSACTIONAL | PS_DIRTY | PS_NEW ; context . getSession ( ) . internalGetCache ( ) . notifyDirty ( this ) ; }
not to be used from outside
4,770
public final void zooActivateRead ( ) { if ( DBTracer . TRACE ) DBTracer . logCall ( this ) ; switch ( getStatus ( ) ) { case DETACHED_CLEAN : return ; case HOLLOW_PERSISTENT_NONTRANSACTIONAL : try { Session session = context . getSession ( ) ; session . lock ( ) ; if ( session . isClosed ( ) ) { throw DBLogger . newUs...
This method ensures that the specified object is in the cache .
4,771
int binarySearch ( int fromIndex , int toIndex , long key , long value ) { if ( ind . isUnique ( ) ) { return binarySearchUnique ( fromIndex , toIndex , key ) ; } return binarySearchNonUnique ( fromIndex , toIndex , key , value ) ; }
Binary search .
4,772
protected void replaceChildPage ( LLIndexPage indexPage , long key , long value , AbstractIndexPage subChild ) { int start = binarySearch ( 0 , nEntries , key , value ) ; if ( start < 0 ) { start = - ( start + 1 ) ; } for ( int i = start ; i <= nEntries ; i ++ ) { if ( subPages [ i ] == indexPage ) { markPageDirtyAndCl...
Replacing sub - pages occurs when the sub - page shrinks down to a single sub - sub - page in which case we pull up the sub - sub - page to the local page replacing the sub - page .
4,773
public long deleteAndCheckRangeEmpty ( long key , long min , long max ) { LLIndexPage pageKey = locatePageForKeyUnique ( key , false ) ; int posKey = pageKey . binarySearchUnique ( 0 , pageKey . nEntries , key ) ; long [ ] keys = pageKey . getKeys ( ) ; if ( posKey > 0 ) { if ( keys [ posKey - 1 ] >= min ) { return pag...
Special method to remove entries . When removing the entry it checks whether other entries in the given range exist . If none exist the value is returned as free page to FSM .
4,774
public LongLongIndex . LLEntry nextULL ( ) { if ( ! hasNextULL ( ) ) { throw new NoSuchElementException ( ) ; } LongLongIndex . LLEntry e = new LongLongIndex . LLEntry ( nextKey , nextValue ) ; if ( currentPage == null ) { hasValue = false ; } else { gotoPosInPage ( ) ; } return e ; }
Dirty trick to avoid delays from finding the correct method .
4,775
public synchronized void scavenge ( ) throws InterruptedException { int delta = this . totalCount - config . getMinSize ( ) ; if ( delta <= 0 ) return ; int removed = 0 ; long now = System . currentTimeMillis ( ) ; Poolable < T > obj ; while ( delta -- > 0 && ( obj = objectQueue . poll ( ) ) != null ) { if ( Log . isDe...
set the scavenge interval carefully
4,776
private void registerCallbacks ( Manager manager ) { if ( callbacks != null ) { for ( Callback callback : callbacks ) { manager . callback ( ) . addCallback ( callback ) ; } } }
Register callbacks in given manager
4,777
private void configureEnabled ( Manager manager ) { if ( enabled != manager . isEnabled ( ) ) { if ( enabled ) { manager . enable ( ) ; } else { manager . disable ( ) ; } } }
When needed toggle the enabled flag of given Simon manager
4,778
@ SuppressWarnings ( "InfiniteLoopStatement" ) public static void main ( String [ ] args ) throws Exception { SimonManager . callback ( ) . addCallback ( new JmxRegisterCallback ( "org.javasimon.examples.jmx.JmxCallbackExample" ) ) ; Counter counter = SimonManager . getCounter ( "org.javasimon.examples.jmx.counter" ) ;...
Entry point to the JMX Callback Example .
4,779
private static < T > SimonType getValue ( Class < ? extends T > type , SimonTypeMatcher < T > typeMatcher ) { SimonType simonType = SIMON_TYPE_CACHE . get ( type ) ; if ( simonType == null ) { for ( SimonType lSimonType : SimonType . values ( ) ) { if ( typeMatcher . matches ( type , lSimonType ) ) { simonType = lSimon...
Get Simon type corresponding to class .
4,780
public static SimonType getValueFromInstance ( Simon simon ) { return simon == null ? null : getValueFromType ( simon . getClass ( ) ) ; }
Get simon type from simon instance .
4,781
public static SimonType getValueFromInstance ( Sample sample ) { return sample == null ? null : getValueFromSampleType ( sample . getClass ( ) ) ; }
Get simon type from simon sample instance .
4,782
public static Class normalizeType ( Class type ) { SimonType simonType = SimonTypeFactory . getValueFromType ( type ) ; Class normalizedType ; if ( simonType == null ) { simonType = SimonTypeFactory . getValueFromSampleType ( type ) ; if ( simonType == null ) { normalizedType = type ; } else { normalizedType = simonTyp...
Get the main interface of the type .
4,783
public CallTreeNode onStopwatchStart ( Split split ) { final String name = split . getStopwatch ( ) . getName ( ) ; CallTreeNode currentNode ; if ( callStack . isEmpty ( ) ) { rootNode = new CallTreeNode ( name ) ; currentNode = rootNode ; onRootStopwatchStart ( currentNode , split ) ; } else { currentNode = callStack ...
When stopwatch is started a new tree node is added to the parent tree node and pushed on the call stack . As a result child tree node becomes the current tree node .
4,784
public CallTreeNode onStopwatchStop ( Split split ) { CallTreeNode currentNode = callStack . removeLast ( ) ; currentNode . addSplit ( split ) ; if ( callStack . isEmpty ( ) ) { onRootStopwatchStop ( currentNode , split ) ; } return currentNode ; }
When stopwatch is stopped the the split is added to current tree node and this tree node is popped from call stack . As a result parent tree node becomes current tree node .
4,785
public String getLogMessage ( Split context ) { context . getStopwatch ( ) . setAttribute ( CallTreeCallback . ATTR_NAME_LAST , this ) ; return "Call Tree:\r\n" + rootNode . toString ( ) ; }
Transforms this call tree into a loggable message .
4,786
public Connection connect ( String simonUrl , Properties info ) throws SQLException { if ( ! acceptsURL ( simonUrl ) ) { return null ; } SimonConnectionConfiguration url = new SimonConnectionConfiguration ( simonUrl ) ; driver = getRealDriver ( url , info ) ; return new SimonConnection ( driver . connect ( url . getRea...
Opens new Simon proxy driver connection associated with real connection to the specified database .
4,787
public final void addResource ( String path , HtmlResourceType type ) { resources . add ( new HtmlResource ( path , type ) ) ; }
Add a resource to this plugin .
4,788
public static List < HtmlResource > getResources ( ActionContext context , Class < ? extends SimonConsolePlugin > pluginType ) { List < HtmlResource > resources = new ArrayList < > ( ) ; for ( SimonConsolePlugin plugin : context . getPluginManager ( ) . getPluginsByType ( pluginType ) ) { resources . addAll ( plugin . ...
Gather resources used by all Detail plugins in the plugin manager
4,789
public final ObjectJS toJson ( StringifierFactory jsonStringifierFactory ) { final ObjectJS pluginJS = new ObjectJS ( ) ; final Stringifier < String > stringStringifier = jsonStringifierFactory . getStringifier ( String . class ) ; pluginJS . setSimpleAttribute ( "id" , getId ( ) , stringStringifier ) ; pluginJS . setS...
Serialize plugin data into a JSON object
4,790
private org . javasimon . jmx . CounterSample sampleCounter ( Simon counter ) { return new CounterSample ( ( org . javasimon . CounterSample ) counter . sample ( ) ) ; }
Create a JMX Counter Sample from a Sample
4,791
public List < CounterSample > getCounterSamples ( String namePattern ) { List < CounterSample > counterSamples = new ArrayList < > ( ) ; for ( Simon simon : manager . getSimons ( SimonPattern . createForCounter ( namePattern ) ) ) { counterSamples . add ( sampleCounter ( simon ) ) ; } return counterSamples ; }
Sample all Counters whose name matches given pattern
4,792
private org . javasimon . jmx . StopwatchSample sampleStopwatch ( Simon s ) { return new StopwatchSample ( ( org . javasimon . StopwatchSample ) s . sample ( ) ) ; }
Create a JMX Stopwatch Sample from a Stopwatch
4,793
public final void onSimonDestroyed ( Simon simon ) { String name = constructObjectName ( simon ) ; unregisterSimon ( name ) ; }
When the Simon is destroyed its MX bean is unregistered .
4,794
private synchronized void unregisterAllSimons ( ) { Iterator < String > namesIter = registeredNames . iterator ( ) ; while ( namesIter . hasNext ( ) ) { String name = namesIter . next ( ) ; try { ObjectName objectName = new ObjectName ( name ) ; mBeanServer . unregisterMBean ( objectName ) ; namesIter . remove ( ) ; on...
Unregister all previously registered Simons .
4,795
protected final void register ( Simon simon ) { Object mBean = constructObject ( simon ) ; String name = constructObjectName ( simon ) ; registerSimonBean ( mBean , name ) ; }
Method registering Simon MX Bean - can not be overridden but can be used in subclasses .
4,796
protected SimonSuperMXBean constructObject ( Simon simon ) { SimonSuperMXBean simonMxBean ; if ( simon instanceof Counter ) { simonMxBean = new CounterMXBeanImpl ( ( Counter ) simon ) ; } else if ( simon instanceof Stopwatch ) { simonMxBean = new StopwatchMXBeanImpl ( ( Stopwatch ) simon ) ; } else { onManagerWarning (...
Constructs JMX object from Simon object . Method can be overridden .
4,797
public static void main ( String [ ] args ) { Stopwatch stopwatch = SimonManager . getStopwatch ( "stopwatch" ) ; for ( int i = 1 ; i <= 10 ; i ++ ) { try ( Split ignored = SimonManager . getStopwatch ( "stopwatch" ) . start ( ) ) { ExampleUtils . waitRandomlySquared ( 50 ) ; } System . out . println ( "Stopwatch after...
Entry point to the Example .
4,798
private static synchronized ExecutorService initAsyncExecutorService ( ) { if ( ASYNC_EXECUTOR_SERVICE == null ) { ASYNC_EXECUTOR_SERVICE = java . util . concurrent . Executors . newSingleThreadExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread thread = new Thread ( r , "javasimon-async"...
Initializes default single threaded executor service .
4,799
public static void main ( String [ ] args ) { System . out . println ( "Wait for it... (~10s or more)" ) ; for ( int i = 0 ; i < ITERATIONS ; i ++ ) { try ( Split ignored = SimonManager . getStopwatch ( STOPWATCH_PARENT + Manager . HIERARCHY_DELIMITER + random . nextInt ( STOPWATCH_COUNT ) ) . start ( ) ) { ExampleUtil...
Entry point to the Aggregation Example .