idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
4,800
protected Split startSplit ( ) { Stopwatch stopwatch = SimonManager . getStopwatch ( sqlCmdLabel + Manager . HIERARCHY_DELIMITER + sqlNormalizer . getNormalizedSql ( ) . hashCode ( ) ) ; if ( stopwatch . getNote ( ) == null ) { stopwatch . setNote ( sqlNormalizer . getNormalizedSql ( ) ) ; } return stopwatch . start ( ) ; }
Starts the split for the SQL specific stopwatch sets the note and returns the split . Used in the statment and prepared statement classes to measure runs of execute methods .
4,801
public final void addBatch ( String s ) throws SQLException { batchSql . add ( s ) ; stmt . addBatch ( s ) ; }
Adds given SQL command into batch list of sql and also into real batch .
4,802
public void readConfig ( Reader reader ) throws IOException { try { XMLStreamReader xr = XMLInputFactory . newInstance ( ) . createXMLStreamReader ( reader ) ; try { while ( ! xr . isStartElement ( ) ) { xr . next ( ) ; } processStartElement ( xr , "simon-configuration" ) ; while ( true ) { if ( isStartTag ( xr , "callback" ) ) { manager . callback ( ) . addCallback ( processCallback ( xr ) ) ; } else if ( isStartTag ( xr , "filter-callback" ) ) { manager . callback ( ) . addCallback ( processFilterCallback ( xr ) ) ; } else if ( isStartTag ( xr , "simon" ) ) { processSimon ( xr ) ; } else { break ; } } assertEndTag ( xr , "simon-configuration" ) ; } finally { xr . close ( ) ; } } catch ( XMLStreamException e ) { manager . callback ( ) . onManagerWarning ( null , e ) ; } catch ( SimonException e ) { manager . callback ( ) . onManagerWarning ( e . getMessage ( ) , e ) ; } }
Reads config from provided buffered reader . Reader is not closed after this method finishes .
4,803
private void setProperty ( Callback callback , String property , String value ) { try { if ( value != null ) { SimonBeanUtils . getInstance ( ) . setProperty ( callback , property , value ) ; } else { callback . getClass ( ) . getMethod ( setterName ( property ) ) . invoke ( callback ) ; } } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) { throw new SimonException ( e ) ; } }
Sets the callback property .
4,804
SimonConfiguration getConfig ( String name ) { SimonState state = null ; for ( SimonPattern pattern : configs . keySet ( ) ) { if ( pattern . matches ( name ) ) { SimonConfiguration config = configs . get ( pattern ) ; if ( config . getState ( ) != null ) { state = config . getState ( ) ; } } } return new SimonConfiguration ( state ) ; }
Returns configuration for the Simon with the specified name .
4,805
public boolean matches ( String name ) { if ( name == null ) { return pattern . equals ( "" ) ; } if ( all != null ) { return all . equals ( name ) ; } if ( middle != null ) { return name . contains ( middle ) ; } if ( start != null && ! name . startsWith ( start ) ) { return false ; } return end == null || name . endsWith ( end ) ; }
Checks if Simon name matches this pattern .
4,806
private static boolean isGetterMethod ( Method method ) { return ! Modifier . isStatic ( method . getModifiers ( ) ) && ( method . getName ( ) . startsWith ( "get" ) || method . getName ( ) . startsWith ( "is" ) ) && method . getParameterTypes ( ) . length == 0 ; }
Test whether method is a getter .
4,807
private static String getPropertyName ( Method method ) { String propertyName = method . getName ( ) ; if ( propertyName . startsWith ( "get" ) ) { propertyName = propertyName . substring ( 3 ) ; } else if ( propertyName . startsWith ( "is" ) ) { propertyName = propertyName . substring ( 2 ) ; } propertyName = propertyName . substring ( 0 , 1 ) . toLowerCase ( ) + propertyName . substring ( 1 ) ; return propertyName ; }
Transform method name into property name .
4,808
private static String getSubType ( Class type , String propertyName ) { @ SuppressWarnings ( "unchecked" ) Class normalizedType = SimonTypeFactory . normalizeType ( type ) ; if ( normalizedType == null ) { return null ; } else { return subTypeProperties . getProperty ( normalizedType . getName ( ) + "." + propertyName ) ; } }
Get subtype for given Class and property .
4,809
private static Map < String , Getter > getGettersAsMap ( Class type ) { Map < String , Getter > typeGetters = GETTER_CACHE . get ( type ) ; if ( typeGetters == null ) { typeGetters = new HashMap < > ( ) ; for ( Method method : type . getMethods ( ) ) { if ( isGetterMethod ( method ) ) { String propertyName = getPropertyName ( method ) ; Class propertyType = method . getReturnType ( ) ; typeGetters . put ( propertyName , new Getter ( propertyName , propertyType , getSubType ( type , propertyName ) , method ) ) ; } } GETTER_CACHE . put ( type , typeGetters ) ; } return typeGetters ; }
Extract all getters for given class .
4,810
@ SuppressWarnings ( "unchecked" ) public static Getter getGetter ( Class type , String name ) { return getGettersAsMap ( type ) . get ( name ) ; }
Search getter for given class and property name .
4,811
public void onStopwatchStop ( Split split , StopwatchSample sample ) { logger . log ( level , "SIMON STOP: " + sample . simonToString ( ) + " (" + split . runningFor ( ) + ")" ) ; }
Logs Simon stop on a specified log level .
4,812
public void onManagerWarning ( String warning , Exception cause ) { logger . log ( level , "SIMON WARNING: " + warning , cause ) ; }
Logs the warning on a specified log level .
4,813
private void htmlMessage ( DetailHtmlBuilder htmlBuilder , String message ) throws IOException { htmlBuilder . beginRow ( ) . labelCell ( "Message" ) . valueCell ( " colspan=\"3\"" , message ) . endRow ( ) ; }
Generate an HTML message row
4,814
protected Object processInvoke ( MethodInvocation invocation , Split split ) throws Throwable { try { return invocation . proceed ( ) ; } catch ( Throwable t ) { split . stop ( tagByExceptionType ? t . getClass ( ) . getSimpleName ( ) : EXCEPTION_TAG ) ; throw t ; } }
Method stops the split
4,815
@ SuppressWarnings ( "SynchronizationOnLocalVariableOrMethodParameter" ) private List < Long > getOrCreateBucketsValues ( final Stopwatch stopwatch ) { synchronized ( stopwatch ) { List < Long > values = getBucketsValues ( stopwatch ) ; if ( values == null ) { values = new ArrayList < > ( ( int ) warmupCounter ) ; stopwatch . setAttribute ( ATTR_NAME_BUCKETS_VALUES , values ) ; } return values ; } }
Get the bucket values attribute or create it if it does not exist .
4,816
@ SuppressWarnings ( "unchecked" ) private List < Long > getBucketsValues ( final Stopwatch stopwatch ) { return ( List < Long > ) stopwatch . getAttribute ( ATTR_NAME_BUCKETS_VALUES ) ; }
Get the bucket values attribute .
4,817
protected final Buckets createBuckets ( Stopwatch stopwatch ) { if ( stopwatch . getCounter ( ) > warmupCounter ) { Buckets buckets = createBucketsAfterWarmup ( stopwatch ) ; buckets . addValues ( getBucketsValues ( stopwatch ) ) ; removeBucketsValues ( stopwatch ) ; return buckets ; } else { return null ; } }
When warmup ends buckets are create and retained splits are sorted in the buckets .
4,818
public void onSimonCreated ( Simon simon ) { if ( simon instanceof Stopwatch ) { Stopwatch stopwatch = ( Stopwatch ) simon ; getOrCreateBucketsValues ( stopwatch ) ; } }
When simon is created the list containing Split values is added to stopwatch attributes .
4,819
private DetailHtmlBuilder htmlTreeNode ( CallTreeNode node , DetailHtmlBuilder htmlBuilder , StringifierFactory htmlStringifierFactory ) throws IOException { htmlBuilder . begin ( "li" ) . text ( node . getName ( ) ) . text ( ":&nbsp;" ) ; if ( node . getParent ( ) != null ) { htmlBuilder . text ( htmlStringifierFactory . toString ( node . getPercent ( ) ) ) . text ( "%" ) . text ( ", " ) ; } htmlBuilder . text ( "total&nbsp;" ) . text ( htmlStringifierFactory . toString ( node . getTotal ( ) , "Time" ) ) . text ( ", " ) . text ( "count&nbsp;" ) . text ( htmlStringifierFactory . toString ( node . getSplitCount ( ) ) ) ; if ( ! node . getChildren ( ) . isEmpty ( ) ) { htmlBuilder . begin ( "ul" ) ; for ( CallTreeNode childNode : node . getChildren ( ) ) { htmlTreeNode ( childNode , htmlBuilder , htmlStringifierFactory ) ; } htmlBuilder . end ( "ul" ) ; } return htmlBuilder . end ( "li" ) ; }
Generate a HTML call tree node list
4,820
private ObjectJS jsonMessage ( String message , StringifierFactory jsonStringifierFactory ) { ObjectJS callTreeJS = new ObjectJS ( ) ; callTreeJS . setSimpleAttribute ( "message" , message , jsonStringifierFactory . getStringifier ( String . class ) ) ; return callTreeJS ; }
Generate a JSON message object
4,821
private ObjectJS jsonTreeNode ( CallTreeNode node , StringifierFactory jsonStringifierFactory ) { final ObjectJS nodeJS = ObjectJS . create ( node , jsonStringifierFactory ) ; if ( ! node . getChildren ( ) . isEmpty ( ) ) { final ArrayJS childNodesJS = new ArrayJS ( node . getChildren ( ) . size ( ) ) ; for ( CallTreeNode childNode : node . getChildren ( ) ) { childNodesJS . addElement ( jsonTreeNode ( childNode , jsonStringifierFactory ) ) ; } nodeJS . setAttribute ( "children" , childNodesJS ) ; } return nodeJS ; }
Generate a JSON call tree node object
4,822
public ObjectJS executeJson ( ActionContext context , StringifierFactory jsonStringifierFactory , Simon simon ) { ObjectJS callTreeJS ; if ( isCallTreeCallbackRegistered ( context ) ) { CallTree callTree = getData ( simon ) ; if ( callTree == null ) { callTreeJS = jsonMessage ( NO_DATA_MESSAGE , jsonStringifierFactory ) ; } else { callTreeJS = ObjectJS . create ( callTree , jsonStringifierFactory ) ; callTreeJS . setAttribute ( "rootNode" , jsonTreeNode ( callTree . getRootNode ( ) , jsonStringifierFactory ) ) ; } } else { callTreeJS = jsonMessage ( NO_CALLBACK_MESSAGE , jsonStringifierFactory ) ; } return callTreeJS ; }
Generate a JSON call tree object or an error string if no call tree
4,823
public static String barChart ( StopwatchSample [ ] samples , String title , double divisor , String unit ) { final StringBuilder result = new StringBuilder ( "<html>\n" + " <head>\n" + " <script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n" + " <script type=\"text/javascript\">\n" + " google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});\n" + " google.setOnLoadCallback(drawChart);\n" + " function drawChart() {\n" + " var data = new google.visualization.DataTable();\n" ) ; result . append ( " data.addColumn('string', 'stopwatch');\n" + " data.addColumn('number', 'avg');\n" + " data.addColumn('number', 'max');\n" + " data.addColumn('number', 'min');\n" + " data.addRows(" ) . append ( samples . length ) . append ( ");\n" ) ; int rowIndex = 0 ; for ( StopwatchSample sample : samples ) { Stopwatch stopwatch = ( Stopwatch ) sample ; result . append ( " data.setValue(" ) . append ( rowIndex ) . append ( ", 0, '" ) . append ( stopwatch . getName ( ) ) . append ( "');\n" ) . append ( " data.setValue(" ) . append ( rowIndex ) . append ( ", 1, " ) . append ( stopwatch . getMean ( ) / divisor ) . append ( ");\n" ) . append ( " data.setValue(" ) . append ( rowIndex ) . append ( ", 2, " ) . append ( stopwatch . getMax ( ) / divisor ) . append ( ");\n" ) . append ( " data.setValue(" ) . append ( rowIndex ) . append ( ", 3, " ) . append ( stopwatch . getMin ( ) / divisor ) . append ( ");\n" ) ; rowIndex ++ ; } result . append ( " var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));\n" + " chart.draw(data, {width: " ) . append ( ONE_BAR_WIDTH * ( 1 + samples . length ) ) . append ( ", height: 600, title: '" ) . append ( title ) . append ( "',\n hAxis: {title: 'stopwatch', titleTextStyle: {color: 'red'}}\n" + " });\n }\n" + " </script>\n" + " </head>\n\n <body>\n <div id=\"chart_div\"></div>\n </body>\n</html>" ) ; return result . toString ( ) ; }
Generates Google bar chart HTML5 source code for the provided samples .
4,824
static public JmxReporter forManager ( Manager manager ) { JmxReporter reporter = new JmxReporter ( manager ) ; reporter . setBeanName ( DEFAULT_BEAN_NAME ) ; reporter . simonDomain = DEFAULT_SIMON_DOMAIN ; reporter . beanServer = ManagementFactory . getPlatformMBeanServer ( ) ; return reporter ; }
Creates new JmxReporter for the specified manager with default values .
4,825
public JmxReporter start ( ) { SimonManagerMXBean simonManagerMXBean = new SimonManagerMXBeanImpl ( manager ) ; registerMXBean ( simonManagerMXBean , beanName ) ; if ( registerSimons ) { jmxRegisterCallback = new JmxRegisterCallback ( beanServer , simonDomain ) ; if ( registerExistingSimons ) { jmxRegisterCallback . setRegisterExisting ( true ) ; } manager . callback ( ) . addCallback ( jmxRegisterCallback ) ; } return this ; }
Starts JmxReporter - registers all required beans in JMX bean server .
4,826
private < T > T processFunction ( SplitFunction < T > function ) { synchronized ( splits ) { if ( splits . isEmpty ( ) ) { return null ; } for ( Split split : splits ) { function . evaluate ( split ) ; } return function . result ( ) ; } }
Evaluate a function over the list of splits .
4,827
public Double getMean ( ) { return processFunction ( new AbstractSplitFunction < Double > ( 0.0D ) { public void evaluate ( long runningFor ) { result += ( double ) runningFor ; } public Double result ( ) { return result / ( double ) splits . size ( ) ; } } ) ; }
Compute mean duration of splits in the buffer
4,828
public Long getMin ( ) { return processFunction ( new AbstractSplitFunction < Long > ( Long . MAX_VALUE ) { public void evaluate ( long runningFor ) { if ( runningFor < result ) { result = runningFor ; } } } ) ; }
Compute the smallest duration of splits in the buffer
4,829
public Long getMax ( ) { return processFunction ( new AbstractSplitFunction < Long > ( Long . MIN_VALUE ) { public void evaluate ( long runningFor ) { if ( runningFor > result ) { result = runningFor ; } } } ) ; }
Compute the longest duration of splits in the buffer
4,830
private String getSplitsAsString ( ) { return processFunction ( new AbstractSplitFunction < StringBuilder > ( new StringBuilder ( ) ) { private boolean first = true ; public void evaluate ( long runningFor ) { if ( first ) { first = false ; } else { result . append ( ',' ) ; } result . append ( presentNanoTime ( runningFor ) ) ; } } ) . toString ( ) ; }
Transforms split values into a String
4,831
public synchronized boolean checkCondition ( Simon simon , Object ... params ) throws ScriptException { if ( condition == null ) { return true ; } if ( simon instanceof Stopwatch ) { return checkStopwtach ( ( Stopwatch ) simon , params ) ; } if ( simon instanceof Counter ) { return checkCounter ( ( Counter ) simon , params ) ; } return true ; }
Checks the Simon and optional parameters against the condition specified for a rule .
4,832
private static String getProperty ( String driverId , String propertyName ) { String propertyValue = PROPERTIES . getProperty ( DEFAULT_PREFIX + "." + driverId + "." + propertyName ) ; if ( propertyValue != null ) { propertyValue = propertyValue . trim ( ) ; if ( propertyValue . isEmpty ( ) ) { propertyValue = null ; } } return propertyValue ; }
Gets value of the specified property .
4,833
public static boolean isSimonUrl ( String url ) { return url != null && url . toLowerCase ( ) . startsWith ( SimonConnectionConfiguration . URL_PREFIX ) ; }
Tests whether URL is a Simon JDBC connection URL .
4,834
public Integer getPercent ( ) { Integer percent ; if ( parent == null ) { percent = null ; } else { percent = ( int ) ( getTotal ( ) * 100L / getParent ( ) . getTotal ( ) ) ; } return percent ; }
Returns the part of time spent in this node compared to parent .
4,835
public CallTreeNode addChild ( String name ) { if ( children == null ) { children = new HashMap < > ( ) ; } CallTreeNode child = new CallTreeNode ( name ) ; children . put ( name , child ) ; child . parent = this ; return child ; }
Adds a child to this tree node .
4,836
public CallTreeNode getChild ( String name ) { return ( children == null ) ? null : children . get ( name ) ; }
Returns the child node by Simon name .
4,837
public Collection < CallTreeNode > getChildren ( ) { return children == null ? Collections . < CallTreeNode > emptyList ( ) : children . values ( ) ; }
Returns all child nodes .
4,838
public CallTreeNode getOrAddChild ( String name ) { CallTreeNode child = getChild ( name ) ; if ( child == null ) { child = addChild ( name ) ; } return child ; }
Returns a child node with given name or creates it if it does not exists .
4,839
private void print ( PrintWriter printWriter , String prefix , Long parentTotal ) { long total = getTotal ( ) ; printWriter . print ( prefix ) ; printWriter . print ( name ) ; printWriter . print ( ' ' ) ; if ( parentTotal != null && parentTotal != 0L ) { printWriter . print ( total * 100 / parentTotal ) ; printWriter . print ( "%, " ) ; } printWriter . print ( SimonUtils . presentNanoTime ( total ) ) ; long counter = getSplitCount ( ) ; if ( counter > 1 ) { printWriter . print ( ", " ) ; printWriter . print ( counter ) ; } printWriter . println ( ) ; for ( CallTreeNode child : getChildren ( ) ) { child . print ( printWriter , prefix + "\t" , total ) ; } }
Recursively prints this tree node to given print writer .
4,840
@ SuppressWarnings ( "InfiniteLoopStatement" ) public static void main ( String [ ] args ) throws Exception { LoggingCallback loggingCallback = new LoggingCallback ( ) ; loggingCallback . setLevel ( Level . INFO ) ; SimonManager . callback ( ) . addCallback ( loggingCallback ) ; Random random = new Random ( ) ; register ( ) ; try { while ( true ) { final int task = random . nextInt ( TASK_SPREAD ) + TASK_MIN ; new Thread ( ) { public void run ( ) { try ( Split split = SimonManager . getStopwatch ( TASK_STOPWATCH ) . start ( ) ) { Thread . sleep ( task ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } . start ( ) ; int sleep = random . nextInt ( NEW_TASK_SPREAD ) + NEW_TASK_MIN ; Thread . sleep ( sleep ) ; } } finally { unregister ( ) ; } }
Entry point to the JMX task processing simulator .
4,841
public static void visitTree ( Simon simon , SimonVisitor visitor ) throws IOException { visitor . visit ( simon ) ; for ( Simon childSimon : simon . getChildren ( ) ) { visitTree ( childSimon , visitor ) ; } }
Visit Simons recursively as a tree starting from the specified Simon .
4,842
void addSample ( StopwatchSample sample ) { total += sample . getTotal ( ) ; counter += sample . getCounter ( ) ; if ( min > sample . getMin ( ) ) { min = sample . getMin ( ) ; minTimestamp = sample . getMinTimestamp ( ) ; } if ( max < sample . getMax ( ) ) { max = sample . getMax ( ) ; maxTimestamp = sample . getMaxTimestamp ( ) ; } active += sample . getActive ( ) ; if ( maxActive < sample . getMaxActive ( ) ) { maxActive = sample . getMaxActive ( ) ; maxActiveTimestamp = sample . getMaxActiveTimestamp ( ) ; } }
Add stopwatch sample to current statistics aggregate .
4,843
protected Buckets createBuckets ( Stopwatch stopwatch ) { return createBuckets ( stopwatch , min * SimonClock . NANOS_IN_MILLIS , max * SimonClock . NANOS_IN_MILLIS , bucketNb ) ; }
Create buckets using callback attributes
4,844
public void onSimonCreated ( Simon simon ) { if ( simon instanceof Stopwatch ) { Stopwatch stopwatch = ( Stopwatch ) simon ; LastSplits lastSplits = new LastSplits ( capacity ) ; lastSplits . setLogTemplate ( createLogTemplate ( stopwatch ) ) ; stopwatch . setAttribute ( ATTR_NAME_LAST_SPLITS , lastSplits ) ; } }
When Stopwatch is created a Last Splits attributes is added .
4,845
public void onStopwatchStop ( Split split , StopwatchSample sample ) { LastSplits lastSplits = getLastSplits ( split . getStopwatch ( ) ) ; lastSplits . add ( split ) ; lastSplits . log ( split ) ; }
When a Splits is stopped it is added to the stopwatch a Last Splits attribute .
4,846
public static void main ( String [ ] args ) { SimonManager . callback ( ) . addCallback ( new CallbackSkeleton ( ) { public void onStopwatchStart ( Split split ) { System . out . println ( "\nStopwatch " + split . getStopwatch ( ) . getName ( ) + " has just been started." ) ; } public void onStopwatchStop ( Split split , StopwatchSample sample ) { System . out . println ( "Stopwatch " + split . getStopwatch ( ) . getName ( ) + " has just been stopped (" + SimonUtils . presentNanoTime ( split . runningFor ( ) ) + ")." ) ; } } ) ; Stopwatch sw = SimonManager . getStopwatch ( SimonUtils . generateName ( ) ) ; sw . start ( ) . stop ( ) ; Split split = sw . start ( ) ; for ( int i = 0 ; i < 1000000 ; i ++ ) { } split . stop ( ) ; sw . start ( ) . stop ( ) ; System . out . println ( "\nAdditional stop() does nothing, Split state is preserved." ) ; split . stop ( ) ; System . out . println ( "split = " + split ) ; }
Entry point to the Callback Example .
4,847
public void addSplit ( long timestampInMs , long durationInNs ) { last = durationInNs ; total += durationInNs ; squareTotal += durationInNs * durationInNs ; if ( durationInNs > max ) { max = durationInNs ; } if ( durationInNs < min ) { min = durationInNs ; } counter ++ ; lastTimestamp = timestampInMs ; }
Add stopwatch split information .
4,848
public Double getVariance ( ) { if ( counter == 0 ) { return Double . NaN ; } else { final double mean = computeMean ( ) ; final double meanSquare = mean * mean ; final double squareMean = ( ( double ) squareTotal ) / counter ; return squareMean - meanSquare ; } }
Compute variance .
4,849
public void rollback ( Savepoint savepoint ) throws SQLException { conn . rollback ( savepoint ) ; rollbacks . increase ( ) ; }
Rollbacks the real connection and increases the rollbacks Simon .
4,850
public Statement createStatement ( int rsType , int rsConcurrency ) throws SQLException { return new SimonStatement ( this , conn . createStatement ( rsType , rsConcurrency ) , prefix ) ; }
Calls real createStatement and wraps returned statement by Simon s statement .
4,851
public CallableStatement prepareCall ( String sql ) throws SQLException { return new SimonCallableStatement ( conn , conn . prepareCall ( sql ) , sql , prefix ) ; }
Calls real prepareCall and wraps returned statement by Simon s statement .
4,852
public synchronized void start ( long period , TimeUnit timeUnit ) { if ( scheduledFuture == null ) { PurgerRunnable runnable = new PurgerRunnable ( manager ) ; scheduledFuture = executorService . scheduleWithFixedDelay ( runnable , period , period , timeUnit ) ; } else { throw new IllegalStateException ( "IncrementSimonPurger has already been started" ) ; } }
Start periodical Simons purging with the specified period .
4,853
public static void main ( String [ ] args ) throws IOException , MalformedObjectNameException { final JMXServiceURL url = new JMXServiceURL ( "service:jmx:rmi:///jndi/rmi://" + args [ 0 ] + "/jmxrmi" ) ; JMXConnector jmxc = JMXConnectorFactory . connect ( url , null ) ; MBeanServerConnection mbsc = jmxc . getMBeanServerConnection ( ) ; SimonManagerMXBean simonManagerMXBean = JMX . newMXBeanProxy ( mbsc , new ObjectName ( "org.javasimon.jmx.example:type=Simon" ) , SimonManagerMXBean . class ) ; System . out . println ( "List of retrieved Simons:" ) ; for ( String n : simonManagerMXBean . getSimonNames ( ) ) { System . out . println ( " " + n ) ; } System . out . println ( "List of stopwatch Simons:" ) ; for ( SimonInfo si : simonManagerMXBean . getSimonInfos ( ) ) { if ( si . getType ( ) . equals ( SimonInfo . STOPWATCH ) ) { System . out . println ( " " + si . getName ( ) ) ; } } simonManagerMXBean . printSimonTree ( ) ; jmxc . close ( ) ; }
Entry point to this monitoring client .
4,854
private int incrementIndex ( int index , int maxIndex ) { int newIndex = index + 1 ; if ( newIndex >= elements . length ) { newIndex = maxIndex ; } return newIndex ; }
Increment an index
4,855
public boolean add ( T newElement ) { elements [ lastIndex ] = newElement ; lastIndex = incrementIndex ( lastIndex , 0 ) ; if ( isEmpty ( ) ) { firstIndex = 0 ; size = 1 ; } else if ( isFull ( ) ) { firstIndex = lastIndex ; } else { size = incrementIndex ( size , elements . length ) ; } return true ; }
Add an element to the list overwriting last added element when list s capacity is reached
4,856
public boolean addAll ( Collection < ? extends T > newElements ) { for ( T newElement : newElements ) { add ( newElement ) ; } return true ; }
Inserts a collection of elements looping on them .
4,857
private < X > void copy ( X [ ] elementsCopy ) { if ( ! isEmpty ( ) ) { if ( firstIndex < lastIndex ) { System . arraycopy ( elements , firstIndex , elementsCopy , 0 , lastIndex - firstIndex ) ; } else { int firstSize = elements . length - firstIndex ; System . arraycopy ( elements , firstIndex , elementsCopy , 0 , firstSize ) ; System . arraycopy ( elements , 0 , elementsCopy , firstSize , lastIndex ) ; } } }
Copy elements in a target array .
4,858
public void run ( ) { Stopwatch stopwatch = SimonManager . getStopwatch ( NAME ) ; try ( Split ignored = stopwatch . start ( ) ; ) { sleep ( SLEEP ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } latch . countDown ( ) ; }
Run method implementing the code performed by the thread .
4,859
public T attr ( String name , String value ) throws IOException { if ( value != null ) { writer . write ( ' ' ) ; writer . write ( name ) ; writer . write ( "=\"" ) ; writer . write ( value ) ; writer . write ( '\"' ) ; } return ( T ) this ; }
Add attribute .
4,860
public T element ( String element , String id , String cssClass ) throws IOException { doBegin ( element , id , cssClass ) ; writer . write ( " />" ) ; return ( T ) this ; }
Simple element .
4,861
public T end ( String element ) throws IOException { writer . write ( "</" ) ; writer . write ( element ) ; writer . write ( '>' ) ; return ( T ) this ; }
End an element .
4,862
public T text ( String text ) throws IOException { if ( text != null ) { writer . write ( text ) ; } return ( T ) this ; }
Writes text .
4,863
private T cssResource ( String path ) throws IOException { return ( T ) write ( "<link href=\"../resource/" ) . write ( path ) . write ( "\" rel=\"stylesheet\" type=\"text/css\" />" ) ; }
Adds a CSS StyleSheet link .
4,864
public T header ( String title , Iterable < HtmlResource > resources ) throws IOException { return ( T ) begin ( "html" ) . begin ( "head" ) . begin ( "title" ) . text ( "Simon Console: " ) . text ( title ) . end ( "title" ) . resources ( resources ) . end ( "head" ) . begin ( "body" ) . begin ( "h1" ) . write ( "<img id=\"logo\" src=\"../resource/images/logo.png\" alt=\"Logo\" />" ) . text ( "Simon Console: " ) . text ( title ) . end ( "h1" ) ; }
Page header .
4,865
public < X > T value ( X value , String subType ) throws IOException { return text ( stringifierFactory . toString ( value , subType ) ) ; }
Write value using appropriate stringifier .
4,866
public T object ( Object object ) throws IOException { text ( stringifierFactory . toString ( object ) ) ; return ( T ) this ; }
Apply stringifier on object and write it .
4,867
public T simonTypeImg ( SimonType simonType , String rootPath ) throws IOException { String image = null ; switch ( simonType ) { case COUNTER : image = "TypeCounter.png" ; break ; case STOPWATCH : image = "TypeStopwatch.png" ; break ; case UNKNOWN : image = "TypeUnknown.png" ; break ; } String label = simonType . name ( ) . toLowerCase ( ) ; doBegin ( "img" , null , label + " icon" ) ; attr ( "src" , rootPath + "resource/images/" + image ) ; attr ( "alt" , label ) ; writer . write ( " />" ) ; return ( T ) this ; }
Icon image representing Simon Type .
4,868
private CallTree initCallTree ( ) { final CallTree callTree = new CallTree ( logThreshold ) { protected void onRootStopwatchStop ( CallTreeNode rootNode , Split split ) { CallTreeCallback . this . onRootStopwatchStop ( this , split ) ; } } ; threadCallTree . set ( callTree ) ; return callTree ; }
Initializes the call tree for current thread .
4,869
public void onRootStopwatchStop ( CallTree callTree , Split split ) { callTreeLogTemplate . log ( split , callTree ) ; if ( logThreshold != null && split . runningFor ( ) > logThreshold ) { split . getStopwatch ( ) . setAttribute ( ATTR_NAME_LAST , callTree ) ; } removeCallTree ( ) ; }
When stopwatch corresponding to root tree node is stopped this method is called . Logs call tree when split is longer than threshold .
4,870
static void init ( ) { Callback temporaryDebugCallback = new SystemDebugCallback ( ) ; manager . callback ( ) . addCallback ( temporaryDebugCallback ) ; try { manager . configuration ( ) . clear ( ) ; String fileName = System . getProperty ( PROPERTY_CONFIG_FILE_NAME ) ; if ( fileName != null ) { try ( FileReader fileReader = new FileReader ( fileName ) ) { manager . configuration ( ) . readConfig ( fileReader ) ; } } String resourceName = System . getProperty ( PROPERTY_CONFIG_RESOURCE_NAME ) ; if ( resourceName != null ) { InputStream is = SimonManager . class . getClassLoader ( ) . getResourceAsStream ( resourceName ) ; if ( is == null ) { throw new FileNotFoundException ( resourceName ) ; } manager . configuration ( ) . readConfig ( new InputStreamReader ( is ) ) ; } } catch ( Exception e ) { manager . callback ( ) . onManagerWarning ( "SimonManager initialization error" , e ) ; } manager . callback ( ) . removeCallback ( temporaryDebugCallback ) ; }
Initializes the configuration facility for the default Simon Manager . Fetches exception if configuration resource or file is not found . This method does NOT clear the manager itself only the configuration is reloaded . Method also preserves Callback setup .
4,871
void stop ( final Split split , final long start , final long nowNanos , final String subSimon ) { StopwatchSample sample = null ; synchronized ( this ) { active -- ; updateUsagesNanos ( nowNanos ) ; if ( subSimon == null ) { long splitNs = nowNanos - start ; addSplit ( splitNs ) ; if ( ! manager . callback ( ) . callbacks ( ) . isEmpty ( ) ) { sample = sample ( ) ; } updateIncrementalSimons ( splitNs , nowNanos ) ; } } if ( subSimon != null ) { Stopwatch effectiveStopwatch = manager . getStopwatch ( getName ( ) + Manager . HIERARCHY_DELIMITER + subSimon ) ; split . setAttribute ( Split . ATTR_EFFECTIVE_STOPWATCH , effectiveStopwatch ) ; effectiveStopwatch . addSplit ( split ) ; return ; } manager . callback ( ) . onStopwatchStop ( split , sample ) ; }
Protected method doing the stop work based on provided start nano - time .
4,872
protected final Stringifier registerNullStringifier ( final String nullValue ) { Stringifier nullStringifier = new Stringifier ( ) { public String toString ( Object object ) { return nullValue ; } } ; compositeStringifier . setNullStringifier ( nullStringifier ) ; return nullStringifier ; }
Register a stringifier for null values .
4,873
protected Stringifier < String > registerStringStringifier ( Stringifier nullStringifier ) { Stringifier < String > stringStringifier = new BaseStringifier < String > ( nullStringifier ) { protected String doToString ( String s ) { return s ; } } ; compositeStringifier . add ( String . class , stringStringifier ) ; return stringStringifier ; }
Register a stringifier for String values . Method aimed at being overridden .
4,874
protected final Stringifier < Long > registerLongStringifier ( String name , Stringifier < Long > longStringifier ) { compositeStringifier . add ( Long . class , name , longStringifier ) ; compositeStringifier . add ( Long . TYPE , name , longStringifier ) ; return longStringifier ; }
Register a stringifier for Long and long values .
4,875
protected final Stringifier < Double > registerDoubleStringifier ( String name , Stringifier < Double > doubleStringifier ) { compositeStringifier . add ( Double . class , name , doubleStringifier ) ; compositeStringifier . add ( Double . TYPE , name , doubleStringifier ) ; return doubleStringifier ; }
Register a stringifier for Double and double values .
4,876
public < T > Stringifier < T > getStringifier ( Class < ? extends T > type ) { return compositeStringifier . getForType ( type ) ; }
Get the stringifier for given type .
4,877
public < T > Stringifier < T > getStringifier ( Class < ? extends T > type , String subType ) { return compositeStringifier . getForType ( type , subType ) ; }
Get the stringifier for given type and sub type .
4,878
public < T extends SimonConsolePlugin > List < T > getPluginsByType ( Class < T > pluginType ) { List < T > specPlugins = new ArrayList < > ( ) ; for ( SimonConsolePlugin plugin : plugins ) { if ( pluginType . isInstance ( plugin ) ) { specPlugins . add ( pluginType . cast ( plugin ) ) ; } } return Collections . unmodifiableList ( specPlugins ) ; }
Return plugin list filtered by plugin type .
4,879
public List < ActionBinding > getActionBindings ( ) { List < ActionBinding > actionBindings = new ArrayList < > ( ) ; for ( SimonConsolePlugin plugin : plugins ) { actionBindings . addAll ( plugin . getActionBindings ( ) ) ; } return Collections . unmodifiableList ( actionBindings ) ; }
Get all action bindings of all plugins .
4,880
protected final TR getOrCreateTimeRange ( long timestamp ) { TR timeRange ; if ( lastTimeRange == null || timestamp > lastTimeRange . getEndTimestamp ( ) ) { long roundedTimestamp = timestamp - timestamp % timeRangeWidth ; timeRange = createTimeRange ( roundedTimestamp , roundedTimestamp + timeRangeWidth ) ; timeRanges . add ( timeRange ) ; lastTimeRange = timeRange ; } else if ( timestamp >= lastTimeRange . getStartTimestamp ( ) ) { timeRange = lastTimeRange ; } else { timeRange = null ; for ( TR oldTimeRange : timeRanges ) { if ( oldTimeRange . containsTimestamp ( timestamp ) ) { timeRange = oldTimeRange ; break ; } } } return timeRange ; }
Returns existing time range if it already exists or create a new one .
4,881
public static String barChart ( String title , SimonUnit unit , boolean showMaxMin , StopwatchSample ... samples ) { return new GoogleChartImageGenerator ( samples , title , unit , showMaxMin ) . process ( ) ; }
Generates Google bar chart URL for the provided samples .
4,882
private int checkAndGetTotalCount ( ) throws IllegalStateException { int usedBuckets = 0 ; int totalCount = buckets [ 0 ] . getCount ( ) ; for ( int i = 1 ; i <= bucketNb ; i ++ ) { int bucketCount = buckets [ i ] . getCount ( ) ; totalCount += bucketCount ; if ( bucketCount > 0 ) { usedBuckets ++ ; } } totalCount += buckets [ bucketNb + 1 ] . getCount ( ) ; if ( usedBuckets < 3 ) { throw new IllegalStateException ( "Only " + usedBuckets + " buckets used, not enough for interpolation, consider reconfiguring min/max/nb" ) ; } return totalCount ; }
Computes expected count and check used buckets number .
4,883
private double computeQuantile ( double ration , int totalCount ) throws IllegalStateException , IllegalArgumentException { if ( ration <= 0.0D || ration >= 1.0D ) { throw new IllegalArgumentException ( "Expected ratio between 0 and 1 excluded: " + ration ) ; } final double expectedCount = ration * totalCount ; double lastCount = 0D , newCount ; int bucketIndex = 0 ; for ( int i = 0 ; i < buckets . length ; i ++ ) { newCount = lastCount + buckets [ i ] . getCount ( ) ; if ( expectedCount >= lastCount && expectedCount < newCount ) { bucketIndex = i ; break ; } lastCount = newCount ; } if ( bucketIndex == 0 ) { throw new IllegalStateException ( "Quantile out of bounds: decrease min" ) ; } else if ( bucketIndex == bucketNb + 1 ) { throw new IllegalStateException ( "Quantile out of bounds: increase max" ) ; } final Bucket bucket = buckets [ bucketIndex ] ; return estimateQuantile ( bucket , expectedCount , lastCount ) ; }
Computes given quantile .
4,884
public void addValues ( Collection < Long > values ) { synchronized ( buckets ) { for ( Long value : values ) { addValue ( value ) ; } } }
For each value search the appropriate bucket and add the value in it .
4,885
@ SuppressWarnings ( "EmptyCatchBlock" ) public Double [ ] getQuantiles ( double ... ratios ) { synchronized ( buckets ) { final Double [ ] quantiles = new Double [ ratios . length ] ; try { final int totalCount = checkAndGetTotalCount ( ) ; for ( int i = 0 ; i < ratios . length ; i ++ ) { try { quantiles [ i ] = computeQuantile ( ratios [ i ] , totalCount ) ; } catch ( IllegalStateException e ) { } } } catch ( IllegalStateException e ) { } return quantiles ; } }
Computes many quantiles .
4,886
public BucketsSample sample ( ) { synchronized ( buckets ) { BucketSample [ ] bucketSamples = new BucketSample [ buckets . length ] ; for ( int i = 0 ; i < buckets . length ; i ++ ) { bucketSamples [ i ] = buckets [ i ] . sample ( ) ; } Double [ ] quantiles = getQuantiles ( 0.50D , 0.90D ) ; return new BucketsSample ( bucketSamples , quantiles [ 0 ] , quantiles [ 1 ] ) ; } }
Sample buckets and quantiles state .
4,887
public String process ( final String in ) { String retVal = in ; String old ; do { old = retVal ; retVal = from . matcher ( retVal ) . replaceAll ( to ) ; } while ( repeatUntilUnchanged && ! old . equals ( retVal ) ) ; return retVal ; }
Processes input replaces all as expected and returns the result .
4,888
private static < T > CachedStopwatchSource < T , Method > newCacheStopwatchSource ( final AbstractMethodStopwatchSource < T > stopwatchSource ) { return new CachedStopwatchSource < T , Method > ( stopwatchSource ) { protected Method getLocationKey ( T location ) { return stopwatchSource . getTargetMethod ( location ) ; } } ; }
Wraps given stopwatch source in a cache .
4,889
public Object monitor ( InvocationContext context ) throws Exception { if ( isMonitored ( context ) ) { String simonName = getSimonName ( context ) ; try ( Split ignored = SimonManager . getStopwatch ( simonName ) . start ( ) ) { return context . proceed ( ) ; } } else { return context . proceed ( ) ; } }
Around invoke method that measures the split for one method invocation .
4,890
public final boolean log ( C context , LogMessageSource < C > messageSource ) { final boolean enabled = isEnabled ( context ) ; if ( enabled ) { log ( messageSource . getLogMessage ( context ) ) ; } return enabled ; }
If enabled logs the message for context .
4,891
public TimelineSample < StopwatchTimeRange > sample ( ) { StopwatchTimeRange [ ] timeRangesCopy ; synchronized ( this ) { timeRangesCopy = timeRanges . toArray ( new StopwatchTimeRange [ timeRanges . size ( ) ] ) ; } return new TimelineSample < > ( timeRanges . getCapacity ( ) , timeRangeWidth * SimonClock . NANOS_IN_MILLIS , timeRangesCopy ) ; }
Take a snapshot of the timeline .
4,892
public void randomWait ( long min , long max ) { final long waitTime = randomLong ( min , max ) ; try { Thread . sleep ( waitTime ) ; } catch ( InterruptedException interruptedException ) { } }
Wait random time .
4,893
public void addDefaultSimons ( ) { addTime ( "A" , 100 ) ; addTime ( "B" , 200 ) ; addTime ( "C" , 300 ) ; addTime ( "A" , 200 ) ; addTime ( "A" , 300 ) ; addTime ( "B" , 100 ) ; addCounter ( "X" , 1L ) ; addCounter ( "X" , 4L ) ; addCounter ( "X" , 2L ) ; addStopwatchSplits ( SimonManager . getStopwatch ( "$Proxy" ) , 5 ) ; }
Add basic simons A B C and X . X is used to test Counter rendering .
4,894
public void addChangingSimons ( ) { timer . schedule ( new TimerTask ( ) { final Stopwatch tlStopwatch = SimonManager . getStopwatch ( "TL" ) ; public void run ( ) { try { lock . lock ( ) ; System . out . println ( "TL " + addStopwatchSplit ( tlStopwatch ) ) ; } finally { lock . unlock ( ) ; } } } , 0 , 10000L ) ; }
Starts a timer which changes Simons values . TL is used to test Timeline and Quantiles plugins rendering .
4,895
private void addManySimons ( String prefix , int depth , int groupWidth , int leafWidth , int splitWidth ) { if ( depth == 0 ) { final int sibblings = randomInt ( Math . min ( 1 , groupWidth / 2 ) , leafWidth ) ; for ( int i = 0 ; i < sibblings ; i ++ ) { String name = prefix + "." + ALPHABET . charAt ( i ) ; addStopwatchSplits ( SimonManager . getStopwatch ( name ) , splitWidth ) ; } } else { final int sibblings = randomInt ( Math . min ( 1 , groupWidth / 2 ) , groupWidth ) ; for ( int i = 0 ; i < sibblings ; i ++ ) { String name = prefix + "." + ALPHABET . charAt ( i ) ; addManySimons ( name , depth - 1 , groupWidth , leafWidth , splitWidth ) ; } } }
Recursively Add many Simons for performances testing .
4,896
private long addStopwatchSplit ( Stopwatch stopwatch ) { Split split = stopwatch . start ( ) ; try { randomWait ( 50 , 150 ) ; } finally { split . stop ( ) ; } return split . runningFor ( ) / SimonClock . NANOS_IN_MILLIS ; }
Generate a split for a Stopwatch .
4,897
private void addStopwatchSplits ( Stopwatch stopwatch , int splitWidth ) { final int splits = randomInt ( splitWidth / 2 , splitWidth ) ; try { lock . lock ( ) ; System . out . print ( stopwatch . getName ( ) + " " + splits + ": " ) ; for ( int i = 0 ; i < splits ; i ++ ) { System . out . print ( addStopwatchSplit ( stopwatch ) + "," ) ; } System . out . println ( ) ; } finally { lock . unlock ( ) ; } }
Generate a Simon of type Stopwatch and fill it with some Splits .
4,898
public void addStackedSimons ( ) { Split splitA = SimonManager . getStopwatch ( "Y.A" ) . start ( ) ; Split splitB = SimonManager . getStopwatch ( "Y.B" ) . start ( ) ; addStopwatchSplits ( SimonManager . getStopwatch ( "Y.C" ) , 6 ) ; splitB . stop ( ) ; Split splitD = SimonManager . getStopwatch ( "Y.D" ) . start ( ) ; randomWait ( 100 , 250 ) ; randomWait ( 100 , 250 ) ; splitD . stop ( ) ; splitA . stop ( ) ; }
Stacked stopwatches to test call tree .
4,899
public DetailHtmlBuilder executeHtml ( ActionContext context , DetailHtmlBuilder htmlBuilder , StringifierFactory htmlStringifierFactory , Simon simon ) throws IOException { return htmlBuilder ; }
Callback for flat HTML rendering .