idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
4,900
|
protected final ActionBinding findActionBinding ( ActionContext actionContext ) { for ( ActionBinding actionBinding : this . actionBindings ) { if ( actionBinding . supports ( actionContext ) ) { return actionBinding ; } } return null ; }
|
Find an acttion binding for the given action context
|
4,901
|
protected void processContext ( ActionContext actionContext ) throws ServletException , IOException { Action action = null ; try { ActionBinding actionBinding = findActionBinding ( actionContext ) ; if ( actionBinding != null ) { action = actionBinding . create ( actionContext ) ; } if ( action == null ) { throw new ActionException ( "No action bound to path " + actionContext . getPath ( ) ) ; } action . readParameters ( ) ; action . execute ( ) ; } catch ( ActionException actionException ) { try { ErrorAction errorAction = new ErrorAction ( actionContext ) ; errorAction . setError ( actionException ) ; errorAction . execute ( ) ; } catch ( ActionException actionException1 ) { throw new ServletException ( actionException ) ; } } }
|
Process an HTTP request .
|
4,902
|
private void runAndWait ( ) throws Exception { server . start ( ) ; Logger logger = LoggerFactory . getLogger ( SimonJolokiaDemo . class ) ; logger . info ( "Jolokia Agent started http://localhost:8778/jolokia/" ) ; logger . info ( "Search http://localhost:8778/jolokia/search/org.javasimon:*" ) ; logger . info ( "Manager http://localhost:8778/jolokia/read/org.javasimon:type=Manager" ) ; logger . info ( "Stopwatch http://localhost:8778/jolokia/read/org.javasimon:name=A,type=Stopwatch" ) ; logger . info ( "Counter http://localhost:8778/jolokia/read/org.javasimon:name=X,type=Counter" ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; String line ; boolean stop = false ; while ( ! stop && ( line = reader . readLine ( ) ) != null ) { stop = line . toLowerCase ( ) . contains ( "stop" ) ; } }
|
Run Jetty and wait till it stops .
|
4,903
|
public String getParameterAsString ( String name , String defaultValue ) { return defaultValue ( blankToNull ( getParameter ( name ) ) , defaultValue ) ; }
|
Get request parameter as a String .
|
4,904
|
private static Boolean stringToBoolean ( String value ) { final String s = blankToNull ( value ) ; return s == null ? null : Boolean . valueOf ( s ) ; }
|
Transform a string into an boolean .
|
4,905
|
public boolean getParameterAsBoolean ( String name , Boolean defaultValue ) { return defaultValue ( stringToBoolean ( getParameter ( name ) ) , defaultValue ) ; }
|
Get request parameter as a Boolean .
|
4,906
|
private static < T extends Enum < T > > T stringToEnum ( String value , Class < T > type ) { final String s = blankToNull ( value ) ; return value == null ? null : Enum . valueOf ( type , s . toUpperCase ( ) ) ; }
|
Transform a string into an enum ( using its name which is supposed to be uppercase handles null values .
|
4,907
|
public < T extends Enum < T > > T getParameterAsEnum ( String name , Class < T > type , T defaultValue ) { return defaultValue ( stringToEnum ( getParameter ( name ) , type ) , defaultValue ) ; }
|
Get request parameter as a Enum .
|
4,908
|
public < T extends Enum < T > > EnumSet < T > getParametersAsEnums ( String name , Class < T > type , EnumSet < T > defaultValue ) { String [ ] enumNames = getParameters ( name ) ; if ( enumNames == null ) { return defaultValue ; } else { Collection < T > enums = new ArrayList < > ( ) ; for ( String enumName : enumNames ) { T enumValue = stringToEnum ( blankToNull ( enumName ) , type ) ; if ( enumValue != null ) { enums . add ( enumValue ) ; } } return enums . isEmpty ( ) ? defaultValue : EnumSet . copyOf ( enums ) ; } }
|
Get multiple request parameters as Enums .
|
4,909
|
@ SuppressWarnings ( "UnusedParameters" ) protected LogTemplate < Split > createLogTemplate ( Stopwatch stopwatch ) { LogTemplate < Split > logTemplate ; if ( logEnabled ) { logTemplate = everyNSeconds ( enabledStopwatchLogTemplate , 60 ) ; } else { logTemplate = disabled ( ) ; } return logTemplate ; }
|
Create log template for given stopwatch . This method can be overridden to tune logging strategy . By default when enabled quantiles are logged at most once per minute
|
4,910
|
protected final Buckets createBuckets ( Stopwatch stopwatch , long min , long max , int bucketNb ) { Buckets buckets = bucketsType . createBuckets ( stopwatch , min , max , bucketNb ) ; buckets . setLogTemplate ( createLogTemplate ( stopwatch ) ) ; return buckets ; }
|
Factory method to create a Buckets object using given configuration .
|
4,911
|
@ SuppressWarnings ( "SynchronizationOnLocalVariableOrMethodParameter" ) protected final Buckets getOrCreateBuckets ( Stopwatch stopwatch ) { synchronized ( stopwatch ) { Buckets buckets = getBuckets ( stopwatch ) ; if ( buckets == null ) { buckets = createBuckets ( stopwatch ) ; stopwatch . setAttribute ( ATTR_NAME_BUCKETS , buckets ) ; } return buckets ; } }
|
Returns the buckets attribute or create it if it does not exist .
|
4,912
|
public static BucketsSample sampleBuckets ( Stopwatch stopwatch ) { final Buckets buckets = getBuckets ( stopwatch ) ; return buckets == null ? null : buckets . sample ( ) ; }
|
Returns the buckets attribute and sample them .
|
4,913
|
public void onStopwatchStop ( Split split , StopwatchSample sample ) { onStopwatchSplit ( split . getStopwatch ( ) , split ) ; }
|
When a split is stopped if buckets have been initialized the value is added to appropriate bucket .
|
4,914
|
public void onStopwatchAdd ( Stopwatch stopwatch , Split split , StopwatchSample sample ) { onStopwatchSplit ( split . getStopwatch ( ) , split ) ; }
|
When a split is added if buckets have been initialized the value is added to appropriate bucket .
|
4,915
|
private MonitorInformation getMonitorInformation ( L location ) { final K monitorKey = getLocationKey ( location ) ; MonitorInformation monitorInformation = monitorInformations . get ( monitorKey ) ; if ( monitorInformation == null ) { if ( delegate . isMonitored ( location ) ) { monitorInformation = new MonitorInformation ( true , delegate . getMonitor ( location ) ) ; } else { monitorInformation = NULL_MONITOR_INFORMATION ; } monitorInformations . put ( monitorKey , monitorInformation ) ; } return monitorInformation ; }
|
Get monitor information for given location . First monitor information is looked up in cache . Then when not found delegate is called .
|
4,916
|
public M getMonitor ( L location ) { M monitor = getMonitorOnce ( location ) ; if ( monitor == null ) { removeMonitorInformation ( location ) ; monitor = getMonitorOnce ( location ) ; } return monitor ; }
|
Get Simon for the specified location . Simon is retrieved from name in cache .
|
4,917
|
public void onStopwatchStop ( Split split , StopwatchSample sample ) { logger . debug ( marker , "SIMON STOP: {} ({})" , sample . toString ( ) , split . runningFor ( ) ) ; }
|
Logs Simon stop on a specified log marker .
|
4,918
|
public void onManagerWarning ( String warning , Exception cause ) { logger . debug ( marker , "SIMON WARNING: {}" , warning , cause ) ; }
|
Logs the warning on a specified log marker .
|
4,919
|
public Object newProxy ( ClassLoader classLoader , Class < ? > ... interfaces ) { return Proxy . newProxyInstance ( classLoader , interfaces , this ) ; }
|
Create a proxy using given classloader and interfaces
|
4,920
|
public < X > X newProxy ( Class < X > interfaces ) { return ( X ) newProxy ( new Class [ ] { interfaces } ) ; }
|
Create a proxy using given classloader and interfaces .
|
4,921
|
public static < C > LogTemplate < C > everyNSplits ( LogTemplate < C > delegateLogger , int period ) { return new CounterLogTemplate < > ( delegateLogger , period ) ; }
|
Produces a log template which logs something every N split .
|
4,922
|
public static < C > LogTemplate < C > everyNSeconds ( LogTemplate < C > delegateLogger , long period ) { return everyNMilliseconds ( delegateLogger , period * SimonClock . MILLIS_IN_SECOND ) ; }
|
Produces a log template which logs something at most every N secoonds .
|
4,923
|
public static < C > JULLogTemplate < C > toJUL ( String loggerName , Level level ) { return new JULLogTemplate < > ( loggerName , level ) ; }
|
Produces a concrete log template which logs messages into a Java Util Logging Logger .
|
4,924
|
public static SplitThresholdLogTemplate whenSplitLongerThanMilliseconds ( LogTemplate < Split > delegateLogger , long threshold ) { return whenSplitLongerThanNanoseconds ( delegateLogger , threshold * SimonClock . NANOS_IN_MILLIS ) ; }
|
Produces a log template which logs something when stopwatch split is longer than threshold .
|
4,925
|
public static void waitRandomlySquared ( long maxMsRoot ) { long random = ( long ) ( Math . random ( ) * maxMsRoot ) ; try { Thread . sleep ( random * random ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } }
|
Method that lasts randomly from ~0 to the square of the specified amount of maxMsRoot . This is just to avoid linear randomness .
|
4,926
|
public static < T > Stringifier < T > checkInstance ( Stringifier < T > stringifier ) { return INSTANCE == stringifier ? null : stringifier ; }
|
Check whether stringifier is the NoneStringifier
|
4,927
|
@ SuppressWarnings ( "unchecked" ) public static < L , M extends Simon > DisabledMonitorSource < L , M > get ( ) { return ( DisabledMonitorSource < L , M > ) INSTANCE ; }
|
Returns a singleton instance .
|
4,928
|
public synchronized void initialize ( Manager manager ) { if ( this . manager != null ) { throw new IllegalStateException ( "Callback was already initialized" ) ; } this . manager = manager ; for ( Callback callback : callbacks ) { try { callback . initialize ( manager ) ; } catch ( Exception e ) { onManagerWarning ( "Callback initialization error" , e ) ; } } }
|
Calls initialize on all children .
|
4,929
|
public void addCallback ( Callback callback ) { if ( manager != null ) { callback . initialize ( manager ) ; } callbacks . add ( callback ) ; }
|
Adds another callback as a child to this callback .
|
4,930
|
public void removeCallback ( Callback callback ) { callbacks . remove ( callback ) ; if ( manager != null ) { callback . cleanup ( ) ; } }
|
Removes specified callback from this callback properly cleans up the removed callback .
|
4,931
|
public void cleanup ( ) { manager = null ; for ( Callback callback : callbacks ) { try { callback . cleanup ( ) ; } catch ( Exception e ) { onManagerWarning ( "Callback cleanup error" , e ) ; } } }
|
Calls deactivate on all children .
|
4,932
|
protected String getMonitorName ( InvocationContext context ) { String className = context . getMethod ( ) . getDeclaringClass ( ) . getSimpleName ( ) ; String methodName = context . getMethod ( ) . getName ( ) ; return prefix + Manager . HIERARCHY_DELIMITER + className + Manager . HIERARCHY_DELIMITER + methodName ; }
|
Returns Simon name for the specified Invocation context . By default it contains the prefix + method name . This method can be overridden .
|
4,933
|
public T get ( Object source ) { try { if ( ! method . isAccessible ( ) ) { method . setAccessible ( true ) ; } @ SuppressWarnings ( "unchecked" ) T value = ( T ) method . invoke ( source ) ; return value ; } catch ( IllegalAccessException illegalAccessException ) { return null ; } catch ( IllegalArgumentException illegalArgumentException ) { return null ; } catch ( InvocationTargetException invocationTargetException ) { return null ; } }
|
Get value from source object using getter method
|
4,934
|
public static String localName ( String name ) { int ix = name . lastIndexOf ( Manager . HIERARCHY_DELIMITER ) ; if ( ix == - 1 ) { return name ; } return name . substring ( ix + 1 ) ; }
|
Returns last part of Simon name - local name .
|
4,935
|
private static String generatePrivate ( String suffix , boolean includeMethodName ) { StackTraceElement stackElement = Thread . currentThread ( ) . getStackTrace ( ) [ CLIENT_CODE_STACK_INDEX ] ; StringBuilder nameBuilder = new StringBuilder ( stackElement . getClassName ( ) ) ; if ( includeMethodName ) { nameBuilder . append ( '.' ) . append ( stackElement . getMethodName ( ) ) ; } if ( suffix != null ) { nameBuilder . append ( suffix ) ; } return nameBuilder . toString ( ) ; }
|
method is extracted so the stack trace index is always right
|
4,936
|
public static < T > T doWithStopwatch ( String name , Callable < T > callable ) throws Exception { try ( Split split = SimonManager . getStopwatch ( name ) . start ( ) ) { return callable . call ( ) ; } }
|
Calls a block of code with stopwatch around and returns result .
|
4,937
|
public static String compact ( String input , int limitTo ) { if ( input == null || input . length ( ) <= limitTo ) { return input ; } int headLength = limitTo / 2 ; int tailLength = limitTo - SHRINKED_STRING . length ( ) - headLength ; if ( tailLength < 0 ) { tailLength = 1 ; } return input . substring ( 0 , headLength ) + SHRINKED_STRING + input . substring ( input . length ( ) - tailLength ) ; }
|
Shrinks the middle of the input string if it is too long so it does not exceed limitTo .
|
4,938
|
public static StopwatchAggregate calculateStopwatchAggregate ( Simon simon , SimonFilter filter ) { StopwatchAggregate stopwatchAggregate = new StopwatchAggregate ( ) ; aggregateStopwatches ( stopwatchAggregate , simon , filter != null ? filter : SimonFilter . ACCEPT_ALL_FILTER ) ; return stopwatchAggregate ; }
|
Aggregate statistics from all stopwatches in hierarchy that pass specified filter . Filter is applied to all simons in the hierarchy of all types . If a simon is rejected by filter its children are not considered . Simons are aggregated in the top - bottom fashion i . e . parent simons are aggregated before children .
|
4,939
|
public static CounterAggregate calculateCounterAggregate ( Simon simon , SimonFilter filter ) { CounterAggregate aggregate = new CounterAggregate ( ) ; aggregateCounters ( aggregate , simon , filter != null ? filter : SimonFilter . ACCEPT_ALL_FILTER ) ; return aggregate ; }
|
Aggregate statistics from all counters in hierarchy that pass specified filter . Filter is applied to all simons in the hierarchy of all types . If a simon is rejected by filter its children are not considered . Simons are aggregated in the top - bottom fashion i . e . parent simons are aggregated before children .
|
4,940
|
final void addChild ( AbstractSimon simon ) { children . add ( simon ) ; simon . setParent ( this ) ; simon . enabled = enabled ; }
|
Adds child to this Simon with setting the parent of the child .
|
4,941
|
public void setAttribute ( String name , Object value ) { attributesSupport . setAttribute ( name , value ) ; }
|
Stores an attribute in this Simon . Attributes can be used to store any custom objects .
|
4,942
|
private void copyStream ( InputStream inputStream ) throws IOException { OutputStream outputStream = null ; try { outputStream = getContext ( ) . getOutputStream ( ) ; byte [ ] buffer = new byte [ 65535 ] ; int bufferLen ; int totalLen = 0 ; while ( ( bufferLen = inputStream . read ( buffer ) ) > 0 ) { outputStream . write ( buffer , 0 , bufferLen ) ; totalLen += bufferLen ; } getContext ( ) . getResponse ( ) . setContentLength ( totalLen ) ; } finally { if ( outputStream != null ) { outputStream . flush ( ) ; } } }
|
Copy resource input stream to HTTP response output stream using a 64kib buffer
|
4,943
|
public void setProperty ( Object target , String property , Object value ) { NestedResolver resolver = new NestedResolver ( target , property ) ; if ( value instanceof String ) { convertStringValue ( resolver . getNestedTarget ( ) , resolver . getProperty ( ) , ( String ) value ) ; } else { setObjectValue ( resolver . getNestedTarget ( ) , resolver . getProperty ( ) , value ) ; } }
|
Set property in object target . If values has type other than String setter method or field with specified type will be used to set value . If value has String type value will be converted using available converters . If conversion to all of the types accepted by setters fails field with corresponding name will be used
|
4,944
|
public Stopwatch getMonitor ( HttpServletRequest request ) { final Stopwatch stopwatch = super . getMonitor ( request ) ; if ( stopwatch . getNote ( ) == null ) { stopwatch . setNote ( request . getRequestURI ( ) ) ; } return stopwatch ; }
|
Get a stopwatch for given HTTP request .
|
4,945
|
public static StopwatchSource < HttpServletRequest > newCacheStopwatchSource ( StopwatchSource < HttpServletRequest > stopwatchSource ) { return new CachedStopwatchSource < HttpServletRequest , String > ( stopwatchSource ) { protected String getLocationKey ( HttpServletRequest location ) { return location . getRequestURI ( ) ; } } ; }
|
Wraps given stop watch source in a cache .
|
4,946
|
public static void main ( String [ ] args ) { Manager manager = new EnabledManager ( ) ; Stopwatch sw1 = manager . getStopwatch ( "org.javasimon.examples.stopwatch1" ) ; Stopwatch sw2 = manager . getStopwatch ( "other.stopwatch2" ) ; Callback stdoutCallback = new CallbackSkeleton ( ) { public void onStopwatchStart ( Split split ) { System . out . println ( "Starting " + split . getStopwatch ( ) . getName ( ) ) ; } public void onStopwatchStop ( Split split , StopwatchSample sample ) { System . out . println ( "Stopped " + split . getStopwatch ( ) . getName ( ) + " (" + SimonUtils . presentNanoTime ( split . runningFor ( ) ) + ")" ) ; } } ; manager . callback ( ) . addCallback ( stdoutCallback ) ; sw1 . start ( ) . stop ( ) ; sw2 . start ( ) . stop ( ) ; System . out . println ( ) ; manager . callback ( ) . removeCallback ( stdoutCallback ) ; SimonManager . callback ( ) . removeAllCallbacks ( ) ; CompositeFilterCallback filter = new CompositeFilterCallback ( ) ; filter . addRule ( FilterRule . Type . MUST_NOT , null , "other.*" ) ; filter . addCallback ( stdoutCallback ) ; manager . callback ( ) . addCallback ( filter ) ; sw1 . start ( ) . stop ( ) ; sw2 . start ( ) . stop ( ) ; }
|
Entry point to the Callback Filtering Example .
|
4,947
|
static Field getField ( Class < ? > targetClass , String fieldName ) { while ( targetClass != null ) { try { Field field = targetClass . getDeclaredField ( fieldName ) ; logger . debug ( "Found field {} in class {}" , fieldName , targetClass . getName ( ) ) ; return field ; } catch ( NoSuchFieldException e ) { logger . debug ( "Failed to find field {} in class {}" , fieldName , targetClass . getName ( ) ) ; } targetClass = targetClass . getSuperclass ( ) ; } return null ; }
|
Get field with the specified name .
|
4,948
|
static Set < Method > getSetters ( Class < ? > targetClass , String propertyName ) { String setterName = setterName ( propertyName ) ; Set < Method > setters = new HashSet < > ( ) ; while ( targetClass != null ) { for ( Method method : targetClass . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( setterName ) && method . getParameterTypes ( ) . length == 1 ) { logger . debug ( "Found setter {} in class {}" , method , targetClass ) ; setters . add ( method ) ; } } targetClass = targetClass . getSuperclass ( ) ; } return setters ; }
|
Get all setters for the specified property
|
4,949
|
static Class < ? > getSetterType ( Method setter ) { Class < ? > [ ] parameterTypes = setter . getParameterTypes ( ) ; if ( parameterTypes . length != 1 ) { throw new BeanUtilsException ( String . format ( "Method %s has %d parameters and cannot be a setter" , setter . getName ( ) , parameterTypes . length ) ) ; } return parameterTypes [ 0 ] ; }
|
Get property type by a setter method .
|
4,950
|
static Method getGetter ( Class < ? > targetClass , String propertyName ) { if ( targetClass == null ) { return null ; } final String getterName = getterName ( propertyName , false ) ; Method result = findPublicGetter ( targetClass , getterName , propertyName , false ) ; if ( result == null ) { final String booleanGetterName = getterName ( propertyName , true ) ; result = findPublicGetter ( targetClass , booleanGetterName , propertyName , true ) ; if ( result == null ) { do { result = findNonPublicGetter ( targetClass , getterName , propertyName , false ) ; if ( result == null ) { result = findNonPublicGetter ( targetClass , booleanGetterName , propertyName , true ) ; } } while ( result == null && ( targetClass = targetClass . getSuperclass ( ) ) != null ) ; } } return result ; }
|
Get getter method for a specified property .
|
4,951
|
protected Object invoke ( DelegatingMethodInvocation < T > methodInvocation ) throws Throwable { final Split split = stopwatchSource . start ( methodInvocation ) ; try { return methodInvocation . proceed ( ) ; } finally { split . stop ( ) ; } }
|
Invocation handler main method .
|
4,952
|
protected final Split startStopwatch ( HandlerLocation location ) { Split split = stopwatchSource . start ( location ) ; location . setSplit ( split ) ; return split ; }
|
Start stopwatch for given name and thread .
|
4,953
|
public boolean preHandle ( HttpServletRequest request , HttpServletResponse response , Object handler ) { final HandlerLocation location = new HandlerLocation ( request , handler , HandlerStep . CONTROLLER ) ; threadLocation . set ( location ) ; startStopwatch ( location ) ; return true ; }
|
Invoked before controller .
|
4,954
|
public void postHandle ( HttpServletRequest request , HttpServletResponse response , Object handler , ModelAndView modelAndView ) { stopStopwatch ( ) ; HandlerLocation location = threadLocation . get ( ) ; location . setStep ( HandlerStep . VIEW ) ; startStopwatch ( location ) ; }
|
Invoked between controller and view .
|
4,955
|
public void afterCompletion ( HttpServletRequest request , HttpServletResponse response , Object handler , Exception ex ) { stopStopwatch ( ) ; threadLocation . remove ( ) ; }
|
Invoked after view .
|
4,956
|
public final String getRealDataSourceClassName ( ) { if ( ( realDataSourceClassName == null || realDataSourceClassName . isEmpty ( ) ) && ( configuration != null ) ) { realDataSourceClassName = doGetRealDataSourceClassName ( ) ; } return realDataSourceClassName ; }
|
Returns real datasource class name .
|
4,957
|
protected final < T > T createDataSource ( Class < T > dataSourceClass ) throws SQLException { if ( getRealDataSourceClassName ( ) == null ) { throw new SQLException ( "Property realDataSourceClassName is not set" ) ; } try { T ds = dataSourceClass . cast ( Class . forName ( realDataSourceClassName ) . newInstance ( ) ) ; for ( Method m : ds . getClass ( ) . getMethods ( ) ) { String methodName = m . getName ( ) ; if ( methodName . startsWith ( "set" ) && m . getParameterTypes ( ) . length == 1 ) { final Object propertyValue ; if ( methodName . equals ( "setUser" ) ) { propertyValue = getUser ( ) ; } else if ( methodName . equals ( "setPassword" ) ) { propertyValue = getPassword ( ) ; } else if ( methodName . equalsIgnoreCase ( "setUrl" ) ) { propertyValue = getRealUrl ( ) ; } else if ( methodName . equals ( "setLogWriter" ) ) { propertyValue = getLogWriter ( ) ; } else if ( methodName . equals ( "setLoginTimeout" ) ) { propertyValue = getLoginTimeout ( ) ; } else { String propertyName = methodName . substring ( 3 , 4 ) . toLowerCase ( ) ; if ( methodName . length ( ) > 4 ) { propertyName += methodName . substring ( 4 ) ; } final Class < ? > propertyType = m . getParameterTypes ( ) [ 0 ] ; propertyValue = getPropertyAs ( propertyName , propertyType ) ; } if ( propertyValue != null ) { m . invoke ( ds , propertyValue ) ; } } } return ds ; } catch ( Exception e ) { throw new SQLException ( e ) ; } }
|
Instantiates the DataSource .
|
4,958
|
public final String getPrefix ( ) { if ( ( prefix == null || prefix . isEmpty ( ) ) && ( configuration != null ) ) { prefix = configuration . getPrefix ( ) ; } return prefix ; }
|
Returns Simon prefix for constructing names of Simons .
|
4,959
|
public boolean next ( ) throws SQLException { try ( Split ignored = SimonManager . getStopwatch ( stmtPrefix + ".next" ) . start ( ) ) { return rset . next ( ) ; } }
|
Measure next operation .
|
4,960
|
public final Object invoke ( MethodInvocation invocation ) throws Throwable { final Split split = stopwatchSource . start ( invocation ) ; try { return processInvoke ( invocation , split ) ; } finally { split . stop ( ) ; } }
|
Performs method invocation and wraps it with Stopwatch .
|
4,961
|
protected Buckets createBuckets ( Stopwatch stopwatch ) { BucketsType type = bucketsTypeEnumPropertyType . get ( stopwatch , "type" ) ; Long min = longPropertyType . get ( stopwatch , "min" ) ; Long max = longPropertyType . get ( stopwatch , "max" ) ; Integer nb = integerPropertyType . get ( stopwatch , "nb" ) ; Buckets buckets = type . createBuckets ( stopwatch , min , max , nb ) ; buckets . setLogTemplate ( createLogTemplate ( stopwatch ) ) ; return buckets ; }
|
Create buckets using callback attributes .
|
4,962
|
private String getProperty ( Simon simon , String name ) { return properties . getProperty ( simon . getName ( ) + "." + name ) ; }
|
Returns value of Simon property .
|
4,963
|
private static String cleanString ( String s ) { if ( s != null ) { s = s . trim ( ) ; if ( s . equals ( "" ) ) { s = null ; } } return s ; }
|
Remove space at both ends and convert empty strings to null .
|
4,964
|
public static < T extends Callback > T getCallbackByType ( Manager manager , Class < T > callbackType ) { return getCallbackByType ( manager . callback ( ) . callbacks ( ) , callbackType ) ; }
|
Get the first callback of given type in manager
|
4,965
|
private static < T extends Callback > T getCallbackByType ( Iterable < Callback > callbacks , Class < T > callbackType ) { T foundCallback = null ; Iterator < Callback > callbackIterator = callbacks . iterator ( ) ; while ( foundCallback == null && callbackIterator . hasNext ( ) ) { Callback callback = callbackIterator . next ( ) ; while ( ( callback instanceof Delegating ) && ( ! callbackType . isInstance ( callback ) ) ) { callback = ( ( Delegating < Callback > ) callback ) . getDelegate ( ) ; } if ( callbackType . isInstance ( callback ) ) { foundCallback = callbackType . cast ( callback ) ; } else if ( callback instanceof CompositeCallback ) { foundCallback = getCallbackByType ( ( ( CompositeCallback ) callback ) . callbacks ( ) , callbackType ) ; } } return foundCallback ; }
|
Search callback by type in list of callbacks
|
4,966
|
public WriteBuffer set ( final int index ) { if ( useMmap ) { final ByteBuffer buf = getMmapForIndex ( index ) ; if ( buf != null ) { return new WriteBuffer ( this , index , useMmap , buf ) ; } } return new WriteBuffer ( this , index , false , bufstack . pop ( ) ) ; }
|
Alloc a WriteBuffer
|
4,967
|
@ SuppressWarnings ( "unchecked" ) public void clear ( final boolean shrink ) { clearCache ( ) ; if ( elementCount > 0 ) { elementCount = 0 ; } if ( shrink && ( elementData . length > 1024 ) && ( elementData . length > defaultSize ) ) { elementData = new IntEntry [ defaultSize ] ; } else { Arrays . fill ( elementData , null ) ; } computeMaxSize ( ) ; }
|
Clear the map
|
4,968
|
public V get ( final int key ) { final int index = ( key & 0x7FFFFFFF ) % elementData . length ; IntEntry < V > m = elementData [ index ] ; while ( m != null ) { if ( key == m . key ) { return m . value ; } m = m . nextInSlot ; } return null ; }
|
Returns the value of specified key .
|
4,969
|
public V [ ] getValues ( ) { final V [ ] array = factory . newArray ( elementCount ) ; int i = 0 ; for ( final V v : this ) { array [ i ++ ] = v ; } return array ; }
|
Return an array with values in this map
|
4,970
|
protected void registerDefaults ( ) { register ( Long . class , new LongConverter ( ) ) ; register ( Integer . class , new IntegerConverter ( ) ) ; register ( Short . class , new ShortConverter ( ) ) ; register ( Byte . class , new ByteConverter ( ) ) ; register ( Double . class , new DoubleConverter ( ) ) ; register ( Float . class , new FloatConverter ( ) ) ; register ( Character . class , new CharacterConverter ( ) ) ; register ( Boolean . class , new BooleanConverter ( ) ) ; register ( String . class , new StringConverter ( ) ) ; register ( URL . class , new UrlConverter ( ) ) ; register ( URI . class , new UriConverter ( ) ) ; register ( Charset . class , new CharsetConverter ( ) ) ; register ( File . class , new FileConverter ( ) ) ; register ( Path . class , new PathConverter ( ) ) ; register ( Locale . class , new LocaleConverter ( ) ) ; register ( Pattern . class , new PatternConverter ( ) ) ; register ( Long . TYPE , new LongConverter ( ) ) ; register ( Integer . TYPE , new IntegerConverter ( ) ) ; register ( Short . TYPE , new ShortConverter ( ) ) ; register ( Byte . TYPE , new ByteConverter ( ) ) ; register ( Character . TYPE , new CharacterConverter ( ) ) ; register ( Double . TYPE , new DoubleConverter ( ) ) ; register ( Float . TYPE , new FloatConverter ( ) ) ; register ( Boolean . TYPE , new BooleanConverter ( ) ) ; }
|
Register converters supported by default .
|
4,971
|
public < T > void register ( Class < T > type , Converter < T > converter ) { addConverter ( type , converter ) ; }
|
Register converter .
|
4,972
|
protected < T > void addConverter ( Class < T > type , Converter < T > converter ) { storage . put ( type , converter ) ; }
|
Add converter to the storage .
|
4,973
|
protected < T > Converter < T > find ( Class < T > type ) throws ConversionException { Converter < T > converter = ( Converter < T > ) storage . get ( type ) ; if ( converter == null ) { if ( type . isEnum ( ) ) { return new EnumConverter ( ( Class < ? extends Enum > ) type ) ; } if ( type . isArray ( ) ) { Class < ? > componentType = type . getComponentType ( ) ; Converter childConverter = find ( componentType ) ; return new ArrayConverter ( childConverter , componentType , stringSplitter ) ; } throw new ConversionException ( String . format ( "Could not find converter for type <%s>" , type ) ) ; } return converter ; }
|
Find converter for given type . Returns null if converter doesn t exists .
|
4,974
|
public Object convert ( Class < ? > type , String origin ) throws ConversionException { if ( origin == null ) { return convertNullValue ( type ) ; } Converter converter = find ( type ) ; try { return converter . convert ( origin ) ; } catch ( Exception e ) { throw new ConversionException ( String . format ( "Could not convert string <%s> to type <%s>" , origin , type ) , e ) ; } }
|
Convert given string to type .
|
4,975
|
protected Object convertNullValue ( Class type ) throws ConversionException { try { return type . isPrimitive ( ) ? Array . get ( Array . newInstance ( type , 1 ) , 0 ) : null ; } catch ( Exception e ) { throw new ConversionException ( String . format ( "Could not convert null to primitive type <%s>" , type ) , e ) ; } }
|
Convert null to given type .
|
4,976
|
public < T > Object convert ( Class collectionType , Class < T > elementType , String origin ) throws ConversionException { Converter < T > elementConverter = find ( elementType ) ; CollectionConverter < T > converter = new CollectionConverter < > ( elementConverter , stringSplitter ) ; try { Collection < T > converted = converter . convert ( origin ) ; return castCollectionToType ( collectionType , converted ) ; } catch ( Exception e ) { throw new ConversionException ( String . format ( "Could not convert string <%s> to collection <%s> " + "with element type <%s>" , origin , collectionType , elementType ) , e ) ; } }
|
Convert given string to specified collection with given element type .
|
4,977
|
@ SuppressWarnings ( "unchecked" ) protected < T > Collection < T > castCollectionToType ( Class collectionType , Collection < T > converted ) throws ConversionException { if ( ! Collection . class . isAssignableFrom ( collectionType ) ) { throw new ConversionException ( "Collection type should extends collection" + collectionType ) ; } if ( collectionType . isInterface ( ) ) { if ( collectionType . isAssignableFrom ( Set . class ) ) { return Collections . unmodifiableSet ( new HashSet < > ( converted ) ) ; } if ( collectionType . isAssignableFrom ( List . class ) ) { return Collections . unmodifiableList ( new LinkedList < > ( converted ) ) ; } if ( collectionType . isAssignableFrom ( Collection . class ) ) { return Collections . unmodifiableCollection ( converted ) ; } throw new ConversionException ( "Unsupported collection type " + collectionType ) ; } try { Constructor constructor = collectionType . getConstructor ( Collection . class ) ; return ( Collection < T > ) constructor . newInstance ( converted ) ; } catch ( Exception e ) { throw new ConversionException ( "Could not create an instance of " + collectionType , e ) ; } }
|
Create an instance of specified collection with given element type .
|
4,978
|
public final int pop ( ) { if ( stackPointer == 0 ) { return null_value ; } final int element = stack [ -- stackPointer ] ; stack [ stackPointer ] = null_value ; return element ; }
|
Pop value from top of stack
|
4,979
|
public synchronized void read ( ) throws IOException { if ( ! validState ) { throw new InvalidStateException ( ) ; } final long offset = ( ( fc . size ( ) & ~ 7 ) - 8 ) ; if ( offset < 0 ) { throw new IOException ( "Empty file" ) ; } buf . clear ( ) ; int readed = fc . position ( offset ) . read ( buf ) ; if ( readed < 8 ) { throw new IOException ( "cant read long from file" ) ; } buf . flip ( ) ; value = buf . getLong ( ) ; }
|
Read value from file
|
4,980
|
public synchronized void write ( final boolean forceSync ) throws IOException { if ( ! validState ) { throw new InvalidStateException ( ) ; } buf . clear ( ) ; buf . putLong ( value ) ; buf . flip ( ) ; fc . position ( fc . size ( ) ) . write ( buf ) ; if ( forceSync ) { fc . force ( false ) ; } }
|
Write value to file
|
4,981
|
public synchronized void pack ( ) throws IOException { if ( ! validState ) { throw new InvalidStateException ( ) ; } buf . clear ( ) ; buf . putLong ( value ) ; buf . flip ( ) ; fc . position ( 0 ) . write ( buf ) ; fc . truncate ( 8 ) . force ( true ) ; }
|
Write value to file and reduce size to minimal
|
4,982
|
private void ensureCapacity ( int wordsRequired ) { if ( words . length < wordsRequired ) { int request = Math . max ( 2 * words . length , wordsRequired ) ; words = Arrays . copyOf ( words , request ) ; sizeIsSticky = false ; } }
|
Ensures that the BitSet can hold enough words .
|
4,983
|
private static void checkRange ( int fromIndex , int toIndex ) { if ( fromIndex < 0 ) throw new IndexOutOfBoundsException ( "fromIndex < 0: " + fromIndex ) ; if ( toIndex < 0 ) throw new IndexOutOfBoundsException ( "toIndex < 0: " + toIndex ) ; if ( fromIndex > toIndex ) throw new IndexOutOfBoundsException ( "fromIndex: " + fromIndex + " > toIndex: " + toIndex ) ; }
|
Checks that fromIndex ... toIndex is a valid range of bit indices .
|
4,984
|
private Node < K , V > getNodeFromStore ( final int nodeid ) { final int index = nodeid < 0 ? - nodeid : nodeid ; final ByteBuffer buf = storage . get ( index ) ; final Node < K , V > node = Node . deserialize ( buf , this ) ; if ( rootIdx == node . id ) { log . warn ( this . getClass ( ) . getName ( ) + "::getNodeFromStore(" + nodeid + ") WARN LOADED ROOT NODE" ) ; } storage . release ( buf ) ; if ( enableIOStats ) { getIOStat ( nodeid ) . incPhysRead ( ) ; } return node ; }
|
Get node from file
|
4,985
|
private void putNodeToStore ( final Node < K , V > node ) { final int nodeid = node . id ; final int index = ( nodeid < 0 ? - nodeid : nodeid ) ; final WriteBuffer wbuf = storage . set ( index ) ; final ByteBuffer buf = wbuf . buf ( ) ; if ( node . isDeleted ( ) ) { if ( cleanBlocksOnFree ) { buf . clear ( ) ; int cx = ( blockSize >> 3 ) ; while ( cx -- > 0 ) { buf . putLong ( 0 ) ; } buf . flip ( ) ; } else { node . clean ( buf ) ; } freeBlocks . set ( index ) ; } else { node . serialize ( buf ) ; } wbuf . save ( ) ; if ( enableDirtyCheck ) { dirtyCheck . clear ( index ) ; } if ( enableIOStats ) { getIOStat ( nodeid ) . incPhysWrite ( ) ; } }
|
Put a node in file
|
4,986
|
@ SuppressWarnings ( "rawtypes" ) private final int removeEldestElementsFromCache ( final IntLinkedHashMap < Node > hash , final int maxSize ) { final int evict = hash . size ( ) - maxSize ; if ( evict <= 0 ) { return 0 ; } for ( int count = 0 ; count < evict ; count ++ ) { hash . removeEldest ( ) ; } return evict ; }
|
Evict from Read Cache excess nodes
|
4,987
|
private boolean writeMetaData ( final boolean isClean ) { if ( readOnly ) { return true ; } final WriteBuffer wbuf = storage . set ( 0 ) ; final ByteBuffer buf = wbuf . buf ( ) ; boolean isOK = false ; buf . putInt ( MAGIC_1 ) . putInt ( blockSize ) . putInt ( b_order_leaf ) . putInt ( b_order_internal ) . putInt ( storageBlock ) . putInt ( rootIdx ) . putInt ( lowIdx ) . putInt ( highIdx ) . putInt ( elements ) . putInt ( height ) . putInt ( maxInternalNodes ) . putInt ( maxLeafNodes ) . put ( ( byte ) ( isClean ? 0xEA : 0x00 ) ) . putInt ( MAGIC_2 ) . flip ( ) ; isOK = wbuf . save ( ) ; if ( isClean ) { storage . sync ( ) ; } try { if ( isClean ) { SimpleBitSet . serializeToFile ( fileFreeBlocks , freeBlocks ) ; } else { fileFreeBlocks . delete ( ) ; } } catch ( IOException e ) { log . error ( "IOException in writeMetaData(" + isClean + ")" , e ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( this . getClass ( ) . getName ( ) + "::writeMetaData() elements=" + elements + " rootIdx=" + rootIdx + " lastNodeId=" + storageBlock + " freeBlocks=" + freeBlocks . cardinality ( ) ) ; } return isOK ; }
|
Write metadata to file
|
4,988
|
private boolean readMetaData ( ) throws InvalidDataException { final ByteBuffer buf = storage . get ( 0 ) ; int magic1 , magic2 , t_b_order_leaf , t_b_order_internal , t_blockSize ; boolean isClean = false ; magic1 = buf . getInt ( ) ; if ( magic1 != MAGIC_1 ) { throw new InvalidDataException ( "Invalid metadata (MAGIC1)" ) ; } t_blockSize = buf . getInt ( ) ; if ( t_blockSize != blockSize ) { throw new InvalidDataException ( "Invalid metadata (blockSize) " + t_blockSize + " != " + blockSize ) ; } t_b_order_leaf = buf . getInt ( ) ; t_b_order_internal = buf . getInt ( ) ; if ( t_b_order_leaf != b_order_leaf ) { throw new InvalidDataException ( "Invalid metadata (b-order leaf) " + t_b_order_leaf + " != " + b_order_leaf ) ; } if ( t_b_order_internal != b_order_internal ) { throw new InvalidDataException ( "Invalid metadata (b-order internal) " + t_b_order_internal + " != " + b_order_internal ) ; } storageBlock = buf . getInt ( ) ; rootIdx = buf . getInt ( ) ; lowIdx = buf . getInt ( ) ; highIdx = buf . getInt ( ) ; elements = buf . getInt ( ) ; height = buf . getInt ( ) ; maxInternalNodes = buf . getInt ( ) ; maxLeafNodes = buf . getInt ( ) ; isClean = ( ( buf . get ( ) == ( ( byte ) 0xEA ) ) ? true : false ) ; magic2 = buf . getInt ( ) ; if ( magic2 != MAGIC_2 ) { throw new InvalidDataException ( "Invalid metadata (MAGIC2)" ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( this . getClass ( ) . getName ( ) + "::readMetaData() elements=" + elements + " rootIdx=" + rootIdx ) ; } storage . release ( buf ) ; clearReadCaches ( ) ; clearWriteCaches ( ) ; if ( isClean && fileFreeBlocks . exists ( ) ) { try { final SimpleBitSet newFreeBlocks = SimpleBitSet . deserializeFromFile ( fileFreeBlocks ) ; freeBlocks = newFreeBlocks ; } catch ( IOException e ) { log . error ( "IOException in readMetaData()" , e ) ; } } return isClean ; }
|
Read metadata from file
|
4,989
|
public synchronized void delete ( ) { try { clear ( ) ; } catch ( Exception ign ) { } try { close ( ) ; } catch ( Exception ign ) { } try { fileRedo . delete ( ) ; } catch ( Exception ign ) { } try { fileStorage . delete ( ) ; } catch ( Exception ign ) { } try { fileFreeBlocks . delete ( ) ; } catch ( Exception ign ) { } }
|
Clear tree and Delete associated files
|
4,990
|
public synchronized void setUseRedo ( final boolean useRedo ) { if ( validState && this . useRedo && ! useRedo ) { redoQueue . clear ( ) ; redoStore . clear ( ) ; } this . useRedo = useRedo ; }
|
Use Redo system?
|
4,991
|
public synchronized void setUseRedoThread ( final boolean useRedoThread ) { if ( this . useRedoThread && ! useRedoThread ) { if ( redoThread != null ) { stopRedoThread ( redoThread ) ; } } this . useRedoThread = useRedoThread ; }
|
Use Dedicated Thread for Redo?
|
4,992
|
protected void submitRedoPut ( final K key , final V value ) { if ( ! useRedo ) { return ; } createRedoThread ( ) ; final ByteBuffer buf = bufstack . pop ( ) ; buf . put ( ( byte ) 0x0A ) ; key . serialize ( buf ) ; value . serialize ( buf ) ; buf . put ( ( byte ) 0x0A ) ; buf . flip ( ) ; if ( useRedoThread ) { try { redoQueue . put ( buf ) ; } catch ( InterruptedException e ) { log . error ( "InterruptedException in submitRedoPut(key, value)" , e ) ; } } else { redoStore . write ( buf ) ; bufstack . push ( buf ) ; } }
|
submit put to redo
|
4,993
|
protected void submitRedoMeta ( final int futureUse ) { if ( ! useRedo ) { return ; } createRedoThread ( ) ; final ByteBuffer buf = bufstack . pop ( ) ; buf . putInt ( 0x0C0C0C0C ) ; buf . flip ( ) ; if ( useRedoThread ) { try { redoQueue . put ( buf ) ; } catch ( InterruptedException e ) { log . error ( "InterruptedException in submitRedoMeta(" + futureUse + ")" , e ) ; } } else { redoStore . write ( buf ) ; bufstack . push ( buf ) ; } }
|
submit metadata to redo
|
4,994
|
public synchronized void setMaxCacheSizeInBytes ( final int newsize ) { if ( validState ) { log . info ( this . getClass ( ) . getName ( ) + "::setMaxCacheSizeInBytes newsize=" + newsize + " flushing write-cache" ) ; privateSync ( true , false ) ; clearReadCaches ( ) ; } if ( newsize >= 1024 ) { maxCacheSizeInBytes = newsize ; createReadCaches ( ) ; } }
|
Clear caches and Set new value of maximal bytes used for nodes in cache .
|
4,995
|
private void recalculateSizeReadCaches ( ) { final int maxCacheNodes = ( maxCacheSizeInBytes / blockSize ) ; readCacheInternal = Math . max ( ( int ) ( maxCacheNodes * .05f ) , 37 ) ; readCacheLeaf = Math . max ( ( int ) ( maxCacheNodes * .95f ) , 37 ) ; }
|
Recalculate size of read caches
|
4,996
|
private void createReadCaches ( ) { recalculateSizeReadCaches ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( this . getClass ( ) . getName ( ) + "::createReadCaches readCacheInternal=" + readCacheInternal + " readCacheLeaf=" + readCacheLeaf ) ; } cacheInternalNodes = createCacheLRUlinked ( readCacheInternal ) ; cacheLeafNodes = createCacheLRUlinked ( readCacheLeaf ) ; }
|
Create read caches
|
4,997
|
@ SuppressWarnings ( "rawtypes" ) private IntLinkedHashMap < Node > createCacheLRUlinked ( final int maxSize ) { return new IntLinkedHashMap < Node > ( ( int ) ( maxSize * 1.5f ) , Node . class , true ) ; }
|
Create a LRU hashmap of size maxSize
|
4,998
|
private void populateCache ( ) { if ( disableAllCaches || disablePopulateCache ) { return ; } final long ts = System . currentTimeMillis ( ) ; for ( int index = 1 ; ( ( index < storageBlock ) && ( cacheInternalNodes . size ( ) < readCacheInternal ) && ( cacheLeafNodes . size ( ) < readCacheLeaf ) ) ; index ++ ) { if ( freeBlocks . get ( index ) ) { continue ; } try { final Node < K , V > node = getNodeFromStore ( index ) ; ( node . isLeaf ( ) ? cacheLeafNodes : cacheInternalNodes ) . put ( node . id , node ) ; } catch ( Node . InvalidNodeID e ) { freeBlocks . set ( index ) ; } } log . info ( "Populated read cache ts=" + ( System . currentTimeMillis ( ) - ts ) + " blocks=" + storageBlock + " elements=" + elements ) ; }
|
Populate read cache if cache is enabled
|
4,999
|
@ SuppressWarnings ( "unchecked" ) private Node < K , V > getNodeCache ( final int nodeid ) { final boolean isLeaf = Node . isLeaf ( nodeid ) ; boolean responseFromCache = true ; Node < K , V > node = ( isLeaf ? dirtyLeafNodes : dirtyInternalNodes ) . get ( nodeid ) ; if ( node == null ) { node = ( isLeaf ? cacheLeafNodes : cacheInternalNodes ) . get ( nodeid ) ; if ( node == null ) { if ( log . isDebugEnabled ( ) ) log . debug ( "diskread node id=" + nodeid ) ; node = getNodeFromStore ( nodeid ) ; responseFromCache = false ; ( node . isLeaf ( ) ? cacheLeafNodes : cacheInternalNodes ) . put ( nodeid , node ) ; } } if ( enableIOStats ) { if ( responseFromCache ) { getIOStat ( nodeid ) . incCacheRead ( ) ; } } return node ; }
|
Get node from cache
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.