idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
8,500
public static < K > Consumer < K > from ( K group , K name ) { LettuceAssert . notNull ( group , "Group must not be null" ) ; LettuceAssert . notNull ( name , "Name must not be null" ) ; return new Consumer < > ( group , name ) ; }
Create a new consumer .
8,501
@ TargetApi ( 21 ) public Bundler putSize ( String key , Size value ) { bundle . putSize ( key , value ) ; return this ; }
Inserts a Size value into the mapping of this Bundle replacing any existing value for the given key . Either key or value may be null .
8,502
@ TargetApi ( 21 ) public Bundler putSizeF ( String key , SizeF value ) { bundle . putSizeF ( key , value ) ; return this ; }
Inserts a SizeF value into the mapping of this Bundle replacing any existing value for the given key . Either key or value may be null .
8,503
public < T extends Fragment > T into ( T fragment ) { fragment . setArguments ( get ( ) ) ; return fragment ; }
Set the argument of Fragment .
8,504
private String cleanRoute ( String route ) { if ( ! route . startsWith ( "/" ) ) { route = "/" + route ; } if ( route . endsWith ( "/" ) ) { route = route . substring ( 0 , route . length ( ) - 1 ) ; } return route ; }
Leading slash but no trailing .
8,505
public UUID getMessageId ( ) { final ByteBuffer wrap = ByteBuffer . wrap ( messageIdBytes ) ; return new UUID ( wrap . asLongBuffer ( ) . get ( 0 ) , wrap . asLongBuffer ( ) . get ( 1 ) ) ; }
performance doesn t matter it s only being called during tracing
8,506
public Rule parseRule ( String id , String rule , boolean silent , PipelineClassloader ruleClassLoader ) throws ParseException { final ParseContext parseContext = new ParseContext ( silent ) ; final SyntaxErrorListener errorListener = new SyntaxErrorListener ( parseContext ) ; final RuleLangLexer lexer = new RuleLangLe...
Parses the given rule source and optionally generates a Java class for it if the classloader is not null .
8,507
public Messages process ( Messages messages , InterpreterListener interpreterListener , State state ) { interpreterListener . startProcessing ( ) ; final Set < Tuple2 < String , String > > processingBlacklist = Sets . newHashSet ( ) ; final List < Message > toProcess = Lists . newArrayList ( messages ) ; final List < M...
Evaluates all pipelines that apply to the given messages based on the current stream routing of the messages .
8,508
public List < Message > processForPipelines ( Message message , Set < String > pipelineIds , InterpreterListener interpreterListener , State state ) { final Map < String , Pipeline > currentPipelines = state . getCurrentPipelines ( ) ; final ImmutableSet < Pipeline > pipelinesToRun = pipelineIds . stream ( ) . map ( cu...
Given a set of pipeline ids process the given message according to the passed state .
8,509
public List < Stream > match ( Message message ) { final Set < Stream > result = Sets . newHashSet ( ) ; final Set < Stream > blackList = Sets . newHashSet ( ) ; for ( final Rule rule : rulesList ) { if ( blackList . contains ( rule . getStream ( ) ) ) { continue ; } final StreamRule streamRule = rule . getStreamRule (...
Returns a list of matching streams for the given message .
8,510
public void registerMetrics ( MetricRegistry metricRegistry , String pipelineId ) { meterName = name ( Pipeline . class , pipelineId , "stage" , String . valueOf ( stage ( ) ) , "executed" ) ; executed = metricRegistry . meter ( meterName ) ; }
Register the metrics attached to this stage .
8,511
public boolean greaterMinor ( Version other ) { return other . major < this . major || other . major == this . major && other . minor < this . minor ; }
Check if this version is higher than the passed other version . Only taking major and minor version number in account .
8,512
public static byte [ ] readBytes ( ByteBuffer buffer , int offset , int size ) { final byte [ ] dest = new byte [ size ] ; buffer . get ( dest , offset , size ) ; return dest ; }
Read a byte array from the given offset and size in the buffer
8,513
public static Map < String , Object > convertValues ( final Map < String , Object > data , final ConfigurationRequest configurationRequest ) throws ValidationException { final Map < String , Object > configuration = Maps . newHashMapWithExpectedSize ( data . size ( ) ) ; final Map < String , Map < String , Object > > c...
Converts the values in the map to the requested types . This has been copied from the Graylog web interface and should be removed once we have better configuration objects .
8,514
public static Optional < String > extractStreamId ( String filter ) { if ( isNullOrEmpty ( filter ) ) { return Optional . empty ( ) ; } final Matcher streamIdMatcher = filterStreamIdPattern . matcher ( filter ) ; if ( streamIdMatcher . find ( ) ) { return Optional . of ( streamIdMatcher . group ( 2 ) ) ; } return Optio...
Extracts the last stream id from the filter string passed as part of the elasticsearch query . This is used later to pass to possibly existing message decorators for stream - specific configurations .
8,515
public Rule invokableCopy ( FunctionRegistry functionRegistry ) { final Builder builder = toBuilder ( ) ; final Class < ? extends GeneratedRule > ruleClass = generatedRuleClass ( ) ; if ( ruleClass != null ) { try { final Set < Constructor > constructors = ReflectionUtils . getConstructors ( ruleClass ) ; final Constru...
Creates a copy of this Rule with a new instance of the generated rule class if present .
8,516
public Optional < IndexFieldTypesDTO > pollIndex ( final String indexName , final String indexSetId ) { final GetMapping getMapping = new GetMapping . Builder ( ) . addIndex ( indexName ) . build ( ) ; final JestResult result ; try ( final Timer . Context ignored = pollTimer . time ( ) ) { result = JestUtils . execute ...
Returns the index field types for the given index .
8,517
public static NetFlowV9Header parseHeader ( ByteBuf bb ) { final int version = bb . readUnsignedShort ( ) ; if ( version != 9 ) { throw new InvalidFlowVersionException ( version ) ; } final int count = bb . readUnsignedShort ( ) ; final long sysUptime = bb . readUnsignedInt ( ) ; final long unixSecs = bb . readUnsigned...
Flow Header Format
8,518
public static List < NetFlowV9Template > parseTemplates ( ByteBuf bb , NetFlowV9FieldTypeRegistry typeRegistry ) { final ImmutableList . Builder < NetFlowV9Template > templates = ImmutableList . builder ( ) ; int len = bb . readUnsignedShort ( ) ; int p = 4 ; while ( p < len ) { final NetFlowV9Template template = parse...
Template FlowSet Format
8,519
public static List < Map . Entry < Integer , byte [ ] > > parseTemplatesShallow ( ByteBuf bb ) { final ImmutableList . Builder < Map . Entry < Integer , byte [ ] > > templates = ImmutableList . builder ( ) ; int len = bb . readUnsignedShort ( ) ; int p = 4 ; while ( p < len ) { final int start = bb . readerIndex ( ) ; ...
Like above but only retrieves the bytes and template ids
8,520
public static NetFlowV9OptionTemplate parseOptionTemplate ( ByteBuf bb , NetFlowV9FieldTypeRegistry typeRegistry ) { int length = bb . readUnsignedShort ( ) ; final int templateId = bb . readUnsignedShort ( ) ; int optionScopeLength = bb . readUnsignedShort ( ) ; int optionLength = bb . readUnsignedShort ( ) ; int p = ...
Options Template Format
8,521
public static List < NetFlowV9BaseRecord > parseRecords ( ByteBuf bb , Map < Integer , NetFlowV9Template > cache , NetFlowV9OptionTemplate optionTemplate ) { List < NetFlowV9BaseRecord > records = new ArrayList < > ( ) ; int flowSetId = bb . readUnsignedShort ( ) ; int length = bb . readUnsignedShort ( ) ; int end = bb...
Data FlowSet Format
8,522
public static Integer parseRecordShallow ( ByteBuf bb ) { final int start = bb . readerIndex ( ) ; int usedTemplateId = bb . readUnsignedShort ( ) ; int length = bb . readUnsignedShort ( ) ; int end = bb . readerIndex ( ) - 4 + length ; bb . readerIndex ( end ) ; return usedTemplateId ; }
like above but contains all records for the template id as raw bytes
8,523
public void upgrade ( ) { this . indexSetService . findAll ( ) . stream ( ) . map ( mongoIndexSetFactory :: create ) . flatMap ( indexSet -> getReopenedIndices ( indexSet ) . stream ( ) ) . map ( indexName -> { LOG . debug ( "Marking index {} to be reopened using alias." , indexName ) ; return indexName ; } ) . forEach...
Create aliases for legacy reopened indices .
8,524
protected String buildQueryFilter ( String streamId , String query ) { checkArgument ( streamId != null , "streamId parameter cannot be null" ) ; final String trimmedStreamId = streamId . trim ( ) ; checkArgument ( ! trimmedStreamId . isEmpty ( ) , "streamId parameter cannot be empty" ) ; final StringBuilder builder = ...
Combines the given stream ID and query string into a single filter string .
8,525
private int findFrameSizeValueLength ( final ByteBuf buffer ) { final int readerIndex = buffer . readerIndex ( ) ; int index = buffer . forEachByte ( BYTE_PROCESSOR ) ; if ( index >= 0 ) { return index - readerIndex ; } else { return - 1 ; } }
Find the byte length of the frame length value .
8,526
public synchronized Mongo connect ( ) { if ( m == null ) { final String dbName = mongoClientURI . getDatabase ( ) ; if ( isNullOrEmpty ( dbName ) ) { LOG . error ( "The MongoDB database name must not be null or empty (mongodb_uri was: {})" , mongoClientURI ) ; throw new RuntimeException ( "MongoDB database name is miss...
Connect the instance .
8,527
protected DBSort . SortBuilder getSortBuilder ( String order , String field ) { DBSort . SortBuilder sortBuilder ; if ( "desc" . equalsIgnoreCase ( order ) ) { sortBuilder = DBSort . desc ( field ) ; } else { sortBuilder = DBSort . asc ( field ) ; } return sortBuilder ; }
Returns a sort builder for the given order and field name .
8,528
private void assignMinimumTTL ( List < ? extends DnsAnswer > dnsAnswers , LookupResult . Builder builder ) { if ( config . hasOverrideTTL ( ) ) { builder . cacheTTL ( config . getCacheTTLOverrideMillis ( ) ) ; } else { builder . cacheTTL ( dnsAnswers . stream ( ) . map ( DnsAnswer :: dnsTTL ) . min ( Comparator . compa...
Assigns the minimum TTL found in the supplied DnsAnswers . The minimum makes sense because this is the least amount of time that at least one of the records is valid for .
8,529
public long countInstallationOfEntityById ( ModelId entityId ) { final String field = String . format ( Locale . ROOT , "%s.%s" , ContentPackInstallation . FIELD_ENTITIES , NativeEntityDescriptor . FIELD_META_ID ) ; return dbCollection . getCount ( DBQuery . is ( field , entityId ) ) ; }
Returns the number of installations the given content pack entity ID is used in .
8,530
public void addStream ( Stream stream ) { indexSets . add ( stream . getIndexSet ( ) ) ; if ( streams . add ( stream ) ) { sizeCounter . inc ( 8 ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "[Message size update][{}] stream added: {}" , getId ( ) , sizeCounter . getCount ( ) ) ; } } }
Assign the given stream to this message .
8,531
public boolean removeStream ( Stream stream ) { final boolean removed = streams . remove ( stream ) ; if ( removed ) { indexSets . clear ( ) ; for ( Stream s : streams ) { indexSets . add ( s . getIndexSet ( ) ) ; } sizeCounter . dec ( 8 ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "[Message size update][{}] str...
Remove the stream assignment from this message .
8,532
public static int toSeconds ( TimeRange timeRange ) { if ( timeRange . getFrom ( ) == null || timeRange . getTo ( ) == null ) { return 0 ; } try { return Seconds . secondsBetween ( timeRange . getFrom ( ) , timeRange . getTo ( ) ) . getSeconds ( ) ; } catch ( IllegalArgumentException e ) { return 0 ; } }
Calculate the number of seconds in the given time range .
8,533
public void handleIndexSetCreation ( final IndexSetCreatedEvent event ) { final String indexSetId = event . indexSet ( ) . id ( ) ; final Optional < IndexSetConfig > optionalIndexSet = indexSetService . get ( indexSetId ) ; if ( optionalIndexSet . isPresent ( ) ) { schedule ( mongoIndexSetFactory . create ( optionalInd...
Creates a new field type polling job for the newly created index set .
8,534
public void handleIndexSetDeletion ( final IndexSetDeletedEvent event ) { final String indexSetId = event . id ( ) ; LOG . debug ( "Disable field type updating for index set <{}>" , indexSetId ) ; cancel ( futures . remove ( indexSetId ) ) ; }
Removes the field type polling job for the now deleted index set .
8,535
public void handleIndexDeletion ( final IndicesDeletedEvent event ) { event . indices ( ) . forEach ( indexName -> { LOG . debug ( "Removing field type information for deleted index <{}>" , indexName ) ; dbService . delete ( indexName ) ; } ) ; }
Removes the index field type data for the deleted index .
8,536
private void schedule ( final IndexSet indexSet ) { final String indexSetId = indexSet . getConfig ( ) . id ( ) ; final String indexSetTitle = indexSet . getConfig ( ) . title ( ) ; final Duration refreshInterval = indexSet . getConfig ( ) . fieldTypeRefreshInterval ( ) ; if ( Duration . ZERO . equals ( refreshInterval...
Creates a new polling job for the given index set to keep the active write index information up to date .
8,537
public static PluginProperties fromJarFile ( final String filename ) { final Properties properties = new Properties ( ) ; try { final JarFile jarFile = new JarFile ( requireNonNull ( filename ) ) ; final Optional < String > propertiesPath = getPropertiesPath ( jarFile ) ; if ( propertiesPath . isPresent ( ) ) { LOG . d...
Loads the Graylog plugin properties file from the given JAR file .
8,538
public boolean isConnected ( ) { final Health request = new Health . Builder ( ) . local ( ) . timeout ( Ints . saturatedCast ( requestTimeout . toSeconds ( ) ) ) . build ( ) ; try { final JestResult result = JestUtils . execute ( jestClient , request , ( ) -> "Couldn't check connection status of Elasticsearch" ) ; fin...
Check if Elasticsearch is available and that there are data nodes in the cluster .
8,539
public void waitForConnectedAndDeflectorHealthy ( long timeout , TimeUnit unit ) throws InterruptedException , TimeoutException { LOG . debug ( "Waiting until the write-active index is healthy again, checking once per second." ) ; final CountDownLatch latch = new CountDownLatch ( 1 ) ; final ScheduledFuture < ? > sched...
Blocks until the Elasticsearch cluster and current write index is healthy again or the given timeout fires .
8,540
public void register ( GracefulShutdownHook shutdownHook ) { if ( isShuttingDown . get ( ) ) { throw new IllegalStateException ( "Couldn't register shutdown hook because shutdown is already in progress" ) ; } shutdownHooks . add ( requireNonNull ( shutdownHook , "shutdownHook cannot be null" ) ) ; }
Register a shutdown hook with the service .
8,541
List < String > sortedJsFiles ( ) { return jsFiles ( ) . stream ( ) . sorted ( ( file1 , file2 ) -> { if ( vendorJsFiles . contains ( file1 ) ) { return - 1 ; } if ( vendorJsFiles . contains ( file2 ) ) { return 1 ; } if ( file1 . equals ( polyfillJsFile ) ) { return - 1 ; } if ( file2 . equals ( polyfillJsFile ) ) { r...
Sort JS files in the intended load order so templates don t need to care about it .
8,542
public static < N > ImmutableGraph < N > singletonDirectedGraph ( N node ) { final MutableGraph < N > graph = GraphBuilder . directed ( ) . build ( ) ; graph . addNode ( node ) ; return ImmutableGraph . copyOf ( graph ) ; }
Returns an immutable directed graph containing only the specified node .
8,543
public static < N > ImmutableGraph < N > singletonUndirectedGraph ( N node ) { final MutableGraph < N > graph = GraphBuilder . undirected ( ) . build ( ) ; graph . addNode ( node ) ; return ImmutableGraph . copyOf ( graph ) ; }
Returns an immutable undirected graph containing only the specified node .
8,544
public static < N > ImmutableGraph < N > singletonGraph ( Graph < N > graph , N node ) { final MutableGraph < N > mutableGraph = GraphBuilder . from ( graph ) . build ( ) ; mutableGraph . addNode ( node ) ; return ImmutableGraph . copyOf ( mutableGraph ) ; }
Returns an immutable graph containing only the specified node .
8,545
public static < N > void merge ( MutableGraph < N > graph1 , Graph < N > graph2 ) { for ( N node : graph2 . nodes ( ) ) { graph1 . addNode ( node ) ; } for ( EndpointPair < N > edge : graph2 . edges ( ) ) { graph1 . putEdge ( edge . nodeU ( ) , edge . nodeV ( ) ) ; } }
Merge all nodes and edges of two graphs .
8,546
private String normalizedDn ( String dn ) { if ( isNullOrEmpty ( dn ) ) { return dn ; } else { try { return new Dn ( dn ) . getNormName ( ) ; } catch ( LdapInvalidDnException e ) { LOG . debug ( "Invalid DN" , e ) ; return dn ; } } }
When the given string is a DN the method ensures that the DN gets normalized so it can be used in string comparison .
8,547
public Object convert ( String value ) { if ( value == null || value . isEmpty ( ) ) { return value ; } Object result = Ints . tryParse ( value ) ; if ( result != null ) { return result ; } result = Longs . tryParse ( value ) ; if ( result != null ) { return result ; } result = Doubles . tryParse ( value ) ; if ( resul...
Attempts to convert the provided string value to a numeric type trying Integer Long and Double in order until successful .
8,548
public String getJSON ( long maxBytes ) { try { switch ( getGELFType ( ) ) { case ZLIB : return Tools . decompressZlib ( payload , maxBytes ) ; case GZIP : return Tools . decompressGzip ( payload , maxBytes ) ; case UNCOMPRESSED : return new String ( payload , StandardCharsets . UTF_8 ) ; case CHUNKED : case UNSUPPORTE...
Return the JSON payload of the GELF message .
8,549
public Map < String , FieldTypes > get ( final Collection < String > fieldNames , Collection < String > indexNames ) { if ( fieldNames . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } final Map < String , SetMultimap < String , String > > fields = new HashMap < > ( ) ; getTypesStream ( fieldNames , indexNames ) ...
Returns a map of field names to the corresponding field types .
8,550
public Optional < FieldTypes . Type > mapType ( String typeName ) { return Optional . ofNullable ( TYPE_MAP . get ( typeName ) ) ; }
Map the given Elasticsearch field type to a Graylog type .
8,551
private ByteBuf checkForCompletion ( GELFMessage gelfMessage ) { if ( ! chunks . isEmpty ( ) && log . isDebugEnabled ( ) ) { log . debug ( "Dumping GELF chunk map [chunks for {} messages]:\n{}" , chunks . size ( ) , humanReadableChunkMap ( ) ) ; } final GELFMessageChunk chunk = new GELFMessageChunk ( gelfMessage , null...
Checks whether the presented gelf message chunk completes the incoming raw message and returns it if it does . If the message isn t complete it adds the chunk to the internal buffer and waits for more incoming messages . Outdated chunks are being purged regularly .
8,552
private static Configuration overrideDelimiter ( Configuration configuration ) { configuration . setBoolean ( TcpTransport . CK_USE_NULL_DELIMITER , true ) ; return configuration ; }
has been created with the wrong value .
8,553
private static ADnsAnswer decodeDnsRecord ( DnsRecord dnsRecord , boolean includeIpVersion ) { if ( dnsRecord == null ) { return null ; } LOG . trace ( "Attempting to decode DNS record [{}]" , dnsRecord ) ; byte [ ] ipAddressBytes ; final DefaultDnsRawRecord dnsRawRecord = ( DefaultDnsRawRecord ) dnsRecord ; try { fina...
Picks out the IP address and TTL from the answer response for each record .
8,554
public static FileInfo forPath ( Path path ) { try { final BasicFileAttributes attributes = Files . readAttributes ( path , BasicFileAttributes . class ) ; return FileInfo . builder ( ) . path ( path ) . key ( attributes . fileKey ( ) ) . size ( attributes . size ( ) ) . modificationTime ( attributes . lastModifiedTime...
Create a file info for the given path .
8,555
private ConfigurationRequest getConfigurationRequest ( Map < String , String > userNames ) { ConfigurationRequest configurationRequest = new ConfigurationRequest ( ) ; configurationRequest . addField ( new TextField ( "sender" , "Sender" , "graylog@example.org" , "The sender of sent out mail alerts" , ConfigurationFiel...
I am truly sorry about this but leaking the user list is not okay ...
8,556
public void updateThrottleState ( ThrottleState throttleState ) { if ( ! throttlingAllowed ) { return ; } final boolean throttled = determineIfThrottled ( throttleState ) ; if ( currentlyThrottled . get ( ) ) { if ( throttled ) { return ; } if ( blockLatch == null ) { log . error ( "Expected to see a transport throttle...
Only executed if the Allow Throttling checkbox is set in the input s configuration .
8,557
public boolean blockUntilUnthrottled ( long timeout , TimeUnit unit ) { if ( blockLatch == null ) { return false ; } try { return blockLatch . await ( timeout , unit ) ; } catch ( InterruptedException e ) { return false ; } }
Blocks until the blockLatch is released or until the timeout is exceeded .
8,558
public static String getSystemInformation ( ) { String ret = System . getProperty ( "java.vendor" ) ; ret += " " + System . getProperty ( "java.version" ) ; ret += " on " + System . getProperty ( "os.name" ) ; ret += " " + System . getProperty ( "os.version" ) ; return ret ; }
Get a String containing version information of JRE OS ...
8,559
public static DateTimeFormatter timeFormatterWithOptionalMilliseconds ( ) { DateTimeParser ms = new DateTimeFormatterBuilder ( ) . appendLiteral ( "." ) . appendFractionOfSecond ( 1 , 3 ) . toParser ( ) ; return new DateTimeFormatterBuilder ( ) . append ( DateTimeFormat . forPattern ( ES_DATE_FORMAT_NO_MS ) . withZoneU...
Accepts our ElasticSearch time formats without milliseconds .
8,560
public static String elasticSearchTimeFormatToISO8601 ( String time ) { try { DateTime dt = DateTime . parse ( time , ES_DATE_FORMAT_FORMATTER ) ; return getISO8601String ( dt ) ; } catch ( IllegalArgumentException e ) { return time ; } }
Try to parse a date in ES_DATE_FORMAT format considering it is in UTC and convert it to an ISO8601 date . If an error is encountered in the process it will return the original string .
8,561
public static void silenceUncaughtExceptionsInThisThread ( ) { Thread . currentThread ( ) . setUncaughtExceptionHandler ( new Thread . UncaughtExceptionHandler ( ) { public void uncaughtException ( Thread ignored , Throwable ignored1 ) { } } ) ; }
The default uncaught exception handler will print to STDERR which we don t always want for threads . Using this utility method you can avoid writing to STDERR on a per - thread basis
8,562
public boolean exists ( String indexName ) { try { final JestResult result = jestClient . execute ( new GetSettings . Builder ( ) . addIndex ( indexName ) . build ( ) ) ; return result . isSucceeded ( ) && Iterators . contains ( result . getJsonObject ( ) . fieldNames ( ) , indexName ) ; } catch ( IOException e ) { thr...
Check if a given name is an existing index .
8,563
public boolean aliasExists ( String alias ) { try { final JestResult result = jestClient . execute ( new GetSettings . Builder ( ) . addIndex ( alias ) . build ( ) ) ; return result . isSucceeded ( ) && ! Iterators . contains ( result . getJsonObject ( ) . fieldNames ( ) , alias ) ; } catch ( IOException e ) { throw ne...
Check if a given name is an existing alias .
8,564
public Map < String , Set < String > > getIndexNamesAndAliases ( String indexPattern ) { final GetAliases request = new GetAliases . Builder ( ) . addIndex ( indexPattern ) . setParameter ( "expand_wildcards" , "open" ) . build ( ) ; final JestResult jestResult = JestUtils . execute ( jestClient , request , ( ) -> "Cou...
Returns index names and their aliases . This only returns indices which actually have an alias .
8,565
public Map < String , Object > getIndexTemplate ( IndexSet indexSet ) { final String indexWildcard = indexSet . getIndexWildcard ( ) ; final String analyzer = indexSet . getConfig ( ) . indexAnalyzer ( ) ; return indexMappingFactory . createIndexMapping ( ) . messageTemplate ( indexWildcard , analyzer ) ; }
Returns the generated Elasticsearch index template for the given index set .
8,566
public IndexRangeStats indexRangeStatsOfIndex ( String index ) { final FilterAggregationBuilder builder = AggregationBuilders . filter ( "agg" , QueryBuilders . existsQuery ( Message . FIELD_TIMESTAMP ) ) . subAggregation ( AggregationBuilders . min ( "ts_min" ) . field ( Message . FIELD_TIMESTAMP ) ) . subAggregation ...
Calculate min and max message timestamps in the given index .
8,567
public void markAsAlive ( Node node , boolean isMaster , String restTransportAddress ) { node . getFields ( ) . put ( "last_seen" , Tools . getUTCTimestamp ( ) ) ; node . getFields ( ) . put ( "is_master" , isMaster ) ; node . getFields ( ) . put ( "transport_address" , restTransportAddress ) ; try { save ( node ) ; } ...
Mark this node as alive and probably update some settings that may have changed since last server boot .
8,568
public static long buff2long ( byte [ ] bs , int offset ) { return ( ( ( long ) ( bs [ offset ] >= 0 ? bs [ offset ] : 256 + bs [ offset ] ) ) << 56 ) | ( ( ( long ) ( bs [ offset + 1 ] >= 0 ? bs [ offset + 1 ] : 256 + bs [ offset + 1 ] ) ) << 48 ) | ( ( ( long ) ( bs [ offset + 2 ] >= 0 ? bs [ offset + 2 ] : 256 + bs ...
buff convert to long
8,569
public static int buff2int ( byte [ ] bs , int offset ) { return ( ( bs [ offset ] >= 0 ? bs [ offset ] : 256 + bs [ offset ] ) << 24 ) | ( ( bs [ offset + 1 ] >= 0 ? bs [ offset + 1 ] : 256 + bs [ offset + 1 ] ) << 16 ) | ( ( bs [ offset + 2 ] >= 0 ? bs [ offset + 2 ] : 256 + bs [ offset + 2 ] ) << 8 ) | ( bs [ offset...
buff convert to int
8,570
public static Period parsePeriod ( String input , ConfigOrigin originForException , String pathForException ) { String s = ConfigImplUtil . unicodeTrim ( input ) ; String originalUnitString = getUnits ( s ) ; String unitString = originalUnitString ; String numberString = ConfigImplUtil . unicodeTrim ( s . substring ( 0...
Parses a period string . If no units are specified in the string it is assumed to be in days . The returned period is in days . The purpose of this function is to implement the period - related methods in the ConfigObject interface .
8,571
static void addMissing ( List < ConfigException . ValidationProblem > accumulator , ConfigValueType refType , Path path , ConfigOrigin origin ) { addMissing ( accumulator , getDesc ( refType ) , path , origin ) ; }
JavaBean stuff uses this
8,572
private static void checkValidObject ( Path path , AbstractConfigObject reference , AbstractConfigObject value , List < ConfigException . ValidationProblem > accumulator ) { for ( Map . Entry < String , ConfigValue > entry : reference . entrySet ( ) ) { String key = entry . getKey ( ) ; Path childPath ; if ( path != nu...
path is null if we re at the root
8,573
static void checkValid ( Path path , ConfigValueType referenceType , AbstractConfigValue value , List < ConfigException . ValidationProblem > accumulator ) { if ( haveCompatibleTypes ( referenceType , value ) ) { if ( referenceType == ConfigValueType . LIST && value instanceof SimpleConfigObject ) { AbstractConfigValue...
Used by the JavaBean - based validator
8,574
private static void writeOriginField ( DataOutput out , SerializedField code , Object v ) throws IOException { switch ( code ) { case ORIGIN_DESCRIPTION : out . writeUTF ( ( String ) v ) ; break ; case ORIGIN_LINE_NUMBER : out . writeInt ( ( Integer ) v ) ; break ; case ORIGIN_END_LINE_NUMBER : out . writeInt ( ( Integ...
outer stream instead of field . data
8,575
static void writeOrigin ( DataOutput out , SimpleConfigOrigin origin , SimpleConfigOrigin baseOrigin ) throws IOException { Map < SerializedField , Object > m ; if ( origin != null ) m = origin . toFieldsDelta ( baseOrigin ) ; else m = Collections . emptyMap ( ) ; for ( Map . Entry < SerializedField , Object > e : m . ...
not private because we use it to serialize ConfigException
8,576
static SimpleConfigOrigin readOrigin ( DataInput in , SimpleConfigOrigin baseOrigin ) throws IOException { Map < SerializedField , Object > m = new EnumMap < SerializedField , Object > ( SerializedField . class ) ; while ( true ) { Object v = null ; SerializedField field = readCode ( in ) ; switch ( field ) { case END_...
not private because we use it to deserialize ConfigException
8,577
static Token newWithoutOrigin ( TokenType tokenType , String debugString , String tokenText ) { return new Token ( tokenType , null , tokenText , debugString ) ; }
this is used for singleton tokens like COMMA or OPEN_CURLY
8,578
ResolveContext restrict ( Path restrictTo ) { if ( restrictTo == restrictToChild ) return this ; else return new ResolveContext ( memos , options , restrictTo , resolveStack , cycleMarkers ) ; }
restrictTo may be null to unrestrict
8,579
static boolean hasFunkyChars ( String s ) { int length = s . length ( ) ; if ( length == 0 ) return false ; for ( int i = 0 ; i < length ; ++ i ) { char c = s . charAt ( i ) ; if ( Character . isLetterOrDigit ( c ) || c == '-' || c == '_' ) continue ; else return true ; } return false ; }
noise from quotes in the rendered path for average cases
8,580
public static Parseable newReader ( Reader reader , ConfigParseOptions options ) { return new ParseableReader ( doNotClose ( reader ) , options ) ; }
is complete .
8,581
private static String convertResourceName ( Class < ? > klass , String resource ) { if ( resource . startsWith ( "/" ) ) { return resource . substring ( 1 ) ; } else { String className = klass . getName ( ) ; int i = className . lastIndexOf ( '.' ) ; if ( i < 0 ) { return resource ; } else { String packageName = classN...
use ClassLoader directly .
8,582
protected SimpleConfigObject withOnlyPathOrNull ( Path path ) { String key = path . first ( ) ; Path next = path . remainder ( ) ; AbstractConfigValue v = value . get ( key ) ; if ( next != null ) { if ( v != null && ( v instanceof AbstractConfigObject ) ) { v = ( ( AbstractConfigObject ) v ) . withOnlyPathOrNull ( nex...
a object .
8,583
private static boolean looksUnsafeForFastParser ( String s ) { boolean lastWasDot = true ; int len = s . length ( ) ; if ( s . isEmpty ( ) ) return true ; if ( s . charAt ( 0 ) == '.' ) return true ; if ( s . charAt ( len - 1 ) == '.' ) return true ; for ( int i = 0 ; i < len ; ++ i ) { char c = s . charAt ( i ) ; if (...
that might require the full parser to deal with .
8,584
static ConfigParseOptions clearForInclude ( ConfigParseOptions options ) { return options . setSyntax ( null ) . setOriginDescription ( null ) . setAllowMissing ( true ) ; }
ConfigIncludeContext does this for us on its options
8,585
public ConfigObject include ( final ConfigIncludeContext context , String name ) { ConfigObject obj = includeWithoutFallback ( context , name ) ; if ( fallback != null ) { return obj . withFallback ( fallback . include ( context , name ) ) ; } else { return obj ; } }
this is the heuristic includer
8,586
static ConfigObject includeWithoutFallback ( final ConfigIncludeContext context , String name ) { URL url ; try { url = new URL ( name ) ; } catch ( MalformedURLException e ) { url = null ; } if ( url != null ) { return includeURLWithoutFallback ( context , url ) ; } else { NameSource source = new RelativeNameSource ( ...
the heuristic includer in static form
8,587
private void writeObject ( java . io . ObjectOutputStream out ) throws IOException { out . defaultWriteObject ( ) ; ConfigImplUtil . writeOrigin ( out , origin ) ; }
support it )
8,588
private static < T > void setOriginField ( T hasOriginField , Class < T > clazz , ConfigOrigin origin ) throws IOException { Field f ; try { f = clazz . getDeclaredField ( "origin" ) ; } catch ( NoSuchFieldException e ) { throw new IOException ( clazz . getSimpleName ( ) + " has no origin field?" , e ) ; } catch ( Secu...
For deserialization - uses reflection to set the final origin field on the object
8,589
protected final AbstractConfigValue peekAssumingResolved ( String key , Path originalPath ) { try { return attemptPeekWithPartialResolve ( key ) ; } catch ( ConfigException . NotResolved e ) { throw ConfigImpl . improveNotResolved ( originalPath , e ) ; } }
This looks up the key with no transformation or type conversion of any kind and returns null if the key is not present . The object must be resolved along the nodes needed to get the key or ConfigException . NotResolved will be thrown .
8,590
public static ConfigDocument parseReader ( Reader reader , ConfigParseOptions options ) { return Parseable . newReader ( reader , options ) . parseConfigDocument ( ) ; }
Parses a Reader into a ConfigDocument instance .
8,591
public static ConfigDocument parseFile ( File file , ConfigParseOptions options ) { return Parseable . newFile ( file , options ) . parseConfigDocument ( ) ; }
Parses a file into a ConfigDocument instance .
8,592
public static ConfigDocument parseString ( String s , ConfigParseOptions options ) { return Parseable . newString ( s , options ) . parseConfigDocument ( ) ; }
Parses a string which should be valid HOCON or JSON .
8,593
public AbstractConfigValue withFallback ( ConfigMergeable mergeable ) { if ( ignoresFallbacks ( ) ) { return this ; } else { ConfigValue other = ( ( MergeableValue ) mergeable ) . toFallbackValue ( ) ; if ( other instanceof Unmergeable ) { return mergedWithTheUnmergeable ( ( Unmergeable ) other ) ; } else if ( other in...
this is only overridden to change the return type
8,594
public void printSetting ( String path ) { System . out . println ( "The setting '" + path + "' is: " + config . getString ( path ) ) ; }
this is the amazing functionality provided by simple - lib
8,595
public ConfigResolveOptions appendResolver ( ConfigResolver value ) { if ( value == null ) { throw new ConfigException . BugOrBroken ( "null resolver passed to appendResolver" ) ; } else if ( value == this . resolver ) { return this ; } else { return new ConfigResolveOptions ( useSystemEnvironment , allowUnresolved , t...
Returns options where the given resolver used as a fallback if a reference cannot be otherwise resolved . This resolver will only be called after resolution has failed to substitute with a value from within the config itself and with any other resolvers that have been appended before this one . Multiple resolvers can b...
8,596
@ SuppressWarnings ( "unchecked" ) ResolveResult < AbstractConfigObject > asObjectResult ( ) { if ( ! ( value instanceof AbstractConfigObject ) ) throw new ConfigException . BugOrBroken ( "Expecting a resolve result to be an object, but it was " + value ) ; Object o = this ; return ( ResolveResult < AbstractConfigObjec...
better option? we don t have variance
8,597
public static ConfigSyntax syntaxFromExtension ( String filename ) { if ( filename == null ) return null ; else if ( filename . endsWith ( ".json" ) ) return ConfigSyntax . JSON ; else if ( filename . endsWith ( ".conf" ) ) return ConfigSyntax . CONF ; else if ( filename . endsWith ( ".properties" ) ) return ConfigSynt...
Guess configuration syntax from given filename .
8,598
static AbstractConfigValue makeReplacement ( ResolveContext context , List < AbstractConfigValue > stack , int skipping ) { List < AbstractConfigValue > subStack = stack . subList ( skipping , stack . size ( ) ) ; if ( subStack . isEmpty ( ) ) { if ( ConfigImpl . traceSubstitutionsEnabled ( ) ) ConfigImpl . trace ( con...
static method also used by ConfigDelayedMergeObject ; end may be null
8,599
static boolean stackIgnoresFallbacks ( List < AbstractConfigValue > stack ) { AbstractConfigValue last = stack . get ( stack . size ( ) - 1 ) ; return last . ignoresFallbacks ( ) ; }
static utility shared with ConfigDelayedMergeObject