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" ) ) { ha...
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 . getQuer...
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 ( ...
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 ....
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 . ge...
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 . getQueryStringP...
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 BadReque...
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 { ret...
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 =...
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_...
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_wid...
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 ) < timestam...
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 ( sp...
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 [" + thre...
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 Sca...
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_...
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: I...
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 c...
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 ( Ex...
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 (...
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 ( "s...
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" , ne...
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 + "] ...
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 ( ) ; } } c...
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 ) ...
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" )...
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 ...
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 )...
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 . ...
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 ...
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 . leng...
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 t...
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 ) ; ...
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_t...
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 ...
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...
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 ( Reques...
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 ( m...
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 . exc...
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 = custom...
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 ...
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 ( routeMatc...
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 { res...
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 . setSta...
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 ( Stri...
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 . ...
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 , en...
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 ) { ...
Finds multiple targets for a requested route .