idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
37,800
public static HttpResponse getHttpResponse ( String url , UsernamePasswordCredentials credentials ) throws IOException { HttpGet request = new HttpGet ( url ) ; if ( credentials != null ) { URI uri = request . getURI ( ) ; AuthScope authScope = new AuthScope ( uri . getHost ( ) , uri . getPort ( ) ) ; Credentials cached = httpClient . getCredentialsProvider ( ) . getCredentials ( authScope ) ; if ( ! areSame ( cached , credentials ) ) { httpClient . getCredentialsProvider ( ) . setCredentials ( authScope , credentials ) ; } } return httpClient . execute ( request ) ; }
Executes a request using the given URL and credentials .
37,801
private static boolean areSame ( Credentials c1 , Credentials c2 ) { if ( c1 == null ) { return c2 == null ; } else { return StringUtils . equals ( c1 . getUserPrincipal ( ) . getName ( ) , c1 . getUserPrincipal ( ) . getName ( ) ) && StringUtils . equals ( c1 . getPassword ( ) , c1 . getPassword ( ) ) ; } }
Compare two instances of Credentials .
37,802
public static String getResponseContent ( HttpResponse response ) throws IOException { final HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { try { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; entity . writeTo ( out ) ; return isScOk ( response ) ? new String ( out . toByteArray ( ) , Charset . forName ( "UTF-8" ) ) : null ; } finally { EntityUtils . consume ( entity ) ; } } else { return null ; } }
Get text content from the response if response status code is 200 .
37,803
public ThresholdConfig toConfigObject ( ) { ThresholdConfig ret = new ThresholdConfig ( ) ; ret . setIntervalName ( getDefinition ( ) . getIntervalName ( ) ) ; ret . setName ( getDefinition ( ) . getName ( ) ) ; ret . setProducerName ( getDefinition ( ) . getProducerName ( ) ) ; ret . setStatName ( getDefinition ( ) . getStatName ( ) ) ; ret . setValueName ( getDefinition ( ) . getValueName ( ) ) ; ret . setTimeUnit ( getDefinition ( ) . getTimeUnit ( ) . name ( ) ) ; return ret ; }
This method allows to recreate proper configuration object for this threshold .
37,804
public TraceStep startStep ( String call , IStatsProducer producer , String methodName ) { TraceStep last = current ; current = new TraceStep ( call , producer , methodName ) ; if ( last != null ) last . addChild ( current ) ; return current ; }
Creates a new sub step in current call .
37,805
public int getNumberOfSteps ( ) { int result = 0 ; final Queue < TraceStep > queue = new LinkedList < > ( ) ; queue . add ( root ) ; while ( ! queue . isEmpty ( ) ) { final TraceStep currentTraceStep = queue . poll ( ) ; result ++ ; final List < TraceStep > children = currentTraceStep . getChildren ( ) ; if ( ! children . isEmpty ( ) ) { queue . addAll ( children ) ; } } return result ; }
Calculates the number of steps .
37,806
public void dumpOut ( ) { System . out . println ( this . toString ( ) ) ; TraceStep root = getRootStep ( ) ; dumpOut ( root , 1 ) ; }
This is a debug method used to dump out the call into stdout .
37,807
private static void init ( ) { String junittest = System . getProperty ( "JUNITTEST" ) ; if ( junittest != null && ( junittest . equalsIgnoreCase ( "true" ) ) ) return ; StartBuiltInProducers . startbuiltin ( ) ; PluginRepository . getInstance ( ) ; AccumulatorRepository . getInstance ( ) ; ThresholdRepository . getInstance ( ) ; }
Initializes the registry . If we are not in junit mode start built - in producers .
37,808
public void disableAll ( ) { javaMemoryProducers = javaMemoryPoolProducers = javaThreadingProducers = osProducer = runtimeProducer = mbeanProducers = gcProducer = errorProducer = false ; }
this method is for unit - test .
37,809
protected String getForward ( HttpServletRequest req ) { String forward = req . getParameter ( PARAM_FORWARD ) ; if ( forward == null ) forward = DEFAULT_FORWARD ; return forward ; }
Returns the specified forward .
37,810
protected String getCurrentInterval ( HttpServletRequest req , boolean saveToSession ) { String intervalParameter = req . getParameter ( PARAM_INTERVAL ) ; String interval = intervalParameter ; if ( interval == null ) { interval = ( String ) req . getSession ( ) . getAttribute ( BEAN_INTERVAL ) ; if ( interval == null ) interval = DEFAULT_INTERVAL ; } if ( intervalParameter != null && saveToSession ) req . getSession ( ) . setAttribute ( BEAN_INTERVAL , interval ) ; return interval ; }
Returns the currently selected interval either as parameter or from session .
37,811
protected UnitBean getCurrentUnit ( HttpServletRequest req , boolean saveToSession ) { String unitParameter = req . getParameter ( PARAM_UNIT ) ; if ( unitParameter == null ) { UnitBean ret = ( UnitBean ) req . getSession ( ) . getAttribute ( BEAN_UNIT ) ; if ( ret == null ) { ret = DEFAULT_UNIT_BEAN ; req . getSession ( ) . setAttribute ( BEAN_UNIT , ret ) ; } return ret ; } int index = - 1 ; for ( int i = 0 ; i < AVAILABLE_UNITS_LIST . size ( ) ; i ++ ) { if ( AVAILABLE_UNITS_LIST . get ( i ) . getUnitName ( ) . equalsIgnoreCase ( unitParameter ) ) { index = i ; break ; } } UnitBean ret = index == - 1 ? DEFAULT_UNIT_BEAN : AVAILABLE_UNITS [ index ] ; if ( saveToSession ) req . getSession ( ) . setAttribute ( BEAN_UNIT , ret ) ; return ret ; }
Returns the currently selected unit either from request or session .
37,812
private void fetchRemoteConnectionFromUrl ( HttpServletRequest req ) { String connection = req . getParameter ( "remoteConnection" ) ; if ( connection != null ) try { connection = URLDecoder . decode ( connection , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { return ; } else return ; String [ ] remoteHostAndPort ; if ( ( remoteHostAndPort = connection . split ( ":" ) ) . length == 2 ) { String remoteHost = remoteHostAndPort [ 0 ] ; int remotePort ; try { remotePort = Integer . valueOf ( remoteHostAndPort [ 1 ] ) ; } catch ( NumberFormatException e ) { return ; } try { if ( ! APILookupUtility . isLocal ( ) && APILookupUtility . getCurrentRemoteInstance ( ) . equalsByKey ( remoteHost + '-' + remotePort ) ) return ; } catch ( IllegalStateException ignored ) { } RemoteInstance newRemoteInstance = new RemoteInstance ( ) ; newRemoteInstance . setHost ( remoteHost ) ; newRemoteInstance . setPort ( remotePort ) ; WebUIConfig . getInstance ( ) . addRemote ( newRemoteInstance ) ; APILookupUtility . setCurrentConnectivityMode ( ConnectivityMode . REMOTE ) ; APILookupUtility . setCurrentRemoteInstance ( newRemoteInstance ) ; } }
Acquire remote connection url from request parameter . If current user is not connected to application from url - moskito will be connected to this application . This made up for possibility to share links on moskito - inspect pages .
37,813
protected String rebuildQueryStringWithoutParameter ( String source , String ... params ) { if ( source == null || source . length ( ) == 0 ) return "" ; if ( params == null || params . length == 0 ) return source ; HashSet < String > paramsSet = new HashSet < String > ( params . length ) ; paramsSet . addAll ( Arrays . asList ( params ) ) ; String [ ] tokens = StringUtils . tokenize ( source , '&' ) ; StringBuilder ret = new StringBuilder ( ) ; for ( String t : tokens ) { String [ ] values = StringUtils . tokenize ( t , '=' ) ; if ( paramsSet . contains ( values [ 0 ] ) ) continue ; if ( ret . length ( ) > 0 ) ret . append ( '&' ) ; ret . append ( values [ 0 ] ) . append ( '=' ) . append ( values . length >= 2 ? values [ 1 ] : "" ) ; } return ret . toString ( ) ; }
Rebuilds query string from source .
37,814
private void checkNavigationMenuState ( final HttpServletRequest req ) { if ( req == null ) return ; if ( req . getSession ( ) . getAttribute ( ATTR_IS_NAV_MENU_COLLAPSED ) != null ) return ; req . getSession ( ) . setAttribute ( ATTR_IS_NAV_MENU_COLLAPSED , false ) ; }
Check if navigation menu default state present in request . If there is no state set default value .
37,815
protected void setInfoMessage ( String message ) { try { APICallContext . getCallContext ( ) . getCurrentSession ( ) . setAttribute ( "infoMessage" , APISession . POLICY_FLASH , message ) ; } catch ( NullPointerException e ) { log . error ( "Can't set info message (flash) due" , e ) ; log . error ( "APICallContext: " + APICallContext . getCallContext ( ) ) ; if ( APICallContext . getCallContext ( ) != null ) { log . error ( "Current Session: " + APICallContext . getCallContext ( ) . getCurrentSession ( ) ) ; } } }
Sets an info message that can be shown on next screen . The info message is readable exactly once .
37,816
protected String getInfoMessage ( ) { try { return ( String ) APICallContext . getCallContext ( ) . getCurrentSession ( ) . getAttribute ( "infoMessage" ) ; } catch ( Exception any ) { return null ; } }
Returns a previously set info message or null if no message has been set .
37,817
public synchronized void updateProducer ( PHPProducerDTO producerDTO ) { Mapper mapper = mappersRegistry . getMapper ( producerDTO . getMapperId ( ) ) ; if ( mapper == null ) { log . error ( "Mapper with id " + producerDTO . getMapperId ( ) + " is not found to map producer " + producerDTO . getProducerId ( ) ) ; return ; } try { mapper . mapProducer ( producerRegistry , producerDTO ) ; } catch ( MappingException e ) { log . error ( "Failed to process producer data with producer id " + producerDTO . getProducerId ( ) + " because mapper throws an exception" , e ) ; } }
Processes incoming producer data .
37,818
public void init ( ServletConfig config ) throws ServletException { super . init ( config ) ; getStats = new ServletStats ( "get" , getMonitoringIntervals ( ) ) ; postStats = new ServletStats ( "post" , getMonitoringIntervals ( ) ) ; putStats = new ServletStats ( "put" , getMonitoringIntervals ( ) ) ; headStats = new ServletStats ( "head" , getMonitoringIntervals ( ) ) ; optionsStats = new ServletStats ( "options" , getMonitoringIntervals ( ) ) ; traceStats = new ServletStats ( "trace" , getMonitoringIntervals ( ) ) ; deleteStats = new ServletStats ( "delete" , getMonitoringIntervals ( ) ) ; lastModifiedStats = new ServletStats ( "lastModified" , getMonitoringIntervals ( ) ) ; cachedStatList = new ArrayList < IStats > ( useShortStatList ( ) ? 2 : 8 ) ; cachedStatList . add ( getStats ) ; cachedStatList . add ( postStats ) ; if ( ! useShortStatList ( ) ) { cachedStatList . add ( deleteStats ) ; cachedStatList . add ( headStats ) ; cachedStatList . add ( optionsStats ) ; cachedStatList . add ( putStats ) ; cachedStatList . add ( traceStats ) ; cachedStatList . add ( lastModifiedStats ) ; } ProducerRegistryFactory . getProducerRegistryInstance ( ) . registerProducer ( this ) ; }
Creates the stats objects . Registers the servlet at the ProducerRegistry .
37,819
protected void moskitoDoDelete ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doDelete ( req , res ) ; }
Override this method to react on http delete method .
37,820
protected void moskitoDoGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doGet ( req , res ) ; }
Override this method to react on http get method .
37,821
protected void moskitoDoHead ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doHead ( req , res ) ; }
Override this method to react on http head method .
37,822
protected void moskitoDoOptions ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doOptions ( req , res ) ; }
Override this method to react on http options method .
37,823
protected void moskitoDoPost ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doPost ( req , res ) ; }
Override this method to react on http post method .
37,824
protected void moskitoDoPut ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doPut ( req , res ) ; }
Override this method to react on http put method .
37,825
protected void moskitoDoTrace ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { super . doTrace ( req , res ) ; }
Override this method to react on http trace method .
37,826
private void updateStats ( ) { EhcacheStats stats = getProducerStats ( ) ; Statistics statistics = underlyingCache . getStatistics ( ) ; double accesses = statistics . getCacheHits ( ) + statistics . getCacheMisses ( ) ; double hitRatio = accesses != 0 ? statistics . getCacheHits ( ) / accesses : 0 ; stats . getStatisticsAccuracy ( ) . setValueAsString ( statistics . getStatisticsAccuracyDescription ( ) ) ; stats . getHitRatio ( ) . setValueAsDouble ( hitRatio ) ; stats . getHits ( ) . setValueAsLong ( statistics . getCacheHits ( ) ) ; stats . getMisses ( ) . setValueAsLong ( statistics . getCacheMisses ( ) ) ; stats . getElements ( ) . setValueAsLong ( statistics . getObjectCount ( ) ) ; stats . getInMemoryHits ( ) . setValueAsLong ( statistics . getInMemoryHits ( ) ) ; stats . getInMemoryMisses ( ) . setValueAsLong ( statistics . getInMemoryMisses ( ) ) ; stats . getInMemoryElements ( ) . setValueAsLong ( statistics . getMemoryStoreObjectCount ( ) ) ; stats . getOnDiskHits ( ) . setValueAsLong ( statistics . getOnDiskHits ( ) ) ; stats . getOnDiskMisses ( ) . setValueAsLong ( statistics . getOnDiskMisses ( ) ) ; stats . getOnDiskElements ( ) . setValueAsLong ( statistics . getDiskStoreObjectCount ( ) ) ; stats . getOffHeapHits ( ) . setValueAsLong ( statistics . getOffHeapHits ( ) ) ; stats . getOffHeapMisses ( ) . setValueAsLong ( statistics . getOffHeapMisses ( ) ) ; stats . getOffHeapElements ( ) . setValueAsLong ( statistics . getOffHeapStoreObjectCount ( ) ) ; stats . getAverageGetTime ( ) . setValueAsDouble ( statistics . getAverageGetTime ( ) ) ; stats . getAverageSearchTime ( ) . setValueAsLong ( statistics . getAverageSearchTime ( ) ) ; stats . getSearchesPerSecond ( ) . setValueAsLong ( statistics . getSearchesPerSecond ( ) ) ; stats . getEvictionCount ( ) . setValueAsLong ( statistics . getEvictionCount ( ) ) ; stats . getWriterQueueLength ( ) . setValueAsLong ( statistics . getWriterQueueSize ( ) ) ; }
Updates internal producer s stats using Ehcache statistics .
37,827
private void populateStats ( final StatDecoratorBean statDecoratorBean , final List < StatLineAO > allStatLines , final StatBeanSortType sortType ) { if ( allStatLines == null || allStatLines . isEmpty ( ) ) { LOGGER . warn ( "Producer's stats are empty" ) ; return ; } final int cumulatedIndex = getCumulatedIndex ( allStatLines ) ; int allStatLinesSize = allStatLines . size ( ) ; final List < StatBean > statBeans = new ArrayList < > ( allStatLinesSize ) ; for ( int i = 0 ; i < allStatLinesSize ; i ++ ) { if ( i == cumulatedIndex ) continue ; final StatLineAO line = allStatLines . get ( i ) ; final List < StatValueAO > statValues = line . getValues ( ) ; final StatBean statBean = new StatBean ( ) ; statBean . setName ( line . getStatName ( ) ) ; statBean . setValues ( statValues ) ; statBeans . add ( statBean ) ; } StaticQuickSorter . sort ( statBeans , sortType ) ; statDecoratorBean . setStats ( statBeans ) ; }
Allows to set all stats to decorator except cumulated stat . Stats will be sorted using given sort type .
37,828
private void populateGraphData ( final IDecorator decorator , final Map < String , GraphDataBean > graphData , final List < StatLineAO > allStatLines ) { final int cumulatedIndex = getCumulatedIndex ( allStatLines ) ; for ( int i = 0 ; i < allStatLines . size ( ) ; i ++ ) { if ( i == cumulatedIndex ) continue ; final StatLineAO line = allStatLines . get ( i ) ; final List < StatValueAO > statValues = line . getValues ( ) ; for ( StatValueAO statValue : statValues ) { final String graphKey = decorator . getName ( ) + '_' + statValue . getName ( ) ; final GraphDataValueBean value = new GraphDataValueBean ( line . getStatName ( ) , statValue . getRawValue ( ) ) ; final GraphDataBean graphDataBean = graphData . get ( graphKey ) ; if ( graphDataBean != null ) graphDataBean . addValue ( value ) ; } } }
Allows to populate graph data .
37,829
private int getCumulatedIndex ( final List < StatLineAO > allStatLines ) { if ( allStatLines == null || allStatLines . isEmpty ( ) ) { return - 1 ; } int cumulatedIndex = - 1 ; for ( int i = 0 , allStatLinesSize = allStatLines . size ( ) ; i < allStatLinesSize ; i ++ ) { final StatLineAO statLine = allStatLines . get ( i ) ; if ( CUMULATED_STAT_NAME_VALUE . equals ( statLine . getStatName ( ) ) ) { cumulatedIndex = i ; break ; } } return cumulatedIndex ; }
Returns index of cumulated stat in producer s stats .
37,830
protected final T getDefaultStats ( OnDemandStatsProducer producer ) { try { return getStatsClass ( ) . cast ( producer . getDefaultStats ( ) ) ; } catch ( ClassCastException e ) { LOGGER . error ( "getDefaultStats(): Unexpected stats type" , e ) ; return null ; } }
Returns default stats for producer .
37,831
protected final T getStats ( OnDemandStatsProducer producer , String name ) { try { return getStatsClass ( ) . cast ( producer . getStats ( name ) ) ; } catch ( ClassCastException e ) { LOGGER . error ( "getStats(): Unexpected stats type" , e ) ; } catch ( OnDemandStatsProducerException e ) { LOGGER . error ( "getStats(): Failed to get stats for name=" + name , e ) ; } return null ; }
Returns stats for producer .
37,832
protected static Object proceed ( InvocationContext ctx ) throws Throwable { try { return ctx . proceed ( ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } }
Proceed further .
37,833
private void createAccumulator ( String producerId , Accumulate annotation , String accName , String statsName ) { if ( annotation != null && producerId != null && ! producerId . isEmpty ( ) && accName != null && ! accName . isEmpty ( ) && statsName != null && ! statsName . isEmpty ( ) ) { AccumulatorDefinition definition = new AccumulatorDefinition ( ) ; if ( annotation . name ( ) . length ( ) > 0 ) { definition . setName ( annotation . name ( ) ) ; } else { definition . setName ( accName ) ; } definition . setIntervalName ( annotation . intervalName ( ) ) ; definition . setProducerName ( producerId ) ; definition . setStatName ( statsName ) ; definition . setValueName ( annotation . valueName ( ) ) ; definition . setTimeUnit ( annotation . timeUnit ( ) ) ; AccumulatorRepository . getInstance ( ) . createAccumulator ( definition ) ; } }
Create accumulator and register it .
37,834
private String getMethodName ( Method method ) { StatName statNameAnnotation = method . getAnnotation ( StatName . class ) ; return statNameAnnotation != null ? statNameAnnotation . value ( ) : method . getName ( ) ; }
Returns name of the given method .
37,835
public void addProducerCall ( String producerId , long duration ) { AnalyzedProducerCallsAO bean = beans . get ( producerId ) ; if ( bean == null ) { bean = new AnalyzedProducerCallsAO ( producerId ) ; beans . put ( producerId , bean ) ; } bean . addCall ( duration ) ; totalCalls ++ ; totalDuration += duration ; }
Adds a new producer call . The duration and the number of calls for each producer will be increased accordingly .
37,836
public static String getInputStreamAsString ( InputStream is ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ReadableByteChannel rbch = Channels . newChannel ( is ) ; WritableByteChannel wbch = Channels . newChannel ( baos ) ; fastChannelCopy ( rbch , wbch ) ; rbch . close ( ) ; wbch . close ( ) ; return new String ( baos . toByteArray ( ) , Charset . forName ( "UTF-8" ) ) ; }
converts input stream to string value
37,837
private void rebuildProducerCache ( Collection < IStatsProducer > producers ) { log . debug ( "Rebuilding producer cache with " + producers . size ( ) + " producers." ) ; log . debug ( "Following producers known: " + producers ) ; synchronized ( cacheLock ) { final int approxSize = ( int ) ( producers . size ( ) * 1.5 ) ; _cachedProducerList = new ArrayList < ProducerReference > ( approxSize ) ; _cachedProducerMap = new HashMap < String , ProducerReference > ( approxSize ) ; for ( IStatsProducer sp : producers ) { final ProducerReference reference = new ProducerReference ( sp ) ; _cachedProducerList . add ( reference ) ; _cachedProducerMap . put ( sp . getProducerId ( ) , reference ) ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( "Cachedproducer list contains " + _cachedProducerList . size ( ) + " producers: " ) ; log . debug ( String . valueOf ( _cachedProducerList ) ) ; log . debug ( "Cached producer map contains: " + _cachedProducerMap . size ( ) + " producers" ) ; log . debug ( String . valueOf ( _cachedProducerMap ) ) ; } }
Rebuilds the caches with given producers ..
37,838
public List < IStatsProducer > getAllProducers ( ) { if ( _cachedProducerList == null ) buildProducerCacheFromScratch ( ) ; List < IStatsProducer > ret = new ArrayList < > ( ) ; for ( ProducerReference pr : _cachedProducerList ) { if ( pr . get ( ) != null ) ret . add ( pr . get ( ) ) ; } return ret ; }
producer during processing .
37,839
private void createIntervalList ( ) { synchronized ( intervalLock ) { if ( _cachedIntervalInfos != null ) return ; List < Interval > intervals = intervalRegistry . getIntervals ( ) ; _cachedIntervalInfos = new ArrayList < IntervalInfo > ( intervals . size ( ) ) ; for ( Interval interval : intervals ) { _cachedIntervalInfos . add ( new IntervalInfo ( interval ) ) ; interval . addSecondaryIntervalListener ( this ) ; } } }
Creates the list of existing intervals .
37,840
public void update ( long aRequestCount , long aMaxTime , long aBytesReceived , long aBytesSent , long aProcessingTime , long aErrorCount ) { requestCount . setValueAsLong ( aRequestCount ) ; maxTime . setValueAsLong ( aMaxTime ) ; bytesReceived . setValueAsLong ( aBytesReceived ) ; bytesSent . setValueAsLong ( aBytesSent ) ; processingTime . setValueAsLong ( aProcessingTime ) ; errorCount . setValueAsLong ( aErrorCount ) ; }
Updates stats .
37,841
void reset ( ) { cleanup ( ) ; listeners . clear ( ) ; registry . clear ( ) ; String junittest = System . getProperty ( "JUNITTEST" ) ; if ( junittest != null && junittest . equalsIgnoreCase ( "true" ) ) return ; addListener ( new JMXBridgeListener ( ) ) ; }
Resets the impl for unittests .
37,842
public void cleanup ( ) { ArrayList < ProducerReference > producerReferences = new ArrayList < ProducerReference > ( registry . values ( ) ) ; for ( ProducerReference p : producerReferences ) { try { if ( p . get ( ) != null ) unregisterProducer ( p . get ( ) ) ; } catch ( Exception e ) { LOGGER . warn ( "can't unregister producer " + p , e ) ; } } }
This method is primary used for unit tests .
37,843
private static boolean isMBeanRequired ( final ObjectInstance mBean ) { final String domain = mBean . getObjectName ( ) . getDomain ( ) ; final String className = mBean . getClassName ( ) ; return ! domain . startsWith ( "moskito." ) && conf . isMBeanRequired ( domain , className ) ; }
Checks is mbean required to be registered as producer
37,844
public static void buildProducers ( ) { DecoratorRegistryFactory . getDecoratorRegistry ( ) . addDecorator ( MBeanStats . class , new GeneralMBeanDecorator ( ) ) ; for ( MBeanServer server : MBeanServerFactory . findMBeanServer ( null ) ) for ( final ObjectInstance mBean : server . queryMBeans ( null , null ) ) if ( isMBeanRequired ( mBean ) ) { SimpleStatsProducer < MBeanStats > producer = buildProducer ( server , mBean ) ; if ( producer != null ) { producerRegistry . registerProducer ( producer ) ; log . debug ( "Registered new producer for " + mBean . getObjectName ( ) . getCanonicalName ( ) + "mbean" ) ; } } }
Builds all mbean producer that required by mbean producers configuration .
37,845
public static < T > T createInstance ( T impl , String name , String category , String subsystem , IOnDemandCallHandler handler , IOnDemandStatsFactory < ? extends IStats > statsFactory , boolean attachLoggers , Class < T > interf , Class < ? > ... additionalInterfaces ) { if ( name == null ) name = extractName ( interf ) ; Class < ? > [ ] interfacesParameter = mergeInterfaces ( interf , additionalInterfaces ) ; @ SuppressWarnings ( "unchecked" ) final MoskitoInvokationProxy proxy = new MoskitoInvokationProxy ( impl , handler , statsFactory , name + '-' + getInstanceCounter ( name ) , category , subsystem , interfacesParameter ) ; @ SuppressWarnings ( "unchecked" ) T ret = ( T ) proxy . createProxy ( ) ; if ( attachLoggers ) { LoggerUtil . createSLF4JDefaultAndIntervalStatsLogger ( proxy . getProducer ( ) ) ; } return ret ; }
Creates a new proxied instance for an existing implementation .
37,846
public static < T > T createServiceInstance ( T impl , String category , String subsystem , Class < T > interf , Class < ? > ... additionalInterfaces ) { return createServiceInstance ( impl , null , category , subsystem , interf , additionalInterfaces ) ; }
Shortcut method to create service instance . Creates an instance with service interface name as instance name custom category and subsystem ServiceStatsCallHandler and ServiceStatsFactory .
37,847
private static String extractName ( Class < ? > clazz ) { String name = clazz . getName ( ) ; if ( name == null ) name = "" ; int indexOfDot = name . lastIndexOf ( '.' ) ; return indexOfDot == - 1 ? name : name . substring ( indexOfDot + 1 ) ; }
Internal method which extracts name of the service out of it class . net . java . dev . moskito . core . dynamic . ProxyUtils - > ProxyUtils .
37,848
private Object parseValue ( String value ) { try { return Double . valueOf ( value ) ; } catch ( NumberFormatException ignored ) { } if ( value . equals ( "true" ) || value . equals ( "false" ) ) return Boolean . valueOf ( value ) ; throw new IllegalArgumentException ( "Only number or boolean stats values allowed" ) ; }
Helper method to parse string representation of value item to number or boolean type
37,849
public void addConsumer ( SnapshotConsumer consumer ) { if ( consumers . contains ( consumer ) ) consumers . remove ( consumer ) ; consumers . add ( consumer ) ; }
Adds a new snapshot consumer .
37,850
static final int guessLengthFromName ( String aName ) { if ( aName . startsWith ( Constants . PREFIX_SNAPSHOT_INTERVAL ) ) return - 1 ; int unitFactor ; int value ; try { value = Integer . parseInt ( aName . substring ( 0 , aName . length ( ) - 1 ) ) ; } catch ( NumberFormatException e ) { throw new UnknownIntervalLengthException ( "Unsupported Interval name format: " + aName ) ; } char lastChar = aName . charAt ( aName . length ( ) - 1 ) ; TimeUnit unit = lookupMap . get ( Character . toLowerCase ( lastChar ) ) ; if ( unit == null ) throw new UnknownIntervalLengthException ( aName + ", " + lastChar + " is not a supported unit." ) ; unitFactor = unit . getFactor ( ) ; if ( value == 0 ) throw new UnknownIntervalLengthException ( aName + ", zero duration is not allowed." ) ; return value * unitFactor ; }
This method parses the given Interval name and returns the length of such an Interval in seconds .
37,851
protected static < T extends GenericMetrics > List < T > getMetricsOfType ( Class < T > type ) { List < T > metricsList = ( List < T > ) registry . get ( type ) ; if ( metricsList == null ) { metricsList = new CopyOnWriteArrayList < > ( ) ; List < T > previous = ( List < T > ) registry . putIfAbsent ( type , metricsList ) ; if ( previous != null ) metricsList = previous ; } return metricsList ; }
Get all registered metrics of given Class .
37,852
public String getAccumulatorColor ( final String accumulatorName ) { if ( StringUtils . isEmpty ( accumulatorName ) ) throw new IllegalArgumentException ( "accumulatorName is null" ) ; if ( accumulatorsColors == null || accumulatorsColors . length == 0 ) return null ; for ( AccumulatorGraphColor accumulator : accumulatorsColors ) { if ( accumulatorName . equals ( accumulator . getName ( ) ) ) return accumulator . getColor ( ) ; } return null ; }
Returns accumulator color by given accumulator name .
37,853
public String registerMBean ( Object bean , String name , boolean replace ) throws MalformedObjectNameException , NotCompliantMBeanException , MBeanRegistrationException { synchronized ( mBeanServer ) { ObjectName newBeanName = null ; try { newBeanName = new ObjectName ( name ) ; beansNames . add ( newBeanName ) ; mBeanServer . registerMBean ( bean , newBeanName ) ; return name ; } catch ( InstanceAlreadyExistsException e ) { beansNames . remove ( newBeanName ) ; if ( replace ) { unregisterMBean ( name ) ; return registerMBean ( bean , name , true ) ; } else return registerMBean ( bean , resolveDuplicateName ( name ) ) ; } } }
Registers MBean in local MBean server .
37,854
public boolean unregisterMBean ( String name ) throws MBeanRegistrationException { synchronized ( mBeanServer ) { ObjectName toRemoveName ; try { toRemoveName = new ObjectName ( name ) ; } catch ( MalformedObjectNameException e ) { return false ; } beansNames . remove ( toRemoveName ) ; try { mBeanServer . unregisterMBean ( toRemoveName ) ; return true ; } catch ( InstanceNotFoundException e ) { return false ; } } }
Unregisters MBean from platform MBean server .
37,855
public void cleanup ( ) { synchronized ( mBeanServer ) { for ( ObjectName beanName : beansNames ) try { mBeanServer . unregisterMBean ( beanName ) ; } catch ( InstanceNotFoundException ignored ) { } catch ( MBeanRegistrationException e ) { log . warn ( "Exception thrown while trying to clean up registered MBeans" , e ) ; } } }
Unregisters all beans that been registered by this utility object .
37,856
@ Path ( "/{name}" ) public ReplyObject getDashboard ( @ PathParam ( "name" ) String name ) { try { ReplyObject ret = ReplyObject . success ( ) ; DashboardAO dashboard = getDashboardAPI ( ) . getDashboard ( name ) ; ret . addResult ( "dashboard" , dashboard ) ; return ret ; } catch ( APIException e ) { return ReplyObject . error ( e . getMessage ( ) ) ; } }
Returns a dashboard by its name .
37,857
private void readThreads ( ) { long [ ] ids = threadMxBean . getAllThreadIds ( ) ; Map < Thread . State , Long > count = new EnumMap < > ( Thread . State . class ) ; for ( int i = 0 ; i < ids . length ; i ++ ) { long id = ids [ i ] ; ThreadInfo info = threadMxBean . getThreadInfo ( id ) ; if ( info != null ) { Thread . State state = info . getThreadState ( ) ; Long old = count . get ( state ) ; if ( old == null ) { old = 0L ; } count . put ( state , old + 1 ) ; } } long total = 0 ; for ( Map . Entry < Thread . State , ThreadStateStats > entry : statsMap . entrySet ( ) ) { Long c = count . get ( entry . getKey ( ) ) ; entry . getValue ( ) . updateCurrentValue ( c == null ? 0 : c . longValue ( ) ) ; if ( c != null ) total += c . longValue ( ) ; } cumulated . updateCurrentValue ( total ) ; }
Reads and updates the thread info .
37,858
private String getDashboardRestApiUrl ( final HttpServletRequest request , final String dashboardName ) { String contextPath = request . getContextPath ( ) ; if ( contextPath == null ) { contextPath = "" ; } if ( ! contextPath . endsWith ( "/" ) ) { contextPath += "/" ; } return contextPath + "moskito-inspect-rest/dashboards/" + dashboardName ; }
Creates Dashboard REST API url for given dashboard . Used at UI .
37,859
private long getDashboardRefreshRate ( final DashboardConfig selectedDashboardConfig ) { if ( selectedDashboardConfig == null ) { return DEFAULT_DASHBOARD_REFRESH_RATE ; } return TimeUnit . SECONDS . toMillis ( selectedDashboardConfig . getRefresh ( ) ) ; }
Returns dashboard refresh rate in ms . Used at UI for refreshing the dashboard .
37,860
private IntervalListener getListener ( String intervalName ) { IntervalListener listener = listeners . get ( intervalName ) ; if ( listener != null ) return listener ; try { Interval interval = IntervalRegistry . getInstance ( ) . getIntervalOnlyIfExisting ( intervalName ) ; listener = new IntervalListener ( ) ; IntervalListener old = listeners . putIfAbsent ( intervalName , listener ) ; if ( old != null ) return old ; interval . addSecondaryIntervalListener ( listener ) ; return listener ; } catch ( UnknownIntervalException e ) { return NoIntervalListener . INSTANCE ; } }
Returns interval listener for the specified interval . If there already was a listener it will be returned otherwise a new one will be created . However if there have been no such interval the interval listener will be substituted for a dummy object and no further action will be taken .
37,861
public void removeTieable ( String name ) { T t = tieables . remove ( name ) ; if ( t == null ) return ; detachFromListener ( t ) ; try { yetUntied . remove ( t ) ; } catch ( Exception e ) { } }
Removes previously added tieable by name .
37,862
@ Around ( value = "execution(* *(..)) && (@annotation(method))" ) public Object doProfilingMethod ( ProceedingJoinPoint pjp , Monitor method ) throws Throwable { return doProfiling ( pjp , method . producerId ( ) , method . subsystem ( ) , method . category ( ) ) ; }
Common method profiling entry - point .
37,863
@ Around ( value = "execution(* *.*(..)) && @within(monitor) && !@annotation(net.anotheria.moskito.aop.annotation.DontMonitor)" ) public Object doProfilingClass ( ProceedingJoinPoint pjp , Monitor monitor ) throws Throwable { return doProfiling ( pjp , monitor . producerId ( ) , monitor . subsystem ( ) , monitor . category ( ) ) ; }
Common class profiling entry - point .
37,864
public void reset ( ) { tags = new HashMap < > ( ) ; errorOccured = new AtomicBoolean ( false ) ; seenErrors = new HashSet < > ( ) ; tracerFired = false ; }
Resets the current context . Especially useful for unit - testing .
37,865
public void addPlugin ( String name , MoskitoPlugin plugin , PluginConfig config ) { plugins . put ( name , plugin ) ; try { plugin . initialize ( ) ; configs . put ( name , config ) ; } catch ( Exception e ) { log . warn ( "couldn't initialize plugin " + name + " - " + plugin + ", removing" , e ) ; plugins . remove ( name ) ; } }
Adds a new loaded plugin .
37,866
public void removePlugin ( String name ) { configs . remove ( name ) ; MoskitoPlugin plugin = plugins . remove ( name ) ; if ( plugin == null ) { log . warn ( "Trying to remove not registered plugin " + name ) ; return ; } try { plugin . deInitialize ( ) ; } catch ( Exception e ) { log . warn ( "Couldn't de-initialize plugin " + name + " - " + plugin , e ) ; } }
Removes a plugin . This call will call deInitialize on the plugin . The plugin is responsible to free all used resources and un - register itself from listening .
37,867
public List < String > getPluginNames ( ) { ArrayList < String > ret = new ArrayList < String > ( plugins . keySet ( ) ) ; return ret ; }
Returns the names of the active plugins .
37,868
public List < MoskitoPlugin > getPlugins ( ) { ArrayList < MoskitoPlugin > ret = new ArrayList < MoskitoPlugin > ( plugins . values ( ) ) ; return ret ; }
Returns all active plugins .
37,869
public TraceStep getLastStep ( ) { TraceStep result = this ; while ( true ) { if ( result . children == null || result . children . size ( ) == 0 ) return result ; result = result . children . get ( result . children . size ( ) - 1 ) ; } }
Returns the last step in this execution .
37,870
public long getNetDuration ( ) { long ret = duration ; for ( TraceStep s : children ) ret -= s . getDuration ( ) ; return ret ; }
Returns the net duration which means total duration minus the duration of all children .
37,871
public void addMemoryUsage ( long memoryUsed ) { totalMemoryUsage . increaseByLong ( memoryUsed ) ; minMemoryUsage . setValueIfLesserThanCurrentAsLong ( memoryUsed ) ; maxMemoryUsage . setValueIfGreaterThanCurrentAsLong ( memoryUsed ) ; }
Adds memory used by script call
37,872
public JSONObject mapColorDataToJSON ( ) { final JSONObject jsonObject = new JSONObject ( ) ; try { jsonObject . put ( "name" , name ) ; jsonObject . put ( "color" , color ) ; } catch ( JSONException e ) { final String message = LogMessageUtil . failMsg ( e ) ; LoggerFactory . getLogger ( AccumulatedSingleGraphAO . class ) . warn ( message , e ) ; } return jsonObject ; }
Maps accumulator s color and name to JSON object .
37,873
public boolean isTracingEnabledForProducer ( String producerId ) { if ( ! MoskitoConfigurationHolder . getConfiguration ( ) . getTracingConfig ( ) . isTracingEnabled ( ) ) return false ; Tracer tracer = tracers . get ( producerId ) ; return tracer != null && tracer . isEnabled ( ) ; }
Returns true if tracing is enabled globally and in particular for this producer .
37,874
public static final StatValue createStatValue ( Object aPattern , String aName , Interval [ ] aIntervals ) { return createStatValue ( StatValueTypeUtility . object2type ( aPattern ) , aName , aIntervals ) ; }
This method creates a new StatValue instance . The new object will be from the same type as the given template object .
37,875
public static TypeAwareStatValue createStatValue ( StatValueTypes aType , String aName , Interval [ ] aIntervals ) { IValueHolderFactory valueHolderFactory = StatValueTypeUtility . createValueHolderFactory ( aType ) ; TypeAwareStatValue value = new TypeAwareStatValueImpl ( aName , aType , valueHolderFactory ) ; for ( int i = 0 ; i < aIntervals . length ; i ++ ) { value . addInterval ( aIntervals [ i ] ) ; } return value ; }
This method creates a StatValue instance .
37,876
protected void preProcessExecute ( ActionMapping mapping , ActionForm af , HttpServletRequest req , HttpServletResponse res ) throws Exception { }
This method allows you to perform some tasks prior to call to the moskitoExecute .
37,877
private void debug ( final HttpServletRequest request ) { if ( ! logger . isInfoEnabled ( ) ) { logger . warn ( "Logger INTO not enabled!" ) ; return ; } logger . info ( HEADERS ) ; Enumeration headerEnumeration = request . getHeaderNames ( ) ; while ( headerEnumeration . hasMoreElements ( ) ) { String elementName = ( String ) headerEnumeration . nextElement ( ) ; logger . info ( elementName + " = " + request . getHeader ( elementName ) ) ; } logger . info ( ATTRIBUTES ) ; Enumeration attributeEnumeration = request . getAttributeNames ( ) ; while ( attributeEnumeration . hasMoreElements ( ) ) { String elementName = ( String ) attributeEnumeration . nextElement ( ) ; logger . info ( elementName + " = " + request . getAttribute ( elementName ) ) ; } logger . info ( PARAMETERS ) ; Map < String , String [ ] > parameterMap = request . getParameterMap ( ) ; for ( Map . Entry < String , String [ ] > entry : parameterMap . entrySet ( ) ) { StringBuilder parameterValues = new StringBuilder ( ) ; if ( entry . getValue ( ) != null ) for ( String value : entry . getValue ( ) ) { parameterValues . append ( value ) ; parameterValues . append ( ' ' ) ; } logger . info ( entry . getKey ( ) + " = " + parameterValues ) ; } HttpSession session = request . getSession ( false ) ; if ( session != null ) { logger . info ( "Session = " + session . getId ( ) ) ; logger . info ( SESSION_ATTRIBUTES ) ; Enumeration sessionAttrEnumeration = session . getAttributeNames ( ) ; while ( sessionAttrEnumeration . hasMoreElements ( ) ) { String elementName = ( String ) sessionAttrEnumeration . nextElement ( ) ; logger . info ( elementName + " = " + session . getAttribute ( elementName ) ) ; } } logger . info ( "Remote ip = " + request . getRemoteAddr ( ) ) ; logger . info ( "Server name = " + request . getServerName ( ) ) ; logger . info ( "Server port = " + request . getServerPort ( ) ) ; }
Dump out to sysOut request parameters .
37,878
public static ReplyObject error ( String message ) { ReplyObject ret = new ReplyObject ( ) ; ret . success = false ; ret . message = message ; return ret ; }
Factory method that creates a new erroneous reply object .
37,879
protected void handleStatsResetIfNeeded ( StatusData < NginxMetrics > status ) { StatValue previousHandled = getStatValue ( NginxMetrics . HANDLED ) ; Long currentHandled = Long . class . cast ( status . get ( NginxMetrics . HANDLED ) ) ; if ( previousHandled != null && currentHandled != null && previousHandled . getValueAsLong ( ) > currentHandled ) { for ( NginxMetrics metric : getAvailableMetrics ( ) ) { if ( metric . getType ( ) == StatValueTypes . DIFFLONG ) { StatValue stat = getStatValue ( metric ) ; if ( stat != null ) stat . reset ( ) ; } } } }
Check HANDLED metric and if its value is lower than the stored one - monitored Nginx server was restarted . In this case all DIFFLONG statValues need resetting .
37,880
private void readConfig ( ) { AccumulatorsConfig config = MoskitoConfigurationHolder . getConfiguration ( ) . getAccumulatorsConfig ( ) ; AccumulatorConfig [ ] acs = config . getAccumulators ( ) ; if ( acs != null && acs . length > 0 ) { for ( AccumulatorConfig ac : acs ) { AccumulatorDefinition ad = new AccumulatorDefinition ( ) ; ad . setName ( ac . getName ( ) ) ; ad . setIntervalName ( ac . getIntervalName ( ) ) ; ad . setProducerName ( ac . getProducerName ( ) ) ; ad . setStatName ( ac . getStatName ( ) ) ; ad . setTimeUnit ( TimeUnit . valueOf ( ac . getTimeUnit ( ) ) ) ; ad . setValueName ( ac . getValueName ( ) ) ; Accumulator acc = createAccumulator ( ad ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Created accumulator " + acc ) ; } } } AutoAccumulatorConfig [ ] autoAccumulatorConfigs = config . getAutoAccumulators ( ) ; if ( autoAccumulatorConfigs != null && autoAccumulatorConfigs . length > 0 ) { for ( AutoAccumulatorConfig aac : autoAccumulatorConfigs ) { AutoAccumulatorDefinition aad = new AutoAccumulatorDefinition ( ) ; aad . setNamePattern ( aac . getNamePattern ( ) ) ; aad . setProducerNamePattern ( aac . getProducerNamePattern ( ) ) ; aad . setIntervalName ( aac . getIntervalName ( ) ) ; aad . setValueName ( aac . getValueName ( ) ) ; aad . setStatName ( aac . getStatName ( ) ) ; aad . setTimeUnit ( TimeUnit . fromString ( aac . getTimeUnit ( ) ) ) ; aad . setAccumulationAmount ( aac . getAccumulationAmount ( ) ) ; autoAccumulatorDefinitions . add ( aad ) ; } } }
Reads the config and creates configured accumulators . For now this method is only executed on startup .
37,881
public static void addThreshold ( String name , String producerName , String statName , String valueName , String intervalName , ThresholdConditionGuard ... guards ) { ThresholdDefinition definition = new ThresholdDefinition ( ) ; definition . setName ( name ) ; definition . setProducerName ( producerName ) ; definition . setStatName ( statName ) ; definition . setValueName ( valueName ) ; definition . setIntervalName ( intervalName ) ; Threshold threshold = ThresholdRepository . getInstance ( ) . createThreshold ( definition ) ; if ( guards != null ) { for ( ThresholdConditionGuard g : guards ) { threshold . addGuard ( g ) ; } } }
Creates a new Threshold and adds it to repository .
37,882
private boolean isAuthorized ( HttpServletRequest request ) { if ( Boolean . TRUE . equals ( request . getSession ( true ) . getAttribute ( AuthConstants . AUTH_SESSION_ATTR_NAME ) ) ) return true ; final AuthApi api = APILookupUtility . getAuthApi ( ) ; if ( request . getCookies ( ) != null ) for ( Cookie cookie : request . getCookies ( ) ) if ( cookie . getName ( ) . equals ( AuthConstants . AUTH_COOKIE_NAME ) ) { try { if ( api . userExists ( cookie . getValue ( ) ) ) { request . getSession ( ) . setAttribute ( AuthConstants . AUTH_SESSION_ATTR_NAME , true ) ; return true ; } } catch ( APIException e ) { log . error ( "Failed to decrypt user authorization cookie" , e ) ; return false ; } } return false ; }
Check is current connection user authorized in moskito - inspect . First checks authorization flag in session attributes . Then tries to find valid authorization cookie if flag not found . If cookie was found - sets authorization flag to true .
37,883
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { if ( ! ( request instanceof HttpServletRequest ) ) { chain . doFilter ( request , response ) ; return ; } HttpServletRequest httpServletRequest = ( ( HttpServletRequest ) request ) ; HttpServletResponse httpServletResponse = ( ( HttpServletResponse ) response ) ; if ( WebUIConfig . getInstance ( ) . getAuthentication ( ) . isAuthenticationEnabled ( ) && ! isAuthAction ( httpServletRequest . getRequestURI ( ) ) ) { if ( isAuthorized ( httpServletRequest ) ) { httpServletRequest . setAttribute ( "mskIsAuthorized" , true ) ; } else { Cookie authCookie = new Cookie ( AuthConstants . AUTH_COOKIE_NAME , "" ) ; authCookie . setMaxAge ( 0 ) ; httpServletResponse . addCookie ( authCookie ) ; httpServletRequest . getSession ( ) . setAttribute ( AuthConstants . LOGIN_REFER_PAGE_SESSION_ATTR_NAME , httpServletRequest . getRequestURL ( ) . toString ( ) ) ; httpServletResponse . sendRedirect ( "mskSignIn" ) ; return ; } } super . doFilter ( request , response , chain ) ; }
Checks user authorization if it enabled in config
37,884
public static final ThreadHistoryEvent created ( long threadId , String threadName ) { return new ThreadHistoryEvent ( threadId , threadName , OPERATION . CREATED ) ; }
Factory method to create new created event .
37,885
public static final ThreadHistoryEvent deleted ( long threadId , String threadName ) { return new ThreadHistoryEvent ( threadId , threadName , OPERATION . DELETED ) ; }
Factory method to create new deleted event .
37,886
private void initializeMe ( ) { Long pattern = Long . valueOf ( 0 ) ; ioExceptions = StatValueFactory . createStatValue ( pattern , "ioexceptions" , getSelectedIntervals ( ) ) ; servletExceptions = StatValueFactory . createStatValue ( pattern , "servletExceptions" , getSelectedIntervals ( ) ) ; runtimeExceptions = StatValueFactory . createStatValue ( pattern , "runtimeExceptions" , getSelectedIntervals ( ) ) ; addStatValues ( ioExceptions , servletExceptions , runtimeExceptions ) ; }
Initializes this object .
37,887
public static void reconfigureMonitor ( MonitoringPluginConfig config ) { for ( GenericMonitor monitor : MONITORS ) { if ( monitor . config == config ) { monitor . stop ( ) ; monitor . setup ( ) ; } } }
Called when MonitoringPluginConfig source changed at runtime .
37,888
protected String getSelectedDashboard ( HttpServletRequest req ) throws APIException { String dashboardName = req . getParameter ( "dashboard" ) ; if ( dashboardName != null ) return dashboardName ; return getDashboardAPI ( ) . getDefaultDashboardName ( ) ; }
Returns currently selected dashboard .
37,889
private void writeObject ( ObjectOutputStream out ) throws IOException { out . writeObject ( clazz ) ; out . writeInt ( defaultBatchSize ) ; out . writeInt ( queryIndex ) ; out . writeObject ( cursor ) ; out . writeObject ( generators ) ; out . writeInt ( generatorIndex ) ; writeObjects ( out ) ; }
Pumps may be serialized to be processed by asynchronous queues
37,890
public List < String > findAvailableStrings ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; String fulluri = path + uri ; List < String > strings = new ArrayList < > ( ) ; Enumeration < URL > resources = getResources ( fulluri ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; try { String string = readContents ( url ) ; strings . add ( string ) ; } catch ( IOException notAvailable ) { resourcesNotLoaded . add ( url . toExternalForm ( ) ) ; } } return strings ; }
Reads the contents of the found URLs as a Strings and returns them . Individual URLs that cannot be read are skipped and added to the list of resourcesNotLoaded
37,891
public static int fromFloat ( float fval ) { int fbits = Float . floatToIntBits ( fval ) ; int sign = fbits >>> 16 & 0x8000 ; int val = 0x1000 + fbits & 0x7fffffff ; if ( val >= 0x47800000 ) { if ( ( fbits & 0x7fffffff ) >= 0x47800000 ) { if ( val < 0x7f800000 ) { return sign | 0x7c00 ; } return sign | 0x7c00 | ( fbits & 0x007fffff ) >>> 13 ; } return sign | 0x7bff ; } if ( val >= 0x38800000 ) { return sign | val - 0x38000000 >>> 13 ; } if ( val < 0x33000000 ) { return sign ; } val = ( fbits & 0x7fffffff ) >>> 23 ; return sign | ( ( fbits & 0x7fffff | 0x800000 ) + ( 0x800000 >>> val - 102 ) >>> 126 - val ) ; }
returns all higher 16 bits as 0 for all results
37,892
public void decode ( DataItemListener dataItemListener ) throws CborException { Objects . requireNonNull ( dataItemListener ) ; DataItem dataItem = decodeNext ( ) ; while ( dataItem != null ) { dataItemListener . onDataItem ( dataItem ) ; dataItem = decodeNext ( ) ; } }
Streaming decoding of an input stream . On each decoded DataItem the callback listener is invoked .
37,893
public DataItem decodeNext ( ) throws CborException { int symbol ; try { symbol = inputStream . read ( ) ; } catch ( IOException ioException ) { throw new CborException ( ioException ) ; } if ( symbol == - 1 ) { return null ; } switch ( MajorType . ofByte ( symbol ) ) { case ARRAY : return arrayDecoder . decode ( symbol ) ; case BYTE_STRING : return byteStringDecoder . decode ( symbol ) ; case MAP : return mapDecoder . decode ( symbol ) ; case NEGATIVE_INTEGER : return negativeIntegerDecoder . decode ( symbol ) ; case UNICODE_STRING : return unicodeStringDecoder . decode ( symbol ) ; case UNSIGNED_INTEGER : return unsignedIntegerDecoder . decode ( symbol ) ; case SPECIAL : return specialDecoder . decode ( symbol ) ; case TAG : Tag tag = tagDecoder . decode ( symbol ) ; DataItem next = decodeNext ( ) ; if ( next == null ) { throw new CborException ( "Unexpected end of stream: tag without following data item." ) ; } else { if ( autoDecodeRationalNumbers && tag . getValue ( ) == 30 ) { return decodeRationalNumber ( next ) ; } else if ( autoDecodeLanguageTaggedStrings && tag . getValue ( ) == 38 ) { return decodeLanguageTaggedString ( next ) ; } else { DataItem itemToTag = next ; while ( itemToTag . hasTag ( ) ) itemToTag = itemToTag . getTag ( ) ; itemToTag . setTag ( tag ) ; return next ; } } case INVALID : default : throw new CborException ( "Not implemented major type " + symbol ) ; } }
Decodes exactly one DataItem from the input stream .
37,894
public Fingerprint callback ( FingerprintSecureCallback fingerprintSecureCallback , String KEY_NAME ) { this . fingerprintSecureCallback = fingerprintSecureCallback ; this . cipherHelper = new CipherHelper ( KEY_NAME ) ; return this ; }
Set fingerprint secure callback .
37,895
public Fingerprint fingerprintScanningColor ( int fingerprintScanning ) { this . fingerprintScanning = fingerprintScanning ; this . fingerprintImageView . setBackgroundTintList ( ColorStateList . valueOf ( getContext ( ) . getColor ( fingerprintScanning ) ) ) ; return this ; }
Set the fingerprint icon color in scanning state .
37,896
public Fingerprint fingerprintSuccessColor ( int fingerprintSuccess ) { this . fingerprintSuccess = fingerprintSuccess ; this . fingerprintImageView . setBackgroundTintList ( ColorStateList . valueOf ( getContext ( ) . getColor ( fingerprintSuccess ) ) ) ; return this ; }
Set the fingerprint icon color in success state .
37,897
public Fingerprint fingerprintErrorColor ( int fingerprintError ) { this . fingerprintError = fingerprintError ; this . fingerprintImageView . setBackgroundTintList ( ColorStateList . valueOf ( getContext ( ) . getColor ( fingerprintError ) ) ) ; return this ; }
Set the fingerprint icon color in error state .
37,898
public Fingerprint circleScanningColor ( int circleScanning ) { this . circleScanning = circleScanning ; this . circleView . setBackgroundTintList ( ColorStateList . valueOf ( getContext ( ) . getColor ( circleScanning ) ) ) ; return this ; }
Set the fingerprint circular background color in scanning state .
37,899
public Fingerprint circleSuccessColor ( int circleSuccess ) { this . circleSuccess = circleSuccess ; this . circleView . setBackgroundTintList ( ColorStateList . valueOf ( getContext ( ) . getColor ( circleSuccess ) ) ) ; return this ; }
Set the fingerprint circular background color in success state .