idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
35,200
public void setMetatags ( Map < String , String > metatags , String key ) { if ( metatags != null ) { TSDBEntity . validateTags ( metatags ) ; _metatags . clear ( ) ; _metatags . putAll ( metatags ) ; _key = key ; } }
Replaces the metatags for a metric . Metatags cannot use any of the reserved tag names .
35,201
public static < D extends TSDBEntityDto , E extends TSDBEntity > D createDtoObject ( Class < D > clazz , E tsdbEntity ) { D result = null ; try { result = clazz . newInstance ( ) ; BeanUtils . copyProperties ( result , tsdbEntity ) ; } catch ( Exception ex ) { throw new WebApplicationException ( "DTO transformation failed." , Status . INTERNAL_SERVER_ERROR ) ; } return result ; }
Converts a TSDB entity to a DTO .
35,202
public HttpClient getHttpClient ( SystemConfiguration config ) { HttpClient httpclient = new HttpClient ( theConnectionManager ) ; httpclient . getParams ( ) . setParameter ( "http.connection-manager.timeout" , 2000L ) ; String host = config . getValue ( Property . GUS_PROXY_HOST . getName ( ) , Property . GUS_PROXY_HOST . getDefaultValue ( ) ) ; if ( host != null && host . length ( ) > 0 ) { httpclient . getHostConfiguration ( ) . setProxy ( host , Integer . parseInt ( config . getValue ( Property . GUS_PROXY_PORT . getName ( ) , Property . GUS_PROXY_PORT . getDefaultValue ( ) ) ) ) ; } return httpclient ; }
Get HttpClient with proper proxy and timeout settings .
35,203
public String getTSDBMetricName ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( getMetric ( ) ) . append ( DefaultTSDBService . DELIMITER ) . append ( getScope ( ) ) ; if ( _namespace != null && ! _namespace . isEmpty ( ) ) { sb . append ( DefaultTSDBService . DELIMITER ) . append ( getNamespace ( ) ) ; } return sb . toString ( ) ; }
Returns the TSDB metric name .
35,204
public static ItemsCountDto transformToDto ( int value ) { if ( value < 0 ) { throw new WebApplicationException ( "Items count cannot be negative" , Status . INTERNAL_SERVER_ERROR ) ; } ItemsCountDto result = new ItemsCountDto ( ) ; result . setValue ( value ) ; return result ; }
Converts an integer to ItemsCountDto instance .
35,205
public void initializeTopic ( String topic ) { if ( _topics . get ( topic ) == null ) { synchronized ( this ) { if ( _topics . get ( topic ) == null ) { _logger . info ( "Initializing streams for topic: {}" , topic ) ; Properties props = new Properties ( ) ; props . setProperty ( "zookeeper.connect" , _configuration . getValue ( Property . ZOOKEEPER_CONNECT . getName ( ) , Property . ZOOKEEPER_CONNECT . getDefaultValue ( ) ) ) ; props . setProperty ( "group.id" , _configuration . getValue ( Property . KAFKA_CONSUMER_GROUPID . getName ( ) , Property . KAFKA_CONSUMER_GROUPID . getDefaultValue ( ) ) ) ; props . setProperty ( "auto.offset.reset" , _configuration . getValue ( Property . KAFKA_CONSUMER_OFFSET_RESET . getName ( ) , Property . KAFKA_CONSUMER_OFFSET_RESET . getDefaultValue ( ) ) ) ; props . setProperty ( "auto.commit.interval.ms" , "60000" ) ; props . setProperty ( "fetch.message.max.bytes" , "2000000" ) ; ConsumerConnector consumer = kafka . consumer . Consumer . createJavaConsumerConnector ( new ConsumerConfig ( props ) ) ; List < KafkaStream < byte [ ] , byte [ ] > > streams = _createStreams ( consumer , topic ) ; Topic t = new Topic ( topic , consumer , streams . size ( ) ) ; _topics . put ( topic , t ) ; _startStreamingMessages ( topic , streams ) ; } } } }
This method creates Kafka streams for a topic so that messages can be streamed to the local buffer . If the streams for the given topic have already been initialized the returns . Information about a particular topic is stored in a HashMap . This method uses double - checked locking to make sure only one client thread can initialize streams for a topic . Moreover it also helps subsequent calls to check if the topic has been initialized be not synchronized and hence return faster .
35,206
private void _startStreamingMessages ( String topic , List < KafkaStream < byte [ ] , byte [ ] > > streams ) { ExecutorService executorService = _topics . get ( topic ) . getStreamExecutorService ( ) ; for ( final KafkaStream < byte [ ] , byte [ ] > stream : streams ) { executorService . submit ( new KafkaConsumer ( stream ) ) ; } }
Retrieves the executor service for the given topic from the map of topics and submits a KafkaConsumer task for each stream in the list of streams .
35,207
public < T extends Serializable > List < T > dequeueFromBuffer ( String topic , Class < T > type , int timeout , int limit ) { List < T > result = new ArrayList < T > ( ) ; long cutoff = System . currentTimeMillis ( ) + timeout ; BlockingQueue < String > queue = _topics . get ( topic ) . getMessages ( ) ; while ( System . currentTimeMillis ( ) < cutoff && ( limit < 0 || result . size ( ) < limit ) ) { if ( Thread . currentThread ( ) . isInterrupted ( ) ) { break ; } try { String message = queue . poll ( timeout , TimeUnit . MILLISECONDS ) ; if ( message != null && ! message . isEmpty ( ) ) { if ( String . class . isAssignableFrom ( type ) ) { result . add ( type . cast ( message ) ) ; } else { result . add ( _mapper . readValue ( message , type ) ) ; } if ( result . size ( ) % 1000 == 0 ) { _logger . debug ( "Dequeued {} messages from local buffer." , result . size ( ) ) ; } } } catch ( InterruptedException e ) { _logger . warn ( "Interrupted while waiting for poll() to return a message." ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( IOException e ) { _logger . warn ( "Exception while deserializing message to type: " + type + ". Skipping this message." , e ) ; } } return result ; }
Dequeues messages from the local buffer as specified by the limit . If no messages are available to dequeue then waits for at most timeout milliseconds before returning .
35,208
public void shutdown ( ) { for ( Topic topic : _topics . values ( ) ) { if ( topic . getConsumerConnector ( ) != null ) { topic . getConsumerConnector ( ) . shutdown ( ) ; } topic . getStreamExecutorService ( ) . shutdownNow ( ) ; try { topic . getStreamExecutorService ( ) . awaitTermination ( 60 , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { _logger . warn ( "Stream executor service was interrupted while awaiting termination. This should never happen." ) ; } } _logger . debug ( "Pushing unflushed messages back to Kafka." ) ; Producer producer = new Producer ( _configuration ) ; for ( Map . Entry < String , Topic > entry : _topics . entrySet ( ) ) { String topicName = entry . getKey ( ) ; Topic topic = entry . getValue ( ) ; List < String > unflushedMessages = new ArrayList < String > ( ) ; if ( ! topic . getMessages ( ) . isEmpty ( ) ) { topic . getMessages ( ) . drainTo ( unflushedMessages ) ; producer . enqueue ( topicName , unflushedMessages ) ; } _logger . debug ( "{} messages for topic {} enqueued on Kafka queue" , unflushedMessages . size ( ) , topicName ) ; } producer . shutdown ( ) ; }
Enqueue un - flushed messages back on to Kafka .
35,209
public static boolean shouldRun ( String entry , Date atTime ) { entry = entry . trim ( ) . toUpperCase ( ) ; if ( ANNUALLY . equals ( entry ) || ( YEARLY . equals ( entry ) ) ) { entry = "0 0 1 1 *" ; } else if ( MONTHLY . equals ( entry ) ) { entry = "0 0 1 * *" ; } else if ( WEEKLY . equals ( entry ) ) { entry = "0 0 * * 0" ; } else if ( DAILY . equals ( entry ) || ( MIDNIGHT . equals ( entry ) ) ) { entry = "0 0 * * *" ; } else if ( HOURLY . equals ( entry ) ) { entry = "0 * * * *" ; } return new CronTabEntry ( entry ) . isRunnable ( atTime ) ; }
Determines if the given CRON entry is runnable at this current moment in time . This mimics the original implementation of the CRON table .
35,210
public static boolean isValid ( String entry ) { boolean result = true ; try { shouldRun ( entry ) ; } catch ( Exception ex ) { result = false ; } return result ; }
Determines if an entry is valid CRON syntax .
35,211
public List < Audit > getAuditsForEntity ( BigInteger entityId ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/entity/" + entityId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < Audit > > ( ) { } ) ; }
Returns the audit history for the given entity .
35,212
public Audit getAudit ( BigInteger id ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + id . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Audit . class ) ; }
Returns the audit item for the given audit ID .
35,213
public void setTag ( String key , String value ) { requireArgument ( key != null && ! key . trim ( ) . isEmpty ( ) , "Tag key cannot be null." ) ; requireArgument ( ! ReservedField . isReservedField ( key ) , "Tag is a reserved tag name." ) ; if ( value == null || value . isEmpty ( ) ) { _tags . remove ( key ) ; } else { _tags . put ( key , value ) ; } }
Sets a single tag for the query .
35,214
public String getTag ( String key ) { return ( ! Metric . ReservedField . isReservedField ( key ) ) ? _tags . get ( key ) : null ; }
Returns the tag value for the given key .
35,215
public final void setTags ( Map < String , String > tags ) { Map < String , String > updatedTags = new TreeMap < > ( ) ; if ( tags != null ) { for ( Map . Entry < String , String > entry : tags . entrySet ( ) ) { String key = entry . getKey ( ) ; requireArgument ( ! Metric . ReservedField . isReservedField ( key ) , MessageFormat . format ( "Tag {0} is a reserved tag name." , key ) ) ; updatedTags . put ( key , entry . getValue ( ) ) ; } } _tags . clear ( ) ; _tags . putAll ( updatedTags ) ; }
Replaces the tags for the query .
35,216
protected void setScope ( String scope ) { requireArgument ( scope != null && ! scope . isEmpty ( ) , "Scope cannot be null or empty." ) ; _scope = scope ; }
Sets the scope of the query .
35,217
protected void setMetric ( String metric ) { requireArgument ( metric != null && ! metric . isEmpty ( ) , "Metric name cannot be null or empty." ) ; _metric = metric ; }
Sets the metric name for the query .
35,218
protected String toTagParameterArray ( Map < String , String > tags ) throws UnsupportedEncodingException { if ( tags == null || tags . isEmpty ( ) ) { return "" ; } StringBuilder sb = new StringBuilder ( encode ( "{" , "UTF-8" ) ) ; for ( Map . Entry < String , String > tagEntry : tags . entrySet ( ) ) { sb . append ( tagEntry . getKey ( ) ) . append ( "=" ) ; String tagV = tagEntry . getValue ( ) . replaceAll ( "\\|" , encode ( "|" , "UTF-8" ) ) ; sb . append ( tagV ) . append ( "," ) ; } sb . replace ( sb . length ( ) - 1 , sb . length ( ) , encode ( "}" , "UTF-8" ) ) ; return sb . toString ( ) ; }
Returns the tags in TSDB query string format .
35,219
private Map < String , Double > getMinMax ( Map < Long , Double > metricData ) { double min = 0.0 ; double max = 0.0 ; boolean isMinMaxSet = false ; for ( Double value : metricData . values ( ) ) { double valueDouble = value ; if ( ! isMinMaxSet ) { min = valueDouble ; max = valueDouble ; isMinMaxSet = true ; } else { if ( valueDouble < min ) { min = valueDouble ; } else if ( valueDouble > max ) { max = valueDouble ; } } } Map < String , Double > minMax = new HashMap < > ( ) ; minMax . put ( "min" , min ) ; minMax . put ( "max" , max ) ; return minMax ; }
Identifies the min and max values of a metric
35,220
static void main ( String [ ] args , PrintStream out ) throws IOException { try { Main main = null ; Option [ ] options = Option . parseCLArgs ( args , TEMPLATES ) ; Option helpOption = ( options == null ) ? null : findOption ( HELP_OPTION . getName ( ) , options ) ; Option installOption = ( options == null ) ? null : findOption ( INSTALL_OPTION . getName ( ) , options ) ; Option configOption = ( options == null ) ? null : findOption ( CONFIG_OPTION . getName ( ) , options ) ; Option typeOption = ( options == null ) ? null : findOption ( TYPE_OPTION . getName ( ) , options ) ; if ( helpOption != null ) { out . println ( usage ( ) ) ; } else if ( installOption != null ) { SystemConfiguration . generateConfiguration ( System . in , out , new File ( installOption . getValue ( ) ) ) ; } else if ( configOption != null ) { FileInputStream fis = null ; Properties props = new Properties ( ) ; try { fis = new FileInputStream ( configOption . getValue ( ) ) ; props . load ( fis ) ; } finally { if ( fis != null ) { fis . close ( ) ; } } main = new Main ( props ) ; } else { main = new Main ( ) ; } if ( main != null ) { ClientType type ; try { type = typeOption == null ? COMMIT_METRICS : ClientType . valueOf ( typeOption . getValue ( ) ) ; } catch ( Exception ex ) { type = COMMIT_METRICS ; } final Thread mainThread = Thread . currentThread ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( new Runnable ( ) { public void run ( ) { mainThread . interrupt ( ) ; try { mainThread . join ( ) ; } catch ( InterruptedException ex ) { LOGGER . warn ( "Interrupted while shutting down. Giving up." ) ; } } } ) ) ; main . invoke ( type ) ; } } catch ( IllegalArgumentException ex ) { out . println ( usage ( ) ) ; } }
The main invocation method .
35,221
void invoke ( ClientType clientType ) { try { LOGGER . info ( "Starting service." ) ; ExecutorService service = ClientServiceFactory . startClientService ( _system , clientType , _jobCounter ) ; LOGGER . info ( "Service started." ) ; Thread currentThread = Thread . currentThread ( ) ; while ( ! currentThread . isInterrupted ( ) ) { try { Thread . sleep ( 500 ) ; } catch ( InterruptedException ex ) { currentThread . interrupt ( ) ; break ; } } LOGGER . info ( "Stopping service." ) ; service . shutdownNow ( ) ; try { if ( ! service . awaitTermination ( 60000 , TimeUnit . MILLISECONDS ) ) { LOGGER . warn ( "Shutdown timed out after 60 seconds. Exiting." ) ; } } catch ( InterruptedException iex ) { LOGGER . warn ( "Forcing shutdown." ) ; } LOGGER . info ( "Service stopped." ) ; } catch ( Exception ex ) { throw new SystemException ( "There was a problem invoking the committer." , ex ) ; } finally { if ( _system != null ) { _system . stop ( ) ; } LOGGER . info ( "Finished" ) ; } }
This method creates multiple threads to dequeue messages from message queue and push into TSDB . One thread is created for every type . Depending on message queue connection count multiple threads may be created for Metric type
35,222
public boolean enter ( ) throws KeeperException , InterruptedException { zooKeeper . create ( rootPath + "/" + name , new byte [ 0 ] , Ids . OPEN_ACL_UNSAFE , CreateMode . EPHEMERAL ) ; while ( true ) { synchronized ( mutex ) { List < String > list = zooKeeper . getChildren ( rootPath , true ) ; if ( list . size ( ) < size ) { mutex . wait ( ) ; } else { return true ; } } } }
Wait until required number of nodes join barrier
35,223
public boolean leave ( ) throws KeeperException , InterruptedException { zooKeeper . delete ( rootPath + "/" + name , 0 ) ; while ( true ) { synchronized ( mutex ) { List < String > list = zooKeeper . getChildren ( rootPath , true ) ; if ( list . size ( ) > 0 ) { mutex . wait ( ) ; } else { return true ; } } } }
Wait until all nodes leave barrier
35,224
public List < Metric > getMetrics ( List < String > expressions ) throws IOException , TokenExpiredException { StringBuilder requestUrl = new StringBuilder ( RESOURCE ) ; for ( int i = 0 ; i < expressions . size ( ) ; i ++ ) { requestUrl . append ( i == 0 ? "?" : "&" ) ; requestUrl . append ( "expression=" ) . append ( expressions . get ( i ) ) ; } ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl . toString ( ) , null ) ; assertValidResponse ( response , requestUrl . toString ( ) ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < Metric > > ( ) { } ) ; }
Returns the metrics for the given set of expressions .
35,225
public static String obtainLock ( EntityManager em , long expiration , long type , String note ) { EntityTransaction tx = null ; try { long now = System . currentTimeMillis ( ) ; tx = em . getTransaction ( ) ; tx . begin ( ) ; GlobalInterlock lock = _findAndRefreshLock ( em , type ) ; if ( lock != null && now - lock . lockTime > expiration ) { em . remove ( lock ) ; em . flush ( ) ; } tx . commit ( ) ; } catch ( Exception ex ) { LOGGER . warn ( "An error occurred trying to refresh the type {} lock: {}" , type , ex . getMessage ( ) ) ; LOGGER . debug ( ex . getMessage ( ) , ex ) ; if ( tx != null && tx . isActive ( ) ) { tx . rollback ( ) ; } } try { tx = em . getTransaction ( ) ; tx . begin ( ) ; GlobalInterlock lock = em . merge ( new GlobalInterlock ( type , note ) ) ; em . flush ( ) ; tx . commit ( ) ; return Long . toHexString ( lock . lockTime ) ; } catch ( Exception ex ) { throw new GlobalInterlockException ( "Could not obtain " + type + " lock" , ex ) ; } finally { if ( tx != null && tx . isActive ( ) ) { tx . rollback ( ) ; } } }
Obtains a global lock of a given type .
35,226
public static void releaseLock ( EntityManager em , long type , String key ) { EntityTransaction tx = null ; try { tx = em . getTransaction ( ) ; tx . begin ( ) ; GlobalInterlock lock = _findAndRefreshLock ( em , type ) ; if ( lock == null ) { throw new GlobalInterlockException ( "No lock of type " + type + " exists for key " + key + "." ) ; } String ref = Long . toHexString ( lock . lockTime ) ; if ( ref . equalsIgnoreCase ( key ) ) { em . remove ( lock ) ; em . flush ( ) ; tx . commit ( ) ; } else { throw new GlobalInterlockException ( "This process doesn't own the type " + type + " lock having key " + key + "." ) ; } } finally { if ( tx != null && tx . isActive ( ) ) { tx . rollback ( ) ; } } }
Releases a global lock of the indicated type if the supplied key is a match for the lock .
35,227
public static String refreshLock ( EntityManager em , long type , String key , String note ) { EntityTransaction tx = null ; try { tx = em . getTransaction ( ) ; tx . begin ( ) ; GlobalInterlock lock = _findAndRefreshLock ( em , type ) ; if ( lock == null ) { throw new GlobalInterlockException ( "No lock of type " + type + " exists for key " + key + "." ) ; } String ref = Long . toHexString ( lock . lockTime ) ; if ( ref . equalsIgnoreCase ( key ) ) { lock . lockTime = System . currentTimeMillis ( ) ; lock . note = note ; em . merge ( lock ) ; em . flush ( ) ; tx . commit ( ) ; return Long . toHexString ( lock . lockTime ) ; } throw new GlobalInterlockException ( "This process doesn't own the type " + type + " lock having key " + key + "." ) ; } finally { if ( tx != null && tx . isActive ( ) ) { tx . rollback ( ) ; } } }
Refreshes a global lock of the indicated type if the supplied key is a match for the lock .
35,228
public static AuditDto transformToDto ( Audit audit ) { if ( audit == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } AuditDto auditDto = new AuditDto ( ) ; try { auditDto . setId ( audit . getId ( ) ) ; auditDto . setHostName ( audit . getHostName ( ) ) ; auditDto . setMessage ( audit . getMessage ( ) ) ; auditDto . setCreatedDate ( audit . getCreatedDate ( ) ) ; auditDto . setEntityId ( audit . getEntityId ( ) ) ; } catch ( Exception ex ) { throw new WebApplicationException ( "DTO transformation failed." , Status . INTERNAL_SERVER_ERROR ) ; } return auditDto ; }
Converts the audit entity to DTO .
35,229
public static List < AuditDto > transformToDto ( List < Audit > audits ) { if ( audits == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } List < AuditDto > result = new ArrayList < AuditDto > ( ) ; for ( Audit audit : audits ) { result . add ( transformToDto ( audit ) ) ; } return result ; }
Converts a list of audit entities to DTOs .
35,230
public static int findInfractionCount ( EntityManager em , PrincipalUser user , SubSystem subSystem , long startTime ) { List < SuspensionRecord > records ; if ( subSystem == null ) { records = findByUser ( em , user ) ; } else { SuspensionRecord record = findByUserAndSubsystem ( em , user , subSystem ) ; records = record == null ? new ArrayList < SuspensionRecord > ( 0 ) : Arrays . asList ( new SuspensionRecord [ ] { record } ) ; } int count = 0 ; for ( SuspensionRecord record : records ) { List < Long > timestamps = record . getInfractionHistory ( ) ; for ( Long timestamp : timestamps ) { if ( timestamp > startTime ) { count ++ ; } } } return count ; }
Finds the number of user infractions for a subsystem that have occurred since the given start time .
35,231
public static SuspensionRecord findByUserAndSubsystem ( EntityManager em , PrincipalUser user , SubSystem subSystem ) { TypedQuery < SuspensionRecord > query = em . createNamedQuery ( "SuspensionRecord.findByUserAndSubsystem" , SuspensionRecord . class ) ; try { query . setParameter ( "user" , user ) ; query . setParameter ( "subSystem" , subSystem ) ; query . setHint ( "javax.persistence.cache.storeMode" , "REFRESH" ) ; return query . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Find the suspension record for a given user - subsystem combination .
35,232
public static List < SuspensionRecord > findByUser ( EntityManager em , PrincipalUser user ) { TypedQuery < SuspensionRecord > query = em . createNamedQuery ( "SuspensionRecord.findByUser" , SuspensionRecord . class ) ; try { query . setParameter ( "user" , user ) ; return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Find all suspension records for a given user .
35,233
public void setInfractionHistory ( List < Long > history ) { SystemAssert . requireArgument ( history != null && ! history . isEmpty ( ) , "Infraction History cannot be set to null or empty." ) ; this . infractionHistory = history ; }
Sets the detailed infraction history .
35,234
public Map < String , String > getTags ( ) { Map < String , String > result = new HashMap < > ( ) ; for ( Map . Entry < String , String > entry : _tags . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( ! ReservedField . isReservedField ( key ) ) { result . put ( key , entry . getValue ( ) ) ; } } return Collections . unmodifiableMap ( result ) ; }
Returns an unmodifiable collection of tags associated with the metric .
35,235
public void setTags ( Map < String , String > tags ) { TSDBEntity . validateTags ( tags ) ; _tags . clear ( ) ; if ( tags != null ) { _tags . putAll ( tags ) ; } }
Replaces the tags for a metric . Tags cannot use any of the reserved tag names .
35,236
private void setType ( String type ) { requireArgument ( type != null && ! type . trim ( ) . isEmpty ( ) , "Type cannot be null or empty." ) ; _type = type ; }
Sets the category of the metric .
35,237
private void setSource ( String source ) { requireArgument ( source != null && ! source . trim ( ) . isEmpty ( ) , "Source cannot be null or empty." ) ; _source = source ; }
Sets the source of the annotation .
35,238
private void setId ( String id ) { requireArgument ( id != null && ! id . trim ( ) . isEmpty ( ) , "ID cannot be null or empty." ) ; _id = id ; }
Sets the ID of the annotation as indicated by the data source .
35,239
public void setFields ( Map < String , String > fields ) { _fields . clear ( ) ; if ( fields != null ) { _fields . putAll ( fields ) ; } }
Replaces the user defined fields associated with the annotation . This information can be used to store information about the annotation such as the event name the associated user or any other relevant information . Existing fields will always be deleted .
35,240
public static PolicyLimit findPolicyLimitByUserAndCounter ( EntityManager em , PrincipalUser user , PolicyCounter counter ) { TypedQuery < PolicyLimit > query = em . createNamedQuery ( "PolicyLimit.findPolicyLimitByUserAndCounter" , PolicyLimit . class ) ; try { query . setParameter ( "user" , user ) ; query . setParameter ( "counter" , counter ) ; return query . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Retrieves the policy limit object for a given user - counter combination .
35,241
public static double getLimitByUserAndCounter ( EntityManager em , PrincipalUser user , PolicyCounter counter ) { PolicyLimit pLimit = findPolicyLimitByUserAndCounter ( em , user , counter ) ; if ( pLimit != null ) { return pLimit . getLimit ( ) ; } return counter . getDefaultValue ( ) ; }
Retrieves the limit for a given user - counter combination .
35,242
public static ServiceManagementRecord findServiceManagementRecord ( EntityManager em , Service service ) { requireArgument ( em != null , "Entity manager can not be null." ) ; requireArgument ( service != null , "Service cannot be null." ) ; TypedQuery < ServiceManagementRecord > query = em . createNamedQuery ( "ServiceManagementRecord.findByService" , ServiceManagementRecord . class ) ; try { query . setParameter ( "service" , service ) ; return query . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Returns a record for the specified service .
35,243
public static boolean isServiceEnabled ( EntityManager em , Service service ) { ServiceManagementRecord record = findServiceManagementRecord ( em , service ) ; return record == null ? true : record . isEnabled ( ) ; }
Determine a given service s enability .
35,244
public static ServiceManagementRecord updateServiceManagementRecord ( EntityManager em , ServiceManagementRecord record ) { SystemAssert . requireArgument ( em != null , "Entity manager can not be null." ) ; SystemAssert . requireArgument ( record != null , "ServiceManagementRecord cannot be null." ) ; TypedQuery < ServiceManagementRecord > query = em . createNamedQuery ( "ServiceManagementRecord.findByService" , ServiceManagementRecord . class ) ; query . setParameter ( "service" , record . getService ( ) ) ; try { ServiceManagementRecord oldRecord = query . getSingleResult ( ) ; oldRecord . setEnabled ( record . isEnabled ( ) ) ; return em . merge ( oldRecord ) ; } catch ( NoResultException ex ) { return em . merge ( record ) ; } }
Updates the ServiceManagementRecord entity .
35,245
private void _processNotification ( Alert alert , History history , List < Metric > metrics , Map < BigInteger , Map < Metric , Long > > triggerFiredTimesAndMetricsByTrigger , Notification notification , Long alertEnqueueTimestamp ) { boolean isRefocusNotifier = SupportedNotifier . REFOCUS . getName ( ) . equals ( notification . getNotifierName ( ) ) ; for ( Trigger trigger : notification . getTriggers ( ) ) { Map < Metric , Long > triggerFiredTimesForMetrics = triggerFiredTimesAndMetricsByTrigger . get ( trigger . getId ( ) ) ; for ( Metric m : metrics ) { if ( triggerFiredTimesForMetrics != null && triggerFiredTimesForMetrics . containsKey ( m ) ) { String logMessage = MessageFormat . format ( "The trigger {0} was evaluated against metric {1} and it is fired." , trigger . getName ( ) , m . getIdentifier ( ) ) ; history . appendMessageNUpdateHistory ( logMessage , null , 0 ) ; if ( isRefocusNotifier ) { sendNotification ( trigger , m , history , notification , alert , triggerFiredTimesForMetrics . get ( m ) , alertEnqueueTimestamp ) ; continue ; } if ( ! notification . onCooldown ( trigger , m ) ) { _updateNotificationSetActiveStatus ( trigger , m , history , notification ) ; sendNotification ( trigger , m , history , notification , alert , triggerFiredTimesForMetrics . get ( m ) , alertEnqueueTimestamp ) ; } else { logMessage = MessageFormat . format ( "The notification {0} is on cooldown until {1}." , notification . getName ( ) , getDateMMDDYYYY ( notification . getCooldownExpirationByTriggerAndMetric ( trigger , m ) ) ) ; history . appendMessageNUpdateHistory ( logMessage , null , 0 ) ; } } else { String logMessage = MessageFormat . format ( "The trigger {0} was evaluated against metric {1} and it is not fired." , trigger . getName ( ) , m . getIdentifier ( ) ) ; history . appendMessageNUpdateHistory ( logMessage , null , 0 ) ; if ( isRefocusNotifier ) { sendClearNotification ( trigger , m , history , notification , alert , alertEnqueueTimestamp ) ; continue ; } if ( notification . isActiveForTriggerAndMetric ( trigger , m ) ) { _updateNotificationClearActiveStatus ( trigger , m , notification ) ; sendClearNotification ( trigger , m , history , notification , alert , alertEnqueueTimestamp ) ; } } } } }
Evaluates all triggers associated with the notification and updates the job history .
35,246
private void _processMissingDataNotification ( Alert alert , History history , Set < Trigger > triggers , Notification notification , boolean isDataMissing , Long alertEnqueueTimestamp ) { boolean isRefocusNotifier = SupportedNotifier . REFOCUS . getName ( ) . equals ( notification . getNotifierName ( ) ) ; for ( Trigger trigger : notification . getTriggers ( ) ) { if ( triggers . contains ( trigger ) ) { Metric m = new Metric ( "argus" , "argus" ) ; if ( isDataMissing ) { String logMessage = MessageFormat . format ( "The trigger {0} was evaluated and it is fired as data for the metric expression {1} does not exist" , trigger . getName ( ) , alert . getExpression ( ) ) ; history . appendMessageNUpdateHistory ( logMessage , null , 0 ) ; if ( isRefocusNotifier ) { sendNotification ( trigger , m , history , notification , alert , System . currentTimeMillis ( ) , alertEnqueueTimestamp ) ; continue ; } if ( ! notification . onCooldown ( trigger , m ) ) { _updateNotificationSetActiveStatus ( trigger , m , history , notification ) ; sendNotification ( trigger , m , history , notification , alert , System . currentTimeMillis ( ) , alertEnqueueTimestamp ) ; } else { logMessage = MessageFormat . format ( "The notification {0} is on cooldown until {1}." , notification . getName ( ) , getDateMMDDYYYY ( notification . getCooldownExpirationByTriggerAndMetric ( trigger , m ) ) ) ; history . appendMessageNUpdateHistory ( logMessage , null , 0 ) ; } } else { String logMessage = MessageFormat . format ( "The trigger {0} was evaluated and it is not fired as data exists for the expression {1}" , trigger . getName ( ) , alert . getExpression ( ) ) ; history . appendMessageNUpdateHistory ( logMessage , null , 0 ) ; if ( isRefocusNotifier ) { sendClearNotification ( trigger , m , history , notification , alert , alertEnqueueTimestamp ) ; continue ; } if ( notification . isActiveForTriggerAndMetric ( trigger , m ) ) { _updateNotificationClearActiveStatus ( trigger , m , notification ) ; sendClearNotification ( trigger , m , history , notification , alert , alertEnqueueTimestamp ) ; } } } } }
Evaluates all triggers associated with the missing data notification and updates the job history .
35,247
private boolean _shouldEvaluateAlert ( Alert alert , BigInteger alertId ) { if ( alert == null ) { _logger . warn ( MessageFormat . format ( "Could not find alert ID {0}" , alertId ) ) ; return false ; } if ( ! alert . isEnabled ( ) ) { _logger . warn ( MessageFormat . format ( "Alert {0} has been disabled. Will not evaluate." , alert . getId ( ) . intValue ( ) ) ) ; return false ; } return true ; }
Determines if the alert should be evaluated or not .
35,248
private Map < BigInteger , Map < Metric , Long > > _evaluateTriggers ( Set < Trigger > triggers , List < Metric > metrics , String queryExpression , Long alertEnqueueTimestamp ) { Map < BigInteger , Map < Metric , Long > > triggerFiredTimesAndMetricsByTrigger = new HashMap < > ( ) ; for ( Trigger trigger : triggers ) { Map < Metric , Long > triggerFiredTimesForMetrics = new HashMap < > ( metrics . size ( ) ) ; for ( Metric metric : metrics ) { Long triggerFiredTime = getTriggerFiredDatapointTime ( trigger , metric , queryExpression , alertEnqueueTimestamp ) ; if ( triggerFiredTime != null ) { triggerFiredTimesForMetrics . put ( metric , triggerFiredTime ) ; Map < String , String > tags = new HashMap < > ( ) ; tags . put ( USERTAG , trigger . getAlert ( ) . getOwner ( ) . getUserName ( ) ) ; _monitorService . modifyCounter ( Counter . TRIGGERS_VIOLATED , 1 , tags ) ; } } triggerFiredTimesAndMetricsByTrigger . put ( trigger . getId ( ) , triggerFiredTimesForMetrics ) ; } return triggerFiredTimesAndMetricsByTrigger ; }
Evaluates all triggers for the given set of metrics and returns a map of triggerIds to a map containing the triggered metric and the trigger fired time .
35,249
public Notifier getNotifier ( SupportedNotifier notifier ) { switch ( notifier ) { case CALLBACK : return _notifierFactory . getCallbackNotifier ( ) ; case EMAIL : return _notifierFactory . getEmailNotifier ( ) ; case GOC : return _notifierFactory . getGOCNotifier ( ) ; case DATABASE : return _notifierFactory . getDBNotifier ( ) ; case WARDENAPI : return _notifierFactory . getWardenApiNotifier ( ) ; case WARDENPOSTING : return _notifierFactory . getWardenPostingNotifier ( ) ; case GUS : return _notifierFactory . getGusNotifier ( ) ; case REFOCUS : return _notifierFactory . getRefocusNotifier ( ) ; default : return _notifierFactory . getDBNotifier ( ) ; } }
Returns an instance of a supported notifier .
35,250
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { HttpServletRequest req = HttpServletRequest . class . cast ( request ) ; long start = System . currentTimeMillis ( ) ; try { chain . doFilter ( request , response ) ; } finally { long delta = System . currentTimeMillis ( ) - start ; HttpServletResponse resp = HttpServletResponse . class . cast ( response ) ; updateCounters ( req , resp , delta ) ; } }
Updates performance counters using the Argus monitoring service .
35,251
public static void setCommonAttributes ( List < Metric > metrics , Metric result ) { MetricDistiller distiller = new MetricDistiller ( ) ; distiller . distill ( metrics ) ; result . setDisplayName ( distiller . getDisplayName ( ) ) ; result . setUnits ( distiller . getUnits ( ) ) ; result . setTags ( distiller . getTags ( ) ) ; }
Filters common attributes from list of metrics and writes them to result metric .
35,252
public Map < String , String > getTags ( ) { Map < String , String > distilledTags = new HashMap < String , String > ( ) ; for ( Map . Entry < String , String > entry : potentialTags . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( tagCounts . get ( key ) . equals ( totalAdds ) ) { distilledTags . put ( key , value ) ; } } return distilledTags ; }
The common tags .
35,253
public static < D extends EntityDTO , E extends JPAEntity > D createDtoObject ( Class < D > clazz , E entity ) { D result = null ; try { result = clazz . newInstance ( ) ; BeanUtils . copyProperties ( result , entity ) ; result . setCreatedById ( entity . getCreatedBy ( ) != null ? entity . getCreatedBy ( ) . getId ( ) : null ) ; result . setModifiedById ( entity . getModifiedBy ( ) != null ? entity . getModifiedBy ( ) . getId ( ) : null ) ; } catch ( Exception ex ) { throw new WebApplicationException ( "DTO transformation failed." , Status . INTERNAL_SERVER_ERROR ) ; } return result ; }
Creates BaseDto object and copies properties from entity object .
35,254
public void execute ( JobExecutionContext context ) throws JobExecutionException { JobDataMap map = context . getJobDetail ( ) . getJobDataMap ( ) ; AlertService alertService = ( AlertService ) map . get ( "AlertService" ) ; AuditService auditService = ( AuditService ) map . get ( "AuditService" ) ; if ( map . containsKey ( LOCK_TYPE ) ) { lockType = ( LockType ) map . get ( LOCK_TYPE ) ; } if ( map . containsKey ( CRON_JOB ) ) { job = ( CronJob ) map . get ( CRON_JOB ) ; } try { if ( ! alertService . isDisposed ( ) ) { if ( LockType . ALERT_SCHEDULING . equals ( lockType ) ) { alertService . enqueueAlerts ( Arrays . asList ( new Alert [ ] { Alert . class . cast ( job ) } ) ) ; } else { throw new SystemException ( "Unsupported lock type " + lockType ) ; } } } catch ( Exception ex ) { auditService . createAudit ( "Could not enqueue scheduled job. " + ex . getMessage ( ) , JPAEntity . class . cast ( job ) ) ; } }
Passing the service instance from quartz main thread to worker thread as a parameter . Although the alert service used here is not thread safe we are using the enqueueAlerts in a thread safe manner since there is no shared mutable state in this method .
35,255
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { HttpServletRequest req = HttpServletRequest . class . cast ( request ) ; String url = req . getRequestURI ( ) ; LoggerFactory . getLogger ( getClass ( ) ) . debug ( "Request started: {}" , url ) ; long start = System . currentTimeMillis ( ) ; try { chain . doFilter ( request , response ) ; } finally { long delta = System . currentTimeMillis ( ) - start ; LoggerFactory . getLogger ( getClass ( ) ) . info ( "Request completed in {}ms: {}" , delta , url ) ; } }
Logs username request count and timing information .
35,256
public < T extends Serializable > int enqueue ( final String topic , List < T > objects ) { int messagesBuffered = 0 ; for ( T object : objects ) { final String value ; if ( String . class . isAssignableFrom ( object . getClass ( ) ) ) { value = String . class . cast ( object ) ; } else { try { value = _mapper . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { _logger . warn ( "Exception while serializing the object to a string. Skipping this object." , e ) ; continue ; } } try { boolean addedToBuffer = _executorService . submit ( new ProducerWorker ( topic , value ) ) . get ( ) ; if ( addedToBuffer ) { messagesBuffered ++ ; } } catch ( InterruptedException e ) { _logger . warn ( "Enqueue operation was interrupted by calling code." ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( ExecutionException e ) { throw new SystemException ( e ) ; } } return messagesBuffered ; }
Adds the messages to the Producer Buffer which will later be batched by Kafka and sent to the brokers .
35,257
public void shutdown ( ) { if ( _producer != null ) { _producer . close ( ) ; } _executorService . shutdown ( ) ; try { if ( ! _executorService . awaitTermination ( 10 , TimeUnit . SECONDS ) ) { _logger . warn ( "Shutdown of Kafka executor service timed out after 10 seconds." ) ; _executorService . shutdownNow ( ) ; } } catch ( InterruptedException ex ) { _logger . warn ( "Shutdown of executor service was interrupted." ) ; Thread . currentThread ( ) . interrupt ( ) ; } }
Shuts down the producer .
35,258
public static Metric getMetricToAnnotate ( String metric ) { Metric result = null ; if ( metric != null && ! metric . isEmpty ( ) ) { Pattern pattern = Pattern . compile ( "([\\w,\\-,\\.,/]+):([\\w,\\-,\\.,/]+)(\\{(?:[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)(?:,[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)*\\})?:([\\w,\\-,\\.,/]+)" ) ; Matcher matcher = pattern . matcher ( metric . replaceAll ( "\\s" , "" ) ) ; if ( matcher . matches ( ) ) { String scopeName = matcher . group ( 1 ) ; String metricName = matcher . group ( 2 ) ; String tagString = matcher . group ( 3 ) ; Map < String , String > tags = new HashMap < > ( ) ; if ( tagString != null ) { tagString = tagString . replaceAll ( "\\{" , "" ) . replaceAll ( "\\}" , "" ) ; for ( String tag : tagString . split ( "," ) ) { String [ ] entry = tag . split ( "=" ) ; tags . put ( entry [ 0 ] , entry [ 1 ] ) ; } } result = new Metric ( scopeName , metricName ) ; result . setTags ( tags ) ; } } return result ; }
Given a metric to annotate expression return a corresponding metric object .
35,259
public void setSubscriptions ( List < String > subscriptions ) { this . subscriptions . clear ( ) ; if ( subscriptions == null ) return ; for ( String currentSubscription : subscriptions ) { if ( this . getNotifierName ( ) . equals ( AlertService . SupportedNotifier . GUS . getName ( ) ) ) { if ( currentSubscription . isEmpty ( ) || currentSubscription . length ( ) < 10 ) throw new IllegalArgumentException ( "GUS Subscription has to contain subjectId with more than 10 characters." ) ; } else if ( this . getNotifierName ( ) . equals ( AlertService . SupportedNotifier . EMAIL . getName ( ) ) ) { if ( currentSubscription . isEmpty ( ) || ! currentSubscription . contains ( "@" ) ) { String errorMessage = MessageFormat . format ( "Email Address {0} is not allowed as @ not present." , currentSubscription ) ; throw new IllegalArgumentException ( errorMessage ) ; } } else if ( this . getNotifierName ( ) . equals ( AlertService . SupportedNotifier . CALLBACK . getName ( ) ) && currentSubscription . isEmpty ( ) ) { throw new IllegalArgumentException ( "Callback Notifier Subscription cannot be empty." ) ; } } if ( subscriptions != null && ! subscriptions . isEmpty ( ) ) { this . subscriptions . addAll ( subscriptions ) ; } }
Replaces the subscriptions used by the notifier to send the notifications .
35,260
public long getCooldownExpirationByTriggerAndMetric ( Trigger trigger , Metric metric ) { String key = _hashTriggerAndMetric ( trigger , metric ) ; return this . cooldownExpirationByTriggerAndMetric . containsKey ( key ) ? this . cooldownExpirationByTriggerAndMetric . get ( key ) : 0 ; }
Returns the cool down expiration time of the notification given a metric trigger combination .
35,261
public void setCooldownExpirationByTriggerAndMetric ( Trigger trigger , Metric metric , long cooldownExpiration ) { requireArgument ( cooldownExpiration >= 0 , "Cool down expiration time cannot be negative." ) ; String key = _hashTriggerAndMetric ( trigger , metric ) ; this . cooldownExpirationByTriggerAndMetric . put ( key , cooldownExpiration ) ; }
Sets the cool down expiration time of the notification given a metric trigger combination .
35,262
public void setMetricsToAnnotate ( List < String > metricsToAnnotate ) { this . metricsToAnnotate . clear ( ) ; if ( metricsToAnnotate != null && ! metricsToAnnotate . isEmpty ( ) ) { for ( String metric : metricsToAnnotate ) { requireArgument ( getMetricToAnnotate ( metric ) != null , "Metrics to annotate should be of the form 'scope:metric[{[tagk=tagv]+}]" ) ; this . metricsToAnnotate . add ( metric ) ; } } }
Sets metrics to be annotated .
35,263
public void setTriggers ( List < Trigger > triggers ) { this . triggers . clear ( ) ; if ( triggers != null ) { this . triggers . addAll ( triggers ) ; } }
Replaces the triggers associated with the notification .
35,264
public boolean isActiveForTriggerAndMetric ( Trigger trigger , Metric metric ) { String key = _hashTriggerAndMetric ( trigger , metric ) ; return this . activeStatusByTriggerAndMetric . containsKey ( key ) ? activeStatusByTriggerAndMetric . get ( key ) : false ; }
Given a metric notification combination indicates whether a triggering condition associated with this notification is still in a triggering state .
35,265
public void setActiveForTriggerAndMetric ( Trigger trigger , Metric metric , boolean active ) { String key = _hashTriggerAndMetric ( trigger , metric ) ; this . activeStatusByTriggerAndMetric . put ( key , active ) ; }
When a notification is sent out when a metric violates the trigger threshold set this notification active for that trigger metric combination
35,266
public static Option createFlag ( String name , String description ) { return new Option ( Type . FLAG , name , 0 , description ) ; }
Creates a new flag type option . These types of options are used to indicate some application switch is either on or off .
35,267
public static Option createOption ( String name , String description ) { return new Option ( Type . OPTION , name , 1 , description ) ; }
Returns a named option having one value . An example may be a logfile option for a program .
35,268
public static Option findListOption ( Option [ ] options ) { for ( int i = 0 ; i < options . length ; i ++ ) { if ( options [ i ] . getType ( ) == Type . LIST ) { return options [ i ] ; } } return null ; }
Returns a list type application option if one exists in the list provided .
35,269
public static Option findOption ( String name , Option [ ] options ) { for ( int i = 0 ; i < options . length ; i ++ ) { if ( options [ i ] . getName ( ) . equals ( name ) ) { return options [ i ] ; } } return null ; }
Returns an option with the given name .
35,270
public static Option [ ] parseCLArgs ( String [ ] args , Option [ ] templates ) { int i = 0 ; List < Option > options = new ArrayList < Option > ( args . length ) ; try { while ( i < args . length ) { String name = args [ i ++ ] ; Option template = findTemplate ( name , templates ) ; StringBuilder values = new StringBuilder ( ) ; if ( ! Type . LIST . equals ( template . getType ( ) ) ) { for ( int j = 0 ; j < template . getLen ( ) ; j ++ ) { values . append ( args [ i ++ ] ) . append ( " " ) ; } } else if ( hasMoreFlags ( args , -- i , templates ) ) { throw new IllegalArgumentException ( ) ; } else { for ( String arg : Arrays . copyOfRange ( args , i , args . length ) ) { values . append ( arg ) . append ( " " ) ; } template . setValue ( values . toString ( ) . trim ( ) ) ; Option [ ] result = new Option [ options . size ( ) + 1 ] ; result = options . toArray ( result ) ; result [ result . length - 1 ] = template ; return result ; } template . setValue ( values . toString ( ) . trim ( ) ) ; options . add ( template ) ; } return options . toArray ( new Option [ options . size ( ) ] ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } }
Parses the command line arguments of an application and compares those options against a list of expected options .
35,271
private static Option findTemplate ( String name , Option [ ] templates ) { boolean listAllowed = false ; Option listOption = null ; for ( int i = 0 ; i < templates . length ; i ++ ) { if ( templates [ i ] . getName ( ) . equals ( name ) ) { return templates [ i ] ; } if ( Type . LIST . equals ( templates [ i ] . getType ( ) ) ) { listAllowed = true ; listOption = templates [ i ] ; } } if ( listAllowed ) { return listOption ; } return null ; }
Searches an array of option templates and returns an option matching the supplied name or null if no match is found .
35,272
public String [ ] getValues ( ) { return value == null || value . isEmpty ( ) ? new String [ 0 ] : len == 1 ? new String [ ] { value } : value . split ( "\\s+" ) ; }
Returns the value of this option as an array . This array will be empty for flag options contain a single value for a simple option or a list of values for list type options .
35,273
private void sendMessage ( String aspectPath , boolean fired ) { if ( Boolean . valueOf ( _config . getValue ( SystemConfiguration . Property . REFOCUS_ENABLED ) ) ) { int refreshMaxTimes = Integer . parseInt ( _config . getValue ( Property . REFOCUS_CONNECTION_REFRESH_MAX_TIMES . getName ( ) , Property . REFOCUS_CONNECTION_REFRESH_MAX_TIMES . getDefaultValue ( ) ) ) ; try { RefocusSample refocusSample = new RefocusSample ( aspectPath , fired ? "1" : "0" ) ; RefocusTransport refocusTransport = RefocusTransport . getInstance ( ) ; HttpClient httpclient = refocusTransport . getHttpClient ( _config ) ; PostMethod post = null ; try { post = new PostMethod ( String . format ( "%s/v1/samples/upsert" , endpoint ) ) ; post . setRequestHeader ( "Authorization" , token ) ; post . setRequestEntity ( new StringRequestEntity ( refocusSample . toJSON ( ) , "application/json" , null ) ) ; for ( int i = 0 ; i < 1 + refreshMaxTimes ; i ++ ) { int respCode = httpclient . executeMethod ( post ) ; if ( respCode == 200 || respCode == 201 || respCode == 204 ) { _logger . info ( "Success - send Refocus sample '{}'." , refocusSample . toJSON ( ) ) ; break ; } else if ( respCode == 401 ) { continue ; } else { _logger . error ( "Failure - send Refocus sample '{}'. Response code '{}' response '{}'" , refocusSample . toJSON ( ) , respCode , post . getResponseBodyAsString ( ) ) ; break ; } } } catch ( Exception e ) { _logger . error ( "Failure - send Refocus sample '{}'. Exception '{}'" , refocusSample . toJSON ( ) , e ) ; } finally { if ( post != null ) { post . releaseConnection ( ) ; } } } catch ( RuntimeException ex ) { throw new SystemException ( "Failed to send an Refocus notification." , ex ) ; } } else { _logger . info ( "Sending Refocus notification is disabled. Not sending message for aspect '{}'." , aspectPath ) ; } }
Sends an Refocus sample .
35,274
public static NamespaceDto transformToDto ( Namespace namespace ) { if ( namespace == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } NamespaceDto result = createDtoObject ( NamespaceDto . class , namespace ) ; for ( PrincipalUser user : namespace . getUsers ( ) ) { result . addUsername ( user . getUserName ( ) ) ; } return result ; }
Converts a namespace entity to a DTO .
35,275
public void addUsername ( String username ) { SystemAssert . requireArgument ( username != null && ! username . isEmpty ( ) , "Username cannot be null or empty." ) ; this . usernames . add ( username ) ; }
Adds an authorized user .
35,276
public void setScope ( String scope ) { SystemAssert . requireArgument ( scope != null && ! scope . isEmpty ( ) , "Scope cannot be null or empty." ) ; this . scope = scope ; }
Specifies the scope of the query .
35,277
public void setMetric ( String metric ) { SystemAssert . requireArgument ( metric != null && ! metric . isEmpty ( ) , "Metric cannot be null or empty." ) ; this . metric = metric ; }
Specifies the metric name of the query .
35,278
private List < Alert > getSharedAlertsObj ( boolean populateMetaFieldsOnly , PrincipalUser owner , Integer limit ) { Set < Alert > result = new HashSet < > ( ) ; result . addAll ( populateMetaFieldsOnly ? alertService . findSharedAlerts ( true , owner , limit ) : alertService . findSharedAlerts ( false , owner , limit ) ) ; return new ArrayList < > ( result ) ; }
Returns list of shared alerts .
35,279
public void setCreatedDate ( Date createdDate ) { _createdDate = createdDate == null ? null : new Date ( createdDate . getTime ( ) ) ; }
Specifies the created date .
35,280
public static TriggerDto transformToDto ( Trigger trigger ) { TriggerDto result = createDtoObject ( TriggerDto . class , trigger ) ; result . setAlertId ( trigger . getAlert ( ) . getId ( ) ) ; for ( Notification notification : trigger . getNotifications ( ) ) { result . addNotificationIds ( notification ) ; } return result ; }
Converts trigger entity to triggerDto object .
35,281
public static List < TriggerDto > transformToDto ( List < Trigger > triggers ) { List < TriggerDto > result = new ArrayList < TriggerDto > ( ) ; for ( Trigger trigger : triggers ) { result . add ( transformToDto ( trigger ) ) ; } return result ; }
Converts list of trigger entity objects to list of triggerDto objects .
35,282
public static HistoryDTO transformToDto ( History history ) { if ( history == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } HistoryDTO historyDto = new HistoryDTO ( ) ; try { BeanUtils . copyProperties ( historyDto , history ) ; } catch ( Exception ex ) { throw new WebApplicationException ( "DTO transformation failed." , Status . INTERNAL_SERVER_ERROR ) ; } return historyDto ; }
Converts a history object to DTO .
35,283
public static List < HistoryDTO > transformToDto ( List < History > list ) { if ( list == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } List < HistoryDTO > result = new ArrayList < HistoryDTO > ( ) ; for ( History history : list ) { result . add ( transformToDto ( history ) ) ; } return result ; }
Converts a list of history entities to DTOs .
35,284
public < E extends Identifiable > E mergeEntity ( EntityManager em , E entity ) { requireArgument ( em != null , "The entity manager cannot be null." ) ; requireArgument ( entity != null , "The entity cannot be null." ) ; E ret = em . merge ( entity ) ; return ret ; }
Persists an entity to the database .
35,285
protected < E extends Identifiable > void deleteEntity ( EntityManager em , E entity ) { requireArgument ( em != null , "The entity manager cannot be null." ) ; requireArgument ( entity != null , "The entity cannot be null." ) ; if ( ! em . contains ( entity ) ) { Identifiable attached = findEntity ( em , entity . getId ( ) , entity . getClass ( ) ) ; em . remove ( attached ) ; } else { em . remove ( entity ) ; } }
Removes an entity from the database .
35,286
protected < E extends Identifiable > E findEntity ( EntityManager em , BigInteger id , Class < E > type ) { requireArgument ( em != null , "The entity manager cannot be null." ) ; requireArgument ( id != null && id . compareTo ( ZERO ) > 0 , "ID must be positive and non-zero" ) ; requireArgument ( type != null , "The entity cannot be null." ) ; em . getEntityManagerFactory ( ) . getCache ( ) . evictAll ( ) ; return em . find ( type , id ) ; }
Locates an entity based on it s primary key value .
35,287
protected < E extends Identifiable > List < E > findEntitiesMarkedForDeletion ( EntityManager em , Class < E > type , final int limit ) { requireArgument ( em != null , "The entity manager cannot be null." ) ; requireArgument ( type != null , "The entity cannot be null." ) ; requireArgument ( limit == - 1 || limit > 0 , "Limit if not -1, must be greater than 0." ) ; em . getEntityManagerFactory ( ) . getCache ( ) . evictAll ( ) ; return JPAEntity . findEntitiesMarkedForDeletion ( em , type , limit ) ; }
Returns a list of entities of the given type that are marked for deletion but have not yet been physically deleted .
35,288
private void fitParameters ( Map < Long , Double > metricData ) { mean = getMetricMean ( metricData ) ; variance = getMetricVariance ( metricData ) ; }
Fits the mean and variance parameters to the data
35,289
private Metric predictAnomalies ( Map < Long , Double > metricData ) { Metric predictions = new Metric ( getResultScopeName ( ) , getResultMetricName ( ) ) ; Map < Long , Double > predictionDatapoints = new HashMap < > ( ) ; if ( variance == 0.0 ) { for ( Entry < Long , Double > entry : metricData . entrySet ( ) ) { Long timestamp = entry . getKey ( ) ; predictionDatapoints . put ( timestamp , 0.0 ) ; } } else { for ( Entry < Long , Double > entry : metricData . entrySet ( ) ) { Long timestamp = entry . getKey ( ) ; double value = entry . getValue ( ) ; try { double anomalyScore = calculateAnomalyScore ( value ) ; predictionDatapoints . put ( timestamp , anomalyScore ) ; } catch ( ArithmeticException e ) { continue ; } } } predictions . setDatapoints ( predictionDatapoints ) ; return predictions ; }
Assigns an anomaly score to each data point indicating how likely it is to be an anomaly relative to other points .
35,290
private Alert _constructWardenAlertForUser ( PrincipalUser user , PolicyCounter counter ) { String metricExp = _constructWardenMetricExpression ( "-1h" , user , counter ) ; Alert alert = new Alert ( _adminUser , _adminUser , _constructWardenAlertName ( user , counter ) , metricExp , "*/5 * * * *" ) ; List < Trigger > triggers = new ArrayList < > ( ) ; EntityManager em = emf . get ( ) ; double limit = PolicyLimit . getLimitByUserAndCounter ( em , user , counter ) ; Trigger trigger = new Trigger ( alert , counter . getTriggerType ( ) , "counter-value-" + counter . getTriggerType ( ) . toString ( ) + "-policy-limit" , limit , 0.0 , 0L ) ; triggers . add ( trigger ) ; List < Notification > notifications = new ArrayList < > ( ) ; Notification notification = new Notification ( NOTIFICATION_NAME , alert , _getWardenNotifierClass ( counter ) , new ArrayList < String > ( ) , 3600000 ) ; List < String > metricAnnotationList = new ArrayList < String > ( ) ; String wardenMetricAnnotation = MessageFormat . format ( "{0}:{1}'{'user={2}'}':sum" , Counter . WARDEN_TRIGGERS . getScope ( ) , Counter . WARDEN_TRIGGERS . getMetric ( ) , user . getUserName ( ) ) ; metricAnnotationList . add ( wardenMetricAnnotation ) ; notification . setMetricsToAnnotate ( metricAnnotationList ) ; notification . setTriggers ( triggers ) ; notifications . add ( notification ) ; alert . setTriggers ( triggers ) ; alert . setNotifications ( notifications ) ; return alert ; }
Create a warden alert which will annotate the corresponding warden metric with suspension events .
35,291
private void _startScheduledExecutorService ( ) { DisableWardenAlertsThread disableWardenAlertThread = new DisableWardenAlertsThread ( ) ; _scheduledExecutorService . scheduleAtFixedRate ( disableWardenAlertThread , 0L , TIME_BETWEEN_WARDEN_ALERT_DISABLEMENT_MILLIS , TimeUnit . MILLISECONDS ) ; }
Starts the scheduled executor service .
35,292
private void _shutdownScheduledExecutorService ( ) { _logger . info ( "Shutting down scheduled disable warden alerts executor service" ) ; _scheduledExecutorService . shutdown ( ) ; try { if ( ! _scheduledExecutorService . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { _logger . warn ( "Shutdown of scheduled disable warden alerts executor service timed out after 5 seconds." ) ; _scheduledExecutorService . shutdownNow ( ) ; } } catch ( InterruptedException ex ) { _logger . warn ( "Shutdown of executor service was interrupted." ) ; Thread . currentThread ( ) . interrupt ( ) ; } }
Shuts down the scheduled executor service .
35,293
protected void _sendAdditionalNotification ( NotificationContext context , NotificationStatus status ) { requireArgument ( context != null , "Notification context cannot be null." ) ; if ( status == NotificationStatus . TRIGGERED ) { super . sendAdditionalNotification ( context ) ; } else { super . clearAdditionalNotification ( context ) ; } Notification notification = null ; Trigger trigger = null ; for ( Notification tempNotification : context . getAlert ( ) . getNotifications ( ) ) { if ( tempNotification . getName ( ) . equalsIgnoreCase ( context . getNotification ( ) . getName ( ) ) ) { notification = tempNotification ; break ; } } requireArgument ( notification != null , "Notification in notification context cannot be null." ) ; for ( Trigger tempTrigger : context . getAlert ( ) . getTriggers ( ) ) { if ( tempTrigger . getName ( ) . equalsIgnoreCase ( context . getTrigger ( ) . getName ( ) ) ) { trigger = tempTrigger ; break ; } } requireArgument ( trigger != null , "Trigger in notification context cannot be null." ) ; String body = getGOCMessageBody ( notification , trigger , context , status ) ; Severity sev = status == NotificationStatus . CLEARED ? Severity . OK : Severity . ERROR ; sendMessage ( sev , TemplateReplacer . applyTemplateChanges ( context , context . getNotification ( ) . getName ( ) ) , TemplateReplacer . applyTemplateChanges ( context , context . getAlert ( ) . getName ( ) ) , TemplateReplacer . applyTemplateChanges ( context , context . getTrigger ( ) . getName ( ) ) , body , context . getNotification ( ) . getSeverityLevel ( ) , context . getNotification ( ) . getSRActionable ( ) , context . getTriggerFiredTime ( ) , context . getTriggeredMetric ( ) ) ; }
Update the state of the notification to indicate whether the triggering condition exists or has been cleared .
35,294
public static < E extends Identifiable > E findByPrimaryKey ( EntityManager em , BigInteger id , Class < E > type ) { requireArgument ( em != null , "The entity manager cannot be null." ) ; requireArgument ( id != null && id . compareTo ( ZERO ) > 0 , "ID cannot be null and must be positive and non-zero" ) ; requireArgument ( type != null , "The entity type cannot be null." ) ; TypedQuery < E > query = em . createNamedQuery ( "JPAEntity.findByPrimaryKey" , type ) ; query . setHint ( "javax.persistence.cache.storeMode" , "REFRESH" ) ; try { query . setParameter ( "id" , id ) ; query . setParameter ( "deleted" , false ) ; return query . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Finds a JPA entity by its primary key .
35,295
public static < E extends Identifiable > List < E > findByPrimaryKeys ( EntityManager em , List < BigInteger > ids , Class < E > type ) { requireArgument ( em != null , "The entity manager cannot be null." ) ; requireArgument ( ids != null && ! ids . isEmpty ( ) , "IDs cannot be null or empty." ) ; requireArgument ( type != null , "The entity type cannot be null." ) ; TypedQuery < E > query = em . createNamedQuery ( "JPAEntity.findByPrimaryKeys" , type ) ; query . setHint ( "javax.persistence.cache.storeMode" , "REFRESH" ) ; try { query . setParameter ( "ids" , ids ) ; query . setParameter ( "deleted" , false ) ; return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Finds JPA entities by their primary keys .
35,296
public static < E extends Identifiable > List < E > findEntitiesMarkedForDeletion ( EntityManager em , Class < E > type , final int limit ) { requireArgument ( em != null , "Entity Manager cannot be null" ) ; requireArgument ( limit == - 1 || limit > 0 , "Limit if not -1, must be greater than 0." ) ; TypedQuery < E > query = em . createNamedQuery ( "JPAEntity.findByDeleteMarker" , type ) ; query . setHint ( "javax.persistence.cache.storeMode" , "REFRESH" ) ; try { query . setParameter ( "deleted" , true ) ; if ( limit > 0 ) { query . setMaxResults ( limit ) ; } return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Finds all entities that have been marked for deletion .
35,297
public PutResult putAnnotations ( List < Annotation > annotations ) throws IOException , TokenExpiredException { String requestUrl = COLLECTION_RESOURCE + RESOURCE ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . POST , requestUrl , annotations ) ; assertValidResponse ( response , requestUrl ) ; Map < String , Object > map = fromJson ( response . getResult ( ) , new TypeReference < Map < String , Object > > ( ) { } ) ; List < String > errorMessages = ( List < String > ) map . get ( "Error Messages" ) ; return new PutResult ( String . valueOf ( map . get ( "Success" ) ) , String . valueOf ( map . get ( "Errors" ) ) , errorMessages ) ; }
Submits annotations .
35,298
public static Double downsamplerReducer ( List < Double > values , String reducerType ) { List < Double > operands = new ArrayList < Double > ( ) ; for ( Double value : values ) { if ( value == null ) { operands . add ( 0.0 ) ; } else { operands . add ( value ) ; } } InternalReducerType type = InternalReducerType . fromString ( reducerType ) ; switch ( type ) { case AVG : return new Mean ( ) . evaluate ( Doubles . toArray ( operands ) ) ; case MIN : return Collections . min ( operands ) ; case MAX : return Collections . max ( operands ) ; case SUM : return new Sum ( ) . evaluate ( Doubles . toArray ( operands ) , 0 , operands . size ( ) ) ; case DEVIATION : return new StandardDeviation ( ) . evaluate ( Doubles . toArray ( operands ) ) ; case COUNT : values . removeAll ( Collections . singleton ( null ) ) ; return ( double ) values . size ( ) ; case PERCENTILE : return new Percentile ( ) . evaluate ( Doubles . toArray ( operands ) , Double . parseDouble ( reducerType . substring ( 1 ) ) ) ; default : throw new UnsupportedOperationException ( "Illegal type: " + reducerType + ". Please provide a valid type." ) ; } }
Implements down sampling .
35,299
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { String user = null ; if ( HttpServletRequest . class . isAssignableFrom ( request . getClass ( ) ) ) { HttpServletRequest req = HttpServletRequest . class . cast ( request ) ; String authorizationHeader = req . getHeader ( HttpHeaders . AUTHORIZATION ) ; if ( _requiresAuthentication ( req ) && ! "options" . equalsIgnoreCase ( req . getMethod ( ) ) ) { if ( authorizationHeader != null && authorizationHeader . startsWith ( "Bearer" ) ) { try { String jwt = authorizationHeader . substring ( "Bearer " . length ( ) ) . trim ( ) ; user = JWTUtils . validateTokenAndGetSubj ( jwt , JWTUtils . TokenType . ACCESS ) ; } catch ( UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e ) { HttpServletResponse httpresponse = HttpServletResponse . class . cast ( response ) ; httpresponse . setHeader ( "Access-Control-Allow-Origin" , req . getHeader ( "Origin" ) ) ; httpresponse . setHeader ( "Access-Control-Allow-Credentials" , "true" ) ; httpresponse . sendError ( HttpServletResponse . SC_UNAUTHORIZED , "Unsupported or Malformed JWT. Please provide a valid JWT." ) ; } catch ( SignatureException e ) { HttpServletResponse httpresponse = HttpServletResponse . class . cast ( response ) ; httpresponse . setHeader ( "Access-Control-Allow-Origin" , req . getHeader ( "Origin" ) ) ; httpresponse . setHeader ( "Access-Control-Allow-Credentials" , "true" ) ; httpresponse . sendError ( HttpServletResponse . SC_UNAUTHORIZED , "Signature Exception. Please provide a valid JWT." ) ; } catch ( ExpiredJwtException e ) { HttpServletResponse httpresponse = HttpServletResponse . class . cast ( response ) ; httpresponse . setHeader ( "Access-Control-Allow-Origin" , req . getHeader ( "Origin" ) ) ; httpresponse . setHeader ( "Access-Control-Allow-Credentials" , "true" ) ; httpresponse . sendError ( HttpServletResponse . SC_UNAUTHORIZED , "JWT has expired. Please obtain a new token." ) ; } } else { HttpServletResponse httpresponse = HttpServletResponse . class . cast ( response ) ; httpresponse . setHeader ( "Access-Control-Allow-Origin" , req . getHeader ( "Origin" ) ) ; httpresponse . setHeader ( "Access-Control-Allow-Credentials" , "true" ) ; httpresponse . sendError ( HttpServletResponse . SC_UNAUTHORIZED , HttpHeaders . AUTHORIZATION + " Header is either not proivded or incorrectly formatted." ) ; } } } try { MDC . put ( USER_ATTRIBUTE_NAME , user ) ; request . setAttribute ( USER_ATTRIBUTE_NAME , user ) ; chain . doFilter ( request , response ) ; } finally { MDC . remove ( USER_ATTRIBUTE_NAME ) ; } }
Authenticates a user if required .