idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
35,100
public < T extends Enum < ? > > T randomElement ( Class < T > enumType ) { return enumType . getEnumConstants ( ) [ randomBetween ( 0 , enumType . getEnumConstants ( ) . length - 1 ) ] ; }
Returns random enum value
35,101
public < T > List < T > randomElements ( List < T > elements , int count ) { if ( elements . size ( ) >= count ) { return extractRandomList ( elements , count ) ; } else { List < T > randomElements = new ArrayList < T > ( ) ; randomElements . addAll ( extractRandomList ( elements , count % elements . size ( ) ) ) ; do { randomElements . addAll ( extractRandomList ( elements , elements . size ( ) ) ) ; } while ( randomElements . size ( ) < count ) ; return randomElements ; } }
Creates new list being random subset of the passed list
35,102
private static String [ ] split ( String input ) { char macroStart = MACRO_START . charAt ( 0 ) ; char macroEnd = MACRO_END . charAt ( 0 ) ; int startIndex = 0 ; boolean inMacro = false ; List < String > list = new ArrayList < String > ( ) ; for ( int endIndex = 0 ; endIndex < input . length ( ) ; endIndex ++ ) { char chr = input . charAt ( endIndex ) ; if ( ! inMacro ) { if ( chr == macroStart ) { String result = input . substring ( startIndex , endIndex ) ; if ( result . length ( ) > 0 ) { list . add ( result ) ; } inMacro = true ; startIndex = endIndex ; } } else { if ( chr == macroEnd ) { String result = input . substring ( startIndex , endIndex + 1 ) ; if ( result . length ( ) > 0 ) { list . add ( result ) ; } inMacro = false ; startIndex = endIndex + 1 ; } } } String result = input . substring ( startIndex ) ; if ( result . length ( ) > 0 ) { list . add ( result ) ; } return list . toArray ( new String [ list . size ( ) ] ) ; }
Split keeping delimiters in split result
35,103
private void initDispatcherThreads ( Feature . AsynchronousMessageDispatch configuration ) { for ( int i = 0 ; i < configuration . getNumberOfMessageDispatchers ( ) ; i ++ ) { Thread dispatcher = configuration . getDispatcherThreadFactory ( ) . newThread ( new Runnable ( ) { public void run ( ) { while ( true ) { IMessagePublication publication = null ; try { publication = pendingMessages . take ( ) ; publication . execute ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return ; } catch ( Throwable t ) { handlePublicationError ( new InternalPublicationError ( t , "Error in asynchronous dispatch" , publication ) ) ; } } } } ) ; dispatcher . setName ( "MsgDispatcher-" + i ) ; dispatchers . add ( dispatcher ) ; dispatcher . start ( ) ; } }
initialize the dispatch workers
35,104
private IMessageFilter [ ] getFilter ( Method method , Handler subscription ) { Filter [ ] filterDefinitions = collectFilters ( method , subscription ) ; if ( filterDefinitions . length == 0 ) { return null ; } IMessageFilter [ ] filters = new IMessageFilter [ filterDefinitions . length ] ; int i = 0 ; for ( Filter filterDef : filterDefinitions ) { IMessageFilter filter = filterCache . get ( filterDef . value ( ) ) ; if ( filter == null ) { try { filter = filterDef . value ( ) . newInstance ( ) ; filterCache . put ( filterDef . value ( ) , filter ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } filters [ i ] = filter ; i ++ ; } return filters ; }
retrieve all instances of filters associated with the given subscription
35,105
public MessageListener getMessageListener ( Class target ) { MessageListener listenerMetadata = new MessageListener ( target ) ; Method [ ] allHandlers = ReflectionUtils . getMethods ( AllMessageHandlers , target ) ; final int length = allHandlers . length ; Method handler ; for ( int i = 0 ; i < length ; i ++ ) { handler = allHandlers [ i ] ; if ( ! ReflectionUtils . containsOverridingMethod ( allHandlers , handler ) ) { Handler handlerConfig = ReflectionUtils . getAnnotation ( handler , Handler . class ) ; Enveloped enveloped = ReflectionUtils . getAnnotation ( handler , Enveloped . class ) ; if ( ! handlerConfig . enabled ( ) || ! isValidMessageHandler ( handler ) ) { continue ; } Method overriddenHandler = ReflectionUtils . getOverridingMethod ( handler , target ) ; Map < String , Object > handlerProperties = MessageHandler . Properties . Create ( overriddenHandler == null ? handler : overriddenHandler , handlerConfig , enveloped , getFilter ( handler , handlerConfig ) , listenerMetadata ) ; MessageHandler handlerMetadata = new MessageHandler ( handlerProperties ) ; listenerMetadata . addHandler ( handlerMetadata ) ; } } return listenerMetadata ; }
listeners defined in super classes )
35,106
public static Method getOverridingMethod ( final Method overridingMethod , final Class subclass ) { Class current = subclass ; while ( ! current . equals ( overridingMethod . getDeclaringClass ( ) ) ) { try { return current . getDeclaredMethod ( overridingMethod . getName ( ) , overridingMethod . getParameterTypes ( ) ) ; } catch ( NoSuchMethodException e ) { current = current . getSuperclass ( ) ; } } return null ; }
Traverses the class hierarchy upwards starting at the given subclass looking for an override of the given methods - > finds the bottom most override of the given method if any exists
35,107
private static < A extends Annotation > A getAnnotation ( AnnotatedElement from , Class < A > annotationType , Set < AnnotatedElement > visited ) { if ( visited . contains ( from ) ) return null ; visited . add ( from ) ; A ann = from . getAnnotation ( annotationType ) ; if ( ann != null ) return ann ; for ( Annotation metaAnn : from . getAnnotations ( ) ) { ann = getAnnotation ( metaAnn . annotationType ( ) , annotationType , visited ) ; if ( ann != null ) { return ann ; } } return null ; }
Searches for an Annotation of the given type on the class . Supports meta annotations .
35,108
public List < MessageHandler > getHandlers ( IPredicate < MessageHandler > filter ) { List < MessageHandler > matching = new ArrayList < MessageHandler > ( ) ; for ( MessageHandler handler : handlers ) { if ( filter . apply ( handler ) ) { matching . add ( handler ) ; } } return matching ; }
used by unit tests
35,109
public T borrowObject ( ) { T object ; if ( ( object = pool . poll ( ) ) == null ) { object = createObject ( ) ; } return object ; }
Gets the next free object from the pool . If the pool doesn t contain any objects a new object will be created and given to the caller of this method back .
35,110
public static boolean validateAuthorizationRequest ( AuthRequestDto authRequestDto , OAuthApplicationDto oAuthApplicationDto ) throws OAuthException { if ( StringUtils . isNotBlank ( oAuthApplicationDto . getClientId ( ) ) && oAuthApplicationDto . getClientId ( ) . equals ( authRequestDto . getClientId ( ) ) ) { try { String decodedRedirectUri = java . net . URLDecoder . decode ( authRequestDto . getRedirectUri ( ) , "UTF-8" ) ; if ( StringUtils . isNotBlank ( oAuthApplicationDto . getRedirectUri ( ) ) && oAuthApplicationDto . getRedirectUri ( ) . equals ( decodedRedirectUri ) ) { return true ; } else { _logger . info ( "Request Redirect URI '" + authRequestDto . getRedirectUri ( ) + "' mismatch" ) ; throw new OAuthException ( ResponseCodes . INVALID_OR_MISSING_REDIRECT_URI , HttpResponseStatus . BAD_REQUEST ) ; } } catch ( UnsupportedEncodingException e ) { _logger . info ( "Request Redirect URI '" + authRequestDto . getRedirectUri ( ) + "' mismatch" ) ; throw new OAuthException ( ResponseCodes . INVALID_OR_MISSING_REDIRECT_URI , HttpResponseStatus . BAD_REQUEST ) ; } } else { _logger . info ( "Request Client ID '" + authRequestDto . getClientId ( ) + "' mismatch" ) ; throw new OAuthException ( ResponseCodes . INVALID_OR_MISSING_CLIENT_ID , HttpResponseStatus . BAD_REQUEST ) ; } }
Validates Authorization Request
35,111
public static String generateAuthorizationCode ( ) { StringBuilder buf = new StringBuilder ( AUTHORIZATION_CODE_LENGTH ) ; SecureRandom rand = new SecureRandom ( ) ; for ( int i = 0 ; i < AUTHORIZATION_CODE_LENGTH ; i ++ ) { buf . append ( allowedCharacters [ rand . nextInt ( allowedCharacters . length ) ] ) ; } return buf . toString ( ) ; }
Generated Unique Authorization Code
35,112
public static boolean validateTokenRequest ( TokenRequestDto tokenRequestDto , OAuthApplicationDto oAuthApplicationDto ) { try { String decodedRedirectUri = java . net . URLDecoder . decode ( tokenRequestDto . getRedirectUri ( ) , "UTF-8" ) ; if ( StringUtils . isNotBlank ( oAuthApplicationDto . getRedirectUri ( ) ) && oAuthApplicationDto . getRedirectUri ( ) . equals ( decodedRedirectUri ) ) { if ( StringUtils . isNotBlank ( tokenRequestDto . getGrantType ( ) ) ) { if ( OAuthFields . AUTHORIZATION_CODE . equals ( tokenRequestDto . getGrantType ( ) ) ) { return true ; } else { _logger . info ( "Grant Type '" + tokenRequestDto . getGrantType ( ) + "' is not supported" ) ; throw new OAuthException ( ResponseCodes . GRANT_TYPE_NOT_SUPPORTED , HttpResponseStatus . BAD_REQUEST ) ; } } else { _logger . info ( "Grant Type '" + tokenRequestDto . getGrantType ( ) + "' mismatch" ) ; throw new OAuthException ( ResponseCodes . INVALID_OR_MISSING_GRANT_TYPE , HttpResponseStatus . BAD_REQUEST ) ; } } else { _logger . info ( "Request Redirect URI '" + tokenRequestDto . getRedirectUri ( ) + "' mismatch" ) ; throw new OAuthException ( ResponseCodes . INVALID_OR_MISSING_REDIRECT_URI , HttpResponseStatus . BAD_REQUEST ) ; } } catch ( UnsupportedEncodingException e ) { _logger . info ( "Request Redirect URI '" + tokenRequestDto . getRedirectUri ( ) + "' mismatch" ) ; throw new OAuthException ( ResponseCodes . INVALID_OR_MISSING_REDIRECT_URI , HttpResponseStatus . BAD_REQUEST ) ; } }
Validates Token Request
35,113
public List < Metric > zip ( List < Metric > metrics , Metric baseMetric ) { SystemAssert . requireArgument ( baseMetric != null , "Zipper transform requires base metric as second param!" ) ; List < Metric > zippedMetrics = new ArrayList < Metric > ( ) ; Map < Long , Double > baseDatapoints = baseMetric . getDatapoints ( ) ; for ( Metric metric : metrics ) { Map < Long , Double > originalDatapoints = metric . getDatapoints ( ) ; Map < Long , Double > zippedDatadpoints = this . zip ( originalDatapoints , baseDatapoints ) ; metric . setDatapoints ( zippedDatadpoints ) ; zippedMetrics . add ( metric ) ; } return zippedMetrics ; }
Merges a list of metrics .
35,114
public Map < Long , Double > zip ( Map < Long , Double > originalDatapoints , Map < Long , Double > baseDatapoints ) { SystemAssert . requireArgument ( baseDatapoints != null && ! baseDatapoints . isEmpty ( ) , "Zipper transform requires valid baseDatapoints from base metric!" ) ; Map < Long , Double > zippedDP = new HashMap < > ( ) ; for ( Map . Entry < Long , Double > originalDP : originalDatapoints . entrySet ( ) ) { Long originalKey = originalDP . getKey ( ) ; Double originalVal = originalDP . getValue ( ) ; Double baseVal = baseDatapoints . containsKey ( originalKey ) ? baseDatapoints . get ( originalKey ) : null ; zippedDP . put ( originalKey , this . valueZipper . zip ( originalVal , baseVal ) ) ; } if ( fulljoinIndicator ) { for ( Map . Entry < Long , Double > baseDP : baseDatapoints . entrySet ( ) ) { Long baseDPKey = baseDP . getKey ( ) ; if ( ! zippedDP . containsKey ( baseDPKey ) ) { zippedDP . put ( baseDPKey , this . valueZipper . zip ( null , baseDP . getValue ( ) ) ) ; } } } return zippedDP ; }
Merges data points .
35,115
public static MethodHelpDto fromMethodClass ( String parentPath , Method method ) { String methodName = _getHttpMethod ( method ) ; Path path = method . getAnnotation ( Path . class ) ; Description description = method . getAnnotation ( Description . class ) ; Produces produces = method . getAnnotation ( Produces . class ) ; Consumes consumes = method . getAnnotation ( Consumes . class ) ; if ( ( path == null || ! path . value ( ) . contains ( "help" ) ) && description != null ) { String relativePath = path == null ? "" : path . value ( ) ; String fullPath = parentPath == null ? relativePath : parentPath + relativePath ; MethodHelpDto result = new MethodHelpDto ( ) ; result . setDescription ( description . value ( ) ) ; result . setMethod ( methodName ) ; result . setPath ( fullPath ) ; if ( produces != null ) { result . setProduces ( produces . value ( ) ) ; } if ( consumes != null ) { result . setConsumes ( consumes . value ( ) ) ; } List < MethodParameterDto > params = _getMethodParams ( method ) ; result . setParams ( params ) ; return result ; } else { return null ; } }
Creates a method help DTO from a method object .
35,116
private void putDataPoint ( int i , Entry < Long , Double > datapoint ) { timestamps [ i ] = datapoint . getKey ( ) ; values [ i ] = datapoint . getValue ( ) ; }
Puts the next data point of an iterator in the next section of internal buffer .
35,117
private boolean doesAnyTimeSeriesHaveData ( ) { for ( int i = 0 ; i < iterators . length ; i ++ ) { if ( ( timestamps [ iterators . length + i ] ) != MARK_END_TIME_SERIES ) { return true ; } } return false ; }
Indicates if there are values still to be read from any time series by inspecting the internal timestamp buffer
35,118
private long updateBufferChronologically ( ) { long minTimestamp = Long . MAX_VALUE ; long timestamp = 0 ; for ( int i = current ; i < iterators . length ; i ++ ) { if ( timestamps [ i ] != 0L && timestamps [ i + iterators . length ] == MARK_END_TIME_SERIES ) { timestamps [ i ] = 0L ; } } current = - 1 ; boolean isMultipleSeriesWithMinimum = false ; for ( int i = 0 ; i < iterators . length ; i ++ ) { timestamp = timestamps [ iterators . length + i ] ; if ( timestamp < minTimestamp ) { minTimestamp = timestamp ; current = i ; isMultipleSeriesWithMinimum = false ; } else if ( timestamp == minTimestamp ) { isMultipleSeriesWithMinimum = true ; } } updateCurrentAndNextSectionOfBuffer ( current ) ; if ( isMultipleSeriesWithMinimum ) { for ( int i = current + 1 ; i < iterators . length ; i ++ ) { timestamp = timestamps [ iterators . length + i ] ; if ( timestamp == minTimestamp ) { updateCurrentAndNextSectionOfBuffer ( i ) ; } } } return minTimestamp ; }
Choose smallest timestamp timeseries from the next section and update the current and next section of that time series
35,119
private void updateCurrentAndNextSectionOfBuffer ( int i ) { int next = iterators . length + i ; timestamps [ i ] = timestamps [ next ] ; values [ i ] = values [ next ] ; if ( iterators [ i ] . hasNext ( ) ) { putDataPoint ( next , ( Entry < Long , Double > ) iterators [ i ] . next ( ) ) ; } else { markEndTimeSeries ( i ) ; } }
Makes iterator number i move forward to the next data point in internal buffer Copies the next datapoint to current datapoint and uses the iterator to populate the next section
35,120
private void markEndTimeSeries ( int i ) { timestamps [ iterators . length + i ] = MARK_END_TIME_SERIES ; iterators [ i ] = null ; }
Mark the timestamp buffer as reached the end if the iterator has reached the end .
35,121
public double calculateAnomalyScore ( double value ) { double zScore = ( value - mean ) / Math . sqrt ( variance ) ; return Math . abs ( zScore ) ; }
Calculates the z - score of the data point which measures how many standard deviations the data point is away from the mean .
35,122
public static ArgusService getInstance ( String endpoint , int maxConn , int connTimeout , int connRequestTimeout ) throws IOException { ArgusHttpClient client = new ArgusHttpClient ( endpoint , maxConn , connTimeout , connRequestTimeout ) ; return new ArgusService ( client ) ; }
Returns a new instance of the Argus service .
35,123
protected static List < EndpointHelpDto > describeEndpoints ( List < Class < ? extends AbstractResource > > resourceClasses ) { List < EndpointHelpDto > result = new LinkedList < > ( ) ; if ( resourceClasses != null && ! resourceClasses . isEmpty ( ) ) { for ( Class < ? extends AbstractResource > resourceClass : resourceClasses ) { EndpointHelpDto dto = EndpointHelpDto . fromResourceClass ( resourceClass ) ; if ( dto != null ) { result . add ( dto ) ; } } } return result ; }
Generates a list of endpoint help DTOs used to describe the major service endpoints .
35,124
public PrincipalUser getRemoteUser ( HttpServletRequest req ) { requireArgument ( req != null , "Request cannot be null." ) ; if ( req . getHeader ( HttpHeaders . AUTHORIZATION ) != null ) { PrincipalUser result = null ; Object username = req . getAttribute ( AuthFilter . USER_ATTRIBUTE_NAME ) ; if ( username != null ) { result = userService . findUserByUsername ( String . class . cast ( username ) ) ; } return result ; } return null ; }
Returns the logged in user object .
35,125
@ Produces ( MediaType . APPLICATION_JSON ) @ Path ( "/help" ) public Map < String , List < ? extends Object > > help ( ) { Map < String , List < ? > > result = new LinkedHashMap < > ( ) ; List < EndpointHelpDto > endpoints = describeEndpoints ( getEndpoints ( ) ) ; if ( endpoints != null && ! endpoints . isEmpty ( ) ) { result . put ( "endpoints" , endpoints ) ; } List < MethodHelpDto > methods = describeMethods ( ) ; if ( methods != null && ! methods . isEmpty ( ) ) { result . put ( "methods" , methods ) ; } return result ; }
Returns the help for the endpoint . For the context root it will return the endpoint help for all major endpoints . For a specific endpoint it will return the method help for the endpoint .
35,126
protected List < MethodHelpDto > describeMethods ( ) { List < MethodHelpDto > result = new LinkedList < > ( ) ; Path endpointPath = getClass ( ) . getAnnotation ( Path . class ) ; for ( Method method : getClass ( ) . getDeclaredMethods ( ) ) { String parentPath = endpointPath == null ? null : endpointPath . value ( ) ; MethodHelpDto methodHelpDto = MethodHelpDto . fromMethodClass ( parentPath , method ) ; if ( methodHelpDto != null ) { result . add ( methodHelpDto ) ; } } Collections . sort ( result ) ; return result ; }
Generates help DTOs for each method on the service interface . The root context shall return a null list . All other endpoints will re - use this implementation .
35,127
protected PrincipalUser validateAndGetOwner ( HttpServletRequest req , String ownerName ) { PrincipalUser remoteUser = getRemoteUser ( req ) ; if ( ownerName == null || ownerName . isEmpty ( ) || ownerName . equalsIgnoreCase ( remoteUser . getUserName ( ) ) ) { return remoteUser ; } else if ( remoteUser . isPrivileged ( ) ) { PrincipalUser owner ; owner = userService . findUserByUsername ( ownerName ) ; if ( owner == null ) { throw new WebApplicationException ( ownerName + ": User does not exist." , Status . NOT_FOUND ) ; } else { return owner ; } } throw new WebApplicationException ( Status . FORBIDDEN . getReasonPhrase ( ) , Status . FORBIDDEN ) ; }
Validates the owner name and returns the owner object .
35,128
protected void validateResourceAuthorization ( HttpServletRequest req , PrincipalUser actualOwner , PrincipalUser currentOwner ) { if ( ! getRemoteUser ( req ) . isPrivileged ( ) && ! actualOwner . equals ( currentOwner ) ) { throw new WebApplicationException ( Status . FORBIDDEN . getReasonPhrase ( ) , Status . FORBIDDEN ) ; } }
Validates the resource authorization . Throws exception if the user is not authorized to access the resource .
35,129
protected void validatePrivilegedUser ( HttpServletRequest req ) { if ( ! getRemoteUser ( req ) . isPrivileged ( ) ) { throw new WebApplicationException ( Status . FORBIDDEN . getReasonPhrase ( ) , Status . FORBIDDEN ) ; } }
Validates that the user making the request is a privileged user .
35,130
protected void copyProperties ( Object dest , Object source ) { try { BeanUtils . copyProperties ( dest , source ) ; } catch ( Exception e ) { String errorMessage = MessageFormat . format ( "M:{0};;E:{1}" , e . getCause ( ) . getMessage ( ) , e . toString ( ) ) ; throw new WebApplicationException ( errorMessage , Status . BAD_REQUEST ) ; } }
Copies properties .
35,131
public void setDatapoints ( Map < Long , Double > datapoints ) { _datapoints . clear ( ) ; if ( datapoints != null ) { _datapoints . putAll ( datapoints ) ; } }
Deletes the current set of data points and replaces them with a new set .
35,132
public void addDatapoints ( Map < Long , Double > datapoints ) { if ( datapoints != null ) { _datapoints . putAll ( datapoints ) ; } }
Adds the current set of data points to the current set .
35,133
public void minimumExistingDatapoints ( Map < Long , Double > datapoints ) { if ( datapoints != null ) { for ( Entry < Long , Double > entry : datapoints . entrySet ( ) ) { Double existingValue = _datapoints . get ( entry . getKey ( ) ) ; if ( existingValue == null ) { _datapoints . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } else if ( existingValue > entry . getValue ( ) ) { _datapoints . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } }
If current set already has a value at that timestamp then sets the minimum of the two values for that timestamp at coinciding cutoff boundary else adds the new data points to the current set .
35,134
public void averageExistingDatapoints ( Map < Long , Double > datapoints ) { if ( datapoints != null ) { for ( Entry < Long , Double > entry : datapoints . entrySet ( ) ) { _datapoints . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }
If current set already has a value at that timestamp then replace the latest average value for that timestamp at coinciding cutoff boundary else adds the new data points to the current set .
35,135
public static SystemMain getSystem ( ) { try { _gate . await ( ) ; return _system ; } catch ( InterruptedException ex ) { _logger . warn ( "Interrupted while waiting for startup to complete." ) ; return null ; } }
Returns the system main instance .
35,136
private void setMeanDistancesToCentroids ( ) { meanDistancesToCentroids = new HashMap < > ( ) ; for ( int i = 0 ; i < clusterCentroids . numInstances ( ) ; i ++ ) { int countAssignedInstances = 0 ; double sumDistancesToCentroid = 0.0 ; Instance centroidInstance = clusterCentroids . instance ( i ) ; for ( int j = 0 ; j < trainingData . numInstances ( ) ; j ++ ) { if ( i == centroidAssignments [ j ] ) { Instance valueInstance = trainingData . instance ( j ) ; double distanceToCentroid = Math . abs ( valueInstance . value ( 0 ) - centroidInstance . value ( 0 ) ) ; sumDistancesToCentroid += distanceToCentroid ; countAssignedInstances ++ ; } } double meanDistanceToCentroid = sumDistancesToCentroid / countAssignedInstances ; meanDistancesToCentroids . put ( centroidInstance , meanDistanceToCentroid ) ; } }
For each cluster caches the mean distance from data points in the cluster to the cluster centroid . Mean distances are used later in anomaly score calculations .
35,137
public double calculateAnomalyScore ( double value ) { int instanceIndex = metricDataValues . indexOf ( value ) ; Instance valueInstance = trainingData . instance ( instanceIndex ) ; Instance centroidInstance = clusterCentroids . instance ( centroidAssignments [ instanceIndex ] ) ; if ( meanDistancesToCentroids . get ( centroidInstance ) == 0.0 ) { throw new ArithmeticException ( "Cannot divide by 0" ) ; } double distanceToCentroid = Math . abs ( valueInstance . value ( 0 ) - centroidInstance . value ( 0 ) ) ; double relativeDistanceToCentroid = distanceToCentroid / meanDistancesToCentroids . get ( centroidInstance ) ; return relativeDistanceToCentroid ; }
Calculates the relative distance of the data point to the centroid which is the ratio of the distance of the point to the centroid to the mean distance of all points in that cluster to the centroid .
35,138
private Map < String , List < Metric > > fractureMetricIntoDayBoundary ( List < Metric > metrics , MetricQuery query ) { Map < String , List < Metric > > cacheMap = new TreeMap < String , List < Metric > > ( ) ; String cacheKey ; Long nextTimeStampDay ; Long previousTimeStampDay ; Long startTimeStampDay = query . getStartTimestamp ( ) ; Long endTimeStampDay = query . getEndTimestamp ( ) ; for ( Metric metric : metrics ) { previousTimeStampDay = startTimeStampDay ; nextTimeStampDay = getNextDayBoundaryTimeStamp ( startTimeStampDay ) ; Metric tempMetric = new Metric ( metric ) ; Map < Long , Double > dataPoints = new LinkedHashMap < > ( ) ; for ( Map . Entry < Long , Double > dataPoint : metric . getDatapoints ( ) . entrySet ( ) ) { if ( dataPoint . getKey ( ) < nextTimeStampDay ) { dataPoints . put ( dataPoint . getKey ( ) , dataPoint . getValue ( ) ) ; } else { while ( dataPoint . getKey ( ) >= nextTimeStampDay ) { tempMetric . setDatapoints ( dataPoints ) ; cacheKey = constructMetricQueryKey ( previousTimeStampDay , metric , query ) ; cacheMap . put ( cacheKey , new ArrayList < Metric > ( Arrays . asList ( tempMetric ) ) ) ; cacheKey = constructMetricQueryKey ( previousTimeStampDay , query ) ; if ( cacheMap . containsKey ( cacheKey ) ) { cacheMap . get ( cacheKey ) . addAll ( Arrays . asList ( tempMetric ) ) ; } else { cacheMap . put ( cacheKey , new ArrayList < Metric > ( Arrays . asList ( tempMetric ) ) ) ; } tempMetric = new Metric ( metric ) ; dataPoints = new LinkedHashMap < > ( ) ; previousTimeStampDay = nextTimeStampDay ; nextTimeStampDay = getNextDayBoundaryTimeStamp ( nextTimeStampDay ) ; } dataPoints . put ( dataPoint . getKey ( ) , dataPoint . getValue ( ) ) ; } } while ( nextTimeStampDay < getNextDayBoundaryTimeStamp ( endTimeStampDay ) ) { tempMetric . setDatapoints ( dataPoints ) ; cacheKey = constructMetricQueryKey ( previousTimeStampDay , metric , query ) ; cacheMap . put ( cacheKey , new ArrayList < Metric > ( Arrays . asList ( tempMetric ) ) ) ; cacheKey = constructMetricQueryKey ( previousTimeStampDay , query ) ; if ( cacheMap . containsKey ( cacheKey ) ) { cacheMap . get ( cacheKey ) . addAll ( Arrays . asList ( tempMetric ) ) ; } else { cacheMap . put ( cacheKey , new ArrayList < Metric > ( Arrays . asList ( tempMetric ) ) ) ; } tempMetric = new Metric ( metric ) ; dataPoints = new LinkedHashMap < > ( ) ; previousTimeStampDay = nextTimeStampDay ; nextTimeStampDay = getNextDayBoundaryTimeStamp ( nextTimeStampDay ) ; } } return cacheMap ; }
From metric query and metric tag generate the cache keys . Fracture the metric data points into each key which stores one day worth of data .
35,139
private String constructMetricQueryKey ( Long startTimeStampBoundary , Metric metric , MetricQuery query ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( startTimeStampBoundary ) . append ( ":" ) ; sb . append ( query . getNamespace ( ) ) . append ( ":" ) ; sb . append ( query . getScope ( ) ) . append ( ":" ) ; sb . append ( query . getMetric ( ) ) . append ( ":" ) ; Map < String , String > treeMap = new TreeMap < > ( ) ; treeMap . putAll ( metric . getTags ( ) ) ; sb . append ( treeMap ) . append ( ":" ) ; sb . append ( query . getAggregator ( ) ) . append ( ":" ) ; sb . append ( query . getDownsampler ( ) ) . append ( ":" ) ; sb . append ( query . getDownsamplingPeriod ( ) ) ; return sb . toString ( ) ; }
Constructs a cache key from start time stamp boundary returned metric tags and metric query .
35,140
public List < Alert > getAlertsMeta ( boolean includeSharedAlerts ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/meta?shared=" + includeSharedAlerts ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < Alert > > ( ) { } ) ; }
Returns all alerts via the meta endpoint .
35,141
public Alert getAlert ( BigInteger alertId ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Alert . class ) ; }
Returns the alert for the given ID .
35,142
public List < Notification > getNotifications ( BigInteger alertId ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) + "/notifications" ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < Notification > > ( ) { } ) ; }
Returns all notifications for the given alert ID .
35,143
public Alert updateAlert ( BigInteger alertId , Alert alert ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . PUT , requestUrl , alert ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Alert . class ) ; }
Updates an existing alert .
35,144
public Notification updateNotification ( BigInteger alertId , BigInteger notificationId , Notification notification ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) + "/notifications/" + notificationId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . PUT , requestUrl , notification ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Notification . class ) ; }
Updates an existing notification .
35,145
public Trigger updateTrigger ( BigInteger alertId , BigInteger triggerId , Trigger trigger ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) + "/triggers/" + triggerId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . PUT , requestUrl , trigger ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Trigger . class ) ; }
Updates an existing trigger .
35,146
public List < Notification > createNotification ( BigInteger alertId , Notification notification ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) + "/notifications" ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . POST , requestUrl , notification ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < Notification > > ( ) { } ) ; }
Creates a new notification .
35,147
public List < Trigger > createTrigger ( BigInteger alertId , Trigger trigger ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) + "/triggers" ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . POST , requestUrl , trigger ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < Trigger > > ( ) { } ) ; }
Creates a new trigger .
35,148
public void deleteAlert ( BigInteger alertId ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + alertId . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . DELETE , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; }
Deletes an alert including its notifications and triggers .
35,149
public Map < MetricQuery , List < Metric > > join ( Map < MetricQuery , List < MetricQuery > > mapQuerySubQueries , Map < MetricQuery , List < Metric > > subQueryMetricsMap ) { Map < MetricQuery , List < Metric > > queryMetricsMap = new HashMap < > ( ) ; String metricIdentifier = null ; for ( Map . Entry < MetricQuery , List < MetricQuery > > entry : mapQuerySubQueries . entrySet ( ) ) { Map < String , Metric > metricMergeMap = new HashMap < > ( ) ; List < Metric > metrics = new ArrayList < > ( ) ; MetricQuery query = entry . getKey ( ) ; List < MetricQuery > subQueries = entry . getValue ( ) ; for ( MetricQuery subQuery : subQueries ) { List < Metric > metricsFromSubQuery = subQueryMetricsMap . get ( subQuery ) ; if ( metricsFromSubQuery != null ) { for ( Metric metric : metricsFromSubQuery ) { if ( metric != null ) { metricIdentifier = metric . getIdentifier ( ) ; Metric finalMetric = metricMergeMap . get ( metricIdentifier ) ; if ( finalMetric == null ) { metric . setQuery ( query ) ; metricMergeMap . put ( metricIdentifier , metric ) ; } else { if ( query . getDownsampler ( ) != null ) { switch ( query . getDownsampler ( ) ) { case SUM : finalMetric . sumExistingDatapoints ( metric . getDatapoints ( ) ) ; break ; case MIN : finalMetric . minimumExistingDatapoints ( metric . getDatapoints ( ) ) ; break ; case MAX : finalMetric . maximumExistingDatapoints ( metric . getDatapoints ( ) ) ; break ; case COUNT : finalMetric . sumExistingDatapoints ( metric . getDatapoints ( ) ) ; break ; case ZIMSUM : finalMetric . sumExistingDatapoints ( metric . getDatapoints ( ) ) ; break ; case AVG : finalMetric . averageExistingDatapoints ( metric . getDatapoints ( ) ) ; break ; default : finalMetric . addDatapoints ( metric . getDatapoints ( ) ) ; } } else { finalMetric . addDatapoints ( metric . getDatapoints ( ) ) ; } } } } } } metrics . addAll ( metricMergeMap . values ( ) ) ; queryMetricsMap . put ( query , metrics ) ; } return queryMetricsMap ; }
Merge metrics from smaller sub queries
35,150
protected String getTriggerDetails ( Trigger trigger , NotificationContext context ) { if ( trigger != null ) { String triggerString = trigger . toString ( ) ; triggerString = TemplateReplacer . applyTemplateChanges ( context , triggerString ) ; return triggerString . substring ( triggerString . indexOf ( "{" ) + 1 , triggerString . indexOf ( "}" ) ) ; } else { return "" ; } }
Returns the trigger detail information .
35,151
protected String getMetricUrl ( String metricToAnnotate , long triggerFiredTime ) { long start = triggerFiredTime - ( 6L * DateTimeConstants . MILLIS_PER_HOUR ) ; long end = Math . min ( System . currentTimeMillis ( ) , triggerFiredTime + ( 6L * DateTimeConstants . MILLIS_PER_HOUR ) ) ; String expression = MessageFormat . format ( "{0,number,#}:{1,number,#}:{2}" , start , end , metricToAnnotate ) ; return getExpressionUrl ( expression ) ; }
Returns the URL linking back to the metric for use in alert notification .
35,152
@ SuppressWarnings ( "deprecation" ) protected String getExpressionUrl ( String expression ) { String template = _config . getValue ( Property . AUDIT_METRIC_URL_TEMPLATE . getName ( ) , Property . AUDIT_METRIC_URL_TEMPLATE . getDefaultValue ( ) ) ; try { expression = URLEncoder . encode ( expression , "UTF-8" ) ; } catch ( Exception ex ) { expression = URLEncoder . encode ( expression ) ; } return template . replaceAll ( "\\$expression\\$" , expression ) ; }
Returns the URL linking back to the expression for use in alert notification .
35,153
protected String getAlertUrl ( BigInteger id ) { String template = _config . getValue ( Property . AUDIT_ALERT_URL_TEMPLATE . getName ( ) , Property . AUDIT_ALERT_URL_TEMPLATE . getDefaultValue ( ) ) ; return template . replaceAll ( "\\$alertid\\$" , String . valueOf ( id ) ) ; }
Returns the URL linking back to the alert for which notification is being sent .
35,154
public List < Audit > getAllNotifications ( JPAEntity entity ) { return _auditService . findByEntityHostnameMessage ( entity . getId ( ) , null , "Triggering event value:" ) ; }
Returns all audit entries for a notification .
35,155
public Namespace updateNamespace ( BigInteger id , Namespace namespace ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + id . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . PUT , requestUrl , namespace ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Namespace . class ) ; }
Updates a new namespace .
35,156
public Namespace updateNamespaceMembers ( BigInteger id , Set < String > users ) throws IOException , TokenExpiredException { String requestUrl = RESOURCE + "/" + id . toString ( ) + "/users" ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . PUT , requestUrl , users ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , Namespace . class ) ; }
Updates a the members of a namespace .
35,157
protected void sendWardenEmailToUser ( NotificationContext context , SubSystem subSystem ) { EntityManager em = emf . get ( ) ; PrincipalUser user = getWardenUser ( context . getAlert ( ) . getName ( ) ) ; SuspensionRecord record = SuspensionRecord . findByUserAndSubsystem ( em , user , subSystem ) ; Set < String > to = new HashSet < > ( ) ; to . add ( user . getEmail ( ) ) ; String subject = "Warden Email Notification" ; StringBuilder message = new StringBuilder ( ) ; message . append ( MessageFormat . format ( "<p>{0} has been suspended from the Argus system for violating the following policy</p>" , user . getUserName ( ) ) ) ; message . append ( MessageFormat . format ( "Subsystem: {0}" , subSystem . toString ( ) ) ) ; message . append ( MessageFormat . format ( "<br>Policy: {0}" , context . getAlert ( ) . getName ( ) . replace ( WARDEN_ALERT_NAME_PREFIX + user . getUserName ( ) + "-" , "" ) ) ) ; message . append ( MessageFormat . format ( "<br>Threshold: {0}" , context . getAlert ( ) . getTriggers ( ) . get ( 0 ) . getThreshold ( ) ) ) ; message . append ( MessageFormat . format ( "<br>Triggering Value: {0}" , context . getTriggerEventValue ( ) ) ) ; if ( record . getSuspendedUntil ( ) == - 1 ) { message . append ( "<br> You have been suspended indefinitely" ) ; } else { message . append ( MessageFormat . format ( "<br>Reinstatement Time: {0}" , DATE_FORMATTER . get ( ) . format ( new Date ( record . getSuspendedUntil ( ) ) ) ) ) ; } _mailService . sendMessage ( to , subject , message . toString ( ) , "text/html; charset=utf-8" , MailService . Priority . HIGH ) ; to . clear ( ) ; to . add ( "argus-admin@salesforce.com" ) ; message . append ( "<p><a href='" ) . append ( getAlertUrl ( context . getAlert ( ) . getId ( ) ) ) . append ( "'>Click here to view alert definition.</a><br/>" ) ; _mailService . sendMessage ( to , subject , message . toString ( ) , "text/html; charset=utf-8" , MailService . Priority . HIGH ) ; }
Sends an email to user and admin with information on suspension and when user will be reinstated .
35,158
protected PrincipalUser getWardenUser ( String wardenAlertName ) { assert ( wardenAlertName != null ) : "Warden alert name cannot be null." ; int beginIndex = wardenAlertName . indexOf ( "-" ) + 1 ; int endIndex = wardenAlertName . lastIndexOf ( "-" ) ; return PrincipalUser . findByUserName ( emf . get ( ) , wardenAlertName . substring ( beginIndex , endIndex ) ) ; }
From warden alert name de - constructs the user for whom this warden alert is associated with .
35,159
public static long findUniqueUserCount ( EntityManager em ) { TypedQuery < Long > query = em . createNamedQuery ( "PrincipalUser.findUniqueUserCount" , Long . class ) ; return query . getSingleResult ( ) ; }
Returns the unique user count .
35,160
public static PrincipalUser findByUserName ( EntityManager em , String userName ) { Class < PrincipalUser > type = PrincipalUser . class ; TypedQuery < PrincipalUser > query = em . createNamedQuery ( "PrincipalUser.findByUserName" , type ) ; try { return query . setParameter ( "userName" , userName ) . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Finds the application database user account for the provided user name .
35,161
public void setEmail ( String email ) { SystemAssert . requireArgument ( email != null && ! email . isEmpty ( ) , "Email cannot be null or empty." ) ; this . email = email ; }
Updates the email address for the user .
35,162
public void setUserName ( String userName ) { SystemAssert . requireArgument ( userName != null && ! userName . isEmpty ( ) , "Username cannot be null or empty." ) ; this . userName = userName ; }
Updates the user name for the user .
35,163
public void login ( String username , String password ) throws IOException { String requestUrl = RESOURCE + "/login" ; Credentials creds = new Credentials ( ) ; creds . setPassword ( password ) ; creds . setUsername ( username ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . POST , requestUrl , creds ) ; try { assertValidResponse ( response , requestUrl ) ; } catch ( TokenExpiredException e ) { throw new RuntimeException ( "This should never happen. login() method should never throw a TokenExpiredException" , e ) ; } Map < String , String > tokens = fromJson ( response . getResult ( ) , new TypeReference < Map < String , String > > ( ) { } ) ; getClient ( ) . accessToken = tokens . get ( "accessToken" ) ; getClient ( ) . refreshToken = tokens . get ( "refreshToken" ) ; }
Logs into Argus .
35,164
public static DashboardDto transformToDto ( Dashboard dashboard ) { if ( dashboard == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } DashboardDto result = createDtoObject ( DashboardDto . class , dashboard ) ; result . setOwnerName ( dashboard . getOwner ( ) . getUserName ( ) ) ; return result ; }
Converts dashboard entity to dashboardDto .
35,165
public static List < DashboardDto > transformToDto ( List < Dashboard > dashboards ) { if ( dashboards == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } List < DashboardDto > result = new ArrayList < DashboardDto > ( ) ; for ( Dashboard dashboard : dashboards ) { result . add ( transformToDto ( dashboard ) ) ; } return result ; }
Converts list of dashboard entity objects to list of dashboardDto objects .
35,166
public void setTemplateVars ( List < TemplateVar > templateVars ) { this . templateVars . clear ( ) ; if ( templateVars != null && ! templateVars . isEmpty ( ) ) { this . templateVars . addAll ( templateVars ) ; } }
Sets the template variables used in this dashboard .
35,167
public static EndpointHelpDto fromResourceClass ( Class < ? extends AbstractResource > resourceClass ) { Path path = resourceClass . getAnnotation ( Path . class ) ; Description description = resourceClass . getAnnotation ( Description . class ) ; if ( path != null && description != null ) { EndpointHelpDto result = new EndpointHelpDto ( ) ; result . setDescription ( description . value ( ) ) ; result . setEndpoint ( path . value ( ) ) ; return result ; } else { return null ; } }
Creates an endpoint help DTO from a resource class .
35,168
public static String getUsername ( String token ) { String accessTokenPayload = token . substring ( token . indexOf ( "." ) + 1 , token . lastIndexOf ( "." ) ) ; byte [ ] decoded = Base64 . getMimeDecoder ( ) . decode ( accessTokenPayload ) ; String output = new String ( decoded ) ; Map < String , Object > myMap = new HashMap < String , Object > ( ) ; String result = "unknown" ; ObjectMapper objectMapper = new ObjectMapper ( ) ; try { myMap = objectMapper . readValue ( output , HashMap . class ) ; if ( myMap . get ( "sub" ) instanceof String ) { result = ( String ) myMap . get ( "sub" ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } return result ; }
Username from a given JWT Token
35,169
protected void _setServiceEnabled ( boolean enabled ) { synchronized ( _serviceManagementRecordService ) { ServiceManagementRecord record = _serviceManagementRecordService . findServiceManagementRecord ( Service . SCHEDULING ) ; if ( record == null ) { record = new ServiceManagementRecord ( _userService . findAdminUser ( ) , Service . SCHEDULING , enabled ) ; } record . setEnabled ( enabled ) ; _serviceManagementRecordService . updateServiceManagementRecord ( record ) ; } }
Enables the scheduling service .
35,170
public static PrincipalUserDto transformToDto ( PrincipalUser user ) { if ( user == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } PrincipalUserDto result = createDtoObject ( PrincipalUserDto . class , user ) ; for ( Dashboard dashboard : user . getOwnedDashboards ( ) ) { result . addOwnedDashboardId ( dashboard . getId ( ) ) ; } return result ; }
Converts a user entity to DTO .
35,171
public String getStringValueForType ( SchemaService . RecordType type ) { switch ( type ) { case NAMESPACE : return getNamespace ( ) ; case SCOPE : return getScope ( ) ; case METRIC : return getMetric ( ) ; case TAGK : return getTagKey ( ) ; case TAGV : return getTagValue ( ) ; case RETENTION_DISCOVERY : return getRetentionDiscovery ( ) == null ? null : getRetentionDiscovery ( ) . toString ( ) ; default : return null ; } }
consolidate this method to where it belongs without fixing its legacy expectation that all members are of string type .
35,172
private boolean _canSkipWhileScanning ( MetricSchemaRecordQuery query , RecordType type ) { if ( ( RecordType . METRIC . equals ( type ) || RecordType . SCOPE . equals ( type ) ) && ! SchemaService . containsFilter ( query . getTagKey ( ) ) && ! SchemaService . containsFilter ( query . getTagValue ( ) ) && ! SchemaService . containsFilter ( query . getNamespace ( ) ) ) { if ( RecordType . METRIC . equals ( type ) && ! SchemaService . containsFilter ( query . getMetric ( ) ) ) { return false ; } if ( RecordType . SCOPE . equals ( type ) && ! SchemaService . containsFilter ( query . getScope ( ) ) ) { return false ; } return true ; } return false ; }
Check if we can perform a faster scan . We can only perform a faster scan when we are trying to discover scopes or metrics without having information on any other fields .
35,173
private ScanMetadata _constructScanMetadata ( MetricSchemaRecordQuery query ) { ScanMetadata metadata = new ScanMetadata ( ) ; char [ ] scopeTableRowKey = _constructRowKey ( query . getNamespace ( ) , query . getScope ( ) , query . getMetric ( ) , query . getTagKey ( ) , query . getTagValue ( ) , SCOPE_SCHEMA_TABLENAME ) . toCharArray ( ) ; char [ ] metricTableRowKey = _constructRowKey ( query . getNamespace ( ) , query . getScope ( ) , query . getMetric ( ) , query . getTagKey ( ) , query . getTagValue ( ) , METRIC_SCHEMA_TABLENAME ) . toCharArray ( ) ; int i = 0 , j = 0 ; for ( ; ( i < scopeTableRowKey . length && j < metricTableRowKey . length ) ; i ++ , j ++ ) { if ( SchemaService . isWildcardCharacter ( scopeTableRowKey [ i ] ) || SchemaService . isWildcardCharacter ( metricTableRowKey [ j ] ) ) { break ; } } while ( i < scopeTableRowKey . length && ! SchemaService . isWildcardCharacter ( scopeTableRowKey [ i ] ) ) { i ++ ; } while ( j < metricTableRowKey . length && ! SchemaService . isWildcardCharacter ( metricTableRowKey [ j ] ) ) { j ++ ; } if ( i < scopeTableRowKey . length && scopeTableRowKey [ i ] == '|' ) { while ( i >= 0 && scopeTableRowKey [ i ] != ROWKEY_SEPARATOR ) { i -- ; } i ++ ; } if ( j < metricTableRowKey . length && metricTableRowKey [ j ] == '|' ) { while ( j >= 0 && metricTableRowKey [ j ] != ROWKEY_SEPARATOR ) { j -- ; } j ++ ; } int indexOfWildcard ; String rowKey ; if ( i < j ) { metadata . tableName = METRIC_SCHEMA_TABLENAME ; indexOfWildcard = j ; rowKey = new String ( metricTableRowKey ) ; } else { metadata . tableName = SCOPE_SCHEMA_TABLENAME ; indexOfWildcard = i ; rowKey = new String ( scopeTableRowKey ) ; } String start = rowKey . substring ( 0 , indexOfWildcard ) ; metadata . startRow = start . getBytes ( Charset . forName ( "UTF-8" ) ) ; String end = "" ; if ( indexOfWildcard > 0 ) { char prev = rowKey . charAt ( indexOfWildcard - 1 ) ; char prevPlusOne = ( char ) ( prev + 1 ) ; end = rowKey . substring ( 0 , indexOfWildcard - 1 ) + prevPlusOne ; } metadata . stopRow = end . getBytes ( Charset . forName ( "UTF-8" ) ) ; return metadata ; }
Construct scan metadata depending on the query . This includes determining the table to query and the start and stop rows for the scan .
35,174
public List < MetricSchemaRecord > getMatchingRecords ( String namespaceRegex , String scopeRegex , String metricRegex , String tagKeyRegex , String tagValueRegex , int limit ) throws IOException , TokenExpiredException { StringBuilder urlBuilder = _buildBaseUrl ( namespaceRegex , scopeRegex , metricRegex , tagKeyRegex , tagValueRegex , limit ) ; String requestUrl = urlBuilder . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < MetricSchemaRecord > > ( ) { } ) ; }
Returns the schema records matching the specified criteria . At least one field matching expression must be supplied .
35,175
public List < String > getMatchingRecordFields ( String namespaceRegex , String scopeRegex , String metricRegex , String tagKeyRegex , String tagValueRegex , FieldSelector type , int limit ) throws IOException , TokenExpiredException { StringBuilder urlBuilder = _buildBaseUrl ( namespaceRegex , scopeRegex , metricRegex , tagKeyRegex , tagValueRegex , limit ) ; urlBuilder . append ( "&type=" ) . append ( type . name ( ) . toLowerCase ( Locale . ENGLISH ) ) ; String requestUrl = urlBuilder . toString ( ) ; ArgusResponse response = getClient ( ) . executeHttpRequest ( ArgusHttpClient . RequestType . GET , requestUrl , null ) ; assertValidResponse ( response , requestUrl ) ; return fromJson ( response . getResult ( ) , new TypeReference < List < String > > ( ) { } ) ; }
Returns the schema record fields values matching the specified criteria . At least one field matching expression must be supplied .
35,176
public ClientsResult calculateAllNodesResult ( ) { final List < String > childNodePaths = getChildren ( electionRootPath , false ) ; _logger . info ( "Total peers = {} " , childNodePaths . size ( ) ) ; Collections . sort ( childNodePaths ) ; int index = childNodePaths . indexOf ( clientNodePath . substring ( clientNodePath . lastIndexOf ( '/' ) + 1 ) ) ; return new ClientsResult ( index , childNodePaths . size ( ) ) ; }
Gets node index and its peer count
35,177
public String createNode ( final String path , final boolean watch , final boolean ephimeral ) { String createdNodePath = null ; try { final Stat nodeStat = zooKeeper . exists ( path , watch ) ; if ( nodeStat == null ) { createdNodePath = zooKeeper . create ( path , new byte [ 0 ] , Ids . OPEN_ACL_UNSAFE , ( ephimeral ? CreateMode . EPHEMERAL_SEQUENTIAL : CreateMode . PERSISTENT ) ) ; } else { createdNodePath = path ; } } catch ( KeeperException | InterruptedException e ) { throw new IllegalStateException ( e ) ; } return createdNodePath ; }
Create a zookeeper node
35,178
public List < String > getChildren ( final String path , final boolean watch ) { List < String > childNodes = null ; try { childNodes = zooKeeper . getChildren ( path , watch ) ; } catch ( KeeperException | InterruptedException e ) { throw new IllegalStateException ( e ) ; } return childNodes ; }
Gets list of children for a znode
35,179
public static Namespace findByQualifier ( EntityManager em , String qualifier ) { SystemAssert . requireArgument ( em != null , "EntityManager cannot be null." ) ; SystemAssert . requireArgument ( qualifier != null && ! qualifier . isEmpty ( ) , "Namespace qualifier cannot be null or empty." ) ; TypedQuery < Namespace > query = em . createNamedQuery ( "Namespace.findByQualifier" , Namespace . class ) ; try { return query . setParameter ( "qualifier" , qualifier ) . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Returns a namespace entity using the provided namespace qualifier .
35,180
public static List < Namespace > findByOwner ( EntityManager em , PrincipalUser owner ) { SystemAssert . requireArgument ( em != null , "EntityManager cannot be null." ) ; SystemAssert . requireArgument ( owner != null , "Owner cannot be null or empty." ) ; TypedQuery < Namespace > query = em . createNamedQuery ( "Namespace.findByOwner" , Namespace . class ) ; try { return query . setParameter ( "owner" , owner ) . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Finds all namespaces for a given owner .
35,181
public void setQualifier ( String qualifier ) { SystemAssert . requireArgument ( qualifier != null && ! qualifier . isEmpty ( ) , "Namespace qualifier cannot be null or empty." ) ; this . qualifier = qualifier ; }
Sets the namespace qualifier .
35,182
public void addUser ( PrincipalUser user ) { SystemAssert . requireArgument ( user != null , "Null user can not be added." ) ; users . add ( user ) ; }
Adds an authorized user of the namespace .
35,183
public static List < History > findHistoryByJob ( EntityManager em , BigInteger jobId , int limit ) { requireArgument ( em != null , "Entity manager cannot be null." ) ; requireArgument ( jobId != null , "The jobId cannot be null." ) ; requireArgument ( limit > 0 , "Limit must be a positive integer." ) ; TypedQuery < History > query = em . createNamedQuery ( "History.findByJob" , History . class ) ; query . setMaxResults ( limit ) ; try { query . setParameter ( "entityId" , jobId ) ; return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < History > ( 0 ) ; } }
Finds all history records for the given job .
35,184
public static int deleteExpiredHistory ( EntityManager em ) { requireArgument ( em != null , "Entity manager cannot be null." ) ; Query query = em . createNamedQuery ( "History.cullExpired" ) ; query . setParameter ( "expiryTime" , System . currentTimeMillis ( ) - ( 2 * MILLIS_PER_WEEK ) ) ; return query . executeUpdate ( ) ; }
Deletes the old job history .
35,185
public void setMessage ( String message ) { requireArgument ( message != null && ! message . isEmpty ( ) , "Message cannot be null or empty." ) ; this . message = message ; }
Sets the exception message .
35,186
public void setHostName ( String hostName ) { requireArgument ( hostName != null && ! hostName . isEmpty ( ) , "Hostname cannot be null or empty." ) ; this . hostName = hostName ; }
Sets the host name .
35,187
public static AnnotationDto transformToDto ( Annotation annotation ) { if ( annotation == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } AnnotationDto result = createDtoObject ( AnnotationDto . class , annotation ) ; return result ; }
Converts annotation entity to DTO .
35,188
public static AlertDto transformToDto ( Alert alert ) { if ( alert == null ) { throw new WebApplicationException ( "Null entity object cannot be converted to Dto object." , Status . INTERNAL_SERVER_ERROR ) ; } AlertDto result = createDtoObject ( AlertDto . class , alert ) ; result . setOwnerName ( alert . getOwner ( ) . getUserName ( ) ) ; for ( Trigger trigger : alert . getTriggers ( ) ) { result . addTriggersIds ( trigger ) ; } for ( Notification notification : alert . getNotifications ( ) ) { result . addNotificationsIds ( notification ) ; } return result ; }
Converts alert entity to alertDto .
35,189
public static List < Audit > findByHostName ( EntityManager em , String hostName ) { requireArgument ( em != null , "Entity manager cannot be null." ) ; requireArgument ( hostName != null && ! hostName . isEmpty ( ) , "Host name cannot be null or empty." ) ; TypedQuery < Audit > query = em . createNamedQuery ( "Audit.findByHostName" , Audit . class ) ; try { query . setParameter ( "hostName" , hostName ) ; return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < Audit > ( 0 ) ; } }
Finds all alerts created by given host name .
35,190
@ SuppressWarnings ( "unchecked" ) public static List < Audit > findByEntityHostnameMessage ( EntityManager em , JPAEntity entity , String hostName , String message ) { boolean isAndrequired = false ; StringBuilder queryString = new StringBuilder ( "SELECT a FROM Audit a " ) ; if ( entity != null ) { isAndrequired = true ; queryString . append ( " WHERE a.entityId=:entityId " ) ; } if ( hostName != null && ! hostName . isEmpty ( ) ) { if ( isAndrequired ) { queryString . append ( " AND " ) ; } else { isAndrequired = true ; queryString . append ( " WHERE " ) ; } queryString . append ( " a.hostName = :hostName " ) ; } if ( message != null && ! message . isEmpty ( ) ) { if ( isAndrequired ) { queryString . append ( " AND " ) ; } else { isAndrequired = true ; queryString . append ( " WHERE " ) ; } queryString . append ( " a.message LIKE :message " ) ; } Query query = em . createQuery ( queryString . toString ( ) , Audit . class ) ; if ( entity != null ) { query . setParameter ( "entityId" , entity . getId ( ) ) ; } if ( hostName != null && ! hostName . isEmpty ( ) ) { query . setParameter ( "hostName" , hostName ) ; } if ( message != null && ! message . isEmpty ( ) ) { query . setParameter ( "message" , "%" + message + "%" ) ; } return query . getResultList ( ) ; }
Finds audit history based on the entity host name and message fragment .
35,191
public static List < Audit > findByMessage ( EntityManager em , String message ) { requireArgument ( em != null , "Entity manager cannot be null." ) ; requireArgument ( message != null && ! message . isEmpty ( ) , "Message cannot be null or empty." ) ; TypedQuery < Audit > query = em . createNamedQuery ( "Audit.findByMessage" , Audit . class ) ; try { query . setParameter ( "message" , "%" + message + "%" ) ; return query . getResultList ( ) ; } catch ( Exception ex ) { return new ArrayList < Audit > ( 0 ) ; } }
Finds audits by exception message .
35,192
public static Dashboard findByNameAndOwner ( EntityManager em , String dashboardName , PrincipalUser owner ) { TypedQuery < Dashboard > query = em . createNamedQuery ( "Dashboard.findByNameAndOwner" , Dashboard . class ) ; try { query . setParameter ( "name" , dashboardName ) ; query . setParameter ( "owner" , owner ) ; return query . getSingleResult ( ) ; } catch ( NoResultException ex ) { return null ; } }
Finds Dashboard in the database with the specified dashboard name and owned by the specified owner .
35,193
public static List < Dashboard > findSharedDashboards ( EntityManager em , PrincipalUser owner , Integer limit , String version ) { requireArgument ( em != null , "Entity manager can not be null." ) ; TypedQuery < Dashboard > query ; if ( owner == null ) { if ( version == null ) { query = em . createNamedQuery ( "Dashboard.getSharedDashboards" , Dashboard . class ) ; } else { query = em . createNamedQuery ( "Dashboard.getSharedDashboardsByVersion" , Dashboard . class ) ; query . setParameter ( "version" , version ) ; } } else { if ( version == null ) { query = em . createNamedQuery ( "Dashboard.getSharedDashboardsByOwner" , Dashboard . class ) ; query . setParameter ( "owner" , owner ) ; } else { query = em . createNamedQuery ( "Dashboard.getSharedDashboardsByOwnerAndByVersion" , Dashboard . class ) ; query . setParameter ( "owner" , owner ) ; query . setParameter ( "version" , version ) ; } } query . setHint ( "javax.persistence.cache.storeMode" , "REFRESH" ) ; if ( limit != null ) { query . setMaxResults ( limit ) ; } try { return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Finds the list of dashboards that are marked as globally shared .
35,194
public static List < Dashboard > findSharedDashboardsMeta ( EntityManager em , PrincipalUser owner , Integer limit , String version ) { requireArgument ( em != null , "Entity manager can not be null." ) ; try { CriteriaBuilder cb = em . getCriteriaBuilder ( ) ; CriteriaQuery < Tuple > cq = cb . createTupleQuery ( ) ; Root < Dashboard > e = cq . from ( Dashboard . class ) ; List < Selection < ? > > fieldsToSelect = new ArrayList < > ( ) ; for ( Field field : FieldUtils . getFieldsListWithAnnotation ( Dashboard . class , Metadata . class ) ) { fieldsToSelect . add ( e . get ( field . getName ( ) ) . alias ( field . getName ( ) ) ) ; } cq . multiselect ( fieldsToSelect ) ; if ( owner != null ) { cq . where ( cb . equal ( e . get ( "shared" ) , true ) , cb . equal ( e . get ( "owner" ) , owner ) , version == null ? cb . isNull ( e . get ( "version" ) ) : cb . equal ( e . get ( "version" ) , version ) ) ; } else { cq . where ( cb . equal ( e . get ( "shared" ) , true ) , version == null ? cb . isNull ( e . get ( "version" ) ) : cb . equal ( e . get ( "version" ) , version ) ) ; } return _readDashboards ( em , cq , limit ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Gets all meta information of shared dashboards with filtering .
35,195
public static List < Dashboard > findDashboards ( EntityManager em , Integer limit , String version ) { requireArgument ( em != null , "Entity manager can not be null." ) ; TypedQuery < Dashboard > query ; if ( version == null ) { query = em . createNamedQuery ( "Dashboard.getDashboards" , Dashboard . class ) ; } else { query = em . createNamedQuery ( "Dashboard.getDashboardsByVersion" , Dashboard . class ) ; query . setParameter ( "version" , version ) ; } try { if ( limit != null ) { query . setMaxResults ( limit ) ; } return query . getResultList ( ) ; } catch ( NoResultException ex ) { return new ArrayList < > ( 0 ) ; } }
Returns dashboards ordered by owner and dashboard name .
35,196
public void setName ( String name ) { SystemAssert . requireArgument ( name != null && ! name . isEmpty ( ) , "Dashboard Name cannot be null or empty" ) ; this . name = name ; }
Sets the name for this Dashboard .
35,197
public List < Metric > union ( List < Metric > metrics ) { SystemAssert . requireArgument ( metrics != null , "Cannot transform empty metric/metrics" ) ; if ( metrics . isEmpty ( ) ) { return metrics ; } Metric newMetric = reduce ( metrics ) ; Map < Long , Double > reducedDatapoints = newMetric . getDatapoints ( ) ; Set < Long > sharedTimestamps = reducedDatapoints . keySet ( ) ; Map < Long , Double > unionDatapoints = new TreeMap < > ( ) ; for ( Metric metric : metrics ) { for ( Map . Entry < Long , Double > entry : metric . getDatapoints ( ) . entrySet ( ) ) { if ( ! sharedTimestamps . contains ( entry . getKey ( ) ) ) { unionDatapoints . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } newMetric . addDatapoints ( unionDatapoints ) ; return Arrays . asList ( newMetric ) ; }
Performs a columnar union of metrics .
35,198
public void setInertia ( Long inertiaMillis ) { if ( this . alert == null ) { this . inertia = inertiaMillis ; } else { requireArgument ( inertiaMillis != null && inertiaMillis >= 0 , "Inertia cannot be negative." ) ; Long longestIntervalLength = AlertUtils . getMaximumIntervalLength ( this . alert . getExpression ( ) ) ; if ( inertiaMillis > longestIntervalLength ) throw new IllegalArgumentException ( String . format ( "Inertia %d cannot be more than width of the longest interval %d." , inertiaMillis , longestIntervalLength ) ) ; this . inertia = inertiaMillis ; } }
Sets the inertia associated with the trigger in milliseconds .
35,199
public Map < String , String > getMetatags ( ) { Map < String , String > result = new HashMap < > ( ) ; for ( Map . Entry < String , String > entry : _metatags . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( ! ReservedField . isReservedField ( key ) ) { result . put ( key , entry . getValue ( ) ) ; } } return Collections . unmodifiableMap ( result ) ; }
Returns an unmodifiable collection of metatags associated with the metric .