idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
35,800
public Stream window ( WindowConfig windowConfig , Fields inputFields , Aggregator aggregator , Fields functionFields ) { InMemoryWindowsStoreFactory inMemoryWindowsStoreFactory = new InMemoryWindowsStoreFactory ( ) ; return window ( windowConfig , inMemoryWindowsStoreFactory , inputFields , aggregator , functionFields , false ) ; }
Returns a stream of aggregated results based on the given window configuration which uses inmemory windowing tuple store .
35,801
public Stream window ( WindowConfig windowConfig , WindowsStoreFactory windowStoreFactory , Fields inputFields , Aggregator aggregator , Fields functionFields ) { return window ( windowConfig , windowStoreFactory , inputFields , aggregator , functionFields , true ) ; }
Returns stream of aggregated results based on the given window configuration .
35,802
public static String get_topology_id ( StormClusterState zkCluster , String storm_name ) throws Exception { List < String > active_storms = zkCluster . active_storms ( ) ; String rtn = null ; if ( active_storms != null ) { for ( String topology_id : active_storms ) { if ( ! topology_id . contains ( storm_name ) ) { continue ; } StormBase base = zkCluster . storm_base ( topology_id , null ) ; if ( base != null && storm_name . equals ( Common . getTopologyNameById ( topology_id ) ) ) { rtn = topology_id ; break ; } } } return rtn ; }
if a topology s name is equal to the input storm_name then return the topology id otherwise return null
35,803
public static HashMap < String , StormBase > get_all_StormBase ( StormClusterState zkCluster ) throws Exception { HashMap < String , StormBase > rtn = new HashMap < > ( ) ; List < String > active_storms = zkCluster . active_storms ( ) ; if ( active_storms != null ) { for ( String topology_id : active_storms ) { StormBase base = zkCluster . storm_base ( topology_id , null ) ; if ( base != null ) { rtn . put ( topology_id , base ) ; } } } return rtn ; }
get all topology s StormBase
35,804
public static Map < String , SupervisorInfo > get_all_SupervisorInfo ( StormClusterState stormClusterState , RunnableCallback callback ) throws Exception { Map < String , SupervisorInfo > rtn = new TreeMap < > ( ) ; List < String > supervisorIds = stormClusterState . supervisors ( callback ) ; List < String > blacklist = stormClusterState . get_blacklist ( ) ; if ( supervisorIds != null ) { for ( Iterator < String > iter = supervisorIds . iterator ( ) ; iter . hasNext ( ) ; ) { String supervisorId = iter . next ( ) ; SupervisorInfo supervisorInfo = stormClusterState . supervisor_info ( supervisorId ) ; if ( supervisorInfo == null ) { LOG . warn ( "Failed to get SupervisorInfo of " + supervisorId ) ; } else if ( blacklist . contains ( supervisorInfo . getHostName ( ) ) ) { LOG . warn ( " hostname:" + supervisorInfo . getHostName ( ) + " is in blacklist" ) ; } else { rtn . put ( supervisorId , supervisorInfo ) ; } } } else { LOG . info ( "No alive supervisor" ) ; } return rtn ; }
get all SupervisorInfo of storm cluster
35,805
public static DirLock tryLock ( FileSystem fs , Path dir ) throws IOException { Path lockFile = getDirLockFile ( dir ) ; try { FSDataOutputStream ostream = HdfsUtils . tryCreateFile ( fs , lockFile ) ; if ( ostream != null ) { LOG . debug ( "Thread ({}) Acquired lock on dir {}" , threadInfo ( ) , dir ) ; ostream . close ( ) ; return new DirLock ( fs , lockFile ) ; } else { LOG . debug ( "Thread ({}) cannot lock dir {} as its already locked." , threadInfo ( ) , dir ) ; return null ; } } catch ( IOException e ) { LOG . error ( "Error when acquiring lock on dir " + dir , e ) ; throw e ; } }
Get a lock on file if not already locked
35,806
public void release ( ) throws IOException { if ( ! fs . delete ( lockFile , false ) ) { LOG . error ( "Thread {} could not delete dir lock {} " , threadInfo ( ) , lockFile ) ; } else { LOG . debug ( "Thread {} Released dir lock {} " , threadInfo ( ) , lockFile ) ; } }
Release lock on dir by deleting the lock file
35,807
public static DirLock takeOwnershipIfStale ( FileSystem fs , Path dirToLock , int lockTimeoutSec ) { Path dirLockFile = getDirLockFile ( dirToLock ) ; long now = System . currentTimeMillis ( ) ; long expiryTime = now - ( lockTimeoutSec * 1000 ) ; try { long modTime = fs . getFileStatus ( dirLockFile ) . getModificationTime ( ) ; if ( modTime <= expiryTime ) { return takeOwnership ( fs , dirLockFile ) ; } return null ; } catch ( IOException e ) { return null ; } }
if the lock on the directory is stale take ownership
35,808
private void setupBlobstore ( ) throws Exception { BlobStore blobStore = data . getBlobStore ( ) ; StormClusterState clusterState = data . getStormClusterState ( ) ; Set < String > localSetOfKeys = Sets . newHashSet ( blobStore . listKeys ( ) ) ; Set < String > allKeys = Sets . newHashSet ( clusterState . active_keys ( ) ) ; Set < String > localAvailableActiveKeys = Sets . intersection ( localSetOfKeys , allKeys ) ; Set < String > keysToDelete = Sets . difference ( localSetOfKeys , allKeys ) ; LOG . debug ( "deleting keys not on zookeeper {}" , keysToDelete ) ; for ( String key : keysToDelete ) { blobStore . deleteBlob ( key ) ; } LOG . debug ( "Creating list of key entries for blobstore inside zookeeper {} local {}" , allKeys , localAvailableActiveKeys ) ; for ( String key : localAvailableActiveKeys ) { int versionForKey = BlobStoreUtils . getVersionForKey ( key , data . getNimbusHostPortInfo ( ) , data . getConf ( ) ) ; clusterState . setup_blobstore ( key , data . getNimbusHostPortInfo ( ) , versionForKey ) ; } }
sets up blobstore state for all current keys
35,809
private boolean check_nimbus_priority ( ) throws Exception { int gap = update_nimbus_detail ( ) ; if ( gap == 0 ) { return true ; } int left = SLAVE_NIMBUS_WAIT_TIME ; while ( left > 0 ) { LOG . info ( "nimbus.differ.count.zk is {}, so after {} seconds, nimbus will try to be leader!" , gap , left ) ; Thread . sleep ( 10 * 1000 ) ; left -= 10 ; } StormClusterState zkClusterState = data . getStormClusterState ( ) ; List < String > followers = zkClusterState . list_dirs ( Cluster . NIMBUS_SLAVE_DETAIL_SUBTREE , false ) ; if ( followers == null || followers . size ( ) == 0 ) { return false ; } for ( String follower : followers ) { if ( follower != null && ! follower . equals ( hostPort ) ) { Map bMap = zkClusterState . get_nimbus_detail ( follower , false ) ; if ( bMap != null ) { Object object = bMap . get ( NIMBUS_DIFFER_COUNT_ZK ) ; if ( object != null && ( JStormUtils . parseInt ( object ) ) < gap ) { LOG . info ( "Current node can't be leader, due to {} has higher priority" , follower ) ; return false ; } } } } return true ; }
Compared with other nimbus to get priority of this nimbus
35,810
private void checkOwnMaster ( ) throws Exception { int retry_times = 10 ; StormClusterState zkClient = data . getStormClusterState ( ) ; for ( int i = 0 ; i < retry_times ; i ++ , JStormUtils . sleepMs ( sleepTime ) ) { if ( ! zkClient . leader_existed ( ) ) { continue ; } String zkHost = zkClient . get_leader_host ( ) ; if ( hostPort . equals ( zkHost ) ) { return ; } LOG . warn ( "Current nimbus has started thrift, but fail to set as leader in zk:" + zkHost ) ; } String err = "Current nimbus failed to set as leader in zk, halting process" ; LOG . error ( err ) ; JStormUtils . halt_process ( 0 , err ) ; }
Check whether current node is master
35,811
protected void doFlush ( ) { long [ ] values = unFlushed . getSnapshot ( ) . getValues ( ) ; for ( JHistogram histogram : histogramMap . values ( ) ) { for ( long val : values ) { histogram . update ( val ) ; } } if ( MetricUtils . metricAccurateCal ) { for ( long val : values ) { for ( AsmMetric metric : this . assocMetrics ) { metric . updateDirectly ( val ) ; } } } this . unFlushed = newHistogram ( ) ; }
flush temp histogram data to all windows & assoc metrics .
35,812
public void emitDirect ( int taskId , String streamId , List < Object > tuple , Object messageId ) { _delegate . emitDirect ( taskId , streamId , tuple , messageId ) ; }
Emits a tuple to the specified task on the specified output stream . This output stream must have been declared as a direct stream and the specified task must use a direct grouping on this stream to receive the message . The emitted values must be immutable .
35,813
public boolean exists ( String key ) { Path dir = getKeyDir ( key ) ; boolean res = false ; try { _fs = dir . getFileSystem ( _hadoopConf ) ; res = _fs . exists ( dir ) ; } catch ( IOException e ) { LOG . warn ( "Exception checking for exists on: " + key ) ; } return res ; }
Check if the key exists in the blob store .
35,814
public static EPlatform getOSname ( ) { if ( isAix ( ) ) { _instance . platform = EPlatform . AIX ; } else if ( isDigitalUnix ( ) ) { _instance . platform = EPlatform . Digital_Unix ; } else if ( isFreeBSD ( ) ) { _instance . platform = EPlatform . FreeBSD ; } else if ( isHPUX ( ) ) { _instance . platform = EPlatform . HP_UX ; } else if ( isIrix ( ) ) { _instance . platform = EPlatform . Irix ; } else if ( isLinux ( ) ) { _instance . platform = EPlatform . Linux ; } else if ( isMacOS ( ) ) { _instance . platform = EPlatform . Mac_OS ; } else if ( isMacOSX ( ) ) { _instance . platform = EPlatform . Mac_OS_X ; } else if ( isMPEiX ( ) ) { _instance . platform = EPlatform . MPEiX ; } else if ( isNetWare ( ) ) { _instance . platform = EPlatform . NetWare_411 ; } else if ( isOpenVMS ( ) ) { _instance . platform = EPlatform . OpenVMS ; } else if ( isOS2 ( ) ) { _instance . platform = EPlatform . OS2 ; } else if ( isOS390 ( ) ) { _instance . platform = EPlatform . OS390 ; } else if ( isOSF1 ( ) ) { _instance . platform = EPlatform . OSF1 ; } else if ( isSolaris ( ) ) { _instance . platform = EPlatform . Solaris ; } else if ( isSunOS ( ) ) { _instance . platform = EPlatform . SunOS ; } else if ( isWindows ( ) ) { _instance . platform = EPlatform . Windows ; } else { _instance . platform = EPlatform . Others ; } return _instance . platform ; }
Get OS name
35,815
public void channelConnected ( ChannelHandlerContext ctx , ChannelStateEvent event ) { Channel channel = event . getChannel ( ) ; LOG . info ( "connection established to :{}, local port:{}" , client . getRemoteAddr ( ) , channel . getLocalAddress ( ) ) ; client . connectChannel ( ctx . getChannel ( ) ) ; client . handleResponse ( ctx . getChannel ( ) , null ) ; }
Sometime when connecting to a bad channel which isn t writable this method will be called
35,816
public static void main ( String [ ] args ) { Thread . setDefaultUncaughtExceptionHandler ( new DefaultUncaughtExceptionHandler ( ) ) ; JStormServerUtils . startTaobaoJvmMonitor ( ) ; Supervisor instance = new Supervisor ( ) ; instance . run ( ) ; }
start supervisor daemon
35,817
private void refreshLocalNodeTasks ( ) { Set < Integer > localNodeTasks = workerData . getLocalNodeTasks ( ) ; if ( localNodeTasks == null || localNodeTasks . equals ( lastLocalNodeTasks ) ) { return ; } LOG . info ( "Old localNodeTasks:" + lastLocalNodeTasks + ", new:" + localNodeTasks ) ; lastLocalNodeTasks = localNodeTasks ; List < Integer > localNodeOutTasks = new ArrayList < > ( ) ; for ( Integer outTask : allTargetTasks ) { if ( localNodeTasks . contains ( outTask ) ) { localNodeOutTasks . add ( outTask ) ; } } if ( ! localNodeOutTasks . isEmpty ( ) ) { this . outTasks = localNodeOutTasks ; } randomrange = new RandomRange ( outTasks . size ( ) ) ; }
Don t need to take care of multiple thread racing condition one thread per task
35,818
private void updateClusterMetrics ( String topologyId , TopologyMetric tpMetric ) { if ( tpMetric . get_topologyMetric ( ) . get_metrics_size ( ) == 0 ) { return ; } MetricInfo topologyMetrics = tpMetric . get_topologyMetric ( ) ; MetricInfo clusterMetrics = MetricUtils . mkMetricInfo ( ) ; Set < String > metricNames = new HashSet < > ( ) ; for ( Map . Entry < String , Map < Integer , MetricSnapshot > > entry : topologyMetrics . get_metrics ( ) . entrySet ( ) ) { String metricName = MetricUtils . topo2clusterName ( entry . getKey ( ) ) ; MetricType metricType = MetricUtils . metricType ( metricName ) ; Map < Integer , MetricSnapshot > winData = new HashMap < > ( ) ; for ( Map . Entry < Integer , MetricSnapshot > entryData : entry . getValue ( ) . entrySet ( ) ) { MetricSnapshot snapshot = entryData . getValue ( ) . deepCopy ( ) ; winData . put ( entryData . getKey ( ) , snapshot ) ; if ( metricType == MetricType . HISTOGRAM ) { entryData . getValue ( ) . set_points ( new byte [ 0 ] ) ; entryData . getValue ( ) . set_pointSize ( 0 ) ; } } clusterMetrics . put_to_metrics ( metricName , winData ) ; metricNames . add ( metricName ) ; } TopologyMetricContext clusterTpMetricContext = context . getClusterTopologyMetricContext ( ) ; clusterTpMetricContext . addToMemCache ( topologyId , clusterMetrics ) ; context . registerMetrics ( JStormMetrics . CLUSTER_METRIC_KEY , metricNames ) ; }
update cluster metrics local cache
35,819
public void freeAllSlots ( Cluster cluster ) { if ( ! _isAlive ) { LOG . warn ( "Freeing all slots on a dead node {} " , _nodeId ) ; } for ( Entry < String , Set < WorkerSlot > > entry : _topIdToUsedSlots . entrySet ( ) ) { cluster . freeSlots ( entry . getValue ( ) ) ; if ( _isAlive ) { _freeSlots . addAll ( entry . getValue ( ) ) ; } } _topIdToUsedSlots = new HashMap < > ( ) ; }
Free all slots on this node . This will update the Cluster too .
35,820
public void free ( WorkerSlot ws , Cluster cluster , boolean forceFree ) { if ( _freeSlots . contains ( ws ) ) return ; boolean wasFound = false ; for ( Entry < String , Set < WorkerSlot > > entry : _topIdToUsedSlots . entrySet ( ) ) { Set < WorkerSlot > slots = entry . getValue ( ) ; if ( slots . remove ( ws ) ) { cluster . freeSlot ( ws ) ; if ( _isAlive ) { _freeSlots . add ( ws ) ; } wasFound = true ; } } if ( ! wasFound ) { if ( forceFree ) { LOG . info ( "Forcefully freeing the " + ws ) ; cluster . freeSlot ( ws ) ; _freeSlots . add ( ws ) ; } else { throw new IllegalArgumentException ( "Tried to free a slot that was not" + " part of this node " + _nodeId ) ; } } }
Frees a single slot in this node
35,821
public void freeTopology ( String topId , Cluster cluster ) { Set < WorkerSlot > slots = _topIdToUsedSlots . get ( topId ) ; if ( slots == null || slots . isEmpty ( ) ) return ; for ( WorkerSlot ws : slots ) { cluster . freeSlot ( ws ) ; if ( _isAlive ) { _freeSlots . add ( ws ) ; } } _topIdToUsedSlots . remove ( topId ) ; }
Frees all the slots for a topology .
35,822
public void assign ( String topId , Collection < ExecutorDetails > executors , Cluster cluster ) { if ( ! _isAlive ) { throw new IllegalStateException ( "Trying to adding to a dead node " + _nodeId ) ; } if ( _freeSlots . isEmpty ( ) ) { throw new IllegalStateException ( "Trying to assign to a full node " + _nodeId ) ; } if ( executors . size ( ) == 0 ) { LOG . warn ( "Trying to assign nothing from " + topId + " to " + _nodeId + " (Ignored)" ) ; } else { WorkerSlot slot = _freeSlots . iterator ( ) . next ( ) ; cluster . assign ( slot , topId , executors ) ; assignInternal ( slot , topId , false ) ; } }
Assign a free slot on the node to the following topology and executors . This will update the cluster too .
35,823
private void updateStreamState ( Map < TaskStream , WindowState > state ) { for ( Map . Entry < TaskStream , WindowState > entry : state . entrySet ( ) ) { TaskStream taskStream = entry . getKey ( ) ; WindowState newState = entry . getValue ( ) ; WindowState curState = streamState . get ( taskStream ) ; if ( curState == null ) { streamState . put ( taskStream , newState ) ; } else { WindowState updatedState = new WindowState ( Math . max ( newState . lastExpired , curState . lastExpired ) , Math . max ( newState . lastEvaluated , curState . lastEvaluated ) ) ; LOG . debug ( "Update window state, taskStream {}, curState {}, newState {}" , taskStream , curState , updatedState ) ; streamState . put ( taskStream , updatedState ) ; } } }
update streamState based on stateUpdates
35,824
private void updateKeySetForBlobStore ( Set < String > keySetBlobStore , CuratorFramework zkClient ) { try { for ( String key : keySetBlobStore ) { LOG . debug ( "updating blob" ) ; BlobStoreUtils . updateKeyForBlobStore ( conf , blobStore , zkClient , key , nimbusInfo ) ; } } catch ( Exception exp ) { throw new RuntimeException ( exp ) ; } }
Update current key list inside the blobstore if the version changes
35,825
public Set < String > getKeySetToDownload ( Set < String > blobStoreKeySet , Set < String > zookeeperKeySet ) { zookeeperKeySet . removeAll ( blobStoreKeySet ) ; LOG . debug ( "Key list to download {}" , zookeeperKeySet ) ; return zookeeperKeySet ; }
Make a key list to download
35,826
public void updateBatch ( V batch ) { if ( intervalCheck . check ( ) ) { rolling ( ) ; } synchronized ( this ) { unflushed = updater . updateBatch ( batch , unflushed ) ; } }
In order to improve performance Flush one batch to rollingWindow
35,827
public static Set < Integer > worker_output_tasks ( WorkerData workerData ) { ContextMaker context_maker = workerData . getContextMaker ( ) ; Set < Integer > taskIds = workerData . getTaskIds ( ) ; StormTopology topology = workerData . getSysTopology ( ) ; Set < Integer > rtn = new HashSet < > ( ) ; for ( Integer taskId : taskIds ) { TopologyContext context = context_maker . makeTopologyContext ( topology , taskId , null ) ; Map < String , Map < String , Grouping > > targets = context . getThisTargets ( ) ; for ( Map < String , Grouping > e : targets . values ( ) ) { for ( String componentId : e . keySet ( ) ) { List < Integer > tasks = context . getComponentTasks ( componentId ) ; rtn . addAll ( tasks ) ; } } } return rtn ; }
get current task s output task list
35,828
@ SuppressWarnings ( "rawtypes" ) public static WorkerShutdown mk_worker ( Map conf , IContext context , String topologyId , String supervisorId , int port , String workerId , String jarPath ) throws Exception { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "topologyId:" ) . append ( topologyId ) . append ( ", " ) ; sb . append ( "port:" ) . append ( port ) . append ( ", " ) ; sb . append ( "workerId:" ) . append ( workerId ) . append ( ", " ) ; sb . append ( "jarPath:" ) . append ( jarPath ) . append ( "\n" ) ; LOG . info ( "Begin to run worker:" + sb . toString ( ) ) ; Worker w = new Worker ( conf , context , topologyId , supervisorId , port , workerId , jarPath ) ; return w . execute ( ) ; }
create worker instance and run it
35,829
public static List < Integer > getOldPortPids ( String port ) { String currPid = JStormUtils . process_pid ( ) ; List < Integer > ret = new ArrayList < > ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "ps -Af " ) ; try { LOG . info ( "Begin to execute " + sb . toString ( ) ) ; String output = JStormUtils . launchProcess ( sb . toString ( ) , new HashMap < String , String > ( ) , false ) ; BufferedReader reader = new BufferedReader ( new StringReader ( output ) ) ; JStormUtils . sleepMs ( 1000 ) ; String str ; while ( ( str = reader . readLine ( ) ) != null ) { if ( StringUtils . isBlank ( str ) ) { continue ; } if ( ! str . contains ( Worker . class . getName ( ) ) ) { continue ; } else if ( str . contains ( ProcessLauncher . class . getName ( ) ) ) { continue ; } else if ( ! str . contains ( port ) ) { continue ; } LOG . info ( "Find :" + str ) ; String [ ] fields = StringUtils . split ( str ) ; boolean find = false ; int i = 0 ; for ( ; i < fields . length ; i ++ ) { String field = fields [ i ] ; LOG . debug ( "Found, " + i + ":" + field ) ; if ( field . contains ( Worker . class . getName ( ) ) ) { if ( i + 3 >= fields . length ) { LOG . info ( "Failed to find port " ) ; } else if ( fields [ i + 3 ] . equals ( String . valueOf ( port ) ) ) { find = true ; } break ; } } if ( ! find ) { LOG . info ( "No old port worker" ) ; continue ; } if ( fields . length >= 2 ) { try { if ( currPid . equals ( fields [ 1 ] ) ) { LOG . info ( "Skip killing myself" ) ; continue ; } Integer pid = Integer . valueOf ( fields [ 1 ] ) ; LOG . info ( "Find one process :" + pid . toString ( ) ) ; ret . add ( pid ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) , e ) ; } } } return ret ; } catch ( IOException e ) { LOG . info ( "Failed to execute " + sb . toString ( ) ) ; return ret ; } catch ( Exception e ) { LOG . info ( e . getMessage ( ) , e ) ; return ret ; } }
Note that if the worker s start parameter length is longer than 4096 ps - ef|grep com . alibaba . jstorm . daemon . worker . Worker can t find worker
35,830
protected boolean sample ( ) { if ( curr . increment ( ) >= freq ) { curr . set ( 0 ) ; target . set ( rand . nextInt ( freq ) ) ; } return curr . get ( ) == target . get ( ) ; }
a faster sampling way
35,831
public BaseStatefulWindowedBolt < T > withMessageIdField ( String fieldName ) { windowConfiguration . put ( Config . TOPOLOGY_BOLTS_MESSAGE_ID_FIELD_NAME , fieldName ) ; return this ; }
Specify the name of the field in the tuple that holds the message id . This is used to track the windowing boundaries and re - evaluating the windowing operation during recovery of IStatefulWindowedBolt
35,832
public void unsubscribe ( ) { List < InvocationHandler > handler = this . handlers . get ( target ) ; if ( handler != null ) { handler . remove ( this . handler ) ; } }
Removes the client method handler represented by this subscription .
35,833
public boolean shouldSendEvent ( Event event ) { double randomDouble = random . nextDouble ( ) ; return sampleRate >= Math . abs ( randomDouble ) ; }
Handles event sampling logic .
35,834
public static Set < String > parseMdcTags ( String mdcTagsString ) { if ( isNullOrEmpty ( mdcTagsString ) ) { return Collections . emptySet ( ) ; } return new HashSet < > ( Arrays . asList ( mdcTagsString . split ( "," ) ) ) ; }
Parses the provided Strings into a Set of Strings .
35,835
public static String trimString ( String string , int maxMessageLength ) { if ( string == null ) { return null ; } else if ( string . length ( ) > maxMessageLength ) { return string . substring ( 0 , maxMessageLength - 3 ) + "..." ; } else { return string ; } }
Trims a String ensuring that the maximum length isn t reached .
35,836
public static boolean safelyRemoveShutdownHook ( Thread shutDownHook ) { try { return Runtime . getRuntime ( ) . removeShutdownHook ( shutDownHook ) ; } catch ( IllegalStateException e ) { if ( e . getMessage ( ) . equals ( "Shutdown in progress" ) ) { } else { throw e ; } } return false ; }
Try to remove the shutDownHook handling the case where the VM is in shutdown process .
35,837
public void tick ( long duration , TimeUnit unit ) { this . date = new Date ( date . getTime ( ) + unit . toMillis ( duration ) ) ; }
Adjust the FixedClock by the given amount .
35,838
public UserBuilder withData ( String name , Object value ) { if ( this . data == null ) { this . data = new HashMap < > ( ) ; } this . data . put ( name , value ) ; return this ; }
Adds to the extra data for the user .
35,839
public static String jndiLookup ( String key ) { String value = null ; try { Context c = new InitialContext ( ) ; value = ( String ) c . lookup ( JNDI_PREFIX + key ) ; } catch ( NoInitialContextException e ) { logger . trace ( "JNDI not configured for Sentry (NoInitialContextEx)" ) ; } catch ( NamingException e ) { logger . trace ( "No /sentry/" + key + " in JNDI" ) ; } catch ( RuntimeException e ) { logger . warn ( "Odd RuntimeException while testing for JNDI" , e ) ; } return value ; }
Looks up for a JNDI definition of the provided key .
35,840
protected void retrieveProperties ( ) { LogManager manager = LogManager . getLogManager ( ) ; String className = SentryHandler . class . getName ( ) ; setPrintfStyle ( Boolean . valueOf ( manager . getProperty ( className + ".printfStyle" ) ) ) ; setLevel ( parseLevelOrDefault ( manager . getProperty ( className + ".level" ) ) ) ; }
Retrieves the properties of the logger .
35,841
protected EventBuilder createEventBuilder ( LogRecord record ) { EventBuilder eventBuilder = new EventBuilder ( ) . withSdkIntegration ( "java.util.logging" ) . withLevel ( getLevel ( record . getLevel ( ) ) ) . withTimestamp ( new Date ( record . getMillis ( ) ) ) . withLogger ( record . getLoggerName ( ) ) ; String message = record . getMessage ( ) ; if ( record . getResourceBundle ( ) != null && record . getResourceBundle ( ) . containsKey ( record . getMessage ( ) ) ) { message = record . getResourceBundle ( ) . getString ( record . getMessage ( ) ) ; } String topLevelMessage = message ; if ( record . getParameters ( ) == null ) { eventBuilder . withSentryInterface ( new MessageInterface ( message ) ) ; } else { String formatted ; List < String > parameters = formatMessageParameters ( record . getParameters ( ) ) ; try { formatted = formatMessage ( message , record . getParameters ( ) ) ; topLevelMessage = formatted ; } catch ( Exception e ) { formatted = null ; } eventBuilder . withSentryInterface ( new MessageInterface ( message , parameters , formatted ) ) ; } eventBuilder . withMessage ( topLevelMessage ) ; Throwable throwable = record . getThrown ( ) ; if ( throwable != null ) { eventBuilder . withSentryInterface ( new ExceptionInterface ( throwable ) ) ; } Map < String , String > mdc = MDC . getMDCAdapter ( ) . getCopyOfContextMap ( ) ; if ( mdc != null ) { for ( Map . Entry < String , String > mdcEntry : mdc . entrySet ( ) ) { if ( Sentry . getStoredClient ( ) . getMdcTags ( ) . contains ( mdcEntry . getKey ( ) ) ) { eventBuilder . withTag ( mdcEntry . getKey ( ) , mdcEntry . getValue ( ) ) ; } else { eventBuilder . withExtra ( mdcEntry . getKey ( ) , mdcEntry . getValue ( ) ) ; } } } eventBuilder . withExtra ( THREAD_ID , record . getThreadID ( ) ) ; return eventBuilder ; }
Builds an EventBuilder based on the log record .
35,842
protected String formatMessage ( String message , Object [ ] parameters ) { String formatted ; if ( printfStyle ) { formatted = String . format ( message , parameters ) ; } else { formatted = MessageFormat . format ( message , parameters ) ; } return formatted ; }
Returns formatted Event message when provided the message template and parameters .
35,843
protected static PackageInfo getPackageInfo ( Context ctx ) { try { return ctx . getPackageManager ( ) . getPackageInfo ( ctx . getPackageName ( ) , 0 ) ; } catch ( PackageManager . NameNotFoundException e ) { Log . e ( TAG , "Error getting package info." , e ) ; return null ; } }
Return the Application s PackageInfo if possible or null .
35,844
protected static String getFamily ( ) { try { return Build . MODEL . split ( " " ) [ 0 ] ; } catch ( Exception e ) { Log . e ( TAG , "Error getting device family." , e ) ; return null ; } }
Fake the device family by using the first word in the Build . MODEL . Works well in most cases ... Nexus 6P - > Nexus Galaxy S7 - > Galaxy .
35,845
protected static ActivityManager . MemoryInfo getMemInfo ( Context ctx ) { try { ActivityManager actManager = ( ActivityManager ) ctx . getSystemService ( ACTIVITY_SERVICE ) ; ActivityManager . MemoryInfo memInfo = new ActivityManager . MemoryInfo ( ) ; actManager . getMemoryInfo ( memInfo ) ; return memInfo ; } catch ( Exception e ) { Log . e ( TAG , "Error getting MemoryInfo." , e ) ; return null ; } }
Get MemoryInfo object representing the memory state of the application .
35,846
protected static String getOrientation ( Context ctx ) { try { String o ; switch ( ctx . getResources ( ) . getConfiguration ( ) . orientation ) { case android . content . res . Configuration . ORIENTATION_LANDSCAPE : o = "landscape" ; break ; case android . content . res . Configuration . ORIENTATION_PORTRAIT : o = "portrait" ; break ; default : o = null ; break ; } return o ; } catch ( Exception e ) { Log . e ( TAG , "Error getting device orientation." , e ) ; return null ; } }
Get the device s current screen orientation .
35,847
protected static Boolean isCharging ( Context ctx ) { try { Intent intent = ctx . registerReceiver ( null , new IntentFilter ( Intent . ACTION_BATTERY_CHANGED ) ) ; if ( intent == null ) { return null ; } int plugged = intent . getIntExtra ( BatteryManager . EXTRA_PLUGGED , - 1 ) ; return plugged == BatteryManager . BATTERY_PLUGGED_AC || plugged == BatteryManager . BATTERY_PLUGGED_USB ; } catch ( Exception e ) { Log . e ( TAG , "Error getting device charging state." , e ) ; return null ; } }
Checks whether or not the device is currently plugged in and charging or null if unknown .
35,848
protected static Long getUnusedInternalStorage ( ) { try { File path = Environment . getDataDirectory ( ) ; StatFs stat = new StatFs ( path . getPath ( ) ) ; long blockSize = stat . getBlockSize ( ) ; long availableBlocks = stat . getAvailableBlocks ( ) ; return availableBlocks * blockSize ; } catch ( Exception e ) { Log . e ( TAG , "Error getting unused internal storage amount." , e ) ; return null ; } }
Get the unused amount of internal storage in bytes .
35,849
protected static Long getTotalInternalStorage ( ) { try { File path = Environment . getDataDirectory ( ) ; StatFs stat = new StatFs ( path . getPath ( ) ) ; long blockSize = stat . getBlockSize ( ) ; long totalBlocks = stat . getBlockCount ( ) ; return totalBlocks * blockSize ; } catch ( Exception e ) { Log . e ( TAG , "Error getting total internal storage amount." , e ) ; return null ; } }
Get the total amount of internal storage in bytes .
35,850
protected static Long getUnusedExternalStorage ( ) { try { if ( isExternalStorageMounted ( ) ) { File path = Environment . getExternalStorageDirectory ( ) ; StatFs stat = new StatFs ( path . getPath ( ) ) ; long blockSize = stat . getBlockSize ( ) ; long availableBlocks = stat . getAvailableBlocks ( ) ; return availableBlocks * blockSize ; } } catch ( Exception e ) { Log . e ( TAG , "Error getting unused external storage amount." , e ) ; } return null ; }
Get the unused amount of external storage in bytes or null if no external storage is mounted .
35,851
protected static Long getTotalExternalStorage ( ) { try { if ( isExternalStorageMounted ( ) ) { File path = Environment . getExternalStorageDirectory ( ) ; StatFs stat = new StatFs ( path . getPath ( ) ) ; long blockSize = stat . getBlockSize ( ) ; long totalBlocks = stat . getBlockCount ( ) ; return totalBlocks * blockSize ; } } catch ( Exception e ) { Log . e ( TAG , "Error getting total external storage amount." , e ) ; } return null ; }
Get the total amount of external storage in bytes or null if no external storage is mounted .
35,852
protected static DisplayMetrics getDisplayMetrics ( Context ctx ) { try { return ctx . getResources ( ) . getDisplayMetrics ( ) ; } catch ( Exception e ) { Log . e ( TAG , "Error getting DisplayMetrics." , e ) ; return null ; } }
Get the DisplayMetrics object for the current application .
35,853
protected static String getApplicationName ( Context ctx ) { try { ApplicationInfo applicationInfo = ctx . getApplicationInfo ( ) ; int stringId = applicationInfo . labelRes ; if ( stringId == 0 ) { if ( applicationInfo . nonLocalizedLabel != null ) { return applicationInfo . nonLocalizedLabel . toString ( ) ; } } else { return ctx . getString ( stringId ) ; } } catch ( Exception e ) { Log . e ( TAG , "Error getting application name." , e ) ; } return null ; }
Get the human - facing Application name .
35,854
protected static boolean isConnected ( Context ctx ) { ConnectivityManager connectivityManager = ( ConnectivityManager ) ctx . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; NetworkInfo activeNetworkInfo = connectivityManager . getActiveNetworkInfo ( ) ; return activeNetworkInfo != null && activeNetworkInfo . isConnected ( ) ; }
Check whether the application has internet access at a point in time .
35,855
private boolean checkPermission ( String permission ) { int res = ctx . checkCallingOrSelfPermission ( permission ) ; return ( res == PackageManager . PERMISSION_GRANTED ) ; }
Check whether the application has been granted a certain permission .
35,856
public static void add ( Throwable throwable , Frame [ ] frames ) { Map < Throwable , Frame [ ] > weakMap = cache . get ( ) ; weakMap . put ( throwable , frames ) ; }
Store the per - frame local variable information for the last exception thrown on this thread .
35,857
public static Frame [ ] get ( Throwable throwable ) { Map < Throwable , Frame [ ] > weakMap = cache . get ( ) ; return weakMap . get ( throwable ) ; }
Retrieve the per - frame local variable information for the last exception thrown on this thread .
35,858
private void writeException ( JsonGenerator generator , SentryException sentryException ) throws IOException { generator . writeStartObject ( ) ; generator . writeStringField ( TYPE_PARAMETER , sentryException . getExceptionClassName ( ) ) ; generator . writeStringField ( VALUE_PARAMETER , sentryException . getExceptionMessage ( ) ) ; generator . writeStringField ( MODULE_PARAMETER , sentryException . getExceptionPackageName ( ) ) ; generator . writeFieldName ( STACKTRACE_PARAMETER ) ; stackTraceInterfaceBinding . writeInterface ( generator , sentryException . getStackTraceInterface ( ) ) ; generator . writeEndObject ( ) ; }
Outputs an exception with its StackTrace on a JSon stream .
35,859
protected Connection createConnection ( Dsn dsn ) { String protocol = dsn . getProtocol ( ) ; Connection connection ; if ( protocol . equalsIgnoreCase ( "http" ) || protocol . equalsIgnoreCase ( "https" ) ) { logger . debug ( "Using an {} connection to Sentry." , protocol . toUpperCase ( ) ) ; connection = createHttpConnection ( dsn ) ; } else if ( protocol . equalsIgnoreCase ( "out" ) ) { logger . debug ( "Using StdOut to send events." ) ; connection = createStdOutConnection ( dsn ) ; } else if ( protocol . equalsIgnoreCase ( "noop" ) ) { logger . debug ( "Using noop to send events." ) ; connection = new NoopConnection ( ) ; } else { throw new IllegalStateException ( "Couldn't create a connection for the protocol '" + protocol + "'" ) ; } BufferedConnection bufferedConnection = null ; if ( getBufferEnabled ( dsn ) ) { Buffer eventBuffer = getBuffer ( dsn ) ; if ( eventBuffer != null ) { long flushtime = getBufferFlushtime ( dsn ) ; boolean gracefulShutdown = getBufferedConnectionGracefulShutdownEnabled ( dsn ) ; Long shutdownTimeout = getBufferedConnectionShutdownTimeout ( dsn ) ; bufferedConnection = new BufferedConnection ( connection , eventBuffer , flushtime , gracefulShutdown , shutdownTimeout ) ; connection = bufferedConnection ; } } if ( getAsyncEnabled ( dsn ) ) { connection = createAsyncConnection ( dsn , connection ) ; } if ( bufferedConnection != null ) { connection = bufferedConnection . wrapConnectionWithBufferWriter ( connection ) ; } return connection ; }
Creates a connection to the given DSN by determining the protocol .
35,860
protected Connection createHttpConnection ( Dsn dsn ) { URL sentryApiUrl = HttpConnection . getSentryApiUrl ( dsn . getUri ( ) , dsn . getProjectId ( ) ) ; String proxyHost = getProxyHost ( dsn ) ; String proxyUser = getProxyUser ( dsn ) ; String proxyPass = getProxyPass ( dsn ) ; int proxyPort = getProxyPort ( dsn ) ; Proxy proxy = null ; if ( proxyHost != null ) { InetSocketAddress proxyAddr = new InetSocketAddress ( proxyHost , proxyPort ) ; proxy = new Proxy ( Proxy . Type . HTTP , proxyAddr ) ; if ( proxyUser != null && proxyPass != null ) { Authenticator . setDefault ( new ProxyAuthenticator ( proxyUser , proxyPass ) ) ; } } Double sampleRate = getSampleRate ( dsn ) ; EventSampler eventSampler = null ; if ( sampleRate != null ) { eventSampler = new RandomEventSampler ( sampleRate ) ; } HttpConnection httpConnection = new HttpConnection ( sentryApiUrl , dsn . getPublicKey ( ) , dsn . getSecretKey ( ) , proxy , eventSampler ) ; Marshaller marshaller = createMarshaller ( dsn ) ; httpConnection . setMarshaller ( marshaller ) ; int timeout = getTimeout ( dsn ) ; httpConnection . setConnectionTimeout ( timeout ) ; boolean bypassSecurityEnabled = getBypassSecurityEnabled ( dsn ) ; httpConnection . setBypassSecurity ( bypassSecurityEnabled ) ; return httpConnection ; }
Creates an HTTP connection to the Sentry server .
35,861
protected Connection createStdOutConnection ( Dsn dsn ) { OutputStreamConnection stdOutConnection = new OutputStreamConnection ( System . out ) ; stdOutConnection . setMarshaller ( createMarshaller ( dsn ) ) ; return stdOutConnection ; }
Uses stdout to send the logs .
35,862
protected long getBufferFlushtime ( Dsn dsn ) { return Util . parseLong ( Lookup . lookup ( BUFFER_FLUSHTIME_OPTION , dsn ) , BUFFER_FLUSHTIME_DEFAULT ) ; }
How long to wait between attempts to flush the disk buffer in milliseconds .
35,863
protected long getAsyncShutdownTimeout ( Dsn dsn ) { return Util . parseLong ( Lookup . lookup ( ASYNC_SHUTDOWN_TIMEOUT_OPTION , dsn ) , ASYNC_SHUTDOWN_TIMEOUT_DEFAULT ) ; }
The graceful shutdown timeout of the async executor in milliseconds .
35,864
protected int getAsyncQueueSize ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( ASYNC_QUEUE_SIZE_OPTION , dsn ) , QUEUE_SIZE_DEFAULT ) ; }
Maximum size of the async send queue .
35,865
protected int getAsyncPriority ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( ASYNC_PRIORITY_OPTION , dsn ) , Thread . MIN_PRIORITY ) ; }
Priority of threads used for the async connection .
35,866
protected int getAsyncThreads ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( ASYNC_THREADS_OPTION , dsn ) , Runtime . getRuntime ( ) . availableProcessors ( ) ) ; }
The number of threads used for the async connection .
35,867
protected int getProxyPort ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( HTTP_PROXY_PORT_OPTION , dsn ) , HTTP_PROXY_PORT_DEFAULT ) ; }
HTTP proxy port for Sentry connections .
35,868
protected int getMaxMessageLength ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( MAX_MESSAGE_LENGTH_OPTION , dsn ) , JsonMarshaller . DEFAULT_MAX_MESSAGE_LENGTH ) ; }
The maximum length of the message body in the requests to the Sentry Server .
35,869
protected int getTimeout ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( TIMEOUT_OPTION , dsn ) , TIMEOUT_DEFAULT ) ; }
Timeout for requests to the Sentry server in milliseconds .
35,870
protected boolean getBufferEnabled ( Dsn dsn ) { String bufferEnabled = Lookup . lookup ( BUFFER_ENABLED_OPTION , dsn ) ; if ( bufferEnabled != null ) { return Boolean . parseBoolean ( bufferEnabled ) ; } return BUFFER_ENABLED_DEFAULT ; }
Whether or not buffering is enabled .
35,871
protected int getBufferSize ( Dsn dsn ) { return Util . parseInteger ( Lookup . lookup ( BUFFER_SIZE_OPTION , dsn ) , BUFFER_SIZE_DEFAULT ) ; }
Get the maximum number of events to cache offline when network is down .
35,872
private void writeObject ( final ObjectOutputStream out ) throws IOException { out . defaultWriteObject ( ) ; out . writeInt ( size ( ) ) ; for ( final E e : this ) { out . writeObject ( e ) ; } }
Write the queue out using a custom routine .
35,873
@ SuppressWarnings ( "unchecked" ) private void readObject ( final ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; elements = ( E [ ] ) new Object [ maxElements ] ; final int size = in . readInt ( ) ; for ( int i = 0 ; i < size ; i ++ ) { elements [ i ] = ( E ) in . readObject ( ) ; } start = 0 ; full = size == maxElements ; if ( full ) { end = 0 ; } else { end = size ; } }
Read the queue in using a custom routine .
35,874
public void clear ( ) { full = false ; start = 0 ; end = 0 ; Arrays . fill ( elements , null ) ; }
Clears this queue .
35,875
public boolean add ( final E element ) { if ( null == element ) { throw new NullPointerException ( "Attempted to add null object to queue" ) ; } if ( isAtFullCapacity ( ) ) { remove ( ) ; } elements [ end ++ ] = element ; if ( end >= maxElements ) { end = 0 ; } if ( end == start ) { full = true ; } return true ; }
Adds the given element to this queue . If the queue is full the least recently added element is discarded so that a new element can be inserted .
35,876
public E get ( final int index ) { final int sz = size ( ) ; if ( index < 0 || index >= sz ) { throw new NoSuchElementException ( String . format ( "The specified index (%1$d) is outside the available range [0, %2$d)" , Integer . valueOf ( index ) , Integer . valueOf ( sz ) ) ) ; } final int idx = ( start + index ) % maxElements ; return elements [ idx ] ; }
Returns the element at the specified position in this queue .
35,877
public Iterator < E > iterator ( ) { return new Iterator < E > ( ) { private int index = start ; private int lastReturnedIndex = - 1 ; private boolean isFirst = full ; public boolean hasNext ( ) { return isFirst || index != end ; } public E next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } isFirst = false ; lastReturnedIndex = index ; index = increment ( index ) ; return elements [ lastReturnedIndex ] ; } public void remove ( ) { if ( lastReturnedIndex == - 1 ) { throw new IllegalStateException ( ) ; } if ( lastReturnedIndex == start ) { CircularFifoQueue . this . remove ( ) ; lastReturnedIndex = - 1 ; return ; } int pos = lastReturnedIndex + 1 ; if ( start < lastReturnedIndex && pos < end ) { System . arraycopy ( elements , pos , elements , lastReturnedIndex , end - pos ) ; } else { while ( pos != end ) { if ( pos >= maxElements ) { elements [ pos - 1 ] = elements [ 0 ] ; pos = 0 ; } else { elements [ decrement ( pos ) ] = elements [ pos ] ; pos = increment ( pos ) ; } } } lastReturnedIndex = - 1 ; end = decrement ( end ) ; elements [ end ] = null ; full = false ; index = decrement ( index ) ; } } ; }
Returns an iterator over this queue s elements .
35,878
@ SuppressWarnings ( "checkstyle:magicnumber" ) private void doClose ( ) throws IOException { logger . debug ( "Gracefully shutting down Sentry async threads." ) ; closed = true ; executorService . shutdown ( ) ; try { if ( shutdownTimeout == - 1L ) { long waitBetweenLoggingMs = 5000L ; while ( true ) { if ( executorService . awaitTermination ( waitBetweenLoggingMs , TimeUnit . MILLISECONDS ) ) { break ; } logger . debug ( "Still waiting on async executor to terminate." ) ; } } else if ( ! executorService . awaitTermination ( shutdownTimeout , TimeUnit . MILLISECONDS ) ) { logger . warn ( "Graceful shutdown took too much time, forcing the shutdown." ) ; List < Runnable > tasks = executorService . shutdownNow ( ) ; logger . warn ( "{} tasks failed to execute before shutdown." , tasks . size ( ) ) ; } logger . debug ( "Shutdown finished." ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; logger . warn ( "Graceful shutdown interrupted, forcing the shutdown." ) ; List < Runnable > tasks = executorService . shutdownNow ( ) ; logger . warn ( "{} tasks failed to execute before shutdown." , tasks . size ( ) ) ; } finally { actualConnection . close ( ) ; } }
Close the connection whether it s from the shutdown hook or not .
35,879
private static String calculateChecksum ( String string ) { byte [ ] bytes = string . getBytes ( UTF_8 ) ; Checksum checksum = new CRC32 ( ) ; checksum . update ( bytes , 0 , bytes . length ) ; return Long . toHexString ( checksum . getValue ( ) ) . toUpperCase ( ) ; }
Calculates a checksum for a given string .
35,880
private void autoSetMissingValues ( ) { if ( event . getTimestamp ( ) == null ) { event . setTimestamp ( new Date ( ) ) ; } if ( event . getPlatform ( ) == null ) { event . setPlatform ( DEFAULT_PLATFORM ) ; } if ( event . getSdk ( ) == null ) { event . setSdk ( new Sdk ( SentryEnvironment . SDK_NAME , SentryEnvironment . SDK_VERSION , sdkIntegrations ) ) ; } if ( event . getServerName ( ) == null ) { event . setServerName ( HOSTNAME_CACHE . getHostname ( ) ) ; } }
Sets default values for each field that hasn t been provided manually .
35,881
public EventBuilder withContexts ( Map < String , Map < String , Object > > contexts ) { event . setContexts ( contexts ) ; return this ; }
Adds a map of map of context objects to the event .
35,882
public EventBuilder withExtra ( String extraName , Object extraValue ) { event . getExtra ( ) . put ( extraName , extraValue ) ; return this ; }
Adds an extra property to the event .
35,883
public EventBuilder withFingerprint ( String ... fingerprint ) { List < String > list = new ArrayList < > ( fingerprint . length ) ; Collections . addAll ( list , fingerprint ) ; event . setFingerprint ( list ) ; return this ; }
Sets event fingerprint an array of strings used to dictate the deduplicating for this event .
35,884
public void uncaughtException ( Thread thread , Throwable thrown ) { if ( enabled ) { logger . trace ( "Uncaught exception received." ) ; EventBuilder eventBuilder = new EventBuilder ( ) . withMessage ( thrown . getMessage ( ) ) . withLevel ( Event . Level . FATAL ) . withSentryInterface ( new ExceptionInterface ( thrown ) ) ; try { Sentry . capture ( eventBuilder ) ; } catch ( Exception e ) { logger . error ( "Error sending uncaught exception to Sentry." , e ) ; } } if ( defaultExceptionHandler != null ) { defaultExceptionHandler . uncaughtException ( thread , thrown ) ; } else if ( ! ( thrown instanceof ThreadDeath ) ) { System . err . print ( "Exception in thread \"" + thread . getName ( ) + "\" " ) ; thrown . printStackTrace ( System . err ) ; } }
Sends any uncaught exception to Sentry then passes the exception on to the pre - existing uncaught exception handler .
35,885
public static SentryUncaughtExceptionHandler setup ( ) { logger . debug ( "Configuring uncaught exception handler." ) ; Thread . UncaughtExceptionHandler currentHandler = Thread . getDefaultUncaughtExceptionHandler ( ) ; if ( currentHandler != null ) { logger . debug ( "default UncaughtExceptionHandler class='" + currentHandler . getClass ( ) . getName ( ) + "'" ) ; } SentryUncaughtExceptionHandler handler = new SentryUncaughtExceptionHandler ( currentHandler ) ; Thread . setDefaultUncaughtExceptionHandler ( handler ) ; return handler ; }
Configures an uncaught exception handler which sends events to Sentry then calls the preexisting uncaught exception handler .
35,886
private String formatLevel ( Event . Level level ) { if ( level == null ) { return null ; } switch ( level ) { case DEBUG : return "debug" ; case FATAL : return "fatal" ; case WARNING : return "warning" ; case INFO : return "info" ; case ERROR : return "error" ; default : logger . error ( "The level '{}' isn't supported, this should NEVER happen, contact Sentry developers" , level . name ( ) ) ; return null ; } }
Formats a log level into one of the accepted string representation of a log level .
35,887
@ SuppressWarnings ( "checkstyle:parameternumber" ) public static SentryAppender createAppender ( @ PluginAttribute ( "name" ) final String name , @ PluginElement ( "filter" ) final Filter filter ) { if ( name == null ) { LOGGER . error ( "No name provided for SentryAppender" ) ; return null ; } return new SentryAppender ( name , filter ) ; }
Create a Sentry Appender .
35,888
public static URL getSentryApiUrl ( URI sentryUri , String projectId ) { try { String url = sentryUri . toString ( ) + "api/" + projectId + "/store/" ; return new URL ( url ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( "Couldn't build a valid URL from the Sentry API." , e ) ; } }
Automatically determines the URL to the HTTP API of Sentry .
35,889
protected HttpURLConnection getConnection ( ) { try { HttpURLConnection connection ; if ( proxy != null ) { connection = ( HttpURLConnection ) sentryUrl . openConnection ( proxy ) ; } else { connection = ( HttpURLConnection ) sentryUrl . openConnection ( ) ; } if ( bypassSecurity && connection instanceof HttpsURLConnection ) { ( ( HttpsURLConnection ) connection ) . setHostnameVerifier ( NAIVE_VERIFIER ) ; } connection . setRequestMethod ( "POST" ) ; connection . setDoOutput ( true ) ; connection . setConnectTimeout ( connectionTimeout ) ; connection . setReadTimeout ( readTimeout ) ; connection . setRequestProperty ( USER_AGENT , SentryEnvironment . getSentryName ( ) ) ; connection . setRequestProperty ( SENTRY_AUTH , getAuthHeader ( ) ) ; if ( marshaller . getContentType ( ) != null ) { connection . setRequestProperty ( "Content-Type" , marshaller . getContentType ( ) ) ; } if ( marshaller . getContentEncoding ( ) != null ) { connection . setRequestProperty ( "Content-Encoding" , marshaller . getContentEncoding ( ) ) ; } return connection ; } catch ( IOException e ) { throw new IllegalStateException ( "Couldn't set up a connection to the Sentry server." , e ) ; } }
Opens a connection to the Sentry API allowing to send new events .
35,890
public synchronized Map < String , String > getTags ( ) { if ( tags == null || tags . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } return Collections . unmodifiableMap ( tags ) ; }
Return tags attached to this context .
35,891
public synchronized Map < String , Object > getExtra ( ) { if ( extra == null || extra . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } return Collections . unmodifiableMap ( extra ) ; }
Return extra data attached to this context .
35,892
public synchronized void addExtra ( String name , Object value ) { if ( extra == null ) { extra = new HashMap < > ( ) ; } extra . put ( name , value ) ; }
Add extra data to the current context .
35,893
public void add ( Event event ) { if ( getNumStoredEvents ( ) >= maxEvents ) { logger . warn ( "Not adding Event because at least " + Integer . toString ( maxEvents ) + " events are already stored: " + event . getId ( ) ) ; return ; } File eventFile = new File ( bufferDir . getAbsolutePath ( ) , event . getId ( ) . toString ( ) + FILE_SUFFIX ) ; if ( eventFile . exists ( ) ) { logger . trace ( "Not adding Event to offline storage because it already exists: " + eventFile . getAbsolutePath ( ) ) ; return ; } else { logger . debug ( "Adding Event to offline storage: " + eventFile . getAbsolutePath ( ) ) ; } try ( FileOutputStream fileOutputStream = new FileOutputStream ( eventFile ) ; ObjectOutputStream objectOutputStream = new ObjectOutputStream ( fileOutputStream ) ) { objectOutputStream . writeObject ( event ) ; } catch ( Exception e ) { logger . error ( "Error writing Event to offline storage: " + event . getId ( ) , e ) ; } logger . debug ( Integer . toString ( getNumStoredEvents ( ) ) + " stored events are now in dir: " + bufferDir . getAbsolutePath ( ) ) ; }
Store a single event to the add directory . Java serialization is used and each event is stored in a file named by its UUID .
35,894
public static String dsnLookup ( ) { String dsn = Lookup . lookup ( "dsn" ) ; if ( Util . isNullOrEmpty ( dsn ) ) { dsn = Lookup . lookup ( "dns" ) ; } if ( Util . isNullOrEmpty ( dsn ) ) { logger . warn ( "*** Couldn't find a suitable DSN, Sentry operations will do nothing!" + " See documentation: https://docs.sentry.io/clients/java/ ***" ) ; dsn = DEFAULT_DSN ; } return dsn ; }
Looks for a DSN configuration within JNDI the System environment or Java properties .
35,895
public static SentryClient sentryClient ( String dsn , SentryClientFactory sentryClientFactory ) { Dsn realDsn = resolveDsn ( dsn ) ; if ( sentryClientFactory == null ) { String sentryClientFactoryName = Lookup . lookup ( "factory" , realDsn ) ; if ( Util . isNullOrEmpty ( sentryClientFactoryName ) ) { sentryClientFactory = new DefaultSentryClientFactory ( ) ; } else { Class < ? extends SentryClientFactory > factoryClass = null ; try { factoryClass = ( Class < ? extends SentryClientFactory > ) Class . forName ( sentryClientFactoryName ) ; sentryClientFactory = factoryClass . newInstance ( ) ; } catch ( ClassNotFoundException | IllegalAccessException | InstantiationException e ) { logger . error ( "Error creating SentryClient using factory class: '" + sentryClientFactoryName + "'." , e ) ; return null ; } } } return sentryClientFactory . createSentryClient ( realDsn ) ; }
Creates an instance of Sentry using the provided DSN and the specified factory .
35,896
public void setMinLevel ( String minLevel ) { this . minLevel = minLevel != null ? Level . toLevel ( minLevel ) : null ; }
Set minimum level to log .
35,897
public static String concernStackString ( BlockInfo blockInfo ) { String result = "" ; for ( String stackEntry : blockInfo . threadStackEntries ) { if ( Character . isLetter ( stackEntry . charAt ( 0 ) ) ) { String [ ] lines = stackEntry . split ( BlockInfo . SEPARATOR ) ; for ( String line : lines ) { String keyStackString = concernStackString ( line ) ; if ( keyStackString != null ) { return keyStackString ; } } return classSimpleName ( lines [ 0 ] ) ; } } return result ; }
Get key stack string to show as title in ui list .
35,898
public static int getNumCores ( ) { class CpuFilter implements FileFilter { public boolean accept ( File pathname ) { return Pattern . matches ( "cpu[0-9]" , pathname . getName ( ) ) ; } } if ( sCoreNum == 0 ) { try { File dir = new File ( "/sys/devices/system/cpu/" ) ; File [ ] files = dir . listFiles ( new CpuFilter ( ) ) ; sCoreNum = files . length ; } catch ( Exception e ) { Log . e ( TAG , "getNumCores exception" , e ) ; sCoreNum = 1 ; } } return sCoreNum ; }
Get cpu core number
35,899
public List < String > provideWhiteList ( ) { LinkedList < String > whiteList = new LinkedList < > ( ) ; whiteList . add ( "org.chromium" ) ; return whiteList ; }
Provide white list entry in white list will not be shown in ui list .