idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
40,100
static public String removeAllCharsExceptDigits ( String str0 ) { if ( str0 == null ) { return null ; } if ( str0 . length ( ) == 0 ) { return str0 ; } StringBuilder buf = new StringBuilder ( str0 . length ( ) ) ; int length = str0 . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { char c = str0 . charAt ( i ) ; if...
Removes all other characters from a string except digits . A good way of cleaing up something like a phone number .
40,101
protected static Country parse ( String line ) throws IOException { try { int pos = line . indexOf ( ' ' ) ; if ( pos < 0 ) throw new IOException ( "Invalid format, could not parse 2 char code" ) ; String code2 = line . substring ( 0 , pos ) ; int pos2 = line . indexOf ( ' ' , pos + 1 ) ; if ( pos2 < 0 ) throw new IOEx...
AF AFG 004 Afghanistan
40,102
public static byte [ ] encodeBcd ( String data , int num_bytes ) { byte buf [ ] = new byte [ num_bytes ] ; if ( ( data . length ( ) % 2 ) != 0 ) { data += "F" ; } int index = 0 ; for ( int i = 0 ; i < data . length ( ) ; i += 2 ) { StringBuilder x = new StringBuilder ( data . substring ( i , i + 2 ) ) ; x . reverse ( )...
BCD encodes a String into a byte array .
40,103
public boolean getAndSet ( boolean newValue ) { boolean oldValue = value . getAndSet ( newValue ) ; if ( oldValue != newValue ) valueTime = System . currentTimeMillis ( ) ; return oldValue ; }
Sets to the given value and returns the previous value . If the previous value is different than the new value the internal valueTime will be updated .
40,104
public static DataSource create ( DataSourceConfiguration configuration ) throws SQLMissingDependencyException , SQLConfigurationException { configuration . validate ( ) ; DataSourceConfiguration config = ( DataSourceConfiguration ) configuration . clone ( ) ; try { Driver driver = ( Driver ) Class . forName ( config ....
Creates a new DataSource from the DataSourceConfiguration .
40,105
static public < E > E convert ( String s , Class < E > type ) throws ConversionException { if ( type . isEnum ( ) ) { Object obj = ClassUtil . findEnumConstant ( type , s ) ; if ( obj == null ) { throw new ConversionException ( "Invalid constant [" + s + "] used, supported values [" + toListString ( type . getEnumConst...
Converts the string value into an Object of the Class type . Will either delegate conversion to a PropertyConverter or will handle creating enums directly .
40,106
public static boolean isValidFileExtension ( String extension ) { for ( int i = 0 ; i < extension . length ( ) ; i ++ ) { char c = extension . charAt ( i ) ; if ( ! ( Character . isDigit ( c ) || Character . isLetter ( c ) || c == '_' ) ) { return false ; } } return true ; }
Checks if the extension is valid . This method only permits letters digits and an underscore character .
40,107
public static String parseFileExtension ( String filename ) { if ( filename == null ) { return null ; } int pos = filename . lastIndexOf ( '.' ) ; if ( pos < 0 || ( pos + 1 ) >= filename . length ( ) ) { return null ; } return filename . substring ( pos + 1 ) ; }
Parse the filename and return the file extension . For example if the file is app . 2006 - 10 - 10 . log then this method will return log . Will only return the last file extension . For example if the filename ends with . log . gz then this method will return gz
40,108
public static void copy ( File sourceFile , File targetFile ) throws FileAlreadyExistsException , IOException { copy ( sourceFile , targetFile , false ) ; }
Copy the source file to the target file .
40,109
public static boolean copy ( File sourceFile , File targetFile , boolean overwrite ) throws FileAlreadyExistsException , IOException { boolean overwriteOccurred = false ; if ( targetFile . exists ( ) ) { if ( ! overwrite ) { throw new FileAlreadyExistsException ( "Target file " + targetFile + " already exists" ) ; } el...
Copy the source file to the target file while optionally permitting an overwrite to occur in case the target file already exists .
40,110
public boolean accept ( File file ) { String fileExt = FileUtil . parseFileExtension ( file . getName ( ) ) ; if ( fileExt == null ) { return false ; } for ( String extension : extensions ) { if ( caseSensitive ) { if ( fileExt . equals ( extension ) ) { return true ; } } else { if ( fileExt . equalsIgnoreCase ( extens...
Accepts a File by its file extension .
40,111
public static String toMetaFieldInfoString ( Object obj ) { StringBuffer buf = new StringBuffer ( 100 ) ; MetaFieldInfo [ ] fields = toMetaFieldInfoArray ( obj , null , true ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { MetaFieldInfo field = fields [ i ] ; buf . append ( field . name ) ; buf . append ( "=" ) ; i...
Creates a string for an object based on the MetaField annotations .
40,112
public static MetaFieldInfo [ ] toMetaFieldInfoArray ( Class type , Object obj , String stringForNullValues , boolean ignoreAnnotatedName , boolean recursive ) { return internalToMetaFieldInfoArray ( type , obj , null , null , stringForNullValues , ignoreAnnotatedName , recursive ) ; }
Returns a new MetaFieldInfo array of all Fields annotated with MetaField in the object type . The object must be an instance of the type otherwise this method may throw a runtime exception . Optionally this method can recursively search the object to provide a deep view of the entire class .
40,113
public List < DateTimePeriod > toMonths ( ) { ArrayList < DateTimePeriod > list = new ArrayList < DateTimePeriod > ( ) ; DateTime currentStart = getStart ( ) ; DateTime nextStart = currentStart . plusMonths ( 1 ) ; while ( nextStart . isBefore ( getEnd ( ) ) || nextStart . isEqual ( getEnd ( ) ) ) { list . add ( new Da...
Converts this period to a list of month periods . Partial months will not be included . For example a period of 2009 will return a list of 12 months - one for each month in 2009 . On the other hand a period of January 20 2009 would return an empty list since partial months are not included .
40,114
public List < DateTimePeriod > toYears ( ) { ArrayList < DateTimePeriod > list = new ArrayList < DateTimePeriod > ( ) ; DateTime currentStart = getStart ( ) ; DateTime nextStart = currentStart . plusYears ( 1 ) ; while ( nextStart . isBefore ( getEnd ( ) ) || nextStart . isEqual ( getEnd ( ) ) ) { list . add ( new Date...
Converts this period to a list of year periods . Partial years will not be included . For example a period of 2009 - 2010 will return a list of 2 years - one for 2009 and one for 2010 . On the other hand a period of January 2009 would return an empty list since partial years are not included .
40,115
static public DateTimePeriod create ( DateTimeDuration duration , DateTime start ) { if ( duration == DateTimeDuration . YEAR ) { return createYear ( start ) ; } else if ( duration == DateTimeDuration . MONTH ) { return createMonth ( start ) ; } else if ( duration == DateTimeDuration . DAY ) { return createDay ( start ...
Creates a new period for the specified duration starting from the provided DateTime .
40,116
static public List < DateTimePeriod > createLastYearMonths ( DateTimeZone zone ) { ArrayList < DateTimePeriod > periods = new ArrayList < DateTimePeriod > ( ) ; DateTime now = new DateTime ( zone ) ; for ( int i = 0 ; i < 12 ; i ++ ) { DateTimePeriod period = createMonth ( now . getYear ( ) , now . getMonthOfYear ( ) ,...
Create a list of DateTimePeriods that represent the last year of YearMonth periods . For example if its currently January 2009 this would return periods representing January 2009 December 2008 ... February 2008
40,117
public static Properties createCommonSystemProperties ( ) throws EnvironmentException { Properties systemProperties = new Properties ( ) ; String hostFQDN = getHostFQDN ( ) ; if ( ! StringUtil . isEmpty ( hostFQDN ) ) { systemProperties . put ( HOST_FQDN , hostFQDN ) ; String [ ] hostInfo = splitHostFQDN ( hostFQDN ) ;...
Creates a Properties object containing common system properties that are determined using various Java routines . For example determining the hostname that the application is running on .
40,118
static public Thread [ ] getAllThreads ( ) { final ThreadGroup root = getRootThreadGroup ( ) ; final ThreadMXBean thbean = ManagementFactory . getThreadMXBean ( ) ; int nAlloc = thbean . getThreadCount ( ) ; int n = 0 ; Thread [ ] threads ; do { nAlloc *= 2 ; threads = new Thread [ nAlloc ] ; n = root . enumerate ( thr...
Gets all threads in the JVM . This is really a snapshot of all threads at the time this method is called .
40,119
public void validate ( ) throws SQLConfigurationException { if ( this . url == null ) { throw new SQLConfigurationException ( "url is a required property" ) ; } if ( this . username == null ) { throw new SQLConfigurationException ( "username is a required property" ) ; } if ( this . name == null ) { throw new SQLConfig...
Validates this configuration and checks that all required parameters are set . Throws an exception if a property is missing .
40,120
public static E164CountryCode lookup ( String address ) { int len = ( address . length ( ) > maxPrefixLength ? maxPrefixLength : address . length ( ) ) ; for ( int i = len ; i > 0 ; i -- ) { String prefix = address . substring ( 0 , i ) ; E164CountryCode entry = byPrefix . get ( prefix ) ; if ( entry != null ) { return...
Looks up an E164CountryCode object by analyzing the address and returning the best match . For example 12125551212 will return an entry for the US .
40,121
public void addListener ( FileChangedListener fileListener ) { for ( Iterator < WeakReference < FileChangedListener > > i = listeners_ . iterator ( ) ; i . hasNext ( ) ; ) { WeakReference < FileChangedListener > reference = i . next ( ) ; FileChangedListener listener = reference . get ( ) ; if ( listener == fileListene...
Add listener to this file monitor .
40,122
public void removeListener ( FileChangedListener fileListener ) { for ( Iterator < WeakReference < FileChangedListener > > i = listeners_ . iterator ( ) ; i . hasNext ( ) ; ) { WeakReference < FileChangedListener > reference = i . next ( ) ; FileChangedListener listener = reference . get ( ) ; if ( listener == fileList...
Remove listener from this file monitor .
40,123
private void dumpNode ( Node node , int level , int idx , java . io . PrintStream out ) { if ( node == null ) { return ; } printSpaces ( level , out ) ; if ( idx == - 2 ) { out . print ( "ROOT -> " ) ; } else { out . print ( idx + " -> " ) ; } out . print ( "S: " ) ; if ( node . getSpecificValue ( ) != null ) { out . p...
Recursively dumps a node at a certain index .
40,124
private void printSpaces ( int count , java . io . PrintStream out ) { for ( int i = 0 ; i < count ; i ++ ) { out . print ( " " ) ; } }
Prints out certain number of spaces .
40,125
protected File [ ] findSshDirs ( ) { ArrayList < File > dirs = new ArrayList < File > ( ) ; File sshHomeDir = new File ( System . getProperty ( "user.home" ) , ".ssh" ) ; if ( sshHomeDir . exists ( ) && sshHomeDir . isDirectory ( ) ) { dirs . add ( sshHomeDir ) ; } return dirs . toArray ( new File [ 0 ] ) ; }
Best attempt to find a default . ssh directory on this particular server . While more directories may be attempted for now the user s home directory will be scanned for a . ssh directory .
40,126
protected KeyStore loadKeyStore ( ) throws Exception { return getKeyStore ( keyStoreInputStream , sslConfig . getKeyStorePath ( ) , sslConfig . getKeyStoreType ( ) , sslConfig . getKeyStoreProvider ( ) , sslConfig . getKeyStorePassword ( ) ) ; }
Override this method to provide alternate way to load a keystore .
40,127
protected KeyStore loadTrustStore ( ) throws Exception { return getKeyStore ( trustStoreInputStream , sslConfig . getTrustStorePath ( ) , sslConfig . getTrustStoreType ( ) , sslConfig . getTrustStoreProvider ( ) , sslConfig . getTrustStorePassword ( ) ) ; }
Override this method to provide alternate way to load a truststore .
40,128
protected KeyStore getKeyStore ( InputStream storeStream , String storePath , String storeType , String storeProvider , String storePassword ) throws Exception { KeyStore keystore = null ; if ( storeStream != null || storePath != null ) { InputStream inStream = storeStream ; try { if ( inStream == null ) { inStream = n...
Loads keystore using an input stream or a file path in the same order of precedence .
40,129
public void checkKeyStore ( ) { if ( sslContext != null ) return ; if ( keyStoreInputStream == null && sslConfig . getKeyStorePath ( ) == null ) { throw new IllegalStateException ( "SSL doesn't have a valid keystore" ) ; } if ( trustStoreInputStream == null && sslConfig . getTrustStorePath ( ) == null ) { trustStoreInp...
Check KeyStore Configuration . Ensures that if keystore has been configured but there s no truststore that keystore is used as truststore .
40,130
private static void streamCopy ( InputStream is , OutputStream os , byte [ ] buf , boolean close ) throws IOException { int len ; if ( buf == null ) { buf = new byte [ 4096 ] ; } while ( ( len = is . read ( buf ) ) > 0 ) { os . write ( buf , 0 , len ) ; } os . flush ( ) ; if ( close ) { is . close ( ) ; } }
Copy the contents of is to os .
40,131
private static boolean contains ( Object [ ] arr , Object obj ) { for ( Object o : arr ) { if ( o . equals ( obj ) ) return true ; } return false ; }
Does an object array include an object .
40,132
public static String toStackTraceString ( String firstLine , StackTraceElement [ ] stack ) { final StringBuilder result = new StringBuilder ( firstLine ) ; final String NEW_LINE = System . getProperty ( "line.separator" ) ; result . append ( NEW_LINE ) ; for ( StackTraceElement element : stack ) { result . append ( " ...
Defines a custom format for the stack trace as String .
40,133
static public int encodeToByteArray ( CharSequence charSeq , char [ ] charBuffer , int charOffset , int charLength , byte [ ] byteBuffer , int byteOffset ) { int c = 0 ; int bytePos = byteOffset ; int charPos = charOffset ; int charAbsLength = charPos + charLength ; if ( charBuffer == null ) { if ( charSeq == null ) { ...
Encode the string to an array of UTF - 8 bytes . The buffer must be pre - allocated and have enough space to hold the encoded string .
40,134
public static RemoteFileSystem create ( String url ) throws MalformedURLException , FileSystemException { URL r = URLParser . parse ( url ) ; return create ( r ) ; }
Creates a new RemoteFileSystem by parsing the URL and creating the correct underlying provider to support the protocol .
40,135
static public DataCoding createCharacterEncodingGroup ( byte characterEncoding ) throws IllegalArgumentException { if ( ( characterEncoding & 0xF0 ) != 0 ) { throw new IllegalArgumentException ( "Invalid characterEncoding [0x" + HexUtil . toHexString ( characterEncoding ) + "] value used: only 16 possible for char enco...
Creates a Character Encoding group data coding scheme where 16 different languages are supported . This method validates the range and sets the message class to 0 and compression flags to false .
40,136
static public DataCoding parse ( byte dcs ) { try { if ( ( dcs & ( byte ) 0xF0 ) == 0x00 ) { return createCharacterEncodingGroup ( dcs ) ; } else if ( ( dcs & ( byte ) 0xF0 ) == ( byte ) 0xF0 ) { byte characterEncoding = CHAR_ENC_DEFAULT ; if ( ( dcs & ( byte ) 0x04 ) == ( byte ) 0x04 ) { characterEncoding = CHAR_ENC_8...
Parse the data coding scheme value into something usable and makes various values easy to use . If a reserved value is used returns a data coding representing the same byte value but all properties to their defaults .
40,137
private void circularByteBufferInitializer ( int bufferCapacity , int bufferSize , int readPosition , int writePosition ) { if ( bufferCapacity < 2 ) { throw new IllegalArgumentException ( "Buffer capacity must be greater than 2 !" ) ; } if ( ( bufferSize < 0 ) || ( bufferSize > bufferCapacity ) ) { throw new IllegalAr...
Intializes the new CircularByteBuffer with all parameters that characterize a CircularByteBuffer .
40,138
private int modularExponentation ( int a , int b , int n ) throws IllegalArgumentException { int result = 1 ; int counter ; int maxBinarySize = 32 ; boolean [ ] b2Binary = new boolean [ maxBinarySize ] ; for ( counter = 0 ; b > 0 ; counter ++ ) { if ( counter >= maxBinarySize ) { throw new IllegalArgumentException ( "E...
Gets the modular exponentiation i . e . result of a^b mod n . Use to calculate hashcode .
40,139
public void add ( byte b ) throws BufferIsFullException { if ( isFull ( ) ) { throw new BufferIsFullException ( "Buffer is full and has reached maximum capacity (" + capacity ( ) + ")" ) ; } this . buffer [ this . currentWritePosition ] = b ; this . currentWritePosition = ( this . currentWritePosition + 1 ) % this . bu...
Adds one byte to the buffer and throws an exception if the buffer is full .
40,140
static protected void checkOffsetLength ( int bytesLength , int offset , int length ) throws IllegalArgumentException { if ( offset < 0 ) { throw new IllegalArgumentException ( "The byte[] offset parameter cannot be negative" ) ; } if ( length < 0 ) { throw new IllegalArgumentException ( "The byte[] length parameter ca...
Helper method for validating if an offset and length are valid for a given byte array . Checks if the offset or length is negative or if the offset + length would cause a read past the end of the byte array .
40,141
public void add ( byte [ ] bytes , int offset , int length ) throws IllegalArgumentException , BufferSizeException { checkOffsetLength ( bytes . length , offset , length ) ; if ( length > free ( ) ) { throw new BufferSizeException ( "Buffer does not have enough free space (" + free ( ) + " bytes) to add " + length + " ...
Adds a byte array to this buffer starting from the offset up to the length requested . If the free space remaining in the buffer is not large enough this method will throw a BufferSizeException .
40,142
public byte get ( int index ) throws IllegalArgumentException , BufferSizeException { if ( ( index < 0 ) || ( index >= capacity ( ) ) ) { throw new IllegalArgumentException ( "The buffer index must be a value between 0 and " + capacity ( ) + "!" ) ; } if ( index >= size ( ) ) { throw new BufferSizeException ( "Index " ...
Gets the byte at the given index relative to the beginning the circular buffer . The index must be a value between 0 and the buffer capacity .
40,143
public void toArray ( int offset , int length , byte [ ] targetBuffer , int targetOffset ) { ByteBuffer . checkOffsetLength ( size ( ) , offset , length ) ; ByteBuffer . checkOffsetLength ( targetBuffer . length , targetOffset , length ) ; if ( targetBuffer . length < length ) { throw new IllegalArgumentException ( "Ta...
Will copy data from this ByteBuffer s buffer into the targetBuffer . This method requires the targetBuffer to already be allocated with enough capacity to hold this ByteBuffer s data .
40,144
public boolean startsWith ( byte [ ] prefix ) { if ( ( prefix . length == 0 ) || ( prefix . length > size ( ) ) ) { return false ; } boolean match = true ; int i = 0 ; int j = this . currentReadPosition ; while ( match && ( i < prefix . length ) ) { if ( this . buffer [ j ] != prefix [ i ] ) { match = false ; } i ++ ; ...
Tests if the buffer starts with the byte array prefix . The byte array prefix must have a size > = this buffer s size .
40,145
public boolean endsWith ( byte [ ] prefix ) { if ( ( prefix . length == 0 ) || ( prefix . length > size ( ) ) ) { return false ; } boolean match = true ; int i = prefix . length - 1 ; int j = ( this . currentWritePosition - 1 + this . buffer . length ) % this . buffer . length ; while ( match && ( i >= 0 ) ) { if ( thi...
Tests if the buffer ends with the bytes array prefix . The byte array prefix must have a size > = this buffer s size .
40,146
public int indexOf ( byte [ ] bytes , int offset ) { if ( bytes . length == 0 || size ( ) == 0 ) { return - 1 ; } if ( offset < 0 || offset >= size ( ) ) { throw new IllegalArgumentException ( "Offset must be a value between 0 and " + size ( ) + " (current buffer size)" ) ; } int length = size ( ) - bytes . length ; fo...
Returns the index within this buffer of the first occurrence of the specified bytes after the offset . The bytes to search for must have a size lower than or equal to the current buffer size . This method will return - 1 if the bytes are not contained within this byte buffer .
40,147
public String toHexString ( int offset , int length ) { checkOffsetLength ( size ( ) , offset , length ) ; if ( length == 0 || size ( ) == 0 ) { return "" ; } StringBuilder s = new StringBuilder ( length * 2 ) ; int end = offset + length ; for ( int i = offset ; i < end ; i ++ ) { HexUtil . appendHexString ( s , getUnc...
Return a hexidecimal String representation of the current buffer with each byte displayed in a 2 character hexidecimal format . Useful for debugging . Convert a ByteBuffer to a String with a hexidecimal format .
40,148
public Response process ( InputStream is ) throws IOException , SAXException , ParserConfigurationException { SxmpParser parser = new SxmpParser ( version ) ; Operation operation = null ; try { operation = parser . parse ( is ) ; } catch ( SxmpParsingException e ) { if ( e . getOperation ( ) != null && e . getOperation...
Processes an InputStream that contains a request . Does its best to only produce a Response that can be written to an OutputStream . Any exception this method throws should be treated as fatal and no attempt should be made to print out valid XML as a response .
40,149
static public Properties loadProperties ( Properties base , File file ) throws IOException { FileReader reader = new FileReader ( file ) ; Properties props = new Properties ( ) ; props . load ( reader ) ; if ( base != null ) props . putAll ( base ) ; reader . close ( ) ; return props ; }
Loads the given file into a Properties object .
40,150
static public void shutdownQuietly ( HttpClient http ) { if ( http != null ) { try { http . getConnectionManager ( ) . shutdown ( ) ; } catch ( Exception ignore ) { } } }
Quitely shuts down an HttpClient instance by shutting down its connection manager and ignoring any errors that occur .
40,151
static public int replaceSafeUnicodeChars ( StringBuilder buffer ) { int replaced = 0 ; for ( int i = 0 ; i < buffer . length ( ) ; i ++ ) { char c = buffer . charAt ( i ) ; for ( int j = 0 ; j < CHAR_TABLE . length ; j ++ ) { if ( c == CHAR_TABLE [ j ] [ 0 ] ) { replaced ++ ; buffer . setCharAt ( i , CHAR_TABLE [ j ] ...
Replace unicode characters with their ascii equivalents limiting replacement to safe characters such as smart quotes to dumb quotes . Safe is subjective but generally the agreement is that these character replacements should not change the meaning of the string in any meaninful way .
40,152
public static String encode ( byte [ ] rawData ) { StringBuilder buffer = new StringBuilder ( 4 * rawData . length / 3 ) ; int pos = 0 ; int iterations = rawData . length / 3 ; for ( int i = 0 ; i < iterations ; i ++ ) { int value = ( ( rawData [ pos ++ ] & 0xFF ) << 16 ) | ( ( rawData [ pos ++ ] & 0xFF ) << 8 ) | ( ra...
Encodes the provided raw data using base64 .
40,153
public boolean accept ( File file ) { if ( caseSensitive ) { return file . getName ( ) . startsWith ( string0 ) ; } else { return file . getName ( ) . toLowerCase ( ) . startsWith ( string0 . toLowerCase ( ) ) ; } }
Accepts a File if its filename startsWith a specific string .
40,154
public void decode ( byte [ ] bytes , StringBuilder buffer ) { if ( bytes == null ) { return ; } char [ ] table = CHAR_TABLE ; for ( int i = 0 ; i < bytes . length ; i ++ ) { int code = ( int ) bytes [ i ] & 0x000000ff ; if ( code == EXTENDED_ESCAPE ) { table = EXT_CHAR_TABLE ; } else { buffer . append ( ( code >= tabl...
Decode an SMS default alphabet - encoded octet string into a Java String .
40,155
public WindowFuture < K , R , P > get ( K key ) { return this . futures . get ( key ) ; }
Gets the a future by its key .
40,156
public void addListener ( WindowListener < K , R , P > listener ) { this . listeners . addIfAbsent ( new UnwrappedWeakReference < WindowListener < K , R , P > > ( listener ) ) ; }
Adds a new WindowListener if and only if it isn t already present .
40,157
public void removeListener ( WindowListener < K , R , P > listener ) { this . listeners . remove ( new UnwrappedWeakReference < WindowListener < K , R , P > > ( listener ) ) ; }
Removes a WindowListener if it is present .
40,158
public synchronized boolean startMonitor ( ) { if ( this . executor != null ) { if ( this . monitorHandle == null ) { this . monitorHandle = this . executor . scheduleWithFixedDelay ( this . monitor , this . monitorInterval , this . monitorInterval , TimeUnit . MILLISECONDS ) ; } return true ; } return false ; }
Starts the monitor if this Window has an executor . Safe to call multiple times .
40,159
public Map < K , WindowFuture < K , R , P > > createSortedSnapshot ( ) { Map < K , WindowFuture < K , R , P > > sortedRequests = new TreeMap < K , WindowFuture < K , R , P > > ( ) ; sortedRequests . putAll ( this . futures ) ; return sortedRequests ; }
Creates an ordered snapshot of the requests in this window . The entries will be sorted by the natural ascending order of the key . A new map is allocated when calling this method so be careful about calling it once .
40,160
public WindowFuture offer ( K key , R request , long offerTimeoutMillis , long expireTimeoutMillis , boolean callerWaitingHint ) throws DuplicateKeyException , OfferTimeoutException , PendingOfferAbortedException , InterruptedException { if ( offerTimeoutMillis < 0 ) { throw new IllegalArgumentException ( "offerTimeout...
Offers a request for acceptance waiting for the specified amount of time in case it could not immediately accepted .
40,161
private boolean endPendingOffer ( ) { int newValue = this . pendingOffers . decrementAndGet ( ) ; if ( newValue == 0 ) { return this . pendingOffersAborted . compareAndSet ( true , false ) ; } else { return this . pendingOffersAborted . get ( ) ; } }
End waiting for a pending offer to be accepted . Decrements pendingOffers by 1 . If pendingOffersAborted is true and pendingOffers reaches 0 then pendingOffersAborted will be reset to false .
40,162
public boolean accept ( File file ) { if ( caseSensitive ) { return file . getName ( ) . endsWith ( string0 ) ; } else { return file . getName ( ) . toLowerCase ( ) . endsWith ( string0 . toLowerCase ( ) ) ; } }
Accepts a File if its filename endsWith a specific string .
40,163
static public MobileAddress . Type parseType ( String type ) { if ( type . equalsIgnoreCase ( "network" ) ) { return MobileAddress . Type . NETWORK ; } else if ( type . equalsIgnoreCase ( "national" ) ) { return MobileAddress . Type . NATIONAL ; } else if ( type . equalsIgnoreCase ( "alphanumeric" ) ) { return MobileAd...
Parses string into a MobileAddress type . Case insensitive . Returns null if no match was found .
40,164
public static Class < ? > [ ] getClassHierarchy ( Class < ? > type ) { ArrayDeque < Class < ? > > classes = new ArrayDeque < Class < ? > > ( ) ; Class < ? > classType = type ; while ( classType != null && ! classType . equals ( Object . class ) ) { classes . addFirst ( classType ) ; classType = classType . getSuperclas...
Returns an array of class objects representing the entire class hierarchy with the most - super class as the first element followed by all subclasses in the order they are declared . This method does not include the generic Object type in its list . If this class represents the Object type this method will return a zer...
40,165
public static Method getMethod ( Class < ? > type , String name , Class < ? > returnType , Class < ? > paramType , boolean caseSensitive ) throws IllegalAccessException , NoSuchMethodException { boolean methodNameFound = false ; Class < ? > classType = type ; while ( classType != null && ! classType . equals ( Object ....
Gets the public method within the type that matches the method name return type and single parameter type . Optionally is a case sensitive search . Useful for searching for bean methods on classes .
40,166
static public < E > LoadBalancedList < E > synchronizedList ( LoadBalancedList < E > list ) { return new ConcurrentLoadBalancedList < E > ( list ) ; }
Creates a synchronized version of a LoadBalancedList by putting a lock around any method that reads or writes to the internal data structure .
40,167
static public String toHexString ( byte value ) { StringBuilder buffer = new StringBuilder ( 2 ) ; appendHexString ( buffer , value ) ; return buffer . toString ( ) ; }
Creates a 2 character hex String from a byte with the byte in a Big Endian hexidecimal format . For example a byte 0x34 will be returned as a String in format 34 . A byte of value 0 will be returned as 00 .
40,168
static public void appendHexString ( StringBuilder buffer , byte value ) { assertNotNull ( buffer ) ; int nibble = ( value & 0xF0 ) >>> 4 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x0F ) ; buffer . append ( HEX_TABLE [ nibble ] ) ; }
Appends 2 characters to a StringBuilder with the byte in a Big Endian hexidecimal format . For example a byte 0x34 will be appended as a String in format 34 . A byte of value 0 will be appended as 00 .
40,169
static public void appendHexString ( StringBuilder buffer , short value ) { assertNotNull ( buffer ) ; int nibble = ( value & 0xF000 ) >>> 12 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x0F00 ) >>> 8 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x00F0 ) >>> 4 ; buffer . append ( ...
Appends 4 characters to a StringBuilder with the short in a Big Endian hexidecimal format . For example a short 0x1234 will be appended as a String in format 1234 . A short of value 0 will be appended as 0000 .
40,170
static public void appendHexString ( StringBuilder buffer , int value ) { assertNotNull ( buffer ) ; int nibble = ( value & 0xF0000000 ) >>> 28 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x0F000000 ) >>> 24 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x00F00000 ) >>> 20 ; buffer...
Appends 8 characters to a StringBuilder with the int in a Big Endian hexidecimal format . For example a int 0xFFAA1234 will be appended as a String in format FFAA1234 . A int of value 0 will be appended as 00000000 .
40,171
static public void appendHexString ( StringBuilder buffer , long value ) { appendHexString ( buffer , ( int ) ( ( value & 0xFFFFFFFF00000000L ) >>> 32 ) ) ; appendHexString ( buffer , ( int ) ( value & 0x00000000FFFFFFFFL ) ) ; }
Appends 16 characters to a StringBuilder with the long in a Big Endian hexidecimal format . For example a long 0xAABBCCDDEE123456 will be appended as a String in format AABBCCDDEE123456 . A long of value 0 will be appended as 0000000000000000 .
40,172
static public int hexCharToIntValue ( char c ) { if ( c == '0' ) { return 0 ; } else if ( c == '1' ) { return 1 ; } else if ( c == '2' ) { return 2 ; } else if ( c == '3' ) { return 3 ; } else if ( c == '4' ) { return 4 ; } else if ( c == '5' ) { return 5 ; } else if ( c == '6' ) { return 6 ; } else if ( c == '7' ) { r...
Converts a hexidecimal character such as 0 or A or a to its integer value such as 0 or 10 . Used to decode hexidecimal Strings to integer values .
40,173
public static String getMBeanServerId ( final MBeanServer aMBeanServer ) { String serverId = null ; final String SERVER_DELEGATE = "JMImplementation:type=MBeanServerDelegate" ; final String MBEAN_SERVER_ID_KEY = "MBeanServerId" ; try { ObjectName delegateObjName = new ObjectName ( SERVER_DELEGATE ) ; serverId = ( Strin...
Get the MBeanServerId of Agent ID for the provided MBeanServer .
40,174
protected void addBuffer ( ) { if ( buffers == null ) { buffers = new LinkedList < byte [ ] > ( ) ; } buffers . addLast ( buffer ) ; buffer = new byte [ blockSize ] ; size += index ; index = 0 ; }
Create a new buffer and store the current one in linked list
40,175
public synchronized Node parse ( String xml ) throws IOException , SAXException { ByteArrayInputStream is = new ByteArrayInputStream ( xml . getBytes ( ) ) ; return parse ( is ) ; }
Parse XML from a String .
40,176
public synchronized Node parse ( File file ) throws IOException , SAXException { return parse ( new InputSource ( file . toURI ( ) . toURL ( ) . toString ( ) ) ) ; }
Parse XML from File .
40,177
public synchronized Node parse ( InputStream in ) throws IOException , SAXException { Handler handler = new Handler ( ) ; XMLReader reader = _parser . getXMLReader ( ) ; reader . setContentHandler ( handler ) ; reader . setErrorHandler ( handler ) ; reader . setEntityResolver ( handler ) ; _parser . parse ( new InputSo...
Parse XML from InputStream .
40,178
public void start ( ) throws Exception { if ( server == null ) { throw new NullPointerException ( "Internal server instance was null, server not configured perhaps?" ) ; } logger . info ( "HttpServer [{}] version [{}] using Jetty [{}]" , configuration . safeGetName ( ) , com . cloudhopper . jetty . Version . getLongVer...
Starts the HTTP server . If an exception is thrown during startup Jetty usually still runs but this method will catch that and make sure it s shutdown before re - throwing the exception .
40,179
public void stop ( ) throws Exception { if ( server == null ) { throw new NullPointerException ( "Internal server instance was null, server already stopped perhaps?" ) ; } logger . info ( "HttpServer [{}] on [{}] stopping..." , configuration . safeGetName ( ) , configuration . getPortString ( ) ) ; server . stop ( ) ; ...
Stops the HTTP server .
40,180
public void addServlet ( Servlet servlet , String uri ) { ServletHolder servletHolder = new ServletHolder ( servlet ) ; rootServletContext . addServlet ( servletHolder , uri ) ; }
Adds a servlet to this server .
40,181
public int getMaxQueuedConnections ( ) { return getThreadPool ( ) == null ? - 1 : ( ( getThreadPool ( ) . getQueue ( ) instanceof ArrayBlockingQueue ) ? ( ( ArrayBlockingQueue ) getThreadPool ( ) . getQueue ( ) ) . size ( ) + ( ( ArrayBlockingQueue ) getThreadPool ( ) . getQueue ( ) ) . remainingCapacity ( ) : - 1 ) ; ...
this should only be used as an estimate
40,182
public static File compress ( File sourceFile , String algorithm , boolean deleteSourceFileAfterCompressed ) throws FileAlreadyExistsException , IOException { return compress ( sourceFile , sourceFile . getParentFile ( ) , algorithm , deleteSourceFileAfterCompressed ) ; }
Compresses the source file using a variety of supported compression algorithms . This method will create a target file in the same directory as the source file and will append a file extension matching the compression algorithm used . For example using gzip will mean a source file of app . log would be compressed to ap...
40,183
public static File compress ( File sourceFile , File targetDir , String algorithm , boolean deleteSourceFileAfterCompressed ) throws FileAlreadyExistsException , IOException { if ( ! targetDir . isDirectory ( ) ) { throw new IOException ( "Cannot compress file since target directory " + targetDir + " neither exists or ...
Compresses the source file using a variety of supported compression algorithms . This method will create a destination file in the destination directory and will append a file extension matching the compression algorithm used . For example using gzip will mean a source file of app . log would be compressed to app . log...
40,184
public static File uncompress ( File sourceFile , boolean deleteSourceFileAfterUncompressed ) throws FileAlreadyExistsException , IOException { return uncompress ( sourceFile , sourceFile . getParentFile ( ) , deleteSourceFileAfterUncompressed ) ; }
Uncompresses the source file using a variety of supported compression algorithms . This method will create a file in the same directory as the source file by stripping the compression algorithm s file extension from the source filename . For example using gzip will mean a source file of app . log . gz would be uncompre...
40,185
public static File uncompress ( File sourceFile , File targetDir , boolean deleteSourceFileAfterUncompressed ) throws FileAlreadyExistsException , IOException { String fileExt = FileUtil . parseFileExtension ( sourceFile . getName ( ) ) ; if ( fileExt == null ) { throw new IOException ( "File '" + sourceFile + "' must ...
Uncompresses the source file using a variety of supported compression algorithms . This method will create a file in the target directory by stripping the compression algorithm s file extension from the source filename . For example using gzip will mean a source file of app . log . gz would be uncompressed to app . log...
40,186
public static byte toByte ( TypeOfAddress toa ) { byte b = 0 ; if ( toa . getTon ( ) != null ) { b |= ( toa . getTon ( ) . toInt ( ) << 0 ) ; } if ( toa . getNpi ( ) != null ) { b |= ( toa . getNpi ( ) . toInt ( ) << 4 ) ; } b |= ( 1 << 7 ) ; return b ; }
To a GSM - encoded type of address byte .
40,187
public static TypeOfAddress valueOf ( byte b ) { int ton = ( b & 0x0F ) ; int npi = ( ( b >> 4 ) & 0x07 ) ; return new TypeOfAddress ( Ton . fromInt ( ton ) , Npi . fromInt ( npi ) ) ; }
Creates a TypeOfAddress from a GSM - encoded type of address byte .
40,188
private void infoOrDebug ( boolean info , String msg ) { if ( info ) { getLogger ( ) . info ( msg ) ; } else { getLogger ( ) . debug ( msg ) ; } }
Log a message as info or debug .
40,189
static private String [ ] getStringList ( String str ) { if ( str == null ) { return null ; } List < String > list = new ArrayList < > ( ) ; int i = 0 ; int length = str . length ( ) ; StringBuffer sb = null ; while ( i < length ) { char ch = str . charAt ( i ) ; if ( ch == ' ' ) { if ( sb != null ) { list . add ( sb ....
Converts a space delimitered string to a list of strings
40,190
public String getHrefValue ( ) { String result ; if ( hrefValue == null && getArtifact ( ) != null ) { result = getArtifact ( ) . getFile ( ) . getName ( ) ; } else { result = hrefValue ; } return result ; }
Returns the value that should be output for this jar in the href attribute of the jar resource element in the generated JNLP file . If not set explicitly this defaults to the file name of the underlying artifact .
40,191
public final void generate ( ) throws Exception { VelocityContext context = createAndPopulateContext ( ) ; Writer writer = WriterFactory . newWriter ( config . getOutputFile ( ) , config . getEncoding ( ) ) ; try { velocityTemplate . merge ( context , writer ) ; writer . flush ( ) ; } catch ( Exception e ) { throw new ...
Generate the JNLP file .
40,192
protected VelocityContext createAndPopulateContext ( ) { VelocityContext context = new VelocityContext ( ) ; context . put ( "dependencies" , getDependenciesText ( ) ) ; context . put ( "arguments" , getArgumentsText ( ) ) ; addPropertiesToContext ( System . getProperties ( ) , context ) ; MavenProject mavenProject = c...
Creates a Velocity context and populates it with replacement values for our pre - defined placeholders .
40,193
private String dateToExplicitTimestamp ( Date date ) { DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ssZ" ) ; return "TS: " + df . format ( date ) ; }
Converts a given date to an explicit timestamp string in local time zone .
40,194
private String dateToExplicitTimestampUTC ( Date date ) { DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; df . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; return "TS: " + df . format ( date ) + "Z" ; }
Converts a given date to an explicit timestamp string in UTC time zone .
40,195
public synchronized DownloadResponse getJarDiffEntry ( ResourceCatalog catalog , DownloadRequest dreq , JnlpResource res ) { if ( dreq . getCurrentVersionId ( ) == null ) { return null ; } boolean doJarDiffWorkAround = isJavawsVersion ( dreq , "1.0*" ) ; JarDiffKey key = new JarDiffKey ( res . getName ( ) , dreq . getC...
Returns a JarDiff for the given request
40,196
private boolean download ( URL target , File file ) { _log . addDebug ( "JarDiffHandler: Doing download" ) ; boolean ret = true ; boolean delete = false ; BufferedInputStream in = null ; BufferedOutputStream out = null ; try { in = new BufferedInputStream ( target . openStream ( ) ) ; out = new BufferedOutputStream ( ...
Download resource to the given file
40,197
private String getRealPath ( String path ) throws IOException { URL fileURL = _servletContext . getResource ( path ) ; File tempDir = ( File ) _servletContext . getAttribute ( "javax.servlet.context.tempdir" ) ; if ( fileURL != null ) { File newFile = File . createTempFile ( "temp" , ".jar" , tempDir ) ; if ( download ...
so it can be used to generate jardiff
40,198
public void addFatal ( String key , Throwable throwable ) { logEvent ( FATAL , getString ( key ) , throwable ) ; }
Logging API . Fatal Warning and Informational are localized
40,199
private String getString ( String key ) { try { return _resources . getString ( key ) ; } catch ( MissingResourceException mre ) { return "Missing resource for: " + key ; } }
Returns a string from the resources