idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
40,400
public synchronized Servlet getServlet ( ) throws ServletException { if ( _unavailable != 0 ) { if ( _unavailable < 0 || _unavailable > 0 && System . currentTimeMillis ( ) < _unavailable ) throw _unavailableEx ; _unavailable = 0 ; _unavailableEx = null ; } try { if ( _servlets != null ) { Servlet servlet = null ; if ( _servlets . size ( ) == 0 ) { servlet = ( Servlet ) newInstance ( ) ; if ( _config == null ) _config = new Config ( ) ; initServlet ( servlet , _config ) ; } else servlet = ( Servlet ) _servlets . pop ( ) ; return servlet ; } if ( _servlet == null ) { _servlet = ( Servlet ) newInstance ( ) ; if ( _config == null ) _config = new Config ( ) ; initServlet ( _servlet , _config ) ; } return _servlet ; } catch ( UnavailableException e ) { _servlet = null ; _config = null ; return makeUnavailable ( e ) ; } catch ( ServletException e ) { _servlet = null ; _config = null ; throw e ; } catch ( Throwable e ) { _servlet = null ; _config = null ; throw new ServletException ( "init" , e ) ; } }
Get the servlet .
40,401
public void handle ( ServletRequest request , ServletResponse response ) throws ServletException , UnavailableException , IOException { if ( _class == null ) throw new UnavailableException ( "Servlet Not Initialized" ) ; Servlet servlet = ( ! _initOnStartup || _servlets != null ) ? getServlet ( ) : _servlet ; if ( servlet == null ) throw new UnavailableException ( "Could not instantiate " + _class ) ; boolean servlet_error = true ; Principal user = null ; HttpRequest http_request = null ; try { if ( _forcedPath != null ) request . setAttribute ( "org.apache.catalina.jsp_file" , _forcedPath ) ; if ( _runAs != null && _realm != null ) { http_request = getHttpContext ( ) . getHttpConnection ( ) . getRequest ( ) ; user = _realm . pushRole ( http_request . getUserPrincipal ( ) , _runAs ) ; http_request . setUserPrincipal ( user ) ; } servlet . service ( request , response ) ; servlet_error = false ; } catch ( UnavailableException e ) { if ( _servlets != null && servlet != null ) stop ( ) ; makeUnavailable ( e ) ; } finally { if ( _runAs != null && _realm != null && user != null ) { user = _realm . popRole ( user ) ; http_request . setUserPrincipal ( user ) ; } if ( servlet_error ) request . setAttribute ( "javax.servlet.error.servlet_name" , getName ( ) ) ; synchronized ( this ) { if ( _servlets != null && servlet != null ) _servlets . push ( servlet ) ; } } }
Service a request with this servlet .
40,402
public Frame nameFrame ( String name , int col , int row ) { if ( frameMap == null ) { frameMap = new Hashtable ( 10 ) ; frameNames = new Vector ( 10 ) ; } Frame frame = frames [ col ] [ row ] ; if ( frame == null ) frame = frames [ col ] [ row ] = new Frame ( ) ; if ( frameMap . get ( name ) == null ) frameNames . addElement ( name ) ; frameMap . put ( name , frame ) ; frame . name ( name ) ; return frame ; }
Name a frame . By convention frame names match Page section names
40,403
public void load ( String config ) throws IOException { _config = config ; if ( log . isDebugEnabled ( ) ) log . debug ( "Load " + this + " from " + config ) ; Properties properties = new Properties ( ) ; Resource resource = Resource . newResource ( config ) ; properties . load ( resource . getInputStream ( ) ) ; Iterator iter = properties . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String username = entry . getKey ( ) . toString ( ) . trim ( ) ; String credentials = entry . getValue ( ) . toString ( ) . trim ( ) ; String roles = null ; int c = credentials . indexOf ( ',' ) ; if ( c > 0 ) { roles = credentials . substring ( c + 1 ) . trim ( ) ; credentials = credentials . substring ( 0 , c ) . trim ( ) ; } if ( username != null && username . length ( ) > 0 && credentials != null && credentials . length ( ) > 0 ) { put ( username , credentials ) ; if ( roles != null && roles . length ( ) > 0 ) { StringTokenizer tok = new StringTokenizer ( roles , ", " ) ; while ( tok . hasMoreTokens ( ) ) addUserToRole ( username , tok . nextToken ( ) ) ; } } } }
Load realm users from properties file . The property file maps usernames to password specs followed by an optional comma separated list of role names .
40,404
public synchronized Object put ( Object name , Object credentials ) { if ( credentials instanceof Principal ) return super . put ( name . toString ( ) , credentials ) ; if ( credentials instanceof Password ) return super . put ( name , new KnownUser ( name . toString ( ) , ( Password ) credentials ) ) ; if ( credentials != null ) return super . put ( name , new KnownUser ( name . toString ( ) , Credential . getCredential ( credentials . toString ( ) ) ) ) ; return null ; }
Put user into realm .
40,405
public synchronized void addUserToRole ( String userName , String roleName ) { HashSet userSet = ( HashSet ) _roles . get ( roleName ) ; if ( userSet == null ) { userSet = new HashSet ( 11 ) ; _roles . put ( roleName , userSet ) ; } userSet . add ( userName ) ; }
Add a user to a role .
40,406
public synchronized boolean isUserInRole ( Principal user , String roleName ) { if ( user instanceof WrappedUser ) return ( ( WrappedUser ) user ) . isUserInRole ( roleName ) ; if ( user == null || ( ( User ) user ) . getUserRealm ( ) != this ) return false ; HashSet userSet = ( HashSet ) _roles . get ( roleName ) ; return userSet != null && userSet . contains ( user . getName ( ) ) ; }
Check if a user is in a role .
40,407
public String [ ] list ( ) { String [ ] list = _file . list ( ) ; if ( list == null ) return null ; for ( int i = list . length ; i -- > 0 ; ) { if ( new File ( _file , list [ i ] ) . isDirectory ( ) && ! list [ i ] . endsWith ( "/" ) ) list [ i ] += "/" ; } return list ; }
Returns a list of resources contained in the given resource
40,408
public ServletHolder mapPathToServlet ( String pathSpec , String servletName ) { ServletHolder holder = ( ServletHolder ) _nameMap . get ( servletName ) ; if ( ! pathSpec . startsWith ( "/" ) && ! pathSpec . startsWith ( "*" ) ) { log . warn ( "pathSpec should start with '/' or '*' : " + pathSpec ) ; pathSpec = "/" + pathSpec ; } if ( holder == null ) throw new IllegalArgumentException ( "Unknown servlet: " + servletName ) ; _servletMap . put ( pathSpec , holder ) ; return holder ; }
Map a servlet to a pathSpec
40,409
public void addServletHolder ( ServletHolder holder ) { ServletHolder existing = ( ServletHolder ) _nameMap . get ( holder . getName ( ) ) ; if ( existing == null ) _nameMap . put ( holder . getName ( ) , holder ) ; else if ( existing != holder ) throw new IllegalArgumentException ( "Holder already exists for name: " + holder . getName ( ) ) ; addComponent ( holder ) ; }
Register an existing ServletHolder with this handler .
40,410
public ServletHolder [ ] getServlets ( ) { HashSet holder_set = new HashSet ( _nameMap . size ( ) ) ; holder_set . addAll ( _nameMap . values ( ) ) ; ServletHolder holders [ ] = ( ServletHolder [ ] ) holder_set . toArray ( new ServletHolder [ holder_set . size ( ) ] ) ; java . util . Arrays . sort ( holders ) ; return holders ; }
Get Servlets .
40,411
public void initializeServlets ( ) throws Exception { MultiException mx = new MultiException ( ) ; ServletHolder [ ] holders = getServlets ( ) ; for ( int i = 0 ; i < holders . length ; i ++ ) { try { holders [ i ] . start ( ) ; } catch ( Exception e ) { log . debug ( LogSupport . EXCEPTION , e ) ; mx . add ( e ) ; } } mx . ifExceptionThrow ( ) ; }
Initialize load - on - startup servlets . Called automatically from start if autoInitializeServlet is true .
40,412
public URL getResource ( String uriInContext ) throws MalformedURLException { if ( uriInContext == null || ! uriInContext . startsWith ( "/" ) ) throw new MalformedURLException ( uriInContext ) ; try { Resource resource = getHttpContext ( ) . getResource ( uriInContext ) ; if ( resource != null && resource . exists ( ) ) return resource . getURL ( ) ; } catch ( IllegalArgumentException e ) { LogSupport . ignore ( log , e ) ; } catch ( MalformedURLException e ) { throw e ; } catch ( IOException e ) { log . warn ( LogSupport . EXCEPTION , e ) ; } return null ; }
Get a Resource . If no resource is found resource aliases are tried .
40,413
public RequestDispatcher getNamedDispatcher ( String name ) { if ( name == null || name . length ( ) == 0 ) name = __DEFAULT_SERVLET ; try { return new Dispatcher ( ServletHandler . this , name ) ; } catch ( Exception e ) { LogSupport . ignore ( log , e ) ; } return null ; }
Get Named dispatcher .
40,414
protected Object getContextAttribute ( String name ) { if ( ServletHandler . __J_S_CONTEXT_TEMPDIR . equals ( name ) ) { Object t = getHttpContext ( ) . getAttribute ( ServletHandler . __J_S_CONTEXT_TEMPDIR ) ; if ( t instanceof File ) return ( File ) t ; return getHttpContext ( ) . getTempDirectory ( ) ; } if ( _attributes . containsKey ( name ) ) return _attributes . get ( name ) ; return getHttpContext ( ) . getAttribute ( name ) ; }
Get context attribute . Tries ServletHandler attributes and then delegated to HttpContext .
40,415
protected Enumeration getContextAttributeNames ( ) { if ( _attributes . size ( ) == 0 ) return getHttpContext ( ) . getAttributeNames ( ) ; HashSet set = new HashSet ( _attributes . keySet ( ) ) ; Enumeration e = getHttpContext ( ) . getAttributeNames ( ) ; while ( e . hasMoreElements ( ) ) set . add ( e . nextElement ( ) ) ; return Collections . enumeration ( set ) ; }
Get context attribute names . Combines ServletHandler and HttpContext attributes .
40,416
public void configure ( Object obj ) throws ClassNotFoundException , NoSuchMethodException , InvocationTargetException , InstantiationException , IllegalAccessException { Class oClass = nodeClass ( _config ) ; if ( oClass != null ) { if ( obj != null && ! oClass . isInstance ( obj ) ) throw new IllegalArgumentException ( "Object is not of type " + oClass ) ; if ( obj == null ) obj = oClass . newInstance ( ) ; } configure ( obj , _config , 0 ) ; }
Configure an object . If the object is of the approprate class the XML configuration script is applied to the object .
40,417
public Object newInstance ( ) throws ClassNotFoundException , NoSuchMethodException , InvocationTargetException , InstantiationException , IllegalAccessException { Class oClass = nodeClass ( _config ) ; Object obj = null ; if ( oClass != null ) obj = oClass . newInstance ( ) ; configure ( obj , _config , 0 ) ; return obj ; }
Create a new object and configure it . A new object is created and configured .
40,418
public void configureWebApp ( ) throws Exception { if ( _context . isStarted ( ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Cannot configure webapp after it is started" ) ; } ; return ; } if ( log . isDebugEnabled ( ) ) log . debug ( "Configuring web-jetty.xml" ) ; Resource webInf = getWebApplicationContext ( ) . getWebInf ( ) ; if ( webInf != null && webInf . isDirectory ( ) ) { Resource jetty = webInf . addPath ( "web-jetty.xml" ) ; if ( ! jetty . exists ( ) ) jetty = webInf . addPath ( "jetty-web.xml" ) ; if ( ! getWebApplicationContext ( ) . isIgnoreWebJetty ( ) && jetty . exists ( ) ) { String [ ] old_server_classes = _context . getServerClasses ( ) ; String [ ] server_classes = new String [ 1 + ( old_server_classes == null ? 0 : old_server_classes . length ) ] ; server_classes [ 0 ] = "-org.browsermob.proxy.jetty." ; if ( server_classes != null ) System . arraycopy ( old_server_classes , 0 , server_classes , 1 , old_server_classes . length ) ; try { _context . setServerClasses ( server_classes ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Configure: " + jetty ) ; XmlConfiguration jetty_config = new XmlConfiguration ( jetty . getURL ( ) ) ; jetty_config . configure ( getWebApplicationContext ( ) ) ; } finally { if ( _context . getServerClasses ( ) == server_classes ) _context . setServerClasses ( old_server_classes ) ; } } } }
configureWebApp Apply web - jetty . xml configuration
40,419
public void addVirtualHost ( String hostname ) { if ( ! _vhosts . contains ( hostname ) ) { _vhosts . add ( hostname ) ; _contextName = null ; if ( _httpServer != null ) { if ( _vhosts . size ( ) == 1 ) _httpServer . removeMapping ( null , this ) ; _httpServer . addMapping ( hostname , this ) ; } _vhostsArray = null ; } }
Add a virtual host alias to this context .
40,420
public void removeVirtualHost ( String hostname ) { if ( _vhosts . remove ( hostname ) ) { _contextName = null ; if ( _httpServer != null ) { _httpServer . removeMapping ( hostname , this ) ; if ( _vhosts . size ( ) == 0 ) _httpServer . addMapping ( null , this ) ; } _vhostsArray = null ; } }
remove a virtual host alias to this context .
40,421
public void prewrite ( byte [ ] b ) { ensureReserve ( b . length ) ; System . arraycopy ( b , 0 , _buf , _start - b . length , b . length ) ; _start -= b . length ; }
Write byte array to start of the buffer .
40,422
public void prewrite ( byte [ ] b , int offset , int length ) { ensureReserve ( length ) ; System . arraycopy ( b , offset , _buf , _start - length , length ) ; _start -= length ; }
Write byte range to start of the buffer .
40,423
public void postwrite ( byte [ ] b , int offset , int length ) throws IOException { System . arraycopy ( b , offset , _buf , _pos , length ) ; _pos += length ; }
Write bytes into the postreserve . The capacity is not checked .
40,424
protected AJP13Connection createConnection ( Socket socket ) throws IOException { return new AJP13Connection ( this , socket . getInputStream ( ) , socket . getOutputStream ( ) , socket , getBufferSize ( ) ) ; }
Create an AJP13Connection instance . This method can be used to override the connection instance .
40,425
public Link target ( String t ) { if ( t != null && t . length ( ) > 0 ) attribute ( "target" , t ) ; return this ; }
Set the link target frame .
40,426
public void write ( Writer out ) throws IOException { if ( codeBase != null ) attribute ( "codebase" , codeBase ) ; if ( debug ) paramHolder . add ( "<param name=\"debug\" value=\"yes\">" ) ; if ( params != null ) for ( Enumeration enm = params . keys ( ) ; enm . hasMoreElements ( ) ; ) { String key = enm . nextElement ( ) . toString ( ) ; paramHolder . add ( "<param name=\"" + key + "\" value=\"" + params . get ( key ) . toString ( ) + "\">" ) ; } super . write ( out ) ; }
Write out the HTML
40,427
public Composite add ( Object o ) { if ( nest != null ) nest . add ( o ) ; else { if ( o != null ) { if ( o instanceof Element ) { if ( o instanceof Page ) throw new IllegalArgumentException ( "Can't insert Page in Composite" ) ; elements . add ( o ) ; } else if ( o instanceof String ) elements . add ( o ) ; else elements . add ( o . toString ( ) ) ; } } return this ; }
Add an Object to the Composite by converting it to a Element or . String
40,428
public Composite nest ( Composite c ) { if ( nest != null ) return nest . nest ( c ) ; else { add ( c ) ; nest = c ; } return this ; }
Nest a Composite within a Composite . The passed Composite is added to this Composite . Adds to this composite are actually added to the nested Composite . Calls to nest are passed the nested Composite
40,429
public void write ( Writer out ) throws IOException { for ( int i = 0 ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; if ( element instanceof Element ) ( ( Element ) element ) . write ( out ) ; else if ( element == null ) out . write ( "null" ) ; else out . write ( element . toString ( ) ) ; } }
Write the composite . The default implementation writes the elements sequentially . May be overridden for more specialized behaviour .
40,430
public String contents ( ) { StringBuffer buf = new StringBuffer ( ) ; synchronized ( buf ) { for ( int i = 0 ; i < elements . size ( ) ; i ++ ) { Object element = elements . get ( i ) ; if ( element == null ) buf . append ( "null" ) ; else buf . append ( element . toString ( ) ) ; } } return buf . toString ( ) ; }
Contents of the composite .
40,431
public boolean replace ( Object oldObj , Object newObj ) { if ( nest != null ) { return nest . replace ( oldObj , newObj ) ; } else { int sz = elements . size ( ) ; for ( int i = 0 ; i < sz ; i ++ ) { if ( elements . get ( i ) == oldObj ) { elements . set ( i , newObj ) ; return true ; } } } return false ; }
Replace an object within the composite .
40,432
public synchronized void log ( String formattedLog ) { if ( _reopen || _out == null ) { stop ( ) ; start ( ) ; } try { _buffer . write ( formattedLog ) ; _buffer . write ( StringUtil . __LINE_SEPARATOR ) ; if ( _flushOn || _buffer . size ( ) > _bufferSize ) { _buffer . writeTo ( _out ) ; _buffer . resetWriter ( ) ; _out . flush ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Log a message . The formatted log string is written to the log sink . The default implementation writes the message to an outputstream .
40,433
public synchronized void start ( ) { _buffer = new ByteArrayISO8859Writer ( _bufferSize ) ; _reopen = false ; if ( _started ) return ; if ( _out == null && _filename != null ) { try { RolloverFileOutputStream rfos = new RolloverFileOutputStream ( _filename , _append , _retainDays ) ; _out = rfos ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } if ( _out == null ) _out = LogStream . STDERR_STREAM ; _started = true ; }
Start a log sink . The default implementation does nothing
40,434
public synchronized void stop ( ) { _started = false ; if ( _out != null ) { try { if ( _buffer . size ( ) > 0 ) { _buffer . writeTo ( _out ) ; } _out . flush ( ) ; _buffer = null ; } catch ( Exception e ) { if ( _logImpl != null && _logImpl . getDebug ( ) ) e . printStackTrace ( ) ; } Thread . yield ( ) ; } if ( _out != null && _out != LogStream . STDERR_STREAM ) { try { _out . close ( ) ; } catch ( Exception e ) { if ( _logImpl != null && _logImpl . getDebug ( ) ) e . printStackTrace ( ) ; } } if ( _filename != null ) _out = null ; }
Stop a log sink . An opportunity for subclasses to clean up . The default implementation does nothing
40,435
public String [ ] getPartNames ( ) { Set s = _partMap . keySet ( ) ; return ( String [ ] ) s . toArray ( new String [ s . size ( ) ] ) ; }
Get the part names .
40,436
public boolean contains ( String name ) { Part part = ( Part ) _partMap . get ( name ) ; return ( part != null ) ; }
Check if a named part is present
40,437
public String getString ( String name ) { List part = _partMap . getValues ( name ) ; if ( part == null ) return null ; if ( _encoding != null ) { try { return new String ( ( ( Part ) part . get ( 0 ) ) . _data , _encoding ) ; } catch ( UnsupportedEncodingException uee ) { if ( log . isDebugEnabled ( ) ) log . debug ( "Invalid character set: " + uee ) ; return null ; } } else return new String ( ( ( Part ) part . get ( 0 ) ) . _data ) ; }
Get the data of a part as a string .
40,438
public InputStream getInputStream ( String name ) { List part = ( List ) _partMap . getValues ( name ) ; if ( part == null ) return null ; return new ByteArrayInputStream ( ( ( Part ) part . get ( 0 ) ) . _data ) ; }
Get the data of a part as a stream .
40,439
public Hashtable getParams ( String name ) { List part = ( List ) _partMap . getValues ( name ) ; if ( part == null ) return null ; return ( ( Part ) part . get ( 0 ) ) . _headers ; }
Get the MIME parameters associated with a part .
40,440
public String getFilename ( String name ) { List part = ( List ) _partMap . getValues ( name ) ; if ( part == null ) return null ; return ( ( Part ) part . get ( 0 ) ) . _filename ; }
Get any file name associated with a part .
40,441
public synchronized ServletHandler getServletHandler ( ) { if ( _webAppHandler == null ) { _webAppHandler = ( WebApplicationHandler ) getHandler ( WebApplicationHandler . class ) ; if ( _webAppHandler == null ) { if ( getHandler ( ServletHandler . class ) != null ) throw new IllegalStateException ( "Cannot have ServletHandler in WebApplicationContext" ) ; _webAppHandler = new WebApplicationHandler ( ) ; addHandler ( _webAppHandler ) ; } } return _webAppHandler ; }
Get the context ServletHandler . Conveniance method . If no ServletHandler exists a new one is added to the context . This derivation of the method creates a WebApplicationHandler extension of ServletHandler .
40,442
protected void doStart ( ) throws Exception { if ( isStarted ( ) ) return ; Thread thread = Thread . currentThread ( ) ; ClassLoader lastContextLoader = thread . getContextClassLoader ( ) ; MultiException mex = null ; try { resolveWebApp ( ) ; getServletHandler ( ) ; _configurations = loadConfigurations ( ) ; configureClassPath ( ) ; initClassLoader ( true ) ; thread . setContextClassLoader ( getClassLoader ( ) ) ; initialize ( ) ; configureDefaults ( ) ; Map . Entry entry = _webAppHandler . getHolderEntry ( "test.jsp" ) ; if ( entry != null ) { ServletHolder jspHolder = ( ServletHolder ) entry . getValue ( ) ; if ( jspHolder != null && jspHolder . getInitParameter ( "classpath" ) == null ) { String fileClassPath = getFileClassPath ( ) ; jspHolder . setInitParameter ( "classpath" , fileClassPath ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Set classpath=" + fileClassPath + " for " + jspHolder ) ; } } configureWebApp ( ) ; _webAppHandler . setAutoInitializeServlets ( false ) ; super . doStart ( ) ; mex = new MultiException ( ) ; if ( _contextListeners != null && _webAppHandler != null ) { ServletContextEvent event = new ServletContextEvent ( getServletContext ( ) ) ; for ( int i = 0 ; i < LazyList . size ( _contextListeners ) ; i ++ ) { try { ( ( ServletContextListener ) LazyList . get ( _contextListeners , i ) ) . contextInitialized ( event ) ; } catch ( Exception ex ) { mex . add ( ex ) ; } } } if ( _webAppHandler != null && _webAppHandler . isStarted ( ) ) { try { _webAppHandler . initializeServlets ( ) ; } catch ( Exception ex ) { mex . add ( ex ) ; } } } catch ( Exception e ) { log . warn ( "Configuration error on " + _war , e ) ; throw e ; } finally { thread . setContextClassLoader ( lastContextLoader ) ; } if ( mex != null ) mex . ifExceptionThrow ( ) ; }
Start the Web Application .
40,443
public void setResourceAlias ( String alias , String uri ) { if ( _resourceAliases == null ) _resourceAliases = new HashMap ( 5 ) ; _resourceAliases . put ( alias , uri ) ; }
Set Resource Alias . Resource aliases map resource uri s within a context . They may optionally be used by a handler when looking for a resource .
40,444
public void setErrorPage ( String error , String uriInContext ) { if ( _errorPages == null ) _errorPages = new HashMap ( ) ; _errorPages . put ( error , uriInContext ) ; }
set error page URI .
40,445
public String getErrorPage ( String error ) { if ( _errorPages == null ) return null ; return ( String ) _errorPages . get ( error ) ; }
get error page URI .
40,446
public void setName ( String name ) { synchronized ( Pool . class ) { if ( isStarted ( ) ) { if ( ( name == null && _pool . getPoolName ( ) != null ) || ( name != null && ! name . equals ( _pool . getPoolName ( ) ) ) ) throw new IllegalStateException ( "started" ) ; return ; } if ( name == null ) { if ( _pool . getPoolName ( ) != null ) { _pool = new Pool ( ) ; _pool . setPoolName ( getName ( ) ) ; } } else if ( ! name . equals ( getName ( ) ) ) { Pool pool = Pool . getPool ( name ) ; if ( pool == null ) _pool . setPoolName ( name ) ; else _pool = pool ; } } }
Set the Pool name . All ThreadPool instances with the same Pool name will share the same Pool instance . Thus they will share the same max min and available Threads . The field values of the first ThreadPool to call setPoolName with a specific name are used for the named Pool . Subsequent ThreadPools that join the name pool will loose their private values .
40,447
public int getThreadsPriority ( ) { int priority = Thread . NORM_PRIORITY ; Object o = _pool . getAttribute ( __PRIORITY ) ; if ( o != null ) { priority = ( ( Integer ) o ) . intValue ( ) ; } return priority ; }
Get the priority of the pool threads .
40,448
public void run ( Object job ) throws InterruptedException { if ( job == null ) return ; try { PoolThread thread = ( PoolThread ) _pool . get ( getMaxIdleTimeMs ( ) ) ; if ( thread != null ) thread . run ( this , job ) ; else { log . warn ( "No thread for " + job ) ; stopJob ( null , job ) ; } } catch ( InterruptedException e ) { throw e ; } catch ( Exception e ) { log . warn ( LogSupport . EXCEPTION , e ) ; } }
Run job . Give a job to the pool .
40,449
protected void handle ( Object job ) throws InterruptedException { if ( job != null && job instanceof Runnable ) ( ( Runnable ) job ) . run ( ) ; else log . warn ( "Invalid job: " + job ) ; }
Handle a job . Called by the allocated thread to handle a job . If the job is a Runnable it s run method is called . Otherwise this method needs to be specialized by a derived class to provide specific handling .
40,450
public static PublicKey parseRecord ( DNSKEYRecord r ) { int alg = r . getAlgorithm ( ) ; byte [ ] data = r . getKey ( ) ; return parseRecord ( alg , data ) ; }
Converts a DNSKEY record into a PublicKey
40,451
public static PublicKey parseRecord ( KEYRecord r ) { int alg = r . getAlgorithm ( ) ; byte [ ] data = r . getKey ( ) ; return parseRecord ( alg , data ) ; }
Converts a KEY record into a PublicKey
40,452
public static KEYRecord buildRecord ( Name name , int dclass , long ttl , int flags , int proto , PublicKey key ) { byte alg ; if ( key instanceof RSAPublicKey ) { alg = DNSSEC . RSAMD5 ; } else if ( key instanceof DHPublicKey ) { alg = DNSSEC . DH ; } else if ( key instanceof DSAPublicKey ) { alg = DNSSEC . DSA ; } else return null ; return ( KEYRecord ) buildRecord ( name , Type . KEY , dclass , ttl , flags , proto , alg , key ) ; }
Builds a KEY record from a PublicKey
40,453
public static Record buildRecord ( Name name , int type , int dclass , long ttl , int flags , int proto , int alg , PublicKey key ) { byte [ ] data ; if ( type != Type . KEY && type != Type . DNSKEY ) throw new IllegalArgumentException ( "type must be KEY " + "or DNSKEY" ) ; if ( key instanceof RSAPublicKey ) { data = buildRSA ( ( RSAPublicKey ) key ) ; } else if ( key instanceof DHPublicKey ) { data = buildDH ( ( DHPublicKey ) key ) ; } else if ( key instanceof DSAPublicKey ) { data = buildDSA ( ( DSAPublicKey ) key ) ; } else return null ; if ( data == null ) return null ; if ( type == Type . DNSKEY ) return new DNSKEYRecord ( name , dclass , ttl , flags , proto , alg , data ) ; else return new KEYRecord ( name , dclass , ttl , flags , proto , alg , data ) ; }
Builds a DNSKEY or KEY record from a PublicKey
40,454
public void setByteLimit ( int bytes ) { _byteLimit = bytes ; if ( bytes >= 0 ) { _newByteLimit = true ; _byteLimit -= _contents - _pos ; if ( _byteLimit < 0 ) { _avail += _byteLimit ; _byteLimit = 0 ; } } else { _newByteLimit = false ; _avail = _contents ; _eof = false ; } }
Set the byte limit . If set only this number of bytes are read before EOF .
40,455
public int readLine ( byte [ ] b , int off , int len ) throws IOException { len = fillLine ( len ) ; if ( len < 0 ) return - 1 ; if ( len == 0 ) return 0 ; System . arraycopy ( _buf , _mark , b , off , len ) ; _mark = - 1 ; return len ; }
Read a line ended by CR LF or CRLF .
40,456
public LineBuffer readLineBuffer ( int len ) throws IOException { len = fillLine ( len > 0 ? len : _buf . length ) ; if ( len < 0 ) return null ; if ( len == 0 ) { _lineBuffer . size = 0 ; return _lineBuffer ; } _byteBuffer . setStream ( _mark , len ) ; _lineBuffer . size = 0 ; int read = 0 ; while ( read < len && _reader . ready ( ) ) { int r = _reader . read ( _lineBuffer . buffer , read , len - read ) ; if ( r <= 0 ) break ; read += r ; } _lineBuffer . size = read ; _mark = - 1 ; return _lineBuffer ; }
Read a Line ended by CR LF or CRLF . Read a line into a shared LineBuffer instance . The LineBuffer is resused between calls and should not be held by the caller . The default or supplied encoding is used to convert bytes to characters .
40,457
public static String dump ( String description , byte [ ] b , int offset , int length ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( length + "b" ) ; if ( description != null ) sb . append ( " (" + description + ")" ) ; sb . append ( ':' ) ; int prefixlen = sb . toString ( ) . length ( ) ; prefixlen = ( prefixlen + 8 ) & ~ 7 ; sb . append ( '\t' ) ; int perline = ( 80 - prefixlen ) / 3 ; for ( int i = 0 ; i < length ; i ++ ) { if ( i != 0 && i % perline == 0 ) { sb . append ( '\n' ) ; for ( int j = 0 ; j < prefixlen / 8 ; j ++ ) sb . append ( '\t' ) ; } int value = ( int ) ( b [ i + offset ] ) & 0xFF ; sb . append ( hex [ ( value >> 4 ) ] ) ; sb . append ( hex [ ( value & 0xF ) ] ) ; sb . append ( ' ' ) ; } sb . append ( '\n' ) ; return sb . toString ( ) ; }
Dumps a byte array into hex format .
40,458
public static Resource newResource ( URL url ) throws IOException { if ( url == null ) return null ; String urls = url . toExternalForm ( ) ; if ( urls . startsWith ( "file:" ) ) { try { FileResource fileResource = new FileResource ( url ) ; return fileResource ; } catch ( Exception e ) { log . debug ( LogSupport . EXCEPTION , e ) ; return new BadResource ( url , e . toString ( ) ) ; } } else if ( urls . startsWith ( "jar:file:" ) ) { return new JarFileResource ( url ) ; } else if ( urls . startsWith ( "jar:" ) ) { return new JarResource ( url ) ; } return new URLResource ( url , null ) ; }
Construct a resource from a url .
40,459
public static Resource newResource ( String resource ) throws MalformedURLException , IOException { URL url = null ; try { url = new URL ( resource ) ; } catch ( MalformedURLException e ) { if ( ! resource . startsWith ( "ftp:" ) && ! resource . startsWith ( "file:" ) && ! resource . startsWith ( "jar:" ) ) { try { if ( resource . startsWith ( "./" ) ) resource = resource . substring ( 2 ) ; File file = new File ( resource ) . getCanonicalFile ( ) ; url = file . toURI ( ) . toURL ( ) ; URLConnection connection = url . openConnection ( ) ; FileResource fileResource = new FileResource ( url , connection , file ) ; return fileResource ; } catch ( Exception e2 ) { log . debug ( LogSupport . EXCEPTION , e2 ) ; throw e ; } } else { log . warn ( "Bad Resource: " + resource ) ; throw e ; } } String nurl = url . toString ( ) ; if ( nurl . length ( ) > 0 && nurl . charAt ( nurl . length ( ) - 1 ) != resource . charAt ( resource . length ( ) - 1 ) ) { if ( ( nurl . charAt ( nurl . length ( ) - 1 ) != '/' || nurl . charAt ( nurl . length ( ) - 2 ) != resource . charAt ( resource . length ( ) - 1 ) ) && ( resource . charAt ( resource . length ( ) - 1 ) != '/' || resource . charAt ( resource . length ( ) - 2 ) != nurl . charAt ( nurl . length ( ) - 1 ) ) ) { return new BadResource ( url , "Trailing special characters stripped by URL in " + resource ) ; } } return newResource ( url ) ; }
Construct a resource from a string .
40,460
public static Resource newSystemResource ( String resource ) throws IOException { URL url = null ; ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader != null ) { url = loader . getResource ( resource ) ; if ( url == null && resource . startsWith ( "/" ) ) url = loader . getResource ( resource . substring ( 1 ) ) ; } if ( url == null ) { loader = Resource . class . getClassLoader ( ) ; if ( loader != null ) { url = loader . getResource ( resource ) ; if ( url == null && resource . startsWith ( "/" ) ) url = loader . getResource ( resource . substring ( 1 ) ) ; } } if ( url == null ) { url = ClassLoader . getSystemResource ( resource ) ; if ( url == null && resource . startsWith ( "/" ) ) url = loader . getResource ( resource . substring ( 1 ) ) ; } if ( url == null ) return null ; return newResource ( url ) ; }
Construct a system resource from a string . The resource is tried as classloader resource before being treated as a normal resource .
40,461
public String getListHTML ( String base , boolean parent ) throws IOException { if ( ! isDirectory ( ) ) return null ; String [ ] ls = list ( ) ; if ( ls == null ) return null ; Arrays . sort ( ls ) ; String title = "Directory: " + URI . decodePath ( base ) ; title = StringUtil . replace ( StringUtil . replace ( title , "<" , "&lt;" ) , ">" , "&gt;" ) ; StringBuffer buf = new StringBuffer ( 4096 ) ; buf . append ( "<HTML><HEAD><TITLE>" ) ; buf . append ( title ) ; buf . append ( "</TITLE></HEAD><BODY>\n<H1>" ) ; buf . append ( title ) ; buf . append ( "</H1><TABLE BORDER=0>" ) ; if ( parent ) { buf . append ( "<TR><TD><A HREF=" ) ; buf . append ( URI . encodePath ( URI . addPaths ( base , "../" ) ) ) ; buf . append ( ">Parent Directory</A></TD><TD></TD><TD></TD></TR>\n" ) ; } DateFormat dfmt = DateFormat . getDateTimeInstance ( DateFormat . MEDIUM , DateFormat . MEDIUM ) ; for ( int i = 0 ; i < ls . length ; i ++ ) { String encoded = URI . encodePath ( ls [ i ] ) ; Resource item = addPath ( encoded ) ; buf . append ( "<TR><TD><A HREF=\"" ) ; String path = URI . addPaths ( base , encoded ) ; if ( item . isDirectory ( ) && ! path . endsWith ( "/" ) ) path = URI . addPaths ( path , "/" ) ; buf . append ( path ) ; buf . append ( "\">" ) ; buf . append ( StringUtil . replace ( StringUtil . replace ( ls [ i ] , "<" , "&lt;" ) , ">" , "&gt;" ) ) ; buf . append ( "&nbsp;" ) ; buf . append ( "</TD><TD ALIGN=right>" ) ; buf . append ( item . length ( ) ) ; buf . append ( " bytes&nbsp;</TD><TD>" ) ; buf . append ( dfmt . format ( new Date ( item . lastModified ( ) ) ) ) ; buf . append ( "</TD></TR>\n" ) ; } buf . append ( "</TABLE>\n" ) ; buf . append ( "</BODY></HTML>\n" ) ; return buf . toString ( ) ; }
Get the resource list as a HTML directory listing .
40,462
private void scavenge ( ) { Thread thread = Thread . currentThread ( ) ; ClassLoader old_loader = thread . getContextClassLoader ( ) ; try { if ( _handler == null ) return ; ClassLoader loader = _handler . getClassLoader ( ) ; if ( loader != null ) thread . setContextClassLoader ( loader ) ; long now = System . currentTimeMillis ( ) ; Object stale = null ; synchronized ( AbstractSessionManager . this ) { for ( Iterator i = _sessions . values ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Session session = ( Session ) i . next ( ) ; long idleTime = session . _maxIdleMs ; if ( idleTime > 0 && session . _accessed + idleTime < now ) { stale = LazyList . add ( stale , session ) ; } } } for ( int i = LazyList . size ( stale ) ; i -- > 0 ; ) { Session session = ( Session ) LazyList . get ( stale , i ) ; long idleTime = session . _maxIdleMs ; if ( idleTime > 0 && session . _accessed + idleTime < System . currentTimeMillis ( ) ) { session . invalidate ( ) ; int nbsess = this . _sessions . size ( ) ; if ( nbsess < this . _minSessions ) this . _minSessions = nbsess ; } } } finally { thread . setContextClassLoader ( old_loader ) ; } }
Find sessions that have timed out and invalidate them . This runs in the SessionScavenger thread .
40,463
public void loadConfig ( String config ) throws IOException { Properties properties = new Properties ( ) ; Resource resource = Resource . newResource ( config ) ; properties . load ( resource . getInputStream ( ) ) ; _jdbcDriver = properties . getProperty ( "jdbcdriver" ) ; _url = properties . getProperty ( "url" ) ; _userName = properties . getProperty ( "username" ) ; _password = properties . getProperty ( "password" ) ; _userTable = properties . getProperty ( "usertable" ) ; _userTableKey = properties . getProperty ( "usertablekey" ) ; _userTableUserField = properties . getProperty ( "usertableuserfield" ) ; _userTablePasswordField = properties . getProperty ( "usertablepasswordfield" ) ; _roleTable = properties . getProperty ( "roletable" ) ; _roleTableKey = properties . getProperty ( "roletablekey" ) ; _roleTableRoleField = properties . getProperty ( "roletablerolefield" ) ; _userRoleTable = properties . getProperty ( "userroletable" ) ; _userRoleTableUserKey = properties . getProperty ( "userroletableuserkey" ) ; _userRoleTableRoleKey = properties . getProperty ( "userroletablerolekey" ) ; _cacheTime = new Integer ( properties . getProperty ( "cachetime" ) ) . intValue ( ) ; if ( _jdbcDriver == null || _jdbcDriver . equals ( "" ) || _url == null || _url . equals ( "" ) || _userName == null || _userName . equals ( "" ) || _password == null || _cacheTime < 0 ) { if ( log . isDebugEnabled ( ) ) log . debug ( "UserRealm " + getName ( ) + " has not been properly configured" ) ; } _cacheTime *= 1000 ; _lastHashPurge = 0 ; _userSql = "select " + _userTableKey + "," + _userTablePasswordField + " from " + _userTable + " where " + _userTableUserField + " = ?" ; _roleSql = "select r." + _roleTableRoleField + " from " + _roleTable + " r, " + _userRoleTable + " u where u." + _userRoleTableUserKey + " = ?" + " and r." + _roleTableKey + " = u." + _userRoleTableRoleKey ; }
Load JDBC connection configuration from properties file .
40,464
protected void initWebXmlElement ( String element , XmlParser . Node node ) throws Exception { if ( "display-name" . equals ( element ) ) initDisplayName ( node ) ; else if ( "description" . equals ( element ) ) { } else if ( "context-param" . equals ( element ) ) initContextParam ( node ) ; else if ( "servlet" . equals ( element ) ) initServlet ( node ) ; else if ( "servlet-mapping" . equals ( element ) ) initServletMapping ( node ) ; else if ( "session-config" . equals ( element ) ) initSessionConfig ( node ) ; else if ( "mime-mapping" . equals ( element ) ) initMimeConfig ( node ) ; else if ( "welcome-file-list" . equals ( element ) ) initWelcomeFileList ( node ) ; else if ( "locale-encoding-mapping-list" . equals ( element ) ) initLocaleEncodingList ( node ) ; else if ( "error-page" . equals ( element ) ) initErrorPage ( node ) ; else if ( "taglib" . equals ( element ) ) initTagLib ( node ) ; else if ( "jsp-config" . equals ( element ) ) initJspConfig ( node ) ; else if ( "resource-ref" . equals ( element ) ) { if ( log . isDebugEnabled ( ) ) log . debug ( "No implementation: " + node ) ; } else if ( "security-constraint" . equals ( element ) ) initSecurityConstraint ( node ) ; else if ( "login-config" . equals ( element ) ) initLoginConfig ( node ) ; else if ( "security-role" . equals ( element ) ) initSecurityRole ( node ) ; else if ( "filter" . equals ( element ) ) initFilter ( node ) ; else if ( "filter-mapping" . equals ( element ) ) initFilterMapping ( node ) ; else if ( "listener" . equals ( element ) ) initListener ( node ) ; else if ( "distributable" . equals ( element ) ) initDistributable ( node ) ; else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Element " + element + " not handled in " + this ) ; log . debug ( node ) ; } } }
Handle web . xml element . This method is called for each top level element within the web . xml file . It may be specialized by derived WebApplicationContexts to provide additional configuration and handling .
40,465
public HttpListener addListener ( InetAddrPort address ) throws IOException { HttpListener listener = new SocketListener ( address ) ; listener . setHttpServer ( this ) ; _listeners . add ( listener ) ; addComponent ( listener ) ; return listener ; }
Create and add a SocketListener . Conveniance method .
40,466
public HttpListener addListener ( HttpListener listener ) throws IllegalArgumentException { listener . setHttpServer ( this ) ; _listeners . add ( listener ) ; addComponent ( listener ) ; return listener ; }
Add a HTTP Listener to the server .
40,467
public void removeListener ( HttpListener listener ) { if ( listener == null ) return ; for ( int l = 0 ; l < _listeners . size ( ) ; l ++ ) { if ( listener . equals ( _listeners . get ( l ) ) ) { _listeners . remove ( l ) ; removeComponent ( listener ) ; if ( listener . isStarted ( ) ) try { listener . stop ( ) ; } catch ( InterruptedException e ) { log . warn ( LogSupport . EXCEPTION , e ) ; } listener . setHttpServer ( null ) ; } } }
Remove a HTTP Listener .
40,468
protected synchronized void doStart ( ) throws Exception { log . info ( "Version " + Version . getImplVersion ( ) ) ; MultiException mex = new MultiException ( ) ; statsReset ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "LISTENERS: " + _listeners ) ; log . debug ( "HANDLER: " + _virtualHostMap ) ; } if ( _requestLog != null && ! _requestLog . isStarted ( ) ) { try { _requestLog . start ( ) ; } catch ( Exception e ) { mex . add ( e ) ; } } HttpContext [ ] contexts = getContexts ( ) ; for ( int i = 0 ; i < contexts . length ; i ++ ) { HttpContext context = contexts [ i ] ; try { context . start ( ) ; } catch ( Exception e ) { mex . add ( e ) ; } } for ( int l = 0 ; l < _listeners . size ( ) ; l ++ ) { HttpListener listener = ( HttpListener ) _listeners . get ( l ) ; listener . setHttpServer ( this ) ; if ( ! listener . isStarted ( ) ) try { listener . start ( ) ; } catch ( Exception e ) { mex . add ( e ) ; } } mex . ifExceptionThrowMulti ( ) ; }
Start all handlers then listeners . If a subcomponent fails to start it s exception is added to a org . mortbay . util . MultiException and the start method continues .
40,469
public synchronized void stop ( boolean graceful ) throws InterruptedException { boolean ov = _gracefulStop ; try { _gracefulStop = graceful ; stop ( ) ; } finally { _gracefulStop = ov ; } }
Stop all listeners then all contexts .
40,470
public void join ( ) throws InterruptedException { for ( int l = 0 ; l < _listeners . size ( ) ; l ++ ) { HttpListener listener = ( HttpListener ) _listeners . get ( l ) ; if ( listener . isStarted ( ) && listener instanceof ThreadPool ) { ( ( ThreadPool ) listener ) . join ( ) ; } } }
Join the listeners . Join all listeners that are instances of ThreadPool .
40,471
public void addHostAlias ( String virtualHost , String alias ) { log . warn ( "addHostAlias is deprecated. Use HttpContext.addVirtualHost" ) ; Object contextMap = _virtualHostMap . get ( virtualHost ) ; if ( contextMap == null ) throw new IllegalArgumentException ( "No Such Host: " + virtualHost ) ; _virtualHostMap . put ( alias , contextMap ) ; }
Define a virtual host alias . All requests to the alias are handled the same as request for the virtualHost .
40,472
public synchronized void setRequestLog ( RequestLog log ) { if ( _requestLog != null ) removeComponent ( _requestLog ) ; _requestLog = log ; if ( _requestLog != null ) addComponent ( _requestLog ) ; }
Set the request log .
40,473
void log ( HttpRequest request , HttpResponse response , int length ) { if ( _requestLog != null && request != null && response != null ) _requestLog . log ( request , response , length ) ; }
Log a request to the request log
40,474
public HttpContext service ( HttpRequest request , HttpResponse response ) throws IOException , HttpException { String host = request . getHost ( ) ; if ( _requestsPerGC > 0 && _gcRequests ++ > _requestsPerGC ) { _gcRequests = 0 ; System . gc ( ) ; } while ( true ) { PathMap contextMap = ( PathMap ) _virtualHostMap . get ( host ) ; if ( contextMap != null ) { List contextLists = contextMap . getMatches ( request . getPath ( ) ) ; if ( contextLists != null ) { if ( log . isTraceEnabled ( ) ) log . trace ( "Contexts at " + request . getPath ( ) + ": " + contextLists ) ; for ( int i = 0 ; i < contextLists . size ( ) ; i ++ ) { Map . Entry entry = ( Map . Entry ) contextLists . get ( i ) ; List contextList = ( List ) entry . getValue ( ) ; for ( int j = 0 ; j < contextList . size ( ) ; j ++ ) { HttpContext context = ( HttpContext ) contextList . get ( j ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Try " + context + "," + j ) ; context . handle ( request , response ) ; if ( request . isHandled ( ) ) return context ; } } } } if ( host == null ) break ; host = null ; } synchronized ( this ) { if ( _notFoundContext == null ) { _notFoundContext = new HttpContext ( ) ; _notFoundContext . setContextPath ( "/" ) ; _notFoundContext . setHttpServer ( this ) ; try { _notFoundContext . addHandler ( ( NotFoundHandler ) Class . forName ( "org.browsermob.proxy.jetty.http.handler.RootNotFoundHandler" ) . newInstance ( ) ) ; } catch ( Exception e ) { _notFoundContext . addHandler ( new NotFoundHandler ( ) ) ; } addComponent ( _notFoundContext ) ; try { _notFoundContext . start ( ) ; } catch ( Exception e ) { log . warn ( LogSupport . EXCEPTION , e ) ; } } _notFoundContext . handle ( request , response ) ; if ( ! request . isHandled ( ) ) response . sendError ( HttpResponse . __404_Not_Found ) ; return _notFoundContext ; } }
Service a request . Handle the request by passing it to the HttpHandler contained in the mapped HttpContexts . The requests host and path are used to select a list of HttpContexts . Each HttpHandler in these context is offered the request in turn until the request is handled .
40,475
public HttpHandler findHandler ( Class handlerClass , String uri , String [ ] vhosts ) { uri = URI . stripPath ( uri ) ; if ( vhosts == null || vhosts . length == 0 ) vhosts = __noVirtualHost ; for ( int h = 0 ; h < vhosts . length ; h ++ ) { String host = vhosts [ h ] ; PathMap contextMap = ( PathMap ) _virtualHostMap . get ( host ) ; if ( contextMap != null ) { List contextLists = contextMap . getMatches ( uri ) ; if ( contextLists != null ) { for ( int i = 0 ; i < contextLists . size ( ) ; i ++ ) { Map . Entry entry = ( Map . Entry ) contextLists . get ( i ) ; List contextList = ( List ) entry . getValue ( ) ; for ( int j = 0 ; j < contextList . size ( ) ; j ++ ) { HttpContext context = ( HttpContext ) contextList . get ( j ) ; HttpHandler handler = context . getHandler ( handlerClass ) ; if ( handler != null ) return handler ; } } } } } return null ; }
Find handler . Find a handler for a URI . This method is provided for the servlet context getContext method to search for another context by URI . A list of hosts may be passed to qualify the search .
40,476
public UserRealm getRealm ( String realmName ) { if ( realmName == null ) { if ( _realmMap . size ( ) == 1 ) return ( UserRealm ) _realmMap . values ( ) . iterator ( ) . next ( ) ; log . warn ( "Null realmName with multiple known realms" ) ; } return ( UserRealm ) _realmMap . get ( realmName ) ; }
Get a named UserRealm .
40,477
public void statsReset ( ) { _statsStartedAt = System . currentTimeMillis ( ) ; _connections = 0 ; _connectionsOpenMin = _connectionsOpen ; _connectionsOpenMax = _connectionsOpen ; _connectionsOpen = 0 ; _connectionsDurationMin = 0 ; _connectionsDurationMax = 0 ; _connectionsDurationTotal = 0 ; _errors = 0 ; _requests = 0 ; _requestsActiveMin = _requestsActive ; _requestsActiveMax = _requestsActive ; _requestsActive = 0 ; _connectionsRequestsMin = 0 ; _connectionsRequestsMax = 0 ; _requestsDurationMin = 0 ; _requestsDurationMax = 0 ; _requestsDurationTotal = 0 ; }
Reset statistics .
40,478
public void save ( String saveat ) throws MalformedURLException , IOException { Resource resource = Resource . newResource ( saveat ) ; ObjectOutputStream out = new ObjectOutputStream ( resource . getOutputStream ( ) ) ; out . writeObject ( this ) ; out . flush ( ) ; out . close ( ) ; log . info ( "Saved " + this + " to " + resource ) ; }
Save the HttpServer The server is saved by serialization to the given filename or URL .
40,479
public static void main ( String [ ] args ) { if ( args . length == 0 || args . length > 2 ) { System . err . println ( "\nUsage - java org.browsermob.proxy.jetty.http.HttpServer [<addr>:]<port>" ) ; System . err . println ( "\nUsage - java org.browsermob.proxy.jetty.http.HttpServer -r [savefile]" ) ; System . err . println ( " Serves files from '.' directory" ) ; System . err . println ( " Dump handler for not found requests" ) ; System . err . println ( " Default port is 8080" ) ; System . exit ( 1 ) ; } try { if ( args . length == 1 ) { HttpServer server = new HttpServer ( ) ; String host = null ; HttpContext context = server . getContext ( host , "/" ) ; context . setResourceBase ( "." ) ; context . addHandler ( new ResourceHandler ( ) ) ; context . addHandler ( new DumpHandler ( ) ) ; context . addHandler ( new NotFoundHandler ( ) ) ; InetAddrPort address = new InetAddrPort ( args [ 0 ] ) ; server . addListener ( address ) ; server . start ( ) ; } else { Resource resource = Resource . newResource ( args [ 1 ] ) ; ObjectInputStream in = new ObjectInputStream ( resource . getInputStream ( ) ) ; HttpServer server = ( HttpServer ) in . readObject ( ) ; in . close ( ) ; server . start ( ) ; } } catch ( Exception e ) { log . warn ( LogSupport . EXCEPTION , e ) ; } }
Construct server from command line arguments .
40,480
public static Certificate parseRecord ( CERTRecord r ) { int type = r . getCertType ( ) ; byte [ ] data = r . getCert ( ) ; Certificate cert ; try { switch ( type ) { case CERTRecord . PKIX : { CertificateFactory cf ; ByteArrayInputStream bs ; cf = CertificateFactory . getInstance ( "X.509" ) ; bs = new ByteArrayInputStream ( data ) ; cert = cf . generateCertificate ( bs ) ; break ; } default : return null ; } return cert ; } catch ( CertificateException e ) { if ( Options . check ( "verboseexceptions" ) ) System . err . println ( "Cert parse exception:" + e ) ; return null ; } }
Converts a CERT record into a Certificate
40,481
public static CERTRecord buildRecord ( Name name , int dclass , long ttl , Certificate cert , int tag , int alg ) { int type ; byte [ ] data ; try { if ( cert instanceof X509Certificate ) { type = CERTRecord . PKIX ; data = cert . getEncoded ( ) ; } else return null ; return new CERTRecord ( name , dclass , ttl , type , tag , alg , data ) ; } catch ( CertificateException e ) { if ( Options . check ( "verboseexceptions" ) ) System . err . println ( "Cert build exception:" + e ) ; return null ; } }
Builds a CERT record from a Certificate associated with a key also in DNS
40,482
public static CERTRecord buildRecord ( Name name , int dclass , long ttl , Certificate cert ) { return buildRecord ( name , dclass , ttl , cert , 0 , 0 ) ; }
Builds a CERT record from a Certificate
40,483
public static byte [ ] getByteArray ( int size ) { byte [ ] [ ] pool = ( byte [ ] [ ] ) __pools . get ( ) ; boolean full = true ; for ( int i = pool . length ; i -- > 0 ; ) { if ( pool [ i ] != null && pool [ i ] . length == size ) { byte [ ] b = pool [ i ] ; pool [ i ] = null ; return b ; } else full = false ; } if ( full ) for ( int i = pool . length ; i -- > 0 ; ) pool [ i ] = null ; return new byte [ size ] ; }
Get a byte array from the pool of known size .
40,484
public static String quote ( String s , String delim ) { if ( s == null ) return null ; if ( s . length ( ) == 0 ) return "\"\"" ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == '"' || c == '\\' || c == '\'' || delim . indexOf ( c ) >= 0 ) { StringBuffer b = new StringBuffer ( s . length ( ) + 8 ) ; quote ( b , s ) ; return b . toString ( ) ; } } return s ; }
Quote a string . The string is quoted only if quoting is required due to embeded delimiters quote characters or the empty string .
40,485
public static void quote ( StringBuffer buf , String s ) { synchronized ( buf ) { buf . append ( '"' ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == '"' ) { buf . append ( "\\\"" ) ; continue ; } if ( c == '\\' ) { buf . append ( "\\\\" ) ; continue ; } buf . append ( c ) ; continue ; } buf . append ( '"' ) ; } }
Quote a string into a StringBuffer .
40,486
public void truncate ( int offset ) throws IOException { if ( ( offset < 0 ) || ( offset > _write_pos ) ) throw new IOException ( "bad truncate offset" ) ; if ( _read_pos > offset ) _read_pos = offset ; if ( _mark_pos > offset ) _mark_pos = offset ; _write_pos = offset ; if ( _file_high > offset ) _file_high = offset ; moveWindow ( _write_pos ) ; }
Truncates buffered data to specified size . Can not be used to extend data . Repositions OutputStream at the end of truncated data . If current read offset or mark is past the new end of data it is moved at the new end .
40,487
public void setTempDirectory ( File dir ) throws IOException { File td = dir . getCanonicalFile ( ) ; if ( td . isDirectory ( ) ) { _temp_directory = td ; } }
Override directory to create temporary file in . Does not affect already open temp file .
40,488
public String getString ( String character_encoding ) throws java . io . UnsupportedEncodingException { if ( _file_mode ) throw new IllegalStateException ( "data too large" ) ; return new String ( _memory_buffer , 0 , _write_pos , character_encoding ) ; }
Returns buffered data as String using given character encoding .
40,489
public java . io . InputStream getInputStream ( ) { if ( _input_stream == null ) { _input_stream = new TempByteHolder . InputStream ( ) ; } return _input_stream ; }
Returns InputSream for reading buffered data .
40,490
public void writeTo ( java . io . OutputStream os , int start_offset , int length ) throws IOException { int towrite = min ( length , _write_pos - start_offset ) ; int writeoff = start_offset ; if ( towrite > 0 ) { while ( towrite >= _window_size ) { moveWindow ( writeoff ) ; os . write ( _memory_buffer , 0 , _window_size ) ; towrite -= _window_size ; writeoff += _window_size ; } if ( towrite > 0 ) { moveWindow ( writeoff ) ; os . write ( _memory_buffer , 0 , towrite ) ; } } }
Writes efficiently part of the content to output stream .
40,491
public void readFrom ( java . io . InputStream is ) throws IOException { int howmuch = 0 ; do { _write_pos += howmuch ; moveWindow ( _write_pos ) ; howmuch = is . read ( _memory_buffer ) ; } while ( howmuch != - 1 ) ; }
Reads all available data from input stream .
40,492
private void createTempFile ( ) throws IOException { _tempfilef = File . createTempFile ( "org.browsermob.proxy.jetty.util.TempByteHolder-" , ".tmp" , _temp_directory ) . getCanonicalFile ( ) ; _tempfilef . deleteOnExit ( ) ; _tempfile = new RandomAccessFile ( _tempfilef , "rw" ) ; }
Create tempfile if it does not already exist
40,493
private void writeToTempFile ( int at_offset , byte [ ] data , int offset , int len ) throws IOException { if ( _tempfile == null ) { createTempFile ( ) ; _file_pos = - 1 ; } _file_mode = true ; if ( at_offset != _file_pos ) { _tempfile . seek ( ( long ) at_offset ) ; } _tempfile . write ( data , offset , len ) ; _file_pos = at_offset + len ; _file_high = max ( _file_high , _file_pos ) ; }
Write chunk of data at specified offset in temp file . Marks data as big . Updates high water mark on tempfile content .
40,494
private void readFromTempFile ( int at_offset , byte [ ] data , int offset , int len ) throws IOException { if ( _file_pos != at_offset ) { _tempfile . seek ( ( long ) at_offset ) ; } _tempfile . readFully ( data , offset , len ) ; _file_pos = at_offset + len ; }
Read chunk of data from specified offset in tempfile
40,495
private static int min ( int a , int b , int c ) { int r = a ; if ( r > b ) r = b ; if ( r > c ) r = c ; return r ; }
Simple minimum for 3 ints
40,496
public synchronized Object put ( Object pathSpec , Object object ) { StringTokenizer tok = new StringTokenizer ( pathSpec . toString ( ) , __pathSpecSeparators ) ; Object old = null ; while ( tok . hasMoreTokens ( ) ) { String spec = tok . nextToken ( ) ; if ( ! spec . startsWith ( "/" ) && ! spec . startsWith ( "*." ) ) { log . warn ( "PathSpec " + spec + ". must start with '/' or '*.'" ) ; spec = "/" + spec ; } old = super . put ( spec , object ) ; Entry entry = new Entry ( spec , object ) ; if ( entry . getKey ( ) . equals ( spec ) ) { if ( spec . equals ( "/*" ) ) _prefixDefault = entry ; else if ( spec . endsWith ( "/*" ) ) { _prefixMap . put ( spec . substring ( 0 , spec . length ( ) - 2 ) , entry ) ; _exactMap . put ( spec . substring ( 0 , spec . length ( ) - 1 ) , entry ) ; _exactMap . put ( spec . substring ( 0 , spec . length ( ) - 2 ) , entry ) ; } else if ( spec . startsWith ( "*." ) ) _suffixMap . put ( spec . substring ( 2 ) , entry ) ; else if ( spec . equals ( "/" ) ) { if ( _nodefault ) _exactMap . put ( spec , entry ) ; else { _default = entry ; _defaultSingletonList = SingletonList . newSingletonList ( _default ) ; } } else _exactMap . put ( spec , entry ) ; } } return old ; }
Add a single path match to the PathMap .
40,497
public Object match ( String path ) { Map . Entry entry = getMatch ( path ) ; if ( entry != null ) return entry . getValue ( ) ; return null ; }
Get object matched by the path .
40,498
public Map . Entry getMatch ( String path ) { Map . Entry entry ; if ( path == null ) return null ; int l = path . indexOf ( ';' ) ; if ( l < 0 ) { l = path . indexOf ( '?' ) ; if ( l < 0 ) l = path . length ( ) ; } entry = _exactMap . getEntry ( path , 0 , l ) ; if ( entry != null ) return ( Map . Entry ) entry . getValue ( ) ; int i = l ; while ( ( i = path . lastIndexOf ( '/' , i - 1 ) ) >= 0 ) { entry = _prefixMap . getEntry ( path , 0 , i ) ; if ( entry != null ) return ( Map . Entry ) entry . getValue ( ) ; } if ( _prefixDefault != null ) return _prefixDefault ; i = 0 ; while ( ( i = path . indexOf ( '.' , i + 1 ) ) > 0 ) { entry = _suffixMap . getEntry ( path , i + 1 , l - i - 1 ) ; if ( entry != null ) return ( Map . Entry ) entry . getValue ( ) ; } return _default ; }
Get the entry mapped by the best specification .
40,499
public List getMatches ( String path ) { Map . Entry entry ; Object entries = null ; if ( path == null ) return LazyList . getList ( entries ) ; int l = path . indexOf ( ';' ) ; if ( l < 0 ) { l = path . indexOf ( '?' ) ; if ( l < 0 ) l = path . length ( ) ; } entry = _exactMap . getEntry ( path , 0 , l ) ; if ( entry != null ) entries = LazyList . add ( entries , entry . getValue ( ) ) ; int i = l - 1 ; while ( ( i = path . lastIndexOf ( '/' , i - 1 ) ) >= 0 ) { entry = _prefixMap . getEntry ( path , 0 , i ) ; if ( entry != null ) entries = LazyList . add ( entries , entry . getValue ( ) ) ; } if ( _prefixDefault != null ) entries = LazyList . add ( entries , _prefixDefault ) ; i = 0 ; while ( ( i = path . indexOf ( '.' , i + 1 ) ) > 0 ) { entry = _suffixMap . getEntry ( path , i + 1 , l - i - 1 ) ; if ( entry != null ) entries = LazyList . add ( entries , entry . getValue ( ) ) ; } if ( _default != null ) { if ( entries == null ) return _defaultSingletonList ; entries = LazyList . add ( entries , _default ) ; } return LazyList . getList ( entries ) ; }
Get all entries matched by the path . Best match first .