idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
37,700
public void setOffsetByMotionEvent ( MotionEvent event ) { int x = ( int ) event . getRawX ( ) ; int y = ( int ) event . getRawY ( ) ; if ( x + contentParams . width + FINGER_SIZE < screenWidth ) { setContentOffset ( x , y , Translation . HORIZONTAL , FINGER_SIZE ) ; } else if ( x - FINGER_SIZE - contentParams . width > 0 ) { setContentOffset ( x , y , Translation . HORIZONTAL , - 1 * FINGER_SIZE ) ; } else if ( y + contentParams . height + FINGER_SIZE < screenHeight ) { setContentOffset ( x , y , Translation . VERTICAL , FINGER_SIZE ) ; } else if ( y - FINGER_SIZE - contentParams . height > 0 ) { setContentOffset ( x , y , Translation . VERTICAL , - 1 * FINGER_SIZE ) ; } else { if ( x < screenWidth / 2 ) { setContentOffset ( x , y , Translation . HORIZONTAL , FINGER_SIZE ) ; } else { setContentOffset ( x , y , Translation . HORIZONTAL , - 1 * FINGER_SIZE ) ; } } }
Places the peek view over the top of a motion event . This will translate the motion event s start points so that the PeekView isn t covered by the finger .
37,701
private void setContentOffset ( int startX , int startY , Translation translation , int movementAmount ) { if ( translation == Translation . VERTICAL ) { int originalStartX = startX ; startX -= contentParams . width / 2 ; boolean moveDown = true ; if ( startY + contentParams . height + FINGER_SIZE > screenHeight ) { startY -= contentParams . height ; moveDown = false ; if ( movementAmount > 0 ) { movementAmount *= - 1 ; } } int extraXOffset = 0 ; if ( moveDown ) { extraXOffset = DensityUtils . toPx ( getContext ( ) , 200 ) ; if ( originalStartX > screenWidth / 2 ) { extraXOffset = extraXOffset * - 1 ; } } startX = ensureWithinBounds ( startX + extraXOffset , screenWidth , contentParams . width ) ; startY = ensureWithinBounds ( startY + movementAmount , screenHeight , contentParams . height ) ; } else { startY -= contentParams . height / 2 ; if ( startX + contentParams . width + FINGER_SIZE > screenWidth ) { startX -= contentParams . width ; if ( movementAmount > 0 ) { movementAmount *= - 1 ; } } startX = ensureWithinBounds ( startX + movementAmount , screenWidth , contentParams . width ) ; startY = ensureWithinBounds ( startY , screenHeight , contentParams . height ) ; } int statusBar = NavigationUtils . getStatusBarHeight ( getContext ( ) ) ; if ( startY < statusBar ) { startY = statusBar + 10 ; } else if ( NavigationUtils . hasNavBar ( getContext ( ) ) && startY + contentParams . height > screenHeight - NavigationUtils . getNavBarHeight ( getContext ( ) ) ) { startY = screenHeight - contentParams . height - NavigationUtils . getNavBarHeight ( getContext ( ) ) - DensityUtils . toDp ( getContext ( ) , 10 ) ; } else if ( ! NavigationUtils . hasNavBar ( getContext ( ) ) && startY + contentParams . height > screenHeight ) { startY = screenHeight - contentParams . height - DensityUtils . toDp ( getContext ( ) , 10 ) ; } setDistanceFromLeft ( startX ) ; setDistanceFromTop ( startY ) ; }
Show the PeekView over the point of motion
37,702
public void show ( ) { androidContentView . addView ( this ) ; content . setTranslationX ( distanceFromLeft ) ; content . setTranslationY ( distanceFromTop ) ; ObjectAnimator animator = ObjectAnimator . ofFloat ( this , View . ALPHA , 0.0f , 1.0f ) ; animator . addListener ( new AnimatorEndListener ( ) { public void onAnimationEnd ( Animator animator ) { if ( callbacks != null ) { callbacks . shown ( ) ; } } } ) ; animator . setDuration ( options . useFadeAnimation ( ) ? ANIMATION_TIME : 0 ) ; animator . setInterpolator ( INTERPOLATOR ) ; animator . start ( ) ; }
Show the content of the PeekView by adding it to the android . R . id . content FrameLayout .
37,703
public void hide ( ) { ObjectAnimator animator = ObjectAnimator . ofFloat ( this , View . ALPHA , 1.0f , 0.0f ) ; animator . addListener ( new AnimatorEndListener ( ) { public void onAnimationEnd ( Animator animator ) { androidContentView . removeView ( PeekView . this ) ; if ( callbacks != null ) { callbacks . dismissed ( ) ; } } } ) ; animator . setDuration ( options . useFadeAnimation ( ) ? ANIMATION_TIME : 0 ) ; animator . setInterpolator ( INTERPOLATOR ) ; animator . start ( ) ; Blurry . delete ( ( ViewGroup ) androidContentView . getRootView ( ) ) ; }
Hide the PeekView and remove it from the android . R . id . content FrameLayout .
37,704
public void applyTo ( final PeekViewActivity activity , final View base ) { final GestureDetectorCompat detector = new GestureDetectorCompat ( activity , new GestureListener ( activity , base , this ) ) ; base . setOnTouchListener ( new View . OnTouchListener ( ) { public boolean onTouch ( View view , final MotionEvent motionEvent ) { detector . onTouchEvent ( motionEvent ) ; if ( motionEvent . getAction ( ) == MotionEvent . ACTION_DOWN ) { forceRippleAnimation ( base , motionEvent ) ; } return true ; } } ) ; }
Finish the builder by selecting the base view that you want to show the PeekView from .
37,705
public void show ( PeekViewActivity activity , MotionEvent motionEvent ) { PeekView peek ; if ( layout == null ) { peek = new PeekView ( activity , options , layoutRes , callbacks ) ; } else { peek = new PeekView ( activity , options , layout , callbacks ) ; } peek . setOffsetByMotionEvent ( motionEvent ) ; activity . showPeek ( peek ) ; }
Show the PeekView
37,706
public void loadStyledAttributes ( AttributeSet attrs , int defStyleAttr ) { if ( attrs != null ) { final TypedArray attributes = mContext . getTheme ( ) . obtainStyledAttributes ( attrs , R . styleable . CircularViewPager , defStyleAttr , 0 ) ; mStartLineEnabled = attributes . getBoolean ( R . styleable . CircularViewPager_progress_start_line_enabled , true ) ; mClockwiseArcColor = attributes . getColor ( R . styleable . CircularViewPager_progress_arc_clockwise_color , default_clockwise_reached_color ) ; mCounterClockwiseArcColor = attributes . getColor ( R . styleable . CircularViewPager_progress_arc_counter_clockwise_color , default_counter_clockwise_reached_color ) ; mClockwiseOutlineArcColor = attributes . getColor ( R . styleable . CircularViewPager_progress_arc_clockwise_outline_color , default_clockwise_outline_color ) ; mCounterClockwiseOutlineArcColor = attributes . getColor ( R . styleable . CircularViewPager_progress_arc_counter_clockwise_outline_color , default_counter_clockwise_outline_color ) ; mClockwiseReachedArcWidth = attributes . getDimension ( R . styleable . CircularViewPager_progress_arc_clockwise_width , default_reached_arc_width ) ; mCounterClockwiseReachedArcWidth = attributes . getDimension ( R . styleable . CircularViewPager_progress_arc_counter_clockwise_width , default_reached_arc_width ) ; mClockwiseOutlineArcWidth = attributes . getDimension ( R . styleable . CircularViewPager_progress_arc_clockwise_outline_width , default_outline_arc_width ) ; mCounterClockwiseOutlineArcWidth = attributes . getDimension ( R . styleable . CircularViewPager_progress_arc_counter_clockwise_outline_width , default_outline_arc_width ) ; mCircleFillColor = attributes . getColor ( R . styleable . CircularViewPager_progress_pager_fill_circle_color , default_circle_fill_color ) ; mCircleFillMode = attributes . getInt ( R . styleable . CircularViewPager_progress_pager_fill_mode , default_circle_fill_mode ) ; cicleFillEnable ( mCircleFillColor != default_circle_fill_color ) ; setMax ( attributes . getInt ( R . styleable . CircularViewPager_progress_arc_max , 100 ) ) ; setProgress ( attributes . getInt ( R . styleable . CircularViewPager_arc_progress , 0 ) ) ; attributes . recycle ( ) ; initializePainters ( ) ; } }
Loads the styles and attributes defined in the xml tag of this class
37,707
private void initializePainters ( ) { mClockwiseReachedArcPaint = new Paint ( Paint . ANTI_ALIAS_FLAG ) ; mClockwiseReachedArcPaint . setColor ( mClockwiseArcColor ) ; mClockwiseReachedArcPaint . setAntiAlias ( true ) ; mClockwiseReachedArcPaint . setStrokeWidth ( mClockwiseReachedArcWidth ) ; mClockwiseReachedArcPaint . setStyle ( Paint . Style . STROKE ) ; mCounterClockwiseReachedArcPaint = new Paint ( Paint . ANTI_ALIAS_FLAG ) ; mCounterClockwiseReachedArcPaint . setColor ( mCounterClockwiseArcColor ) ; mCounterClockwiseReachedArcPaint . setAntiAlias ( true ) ; mCounterClockwiseReachedArcPaint . setStrokeWidth ( mCounterClockwiseReachedArcWidth ) ; mCounterClockwiseReachedArcPaint . setStyle ( Paint . Style . STROKE ) ; mClockwiseOutlineArcPaint = new Paint ( Paint . ANTI_ALIAS_FLAG ) ; mClockwiseOutlineArcPaint . setColor ( mClockwiseOutlineArcColor ) ; mClockwiseOutlineArcPaint . setAntiAlias ( true ) ; mClockwiseOutlineArcPaint . setStrokeWidth ( mClockwiseOutlineArcWidth ) ; mClockwiseOutlineArcPaint . setStyle ( Paint . Style . STROKE ) ; mCounterClockwiseOutlineArcPaint = new Paint ( Paint . ANTI_ALIAS_FLAG ) ; mCounterClockwiseOutlineArcPaint . setColor ( mCounterClockwiseOutlineArcColor ) ; mCounterClockwiseOutlineArcPaint . setAntiAlias ( true ) ; mCounterClockwiseOutlineArcPaint . setStrokeWidth ( mCounterClockwiseOutlineArcWidth ) ; mCounterClockwiseOutlineArcPaint . setStyle ( Paint . Style . STROKE ) ; mCircleFillPaint = new Paint ( Paint . ANTI_ALIAS_FLAG ) ; mCircleFillPaint . setColor ( mCircleFillColor ) ; mCircleFillPaint . setAntiAlias ( true ) ; mCircleFillPaint . setStyle ( Paint . Style . FILL ) ; mReachedArcPaint = mClockwiseReachedArcPaint ; mOutlineArcPaint = mClockwiseOutlineArcPaint ; }
Initializes the paints used for the bars
37,708
public static ProducerSnapshot createSnapshot ( IStatsProducer producer , String intervalName ) { ProducerSnapshot ret = new ProducerSnapshot ( ) ; ret . setCategory ( producer . getCategory ( ) ) ; ret . setSubsystem ( producer . getSubsystem ( ) ) ; ret . setProducerId ( producer . getProducerId ( ) ) ; ret . setIntervalName ( intervalName ) ; List < IStats > stats = producer . getStats ( ) ; if ( stats != null && stats . size ( ) > 0 ) ret . setStatClassName ( stats . get ( 0 ) . getClass ( ) . getName ( ) ) ; if ( stats == null || stats . size ( ) == 0 ) return ret ; List < String > cachedValueNames = stats . get ( 0 ) . getAvailableValueNames ( ) ; for ( IStats stat : stats ) { ret . addSnapshot ( createStatSnapshot ( stat , intervalName , cachedValueNames ) ) ; } return ret ; }
Creates a snapshot for a producer .
37,709
private static StatSnapshot createStatSnapshot ( IStats stat , String intervalName , List < String > valueNames ) { StatSnapshot snapshot = new StatSnapshot ( stat . getName ( ) ) ; for ( String valueName : valueNames ) { snapshot . setValue ( valueName , stat . getValueByNameAsString ( valueName , intervalName , TimeUnit . NANOSECONDS ) ) ; } return snapshot ; }
Creates a snapshot for one stat object .
37,710
public static BlueprintProducer getBlueprintProducer ( String producerId , String category , String subsystem ) { try { BlueprintProducer producer = producers . get ( producerId ) ; if ( producer == null ) { synchronized ( producers ) { producer = producers . get ( producerId ) ; if ( producer == null ) { producer = new BlueprintProducer ( producerId , category , subsystem ) ; producers . put ( producerId , producer ) ; } } } return producer ; } catch ( Exception e ) { log . error ( "getBlueprintProducer(" + producerId + ", " + category + ", " + subsystem + ')' , e ) ; throw new RuntimeException ( "Handler instantiation failed - " + e . getMessage ( ) ) ; } }
Returns the blueprint producer with this id . Creates one if none is existing . Uses DLC pattern to reduce synchronization overhead .
37,711
private void setAccumulatorAttributes ( List < String > accumulatorIds , HttpServletRequest request ) throws APIException { if ( accumulatorIds == null || accumulatorIds . isEmpty ( ) ) { return ; } request . setAttribute ( "accumulatorsPresent" , Boolean . TRUE ) ; List < AccumulatedSingleGraphAO > singleGraphDataBeans = getAccumulatorAPI ( ) . getChartsForMultipleAccumulators ( accumulatorIds ) ; request . setAttribute ( "singleGraphData" , singleGraphDataBeans ) ; request . setAttribute ( "accumulatorsColors" , AccumulatorUtility . accumulatorsColorsToJSON ( singleGraphDataBeans ) ) ; List < String > accumulatorsNames = new LinkedList < > ( ) ; for ( AccumulatedSingleGraphAO ao : singleGraphDataBeans ) { accumulatorsNames . add ( ao . getName ( ) ) ; } request . setAttribute ( "accNames" , accumulatorsNames ) ; request . setAttribute ( "accNamesConcat" , net . anotheria . util . StringUtils . concatenateTokens ( accumulatorsNames , "," ) ) ; }
Sets accumulator specific attributes required to show accumulator charts on page .
37,712
private void setThresholdAttributes ( List < String > thresholdIds , HttpServletRequest request ) throws APIException { if ( thresholdIds == null || thresholdIds . isEmpty ( ) ) { return ; } request . setAttribute ( "thresholdsPresent" , Boolean . TRUE ) ; List < ThresholdStatusBean > thresholdStatusBeans = getThresholdBeans ( getThresholdAPI ( ) . getThresholdStatuses ( thresholdIds . toArray ( new String [ 0 ] ) ) ) ; request . setAttribute ( "thresholds" , thresholdStatusBeans ) ; }
Sets threshold specific attributes required to show thresholds on page .
37,713
private void removeCumulatedStats ( ProducerDecoratorBean decorator ) { if ( decorator == null ) { LOGGER . warn ( "Decorator is empty" ) ; return ; } for ( ProducerAO producer : decorator . getProducers ( ) ) { for ( Iterator < StatLineAO > statLineIterator = producer . getLines ( ) . listIterator ( ) ; statLineIterator . hasNext ( ) ; ) { if ( CUMULATED_STAT_NAME_VALUE . equals ( statLineIterator . next ( ) . getStatName ( ) ) ) { statLineIterator . remove ( ) ; } } } }
Removes cumulated stats from producers inside decorator .
37,714
private boolean hasAnyStat ( ProducerDecoratorBean decorator ) { for ( ProducerAO producer : decorator . getProducers ( ) ) { for ( StatLineAO line : producer . getLines ( ) ) { if ( ! CUMULATED_STAT_NAME_VALUE . equals ( line . getStatName ( ) ) ) { return true ; } } } return false ; }
Checks whether given decorator stat lines contain something besides cumulated stat .
37,715
public boolean isMBeanRequired ( final String domainName , final String className ) { if ( domains == null || domains . length == 0 ) return true ; for ( MBeanProducerDomainConfig domainConfig : domains ) if ( domainConfig . getName ( ) . equalsIgnoreCase ( domainName ) ) { return ArrayUtils . contains ( domainConfig . getClasses ( ) , className ) ; } return false ; }
Checks is mbean with given domain and class required by this configuration .
37,716
private static < A extends Annotation > A findAnnotationInAnnotations ( final AnnotatedElement source , final Class < A > targetAnnotationClass ) { final Annotation [ ] allAnnotations = source . getAnnotations ( ) ; for ( final Annotation annotation : allAnnotations ) { final A result = findAnnotation ( annotation , targetAnnotationClass ) ; if ( result != null ) return result ; } return null ; }
Tries to find required annotation in scope of all annotations of incoming source .
37,717
public static < A extends Annotation > A findTypeAnnotation ( final Class < ? > type , final Class < A > targetAnnotationClass ) { Objects . requireNonNull ( type , "incoming 'type' is not valid" ) ; Objects . requireNonNull ( targetAnnotationClass , "incoming 'targetAnnotationClass' is not valid" ) ; if ( type . equals ( Object . class ) ) return null ; final A annotation = findAnnotation ( type , targetAnnotationClass ) ; if ( annotation != null ) return annotation ; final Class < ? > superClass = type . getSuperclass ( ) ; if ( superClass != null ) return findTypeAnnotation ( superClass , targetAnnotationClass ) ; return null ; }
Recursive annotation search on type it annotations and parents hierarchy . Interfaces ignored .
37,718
private ValueHolder getHolderByIntervalName ( String aIntervalName ) { ValueHolder h = values . get ( aIntervalName ) ; if ( h == null ) throw new UnknownIntervalException ( aIntervalName ) ; return h ; }
This method returns the ValueHolder that is stored for the given Interval name .
37,719
public void initWithDefaultProperties ( Properties properties ) throws ConnectorInitException { log . debug ( "Starting to initWithDefaultProperties RabbitMQ connector in php plugin..." ) ; ConnectionFactory factory = new ConnectionFactory ( ) ; factory . setHost ( properties . getProperty ( "connector.host" ) ) ; factory . setPort ( Integer . valueOf ( properties . getProperty ( "connector.port" ) ) ) ; factory . setUsername ( properties . getProperty ( "connector.username" ) ) ; factory . setPassword ( properties . getProperty ( "connector.password" ) ) ; try { connection = factory . newConnection ( ) ; channel = connection . createChannel ( ) ; channel . queueDeclare ( properties . getProperty ( "connector.queue-name" ) , false , false , false , null ) ; channel . basicConsume ( properties . getProperty ( "connector.queue-name" ) , true , new MoskitoPHPConsumer ( channel ) ) ; enabledInTimestamp = System . currentTimeMillis ( ) ; } catch ( IOException | TimeoutException e ) { deinit ( ) ; throw new ConnectorInitException ( "Failed to open connection to RabbitMQ" , e ) ; } }
Opens connection and channel to listen configured queue for incoming data
37,720
public void deinit ( ) { if ( channel != null ) try { channel . close ( ) ; } catch ( IOException | TimeoutException e ) { log . warn ( "Failed to close channel in RabbitMQ connector" ) ; } if ( connection != null ) try { connection . close ( ) ; } catch ( IOException e ) { log . warn ( "Failed to close connection in RabbitMQ connector" ) ; } }
Closes RabbitMQ channel and connection
37,721
public void intervalUpdated ( Interval caller ) { output . out ( "===============================================================================" ) ; output . out ( "=== SNAPSHOT Interval " + interval . getName ( ) + " updated, Entity: " + id ) ; output . out ( "=== Timestamp: " + Date . currentDate ( ) + ", ServiceId: " + target . getProducerId ( ) ) ; output . out ( "===============================================================================" ) ; for ( IStats stat : target . getStats ( ) ) { output . out ( stat . toStatsString ( interval . getName ( ) ) ) ; } output . out ( "===============================================================================" ) ; output . out ( "== END: Interval " + interval . getName ( ) + ", Entity: " + id ) ; output . out ( "===============================================================================" ) ; }
Called by the timer . Writes the current status to the logger .
37,722
public static void startMoSKitoInspectBackend ( int port ) throws MoSKitoInspectStartException { log . info ( "Starting moskito-inspect remote agent at port " + port ) ; Class serverClazz = null ; Exception exception = null ; try { serverClazz = Class . forName ( "net.anotheria.moskito.webui.shared.api.generated.CombinedAPIServer" ) ; Method startMethod = serverClazz . getMethod ( "createCombinedServicesAndRegisterLocally" , int . class ) ; startMethod . invoke ( null , port ) ; } catch ( ClassNotFoundException e ) { exception = e ; log . error ( "Couldn't find the backend server class" , e ) ; } catch ( NoSuchMethodException e ) { exception = e ; log . error ( "Couldn't find the method in server class" , e ) ; } catch ( InvocationTargetException e ) { exception = e ; log . error ( "Couldn't invoke start method" , e ) ; } catch ( IllegalAccessException e ) { exception = e ; log . error ( "Couldn't invoke start method" , e ) ; } if ( exception != null ) { throw new MoSKitoInspectStartException ( exception ) ; } }
Starts MoSKito Inspect Backend .
37,723
public MapperConfig [ ] getDefault ( ) { MapperConfig executionStatsMapper = new MapperConfig ( ) ; executionStatsMapper . setMapperClass ( "net.anotheria.extensions.php.mappers.impl.ExecutionStatsMapper" ) ; executionStatsMapper . setMapperId ( "ExecutionStatsMapper" ) ; MapperConfig serviceStatsMapper = new MapperConfig ( ) ; serviceStatsMapper . setMapperClass ( "net.anotheria.extensions.php.mappers.impl.ServiceStatsMapper" ) ; serviceStatsMapper . setMapperId ( "ServiceStatsMapper" ) ; MapperConfig counterStatsMapper = new MapperConfig ( ) ; counterStatsMapper . setMapperClass ( "net.anotheria.extensions.php.mappers.impl.CounterStatsMapper" ) ; counterStatsMapper . setMapperId ( "CounterStatsMapper" ) ; return new MapperConfig [ ] { executionStatsMapper , serviceStatsMapper , counterStatsMapper } ; }
Defines builtin default mappers that required for agent proper work
37,724
private Object doMoskitoProfiling ( ProceedingJoinPoint pjp , String statement ) throws Throwable { String statementGeneralized = removeParametersFromStatement ( statement ) ; long callTime = System . nanoTime ( ) ; QueryStats cumulatedStats = producer . getDefaultStats ( ) ; QueryStats statementStats = null ; try { statementStats = producer . getStats ( statementGeneralized ) ; } catch ( OnDemandStatsProducerException limitReachedException ) { log . warn ( "Query limit reached for query " + statement + ", + statementGeneralized ) ; } cumulatedStats . addRequest ( ) ; if ( statementStats != null ) statementStats . addRequest ( ) ; boolean success = true ; try { Object retVal = pjp . proceed ( ) ; return retVal ; } catch ( Throwable t ) { success = false ; cumulatedStats . notifyError ( t ) ; if ( statementStats != null ) statementStats . notifyError ( ) ; throw t ; } finally { final long callDurationTime = System . nanoTime ( ) - callTime ; cumulatedStats . addExecutionTime ( callDurationTime ) ; if ( statementStats != null ) statementStats . addExecutionTime ( callDurationTime ) ; cumulatedStats . notifyRequestFinished ( ) ; if ( statementStats != null ) { statementStats . notifyRequestFinished ( ) ; } addTrace ( statement , success , callDurationTime ) ; } }
Perform MoSKito profiling .
37,725
private void addTrace ( String statement , final boolean isSuccess , final long duration ) { TracedCall aRunningTrace = RunningTraceContainer . getCurrentlyTracedCall ( ) ; CurrentlyTracedCall currentTrace = aRunningTrace . callTraced ( ) ? ( CurrentlyTracedCall ) aRunningTrace : null ; if ( currentTrace != null ) { TraceStep currentStep = currentTrace . startStep ( ( isSuccess ? EMPTY : SQL_QUERY_FAILED ) + "SQL : (' " + statement + "')" , producer , statement ) ; if ( ! isSuccess ) currentStep . setAborted ( ) ; currentStep . setDuration ( duration ) ; currentTrace . endStep ( ) ; } }
Perform additional profiling - for Journey stuff .
37,726
private Object count ( ProceedingJoinPoint pjp , String aProducerId , String aSubsystem , String aCategory ) throws Throwable { return perform ( false , getMethodStatName ( pjp . getSignature ( ) ) , pjp , aProducerId , aCategory , aSubsystem ) ; }
Implementation for the
37,727
void bootstrapPlugin ( IProducerRegistry producerRegistry ) throws PHPPluginBootstrapException { config . setConfigChangedNotifier ( new ConfigChangedNotifierImpl ( ) ) ; MappersRegistry mappersRegistry = new MappersRegistry ( ) ; listener = new OnProducerDataReceivedListenerImpl ( mappersRegistry , producerRegistry ) ; for ( MapperConfig mapperConfig : config . getMappers ( ) ) { try { mappersRegistry . registerMapper ( mapperConfig . getMapperId ( ) , ( ( Mapper ) createInstance ( mapperConfig . getMapperClass ( ) ) ) ) ; } catch ( ClassNotFoundException e ) { throw new PHPPluginBootstrapException ( "Mapper class " + mapperConfig . getMapperClass ( ) + " not found" , e ) ; } catch ( NoSuchMethodException | IllegalAccessException e ) { throw new PHPPluginBootstrapException ( "Mapper class must have default public constructor" , e ) ; } catch ( InvocationTargetException e ) { throw new PHPPluginBootstrapException ( "Mapper constructor throws exception" , e ) ; } catch ( InstantiationException e ) { throw new PHPPluginBootstrapException ( "Failed to instance mapper of class " + mapperConfig . getMapperClass ( ) , e ) ; } catch ( ClassCastException e ) { throw new PHPPluginBootstrapException ( "Class " + mapperConfig . getMapperClass ( ) + " is not instance of " + Mapper . class . getCanonicalName ( ) , e ) ; } } boolean enableConnectorsInitOnStartup = PROPERTY_TRUE_VALUE . equals ( startupProperties . getProperty ( PROPERTY_CONNECTORS_FORCE_ENABLED ) ) ; configureConnectors ( enableConnectorsInitOnStartup ) ; }
Bootstraps Moskito PHP plugin
37,728
public static String makeDeepLink ( String link ) { if ( link != null && getCurrentRemoteConnectionLink ( ) != null && ! containsRemoteParameter ( link ) ) { link += ( link . contains ( "?" ) ? "&" : "?" ) + PARAM_REMOTE_CONNECTION + "=" + getCurrentRemoteConnectionLink ( ) ; } return link ; }
Adds remote connection parameter to link GET query if parameter yet not present in this link .
37,729
private String formatQuery ( final ThresholdAlert alert ) { return String . format ( SMS_QUERY_FORMAT , user , password , createMessage ( alert , smsTemplate ) , recipients ) ; }
Formats query .
37,730
private static String createMessage ( final ThresholdAlert alert , final String template ) { String message ; if ( ! StringUtils . isEmpty ( template ) ) { ThresholdAlertTemplate thresholdAlertTemplate = new ThresholdAlertTemplate ( alert ) ; message = thresholdAlertTemplate . process ( template ) ; } else { message = ThresholdAlertConverter . toPlainText ( alert ) ; } return message ; }
Create SMS message .
37,731
public void addCaption ( String name , String type ) { captions . add ( new StatCaptionBean ( name , name + " as " + type , "" ) ) ; }
Add a caption value .
37,732
public void putAll ( Storage < ? extends K , ? extends V > anotherStorage ) { wrapper . putAll ( anotherStorage . getWrapper ( ) ) ; stats . setSize ( wrapper . size ( ) ) ; }
Puts all elements from anotherStorage to this storage .
37,733
public Map < K , V > fillMap ( Map < K , V > toFill ) { return wrapper . fillMap ( toFill ) ; }
Puts all elements into a given map .
37,734
public static < K , V > Storage < K , V > createHashtableStorage ( ) { return new Storage < K , V > ( new MapStorageWrapper < K , V > ( new HashMap < K , V > ( ) ) ) ; }
Factory method to create a new storage backed by a hashtable .
37,735
public static < K , V > Storage < K , V > createTreeMapStorage ( String name ) { return new Storage < K , V > ( name , new MapStorageWrapper < K , V > ( new TreeMap < K , V > ( ) ) ) ; }
Creates a new TreeMap backed Storage .
37,736
protected static IValueHolderFactory createValueHolderFactory ( StatValueTypes aType ) { switch ( aType ) { case LONG : return longValueHolderFactory ; case INT : return intValueHolderFactory ; case STRING : return stringValueHolderFactory ; case COUNTER : return counterValueHolderFactory ; case DOUBLE : return doubleValueHolderFactory ; case DIFFLONG : return diffLongValueHolderFactory ; default : throw new AssertionError ( "Unsupported type: " + aType ) ; } }
This method creates the responsible ValueHolderFactory from the given internal type representation .
37,737
public static String buildCall ( final Method method , final Object [ ] parameters ) { if ( method == null ) { throw new IllegalArgumentException ( "Parameter method can't be null" ) ; } return buildCall ( method . getDeclaringClass ( ) . getSimpleName ( ) , method . getName ( ) , parameters , null ) . toString ( ) ; }
Builds call .
37,738
public static List < TagEntryAO > tagsMapToTagEntries ( Map < String , String > tagsMap ) { if ( tagsMap == null ) return Collections . EMPTY_LIST ; List < TagEntryAO > tagEntries = new ArrayList < > ( tagsMap . size ( ) ) ; for ( Map . Entry < String , String > entry : tagsMap . entrySet ( ) ) tagEntries . add ( new TagEntryAO ( entry . getKey ( ) , entry . getValue ( ) ) ) ; return tagEntries ; }
Creates tags info beans from given tags map with tag names as keys and tag values as map values
37,739
private void apiAfterConfiguration ( ) { ProducerFilterConfig filterConfig [ ] = WebUIConfig . getInstance ( ) . getFilters ( ) ; if ( filterConfig == null || filterConfig . length == 0 ) return ; List < ProducerFilter > newProducerFilters = new ArrayList < > ( filterConfig . length ) ; for ( ProducerFilterConfig pfc : filterConfig ) { try { ProducerFilter filter = ( ProducerFilter ) Class . forName ( pfc . getClazzName ( ) ) . newInstance ( ) ; filter . customize ( pfc . getParameter ( ) ) ; newProducerFilters . add ( filter ) ; } catch ( InstantiationException e ) { log . warn ( "Can't initialize filter of class " + pfc . getClazzName ( ) ) ; } catch ( IllegalAccessException e ) { log . warn ( "Can't initialize filter of class " + pfc . getClazzName ( ) ) ; } catch ( ClassNotFoundException e ) { log . warn ( "Can't initialize filter of class " + pfc . getClazzName ( ) ) ; } } DecoratorConfig [ ] decoratorConfigs = WebUIConfig . getInstance ( ) . getDecorators ( ) ; if ( decoratorConfigs != null ) { log . debug ( "Configuring decorator configs " + Arrays . toString ( decoratorConfigs ) ) ; for ( DecoratorConfig config : decoratorConfigs ) { try { Class decoratorClass = Class . forName ( config . getDecoratorClazzName ( ) ) ; IDecorator decorator = ( IDecorator ) decoratorClass . newInstance ( ) ; DecoratorRegistryFactory . getDecoratorRegistry ( ) . addDecorator ( config . getStatClazzName ( ) , decorator ) ; } catch ( ClassNotFoundException e ) { log . warn ( "can't configure decorator " + config + " due " , e ) ; } catch ( InstantiationException e ) { log . warn ( "can't configure decorator " + config + " due " , e ) ; } catch ( IllegalAccessException e ) { log . warn ( "can't configure decorator " + config + " due " , e ) ; } } } producerFilters = newProducerFilters ; }
Called after the configuration has been read .
37,740
public void addExecutionTime ( long time ) { totalTime . increaseByLong ( time ) ; lastRequest . setValueAsLong ( time ) ; minTime . setValueIfLesserThanCurrentAsLong ( time ) ; maxTime . setValueIfGreaterThanCurrentAsLong ( time ) ; }
Adds messed execution time to the total execution time .
37,741
public double getAverageRequestDuration ( String intervalName , TimeUnit unit ) { return unit . transformNanos ( totalTime . getValueAsLong ( intervalName ) ) / totalRequests . getValueAsDouble ( intervalName ) ; }
Returns the average request duration for the given interval and converted to the given timeunit .
37,742
public double getErrorRate ( String intervalName ) { long tr = getTotalRequests ( intervalName ) ; double errorRate = tr == 0 ? 0 : ( ( double ) getErrors ( intervalName ) ) / tr ; return ( double ) ( ( int ) ( errorRate * 10000 ) ) / 100 ; }
Returns the error rate . This value was previously calculated in decorator but we moved it into the stats object to be able to define threshold on top of it .
37,743
protected void handleStatsResetIfNeeded ( StatusData < ApacheMetrics > status ) { StatValue uptime = getStatValue ( ApacheMetrics . SERVER_UPTIME ) ; Long currUptime = Long . class . cast ( status . get ( ApacheMetrics . SERVER_UPTIME ) ) ; if ( uptime != null && currUptime != null && uptime . getValueAsLong ( ) > currUptime ) { for ( ApacheMetrics metric : getAvailableMetrics ( ) ) { if ( metric . getType ( ) == StatValueTypes . DIFFLONG ) { StatValue stat = getStatValue ( metric ) ; if ( stat != null ) stat . reset ( ) ; } } } }
Check SERVER_UPTIME metric and if its value is lower than the stored one - monitored apache server was restarted . In this case all DIFFLONG statValues need resetting .
37,744
public AccumulatorDefinition toAccumulatorDefinition ( String producerId ) { AccumulatorDefinition ret = new AccumulatorDefinition ( ) ; ret . setProducerName ( producerId ) ; ret . setName ( replaceName ( producerId ) ) ; ret . setStatName ( getStatName ( ) ) ; ret . setValueName ( getValueName ( ) ) ; ret . setIntervalName ( getIntervalName ( ) ) ; ret . setTimeUnit ( getTimeUnit ( ) ) ; return ret ; }
Creates a new AccumulatorDefinition object for matched producer .
37,745
public String getAttributeName ( ) { return ! StringUtils . isEmpty ( attribute ) && attribute . contains ( "." ) ? attribute . substring ( attribute . indexOf ( "." ) + 1 , attribute . length ( ) ) : "" ; }
Retrieves attribute name .
37,746
private static String [ ] extract ( List < ? extends IGenericMetrics > metrics , Extractor e ) { List < String > strings = new ArrayList < > ( metrics . size ( ) ) ; for ( IGenericMetrics metric : metrics ) { strings . add ( e . extract ( metric ) ) ; } return strings . toArray ( new String [ strings . size ( ) ] ) ; }
Get array of Strings from metrics - one from each with given Extractor .
37,747
public void setUsed ( long value ) { used . setValueAsLong ( value ) ; minUsed . setValueIfLesserThanCurrentAsLong ( value ) ; maxUsed . setValueIfGreaterThanCurrentAsLong ( value ) ; }
Sets new used memory amount .
37,748
public void setCommited ( long value ) { commited . setValueAsLong ( value ) ; minCommited . setValueIfLesserThanCurrentAsLong ( value ) ; maxCommited . setValueIfGreaterThanCurrentAsLong ( value ) ; }
Sets new commited memory amount .
37,749
public void addLoadTime ( final long domLoadTime , final long windowLoadTime ) { totalDomLoadTime . increaseByLong ( domLoadTime ) ; domMinLoadTime . setValueIfLesserThanCurrentAsLong ( domLoadTime ) ; domMaxLoadTime . setValueIfGreaterThanCurrentAsLong ( domLoadTime ) ; domLastLoadTime . setValueAsLong ( domLoadTime ) ; totalWindowLoadTime . increaseByLong ( windowLoadTime ) ; windowMinLoadTime . setValueIfLesserThanCurrentAsLong ( windowLoadTime ) ; windowMaxLoadTime . setValueIfGreaterThanCurrentAsLong ( windowLoadTime ) ; windowLastLoadTime . setValueAsLong ( windowLoadTime ) ; numberOfLoads . increase ( ) ; }
Adds DOM load time and page load time to the stats .
37,750
public long getDomMinLoadTime ( final String intervalName , final TimeUnit unit ) { final long min = domMinLoadTime . getValueAsLong ( intervalName ) ; return min == Constants . MIN_TIME_DEFAULT ? min : unit . transformMillis ( min ) ; }
Returns DOM minimum load time for given interval and time unit .
37,751
public long getDomMaxLoadTime ( final String intervalName , final TimeUnit unit ) { final long max = domMaxLoadTime . getValueAsLong ( intervalName ) ; return max == Constants . MAX_TIME_DEFAULT ? max : unit . transformMillis ( max ) ; }
Returns DOM maximum load time for given interval and time unit .
37,752
public static List < ProducerDecoratorBean > getDecoratedProducers ( HttpServletRequest req , List < ProducerAO > producers , Map < String , GraphDataBean > graphData ) { Map < IDecorator , List < ProducerAO > > decoratorMap = new HashMap < > ( producers . size ( ) ) ; for ( ProducerAO producer : producers ) { try { IDecorator decorator = findOrCreateDecorator ( producer ) ; List < ProducerAO > decoratedProducers = decoratorMap . get ( decorator ) ; if ( decoratedProducers == null ) { decoratedProducers = new ArrayList < > ( ) ; decoratorMap . put ( decorator , decoratedProducers ) ; for ( StatValueAO statBean : producer . getFirstStatsValues ( ) ) { String graphKey = decorator . getName ( ) + '_' + statBean . getName ( ) ; GraphDataBean graphDataBean = new GraphDataBean ( decorator . getName ( ) + '_' + statBean . getJsVariableName ( ) , statBean . getName ( ) ) ; graphData . put ( graphKey , graphDataBean ) ; } } decoratedProducers . add ( producer ) ; } catch ( IndexOutOfBoundsException e ) { } } Set < Map . Entry < IDecorator , List < ProducerAO > > > entries = decoratorMap . entrySet ( ) ; List < ProducerDecoratorBean > beans = new ArrayList < > ( entries . size ( ) ) ; for ( Map . Entry < IDecorator , List < ProducerAO > > entry : entries ) { IDecorator decorator = entry . getKey ( ) ; ProducerDecoratorBean b = new ProducerDecoratorBean ( ) ; b . setName ( decorator . getName ( ) ) ; b . setCaptions ( decorator . getCaptions ( ) ) ; for ( ProducerAO p : entry . getValue ( ) ) { try { List < StatValueAO > values = p . getFirstStatsValues ( ) ; for ( StatValueAO valueBean : values ) { String graphKey = decorator . getName ( ) + '_' + valueBean . getName ( ) ; GraphDataBean bean = graphData . get ( graphKey ) ; if ( bean == null ) { log . warn ( "unable to find bean for key: " + graphKey ) ; } else { bean . addValue ( new GraphDataValueBean ( p . getProducerId ( ) , valueBean . getRawValue ( ) ) ) ; } } } catch ( UnknownIntervalException e ) { } } b . setProducerBeans ( StaticQuickSorter . sort ( decoratorMap . get ( decorator ) , getProducerBeanSortType ( b , req ) ) ) ; beans . add ( b ) ; } return beans ; }
todo make separate method for graphData in future
37,753
public static ProducerDecoratorBean filterProducersByDecoratorName ( String decoratorName , List < ProducerAO > producers , Map < String , GraphDataBean > graphData ) { ProducerDecoratorBean result = new ProducerDecoratorBean ( ) ; result . setName ( decoratorName ) ; List < ProducerAO > decoratedProducers = new ArrayList < > ( ) ; for ( ProducerAO producer : producers ) { IDecorator decorator = findOrCreateDecorator ( producer ) ; if ( decorator . getName ( ) . equals ( decoratorName ) ) { result . setCaptions ( decorator . getCaptions ( ) ) ; decoratedProducers . add ( producer ) ; for ( StatLineAO statLine : producer . getLines ( ) ) { if ( ! "cumulated" . equals ( statLine . getStatName ( ) ) ) { for ( StatValueAO statValue : statLine . getValues ( ) ) { final String graphKey = decorator . getName ( ) + '_' + statValue . getName ( ) ; final GraphDataValueBean value = new GraphDataValueBean ( producer . getProducerId ( ) + '.' + statLine . getStatName ( ) , statValue . getRawValue ( ) ) ; GraphDataBean graphDataBean = graphData . get ( graphKey ) ; if ( graphDataBean == null ) { graphDataBean = new GraphDataBean ( decorator . getName ( ) + '_' + statValue . getJsVariableName ( ) , statValue . getName ( ) ) ; } graphDataBean . addValue ( value ) ; graphData . put ( graphKey , graphDataBean ) ; } } } } } result . setProducerBeans ( decoratedProducers ) ; return result ; }
Filters producers by decorator and returns it .
37,754
public StatusData < NginxMetrics > parse ( String nginxStatus ) { StatusData < NginxMetrics > status = new StatusData < > ( ) ; if ( StringUtils . isEmpty ( nginxStatus ) ) { throw new IllegalArgumentException ( "nginx status is empty!" ) ; } else { Matcher matcher = pattern . matcher ( nginxStatus ) ; if ( matcher . matches ( ) ) { status . put ( NginxMetrics . ACTIVE , Long . parseLong ( matcher . group ( 1 ) ) ) ; Long accepted = Long . parseLong ( matcher . group ( 2 ) ) ; status . put ( NginxMetrics . ACCEPTED , accepted ) ; status . put ( NginxMetrics . ACCEPTEDPERSECOND , accepted ) ; Long handled = Long . parseLong ( matcher . group ( 3 ) ) ; status . put ( NginxMetrics . HANDLED , handled ) ; status . put ( NginxMetrics . HANDLEDPERSECOND , handled ) ; Long dropped = handled - accepted ; status . put ( NginxMetrics . DROPPED , dropped ) ; status . put ( NginxMetrics . DROPPEDPERSECOND , dropped ) ; Long requests = Long . parseLong ( matcher . group ( 4 ) ) ; status . put ( NginxMetrics . REQUESTS , requests ) ; status . put ( NginxMetrics . REQUESTSPERSECOND , requests ) ; status . put ( NginxMetrics . READING , Long . parseLong ( matcher . group ( 5 ) ) ) ; status . put ( NginxMetrics . WRITING , Long . parseLong ( matcher . group ( 6 ) ) ) ; status . put ( NginxMetrics . WAITING , Long . parseLong ( matcher . group ( 7 ) ) ) ; } else { String message = "NginxStubStatusParser can't parse nginx status response: [" + nginxStatus + "]" ; throw new IllegalArgumentException ( message ) ; } } return status ; }
Parse NGINX stub status into StatusData&lt ; NginxMetrics&gt ; .
37,755
public Object execute ( BlueprintCallExecutor executor , Object ... parameters ) throws Exception { stats . addRequest ( ) ; long startTime = System . nanoTime ( ) ; TracedCall aTracedCall = RunningTraceContainer . getCurrentlyTracedCall ( ) ; TraceStep currentElement = null ; CurrentlyTracedCall currentlyTracedCall = aTracedCall . callTraced ( ) ? ( CurrentlyTracedCall ) aTracedCall : null ; if ( currentlyTracedCall != null ) currentElement = currentlyTracedCall . startStep ( new StringBuilder ( getProducerId ( ) ) . append ( '.' ) . append ( "execute" ) . toString ( ) , this , "execute" ) ; try { return executor . execute ( parameters ) ; } catch ( Exception e ) { stats . notifyError ( e ) ; throw e ; } finally { long duration = System . nanoTime ( ) - startTime ; stats . addExecutionTime ( duration ) ; stats . notifyRequestFinished ( ) ; if ( currentElement != null ) currentElement . setDuration ( duration ) ; if ( currentlyTracedCall != null ) currentlyTracedCall . endStep ( ) ; } }
Called by the surrounding code whenever the action which we are measuring is actually executed .
37,756
public void addConnector ( Connector connector ) { connectors . put ( connector . getClass ( ) . getCanonicalName ( ) , new ConnectorEntry ( connector ) ) ; }
Registers new connector
37,757
public void enableConnector ( String connectorClass , Properties connectorInitProperties ) throws ConnectorInitException { ConnectorEntry connector = connectors . get ( connectorClass ) ; if ( connector != null ) connectors . get ( connectorClass ) . enableConnector ( connectorInitProperties ) ; }
Makes enable connector with given class name if it registered and not already enabled . Non - existing or already enabled connectors be ignored
37,758
public void disableConnector ( String connectorClass ) { ConnectorEntry connector = connectors . get ( connectorClass ) ; if ( connector != null ) connectors . get ( connectorClass ) . disableConnector ( ) ; }
Denitializes connector with given class name .
37,759
protected OnDemandStatsProducer < S > getProducer ( final ProceedingJoinPoint pjp , final String aProducerId , final String aCategory , final String aSubsystem , final boolean withMethod , final IOnDemandStatsFactory < S > factory , final boolean tracingSupported , final boolean attachDefaultStatsLoggers ) { final String producerId = getProducerId ( pjp , aProducerId , withMethod ) ; OnDemandStatsProducer < S > producer = producers . get ( producerId ) ; if ( producer != null ) return producer ; producer = new OnDemandStatsProducer < > ( producerId , getCategory ( aCategory ) , getSubsystem ( aSubsystem ) , factory ) ; producer . setTracingSupported ( tracingSupported ) ; final OnDemandStatsProducer < S > p = producers . putIfAbsent ( producerId , producer ) ; if ( p != null ) return p ; ProducerRegistryFactory . getProducerRegistryInstance ( ) . registerProducer ( producer ) ; final Class producerClass = pjp . getSignature ( ) . getDeclaringType ( ) ; createClassLevelAccumulators ( producer , producerClass ) ; for ( Method method : producerClass . getMethods ( ) ) createMethodLevelAccumulators ( producer , method ) ; if ( attachDefaultStatsLoggers ) attachLoggers ( producer , factory ) ; return producer ; }
Returns the producer for the given pjp and producerId . Registers the producer in the registry if it s not already registered .
37,760
private String getProducerId ( final ProceedingJoinPoint pjp , final String aPId , final boolean withMethod ) { if ( ! StringUtils . isEmpty ( aPId ) ) return aPId ; String res = pjp . getSignature ( ) . getDeclaringTypeName ( ) ; try { res = MoskitoUtils . producerName ( res ) ; } catch ( final RuntimeException e ) { if ( logger . isTraceEnabled ( ) ) logger . trace ( e . getMessage ( ) , e ) ; } if ( withMethod ) { res += DOT + getMethodStatName ( pjp . getSignature ( ) ) ; } return res ; }
Fetch producer id - for further usage .
37,761
private String getMethodName ( Method method ) { StatName statName = method . getAnnotation ( StatName . class ) ; return statName == null ? method . getName ( ) : statName . value ( ) ; }
Returns name for monitored method .
37,762
private String createName ( String producerId , String statName ) { String appName = encodeAppName ( MoskitoConfigurationHolder . getConfiguration ( ) . getApplicationName ( ) ) ; return "MoSKito." + ( appName . length ( ) > 0 ? appName + '.' : "" ) + "producers:type=" + producerId + '.' + statName ; }
Creates JMX name for a producer .
37,763
public void update ( long aStarted , long aDaemon , long aCurrent ) { current . setValueAsLong ( aCurrent ) ; started . setValueAsLong ( aStarted ) ; daemon . setValueAsLong ( aDaemon ) ; minCurrent . setValueIfLesserThanCurrentAsLong ( aCurrent ) ; maxCurrent . setValueIfGreaterThanCurrentAsLong ( aCurrent ) ; }
Called regularly by a timer updates the internal stats .
37,764
private String getValueOrDefault ( HttpServletRequest req , String paramName , String defaultValue ) { final String value = req . getParameter ( paramName ) ; return StringUtils . isEmpty ( value ) ? defaultValue : value ; }
Returns parameter value from request if exists otherwise - default value .
37,765
private boolean isLoadTimeValid ( final String loadTimeParam ) { return ! StringUtils . isEmpty ( loadTimeParam ) && isLong ( loadTimeParam ) && Long . valueOf ( loadTimeParam ) > 0 ; }
Validate given load time request parameter .
37,766
private OnDemandStatsProducer < PageInBrowserStats > createProducer ( final String producerId , final String category , final String subsystem ) { OnDemandStatsProducer < PageInBrowserStats > producer = limit == - 1 ? new OnDemandStatsProducer < PageInBrowserStats > ( producerId , category , subsystem , new PageInBrowserStatsFactory ( ) ) : new EntryCountLimitedOnDemandStatsProducer < PageInBrowserStats > ( producerId , category , subsystem , new PageInBrowserStatsFactory ( ) , limit ) ; ProducerRegistryFactory . getProducerRegistryInstance ( ) . registerProducer ( producer ) ; return producer ; }
Creates producer with given producer id category and subsystem and register it in producer registry .
37,767
private boolean isLong ( final String str ) { try { Long . valueOf ( str ) ; return true ; } catch ( NumberFormatException e ) { return false ; } }
Checks if given string is long .
37,768
private boolean processingAllowed ( final String prefix , final String variable , final TemplateReplacementContext context ) { return ( PREFIX . equals ( prefix ) && ! StringUtils . isEmpty ( variable ) && context instanceof MailTemplateReplacementContext ) ; }
Checks whether processing is allowed .
37,769
public static final void createSLF4JIntervalStatsLoggerForAllConfiguredIntervals ( IStatsProducer producer , String loggerNamePrefix ) { List < String > configuredIntervals = MoskitoConfigurationHolder . getConfiguration ( ) . getConfiguredIntervalNames ( ) ; for ( String intervalName : configuredIntervals ) { new IntervalStatsLogger ( producer , IntervalRegistry . getInstance ( ) . getInterval ( intervalName ) , new SLF4JLogOutput ( LoggerFactory . getLogger ( loggerNamePrefix + intervalName ) ) ) ; } }
Creates interval stats loggers for all configured intervals . Every logger is attached to a logger with name loggerNamePrefix&lt ; intervalName&gt ; . If loggerNamePrefix is for example foo then all loggers are attached to foo1m foo5m foo15m etc for all configured intervals .
37,770
private List < GaugeZoneAO > createDefaultZones ( ) { ArrayList < GaugeZoneAO > ret = new ArrayList < > ( 1 ) ; GaugeZoneAO redZone = new GaugeZoneAO ( ) ; redZone . setColor ( "red" ) ; redZone . setLeft ( 0.9f ) ; redZone . setRight ( 1.0f ) ; ret . add ( redZone ) ; return ret ; }
This method creates some default zones if nothing is configured .
37,771
private void guessExceptions ( ) { List < Class < ? > > tmpExceptionList = new ArrayList < > ( ) ; for ( Class < ? > c : supportedInterfaces ) { Method [ ] methods = c . getDeclaredMethods ( ) ; for ( Method m : methods ) { for ( Class < ? > exc : m . getExceptionTypes ( ) ) { if ( ! tmpExceptionList . contains ( exc ) ) tmpExceptionList . add ( exc ) ; } } } declaredExceptions = new Class [ tmpExceptionList . size ( ) ] ; tmpExceptionList . toArray ( declaredExceptions ) ; }
Looks up all possible exceptions .
37,772
private void init ( ) { errorProducerEnabled = MoskitoConfigurationHolder . getConfiguration ( ) . getBuiltinProducersConfig ( ) . isErrorProducer ( ) ; statsMap = new ConcurrentHashMap < > ( ) ; statsList = new CopyOnWriteArrayList < > ( ) ; cumulatedStats = new ErrorStats ( "cumulated" ) ; statsList . add ( cumulatedStats ) ; catchers = new ConcurrentHashMap < > ( ) ; if ( ! errorProducerEnabled ) return ; ProducerRegistryFactory . getProducerRegistryInstance ( ) . registerProducer ( this ) ; AfterStartTasks . submitTask ( new Runnable ( ) { public void run ( ) { AccumulatorRepository . getInstance ( ) . createAccumulator ( createAccumulatorDefinition ( "Errors.Cumulated.Total" , "total" , "cumulated" ) ) ; } } ) ; AfterStartTasks . submitTask ( new Runnable ( ) { public void run ( ) { AccumulatorRepository . getInstance ( ) . createAccumulator ( createAccumulatorDefinition ( "Errors.Cumulated.Initial" , "initial" , "cumulated" ) ) ; } } ) ; errorHandlingConfig = null ; }
Initialization . Moved out to be reused in unit - tests .
37,773
private AccumulatorDefinition createAccumulatorDefinition ( String name , String valueName , String statName ) { AccumulatorDefinition definition = new AccumulatorDefinition ( ) ; definition . setName ( name ) ; definition . setProducerName ( getProducerId ( ) ) ; definition . setStatName ( statName ) ; definition . setValueName ( valueName ) ; definition . setIntervalName ( MoskitoConfigurationHolder . getConfiguration ( ) . getErrorHandlingConfig ( ) . getAutoChartErrorsInterval ( ) ) ; return definition ; }
Helper method to create a accumulator definiton .
37,774
public void afterConfiguration ( ErrorHandlingConfig errorHandlingConfig ) { if ( ! errorProducerEnabled ) return ; this . errorHandlingConfig = errorHandlingConfig ; ErrorCatcherConfig [ ] defaultCatcherConfigs = errorHandlingConfig . getDefaultCatchers ( ) ; if ( defaultCatcherConfigs != null && defaultCatcherConfigs . length > 0 ) { defaultCatchers = new CopyOnWriteArrayList < > ( ) ; for ( ErrorCatcherConfig c : defaultCatcherConfigs ) { defaultCatchers . add ( ErrorCatcherFactory . createErrorCatcher ( c ) ) ; } } ErrorCatcherConfig [ ] catcherConfigs = errorHandlingConfig . getCatchers ( ) ; if ( catcherConfigs != null && catcherConfigs . length > 0 ) { catchers = new ConcurrentHashMap < > ( ) ; for ( ErrorCatcherConfig c : catcherConfigs ) { ErrorCatcher catcher = ErrorCatcherFactory . createErrorCatcher ( c ) ; List < ErrorCatcher > catcherList = catchers . get ( c . getExceptionClazz ( ) ) ; if ( catcherList == null ) { catcherList = new LinkedList < > ( ) ; catchers . put ( c . getExceptionClazz ( ) , catcherList ) ; } catcherList . add ( catcher ) ; } } }
Called from the error handling config instance after a configuration update or initial configuration .
37,775
private SessionThrottleFilterConfig getConfigFromConfigureMe ( ) { SessionThrottleFilterConfig config = new SessionThrottleFilterConfig ( ) ; try { ConfigurationManager . INSTANCE . configure ( config ) ; } catch ( IllegalArgumentException e ) { log . warn ( "Incompatible configuration selected, configureme as source choosen, but sessionthrottle.json is not present" ) ; } return config ; }
Reads config via configureme from sessionthrottle . json .
37,776
private SessionThrottleFilterConfig getConfigFromWebXML ( FilterConfig filterConfig ) { int limit = - 1 ; String l = filterConfig . getInitParameter ( "limit" ) ; try { if ( l != null ) limit = Integer . parseInt ( l ) ; } catch ( NumberFormatException ignored ) { } String target = filterConfig . getInitParameter ( "redirectTarget" ) ; if ( target == null || target . length ( ) == 0 ) limit = - 1 ; return new SessionThrottleFilterConfig ( limit , target ) ; }
Reads config from web . xml .
37,777
public void put ( T key , Object value ) { data . put ( key , ensureValueCorrectness ( key , value ) ) ; }
Stores given key - value mapping if no restrictions are violated by them .
37,778
private Object ensureValueCorrectness ( T key , Object value ) { checkKey ( key ) ; if ( key . isCorrectValue ( value ) || value == null ) { return value ; } if ( value instanceof String ) { value = key . parseValue ( String . class . cast ( value ) ) ; return value ; } throw new IllegalArgumentException ( "Entry <'" + key + "','" + value + "'> rejected! Value should be of correct type or of type String(for auto-parsing)!" ) ; }
Ensure that value is of correct type for the given key . If value is not already of correct type but of type String attempt parsing into correct type .
37,779
protected void invokeExecute ( final ActionMapping mapping , final FormBean bean , final HttpServletRequest req , final HttpServletResponse res , final JSONResponse jsonResponse ) throws Exception { }
Override this method for invoking main action code .
37,780
public void update ( StatusData < T > status ) { if ( status == null ) { throw new IllegalArgumentException ( "Received null as status data!" ) ; } neverUpdated = false ; handleStatsResetIfNeeded ( status ) ; for ( T metric : metrics ) { Object value = status . get ( metric ) ; if ( value == null ) { getLogger ( ) . warn ( "StatusData contains no value for metric '" + metric . getCaption ( ) + "'." ) ; continue ; } StatValue stat = getMonitoredStatValue ( metric ) ; switch ( metric . getType ( ) ) { case INT : stat . setValueAsInt ( Integer . class . cast ( value ) ) ; break ; case DOUBLE : stat . setValueAsDouble ( Double . class . cast ( value ) ) ; break ; case STRING : stat . setValueAsString ( value . toString ( ) ) ; break ; case COUNTER : case DIFFLONG : case LONG : stat . setValueAsLong ( Long . class . cast ( value ) ) ; break ; default : stat . setValueAsString ( value . toString ( ) ) ; break ; } } }
Update this stats with new data contained in StatusData parameter .
37,781
public long getStatValueAsLong ( T metric , String interval ) { if ( metric . isRateMetric ( ) ) { return ( long ) ( getStatValueAsDouble ( metric , interval ) ) ; } return getMonitoredStatValue ( metric ) . getValueAsLong ( interval ) ; }
Get value of provided metric for the given interval as long value .
37,782
public int getStatValueAsInteger ( T metric , String interval ) { if ( metric . isRateMetric ( ) ) { return ( int ) ( getStatValueAsDouble ( metric , interval ) ) ; } return getMonitoredStatValue ( metric ) . getValueAsInt ( interval ) ; }
Get value of provided metric for the given interval as int value .
37,783
public String getStatValueAsString ( T metric , String interval ) { if ( metric . isRateMetric ( ) ) { return String . valueOf ( getStatValueAsDouble ( metric , interval ) ) ; } return getMonitoredStatValue ( metric ) . getValueAsString ( interval ) ; }
Get value of provided metric for the given interval as String value .
37,784
public double getStatValueAsDouble ( T metric , String interval ) { StatValue statValue = getMonitoredStatValue ( metric ) ; if ( metric . isRateMetric ( ) ) { if ( "default" . equals ( interval ) ) { interval = DefaultIntervals . ONE_MINUTE . getName ( ) ; } double result = statValue . getValueAsLong ( interval ) ; long duration = IntervalRegistry . getInstance ( ) . getInterval ( interval ) . getLength ( ) ; if ( duration > 0 ) result /= duration ; return result ; } return statValue . getValueAsDouble ( interval ) ; }
Get value of provided metric for the given interval as double value .
37,785
public void add ( TracedCallStepAO step ) { elements . add ( step ) ; step . setId ( ( counter ++ ) ) ; ReversedCallHelper helper = stepsReversed . get ( step . getCall ( ) ) ; if ( helper == null ) { helper = new ReversedCallHelper ( ) ; stepsReversed . put ( step . getCall ( ) , helper ) ; } helper . add ( step . getNiceId ( ) , step . getTimespent ( ) , step . getDuration ( ) ) ; step . setParentId ( parentHolder . getParentIdByLayer ( step . getLayer ( ) , step . getNiceId ( ) ) ) ; }
Adds a new TracedCallStepAO .
37,786
public ReplyObject getAccumulators ( ) { try { return ReplyObject . success ( "accumulators" , getAccumulatorAPI ( ) . getAccumulatorDefinitions ( ) ) ; } catch ( APIException e ) { return ReplyObject . error ( e ) ; } }
Returns all accumulators .
37,787
@ Path ( "/{id}" ) public ReplyObject deleteAccumulator ( @ PathParam ( "id" ) String id ) { try { getAccumulatorAPI ( ) . removeAccumulator ( id ) ; return ReplyObject . success ( ) ; } catch ( APIException e ) { return ReplyObject . error ( e ) ; } }
Removes one accumulator by id .
37,788
public ReplyObject createAccumulator ( AccumulatorPO po ) { try { AccumulatorDefinitionAO ret = getAccumulatorAPI ( ) . createAccumulator ( po ) ; return ReplyObject . success ( "created" , ret ) ; } catch ( APIException e ) { return ReplyObject . error ( e ) ; } }
Creates new accumulator .
37,789
Interval getInterval ( int aId ) { Interval interval = intervalsById . get ( aId ) ; if ( interval == null ) { throw new UnknownIntervalException ( aId ) ; } return interval ; }
This method retrieves an Interval with the given id .
37,790
private Interval createInterval ( String aName , int aLength ) { if ( aName . equals ( "1m" ) ) { System . out . println ( "CREATE INTERVAL 1M CALLED " ) ; new RuntimeException ( ) . fillInStackTrace ( ) . printStackTrace ( ) ; } IntervalImpl interval = new IntervalImpl ( obtainNextUniqueId ( ) , aName , aLength ) ; if ( aLength != - 1 ) updateTriggerService . addUpdateable ( interval , aLength ) ; intervalsById . put ( interval . getId ( ) , interval ) ; intervalsByName . put ( interval . getName ( ) , interval ) ; for ( IntervalRegistryListener listener : registryListeners ) { listener . intervalCreated ( interval ) ; } interval . addSecondaryIntervalListener ( new IIntervalListener ( ) { public void intervalUpdated ( Interval aCaller ) { intervalUpdateTimestamp . put ( aCaller . getName ( ) , System . currentTimeMillis ( ) ) ; } } ) ; return interval ; }
This method creates a new Interval with the given name and length .
37,791
public Long getUpdateTimestamp ( String intervalName ) { return intervalName == null ? Long . valueOf ( 0 ) : intervalUpdateTimestamp . get ( intervalName ) ; }
Returns last update timestamp of an interval by name .
37,792
public Object aroundInvoke ( InvocationContext ctx ) throws Throwable { final Method method = ctx . getMethod ( ) ; final Count annotation = getAnnotationFromContext ( ctx , Count . class ) ; final CountParameter parameter = method . getAnnotation ( CountParameter . class ) ; final String producerId = annotation . producerId ( ) . isEmpty ( ) ? method . getDeclaringClass ( ) . getSimpleName ( ) : annotation . producerId ( ) ; final String caseName = ( parameter != null && ! parameter . value ( ) . isEmpty ( ) ) ? parameter . value ( ) : method . getName ( ) ; final OnDemandStatsProducer onDemandProducer = getProducer ( method . getDeclaringClass ( ) , producerId , annotation . category ( ) , annotation . subsystem ( ) , false ) ; if ( onDemandProducer != null ) { final CounterStats defaultStats = getDefaultStats ( onDemandProducer ) ; final CounterStats stats = getStats ( onDemandProducer , caseName ) ; if ( defaultStats != null ) defaultStats . inc ( ) ; if ( stats != null ) stats . inc ( ) ; } return proceed ( ctx ) ; }
Around method invoke .
37,793
public void update ( ) { if ( tieable . isActivated ( ) ) { return ; } for ( IStats s : producer . getStats ( ) ) { if ( s . getName ( ) . equals ( tieable . getTargetStatName ( ) ) ) { tieable . tieToStats ( s ) ; tieable . update ( ) ; return ; } } }
Called whenever the appropriate interval has passed and the stats should be updated .
37,794
public ThresholdStatus getWorstStatus ( ) { if ( configuration . getKillSwitch ( ) . disableMetricCollection ( ) ) return ThresholdStatus . OFF ; ThresholdStatus ret = ThresholdStatus . GREEN ; for ( Threshold t : getThresholds ( ) ) { if ( t . getStatus ( ) . overrules ( ret ) ) ret = t . getStatus ( ) ; } return ret ; }
Returns the worst threshold status in the system .
37,795
public ThresholdStatus getWorstStatus ( List < String > names ) { if ( configuration . getKillSwitch ( ) . disableMetricCollection ( ) ) return ThresholdStatus . OFF ; ThresholdStatus ret = ThresholdStatus . GREEN ; for ( Threshold t : getThresholds ( ) ) { if ( names . indexOf ( t . getName ( ) ) == - 1 ) continue ; if ( t . getStatus ( ) . overrules ( ret ) ) ret = t . getStatus ( ) ; } return ret ; }
Returns the worst threshold status in the system for given threshold names .
37,796
private void readConfig ( ) { configuration = MoskitoConfigurationHolder . getConfiguration ( ) ; ThresholdsConfig config = configuration . getThresholdsConfig ( ) ; ThresholdConfig [ ] tcs = config . getThresholds ( ) ; if ( tcs != null && tcs . length > 0 ) { for ( ThresholdConfig tc : tcs ) { ThresholdDefinition td = new ThresholdDefinition ( ) ; td . setName ( tc . getName ( ) ) ; td . setIntervalName ( tc . getIntervalName ( ) ) ; td . setProducerName ( tc . getProducerName ( ) ) ; td . setStatName ( tc . getStatName ( ) ) ; td . setTimeUnit ( TimeUnit . valueOf ( tc . getTimeUnit ( ) ) ) ; td . setValueName ( tc . getValueName ( ) ) ; Threshold newThreshold = createThreshold ( td ) ; GuardConfig [ ] guards = tc . getGuards ( ) ; if ( guards != null && guards . length > 0 ) { boolean hasDots = false ; for ( GuardConfig guard : guards ) { hasDots |= hasDots ( guard . getValue ( ) ) ; } for ( GuardConfig guard : guards ) { newThreshold . addGuard ( hasDots ? new DoubleBarrierPassGuard ( ThresholdStatus . valueOf ( guard . getStatus ( ) ) , Double . parseDouble ( guard . getValue ( ) ) , GuardedDirection . valueOf ( guard . getDirection ( ) ) ) : new LongBarrierPassGuard ( ThresholdStatus . valueOf ( guard . getStatus ( ) ) , Long . parseLong ( guard . getValue ( ) ) , GuardedDirection . valueOf ( guard . getDirection ( ) ) ) ) ; } } } } }
Reads the config and creates configured thresholds . For now this method is only executed on startup .
37,797
private void readMemory ( ) { long space ; try { space = root . getUsableSpace ( ) ; } catch ( IOException e ) { log . error ( "Querying space. Querying error: " + e . toString ( ) ) ; return ; } stats . updateMemoryValue ( space ) ; }
Reads the memory value from the resolver and updates internal stats .
37,798
public static < T > void registerPluginType ( String pluginType , StatsFactory statsFactory , StatusFetcherFactory < T > statusFetcherFactory , StatusParser < T , StatusData > parser ) { PluginTypeConfiguration conf = new PluginTypeConfiguration < > ( statsFactory , statusFetcherFactory , parser ) ; PluginTypeConfiguration previous = registry . putIfAbsent ( pluginType , conf ) ; if ( previous != null ) { getLogger ( ) . warn ( "Registry already have mapping for plugin type '" + pluginType + "'!" ) ; } }
Register plugin type and associate given factories with it .
37,799
public static AlertBean create ( AlertType type , String message ) { AlertBean result = new AlertBean ( type , message ) ; result . setAnimate ( false ) ; result . setFullWidth ( true ) ; result . setRoundBorders ( false ) ; return result ; }
Creates default alert without animation with square borders and full width .