idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
137,300
public static boolean isAllowed ( ServletContext servletContext , ServletRequest request ) { return Boolean . parseBoolean ( servletContext . getInitParameter ( ENABLE_INIT_PARAM ) ) && isAllowedAddr ( request . getRemoteAddr ( ) ) ; }
Checks if the given request is allowed to open files on the server . The servlet init param must have it enabled as well as be from an allowed IP .
64
33
137,301
public static void addFileOpener ( ServletContext servletContext , FileOpener fileOpener , String ... extensions ) { synchronized ( fileOpenersLock ) { @ SuppressWarnings ( "unchecked" ) Map < String , FileOpener > fileOpeners = ( Map < String , FileOpener > ) servletContext . getAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME ) ; if ( fileOpeners == null ) { fileOpeners = new HashMap <> ( ) ; servletContext . setAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME , fileOpeners ) ; } for ( String extension : extensions ) { if ( fileOpeners . containsKey ( extension ) ) throw new IllegalStateException ( "File opener already registered: " + extension ) ; fileOpeners . put ( extension , fileOpener ) ; } } }
Registers a file opener .
196
6
137,302
public static void removeFileOpener ( ServletContext servletContext , String ... extensions ) { synchronized ( fileOpenersLock ) { @ SuppressWarnings ( "unchecked" ) Map < String , FileOpener > fileOpeners = ( Map < String , FileOpener > ) servletContext . getAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME ) ; if ( fileOpeners != null ) { for ( String extension : extensions ) { fileOpeners . remove ( extension ) ; } if ( fileOpeners . isEmpty ( ) ) { servletContext . removeAttribute ( FILE_OPENERS_REQUEST_ATTRIBUTE_NAME ) ; } } } }
Removes file openers .
153
6
137,303
public static void addCookie ( HttpServletRequest request , HttpServletResponse response , String cookieName , String value , String comment , int maxAge , boolean secure , boolean contextOnlyPath ) { Cookie newCookie = new Cookie ( cookieName , value ) ; if ( comment != null ) newCookie . setComment ( comment ) ; newCookie . setMaxAge ( maxAge ) ; newCookie . setSecure ( secure && request . isSecure ( ) ) ; String path ; if ( contextOnlyPath ) { path = request . getContextPath ( ) + "/" ; //if(path.length()==0) path = "/"; } else { path = "/" ; } newCookie . setPath ( path ) ; response . addCookie ( newCookie ) ; }
Adds a cookie .
171
4
137,304
public static void removeCookie ( HttpServletRequest request , HttpServletResponse response , String cookieName , boolean secure , boolean contextOnlyPath ) { addCookie ( request , response , cookieName , "Removed" , null , 0 , secure , contextOnlyPath ) ; }
Removes a cookie by adding it with maxAge of zero .
61
13
137,305
@ Override public int compareTo ( Column o ) { int diff = name . compareToIgnoreCase ( o . name ) ; if ( diff != 0 ) return diff ; return name . compareTo ( o . name ) ; }
Ordered by column name only .
49
7
137,306
@ Override public int read ( ) throws IOException { int c = in . read ( ) ; if ( c == - 1 ) return - 1 ; md5 . Update ( c ) ; return c ; }
Read a byte of data .
44
6
137,307
@ Override public int read ( byte bytes [ ] , int offset , int length ) throws IOException { int r ; if ( ( r = in . read ( bytes , offset , length ) ) == - 1 ) return - 1 ; md5 . Update ( bytes , offset , r ) ; return r ; }
Reads into an array of bytes .
65
8
137,308
void addBundle ( EditableResourceBundle bundle ) { Locale locale = bundle . getBundleLocale ( ) ; if ( ! locales . contains ( locale ) ) throw new AssertionError ( "locale not in locales: " + locale ) ; bundles . put ( locale , bundle ) ; }
The constructor of EditableResourceBundle adds itself here .
68
12
137,309
public EditableResourceBundle getResourceBundle ( Locale locale ) { EditableResourceBundle localeBundle = bundles . get ( locale ) ; if ( localeBundle == null ) { ResourceBundle resourceBundle = ResourceBundle . getBundle ( baseName , locale ) ; if ( ! resourceBundle . getLocale ( ) . equals ( locale ) ) throw new AssertionError ( "ResourceBundle not for this locale: " + locale ) ; if ( ! ( resourceBundle instanceof EditableResourceBundle ) ) throw new AssertionError ( "ResourceBundle is not a EditableResourceBundle: " + resourceBundle ) ; localeBundle = ( EditableResourceBundle ) resourceBundle ; if ( localeBundle . getBundleSet ( ) != this ) throw new AssertionError ( "EditableResourceBundle not for this EditableResourceBundleSet: " + localeBundle ) ; if ( ! localeBundle . getBundleLocale ( ) . equals ( locale ) ) throw new AssertionError ( "EditableResourceBundle not for this locale: " + locale ) ; // EditableResourceBundle will have added the bundle to the bundles map. } return localeBundle ; }
Gets the editable bundle for the provided locale .
270
11
137,310
public static Boolean getEnvironmentBoolean ( String name , Boolean defaultValue ) { if ( envVars == null ) { throw new IllegalStateException ( "The environment vars must be provided before calling getEnvironmentBoolean." ) ; } String value = getEnvironmentString ( name , null ) ; if ( value == null ) { return defaultValue ; } else { return BOOLEAN_PATTERN . matcher ( value ) . matches ( ) ; } }
Retrieve boolean value for the environment variable name
97
9
137,311
public static Integer getEnvironmentInteger ( String name , Integer defaultValue ) { if ( envVars == null ) { throw new IllegalStateException ( "The environment vars must be provided before calling getEnvironmentInteger." ) ; } String value = getEnvironmentString ( name , null ) ; if ( value == null ) { return defaultValue ; } else { return Integer . parseInt ( value ) ; } }
Retrieve integer value for the environment variable name
84
9
137,312
public static String getEnvironmentString ( String name , String defaultValue ) { if ( envVars == null ) { throw new IllegalStateException ( "The environment vars must be provided before calling getEnvironmentString." ) ; } return envVars . get ( ENV_PREFIX + name ) != null ? envVars . get ( ENV_PREFIX + name ) : defaultValue ; }
Retrieve string value for the environment variable name
86
9
137,313
@ Override public String encodeAsString ( ) throws IOException { final int size = messages . size ( ) ; if ( size == 0 ) return "" ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( size ) . append ( DELIMITER ) ; int count = 0 ; for ( Message message : messages ) { count ++ ; String str = message . encodeAsString ( ) ; sb . append ( message . getMessageType ( ) . getTypeChar ( ) ) . append ( str . length ( ) ) . append ( DELIMITER ) . append ( str ) ; } if ( count != size ) throw new ConcurrentModificationException ( ) ; return sb . toString ( ) ; }
Encodes the messages into a single string .
156
9
137,314
@ Override public ByteArray encodeAsByteArray ( ) throws IOException { final int size = messages . size ( ) ; if ( size == 0 ) return ByteArray . EMPTY_BYTE_ARRAY ; AoByteArrayOutputStream bout = new AoByteArrayOutputStream ( ) ; try { try ( DataOutputStream out = new DataOutputStream ( bout ) ) { out . writeInt ( size ) ; int count = 0 ; for ( Message message : messages ) { count ++ ; ByteArray byteArray = message . encodeAsByteArray ( ) ; final int capacity = byteArray . size ; out . writeByte ( message . getMessageType ( ) . getTypeByte ( ) ) ; out . writeInt ( capacity ) ; out . write ( byteArray . array , 0 , capacity ) ; } if ( count != size ) throw new ConcurrentModificationException ( ) ; } } finally { bout . close ( ) ; } return new ByteArray ( bout . getInternalByteArray ( ) , bout . size ( ) ) ; }
Encodes the messages into a single ByteArray . There is likely a more efficient implementation that reads - through but this is a simple implementation .
218
28
137,315
protected void setLength ( long length ) throws IOException { if ( length < 0 ) throw new IllegalArgumentException ( "Invalid length: " + length ) ; synchronized ( this ) { file . seek ( 8 ) ; file . writeLong ( length ) ; if ( length == 0 ) setFirstIndex ( 0 ) ; } }
Sets the number of bytes currently contained by the FIFO .
69
14
137,316
private boolean isExcludedPath ( String requestURI ) { if ( requestURI == null ) return false ; if ( _excludedPaths != null ) { for ( String excludedPath : _excludedPaths ) { if ( requestURI . startsWith ( excludedPath ) ) { return true ; } } } if ( _excludedPathPatterns != null ) { for ( Pattern pattern : _excludedPathPatterns ) { if ( pattern . matcher ( requestURI ) . matches ( ) ) { return true ; } } } return false ; }
Checks to see if the path is excluded
116
9
137,317
@ SuppressWarnings ( "unchecked" ) public static boolean isRunnable ( Class cl , Method method , List < FilterDefinition > filters ) { // Get the ROX annotations ProbeTest mAnnotation = method . getAnnotation ( ProbeTest . class ) ; ProbeTestClass cAnnotation = method . getDeclaringClass ( ) . getAnnotation ( ProbeTestClass . class ) ; String fingerprint = FingerprintGenerator . fingerprint ( cl , method ) ; if ( mAnnotation != null || cAnnotation != null ) { return isRunnable ( new FilterTargetData ( fingerprint , method , mAnnotation , cAnnotation ) , filters ) ; } else { return isRunnable ( new FilterTargetData ( fingerprint , method ) , filters ) ; } }
Define if a test is runnable or not based on a method and class
166
17
137,318
private String readUid ( File uidFile ) { String uid = null ; // Try to read the shared UID try ( BufferedReader br = new BufferedReader ( new FileReader ( uidFile ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { uid = line ; } } catch ( IOException ioe ) { } return uid ; }
Read a UID file
88
4
137,319
public static Version getInstance ( int major , int minor , int release , int build ) { return new Version ( major , minor , release , build ) ; }
Gets a version number instance from its component parts .
33
11
137,320
public static Version valueOf ( String version ) throws IllegalArgumentException { NullArgumentException . checkNotNull ( version , "version" ) ; int dot1Pos = version . indexOf ( ' ' ) ; if ( dot1Pos == - 1 ) throw new IllegalArgumentException ( version ) ; int dot2Pos = version . indexOf ( ' ' , dot1Pos + 1 ) ; if ( dot2Pos == - 1 ) throw new IllegalArgumentException ( version ) ; int dot3Pos = version . indexOf ( ' ' , dot2Pos + 1 ) ; if ( dot3Pos == - 1 ) throw new IllegalArgumentException ( version ) ; return getInstance ( Integer . parseInt ( version . substring ( 0 , dot1Pos ) ) , Integer . parseInt ( version . substring ( dot1Pos + 1 , dot2Pos ) ) , Integer . parseInt ( version . substring ( dot2Pos + 1 , dot3Pos ) ) , Integer . parseInt ( version . substring ( dot3Pos + 1 ) ) ) ; }
Parses a version number from its string representation .
228
11
137,321
public static Config getConfig ( ) { final Configuration systemConfig = new SystemConfiguration ( ) ; final String configName = systemConfig . getString ( CONFIG_PROPERTY_NAME ) ; final String configLocation = systemConfig . getString ( CONFIG_LOCATION_PROPERTY_NAME ) ; Preconditions . checkState ( configLocation != null , "Config location must be set!" ) ; final ConfigFactory configFactory = new ConfigFactory ( URI . create ( configLocation ) , configName ) ; return new Config ( configFactory . load ( ) ) ; }
Loads the configuration . The no - args method uses system properties to determine which configurations to load .
118
20
137,322
public static Config getConfig ( @ Nonnull final URI configLocation , @ Nullable final String configName ) { final ConfigFactory configFactory = new ConfigFactory ( configLocation , configName ) ; return new Config ( configFactory . load ( ) ) ; }
Load Configuration using the supplied URI as base . The loaded configuration can be overridden using system properties .
53
20
137,323
public static Config getOverriddenConfig ( @ Nonnull final Config config , @ Nullable final AbstractConfiguration ... overrideConfigurations ) { if ( overrideConfigurations == null || overrideConfigurations . length == 0 ) { return config ; } final CombinedConfiguration cc = new CombinedConfiguration ( new OverrideCombiner ( ) ) ; int index = 0 ; final AbstractConfiguration first = config . config . getNumberOfConfigurations ( ) > 0 ? AbstractConfiguration . class . cast ( config . config . getConfiguration ( index ) ) // cast always succeeds, internally this returns cd.getConfiguration() which is AbstractConfiguration : null ; // If the passed in configuration has a system config, add this as the very first one so // that system properties override still works. if ( first != null && first . getClass ( ) == SystemConfiguration . class ) { cc . addConfiguration ( first ) ; index ++ ; } else { // Otherwise, if any of the passed in configuration objects is a SystemConfiguration, // put that at the very beginning. for ( AbstractConfiguration c : overrideConfigurations ) { if ( c . getClass ( ) == SystemConfiguration . class ) { cc . addConfiguration ( c ) ; } } } for ( AbstractConfiguration c : overrideConfigurations ) { if ( c . getClass ( ) != SystemConfiguration . class ) { cc . addConfiguration ( c ) ; // Skip system configuration objects, they have been added earlier. } } // Finally, add the existing configuration elements at lowest priority. while ( index < config . config . getNumberOfConfigurations ( ) ) { final AbstractConfiguration c = AbstractConfiguration . class . cast ( config . config . getConfiguration ( index ++ ) ) ; if ( c . getClass ( ) != SystemConfiguration . class ) { cc . addConfiguration ( c ) ; } } return new Config ( cc ) ; }
Create a new configuration object from an existing object using overrides . If no overrides are passed in the same object is returned .
382
26
137,324
public int start ( ) throws Exception { if ( isStarted . compareAndSet ( false , true ) ) { try { for ( Reporter reporter : reporters ) { reporter . start ( ) ; } } catch ( Exception e ) { stop ( ) ; throw e ; } } return reporters . size ( ) ; }
Starts all reporters .
65
5
137,325
public void stop ( ) { if ( isStarted . compareAndSet ( true , false ) ) { for ( Reporter reporter : reporters ) { reporter . stop ( ) ; } } }
Stops all reporting .
39
5
137,326
public static < T > T xmlNodeToObject ( final Node node , final Class < T > valueType , final JAXBContext jaxbContext ) throws JAXBException { if ( node == null ) { return null ; } Validate . notNull ( valueType , "valueType must not be null" ) ; if ( jaxbContext == null ) { return valueType . cast ( getJaxbContext ( valueType ) . createUnmarshaller ( ) . unmarshal ( node ) ) ; } return valueType . cast ( jaxbContext . createUnmarshaller ( ) . unmarshal ( node ) ) ; }
Transforms a XML node into an object .
143
9
137,327
public static < T > T jsonMapToObject ( final Map < String , Object > map , final Class < T > valueType , final ObjectMapper objectMapper ) throws IOException { if ( map == null ) { return null ; } Validate . notNull ( valueType , "valueType must not be null" ) ; if ( objectMapper == null ) { return DEFAULT_OBJECT_MAPPER . readValue ( DEFAULT_OBJECT_MAPPER . writeValueAsBytes ( map ) , valueType ) ; } return objectMapper . readValue ( objectMapper . writeValueAsBytes ( map ) , valueType ) ; }
Transforms a JSON map into an object .
139
9
137,328
static < T > ArraySet < T > fromArray ( List < T > aArray , Boolean aAllowDuplicates ) { ArraySet < T > set = new ArraySet <> ( ) ; for ( int i = 0 , len = aArray . size ( ) ; i < len ; i ++ ) { set . add ( aArray . get ( i ) , aAllowDuplicates ) ; } return set ; }
Static method for creating ArraySet instances from an existing array .
90
12
137,329
Integer indexOf ( T t ) { if ( t == null ) { return null ; } Integer i = _set . get ( t ) ; if ( i == null ) { return - 1 ; } return i ; }
What is the index of the given string in the array?
46
12
137,330
T at ( Integer i ) { if ( i == null ) { return null ; } if ( i >= _array . size ( ) ) { return null ; } return _array . get ( i ) ; }
What is the element at the given index?
44
9
137,331
@ Override public int read ( ) throws IOException { // Read from the queue 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 ) ; long newFirstIndex = pos + 1 ; while ( newFirstIndex >= file . maxFifoLength ) newFirstIndex -= file . maxFifoLength ; file . setFirstIndex ( newFirstIndex ) ; file . setLength ( len - 1 ) ; file . notify ( ) ; return b ; } try { file . wait ( ) ; } catch ( InterruptedException err ) { InterruptedIOException ioErr = new InterruptedIOException ( ) ; ioErr . initCause ( err ) ; throw ioErr ; } } } }
Reads data from the file blocks until the data is available .
220
13
137,332
@ Override public int read ( byte [ ] b , int off , int len ) throws IOException { // Read from the queue 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 ; // When at the end of the file, read the remaining bytes if ( ( pos + readSize ) > file . maxFifoLength ) readSize = ( int ) ( file . maxFifoLength - pos ) ; // Read as many bytes as currently available int totalRead = file . file . read ( b , off , readSize ) ; if ( totalRead == - 1 ) throw new EOFException ( "Unexpected EOF" ) ; addStats ( totalRead ) ; long newFirstIndex = pos + totalRead ; while ( newFirstIndex >= file . maxFifoLength ) newFirstIndex -= file . maxFifoLength ; file . setFirstIndex ( newFirstIndex ) ; file . setLength ( fileLen - totalRead ) ; file . notify ( ) ; return totalRead ; } try { file . wait ( ) ; } catch ( InterruptedException err ) { InterruptedIOException ioErr = new InterruptedIOException ( ) ; ioErr . initCause ( err ) ; throw ioErr ; } } } }
Reads data from the file blocks until at least one byte is available .
316
15
137,333
@ Override public long skip ( long n ) throws IOException { // Skip in the queue synchronized ( file ) { while ( true ) { long fileLen = file . getLength ( ) ; if ( fileLen >= 1 ) { long pos = file . getFirstIndex ( ) ; long skipSize = fileLen > n ? n : fileLen ; // When at the end of the file, skip the remaining bytes if ( ( pos + skipSize ) > file . maxFifoLength ) skipSize = file . maxFifoLength - pos ; // Skip as many bytes as currently available long totalSkipped = skipSize ; long newFirstIndex = pos + skipSize ; while ( newFirstIndex >= file . maxFifoLength ) newFirstIndex -= file . maxFifoLength ; file . setFirstIndex ( newFirstIndex ) ; file . setLength ( fileLen - skipSize ) ; file . notify ( ) ; return totalSkipped ; } try { file . wait ( ) ; } catch ( InterruptedException err ) { InterruptedIOException ioErr = new InterruptedIOException ( ) ; ioErr . initCause ( err ) ; throw ioErr ; } } } }
Skips data in the queue blocks until at least one byte is skipped .
251
15
137,334
@ Override 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 .
49
14
137,335
protected void init ( final String name , final Properties props ) { init = new InitUtil ( "" , props , false ) ; this . name = name ; }
Initialize the properties .
34
5
137,336
public List < GeneratedPosition > allGeneratedPositionsFor ( int line , Integer column , String source ) { // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. ParsedMapping needle = new ParsedMapping ( null , null , line , column == null ? 0 : column , null , null ) ; if ( this . sourceRoot != null ) { source = Util . relative ( this . sourceRoot , source ) ; } if ( ! this . _sources . has ( source ) ) { return Collections . emptyList ( ) ; } needle . source = this . _sources . indexOf ( source ) ; List < GeneratedPosition > mappings = new ArrayList <> ( ) ; int index = _findMapping ( needle , this . _originalMappings ( ) , "originalLine" , "originalColumn" , ( mapping1 , mapping2 ) -> Util . compareByOriginalPositions ( mapping1 , mapping2 , true ) , BinarySearch . Bias . LEAST_UPPER_BOUND ) ; if ( index >= 0 ) { ParsedMapping mapping = this . _originalMappings ( ) . get ( index ) ; if ( column == null ) { int originalLine = mapping . originalLine ; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while ( mapping != null && mapping . originalLine == originalLine ) { mappings . add ( new GeneratedPosition ( mapping . generatedLine , mapping . generatedColumn , mapping . lastGeneratedColumn ) ) ; index ++ ; if ( index >= this . _originalMappings ( ) . size ( ) ) { mapping = null ; } else { mapping = this . _originalMappings ( ) . get ( index ) ; } } } else { int originalColumn = mapping . originalColumn ; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while ( mapping != null && mapping . originalLine == line && mapping . originalColumn == originalColumn ) { mappings . add ( new GeneratedPosition ( mapping . generatedLine , mapping . generatedColumn , mapping . lastGeneratedColumn ) ) ; index ++ ; if ( index >= this . _originalMappings ( ) . size ( ) ) { mapping = null ; } else { mapping = this . _originalMappings ( ) . get ( index ) ; } } } } return mappings ; }
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 either the column we are searching for or the next closest column that has any offsets .
623
74
137,337
< T > int _findMapping ( T aNeedle , List < T > aMappings , Object aLineName , Object aColumnName , BinarySearch . Comparator < T > aComparator , BinarySearch . Bias aBias ) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. // if (aNeedle[aLineName] <= 0) { // throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]); // } // if (aNeedle[aColumnName] < 0) { // throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]); // } 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 .
217
24
137,338
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 .
59
14
137,339
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 ( osw , probeTestRun , true ) ; }
Save a payload
102
3
137,340
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 .
54
17
137,341
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 already been added" ) ; sockets . put ( id , newSocket ) ; future = listenerManager . enqueueEvent ( new ConcurrentListenerManager . Event < SocketContextListener > ( ) { @ Override public Runnable createCall ( final SocketContextListener listener ) { return new Runnable ( ) { @ Override public void run ( ) { listener . onNewSocket ( AbstractSocketContext . this , newSocket ) ; } } ; } } ) ; } try { future . get ( ) ; } catch ( ExecutionException e ) { logger . log ( Level . SEVERE , null , e ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , null , e ) ; // Restore the interrupted status Thread . currentThread ( ) . interrupt ( ) ; } }
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 .
250
40
137,342
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 . length ( ) ; int lastLen = last . length ( ) ; int maxCommon = Math . min ( strLen , lastLen ) ; int common = 0 ; for ( ; common < maxCommon ; common ++ ) { if ( str . charAt ( common ) != last . charAt ( common ) ) break ; } if ( lastCommonLengths == null ) lastCommonLengths = new int [ 64 ] ; int commonDifference = common - lastCommonLengths [ slot ] ; // Write the header byte out . write ( ( commonDifference == 0 ? 0 : 0x80 ) | ( common == strLen ? 0 : 0x40 ) | slot ) ; // Write the common difference if ( commonDifference > 0 ) writeCompressedInt ( commonDifference - 1 ) ; else if ( commonDifference < 0 ) writeCompressedInt ( commonDifference ) ; // Write the suffix if ( common != strLen ) writeUTF ( str . substring ( common ) ) ; // Get ready for the next call lastStrings [ slot ] = str ; lastCommonLengths [ slot ] = common ; }
Writes a String to the stream while using prefix compression .
329
12
137,343
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 , position + blockLength ) ; writeUTF ( block ) ; } }
Writes a string of any length .
93
8
137,344
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='white-space:nowrap'><a class='aoLightLink' href='" ) . encodeXmlAttribute ( req == null ? "" : resp . encodeURL ( req . getContextPath ( ) + req . getURL ( page ) ) ) . print ( "'>" ) . encodeXhtml ( page . getShortTitle ( ) ) . print ( "</a>\n" + " </td>\n" + " <td style='width:12px; white-space:nowrap'>&#160;</td>\n" + " <td style='white-space:nowrap'>" ) . encodeXhtml ( page . getDescription ( ) ) . print ( "</td>\n" + " </tr>\n" ) ; } }
Prints a list of pages .
258
7
137,345
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 .
65
11
137,346
private boolean generatedPositionAfter ( Mapping mappingA , Mapping mappingB ) { // Optimized for most common case 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 || Util . compareByGeneratedPositionsInflated ( mappingA , mappingB ) <= 0 ; }
Determine whether mappingB is after mappingA with respect to generated position .
110
16
137,347
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 .
73
6
137,348
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 .
59
18
137,349
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 .
73
8
137,350
@ Override // @NotThreadSafe 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 .
53
30
137,351
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=\"" + prefix + "\"" ) ; return path . substring ( prefix . length ( ) ) ; }
Gets the relative path for the provided file from the provided iterator .
98
14
137,352
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 .
99
9
137,353
public void connect ( final String endpoint , final Callback < ? super HttpSocket > onConnect , final Callback < ? super Exception > onError ) { executors . getUnbounded ( ) . submit ( new Runnable ( ) { @ Override public void run ( ) { try { // Build request bytes AoByteArrayOutputStream bout = new AoByteArrayOutputStream ( ) ; try { try ( DataOutputStream out = new DataOutputStream ( bout ) ) { out . writeBytes ( "action=connect" ) ; } } finally { bout . close ( ) ; } long connectTime = System . currentTimeMillis ( ) ; URL endpointURL = new URL ( endpoint ) ; HttpURLConnection conn = ( HttpURLConnection ) endpointURL . openConnection ( ) ; conn . setAllowUserInteraction ( false ) ; conn . setConnectTimeout ( CONNECT_TIMEOUT ) ; conn . setDoOutput ( true ) ; conn . setFixedLengthStreamingMode ( bout . size ( ) ) ; conn . setInstanceFollowRedirects ( false ) ; conn . setReadTimeout ( CONNECT_TIMEOUT ) ; conn . setRequestMethod ( "POST" ) ; conn . setUseCaches ( false ) ; // Write request OutputStream out = conn . getOutputStream ( ) ; try { out . write ( bout . getInternalByteArray ( ) , 0 , bout . size ( ) ) ; out . flush ( ) ; } finally { out . close ( ) ; } // Get response int responseCode = conn . getResponseCode ( ) ; if ( responseCode != 200 ) throw new IOException ( "Unexpect response code: " + responseCode ) ; if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: got connection" ) ; DocumentBuilder builder = builderFactory . newDocumentBuilder ( ) ; Element document = builder . parse ( conn . getInputStream ( ) ) . getDocumentElement ( ) ; if ( ! "connection" . equals ( document . getNodeName ( ) ) ) throw new IOException ( "Unexpected root node name: " + document . getNodeName ( ) ) ; Identifier id = Identifier . valueOf ( document . getAttribute ( "id" ) ) ; if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: got id=" + id ) ; HttpSocket httpSocket = new HttpSocket ( HttpSocketClient . this , id , connectTime , endpointURL ) ; if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: adding socket" ) ; addSocket ( httpSocket ) ; if ( onConnect != null ) { if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: calling onConnect" ) ; onConnect . call ( httpSocket ) ; } } catch ( Exception exc ) { if ( onError != null ) { if ( DEBUG ) System . out . println ( "DEBUG: HttpSocketClient: connect: calling onError" ) ; onError . call ( exc ) ; } } } } ) ; }
Asynchronously connects .
665
5
137,354
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 ) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT ; } encoded += Base64 . encode ( digit ) ; } while ( vlq > 0 ) ; return encoded ; }
Returns the base 64 VLQ encoded value .
136
10
137,355
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 ++ ) ) ; if ( digit == - 1 ) { throw new Error ( "Invalid base64 digit: " + aStr . charAt ( aIndex - 1 ) ) ; } continuation = ( digit & VLQ_CONTINUATION_BIT ) != 0 ; digit &= VLQ_BASE_MASK ; result = result + ( digit << shift ) ; shift += VLQ_BASE_SHIFT ; } while ( continuation ) ; return new Base64VLQResult ( fromVLQSigned ( result ) , 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 .
210
29
137,356
public static StringBuilder generateIdPrefix ( String template , String prefix ) { NullArgumentException . checkNotNull ( template , "template" ) ; NullArgumentException . checkNotNull ( prefix , "prefix" ) ; assert isValidId ( prefix ) ; final int len = template . length ( ) ; // First character must be [A-Za-z] int pos = 0 ; while ( pos < len ) { char ch = template . charAt ( pos ) ; if ( ( ch >= ' ' && ch <= ' ' ) || ( ch >= ' ' && ch <= ' ' ) ) { break ; } pos ++ ; } StringBuilder idPrefix ; if ( pos == len ) { // No usable characters from label idPrefix = new StringBuilder ( prefix ) ; } else { // Get remaining usable characters from label idPrefix = new StringBuilder ( len - pos ) ; //idPrefix.append(template.charAt(pos)); //pos++; // Remaining must match [A-Za-z0-9:_.-] while ( pos < len ) { char ch = template . charAt ( pos ) ; pos ++ ; // Convert space to '-' if ( ch == ' ' ) { idPrefix . append ( ' ' ) ; } else if ( ( ch >= ' ' && ch <= ' ' ) || ( ch >= ' ' && ch <= ' ' ) || ( ch >= ' ' && ch <= ' ' ) || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { if ( ch >= ' ' && ch <= ' ' ) { // Works since we're only using ASCII range: ch = ( char ) ( ch + ( ' ' - ' ' ) ) ; // Would support Unicode, but id's don't have Unicode: // ch = Character.toLowerCase(ch); } idPrefix . append ( ch ) ; } } } assert isValidId ( idPrefix . toString ( ) ) ; return idPrefix ; }
Generates a valid ID from an arbitrary string .
429
10
137,357
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 .
63
12
137,358
public String getId ( ) { if ( id == null ) { synchronized ( lock ) { if ( id == null ) { if ( page != null ) { Map < String , Element > elementsById = page . getElementsById ( ) ; // Generate the ID now String template = getElementIdTemplate ( ) ; if ( template == null ) { throw new IllegalStateException ( "null from getElementIdTemplate" ) ; } StringBuilder possId = Element . generateIdPrefix ( template , getDefaultIdPrefix ( ) ) ; int possIdLen = possId . length ( ) ; // Find an unused identifier for ( int i = 1 ; i <= Integer . MAX_VALUE ; i ++ ) { if ( i == Integer . MAX_VALUE ) throw new IllegalStateException ( "ID not generated" ) ; if ( i > 1 ) possId . append ( ' ' ) . append ( i ) ; String newId = possId . toString ( ) ; if ( elementsById == null || ! elementsById . containsKey ( newId ) ) { setId ( newId , true ) ; break ; } // Reset for next element number to check possId . setLength ( possIdLen ) ; } } } } } return id ; }
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 .
264
40
137,359
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 = elementRef ; if ( er == null // Make sure object still valid || ! er . getPageRef ( ) . equals ( pageRef ) || ! er . getId ( ) . equals ( i ) ) { er = new ElementRef ( pageRef , i ) ; elementRef = er ; } return er ; }
Gets an ElementRef for this element . Must have a page set . If id has not yet been set one will be generated .
151
27
137,360
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 .
65
9
137,361
@ Override 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 .
51
8
137,362
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 ( ' ' ) ; } } catch ( IOException e ) { e . printStackTrace ( System . err ) ; } } }
Writes one line to the given file synchronizes on the file object .
114
15
137,363
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 .
55
8
137,364
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
68
13
137,365
@ Override 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
60
7
137,366
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 != null ) ? rmiRegistryPort : NetUtils . findUnusedPort ( ) , ( rmiServerPort != null ) ? rmiServerPort : NetUtils . findUnusedPort ( ) , useRandomIds ) ; }
Creates a default configuration object .
135
7
137,367
public static Writer getInstance ( Writer out ) { // Already in Unix format, no conversion necessary if ( UNIX_EOL . equals ( EOL ) ) return out ; // Use FindReplaceWriter 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 .
62
21
137,368
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 .
38
14
137,369
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 .
45
13
137,370
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 ) ; } finally { in . close ( ) ; } return toolkit . createImage ( imageData ) ; }
Loads an image from a resource using the provided toolkit .
109
13
137,371
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 .
60
10
137,372
public void printUnauthorizedPage ( WebPage page , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { getParent ( ) . printUnauthorizedPage ( page , req , resp ) ; }
Prints the unauthorized page message .
58
7
137,373
protected final long getClassLastModified ( ) throws IOException , SQLException { String dir = getServletContext ( ) . getRealPath ( "/WEB-INF/classes" ) ; if ( dir != null && dir . length ( ) > 0 ) { // Try to get from the class file long lastMod = new File ( dir , getClass ( ) . getName ( ) . replace ( ' ' , File . separatorChar ) + ".class" ) . lastModified ( ) ; if ( lastMod != 0 && lastMod != - 1 ) return lastMod ; } return getUptime ( ) ; }
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 .
136
29
137,374
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 [ c ] . getLastModified ( req ) ; if ( time == - 1 ) return - 1 ; if ( time > mostRecent ) mostRecent = time ; } return mostRecent ; }
Gets the most recent last modified time of this page and its immediate children .
133
16
137,375
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 ( time2 > time ) time = time2 ; } return time ; }
Recursively gets the most recent modification time .
110
10
137,376
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 ] ) ) ; if ( time2 > time ) time = time2 ; } } } return time ; }
Recursively gets the most recent modification time of a file or directory .
117
15
137,377
public void doGet ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp ) throws ServletException , IOException , SQLException { }
By default GET provides no content .
35
7
137,378
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 .
51
18
137,379
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 .
57
10
137,380
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 page index in parent." ) ; }
Gets the index of this page in the parents list of children pages .
99
15
137,381
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 .
43
17
137,382
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 .
49
19
137,383
public static String join ( Iterable < ? > objects , String delimiter ) throws ConcurrentModificationException { int delimiterLength = delimiter . length ( ) ; // Find total length int totalLength = 0 ; boolean didOne = false ; for ( Object obj : objects ) { if ( didOne ) totalLength += delimiterLength ; else didOne = true ; totalLength += String . valueOf ( obj ) . length ( ) ; } // Build result StringBuilder sb = new StringBuilder ( totalLength ) ; didOne = false ; for ( Object obj : objects ) { if ( didOne ) sb . append ( delimiter ) ; else didOne = true ; sb . append ( obj ) ; } if ( totalLength != sb . length ( ) ) throw new ConcurrentModificationException ( ) ; return sb . toString ( ) ; }
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 .
183
38
137,384
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 .
81
13
137,385
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 .
68
15
137,386
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 .
94
17
137,387
public static String replace ( final String string , final String find , final String replacement ) { int pos = string . indexOf ( find ) ; //System.out.println(string+": "+find+" at "+pos); if ( pos == - 1 ) return string ; StringBuilder SB = new StringBuilder ( ) ; int lastpos = 0 ; final int findLen = find . length ( ) ; do { SB . append ( string , lastpos , pos ) . append ( replacement ) ; lastpos = pos + findLen ; pos = string . indexOf ( find , lastpos ) ; } while ( pos != - 1 ) ; int len = string . length ( ) ; if ( lastpos < len ) SB . append ( string , lastpos , len ) ; return SB . toString ( ) ; }
Replaces all occurrences of a String with a String Please consider the variant with the Appendable for higher performance .
170
23
137,388
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 .
87
11
137,389
public static List < String > splitLines ( String S ) { List < String > V = new ArrayList <> ( ) ; int start = 0 ; int pos ; while ( ( pos = S . indexOf ( ' ' , start ) ) != - 1 ) { String line ; if ( pos > start && S . charAt ( pos - 1 ) == ' ' ) line = S . substring ( start , pos - 1 ) ; else line = S . substring ( start , pos ) ; V . add ( line ) ; start = pos + 1 ; } int slen = S . length ( ) ; if ( start < slen ) { // Ignore any trailing '\r' if ( S . charAt ( slen - 1 ) == ' ' ) slen -- ; String line = S . substring ( start , slen ) ; V . add ( line ) ; } return V ; }
Splits a String into lines on any \ n characters . Also removes any ending \ r characters if present
192
21
137,390
public static List < String > splitStringCommaSpace ( String line ) { List < String > words = new ArrayList <> ( ) ; int len = line . length ( ) ; int pos = 0 ; while ( pos < len ) { // Skip past blank space char ch ; while ( pos < len && ( ( ch = line . charAt ( pos ) ) <= ' ' || ch == ' ' ) ) pos ++ ; int start = pos ; // Skip to the next blank space while ( pos < len && ( ch = line . charAt ( pos ) ) > ' ' && ch != ' ' ) pos ++ ; if ( pos > start ) words . add ( line . substring ( start , pos ) ) ; } return words ; }
Splits a string into multiple words on either whitespace or commas
157
14
137,391
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 ) ) ; out . append ( getHexChar ( value >>> 8 ) ) ; out . append ( getHexChar ( value >>> 4 ) ) ; out . append ( getHexChar ( value ) ) ; }
Converts an int to a full 8 - character hex code .
139
13
137,392
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 .
60
29
137,393
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 ( ) ; // This line makes it different than regular String indexOf method. if ( toIndex < sourceCount ) sourceCount = toIndex ; int targetCount = target . length ( ) ; if ( fromIndex >= sourceCount ) { return ( targetCount == 0 ? sourceCount : - 1 ) ; } if ( fromIndex < 0 ) { fromIndex = 0 ; } if ( targetCount == 0 ) { return fromIndex ; } char first = target . charAt ( 0 ) ; int max = sourceCount - targetCount ; for ( int i = fromIndex ; i <= max ; i ++ ) { /* Look for first character. */ if ( source . charAt ( i ) != first ) { while ( ++ i <= max && source . charAt ( i ) != first ) { // Intentionally empty } } /* Found first character, now look at the rest of v2 */ if ( i <= max ) { int j = i + 1 ; int end = j + targetCount - 1 ; for ( int k = 1 ; j < end && source . charAt ( j ) == target . charAt ( k ) ; j ++ , k ++ ) { // Intentionally empty } if ( j == end ) { /* Found whole string. */ return i ; } } } return - 1 ; }
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 .
340
36
137,394
public static String nullIfEmpty ( String value ) { return value == null || value . isEmpty ( ) ? null : value ; }
Returns null if the string is null or empty .
28
10
137,395
@ Override 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 ( set != null && ! set . isEmpty ( ) ) return false ; } } return true ; }
Checks if this set is empty . This can be an expensive method since it can potentially call all methods .
109
22
137,396
@ Override @ 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 .
80
5
137,397
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 .
56
25
137,398
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 .
68
10
137,399
private static File getFileUploadDirectory ( ServletContext servletContext ) throws FileNotFoundException { File uploadDir = new File ( ( File ) servletContext . getAttribute ( ServletContext . TEMPDIR ) , "uploads" ) ; if ( ! uploadDir . exists ( ) && ! uploadDir . mkdirs ( ) // Check exists again, another thread may have created it and interfered with mkdirs && ! uploadDir . exists ( ) ) { throw new FileNotFoundException ( uploadDir . getPath ( ) ) ; } return uploadDir ; }
Gets the upload directory .
121
6