idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
137,600
public int read ( ) throws IOException { synchronized ( file ) { while ( true ) { long len = file . getLength ( ) ; if ( len >= 1 ) { long pos = file . getFirstIndex ( ) ; file . file . seek ( pos + 16 ) ; int b = file . file . read ( ) ; if ( b == - 1 ) throw new EOFException ( "Unexpected EOF" ) ; addStats ( 1 ) ; lo...
Reads data from the file blocks until the data is available .
137,601
public int read ( byte [ ] b , int off , int len ) throws IOException { synchronized ( file ) { while ( true ) { long fileLen = file . getLength ( ) ; if ( fileLen >= 1 ) { long pos = file . getFirstIndex ( ) ; file . file . seek ( pos + 16 ) ; int readSize = fileLen > len ? len : ( int ) fileLen ; if ( ( pos + readSiz...
Reads data from the file blocks until at least one byte is available .
137,602
public long skip ( long n ) throws IOException { synchronized ( file ) { while ( true ) { long fileLen = file . getLength ( ) ; if ( fileLen >= 1 ) { long pos = file . getFirstIndex ( ) ; long skipSize = fileLen > n ? n : fileLen ; if ( ( pos + skipSize ) > file . maxFifoLength ) skipSize = file . maxFifoLength - pos ;...
Skips data in the queue blocks until at least one byte is skipped .
137,603
public int available ( ) throws IOException { synchronized ( file ) { long len = file . getLength ( ) ; return len > Integer . MAX_VALUE ? Integer . MAX_VALUE : ( int ) len ; } }
Determines the number of bytes that may be read without blocking .
137,604
protected void init ( final String name , final Properties props ) { init = new InitUtil ( "" , props , false ) ; this . name = name ; }
Initialize the properties .
137,605
public List < GeneratedPosition > allGeneratedPositionsFor ( int line , Integer column , String source ) { ParsedMapping needle = new ParsedMapping ( null , null , line , column == null ? 0 : column , null , null ) ; if ( this . sourceRoot != null ) { source = Util . relative ( this . sourceRoot , source ) ; } if ( ! t...
Returns all generated line and column information for the original source line and column provided . If no column is provided returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings . Otherwise returns all mappings corresponding to the given line and e...
137,606
< T > int _findMapping ( T aNeedle , List < T > aMappings , Object aLineName , Object aColumnName , BinarySearch . Comparator < T > aComparator , BinarySearch . Bias aBias ) { return BinarySearch . search ( aNeedle , aMappings , aComparator , aBias ) ; }
Find the mapping that best matches the hypothetical needle mapping that we are searching for in the given haystack of mappings .
137,607
public static InputStream getHTMLInputStream ( Class < ? > clazz ) throws IOException { return HTMLInputStreamPage . class . getResourceAsStream ( '/' + clazz . getName ( ) . replace ( '.' , '/' ) + ".html" ) ; }
Gets the HTML file with the same name as the provided Class .
137,608
public void save ( ProbeTestRun probeTestRun ) throws IOException { OutputStreamWriter osw = new OutputStreamWriter ( new FileOutputStream ( new File ( getTmpDir ( probeTestRun ) , UUID . randomUUID ( ) . toString ( ) ) ) , Charset . forName ( Constants . ENCODING ) . newEncoder ( ) ) ; serializer . serializePayload ( ...
Save a payload
137,609
void onClose ( AbstractSocket socket ) { synchronized ( sockets ) { if ( sockets . remove ( socket . getId ( ) ) == null ) throw new AssertionError ( "Socket not part of this context. onClose called twice?" ) ; } }
Called by a socket when it is closed . This will only be called once .
137,610
protected void addSocket ( final S newSocket ) { if ( isClosed ( ) ) throw new IllegalStateException ( "SocketContext is closed" ) ; Future < ? > future ; synchronized ( sockets ) { Identifier id = newSocket . getId ( ) ; if ( sockets . containsKey ( id ) ) throw new IllegalStateException ( "Socket with the same ID has...
Adds a new socket to this context sockets must be added to the context before they create any of their own events . This gives context listeners a chance to register per - socket listeners in onNewSocket .
137,611
public void writeCompressedUTF ( String str , int slot ) throws IOException { if ( slot < 0 || slot > 0x3f ) throw new IOException ( "Slot out of range (0-63): " + slot ) ; if ( lastStrings == null ) lastStrings = new String [ 64 ] ; String last = lastStrings [ slot ] ; if ( last == null ) last = "" ; int strLen = str ...
Writes a String to the stream while using prefix compression .
137,612
public void writeLongUTF ( String str ) throws IOException { int length = str . length ( ) ; writeCompressedInt ( length ) ; for ( int position = 0 ; position < length ; position += 20480 ) { int blockLength = length - position ; if ( blockLength > 20480 ) blockLength = 20480 ; String block = str . substring ( position...
Writes a string of any length .
137,613
public static void printPageList ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp , WebPage [ ] pages , WebPageLayout layout ) throws IOException , SQLException { int len = pages . length ; for ( int c = 0 ; c < len ; c ++ ) { WebPage page = pages [ c ] ; out . print ( " <tr>\n" + " <td style='whit...
Prints a list of pages .
137,614
public static void printPageList ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp , WebPage parent , WebPageLayout layout ) throws IOException , SQLException { printPageList ( out , req , resp , parent . getCachedPages ( req ) , layout ) ; }
Prints an unordered list of the available pages .
137,615
private boolean generatedPositionAfter ( Mapping mappingA , Mapping mappingB ) { int lineA = mappingA . generated . line ; int lineB = mappingB . generated . line ; int columnA = mappingA . generated . column ; int columnB = mappingB . generated . column ; return lineB > lineA || lineB == lineA && columnB >= columnA ||...
Determine whether mappingB is after mappingA with respect to generated position .
137,616
void add ( Mapping aMapping ) { if ( generatedPositionAfter ( this . _last , aMapping ) ) { this . _last = aMapping ; this . _array . add ( aMapping ) ; } else { this . _sorted = false ; this . _array . add ( aMapping ) ; } }
Add the given source mapping .
137,617
List < Mapping > toArray ( ) { if ( ! this . _sorted ) { Collections . sort ( this . _array , Util :: compareByGeneratedPositionsInflated ) ; this . _sorted = true ; } return this . _array ; }
Returns the flat sorted array of mappings . The mappings are sorted by generated position .
137,618
private static void loadDriver ( String classname ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { if ( ! driversLoaded . containsKey ( classname ) ) { Object O = Class . forName ( classname ) . newInstance ( ) ; driversLoaded . putIfAbsent ( classname , O ) ; } }
Loads a driver at most once .
137,619
protected void ensureCapacity ( long capacity ) throws IOException { long curCapacity = pbuffer . capacity ( ) ; if ( curCapacity < capacity ) expandCapacity ( curCapacity , capacity ) ; }
This class takes a lazy approach on allocating buffer space . It will allocate additional space as needed here rounding up to the next 4096 - byte boundary .
137,620
private static String getRelativePath ( File file , FilesystemIterator iterator ) throws IOException { String path = file . getPath ( ) ; String prefix = iterator . getStartPath ( ) ; if ( ! path . startsWith ( prefix ) ) throw new IOException ( "path doesn't start with prefix: path=\"" + path + "\", prefix=\"" + prefi...
Gets the relative path for the provided file from the provided iterator .
137,621
private String toLabel ( final TimeUnit unit ) { switch ( unit ) { case DAYS : return "day" ; case HOURS : return "hour" ; case MINUTES : return "minute" ; case SECONDS : return "second" ; case MILLISECONDS : return "ms" ; case MICROSECONDS : return "us" ; case NANOSECONDS : return "ns" ; default : return "" ; } }
Converts a time unit to a label .
137,622
public void connect ( final String endpoint , final Callback < ? super HttpSocket > onConnect , final Callback < ? super Exception > onError ) { executors . getUnbounded ( ) . submit ( new Runnable ( ) { public void run ( ) { try { AoByteArrayOutputStream bout = new AoByteArrayOutputStream ( ) ; try { try ( DataOutputS...
Asynchronously connects .
137,623
static final String encode ( int aValue ) { String encoded = "" ; int digit ; int vlq = toVLQSigned ( aValue ) ; do { digit = vlq & VLQ_BASE_MASK ; vlq >>>= VLQ_BASE_SHIFT ; if ( vlq > 0 ) { digit |= VLQ_CONTINUATION_BIT ; } encoded += Base64 . encode ( digit ) ; } while ( vlq > 0 ) ; return encoded ; }
Returns the base 64 VLQ encoded value .
137,624
static Base64VLQResult decode ( String aStr , int aIndex ) { int strLen = aStr . length ( ) ; int result = 0 ; int shift = 0 ; boolean continuation ; int digit ; do { if ( aIndex >= strLen ) { throw new Error ( "Expected more digits in base 64 VLQ value." ) ; } digit = Base64 . decode ( aStr . charAt ( aIndex ++ ) ) ; ...
Decodes the next base 64 VLQ value from the given string and returns the value and the rest of the string via the out parameter .
137,625
public static StringBuilder generateIdPrefix ( String template , String prefix ) { NullArgumentException . checkNotNull ( template , "template" ) ; NullArgumentException . checkNotNull ( prefix , "prefix" ) ; assert isValidId ( prefix ) ; final int len = template . length ( ) ; int pos = 0 ; while ( pos < len ) { char ...
Generates a valid ID from an arbitrary string .
137,626
void setPage ( Page page ) { synchronized ( lock ) { checkNotFrozen ( ) ; if ( this . page != null ) throw new IllegalStateException ( "element already has a page: " + this ) ; this . page = page ; } assert checkPageAndParentElement ( ) ; }
This is set when the element is associated with the page .
137,627
public String getId ( ) { if ( id == null ) { synchronized ( lock ) { if ( id == null ) { if ( page != null ) { Map < String , Element > elementsById = page . getElementsById ( ) ; String template = getElementIdTemplate ( ) ; if ( template == null ) { throw new IllegalStateException ( "null from getElementIdTemplate" )...
When inside a page every element must have a per - page unique ID when one is not provided it will be generated . When not inside a page no missing ID is generated and it will remain null .
137,628
public ElementRef getElementRef ( ) throws IllegalStateException { Page p = page ; if ( p == null ) throw new IllegalStateException ( "page not set" ) ; PageRef pageRef = p . getPageRef ( ) ; String i = getId ( ) ; if ( i == null ) throw new IllegalStateException ( "page not set so no id generated" ) ; ElementRef er = ...
Gets an ElementRef for this element . Must have a page set . If id has not yet been set one will be generated .
137,629
private void setParentElement ( Element parentElement ) { synchronized ( lock ) { checkNotFrozen ( ) ; if ( this . parentElement != null ) throw new IllegalStateException ( "parentElement already set" ) ; this . parentElement = parentElement ; } assert checkPageAndParentElement ( ) ; }
Sets the parent element of this element .
137,630
public Long addChildElement ( Element childElement , ElementWriter elementWriter ) { Long elementKey = super . addChildElement ( childElement , elementWriter ) ; childElement . setParentElement ( this ) ; return elementKey ; }
Adds a child element to this element .
137,631
private static void log ( File logFile , long connectionId , char separator , String line ) { synchronized ( logFile ) { try { try ( Writer out = new FileWriter ( logFile , true ) ) { out . write ( Long . toString ( connectionId ) ) ; out . write ( separator ) ; out . write ( ' ' ) ; out . write ( line ) ; out . write ...
Writes one line to the given file synchronizes on the file object .
137,632
public static Optional < Object > tryValue ( ReadableRepresentation representation , String name ) { try { return Optional . fromNullable ( representation . getValue ( name ) ) ; } catch ( RepresentationException e ) { return Optional . absent ( ) ; } }
Returns a property from the Representation .
137,633
private static final int intcmp ( Integer i1 , Integer i2 ) { if ( i1 == null && i2 == null ) { return 0 ; } if ( i1 == null ) { return - i2 ; } if ( i2 == null ) { return i1 ; } return i1 - i2 ; }
mimic the behaviour of i1 - i2 in JS
137,634
public int compareTo ( News o ) { int diff = o . getPubDate ( ) . compareTo ( getPubDate ( ) ) ; if ( diff != 0 ) return diff ; return getPage ( ) . compareTo ( o . getPage ( ) ) ; }
Ordered by pubDate desc page
137,635
public static JmxExporterConfig defaultJmxExporterConfig ( final InetAddress hostname , final Integer rmiRegistryPort , final Integer rmiServerPort , final boolean useRandomIds ) throws IOException { return new JmxExporterConfig ( ( hostname != null ) ? hostname : InetAddress . getByName ( null ) , ( rmiRegistryPort !=...
Creates a default configuration object .
137,636
public static Writer getInstance ( Writer out ) { if ( UNIX_EOL . equals ( EOL ) ) return out ; return new FindReplaceWriter ( out , EOL , UNIX_EOL ) ; }
Gets an instance of the Writer that performs the conversion . The implementation may be optimized for common platforms .
137,637
public static int [ ] getRGB ( BufferedImage image ) { int [ ] pixels = getRGBArray ( image ) ; getRGB ( image , pixels ) ; return pixels ; }
Gets the RGB pixels for the given image into a new array .
137,638
public static Image getImageFromResources ( Class < ? > clazz , String name ) throws IOException { return getImageFromResources ( clazz , name , Toolkit . getDefaultToolkit ( ) ) ; }
Loads an image from a resource using the default toolkit .
137,639
public static Image getImageFromResources ( Class < ? > clazz , String name , Toolkit toolkit ) throws IOException { byte [ ] imageData ; InputStream in = clazz . getResourceAsStream ( name ) ; if ( in == null ) throw new IOException ( "Unable to find resource: " + name ) ; try { imageData = IoUtils . readFully ( in ) ...
Loads an image from a resource using the provided toolkit .
137,640
public void printLoginForm ( WebPage page , LoginException loginException , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { getParent ( ) . printLoginForm ( page , loginException , req , resp ) ; }
Prints the form that is used to login .
137,641
public void printUnauthorizedPage ( WebPage page , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { getParent ( ) . printUnauthorizedPage ( page , req , resp ) ; }
Prints the unauthorized page message .
137,642
protected final long getClassLastModified ( ) throws IOException , SQLException { String dir = getServletContext ( ) . getRealPath ( "/WEB-INF/classes" ) ; if ( dir != null && dir . length ( ) > 0 ) { long lastMod = new File ( dir , getClass ( ) . getName ( ) . replace ( '.' , File . separatorChar ) + ".class" ) . last...
Gets the last modified time of the java class file . If the class file is unavailable it defaults to the time the servlets were loaded .
137,643
public long getWebPageAndChildrenLastModified ( WebSiteRequest req ) throws IOException , SQLException { WebPage [ ] myPages = getCachedPages ( req ) ; int len = myPages . length ; long mostRecent = getClassLastModified ( ) ; if ( mostRecent == - 1 ) return - 1 ; for ( int c = 0 ; c < len ; c ++ ) { long time = myPages...
Gets the most recent last modified time of this page and its immediate children .
137,644
final public long getLastModifiedRecursive ( WebSiteRequest req ) throws IOException , SQLException { long time = getLastModified ( req ) ; WebPage [ ] myPages = getCachedPages ( req ) ; int len = myPages . length ; for ( int c = 0 ; c < len ; c ++ ) { long time2 = myPages [ c ] . getLastModifiedRecursive ( req ) ; if ...
Recursively gets the most recent modification time .
137,645
public static long getLastModifiedRecursive ( File file ) { long time = file . lastModified ( ) ; if ( file . isDirectory ( ) ) { String [ ] list = file . list ( ) ; if ( list != null ) { int len = list . length ; for ( int c = 0 ; c < len ; c ++ ) { long time2 = getLastModifiedRecursive ( new File ( file , list [ c ] ...
Recursively gets the most recent modification time of a file or directory .
137,646
public void doGet ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { }
By default GET provides no content .
137,647
public final WebPage getRootPage ( ) throws IOException , SQLException { WebPage page = this ; WebPage parent ; while ( ( parent = page . getParent ( ) ) != null ) page = parent ; return page ; }
Gets the root page in the web page hierarchy . The root page has no parent .
137,648
public String getNavImageURL ( WebSiteRequest req , HttpServletResponse resp , Object params ) throws IOException , SQLException { return resp . encodeURL ( req . getContextPath ( ) + req . getURL ( this , params ) ) ; }
Gets the URL associated with a nav image .
137,649
final public int getPageIndexInParent ( WebSiteRequest req ) throws IOException , SQLException { WebPage [ ] myPages = getParent ( ) . getCachedPages ( req ) ; int len = myPages . length ; for ( int c = 0 ; c < len ; c ++ ) if ( myPages [ c ] . equals ( this ) ) return c ; throw new RuntimeException ( "Unable to find p...
Gets the index of this page in the parents list of children pages .
137,650
public static Class < ? extends WebPage > loadClass ( String className ) throws ClassNotFoundException { return Class . forName ( className ) . asSubclass ( WebPage . class ) ; }
Dynamically loads new classes based on the source . class file s modified time .
137,651
public String getCopyright ( WebSiteRequest req , HttpServletResponse resp , WebPage requestPage ) throws IOException , SQLException { return getParent ( ) . getCopyright ( req , resp , requestPage ) ; }
Gets the copyright information for this page . Defaults to the copyright of the parent page .
137,652
public static String join ( Iterable < ? > objects , String delimiter ) throws ConcurrentModificationException { int delimiterLength = delimiter . length ( ) ; int totalLength = 0 ; boolean didOne = false ; for ( Object obj : objects ) { if ( didOne ) totalLength += delimiterLength ; else didOne = true ; totalLength +=...
Joins the string representation of objects on the provided delimiter . The iteration will be performed twice . Once to compute the total length of the resulting string and the second to build the result .
137,653
public static < A extends Appendable > A join ( Iterable < ? > objects , String delimiter , A out ) throws IOException { boolean didOne = false ; for ( Object obj : objects ) { if ( didOne ) out . append ( delimiter ) ; else didOne = true ; out . append ( String . valueOf ( obj ) ) ; } return out ; }
Joins the string representation of objects on the provided delimiter .
137,654
public static int compareToDDMMYYYY ( String date1 , String date2 ) { if ( date1 . length ( ) != 8 || date2 . length ( ) != 8 ) return 0 ; return compareToDDMMYYYY0 ( date1 ) - compareToDDMMYYYY0 ( date2 ) ; }
Compare one date to another must be in the DDMMYYYY format .
137,655
public static int indexOf ( String S , char [ ] chars , int start ) { int Slen = S . length ( ) ; int clen = chars . length ; for ( int c = start ; c < Slen ; c ++ ) { char ch = S . charAt ( c ) ; for ( int d = 0 ; d < clen ; d ++ ) if ( ch == chars [ d ] ) return c ; } return - 1 ; }
Finds the first occurrence of any of the supplied characters starting at the specified index .
137,656
public static String replace ( final String string , final String find , final String replacement ) { int pos = string . indexOf ( find ) ; if ( pos == - 1 ) return string ; StringBuilder SB = new StringBuilder ( ) ; int lastpos = 0 ; final int findLen = find . length ( ) ; do { SB . append ( string , lastpos , pos ) ....
Replaces all occurrences of a String with a String Please consider the variant with the Appendable for higher performance .
137,657
public static void replace ( final StringBuffer sb , final String find , final String replacement ) { int pos = 0 ; while ( pos < sb . length ( ) ) { pos = sb . indexOf ( find , pos ) ; if ( pos == - 1 ) break ; sb . replace ( pos , pos + find . length ( ) , replacement ) ; pos += replacement . length ( ) ; } }
Replaces all occurrences of a String with a String .
137,658
public static List < String > splitLines ( String S ) { List < String > V = new ArrayList < > ( ) ; int start = 0 ; int pos ; while ( ( pos = S . indexOf ( '\n' , start ) ) != - 1 ) { String line ; if ( pos > start && S . charAt ( pos - 1 ) == '\r' ) line = S . substring ( start , pos - 1 ) ; else line = S . substring ...
Splits a String into lines on any \ n characters . Also removes any ending \ r characters if present
137,659
public static List < String > splitStringCommaSpace ( String line ) { List < String > words = new ArrayList < > ( ) ; int len = line . length ( ) ; int pos = 0 ; while ( pos < len ) { char ch ; while ( pos < len && ( ( ch = line . charAt ( pos ) ) <= ' ' || ch == ',' ) ) pos ++ ; int start = pos ; while ( pos < len && ...
Splits a string into multiple words on either whitespace or commas
137,660
public static void convertToHex ( int value , Appendable out ) throws IOException { out . append ( getHexChar ( value >>> 28 ) ) ; out . append ( getHexChar ( value >>> 24 ) ) ; out . append ( getHexChar ( value >>> 20 ) ) ; out . append ( getHexChar ( value >>> 16 ) ) ; out . append ( getHexChar ( value >>> 12 ) ) ; o...
Converts an int to a full 8 - character hex code .
137,661
public static int compareToIgnoreCaseCarefulEquals ( String S1 , String S2 ) { int diff = S1 . compareToIgnoreCase ( S2 ) ; if ( diff == 0 ) diff = S1 . compareTo ( S2 ) ; return diff ; }
Compares two strings in a case insensitive manner . However if they are considered equals in the case - insensitive manner the case sensitive comparison is done .
137,662
public static int indexOf ( String source , String target , int fromIndex , int toIndex ) { if ( fromIndex > toIndex ) throw new IllegalArgumentException ( "fromIndex>toIndex: fromIndex=" + fromIndex + ", toIndex=" + toIndex ) ; int sourceCount = source . length ( ) ; if ( toIndex < sourceCount ) sourceCount = toIndex ...
Finds the next of a substring like regular String . indexOf but stops at a certain maximum index . Like substring will look up to the character one before toIndex .
137,663
public static String nullIfEmpty ( String value ) { return value == null || value . isEmpty ( ) ? null : value ; }
Returns null if the string is null or empty .
137,664
public boolean isEmpty ( ) { for ( List < ? extends Method < ? extends E > > methods : methodsByClass . values ( ) ) { for ( Method < ? extends E > method : methods ) { E singleton = method . getSingleton ( target ) ; if ( singleton != null ) return false ; Set < ? extends E > set = method . getSet ( target ) ; if ( se...
Checks if this set is empty . This can be an expensive method since it can potentially call all methods .
137,665
@ SuppressWarnings ( "unchecked" ) public boolean addAll ( Collection < ? extends E > c ) { if ( c . isEmpty ( ) ) return false ; if ( c instanceof Set ) return addAll ( ( Set < ? extends E > ) c ) ; else throw new UnsupportedOperationException ( "May only add sets" ) ; }
Must be a set .
137,666
public TempFile createTempFile ( ) throws IOException { TempFile tempFile = new TempFile ( prefix , suffix , directory ) ; synchronized ( tempFiles ) { tempFiles . add ( new WeakReference < > ( tempFile ) ) ; } return tempFile ; }
Creates a new temp file while adding it to the list of files that will be explicitly deleted when this list is deleted .
137,667
public void delete ( ) throws IOException { synchronized ( tempFiles ) { for ( WeakReference < TempFile > tempFileRef : tempFiles ) { TempFile tempFile = tempFileRef . get ( ) ; if ( tempFile != null ) tempFile . delete ( ) ; } tempFiles . clear ( ) ; } }
Deletes all of the underlying temp files immediately .
137,668
private static File getFileUploadDirectory ( ServletContext servletContext ) throws FileNotFoundException { File uploadDir = new File ( ( File ) servletContext . getAttribute ( ServletContext . TEMPDIR ) , "uploads" ) ; if ( ! uploadDir . exists ( ) && ! uploadDir . mkdirs ( ) && ! uploadDir . exists ( ) ) { throw new ...
Gets the upload directory .
137,669
protected static boolean appendParams ( StringBuilder SB , Object optParam , List < String > finishedParams , boolean alreadyAppended ) { if ( optParam != null ) { if ( optParam instanceof String ) { List < String > nameValuePairs = StringUtility . splitString ( ( String ) optParam , '&' ) ; int len = nameValuePairs . ...
Appends the parameters to a URL . Parameters should already be URL encoded but not XML encoded .
137,670
public String getURL ( String classAndParams ) throws IOException , SQLException { String className , params ; int pos = classAndParams . indexOf ( '?' ) ; if ( pos == - 1 ) { className = classAndParams ; params = null ; } else { className = classAndParams . substring ( 0 , pos ) ; params = classAndParams . substring (...
Gets a relative URL from a String containing a classname and optional parameters . Parameters should already be URL encoded but not XML encoded .
137,671
public String getURL ( String classname , String params ) throws IOException , SQLException { try { Class < ? extends WebPage > clazz = Class . forName ( classname ) . asSubclass ( WebPage . class ) ; return getURL ( clazz , params ) ; } catch ( ClassNotFoundException err ) { throw new IOException ( "Unable to load cla...
Gets a relative URL given its classname and optional parameters . Parameters should already be URL encoded but not XML encoded .
137,672
public String getURL ( String url , Object optParam , boolean keepSettings ) throws IOException { StringBuilder SB = new StringBuilder ( ) ; SB . append ( url ) ; List < String > finishedParams = new SortedArrayList < > ( ) ; boolean alreadyAppended = appendParams ( SB , optParam , finishedParams , false ) ; if ( keepS...
Gets the context - relative URL optionally with the settings embedded . Parameters should already be URL encoded but not XML encoded .
137,673
public String getURL ( WebPage page ) throws IOException , SQLException { return getURL ( page , ( Object ) null ) ; }
Gets the context - relative URL to a web page .
137,674
public String getURL ( String url , Object optParam ) throws IOException { return getURL ( url , optParam , true ) ; }
Gets the URL String with the given parameters embedded keeping the current settings .
137,675
public boolean isLynx ( ) { if ( ! isLynxDone ) { String agent = req . getHeader ( "user-agent" ) ; isLynx = agent != null && agent . toLowerCase ( Locale . ROOT ) . contains ( "lynx" ) ; isLynxDone = true ; } return isLynx ; }
Determines if the request is for a Lynx browser
137,676
public boolean isBlackBerry ( ) { if ( ! isBlackBerryDone ) { String agent = req . getHeader ( "user-agent" ) ; isBlackBerry = agent != null && agent . startsWith ( "BlackBerry" ) ; isBlackBerryDone = true ; } return isBlackBerry ; }
Determines if the request is for a BlackBerry browser
137,677
public boolean isLinux ( ) { if ( ! isLinuxDone ) { String agent = req . getHeader ( "user-agent" ) ; isLinux = agent == null || agent . toLowerCase ( Locale . ROOT ) . contains ( "linux" ) ; isLinuxDone = true ; } return isLinux ; }
Determines if the request is for a Linux browser
137,678
public static String addParams ( String href , HttpParameters params , String encoding ) throws UnsupportedEncodingException { if ( params != null ) { StringBuilder sb = new StringBuilder ( href ) ; int anchorStart = href . lastIndexOf ( '#' ) ; String anchor ; boolean hasQuestion ; if ( anchorStart == - 1 ) { anchor =...
Adds all of the parameters to a URL .
137,679
public static String toJSONString ( Object o ) { try { return objectMapper . writer ( ) . without ( SerializationFeature . INDENT_OUTPUT ) . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( e ) ; } }
A not - pretty printed JSON string . Returns a portable JSON string .
137,680
final public void beginLightArea ( WebSiteRequest req , HttpServletResponse resp , ChainWriter out ) throws IOException { beginLightArea ( req , resp , out , null , false ) ; }
Begins a lighter colored area of the site .
137,681
private void makeNewFile ( ) throws IOException { String filename = prefix + ( files . size ( ) + 1 ) + suffix ; File file = new File ( parent , filename ) ; out = new FileOutputStream ( file ) ; bytesOut = 0 ; files . add ( file ) ; }
All accesses are already synchronized .
137,682
public static FileMessage decode ( String encodedMessage , File file ) throws IOException { return decode ( encodedMessage . isEmpty ( ) ? ByteArray . EMPTY_BYTE_ARRAY : new ByteArray ( Base64Coder . decode ( encodedMessage ) ) , file ) ; }
base - 64 decodes the message into the provided file .
137,683
public static FileMessage decode ( String encodedMessage ) throws IOException { return decode ( encodedMessage . isEmpty ( ) ? ByteArray . EMPTY_BYTE_ARRAY : new ByteArray ( Base64Coder . decode ( encodedMessage ) ) ) ; }
base - 64 decodes the message into a temp file .
137,684
public static FileMessage decode ( ByteArray encodedMessage , File file ) throws IOException { try ( OutputStream out = new FileOutputStream ( file ) ) { out . write ( encodedMessage . array , 0 , encodedMessage . size ) ; } return new FileMessage ( true , file ) ; }
Restores this message into the provided file .
137,685
public static FileMessage decode ( ByteArray encodedMessage ) throws IOException { File file = File . createTempFile ( "FileMessage." , null ) ; file . deleteOnExit ( ) ; return decode ( encodedMessage , file ) ; }
Restores this message into a temp file .
137,686
public static Registry createRegistry ( int port , RMIClientSocketFactory csf , RMIServerSocketFactory ssf ) throws RemoteException { synchronized ( registryCache ) { Integer portObj = port ; Registry registry = registryCache . get ( portObj ) ; if ( registry == null ) { registry = LocateRegistry . createRegistry ( por...
Creates a registry or returns the registry that is already using the port .
137,687
final public void close ( ) { List < C > connsToClose ; synchronized ( poolLock ) { isClosed = true ; connsToClose = new ArrayList < > ( availableConnections . size ( ) ) ; for ( PooledConnection < C > availableConnection : availableConnections ) { synchronized ( availableConnection ) { C conn = availableConnection . c...
Shuts down the pool exceptions during close will be logged as a warning and not thrown .
137,688
final public int getConnectionCount ( ) { int total = 0 ; synchronized ( poolLock ) { for ( PooledConnection < C > pooledConnection : allConnections ) { if ( pooledConnection . connection != null ) total ++ ; } } return total ; }
Gets the number of connections currently connected .
137,689
private void release ( PooledConnection < C > pooledConnection ) { long currentTime = System . currentTimeMillis ( ) ; long useTime ; synchronized ( pooledConnection ) { pooledConnection . releaseTime = currentTime ; useTime = currentTime - pooledConnection . startTime ; if ( useTime > 0 ) pooledConnection . totalTime ...
Releases a PooledConnection . It is safe to release it multiple times . The connection should have either been closed or reset before this is called because this makes the connection available for the next request .
137,690
final public long getConnects ( ) { long total = 0 ; synchronized ( poolLock ) { for ( PooledConnection < C > conn : allConnections ) { total += conn . connectCount . get ( ) ; } } return total ; }
Gets the total number of connects for the entire pool .
137,691
final public void run ( ) { while ( true ) { try { try { sleep ( delayTime ) ; } catch ( InterruptedException err ) { logger . log ( Level . WARNING , null , err ) ; } long time = System . currentTimeMillis ( ) ; List < C > connsToClose ; synchronized ( poolLock ) { if ( isClosed ) return ; int maxIdle = maxIdleTime ; ...
The RefreshConnection thread polls every connection in the connection pool . If it detects a connection is idle for more than the pre - defined MAX_IDLE_TIME it closes the connection . It will stop when the pool is flagged as closed .
137,692
public static byte [ ] md5 ( File file ) throws IOException { try ( InputStream in = new FileInputStream ( file ) ) { return md5 ( in ) ; } }
Gets the MD5 hashcode of a file .
137,693
public static byte [ ] md5 ( InputStream in ) throws IOException { MD5InputStream md5in = new MD5InputStream ( in ) ; byte [ ] trashBuffer = BufferManager . getBytes ( ) ; try { while ( md5in . read ( trashBuffer , 0 , BufferManager . BUFFER_SIZE ) != - 1 ) { } } finally { BufferManager . release ( trashBuffer , false ...
Gets the MD5 hashcode of an input stream .
137,694
public void delete ( ) throws IOException { File f = tempFile ; if ( f != null ) { FileUtils . delete ( f ) ; tempFile = null ; } }
Deletes the underlying temp file immediately . Subsequent calls will not delete the temp file even if another file has the same path . If already deleted has no effect .
137,695
public File getFile ( ) throws IllegalStateException { File f = tempFile ; if ( f == null ) throw new IllegalStateException ( ) ; return f ; }
Gets the temp file .
137,696
private void buildData ( String path , WebPage page , List < TreePageData > data , WebSiteRequest req ) throws IOException , SQLException { if ( isVisible ( page ) ) { if ( path . length ( ) > 0 ) path = path + '/' + page . getShortTitle ( ) ; else path = page . getShortTitle ( ) ; WebPage [ ] pages = page . getCachedP...
Recursively builds the list of all sites .
137,697
public void doGet ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp ) throws IOException , SQLException { if ( req != null ) super . doGet ( out , req , resp ) ; }
The content of this page will not be included in the interal search engine .
137,698
private void saveProperties ( ) { assert Thread . holdsLock ( properties ) ; try { Properties writer = new Properties ( ) { private static final long serialVersionUID = 6953022173340009928L ; public Enumeration < Object > keys ( ) { SortedSet < Object > sortedSet = new TreeSet < > ( Collator . getInstance ( Locale . RO...
Saves the properties file in ascending key order . All accesses must already hold a lock on the properties object .
137,699
public void checkGraph ( ) throws AsymmetricException , CycleException , EX { Set < V > vertices = graph . getVertices ( ) ; Map < V , Color > colors = new HashMap < > ( vertices . size ( ) * 4 / 3 + 1 ) ; Map < V , V > predecessors = new HashMap < > ( ) ; for ( V v : vertices ) { if ( ! colors . containsKey ( v ) ) do...
Test the graph for cycles and makes sure that all connections are consistent with back connections .