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 = format . convert ( TypeUtility . simpleName ( bindMapperName ) ) ; if ( ! alreadyGeneratedMethods . contains ( simpleName ) ) { alreadyGeneratedMethods . add ( simpleName ) ; if ( bindMapperName . equals ( beanTypeName ) ) { context . builder . addField ( FieldSpec . builder ( bindMapperName , simpleName , modifiers ) . addJavadoc ( "$T" , bindMapperName ) . initializer ( "this" ) . build ( ) ) ; } else { context . builder . addField ( FieldSpec . builder ( bindMapperName , simpleName , modifiers ) . addJavadoc ( "$T" , bindMapperName ) . initializer ( "$T.mapperFor($T.class)" , BinderUtils . class , typeName ) . build ( ) ) ; } } return simpleName ; }
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 <code>true</code> if record is inserted, <code>false</code> otherwise" ) ; } else if ( TypeUtility . isTypeIncludedIn ( returnType , Long . TYPE , Long . class ) ) { methodBuilder . addJavadoc ( "\n" ) ; methodBuilder . addJavadoc ( "@return <strong>id</strong> of inserted record" ) ; } else if ( TypeUtility . isTypeIncludedIn ( returnType , Integer . TYPE , Integer . class ) ) { methodBuilder . addJavadoc ( "\n" ) ; methodBuilder . addJavadoc ( "@return <strong>id</strong> of inserted record" ) ; } methodBuilder . addJavadoc ( "\n" ) ; }
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 ) { value = value . substring ( value . lastIndexOf ( "." ) + 1 ) ; } ConflictAlgorithmType conflictAlgorithmType = ConflictAlgorithmType . valueOf ( value ) ; return conflictAlgorithmType ; }
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 ) <= maxFreeTxId ) ) { toDelete . add ( ( int ) pageId ) ; } e = iter . nextULL ( ) ; pageId = e . getKey ( ) ; value = e . getValue ( ) ; } if ( value >= 0 && value <= maxFreeTxId ) { idx . insertLong ( pageId , - currentTxId ) ; iter . close ( ) ; iter = idx . iterator ( pageId + 1 , Long . MAX_VALUE ) ; return ( int ) pageId ; } } return lastPage . addAndGet ( 1 ) ; }
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 . add ( f ) ; } } if ( availableIndices . isEmpty ( ) ) { advices . add ( new QueryAdvice ( queryTree ) ) ; return advices ; } List < QueryTreeNode > subQueries = new LinkedList < QueryTreeNode > ( ) ; subQueries . add ( queryTree ) ; queryTree . createSubs ( subQueries ) ; for ( QueryTreeNode sq : subQueries ) { optimize ( sq ) ; } IdentityHashMap < ZooFieldDef , Long > minMap = new IdentityHashMap < ZooFieldDef , Long > ( ) ; IdentityHashMap < ZooFieldDef , Long > maxMap = new IdentityHashMap < ZooFieldDef , Long > ( ) ; for ( QueryTreeNode sq : subQueries ) { advices . add ( determineIndexToUseSub ( sq , minMap , maxMap ) ) ; minMap . clear ( ) ; maxMap . clear ( ) ; } for ( QueryAdvice qa : advices ) { if ( qa == null ) { advices . clear ( ) ; advices . add ( qa ) ; return advices ; } if ( qa . getMin ( ) <= Long . MIN_VALUE && qa . getMax ( ) >= Long . MAX_VALUE ) { advices . clear ( ) ; advices . add ( qa ) ; return advices ; } } mergeAdvices ( advices ) ; return advices ; }
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 , true , iter , loadFromCache ) ; } } }
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 ) { throw DBLogger . newUser ( "The object belongs to a different PersistenceManager." ) ; } return pci ; }
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 . writeLong ( txId ) ; out . writeInt ( userPage ) ; out . writeInt ( oidPage ) ; out . writeInt ( schemaPage ) ; out . writeInt ( indexPage ) ; out . writeInt ( freeSpaceIndexPage ) ; out . writeInt ( pageCount ) ; out . writeLong ( lastUsedOid ) ; out . writeLong ( txId ) ; }
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: " + dbName ) ; ZooJdoProperties props = new ZooJdoProperties ( dbName ) ; PersistenceManagerFactory pmf = JDOHelper . getPersistenceManagerFactory ( props ) ; PersistenceManager pm = pmf . getPersistenceManager ( ) ; Session s = ( Session ) pm . getDataStoreConnection ( ) . getNativeConnection ( ) ; String report = s . getPrimaryNode ( ) . checkDb ( ) ; out . println ( ) ; out . println ( "Report" ) ; out . println ( "======" ) ; out . println ( report ) ; out . println ( "======" ) ; pm . close ( ) ; pmf . close ( ) ; out . println ( "Checking database done." ) ; }
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 . jdoZooIsStateHollow ( ) ) { return pc ; } } ZooClassDef clsDef = cache . getSchema ( clsOid ) ; ObjectReader or = in ; boolean isEvolved = false ; if ( clsDef . getNextVersion ( ) != null ) { isEvolved = true ; GenericObject go = GenericObject . newInstance ( clsDef , oid , false , cache ) ; readGOPrivate ( go , clsDef ) ; clsDef = go . ensureLatestVersion ( ) ; in = go . toStream ( ) ; if ( oid != in . readLong ( ) ) { throw new IllegalStateException ( ) ; } } ZooPC pObj = getInstance ( clsDef , oid , pc ) ; pObj . jdoZooSetTimestamp ( ts ) ; readObjPrivate ( pObj , clsDef ) ; in = or ; if ( isEvolved ) { pObj . jdoZooMarkDirty ( ) ; } return pObj ; }
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 DBHashMap ) { DBHashMap t = ( DBHashMap ) container ; doCollection ( t . keySet ( ) ) ; doCollection ( t . values ( ) ) ; } else { throw new IllegalArgumentException ( "Unrecognized persistent container in OGT: " + container . getClass ( ) ) ; } }
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 ( true ) ; } } if ( cls . getSuperclass ( ) != Object . class && cls != Object . class ) { for ( Field f : getFields ( cls . getSuperclass ( ) ) ) { retL . add ( f ) ; } } ret = retL . toArray ( new Field [ retL . size ( ) ] ) ; SEEN_CLASSES . put ( cls , ret ) ; return ret ; }
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 . jdoZooGetNode ( ) . getOidBuffer ( ) . allocateOid ( ) ; ZooFieldDef f = new ZooFieldDef ( declaringType , fieldName , typeName , arrayDim , jdoType , fieldOid ) ; return f ; }
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 . execute ( ) ; for ( Course c : courses ) { System . out . println ( ">> - " + c . getName ( ) + " by " + c . getTeacher ( ) . getName ( ) ) ; } }
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 = ( Collection < Course > ) q . execute ( ) ; for ( Course c : courses ) { System . out . println ( ">> - " + c . getName ( ) + " has size: " + c . getStudents ( ) . size ( ) ) ; } }
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 < Course > ) q . execute ( ) ; for ( Course c : courses ) { System . out . println ( ">> - " + c . getName ( ) + " has teacher: " + c . getTeacher ( ) . getName ( ) ) ; } }
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 . iteratorObjects ( ) ; DataDeSerializerNoClass dds = new DataDeSerializerNoClass ( fileInAP ) ; if ( field . isPrimitiveType ( ) ) { while ( iter . hasNext ( ) ) { long pos = iter . nextPos ( ) ; dds . seekPos ( pos ) ; long key = dds . getAttrAsLong ( def , field ) ; if ( isUnique ) { if ( ! fieldInd . insertLongIfNotSet ( key , dds . getLastOid ( ) ) ) { throw DBLogger . newUser ( "Duplicate entry in unique index: " + Util . oidToString ( dds . getLastOid ( ) ) + " v=" + key ) ; } } else { fieldInd . insertLong ( key , dds . getLastOid ( ) ) ; } } } else { while ( iter . hasNext ( ) ) { long pos = iter . nextPos ( ) ; dds . seekPos ( pos ) ; long key = dds . getAttrAsLongObjectNotNull ( def , field ) ; fieldInd . insertLong ( key , dds . getLastOid ( ) ) ; } } iter . close ( ) ; }
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 DataDeSerializerNoClass . getClassOid ( fileInAP ) ; } catch ( Exception e ) { throw DBLogger . newObjectNotFoundException ( "ERROR reading object: " + Util . oidToString ( oid ) ) ; } }
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 op2 = ( SchemaFieldDefine ) op ; int fieldId = op2 . getField ( ) . getFieldPos ( ) ; fV . add ( fieldId , PersistentSchemaOperation . getDefaultValue ( op2 . getField ( ) ) ) ; vV . add ( fieldId , null ) ; } if ( op instanceof SchemaOperation . SchemaFieldDelete ) { SchemaOperation . SchemaFieldDelete op2 = ( SchemaFieldDelete ) op ; int fieldId = op2 . getField ( ) . getFieldPos ( ) ; fV . remove ( fieldId ) ; vV . remove ( fieldId ) ; } fixedValues = fV . toArray ( fixedValues ) ; variableValues = vV . toArray ( variableValues ) ; }
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 DBLogger . newUser ( "This object has been modified via its Java class as well as via" + " the schema API. This is not allowed. Objectid: " + Util . oidToString ( jdoZooGetOid ( ) ) ) ; }
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 ) ) { if ( n . hi != null ) { n = n . hi ; continue ; } return compare ( key , n . hiPost ) == - 1 ; } else { if ( n . lo != null ) { n = n . lo ; continue ; } return compare ( key , n . loPost ) == - 1 ; } } }
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 . hi != null ) { n = n . hi ; continue ; } if ( compare ( key , n . hiPost ) == - 1 ) { return n . hiVal ; } } else { if ( n . lo != null ) { n = n . lo ; continue ; } if ( compare ( key , n . loPost ) == - 1 ) { return n . loVal ; } } return null ; } }
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 ; while ( true ) { if ( ! doesInfixMatch ( n , key ) ) { return null ; } if ( getBit ( key , n . posDiff ) ) { if ( n . hi != null ) { isParentHigh = true ; parent = n ; n = n . hi ; continue ; } else { int posDiff = compare ( key , n . hiPost ) ; if ( posDiff != - 1 ) { return null ; } long newPost = 0 ; if ( n . lo == null ) { newPost = n . loPost ; } updateParentAfterRemove ( parent , newPost , n . loVal , n . lo , isParentHigh , n ) ; return n . hiVal ; } } else { if ( n . lo != null ) { isParentHigh = false ; parent = n ; n = n . lo ; continue ; } else { int posDiff = compare ( key , n . loPost ) ; if ( posDiff != - 1 ) { return null ; } long newPost = 0 ; if ( n . hi == null ) { newPost = n . hiPost ; } updateParentAfterRemove ( parent , newPost , n . hiVal , n . hi , isParentHigh , n ) ; return n . loVal ; } } } }
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 ( ) ; return pm ; }
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 . createIndex ( fieldName , isUnique ) ; }
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 ) { System . out . println ( "Person found: " + p . getName ( ) ) ; } ext . closeAll ( ) ; System . out . println ( "Queries: " ) ; Query query = pm . newQuery ( Person . class , "name == 'Bart'" ) ; Collection < Person > barts = ( Collection < Person > ) query . execute ( ) ; for ( Person p : barts ) { System . out . println ( "Person found called 'Bart': " + p . getName ( ) ) ; } query . closeAll ( ) ; Person bart = barts . iterator ( ) . next ( ) ; System . out . println ( bart . getName ( ) + " has " + bart . getFriends ( ) . size ( ) + " friend(s):" ) ; for ( Person p : bart . getFriends ( ) ) { System . out . println ( p . getName ( ) + " is a friend of " + bart . getName ( ) ) ; } pm . currentTransaction ( ) . commit ( ) ; closeDB ( pm ) ; }
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 ( ) . commit ( ) ; pm . currentTransaction ( ) . begin ( ) ; bart . addFriend ( new Person ( "Maggie" ) ) ; pm . currentTransaction ( ) . commit ( ) ; closeDB ( pm ) ; }
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 . getOid ( ) + " class=" + className ) ; } this . superDef = superDef ; }
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" , e ) ; } createSchema ( cache . getSession ( ) . getPrimaryNode ( ) , cls ) ; } }
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 != null ? n2 . evaluate ( dds , pos ) : t2 . evaluate ( dds , pos ) ) ; }
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 ( n2 != null ) { node2 = n2 . cloneBranch ( ) ; } else { n2 = node2 = new QueryTreeNode ( null , t2 , null , null , null , false ) ; t2 = null ; } QueryTreeNode newTree ; if ( p != null ) { if ( p . n1 == this ) { p . n1 = node1 ; p . t1 = null ; p . relateToChildren ( ) ; } else if ( p . n2 == this ) { p . n2 = node1 ; p . t2 = null ; p . relateToChildren ( ) ; } else { throw new IllegalStateException ( ) ; } } else { subQueries . remove ( this ) ; subQueries . add ( node1 ) ; if ( node1 != null ) { node1 . p = null ; } if ( node2 != null ) { node2 . p = null ; } } if ( p != null ) { newTree = p . cloneTrunk ( node1 , node2 ) ; } else { newTree = node2 ; } newTree . createSubs ( subQueries ) ; subQueries . add ( newTree . root ( ) ) ; } if ( n1 != null ) { n1 . createSubs ( subQueries ) ; } if ( n2 != null ) { n2 . createSubs ( subQueries ) ; } }
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 = cloneSingle ( node1 , t1 , node2 , t2 ) ; if ( p != null ) { p . cloneTrunk ( this , ret ) ; } ret . relateToChildren ( ) ; return 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 . newUser ( "The PersistenceManager of this object is not open." ) ; } if ( ! session . isActive ( ) && ! session . getConfig ( ) . getNonTransactionalRead ( ) ) { throw DBLogger . newUser ( "The PersistenceManager of this object is not active " + "(-> use begin())." ) ; } jdoZooGetNode ( ) . refreshObject ( this ) ; } finally { context . getSession ( ) . unlock ( ) ; } return ; case PERSISTENT_DELETED : case PERSISTENT_NEW_DELETED : throw DBLogger . newUser ( "The object has been deleted." ) ; case PERSISTENT_NEW : case PERSISTENT_CLEAN : case PERSISTENT_DIRTY : return ; case TRANSIENT : case TRANSIENT_CLEAN : case TRANSIENT_DIRTY : return ; default : throw new IllegalStateException ( "" + getStatus ( ) ) ; } }
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 ) { markPageDirtyAndClone ( ) ; ind . file . reportFreePage ( subPageIds [ i ] ) ; subPageIds [ i ] = subChild . pageId ( ) ; subPages [ i ] = subChild ; if ( i > 0 ) { keys [ i - 1 ] = subChild . getMinKey ( ) ; if ( ! ind . isUnique ( ) ) { values [ i - 1 ] = subChild . getMinKeyValue ( ) ; } } subChild . setParent ( this ) ; return ; } } throw DBLogger . newFatalInternal ( "Sub-page not found." ) ; }
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 pageKey . remove ( key ) ; } if ( posKey < pageKey . nEntries - 1 ) { if ( keys [ posKey + 1 ] <= max ) { return pageKey . remove ( key ) ; } ind . file . reportFreePage ( BitTools . getPage ( key ) ) ; return pageKey . remove ( key ) ; } } else if ( posKey == 0 && pageKey . nEntries > 1 ) { if ( keys [ posKey + 1 ] <= max ) { return pageKey . remove ( key ) ; } } long pos = pageKey . remove ( key ) ; LLEntryIterator iter = ind . iterator ( min , max ) ; if ( ! iter . hasNextULL ( ) ) { ind . file . reportFreePage ( BitTools . getPage ( key ) ) ; } iter . close ( ) ; return pos ; }
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 . isDebug ( ) ) Log . debug ( "obj=" , obj , ", now-last=" , now - obj . getLastAccessTs ( ) , ", max idle=" , config . getMaxIdleMilliseconds ( ) ) ; if ( now - obj . getLastAccessTs ( ) > config . getMaxIdleMilliseconds ( ) && ThreadLocalRandom . current ( ) . nextDouble ( 1 ) < config . getScavengeRatio ( ) ) { decreaseObject ( obj ) ; removed ++ ; } else { objectQueue . put ( obj ) ; } } if ( removed > 0 ) Log . debug ( removed , " objects were scavenged." ) ; }
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" ) ; Stopwatch stopwatch = SimonManager . getStopwatch ( "org.javasimon.examples.jmx.stopwatch" ) ; SimonManager . getCounter ( "org.javasimon.different.counter" ) ; SimonManager . getStopwatch ( "org.javasimon.some.other.jmx.stopwatch1" ) ; SimonManager . getStopwatch ( "org.javasimon.some.other.jmx.stopwatch2" ) ; System . out . println ( "Now open jconsole and check it out...\nWatch org.javasimon.examples.jmx.stopwatch for changes." ) ; while ( true ) { counter . increase ( ) ; try ( Split ignored = stopwatch . start ( ) ) { ExampleUtils . waitRandomlySquared ( 40 ) ; } } }
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 = lSimonType ; if ( ! Proxy . isProxyClass ( type ) ) { SIMON_TYPE_CACHE . put ( type , simonType ) ; } break ; } } } return simonType ; }
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 = simonType . getSampleType ( ) ; } } else { normalizedType = simonType . getType ( ) ; } return normalizedType ; }
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 . getLast ( ) . getOrAddChild ( name ) ; } callStack . addLast ( currentNode ) ; return currentNode ; }
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 . getRealUrl ( ) , info ) , url . getPrefix ( ) ) ; }
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 . getResources ( ) ) ; } return resources ; }
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 . setSimpleAttribute ( "label" , getLabel ( ) , stringStringifier ) ; pluginJS . setAttribute ( "resources" , HtmlResource . toJson ( getResources ( ) , jsonStringifierFactory ) ) ; return pluginJS ; }
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 ( ) ; onManagerMessage ( "Unregistered Simon with the name: " + objectName ) ; } catch ( JMException e ) { onManagerWarning ( "JMX unregistration failed for: " + name , e ) ; } } }
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 ( "Unknown type of Simon! " + simon , null ) ; simonMxBean = null ; } return simonMxBean ; }
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 round " + i + ": " + stopwatch ) ; } System . out . println ( "stopwatch.sample() = " + stopwatch . sample ( ) ) ; }
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" ) ; thread . setDaemon ( true ) ; return thread ; } } ) ; } return ASYNC_EXECUTOR_SERVICE ; }
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 ( ) ) { ExampleUtils . waitRandomlySquared ( 20 ) ; } } Simon parent = SimonManager . getSimon ( STOPWATCH_PARENT ) ; List < Simon > children = parent . getChildren ( ) ; System . out . println ( "parent.children count = " + children . size ( ) + '\n' ) ; long totalSum = 0 ; for ( Simon child : children ) { System . out . println ( child ) ; totalSum += ( ( Stopwatch ) child ) . getTotal ( ) ; } System . out . println ( "Programmatic totalSum = " + SimonUtils . presentNanoTime ( totalSum ) ) ; System . out . println ( "\nSimonUtils.calculateStopwatchAggregate(parent) = " + SimonUtils . calculateStopwatchAggregate ( parent ) ) ; }
Entry point to the Aggregation Example .