idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,400
public void execute ( TSDB tsdb , HttpQuery query ) throws IOException { final String [ ] uri = query . explodeAPIPath ( ) ; final String endpoint = uri . length > 1 ? uri [ 1 ] : "" ; try { if ( endpoint . isEmpty ( ) ) { handleTree ( tsdb , query ) ; } else if ( endpoint . toLowerCase ( ) . equals ( "branch" ) ) { handleBranch ( tsdb , query ) ; } else if ( endpoint . toLowerCase ( ) . equals ( "rule" ) ) { handleRule ( tsdb , query ) ; } else if ( endpoint . toLowerCase ( ) . equals ( "rules" ) ) { handleRules ( tsdb , query ) ; } else if ( endpoint . toLowerCase ( ) . equals ( "test" ) ) { handleTest ( tsdb , query ) ; } else if ( endpoint . toLowerCase ( ) . equals ( "collisions" ) ) { handleCollisionNotMatched ( tsdb , query , true ) ; } else if ( endpoint . toLowerCase ( ) . equals ( "notmatched" ) ) { handleCollisionNotMatched ( tsdb , query , false ) ; } else { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "This endpoint is not supported" ) ; } } catch ( BadRequestException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Routes the request to the proper handler
7,401
private void handleBranch ( TSDB tsdb , HttpQuery query ) { if ( query . getAPIMethod ( ) != HttpMethod . GET ) { throw new BadRequestException ( HttpResponseStatus . BAD_REQUEST , "Unsupported HTTP request method" ) ; } try { final int tree_id = parseTreeId ( query , false ) ; final String branch_hex = query . getQueryStringParam ( "branch" ) ; final byte [ ] branch_id ; if ( branch_hex == null || branch_hex . isEmpty ( ) ) { if ( tree_id < 1 ) { throw new BadRequestException ( "Missing or invalid branch and tree IDs" ) ; } branch_id = Tree . idToBytes ( tree_id ) ; } else { branch_id = Branch . stringToId ( branch_hex ) ; } final Branch branch = Branch . fetchBranch ( tsdb , branch_id , true ) . joinUninterruptibly ( ) ; if ( branch == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate branch '" + Branch . idToString ( branch_id ) + "' for tree '" + Tree . bytesToId ( branch_id ) + "'" ) ; } query . sendReply ( query . serializer ( ) . formatBranchV1 ( branch ) ) ; } catch ( BadRequestException e ) { throw e ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Attempts to retrieve a single branch and return it to the user . If the requested branch doesn t exist it returns a 404 .
7,402
private void handleRule ( TSDB tsdb , HttpQuery query ) { final TreeRule rule ; if ( query . hasContent ( ) ) { rule = query . serializer ( ) . parseTreeRuleV1 ( ) ; } else { rule = parseRule ( query ) ; } try { Tree tree = null ; tree = Tree . fetchTree ( tsdb , rule . getTreeId ( ) ) . joinUninterruptibly ( ) ; if ( tree == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate tree: " + rule . getTreeId ( ) ) ; } if ( query . getAPIMethod ( ) == HttpMethod . GET ) { final TreeRule tree_rule = tree . getRule ( rule . getLevel ( ) , rule . getOrder ( ) ) ; if ( tree_rule == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate rule: " + rule ) ; } query . sendReply ( query . serializer ( ) . formatTreeRuleV1 ( tree_rule ) ) ; } else if ( query . getAPIMethod ( ) == HttpMethod . POST || query . getAPIMethod ( ) == HttpMethod . PUT ) { if ( rule . syncToStorage ( tsdb , ( query . getAPIMethod ( ) == HttpMethod . PUT ) ) . joinUninterruptibly ( ) ) { final TreeRule stored_rule = TreeRule . fetchRule ( tsdb , rule . getTreeId ( ) , rule . getLevel ( ) , rule . getOrder ( ) ) . joinUninterruptibly ( ) ; query . sendReply ( query . serializer ( ) . formatTreeRuleV1 ( stored_rule ) ) ; } else { throw new RuntimeException ( "Unable to save rule " + rule + " to storage" ) ; } } else if ( query . getAPIMethod ( ) == HttpMethod . DELETE ) { if ( tree . getRule ( rule . getLevel ( ) , rule . getOrder ( ) ) == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate rule: " + rule ) ; } TreeRule . deleteRule ( tsdb , tree . getTreeId ( ) , rule . getLevel ( ) , rule . getOrder ( ) ) . joinUninterruptibly ( ) ; query . sendStatusOnly ( HttpResponseStatus . NO_CONTENT ) ; } else { throw new BadRequestException ( HttpResponseStatus . BAD_REQUEST , "Unsupported HTTP request method" ) ; } } catch ( BadRequestException e ) { throw e ; } catch ( IllegalStateException e ) { query . sendStatusOnly ( HttpResponseStatus . NOT_MODIFIED ) ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Handles the CRUD calls for a single rule enabling adding editing or deleting the rule
7,403
private void handleRules ( TSDB tsdb , HttpQuery query ) { int tree_id = 0 ; List < TreeRule > rules = null ; if ( query . hasContent ( ) ) { rules = query . serializer ( ) . parseTreeRulesV1 ( ) ; if ( rules == null || rules . isEmpty ( ) ) { throw new BadRequestException ( "Missing tree rules" ) ; } tree_id = rules . get ( 0 ) . getTreeId ( ) ; for ( TreeRule rule : rules ) { if ( rule . getTreeId ( ) != tree_id ) { throw new BadRequestException ( "All rules must belong to the same tree" ) ; } } } else { tree_id = parseTreeId ( query , false ) ; } try { if ( Tree . fetchTree ( tsdb , tree_id ) . joinUninterruptibly ( ) == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate tree: " + tree_id ) ; } if ( query . getAPIMethod ( ) == HttpMethod . POST || query . getAPIMethod ( ) == HttpMethod . PUT ) { if ( rules == null || rules . isEmpty ( ) ) { if ( rules == null || rules . isEmpty ( ) ) { throw new BadRequestException ( "Missing tree rules" ) ; } } if ( query . getAPIMethod ( ) == HttpMethod . PUT ) { TreeRule . deleteAllRules ( tsdb , tree_id ) . joinUninterruptibly ( ) ; } for ( TreeRule rule : rules ) { rule . syncToStorage ( tsdb , query . getAPIMethod ( ) == HttpMethod . PUT ) . joinUninterruptibly ( ) ; } query . sendStatusOnly ( HttpResponseStatus . NO_CONTENT ) ; } else if ( query . getAPIMethod ( ) == HttpMethod . DELETE ) { TreeRule . deleteAllRules ( tsdb , tree_id ) . joinUninterruptibly ( ) ; query . sendStatusOnly ( HttpResponseStatus . NO_CONTENT ) ; } else { throw new BadRequestException ( HttpResponseStatus . BAD_REQUEST , "Unsupported HTTP request method" ) ; } } catch ( BadRequestException e ) { throw e ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Handles requests to replace or delete all of the rules in the given tree . It s an efficiency helper for cases where folks don t want to make a single call per rule when updating many rules at once .
7,404
private void handleCollisionNotMatched ( TSDB tsdb , HttpQuery query , final boolean for_collisions ) { final Map < String , Object > map ; if ( query . hasContent ( ) ) { map = query . serializer ( ) . parseTreeTSUIDsListV1 ( ) ; } else { map = parseTSUIDsList ( query ) ; } final Integer tree_id = ( Integer ) map . get ( "treeId" ) ; if ( tree_id == null ) { throw new BadRequestException ( "Missing or invalid Tree ID" ) ; } try { if ( Tree . fetchTree ( tsdb , tree_id ) . joinUninterruptibly ( ) == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate tree: " + tree_id ) ; } if ( query . getAPIMethod ( ) == HttpMethod . GET || query . getAPIMethod ( ) == HttpMethod . POST || query . getAPIMethod ( ) == HttpMethod . PUT ) { @ SuppressWarnings ( "unchecked" ) final List < String > tsuids = ( List < String > ) map . get ( "tsuids" ) ; final Map < String , String > results = for_collisions ? Tree . fetchCollisions ( tsdb , tree_id , tsuids ) . joinUninterruptibly ( ) : Tree . fetchNotMatched ( tsdb , tree_id , tsuids ) . joinUninterruptibly ( ) ; query . sendReply ( query . serializer ( ) . formatTreeCollisionNotMatchedV1 ( results , for_collisions ) ) ; } else { throw new BadRequestException ( HttpResponseStatus . BAD_REQUEST , "Unsupported HTTP request method" ) ; } } catch ( ClassCastException e ) { throw new BadRequestException ( "Unable to convert the given data to a list" , e ) ; } catch ( BadRequestException e ) { throw e ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Handles requests to fetch collisions or not - matched entries for the given tree . To cut down on code this method uses a flag to determine if we want collisions or not - matched entries since they both have the same data types .
7,405
private Tree parseTree ( HttpQuery query ) { final Tree tree = new Tree ( parseTreeId ( query , false ) ) ; if ( query . hasQueryStringParam ( "name" ) ) { tree . setName ( query . getQueryStringParam ( "name" ) ) ; } if ( query . hasQueryStringParam ( "description" ) ) { tree . setDescription ( query . getQueryStringParam ( "description" ) ) ; } if ( query . hasQueryStringParam ( "notes" ) ) { tree . setNotes ( query . getQueryStringParam ( "notes" ) ) ; } if ( query . hasQueryStringParam ( "strict_match" ) ) { if ( query . getQueryStringParam ( "strict_match" ) . toLowerCase ( ) . equals ( "true" ) ) { tree . setStrictMatch ( true ) ; } else { tree . setStrictMatch ( false ) ; } } if ( query . hasQueryStringParam ( "enabled" ) ) { final String enabled = query . getQueryStringParam ( "enabled" ) ; if ( enabled . toLowerCase ( ) . equals ( "true" ) ) { tree . setEnabled ( true ) ; } else { tree . setEnabled ( false ) ; } } if ( query . hasQueryStringParam ( "store_failures" ) ) { if ( query . getQueryStringParam ( "store_failures" ) . toLowerCase ( ) . equals ( "true" ) ) { tree . setStoreFailures ( true ) ; } else { tree . setStoreFailures ( false ) ; } } return tree ; }
Parses query string parameters into a blank tree object . Used for updating tree meta data .
7,406
private TreeRule parseRule ( HttpQuery query ) { final TreeRule rule = new TreeRule ( parseTreeId ( query , true ) ) ; if ( query . hasQueryStringParam ( "type" ) ) { try { rule . setType ( TreeRule . stringToType ( query . getQueryStringParam ( "type" ) ) ) ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( "Unable to parse the 'type' parameter" , e ) ; } } if ( query . hasQueryStringParam ( "field" ) ) { rule . setField ( query . getQueryStringParam ( "field" ) ) ; } if ( query . hasQueryStringParam ( "custom_field" ) ) { rule . setCustomField ( query . getQueryStringParam ( "custom_field" ) ) ; } if ( query . hasQueryStringParam ( "regex" ) ) { try { rule . setRegex ( query . getQueryStringParam ( "regex" ) ) ; } catch ( PatternSyntaxException e ) { throw new BadRequestException ( "Unable to parse the 'regex' parameter" , e ) ; } } if ( query . hasQueryStringParam ( "separator" ) ) { rule . setSeparator ( query . getQueryStringParam ( "separator" ) ) ; } if ( query . hasQueryStringParam ( "description" ) ) { rule . setDescription ( query . getQueryStringParam ( "description" ) ) ; } if ( query . hasQueryStringParam ( "notes" ) ) { rule . setNotes ( query . getQueryStringParam ( "notes" ) ) ; } if ( query . hasQueryStringParam ( "regex_group_idx" ) ) { try { rule . setRegexGroupIdx ( Integer . parseInt ( query . getQueryStringParam ( "regex_group_idx" ) ) ) ; } catch ( NumberFormatException e ) { throw new BadRequestException ( "Unable to parse the 'regex_group_idx' parameter" , e ) ; } } if ( query . hasQueryStringParam ( "display_format" ) ) { rule . setDisplayFormat ( query . getQueryStringParam ( "display_format" ) ) ; } try { rule . setLevel ( Integer . parseInt ( query . getRequiredQueryStringParam ( "level" ) ) ) ; } catch ( NumberFormatException e ) { throw new BadRequestException ( "Unable to parse the 'level' parameter" , e ) ; } try { rule . setOrder ( Integer . parseInt ( query . getRequiredQueryStringParam ( "order" ) ) ) ; } catch ( NumberFormatException e ) { throw new BadRequestException ( "Unable to parse the 'order' parameter" , e ) ; } return rule ; }
Parses query string parameters into a blank tree rule object . Used for updating individual rules
7,407
private int parseTreeId ( HttpQuery query , final boolean required ) { try { if ( required ) { return Integer . parseInt ( query . getRequiredQueryStringParam ( "treeid" ) ) ; } else { if ( query . hasQueryStringParam ( "treeid" ) ) { return Integer . parseInt ( query . getQueryStringParam ( "treeid" ) ) ; } else { return 0 ; } } } catch ( NumberFormatException nfe ) { throw new BadRequestException ( "Unable to parse 'tree' value" , nfe ) ; } }
Parses the tree ID from a query Used often so it s been broken into it s own method
7,408
private Map < String , Object > parseTSUIDsList ( HttpQuery query ) { final HashMap < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( "treeId" , parseTreeId ( query , true ) ) ; final String tsquery = query . getQueryStringParam ( "tsuids" ) ; if ( tsquery != null ) { final String [ ] tsuids = tsquery . split ( "," ) ; map . put ( "tsuids" , Arrays . asList ( tsuids ) ) ; } return map ; }
Used to parse a list of TSUIDs from the query string for collision or not matched requests . TSUIDs must be comma separated .
7,409
public void setParams ( final Map < String , String > params ) { String [ ] y_format_keys = { "format y" , "format y2" } ; for ( String k : y_format_keys ) { if ( params . containsKey ( k ) ) { params . put ( k , URLDecoder . decode ( params . get ( k ) ) ) ; } } this . params = params ; }
Sets the global parameters for this plot .
7,410
public void add ( final DataPoints datapoints , final String options ) { this . datapoints . add ( datapoints ) ; this . options . add ( options ) ; }
Adds some data points to this plot .
7,411
public int dumpToFiles ( final String basepath ) throws IOException { int npoints = 0 ; final int nseries = datapoints . size ( ) ; final String datafiles [ ] = nseries > 0 ? new String [ nseries ] : null ; FileSystem . checkDirectory ( new File ( basepath ) . getParent ( ) , Const . MUST_BE_WRITEABLE , Const . CREATE_IF_NEEDED ) ; for ( int i = 0 ; i < nseries ; i ++ ) { datafiles [ i ] = basepath + "_" + i + ".dat" ; final PrintWriter datafile = new PrintWriter ( datafiles [ i ] ) ; try { for ( final DataPoint d : datapoints . get ( i ) ) { final long ts = d . timestamp ( ) / 1000 ; if ( d . isInteger ( ) ) { datafile . print ( ts + utc_offset ) ; datafile . print ( ' ' ) ; datafile . print ( d . longValue ( ) ) ; } else { final double value = d . doubleValue ( ) ; if ( Double . isInfinite ( value ) ) { throw new IllegalStateException ( "Infinity found in" + " datapoints #" + i + ": " + value + " d=" + d ) ; } else if ( Double . isNaN ( value ) ) { continue ; } datafile . print ( ts + utc_offset ) ; datafile . print ( ' ' ) ; datafile . print ( value ) ; } datafile . print ( '\n' ) ; if ( ts >= ( start_time & UNSIGNED ) && ts <= ( end_time & UNSIGNED ) ) { npoints ++ ; } } } finally { datafile . close ( ) ; } } if ( npoints == 0 ) { params . put ( "yrange" , "[0:10]" ) ; } writeGnuplotScript ( basepath , datafiles ) ; return npoints ; }
Generates the Gnuplot script and data files .
7,412
public static Throwable getCause ( final DeferredGroupException e ) { Throwable ex = e ; while ( ex . getClass ( ) . equals ( DeferredGroupException . class ) ) { if ( ex . getCause ( ) == null ) { break ; } else { ex = ex . getCause ( ) ; } } return ex ; }
Iterates through the stack trace looking for the actual cause of the deferred group exception . These traces can be huge and truncated in the logs so it s really useful to be able to spit out the source .
7,413
public void add ( final byte [ ] buf , final int offset , final int len ) { segments . add ( new BufferSegment ( buf , offset , len ) ) ; total_length += len ; }
Add a segment to the buffer list .
7,414
public byte [ ] getLastSegment ( ) { if ( segments . isEmpty ( ) ) { return null ; } BufferSegment seg = segments . get ( segments . size ( ) - 1 ) ; return Arrays . copyOfRange ( seg . buf , seg . offset , seg . offset + seg . len ) ; }
Get the most recently added segment .
7,415
public int compareTo ( ByteArrayPair a ) { final int key_compare = Bytes . memcmpMaybeNull ( this . key , a . key ) ; if ( key_compare == 0 ) { return Bytes . memcmpMaybeNull ( this . value , a . value ) ; } return key_compare ; }
Sorts on the key first then on the value . Nulls are allowed and are ordered first .
7,416
private boolean hasNextValue ( boolean update_pos ) { final int size = iterators . length ; for ( int i = pos + 1 ; i < size ; i ++ ) { if ( timestamps [ i ] != 0 ) { if ( update_pos ) { pos = i ; } return true ; } } return false ; }
Returns whether or not there are more values to aggregate .
7,417
protected void addRow ( final KeyValue row ) { long last_ts = 0 ; if ( rows . size ( ) != 0 ) { final byte [ ] key = row . key ( ) ; final iRowSeq last = rows . get ( rows . size ( ) - 1 ) ; final short metric_width = tsdb . metrics . width ( ) ; final short tags_offset = ( short ) ( Const . SALT_WIDTH ( ) + metric_width + Const . TIMESTAMP_BYTES ) ; final short tags_bytes = ( short ) ( key . length - tags_offset ) ; String error = null ; if ( key . length != last . key ( ) . length ) { error = "row key length mismatch" ; } else if ( Bytes . memcmp ( key , last . key ( ) , Const . SALT_WIDTH ( ) , metric_width ) != 0 ) { error = "metric ID mismatch" ; } else if ( Bytes . memcmp ( key , last . key ( ) , tags_offset , tags_bytes ) != 0 ) { error = "tags mismatch" ; } if ( error != null ) { throw new IllegalArgumentException ( error + ". " + "This Span's last row key is " + Arrays . toString ( last . key ( ) ) + " whereas the row key being added is " + Arrays . toString ( key ) + " and metric_width=" + metric_width ) ; } last_ts = last . timestamp ( last . size ( ) - 1 ) ; } final RowSeq rowseq = new RowSeq ( tsdb ) ; rowseq . setRow ( row ) ; sorted = false ; if ( last_ts >= rowseq . timestamp ( 0 ) ) { for ( final iRowSeq rs : rows ) { if ( Bytes . memcmp ( rs . key ( ) , row . key ( ) , Const . SALT_WIDTH ( ) , ( rs . key ( ) . length - Const . SALT_WIDTH ( ) ) ) == 0 ) { rs . addRow ( row ) ; return ; } } } rows . add ( rowseq ) ; }
Adds a compacted row to the span merging with an existing RowSeq or creating a new one if necessary .
7,418
private int seekRow ( final long timestamp ) { checkRowOrder ( ) ; int row_index = 0 ; iRowSeq row = null ; final int nrows = rows . size ( ) ; for ( int i = 0 ; i < nrows ; i ++ ) { row = rows . get ( i ) ; final int sz = row . size ( ) ; if ( sz < 1 ) { row_index ++ ; } else if ( row . timestamp ( sz - 1 ) < timestamp ) { row_index ++ ; } else { break ; } } if ( row_index == nrows ) { -- row_index ; } return row_index ; }
Finds the index of the row in which the given timestamp should be .
7,419
Span . Iterator spanIterator ( ) { if ( ! sorted ) { Collections . sort ( rows , new RowSeq . RowSeqComparator ( ) ) ; sorted = true ; } return new Span . Iterator ( ) ; }
Package private iterator method to access it as a Span . Iterator .
7,420
Downsampler downsampler ( final long start_time , final long end_time , final long interval_ms , final Aggregator downsampler , final FillPolicy fill_policy ) { if ( FillPolicy . NONE == fill_policy ) { return new Downsampler ( spanIterator ( ) , interval_ms , downsampler ) ; } else { return new FillingDownsampler ( spanIterator ( ) , start_time , end_time , interval_ms , downsampler , fill_policy ) ; } }
Package private iterator method to access data while downsampling with the option to force interpolation .
7,421
public void run ( ) { long purged_columns ; try { purged_columns = purgeUIDMeta ( ) . joinUninterruptibly ( ) ; LOG . info ( "Thread [" + thread_id + "] finished. Purged [" + purged_columns + "] UIDMeta columns from storage" ) ; purged_columns = purgeTSMeta ( ) . joinUninterruptibly ( ) ; LOG . info ( "Thread [" + thread_id + "] finished. Purged [" + purged_columns + "] TSMeta columns from storage" ) ; } catch ( Exception e ) { LOG . error ( "Unexpected exception" , e ) ; } }
Loops through the entire tsdb - uid table then the meta data table and exits when complete .
7,422
public Deferred < Long > purgeUIDMeta ( ) { final ArrayList < Deferred < Object > > delete_calls = new ArrayList < Deferred < Object > > ( ) ; final Deferred < Long > result = new Deferred < Long > ( ) ; final class MetaScanner implements Callback < Deferred < Long > , ArrayList < ArrayList < KeyValue > > > { final Scanner scanner ; public MetaScanner ( ) { scanner = getScanner ( tsdb . uidTable ( ) ) ; } public Deferred < Long > scan ( ) { return scanner . nextRows ( ) . addCallbackDeferring ( this ) ; } public Deferred < Long > call ( ArrayList < ArrayList < KeyValue > > rows ) throws Exception { if ( rows == null ) { result . callback ( columns ) ; return null ; } for ( final ArrayList < KeyValue > row : rows ) { ArrayList < byte [ ] > qualifiers = new ArrayList < byte [ ] > ( row . size ( ) ) ; for ( KeyValue column : row ) { if ( Bytes . equals ( TSMeta . META_QUALIFIER ( ) , column . qualifier ( ) ) ) { qualifiers . add ( column . qualifier ( ) ) ; } else if ( Bytes . equals ( "metric_meta" . getBytes ( CHARSET ) , column . qualifier ( ) ) ) { qualifiers . add ( column . qualifier ( ) ) ; } else if ( Bytes . equals ( "tagk_meta" . getBytes ( CHARSET ) , column . qualifier ( ) ) ) { qualifiers . add ( column . qualifier ( ) ) ; } else if ( Bytes . equals ( "tagv_meta" . getBytes ( CHARSET ) , column . qualifier ( ) ) ) { qualifiers . add ( column . qualifier ( ) ) ; } } if ( qualifiers . size ( ) > 0 ) { columns += qualifiers . size ( ) ; final DeleteRequest delete = new DeleteRequest ( tsdb . uidTable ( ) , row . get ( 0 ) . key ( ) , NAME_FAMILY , qualifiers . toArray ( new byte [ qualifiers . size ( ) ] [ ] ) ) ; delete_calls . add ( tsdb . getClient ( ) . delete ( delete ) ) ; } } final class ContinueCB implements Callback < Deferred < Long > , ArrayList < Object > > { public Deferred < Long > call ( ArrayList < Object > deletes ) throws Exception { LOG . debug ( "[" + thread_id + "] Processed [" + deletes . size ( ) + "] delete calls" ) ; delete_calls . clear ( ) ; return scan ( ) ; } } Deferred . group ( delete_calls ) . addCallbackDeferring ( new ContinueCB ( ) ) ; return null ; } } new MetaScanner ( ) . scan ( ) ; return result ; }
Scans the entire UID table and removes any UIDMeta objects found .
7,423
private Scanner getScanner ( final byte [ ] table ) throws HBaseException { short metric_width = TSDB . metrics_width ( ) ; final byte [ ] start_row = Arrays . copyOfRange ( Bytes . fromLong ( start_id ) , 8 - metric_width , 8 ) ; final byte [ ] end_row = Arrays . copyOfRange ( Bytes . fromLong ( end_id ) , 8 - metric_width , 8 ) ; final Scanner scanner = tsdb . getClient ( ) . newScanner ( table ) ; scanner . setStartKey ( start_row ) ; scanner . setStopKey ( end_row ) ; scanner . setFamily ( NAME_FAMILY ) ; return scanner ; }
Returns a scanner to run over the UID table starting at the given row
7,424
public static void mainUsage ( PrintStream ps ) { StringBuilder b = new StringBuilder ( "\nUsage: java -jar [opentsdb.jar] [command] [args]\nValid commands:" ) . append ( "\n\ttsd: Starts a new TSDB instance" ) . append ( "\n\tfsck: Searches for and optionally fixes corrupted data in a TSDB" ) . append ( "\n\timport: Imports data from a file into HBase through a TSDB" ) . append ( "\n\tmkmetric: Creates a new metric" ) . append ( "\n\tquery: Queries time series data from a TSDB " ) . append ( "\n\tscan: Dumps data straight from HBase" ) . append ( "\n\tuid: Provides various functions to search or modify information in the tsdb-uid table. " ) . append ( "\n\texportui: Exports the OpenTSDB UI static content" ) . append ( "\n\n\tUse help <command> for details on a command\n" ) ; ps . println ( b ) ; }
Prints the main usage banner
7,425
public static void main ( String [ ] args ) { log . info ( "Starting." ) ; log . info ( BuildData . revisionString ( ) ) ; log . info ( BuildData . buildString ( ) ) ; try { System . in . close ( ) ; } catch ( Exception e ) { log . warn ( "Failed to close stdin" , e ) ; } if ( args . length == 0 ) { log . error ( "No command supplied" ) ; mainUsage ( System . err ) ; System . exit ( - 1 ) ; } for ( int i = 0 ; i < args . length ; i ++ ) { args [ i ] = args [ i ] . trim ( ) ; } String targetTool = args [ 0 ] . toLowerCase ( ) ; if ( ! COMMANDS . containsKey ( targetTool ) ) { log . error ( "Command not recognized: [" + targetTool + "]" ) ; mainUsage ( System . err ) ; System . exit ( - 1 ) ; } process ( targetTool , shift ( args ) ) ; }
The OpenTSDB fat - jar main entry point
7,426
private static void process ( String targetTool , String [ ] args ) { if ( "mkmetric" . equals ( targetTool ) ) { shift ( args ) ; } if ( ! "tsd" . equals ( targetTool ) ) { try { COMMANDS . get ( targetTool ) . getDeclaredMethod ( "main" , String [ ] . class ) . invoke ( null , new Object [ ] { args } ) ; } catch ( Exception x ) { log . error ( "Failed to call [" + targetTool + "]." , x ) ; System . exit ( - 1 ) ; } } else { launchTSD ( args ) ; } }
Executes the target tool
7,427
protected static void applyCommandLine ( ConfigArgP cap , ArgP argp ) { if ( argp . has ( "--help" ) ) { if ( cap . hasNonOption ( "extended" ) ) { System . out . println ( cap . getExtendedUsage ( "tsd extended usage:" ) ) ; } else { System . out . println ( cap . getDefaultUsage ( "tsd usage:" ) ) ; } System . exit ( 0 ) ; } if ( argp . has ( "--config" ) ) { loadConfigSource ( cap , argp . get ( "--config" ) . trim ( ) ) ; } if ( argp . has ( "--include" ) ) { String [ ] sources = argp . get ( "--include" ) . split ( "," ) ; for ( String s : sources ) { loadConfigSource ( cap , s . trim ( ) ) ; } } }
Applies and processes the pre - tsd command line
7,428
protected static void setJVMName ( final int port , final String iface ) { final Properties p = getAgentProperties ( ) ; if ( p != null ) { final String ifc = ( iface == null || iface . trim ( ) . isEmpty ( ) ) ? "" : ( iface . trim ( ) + ":" ) ; final String name = "opentsdb[" + ifc + port + "]" ; p . setProperty ( "sun.java.command" , name ) ; p . setProperty ( "sun.rt.javaCommand" , name ) ; System . setProperty ( "sun.java.command" , name ) ; System . setProperty ( "sun.rt.javaCommand" , name ) ; } }
Attempts to set the vm agent property that identifies the vm s display name . This is the name displayed for tools such as jconsole and jps when using auto - dicsovery . When using a fat - jar this provides a much more identifiable name
7,429
protected static Properties getAgentProperties ( ) { try { Class < ? > clazz = Class . forName ( "sun.misc.VMSupport" ) ; Method m = clazz . getDeclaredMethod ( "getAgentProperties" ) ; m . setAccessible ( true ) ; Properties p = ( Properties ) m . invoke ( null ) ; return p ; } catch ( Throwable t ) { return null ; } }
Returns the agent properties
7,430
protected static String insertPattern ( final String logFileName , final String rollPattern ) { int index = logFileName . lastIndexOf ( '.' ) ; if ( index == - 1 ) return logFileName + rollPattern ; return logFileName . substring ( 0 , index ) + rollPattern + logFileName . substring ( index ) ; }
Merges the roll pattern name into the file name
7,431
protected static void setLogbackExternal ( final String fileName ) { try { final ObjectName logbackObjectName = new ObjectName ( "ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator" ) ; ManagementFactory . getPlatformMBeanServer ( ) . invoke ( logbackObjectName , "reloadByFileName" , new Object [ ] { fileName } , new String [ ] { String . class . getName ( ) } ) ; log . info ( "Set external logback config to [{}]" , fileName ) ; } catch ( Exception ex ) { log . warn ( "Failed to set external logback config to [{}]" , fileName , ex ) ; } }
Reloads the logback configuration to an external file
7,432
private static String [ ] shift ( String [ ] args ) { if ( args == null || args . length == 0 | args . length == 1 ) return new String [ 0 ] ; String [ ] newArgs = new String [ args . length - 1 ] ; System . arraycopy ( args , 1 , newArgs , 0 , newArgs . length ) ; return newArgs ; }
Drops the first array item in the passed array . If the passed array is null or empty returns an empty array
7,433
private static void writePid ( String file , boolean ignorePidFile ) { File pidFile = new File ( file ) ; if ( pidFile . exists ( ) ) { Long oldPid = getPid ( pidFile ) ; if ( oldPid == null ) { pidFile . delete ( ) ; } else { log . warn ( "\n\t==================================\n\tThe OpenTSDB PID file [" + file + "] already exists for PID [" + oldPid + "]. \n\tOpenTSDB might already be running.\n\t==================================\n" ) ; if ( ! ignorePidFile ) { log . warn ( "Exiting due to existing pid file. Start with option --ignore-existing-pid to overwrite" ) ; System . exit ( - 1 ) ; } else { log . warn ( "Deleting existing pid file [" + file + "]" ) ; pidFile . delete ( ) ; } } } pidFile . deleteOnExit ( ) ; File pidDir = pidFile . getParentFile ( ) ; FileOutputStream fos = null ; try { if ( ! pidDir . exists ( ) ) { if ( ! pidDir . mkdirs ( ) ) { throw new Exception ( "Failed to create PID directory [" + file + "]" ) ; } } fos = new FileOutputStream ( pidFile ) ; String PID = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) . split ( "@" ) [ 0 ] ; fos . write ( String . format ( "%s%s" , PID , EOL ) . getBytes ( ) ) ; fos . flush ( ) ; fos . close ( ) ; fos = null ; log . info ( "PID [" + PID + "] written to pid file [" + file + "]" ) ; } catch ( Exception ex ) { log . error ( "Failed to write PID file to [" + file + "]" , ex ) ; throw new IllegalArgumentException ( "Failed to write PID file to [" + file + "]" , ex ) ; } finally { if ( fos != null ) try { fos . close ( ) ; } catch ( Exception ex ) { } } }
Writes the PID to the file at the passed location
7,434
private static Long getPid ( File pidFile ) { FileReader reader = null ; BufferedReader lineReader = null ; String pidLine = null ; try { reader = new FileReader ( pidFile ) ; lineReader = new BufferedReader ( reader ) ; pidLine = lineReader . readLine ( ) ; if ( pidLine != null ) { pidLine = pidLine . trim ( ) ; } } catch ( Exception ex ) { log . error ( "Failed to read PID from file [" + pidFile . getAbsolutePath ( ) + "]" , ex ) ; } finally { if ( reader != null ) try { reader . close ( ) ; } catch ( Exception ex ) { } } try { return Long . parseLong ( pidLine ) ; } catch ( Exception ex ) { return null ; } }
Reads the pid from the specified pid file
7,435
private long getIdxOffsetFor ( final int i ) { checkRowOrder ( ) ; int idx = 0 ; int offset = 0 ; for ( final iHistogramRowSeq row : rows ) { final int sz = row . size ( ) ; if ( offset + sz > i ) { break ; } offset += sz ; idx ++ ; } return ( ( long ) idx << 32 ) | ( i - offset ) ; }
Finds the index of the row of the ith data point and the offset in the row .
7,436
public void validate ( ) { if ( start == null || start . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty start" ) ; } DateTime . parseDateTimeString ( start , timezone ) ; if ( end != null && ! end . isEmpty ( ) ) { DateTime . parseDateTimeString ( end , timezone ) ; } if ( downsampler != null ) { downsampler . validate ( ) ; } if ( aggregator == null || aggregator . isEmpty ( ) ) { throw new IllegalArgumentException ( "Missing or empty aggregator" ) ; } try { Aggregators . get ( aggregator . toLowerCase ( ) ) ; } catch ( final NoSuchElementException e ) { throw new IllegalArgumentException ( "Invalid aggregator" ) ; } }
Validates the timespan
7,437
private Grid makeStylePanel ( ) { for ( Entry < String , Integer > item : stylesMap . entrySet ( ) ) { styles . insertItem ( item . getKey ( ) , item . getValue ( ) ) ; } final Grid grid = new Grid ( 5 , 3 ) ; grid . setText ( 0 , 1 , "Smooth" ) ; grid . setWidget ( 0 , 2 , smooth ) ; grid . setText ( 1 , 1 , "Style" ) ; grid . setWidget ( 1 , 2 , styles ) ; return grid ; }
Additional styling options .
7,438
private Grid makeAxesPanel ( ) { final Grid grid = new Grid ( 5 , 3 ) ; grid . setText ( 0 , 1 , "Y" ) ; grid . setText ( 0 , 2 , "Y2" ) ; setTextAlignCenter ( grid . getRowFormatter ( ) . getElement ( 0 ) ) ; grid . setText ( 1 , 0 , "Label" ) ; grid . setWidget ( 1 , 1 , ylabel ) ; grid . setWidget ( 1 , 2 , y2label ) ; grid . setText ( 2 , 0 , "Format" ) ; grid . setWidget ( 2 , 1 , yformat ) ; grid . setWidget ( 2 , 2 , y2format ) ; grid . setText ( 3 , 0 , "Range" ) ; grid . setWidget ( 3 , 1 , yrange ) ; grid . setWidget ( 3 , 2 , y2range ) ; grid . setText ( 4 , 0 , "Log scale" ) ; grid . setWidget ( 4 , 1 , ylog ) ; grid . setWidget ( 4 , 2 , y2log ) ; setTextAlignCenter ( grid . getCellFormatter ( ) . getElement ( 4 , 1 ) ) ; setTextAlignCenter ( grid . getCellFormatter ( ) . getElement ( 4 , 2 ) ) ; return grid ; }
Builds the panel containing customizations for the axes of the graph .
7,439
private RadioButton addKeyRadioButton ( final Grid grid , final int row , final int col , final String pos ) { final RadioButton rb = new RadioButton ( "keypos" ) ; rb . addClickHandler ( new ClickHandler ( ) { public void onClick ( final ClickEvent event ) { keypos = pos ; } } ) ; rb . addClickHandler ( refreshgraph ) ; grid . setWidget ( row , col , rb ) ; keypos_map . put ( pos , rb ) ; return rb ; }
Small helper to build a radio button used to change the position of the key of the graph .
7,440
private static void ensureSameWidgetSize ( final DecoratedTabPanel panel ) { if ( ! panel . isAttached ( ) ) { throw new IllegalArgumentException ( "panel not attached: " + panel ) ; } int maxw = 0 ; int maxh = 0 ; for ( final Widget widget : panel ) { final int w = widget . getOffsetWidth ( ) ; final int h = widget . getOffsetHeight ( ) ; if ( w > maxw ) { maxw = w ; } if ( h > maxh ) { maxh = h ; } } if ( maxw == 0 || maxh == 0 ) { throw new IllegalArgumentException ( "maxw=" + maxw + " maxh=" + maxh ) ; } for ( final Widget widget : panel ) { setOffsetWidth ( widget , maxw ) ; setOffsetHeight ( widget , maxh ) ; } }
Ensures all the widgets in the given panel have the same size . Otherwise by default the panel will automatically resize itself to the contents of the currently active panel s widget which is annoying because it makes a number of things move around in the UI .
7,441
private static void setOffsetWidth ( final Widget widget , int width ) { widget . setWidth ( width + "px" ) ; final int offset = widget . getOffsetWidth ( ) ; if ( offset > 0 ) { width -= offset - width ; if ( width > 0 ) { widget . setWidth ( width + "px" ) ; } } }
Properly sets the total width of a widget . This takes into account decorations such as border margin and padding .
7,442
private static void setOffsetHeight ( final Widget widget , int height ) { widget . setHeight ( height + "px" ) ; final int offset = widget . getOffsetHeight ( ) ; if ( offset > 0 ) { height -= offset - height ; if ( height > 0 ) { widget . setHeight ( height + "px" ) ; } } }
Properly sets the total height of a widget . This takes into account decorations such as border margin and padding .
7,443
public static void parse ( final HashMap < String , String > tags , final String tag ) { final String [ ] kv = splitString ( tag , '=' ) ; if ( kv . length != 2 || kv [ 0 ] . length ( ) <= 0 || kv [ 1 ] . length ( ) <= 0 ) { throw new IllegalArgumentException ( "invalid tag: " + tag ) ; } if ( kv [ 1 ] . equals ( tags . get ( kv [ 0 ] ) ) ) { return ; } if ( tags . get ( kv [ 0 ] ) != null ) { throw new IllegalArgumentException ( "duplicate tag: " + tag + ", tags=" + tags ) ; } tags . put ( kv [ 0 ] , kv [ 1 ] ) ; }
Parses a tag into a HashMap .
7,444
public static String parseWithMetric ( final String metric , final List < Pair < String , String > > tags ) { final int curly = metric . indexOf ( '{' ) ; if ( curly < 0 ) { if ( metric . isEmpty ( ) ) { throw new IllegalArgumentException ( "Metric string was empty" ) ; } return metric ; } final int len = metric . length ( ) ; if ( metric . charAt ( len - 1 ) != '}' ) { throw new IllegalArgumentException ( "Missing '}' at the end of: " + metric ) ; } else if ( curly == len - 2 ) { if ( metric . charAt ( 0 ) == '{' ) { throw new IllegalArgumentException ( "Missing metric and tags: " + metric ) ; } return metric . substring ( 0 , len - 2 ) ; } for ( final String tag : splitString ( metric . substring ( curly + 1 , len - 1 ) , ',' ) ) { try { parse ( tags , tag ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "When parsing tag '" + tag + "': " + e . getMessage ( ) ) ; } } if ( metric . charAt ( 0 ) == '{' ) { return null ; } return metric . substring ( 0 , curly ) ; }
Parses an optional metric and tags out of the given string any of which may be null . Requires at least one metric tagk or tagv .
7,445
static String getValue ( final TSDB tsdb , final byte [ ] row , final String name ) throws NoSuchUniqueName { validateString ( "tag name" , name ) ; final byte [ ] id = tsdb . tag_names . getId ( name ) ; final byte [ ] value_id = getValueId ( tsdb , row , id ) ; if ( value_id == null ) { return null ; } try { return tsdb . tag_values . getName ( value_id ) ; } catch ( NoSuchUniqueId e ) { LOG . error ( "Internal error, NoSuchUniqueId unexpected here!" , e ) ; throw e ; } }
Extracts the value of the given tag name from the given row key .
7,446
static byte [ ] getValueId ( final TSDB tsdb , final byte [ ] row , final byte [ ] tag_id ) { final short name_width = tsdb . tag_names . width ( ) ; final short value_width = tsdb . tag_values . width ( ) ; for ( short pos = ( short ) ( Const . SALT_WIDTH ( ) + tsdb . metrics . width ( ) + Const . TIMESTAMP_BYTES ) ; pos < row . length ; pos += name_width + value_width ) { if ( rowContains ( row , pos , tag_id ) ) { pos += name_width ; return Arrays . copyOfRange ( row , pos , pos + value_width ) ; } } return null ; }
Extracts the value ID of the given tag UD name from the given row key .
7,447
private static boolean rowContains ( final byte [ ] row , short offset , final byte [ ] bytes ) { for ( int pos = bytes . length - 1 ; pos >= 0 ; pos -- ) { if ( row [ offset + pos ] != bytes [ pos ] ) { return false ; } } return true ; }
Checks whether or not the row key contains the given byte array at the given offset .
7,448
public static ByteMap < byte [ ] > getTagUids ( final byte [ ] row ) { final ByteMap < byte [ ] > uids = new ByteMap < byte [ ] > ( ) ; final short name_width = TSDB . tagk_width ( ) ; final short value_width = TSDB . tagv_width ( ) ; final short tag_bytes = ( short ) ( name_width + value_width ) ; final short metric_ts_bytes = ( short ) ( TSDB . metrics_width ( ) + Const . TIMESTAMP_BYTES + Const . SALT_WIDTH ( ) ) ; for ( short pos = metric_ts_bytes ; pos < row . length ; pos += tag_bytes ) { final byte [ ] tmp_name = new byte [ name_width ] ; final byte [ ] tmp_value = new byte [ value_width ] ; System . arraycopy ( row , pos , tmp_name , 0 , name_width ) ; System . arraycopy ( row , pos + name_width , tmp_value , 0 , value_width ) ; uids . put ( tmp_name , tmp_value ) ; } return uids ; }
Returns the tag key and value pairs as a byte map given a row key
7,449
public static Deferred < ArrayList < byte [ ] > > resolveAllAsync ( final TSDB tsdb , final Map < String , String > tags ) { return resolveAllInternalAsync ( tsdb , null , tags , false ) ; }
Resolves a set of tag strings to their UIDs asynchronously
7,450
public void writeToBuffers ( ByteBufferList compQualifier , ByteBufferList compValue ) { compQualifier . add ( qualifier , qualifier_offset , current_qual_length ) ; compValue . add ( value , value_offset , current_val_length ) ; }
Copy this value to the output and advance to the next one .
7,451
public int compareTo ( ColumnDatapointIterator o ) { int c = current_timestamp_offset - o . current_timestamp_offset ; if ( c == 0 ) { c = Long . signum ( o . column_timestamp - column_timestamp ) ; } return c ; }
entry we are going to keep first and don t have to copy over it )
7,452
public void addSubMetricQuery ( final String metric_query , final int sub_query_index , final int param_index ) { if ( metric_query == null || metric_query . isEmpty ( ) ) { throw new IllegalArgumentException ( "Metric query cannot be null or empty" ) ; } if ( sub_query_index < 0 ) { throw new IllegalArgumentException ( "Sub query index must be 0 or greater" ) ; } if ( param_index < 0 ) { throw new IllegalArgumentException ( "Parameter index must be 0 or greater" ) ; } if ( sub_metric_queries == null ) { sub_metric_queries = Maps . newHashMap ( ) ; } sub_metric_queries . put ( sub_query_index , metric_query ) ; parameter_index . put ( param_index , Parameter . METRIC_QUERY ) ; }
Sets the metric query key and index setting the Parameter type to METRIC_QUERY
7,453
public void addFunctionParameter ( final String param ) { if ( param == null || param . isEmpty ( ) ) { throw new IllegalArgumentException ( "Parameter cannot be null or empty" ) ; } if ( func_params == null ) { func_params = Lists . newArrayList ( ) ; } func_params . add ( param ) ; }
Adds parameters for the root expression only .
7,454
private String clean ( final Collection < String > values ) { if ( values == null || values . size ( ) == 0 ) { return "" ; } final List < String > strs = Lists . newArrayList ( ) ; for ( String v : values ) { final String tmp = v . replaceAll ( "\\{.*\\}" , "" ) ; final int ix = tmp . lastIndexOf ( ':' ) ; if ( ix < 0 ) { strs . add ( tmp ) ; } else { strs . add ( tmp . substring ( ix + 1 ) ) ; } } return DOUBLE_COMMA_JOINER . join ( strs ) ; }
Helper to clean out some characters
7,455
private < H extends EventHandler > void scheduleEvent ( final DomEvent < H > event ) { DeferredCommand . addCommand ( new Command ( ) { public void execute ( ) { onEvent ( event ) ; } } ) ; }
Executes the event using a deferred command .
7,456
public String render ( Object object ) { ModelAndView modelAndView = ( ModelAndView ) object ; return render ( modelAndView ) ; }
Renders the object
7,457
public AbstractFileResolvingResource getResource ( HttpServletRequest request ) throws MalformedURLException { String servletPath ; String pathInfo ; boolean included = request . getAttribute ( RequestDispatcher . INCLUDE_REQUEST_URI ) != null ; if ( included ) { servletPath = ( String ) request . getAttribute ( RequestDispatcher . INCLUDE_SERVLET_PATH ) ; pathInfo = ( String ) request . getAttribute ( RequestDispatcher . INCLUDE_PATH_INFO ) ; if ( servletPath == null && pathInfo == null ) { servletPath = request . getServletPath ( ) ; pathInfo = request . getPathInfo ( ) ; } } else { servletPath = request . getServletPath ( ) ; pathInfo = request . getPathInfo ( ) ; } String pathInContext = addPaths ( servletPath , pathInfo ) ; return getResource ( pathInContext ) ; }
Gets a resource from a servlet request
7,458
public Server create ( int maxThreads , int minThreads , int threadTimeoutMillis ) { Server server ; if ( maxThreads > 0 ) { int max = maxThreads ; int min = ( minThreads > 0 ) ? minThreads : 8 ; int idleTimeout = ( threadTimeoutMillis > 0 ) ? threadTimeoutMillis : 60000 ; server = new Server ( new QueuedThreadPool ( max , min , idleTimeout ) ) ; } else { server = new Server ( ) ; } return server ; }
Creates a Jetty server .
7,459
public Server create ( ThreadPool threadPool ) { return threadPool != null ? new Server ( threadPool ) : new Server ( ) ; }
Creates a Jetty server with supplied thread pool
7,460
public void map ( Class < ? extends Exception > exceptionClass , ExceptionHandlerImpl handler ) { this . exceptionMap . put ( exceptionClass , handler ) ; }
Maps the given handler to the provided exception type . If a handler was already registered to the same type the handler is overwritten .
7,461
public ExceptionHandlerImpl getHandler ( Class < ? extends Exception > exceptionClass ) { if ( ! this . exceptionMap . containsKey ( exceptionClass ) ) { Class < ? > superclass = exceptionClass . getSuperclass ( ) ; do { if ( this . exceptionMap . containsKey ( superclass ) ) { ExceptionHandlerImpl handler = this . exceptionMap . get ( superclass ) ; this . exceptionMap . put ( exceptionClass , handler ) ; return handler ; } superclass = superclass . getSuperclass ( ) ; } while ( superclass != null ) ; this . exceptionMap . put ( exceptionClass , null ) ; return null ; } return this . exceptionMap . get ( exceptionClass ) ; }
Returns the handler associated with the provided exception class
7,462
public static Object getFor ( int status , Request request , Response response ) { Object customRenderer = CustomErrorPages . getInstance ( ) . customPages . get ( status ) ; Object customPage = CustomErrorPages . getInstance ( ) . getDefaultFor ( status ) ; if ( customRenderer instanceof String ) { customPage = customRenderer ; } else if ( customRenderer instanceof Route ) { try { customPage = ( ( Route ) customRenderer ) . handle ( request , response ) ; } catch ( Exception e ) { LOG . warn ( "Custom error page handler for status code {} has thrown an exception: {}. Using default page instead." , status , e . getMessage ( ) ) ; } } return customPage ; }
Gets the custom error page for a given status code . If the custom error page is a route the output of its handle method is returned . If the custom error page is a String it is returned as an Object .
7,463
public String getDefaultFor ( int status ) { String defaultPage = defaultPages . get ( status ) ; return ( defaultPage != null ) ? defaultPage : "<html><body><h2>HTTP Status " + status + "</h2></body></html>" ; }
Returns the default error page for a given status code . Guaranteed to never be null .
7,464
static void add ( int status , String page ) { CustomErrorPages . getInstance ( ) . customPages . put ( status , page ) ; }
Add a custom error page as a String
7,465
static void add ( int status , Route route ) { CustomErrorPages . getInstance ( ) . customPages . put ( status , route ) ; }
Add a custom error page as a Route handler
7,466
public static void modify ( HttpServletResponse httpResponse , Body body , HaltException halt ) { httpResponse . setStatus ( halt . statusCode ( ) ) ; if ( halt . body ( ) != null ) { body . set ( halt . body ( ) ) ; } else { body . set ( "" ) ; } }
Modifies the HTTP response and body based on the provided HaltException .
7,467
@ SuppressWarnings ( "unchecked" ) public < T > T attribute ( String name ) { return ( T ) session . getAttribute ( name ) ; }
Returns the object bound with the specified name in this session or null if no object is bound under the name .
7,468
public void after ( Filter filter ) { addFilter ( HttpMethod . after , FilterImpl . create ( SparkUtils . ALL_PATHS , filter ) ) ; }
Maps a filter to be executed after any matching routes
7,469
private RouteImpl createRouteImpl ( String path , String acceptType , Route route ) { if ( defaultResponseTransformer != null ) { return ResponseTransformerRouteImpl . create ( path , acceptType , route , defaultResponseTransformer ) ; } return RouteImpl . create ( path , acceptType , route ) ; }
Create route implementation or use default response transformer
7,470
public static ServletContextHandler create ( Map < String , WebSocketHandlerWrapper > webSocketHandlers , Optional < Integer > webSocketIdleTimeoutMillis ) { ServletContextHandler webSocketServletContextHandler = null ; if ( webSocketHandlers != null ) { try { webSocketServletContextHandler = new ServletContextHandler ( null , "/" , true , false ) ; WebSocketUpgradeFilter webSocketUpgradeFilter = WebSocketUpgradeFilter . configureContext ( webSocketServletContextHandler ) ; if ( webSocketIdleTimeoutMillis . isPresent ( ) ) { webSocketUpgradeFilter . getFactory ( ) . getPolicy ( ) . setIdleTimeout ( webSocketIdleTimeoutMillis . get ( ) ) ; } NativeWebSocketConfiguration webSocketConfiguration = ( NativeWebSocketConfiguration ) webSocketServletContextHandler . getServletContext ( ) . getAttribute ( NativeWebSocketConfiguration . class . getName ( ) ) ; for ( String path : webSocketHandlers . keySet ( ) ) { WebSocketCreator webSocketCreator = WebSocketCreatorFactory . create ( webSocketHandlers . get ( path ) ) ; webSocketConfiguration . addMapping ( new ServletPathSpec ( path ) , webSocketCreator ) ; } } catch ( Exception ex ) { logger . error ( "creation of websocket context handler failed." , ex ) ; webSocketServletContextHandler = null ; } } return webSocketServletContextHandler ; }
Creates a new websocket servlet context handler .
7,471
public static EmbeddedServer create ( Object identifier , Routes routeMatcher , ExceptionMapper exceptionMapper , StaticFilesConfiguration staticFilesConfiguration , boolean multipleHandlers ) { EmbeddedServerFactory factory = factories . get ( identifier ) ; if ( factory != null ) { return factory . create ( routeMatcher , staticFilesConfiguration , exceptionMapper , multipleHandlers ) ; } else { throw new RuntimeException ( "No embedded server matching the identifier" ) ; } }
Creates an embedded server of type corresponding to the provided identifier .
7,472
public void redirect ( String location ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Redirecting ({} {} to {}" , "Found" , HttpServletResponse . SC_FOUND , location ) ; } try { response . sendRedirect ( location ) ; } catch ( IOException ioException ) { LOG . warn ( "Redirect failure" , ioException ) ; } }
Trigger a browser redirect
7,473
public void redirect ( String location , int httpStatusCode ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Redirecting ({} to {}" , httpStatusCode , location ) ; } response . setStatus ( httpStatusCode ) ; response . setHeader ( "Location" , location ) ; response . setHeader ( "Connection" , "close" ) ; try { response . sendError ( httpStatusCode ) ; } catch ( IOException e ) { LOG . warn ( "Exception when trying to redirect permanently" , e ) ; } }
Trigger a browser redirect with specific http 3XX status code .
7,474
public void removeCookie ( String path , String name ) { Cookie cookie = new Cookie ( name , "" ) ; cookie . setPath ( path ) ; cookie . setMaxAge ( 0 ) ; response . addCookie ( cookie ) ; }
Removes the cookie with given path and name .
7,475
protected final void loadQueryString ( Map < String , String [ ] > params ) { for ( Map . Entry < String , String [ ] > param : params . entrySet ( ) ) { loadKeys ( param . getKey ( ) , param . getValue ( ) ) ; } }
loads query string
7,476
public boolean consume ( HttpServletRequest httpRequest , HttpServletResponse httpResponse ) throws IOException { try { if ( consumeWithFileResourceHandlers ( httpRequest , httpResponse ) ) { return true ; } } catch ( DirectoryTraversal . DirectoryTraversalDetection directoryTraversalDetection ) { httpResponse . setStatus ( 400 ) ; httpResponse . getWriter ( ) . write ( "Bad request" ) ; httpResponse . getWriter ( ) . flush ( ) ; LOG . warn ( directoryTraversalDetection . getMessage ( ) + " directory traversal detection for path: " + httpRequest . getPathInfo ( ) ) ; } return false ; }
Attempt consuming using either static resource handlers or jar resource handlers
7,477
public void clear ( ) { if ( staticResourceHandlers != null ) { staticResourceHandlers . clear ( ) ; staticResourceHandlers = null ; } staticResourcesSet = false ; externalStaticResourcesSet = false ; }
Clears all static file configuration
7,478
public static String bestMatch ( Collection < String > supported , String header ) { List < ParseResults > parseResults = new LinkedList < > ( ) ; List < FitnessAndQuality > weightedMatches = new LinkedList < > ( ) ; for ( String r : header . split ( "," ) ) { parseResults . add ( parseMediaRange ( r ) ) ; } for ( String s : supported ) { FitnessAndQuality fitnessAndQuality = fitnessAndQualityParsed ( s , parseResults ) ; fitnessAndQuality . mimeType = s ; weightedMatches . add ( fitnessAndQuality ) ; } Collections . sort ( weightedMatches ) ; FitnessAndQuality lastOne = weightedMatches . get ( weightedMatches . size ( ) - 1 ) ; return Float . compare ( lastOne . quality , 0 ) != 0 ? lastOne . mimeType : NO_MIME_TYPE ; }
Finds best match
7,479
public void any ( String fromPath , String toPath , Status status ) { get ( fromPath , toPath , status ) ; post ( fromPath , toPath , status ) ; put ( fromPath , toPath , status ) ; delete ( fromPath , toPath , status ) ; }
Redirects any HTTP request of type GET POST PUT DELETE on fromPath to toPath with the provided redirect status code .
7,480
public void get ( String fromPath , String toPath , Status status ) { http . get ( fromPath , redirectRoute ( toPath , status ) ) ; }
Redirects any HTTP request of type GET on fromPath to toPath with the provided redirect status code .
7,481
public void post ( String fromPath , String toPath , Status status ) { http . post ( fromPath , redirectRoute ( toPath , status ) ) ; }
Redirects any HTTP request of type POST on fromPath to toPath with the provided redirect status code .
7,482
public void put ( String fromPath , String toPath , Status status ) { http . put ( fromPath , redirectRoute ( toPath , status ) ) ; }
Redirects any HTTP request of type PUT on fromPath to toPath with the provided redirect status code .
7,483
public void delete ( String fromPath , String toPath , Status status ) { http . delete ( fromPath , redirectRoute ( toPath , status ) ) ; }
Redirects any HTTP request of type DELETE on fromPath to toPath with the provided redirect status code .
7,484
public static void put ( String path , String acceptType , Route route ) { getInstance ( ) . put ( path , acceptType , route ) ; }
Map the route for HTTP PUT requests
7,485
public static void patch ( String path , String acceptType , Route route ) { getInstance ( ) . patch ( path , acceptType , route ) ; }
Map the route for HTTP PATCH requests
7,486
public static void trace ( String path , String acceptType , Route route ) { getInstance ( ) . trace ( path , acceptType , route ) ; }
Map the route for HTTP TRACE requests
7,487
public static void connect ( String path , String acceptType , Route route ) { getInstance ( ) . connect ( path , acceptType , route ) ; }
Map the route for HTTP CONNECT requests
7,488
public static void options ( String path , String acceptType , Route route ) { getInstance ( ) . options ( path , acceptType , route ) ; }
Map the route for HTTP OPTIONS requests
7,489
public static void before ( String path , String acceptType , Filter ... filters ) { for ( Filter filter : filters ) { getInstance ( ) . before ( path , acceptType , filter ) ; } }
Maps one or many filters to be executed before any matching routes
7,490
public static void after ( String path , String acceptType , Filter ... filters ) { for ( Filter filter : filters ) { getInstance ( ) . after ( path , acceptType , filter ) ; } }
Maps one or many filters to be executed after any matching routes
7,491
public static < T extends Exception > void exception ( Class < T > exceptionClass , ExceptionHandler < ? super T > handler ) { getInstance ( ) . exception ( exceptionClass , handler ) ; }
Maps an exception handler to be executed when an exception occurs during routing
7,492
public boolean exists ( ) { URL url ; if ( this . clazz != null ) { url = this . clazz . getResource ( this . path ) ; } else { url = this . classLoader . getResource ( this . path ) ; } return ( url != null ) ; }
This implementation checks for the resolution of a resource URL .
7,493
public Resource createRelative ( String relativePath ) { String pathToUse = StringUtils . applyRelativePath ( this . path , relativePath ) ; return new ClassPathResource ( pathToUse , this . classLoader , this . clazz ) ; }
This implementation creates a ClassPathResource applying the given path relative to the path of the underlying resource of this descriptor .
7,494
public void process ( OutputStream outputStream , Object element ) throws IOException { this . root . processElement ( outputStream , element ) ; }
Process the output .
7,495
static void modify ( HttpServletRequest httpRequest , HttpServletResponse httpResponse , Body body , RequestWrapper requestWrapper , ResponseWrapper responseWrapper , ExceptionMapper exceptionMapper , Exception e ) { ExceptionHandlerImpl handler = exceptionMapper . getHandler ( e ) ; if ( handler != null ) { handler . handle ( e , requestWrapper , responseWrapper ) ; String bodyAfterFilter = responseWrapper . getDelegate ( ) . body ( ) ; if ( bodyAfterFilter != null ) { body . set ( bodyAfterFilter ) ; } } else { LOG . error ( "" , e ) ; httpResponse . setStatus ( 500 ) ; if ( CustomErrorPages . existsFor ( 500 ) ) { requestWrapper . setDelegate ( RequestResponseFactory . create ( httpRequest ) ) ; responseWrapper . setDelegate ( RequestResponseFactory . create ( httpResponse ) ) ; body . set ( CustomErrorPages . getFor ( 500 , requestWrapper , responseWrapper ) ) ; } else { body . set ( CustomErrorPages . INTERNAL_ERROR ) ; } } }
Modifies the HTTP response and body based on the provided exception .
7,496
public void add ( HttpMethod httpMethod , RouteImpl route ) { add ( httpMethod , route . getPath ( ) , route . getAcceptType ( ) , route ) ; }
Add a route
7,497
public void add ( HttpMethod httpMethod , FilterImpl filter ) { add ( httpMethod , filter . getPath ( ) , filter . getAcceptType ( ) , filter ) ; }
Add a filter
7,498
public RouteMatch find ( HttpMethod httpMethod , String path , String acceptType ) { List < RouteEntry > routeEntries = this . findTargetsForRequestedRoute ( httpMethod , path ) ; RouteEntry entry = findTargetWithGivenAcceptType ( routeEntries , acceptType ) ; return entry != null ? new RouteMatch ( entry . target , entry . path , path , acceptType ) : null ; }
finds target for a requested route
7,499
public List < RouteMatch > findMultiple ( HttpMethod httpMethod , String path , String acceptType ) { List < RouteMatch > matchSet = new ArrayList < > ( ) ; List < RouteEntry > routeEntries = findTargetsForRequestedRoute ( httpMethod , path ) ; for ( RouteEntry routeEntry : routeEntries ) { if ( acceptType != null ) { String bestMatch = MimeParse . bestMatch ( Arrays . asList ( routeEntry . acceptedType ) , acceptType ) ; if ( routeWithGivenAcceptType ( bestMatch ) ) { matchSet . add ( new RouteMatch ( routeEntry . target , routeEntry . path , path , acceptType ) ) ; } } else { matchSet . add ( new RouteMatch ( routeEntry . target , routeEntry . path , path , acceptType ) ) ; } } return matchSet ; }
Finds multiple targets for a requested route .