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 ( Character . isDigit ( c ) ) { buf . append ( c ) ; } } return buf . toString ( ) ; }
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 IOException ( "Invalid format, could not parse 3 char code" ) ; String code3 = line . substring ( pos + 1 , pos2 ) ; int pos3 = line . indexOf ( ' ' , pos2 + 1 ) ; if ( pos3 < 0 ) throw new IOException ( "Invalid format, could not parse 3 char digit code" ) ; String num3 = line . substring ( pos2 + 1 , pos3 ) ; String longName = line . substring ( pos3 + 1 ) . trim ( ) ; if ( longName == null || longName . equals ( "" ) ) { throw new IOException ( "Country name was null or empty" ) ; } String name = longName ; int pos4 = longName . lastIndexOf ( ',' ) ; if ( pos4 > 0 ) { name = longName . substring ( 0 , pos4 ) ; } return new Country ( code2 , name , longName ) ; } catch ( Exception e ) { throw new IOException ( "Failed while parsing country for line: " + line , e ) ; } }
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 ( ) ; buf [ index ] = ByteUtil . decodeHex ( x . toString ( ) , 2 ) [ 0 ] ; index ++ ; } return buf ; }
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 . getDriver ( ) ) . newInstance ( ) ; } catch ( Exception e ) { throw new SQLMissingDependencyException ( "Database driver '" + config . getDriver ( ) + "' failed to load. Perhaps missing jar file?" , e ) ; } String adapterClass = config . getProvider ( ) . getAdapter ( ) ; DataSourceAdapter adapter = null ; try { adapter = ( DataSourceAdapter ) Class . forName ( adapterClass ) . newInstance ( ) ; } catch ( Exception e ) { throw new SQLMissingDependencyException ( "DataSourceAdapter '" + adapterClass + "' failed to load. Perhaps missing jar file?" , e ) ; } ManagedDataSource mds = adapter . create ( config ) ; if ( config . getJmx ( ) ) { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; try { ObjectName name = new ObjectName ( config . getJmxDomain ( ) + ":type=ManagedDataSource,name=" + config . getName ( ) ) ; mbs . registerMBean ( mds , name ) ; } catch ( Exception e ) { logger . error ( "Error while attempting to register ManagedDataSourceMBean '" + config . getName ( ) + "'" , e ) ; } } return mds . getDataSource ( ) ; }
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 . getEnumConstants ( ) ) + "]" ) ; } return ( E ) obj ; } else { TypeConverter converter = REGISTRY . get ( type ) ; if ( converter == null ) { throw new ConversionException ( "The type [" + type . getSimpleName ( ) + "] is not supported" ) ; } return ( E ) converter . convert ( s ) ; } }
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" ) ; } else { overwriteOccurred = true ; } } FileInputStream fis = new FileInputStream ( sourceFile ) ; FileOutputStream fos = new FileOutputStream ( targetFile ) ; fis . getChannel ( ) . transferTo ( 0 , sourceFile . length ( ) , fos . getChannel ( ) ) ; fis . close ( ) ; fos . flush ( ) ; fos . close ( ) ; return overwriteOccurred ; }
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 ( extension ) ) { return true ; } } } return false ; }
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 ( "=" ) ; if ( field . actualValue != null && field . actualValue . getClass ( ) . equals ( String . class ) ) { buf . append ( '"' ) ; buf . append ( field . value ) ; buf . append ( '"' ) ; } else { buf . append ( field . value ) ; } if ( i + 1 < fields . length ) buf . append ( "," ) ; } return buf . toString ( ) ; }
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 DateTimeMonth ( currentStart , nextStart ) ) ; currentStart = nextStart ; nextStart = currentStart . plusMonths ( 1 ) ; } return list ; }
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 DateTimeYear ( currentStart , nextStart ) ) ; currentStart = nextStart ; nextStart = currentStart . plusYears ( 1 ) ; } return list ; }
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 ) ; } else if ( duration == DateTimeDuration . HOUR ) { return createHour ( start ) ; } else if ( duration == DateTimeDuration . FIVE_MINUTES ) { return createFiveMinutes ( start ) ; } else { throw new UnsupportedOperationException ( "Duration " + duration + " not yet supported" ) ; } }
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 ( ) , zone ) ; periods . add ( period ) ; now = now . minusMonths ( 1 ) ; } return periods ; }
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 ) ; systemProperties . put ( HOST_NAME , ( hostInfo [ 0 ] != null ? hostInfo [ 0 ] : "" ) ) ; systemProperties . put ( HOST_DOMAIN , ( hostInfo [ 1 ] != null ? hostInfo [ 1 ] : "" ) ) ; } else { systemProperties . put ( HOST_FQDN , "" ) ; systemProperties . put ( HOST_NAME , "" ) ; systemProperties . put ( HOST_DOMAIN , "" ) ; } return systemProperties ; }
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 ( threads , true ) ; } while ( n == nAlloc ) ; return java . util . Arrays . copyOf ( threads , n ) ; }
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 SQLConfigurationException ( "name is a required property" ) ; } if ( this . driver == null ) { throw new SQLConfigurationException ( "driver is a required property" ) ; } }
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 entry ; } } return null ; }
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 == fileListener ) return ; } listeners_ . add ( new WeakReference < FileChangedListener > ( fileListener ) ) ; }
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 == fileListener ) { i . remove ( ) ; break ; } } }
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 . print ( node . getSpecificValue ( ) . toString ( ) ) ; } else { out . print ( "(null)" ) ; } out . print ( ", W: " ) ; if ( node . getPrefixValue ( ) != null ) { out . println ( node . getPrefixValue ( ) . toString ( ) ) ; } else { out . println ( "(null)" ) ; } for ( int index = 0 ; index < 10 ; index ++ ) { dumpNode ( node . getNode ( index ) , level + 1 , index , out ) ; } }
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 = new FileInputStream ( storePath ) ; } if ( storeProvider != null ) { keystore = KeyStore . getInstance ( storeType , storeProvider ) ; } else { keystore = KeyStore . getInstance ( storeType ) ; } keystore . load ( inStream , storePassword == null ? null : storePassword . toCharArray ( ) ) ; } finally { if ( inStream != null ) { inStream . close ( ) ; } } } return keystore ; }
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 ) { trustStoreInputStream = keyStoreInputStream ; sslConfig . setTrustStorePath ( sslConfig . getKeyStorePath ( ) ) ; sslConfig . setTrustStoreType ( sslConfig . getKeyStoreType ( ) ) ; sslConfig . setTrustStoreProvider ( sslConfig . getKeyStoreProvider ( ) ) ; sslConfig . setTrustStorePassword ( sslConfig . getKeyStorePassword ( ) ) ; sslConfig . setTrustManagerFactoryAlgorithm ( sslConfig . getKeyManagerFactoryAlgorithm ( ) ) ; } if ( keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; streamCopy ( keyStoreInputStream , baos , null , false ) ; keyStoreInputStream . close ( ) ; keyStoreInputStream = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; trustStoreInputStream = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; } catch ( Exception ex ) { throw new IllegalStateException ( ex ) ; } } }
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 ( " at " ) ; result . append ( element ) ; result . append ( NEW_LINE ) ; } return result . toString ( ) ; }
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 ) { throw new IllegalArgumentException ( "Both charSeq and charBuffer cannot be null" ) ; } charOffset = 0 ; charAbsLength = charSeq . length ( ) ; } for ( ; charPos < charAbsLength ; charPos ++ ) { if ( charBuffer != null ) { c = charBuffer [ charPos ] ; } else { c = charSeq . charAt ( charPos ) ; } if ( ! ( ( c >= 0x0000 ) && ( c <= 0x007F ) ) ) break ; byteBuffer [ bytePos ++ ] = ( byte ) c ; } for ( ; charPos < charAbsLength ; charPos ++ ) { if ( charBuffer != null ) { c = charBuffer [ charPos ] ; } else { c = charSeq . charAt ( charPos ) ; } if ( ( c >= 0x0000 ) && ( c <= 0x007F ) ) { byteBuffer [ bytePos ++ ] = ( byte ) c ; } else if ( c > 0x07FF ) { byteBuffer [ bytePos ++ ] = ( byte ) ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ) ; byteBuffer [ bytePos ++ ] = ( byte ) ( 0x80 | ( ( c >> 6 ) & 0x3F ) ) ; byteBuffer [ bytePos ++ ] = ( byte ) ( 0x80 | ( c & 0x3F ) ) ; } else { byteBuffer [ bytePos ++ ] = ( byte ) ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ) ; byteBuffer [ bytePos ++ ] = ( byte ) ( 0x80 | ( c & 0x3F ) ) ; } } return ( bytePos - byteOffset ) ; }
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 encoding group" ) ; } return new DataCoding ( characterEncoding , Group . CHARACTER_ENCODING , characterEncoding , MESSAGE_CLASS_0 , false ) ; }
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_8BIT ; } byte messageClass = ( byte ) ( dcs & ( byte ) 0x03 ) ; return createMessageClassGroup ( characterEncoding , messageClass ) ; } else if ( ( dcs & ( byte ) 0xC0 ) == ( byte ) 0x00 ) { boolean compressed = false ; if ( ( dcs & ( byte ) 0x20 ) == ( byte ) 0x20 ) { compressed = true ; } byte tempMessageClass = ( byte ) ( dcs & ( byte ) 0x03 ) ; Byte messageClass = null ; if ( ( dcs & ( byte ) 0x10 ) == ( byte ) 0x10 ) { messageClass = new Byte ( tempMessageClass ) ; } byte characterEncoding = ( byte ) ( dcs & ( byte ) 0x0C ) ; return createGeneralGroup ( characterEncoding , messageClass , compressed ) ; } else if ( ( dcs & ( byte ) 0xC0 ) == ( byte ) 0xC0 ) { byte characterEncoding = CHAR_ENC_DEFAULT ; if ( ( byte ) ( dcs & ( byte ) 0x20 ) == 0x20 ) { characterEncoding = CHAR_ENC_UCS2 ; } boolean store = false ; if ( ( byte ) ( dcs & ( byte ) 0x10 ) == 0x10 ) { store = true ; } boolean indicatorActive = false ; if ( ( byte ) ( dcs & ( byte ) 0x08 ) == 0x08 ) { indicatorActive = true ; } byte indicatorType = ( byte ) ( dcs & ( byte ) 0x03 ) ; return createMessageWaitingIndicationGroup ( characterEncoding , store , indicatorActive , indicatorType ) ; } else { return createReservedGroup ( dcs ) ; } } catch ( IllegalArgumentException e ) { return createReservedGroup ( dcs ) ; } }
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 IllegalArgumentException ( "Buffer size must be a value between 0 and " + bufferCapacity + " !" ) ; } if ( ( readPosition < 0 ) || ( readPosition > bufferSize ) ) { throw new IllegalArgumentException ( "Buffer read position must be a value between 0 and " + bufferSize + " !" ) ; } if ( ( writePosition < 0 ) || ( writePosition > bufferSize ) ) { throw new IllegalArgumentException ( "Buffer write position must be a value between 0 and " + bufferSize + " !" ) ; } this . buffer = new byte [ bufferCapacity ] ; this . currentBufferSize = bufferSize ; this . currentReadPosition = readPosition ; this . currentWritePosition = writePosition ; }
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 ( "Exponent " + b + " is too big !" ) ; } b2Binary [ counter ] = ( b % 2 != 0 ) ; b = b / 2 ; } for ( int k = counter - 1 ; k >= 0 ; k -- ) { result = ( result * result ) % n ; if ( b2Binary [ k ] ) { result = ( result * a ) % n ; } } return result ; }
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 . buffer . length ; this . currentBufferSize += 1 ; }
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 cannot be negative" ) ; } if ( offset != 0 && offset >= bytesLength ) { throw new IllegalArgumentException ( "The byte[] offset (" + offset + ") must be < the length of the byte[] length (" + bytesLength + ")" ) ; } if ( offset + length > bytesLength ) { throw new IllegalArgumentException ( "The offset+length (" + ( offset + length ) + ") would read past the end of the byte[] (length=" + bytesLength + ")" ) ; } }
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 + " bytes of data" ) ; } for ( int i = 0 ; i < length ; i ++ ) { try { this . add ( bytes [ i + offset ] ) ; } catch ( BufferIsFullException e ) { logger . error ( "Buffer is full even though this method checked its size() ahead of time" , e ) ; throw new BufferSizeException ( e . getMessage ( ) ) ; } } }
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 " + index + " is >= buffer size of " + size ( ) ) ; } return this . buffer [ ( this . currentReadPosition + index ) % this . buffer . length ] ; }
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 ( "TargetBuffer size must be large enough to hold a byte[] of at least a size=" + length ) ; } if ( length > 0 ) { int offsetReadPosition = ( this . currentReadPosition + offset ) % this . buffer . length ; int offsetWritePosition = ( this . currentReadPosition + offset + length ) % this . buffer . length ; if ( offsetReadPosition >= offsetWritePosition ) { System . arraycopy ( this . buffer , offsetReadPosition , targetBuffer , targetOffset , this . buffer . length - offsetReadPosition ) ; System . arraycopy ( this . buffer , 0 , targetBuffer , targetOffset + this . buffer . length - offsetReadPosition , offsetWritePosition ) ; } else { System . arraycopy ( this . buffer , offsetReadPosition , targetBuffer , targetOffset , offsetWritePosition - offsetReadPosition ) ; } } }
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 ++ ; j = ( j + 1 ) % this . buffer . length ; } return match ; }
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 ( this . buffer [ j ] != prefix [ i ] ) { match = false ; } i -- ; j = ( j - 1 + this . buffer . length ) % this . buffer . length ; } return match ; }
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 ; for ( int i = offset ; i <= length ; i ++ ) { int j = 0 ; while ( j < bytes . length && getUnchecked ( i + j ) == bytes [ j ] ) { j ++ ; } if ( j == bytes . length ) { return i ; } } return - 1 ; }
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 , getUnchecked ( i ) ) ; } return s . toString ( ) ; }
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 ( ) . getType ( ) != null ) { logger . warn ( "Unable to fully parse XML into a request, returning ErrorResponse; error: " + e . getMessage ( ) + ", parsed: " + e . getOperation ( ) ) ; return new ErrorResponse ( e . getOperation ( ) . getType ( ) , e . getErrorCode ( ) . getIntValue ( ) , e . getErrorMessage ( ) ) ; } else { throw new SAXException ( e . getMessage ( ) , e ) ; } } try { if ( ! ( operation instanceof Request ) ) { throw new SxmpErrorException ( SxmpErrorCode . UNSUPPORTED_OPERATION , "A session can only process requests" ) ; } Request req = ( Request ) operation ; if ( req . getAccount ( ) == null ) { throw new SxmpErrorException ( SxmpErrorCode . MISSING_REQUIRED_ELEMENT , "A request must include account credentials" ) ; } if ( ! processor . authenticate ( req . getAccount ( ) ) ) { throw new SxmpErrorException ( SxmpErrorCode . AUTHENTICATION_FAILURE , "Authentication failure" ) ; } if ( operation instanceof SubmitRequest ) { return processor . submit ( req . getAccount ( ) , ( SubmitRequest ) operation ) ; } else if ( operation instanceof DeliverRequest ) { return processor . deliver ( req . getAccount ( ) , ( DeliverRequest ) operation ) ; } else if ( operation instanceof DeliveryReportRequest ) { return processor . deliveryReport ( req . getAccount ( ) , ( DeliveryReportRequest ) operation ) ; } else { throw new SxmpErrorException ( SxmpErrorCode . UNSUPPORTED_OPERATION , "Unsupported operation request type" ) ; } } catch ( SxmpErrorException e ) { logger . warn ( e . getMessage ( ) ) ; return new ErrorResponse ( operation . getType ( ) , e . getErrorCode ( ) . getIntValue ( ) , e . getErrorMessage ( ) ) ; } catch ( Throwable t ) { logger . error ( "Major uncaught throwable while processing request, generating an ErrorResponse" , t ) ; return new ErrorResponse ( operation . getType ( ) , SxmpErrorCode . GENERIC . getIntValue ( ) , "Generic error while processing request" ) ; } }
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 ] [ 1 ] ) ; } } } return replaced ; }
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 ) | ( rawData [ pos ++ ] & 0xFF ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 18 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 12 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 6 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ value & 0x3F ] ) ; } switch ( rawData . length % 3 ) { case 1 : buffer . append ( BASE64_ALPHABET [ ( rawData [ pos ] >>> 2 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( rawData [ pos ] << 4 ) & 0x3F ] ) ; buffer . append ( "==" ) ; break ; case 2 : int value = ( ( rawData [ pos ++ ] & 0xFF ) << 8 ) | ( rawData [ pos ] & 0xFF ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 10 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 4 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value << 2 ) & 0x3F ] ) ; buffer . append ( "=" ) ; break ; } return buffer . toString ( ) ; }
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 >= table . length ) ? '?' : table [ code ] ) ; table = CHAR_TABLE ; } } }
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 ( "offerTimeoutMillis must be >= 0 [actual=" + offerTimeoutMillis + "]" ) ; } if ( this . futures . containsKey ( key ) ) { throw new DuplicateKeyException ( "The key [" + key + "] already exists in the window" ) ; } long offerTimestamp = System . currentTimeMillis ( ) ; this . lock . lockInterruptibly ( ) ; try { while ( getFreeSize ( ) <= 0 ) { long currentOfferTime = System . currentTimeMillis ( ) - offerTimestamp ; if ( currentOfferTime >= offerTimeoutMillis ) { throw new OfferTimeoutException ( "Unable to accept offer within [" + offerTimeoutMillis + " ms] (window full)" ) ; } if ( this . pendingOffersAborted . get ( ) ) { throw new PendingOfferAbortedException ( "Pending offer aborted (by an explicit call to abortPendingOffers())" ) ; } long remainingOfferTime = offerTimeoutMillis - currentOfferTime ; try { this . beginPendingOffer ( ) ; this . completedCondition . await ( remainingOfferTime , TimeUnit . MILLISECONDS ) ; } finally { boolean abortPendingOffer = this . endPendingOffer ( ) ; if ( abortPendingOffer ) { throw new PendingOfferAbortedException ( "Pending offer aborted (by an explicit call to abortPendingOffers())" ) ; } } } long acceptTimestamp = System . currentTimeMillis ( ) ; long expireTimestamp = ( expireTimeoutMillis > 0 ? ( acceptTimestamp + expireTimeoutMillis ) : - 1 ) ; int callerStateHint = ( callerWaitingHint ? WindowFuture . CALLER_WAITING : WindowFuture . CALLER_NOT_WAITING ) ; DefaultWindowFuture < K , R , P > future = new DefaultWindowFuture < K , R , P > ( this , lock , completedCondition , key , request , callerStateHint , offerTimeoutMillis , ( futures . size ( ) + 1 ) , offerTimestamp , acceptTimestamp , expireTimestamp ) ; this . futures . put ( key , future ) ; return future ; } finally { this . lock . unlock ( ) ; } }
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 MobileAddress . Type . ALPHANUMERIC ; } else if ( type . equalsIgnoreCase ( "international" ) ) { return MobileAddress . Type . INTERNATIONAL ; } else if ( type . equalsIgnoreCase ( "push_destination" ) ) { return MobileAddress . Type . PUSH_DESTINATION ; } else { return null ; } }
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 . getSuperclass ( ) ; } return classes . toArray ( new Class [ 0 ] ) ; }
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 zero - size array .
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 . class ) ) { for ( Method m : classType . getDeclaredMethods ( ) ) { if ( ( ! caseSensitive && m . getName ( ) . equalsIgnoreCase ( name ) ) || ( caseSensitive && m . getName ( ) . equals ( name ) ) ) { methodNameFound = true ; if ( returnType != null ) { if ( ! m . getReturnType ( ) . equals ( returnType ) ) { throw new NoSuchMethodException ( "Method '" + name + "' was found in " + type . getSimpleName ( ) + ".class" + ", but the returnType " + m . getReturnType ( ) . getSimpleName ( ) + ".class did not match expected " + returnType . getSimpleName ( ) + ".class" ) ; } } else { if ( ! m . getReturnType ( ) . equals ( void . class ) ) { throw new NoSuchMethodException ( "Method '" + name + "' was found in " + type . getSimpleName ( ) + ".class" + ", but the returnType " + m . getReturnType ( ) . getSimpleName ( ) + ".class was expected to be void" ) ; } } Class < ? > [ ] paramTypes = m . getParameterTypes ( ) ; if ( paramType != null ) { if ( paramTypes . length != 1 ) { continue ; } else { if ( ! paramTypes [ 0 ] . equals ( paramType ) ) { continue ; } } } else { if ( paramTypes . length != 0 ) { continue ; } } if ( ! Modifier . isPublic ( m . getModifiers ( ) ) ) { throw new IllegalAccessException ( "Method '" + name + "' was found in " + type . getSimpleName ( ) + ".class " + ", but its not accessible since its " + Modifier . toString ( m . getModifiers ( ) ) ) ; } return m ; } } classType = classType . getSuperclass ( ) ; } String signature = "public " + ( returnType == null ? "void" : returnType . getName ( ) ) + " " + name + "(" + ( paramType == null ? "" : paramType . getName ( ) ) + ")" ; if ( methodNameFound ) { throw new NoSuchMethodException ( "Method '" + signature + "' was found in " + type . getSimpleName ( ) + ".class, but signature match failed" ) ; } else { throw new NoSuchMethodException ( "Method '" + signature + "' was not found in " + type . getSimpleName ( ) + ".class" ) ; } }
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 ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x000F ) ; buffer . append ( HEX_TABLE [ nibble ] ) ; }
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 . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x000F0000 ) >>> 16 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x0000F000 ) >>> 12 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x00000F00 ) >>> 8 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x000000F0 ) >>> 4 ; buffer . append ( HEX_TABLE [ nibble ] ) ; nibble = ( value & 0x0000000F ) ; buffer . append ( HEX_TABLE [ nibble ] ) ; }
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' ) { return 7 ; } else if ( c == '8' ) { return 8 ; } else if ( c == '9' ) { return 9 ; } else if ( c == 'A' || c == 'a' ) { return 10 ; } else if ( c == 'B' || c == 'b' ) { return 11 ; } else if ( c == 'C' || c == 'c' ) { return 12 ; } else if ( c == 'D' || c == 'd' ) { return 13 ; } else if ( c == 'E' || c == 'e' ) { return 14 ; } else if ( c == 'F' || c == 'f' ) { return 15 ; } else { throw new IllegalArgumentException ( "The character [" + c + "] does not represent a valid hex digit" ) ; } }
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 = ( String ) aMBeanServer . getAttribute ( delegateObjName , MBEAN_SERVER_ID_KEY ) ; } catch ( MalformedObjectNameException malformedObjectNameException ) { } catch ( AttributeNotFoundException noMatchingAttrException ) { } catch ( MBeanException mBeanException ) { } catch ( ReflectionException reflectionException ) { } catch ( InstanceNotFoundException noMBeanInstance ) { } return serverId ; }
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 InputSource ( in ) , handler ) ; if ( handler . error != null ) throw handler . error ; Node root = ( Node ) handler . root ; handler . reset ( ) ; return root ; }
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 . getLongVersion ( ) , server . getVersion ( ) ) ; logger . info ( "HttpServer [{}] on [{}] starting..." , configuration . safeGetName ( ) , configuration . getPortString ( ) ) ; try { server . start ( ) ; } catch ( Exception e ) { try { this . stop ( ) ; } catch ( Exception ex ) { } throw e ; } logger . info ( "HttpServer [{}] on [{}] started" , configuration . safeGetName ( ) , configuration . getPortString ( ) ) ; }
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 ( ) ; logger . info ( "HttpServer [{}] on [{}] stopped" , configuration . safeGetName ( ) , configuration . getPortString ( ) ) ; }
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 app . log . gz .
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 is a directory" ) ; } Algorithm a = Algorithm . findByName ( algorithm ) ; if ( a == null ) { throw new IOException ( "Compression algorithm '" + algorithm + "' is not supported" ) ; } File targetFile = new File ( targetDir , sourceFile . getName ( ) + "." + a . getFileExtension ( ) ) ; compress ( a , sourceFile , targetFile , deleteSourceFileAfterCompressed ) ; return targetFile ; }
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 . gz and placed in the destination directory .
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 uncompressed to app . log .
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 contain a file extension in order to lookup the compression algorithm" ) ; } Algorithm a = Algorithm . findByFileExtension ( fileExt ) ; if ( a == null ) { throw new IOException ( "Unrecognized or unsupported compression algorithm for file extension '" + fileExt + "'" ) ; } if ( ! targetDir . isDirectory ( ) ) { throw new IOException ( "Cannot uncompress file since target directory " + targetDir + " neither exists or is a directory" ) ; } String filename = sourceFile . getName ( ) ; filename = filename . substring ( 0 , filename . length ( ) - ( fileExt . length ( ) + 1 ) ) ; File targetFile = new File ( targetDir , filename ) ; uncompress ( a , sourceFile , targetFile , deleteSourceFileAfterUncompressed ) ; return targetFile ; }
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 and placed in the target directory .
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 . toString ( ) ) ; sb = null ; } } else if ( ch == '\\' ) { if ( i + 1 < length ) { ch = str . charAt ( ++ i ) ; if ( sb == null ) { sb = new StringBuffer ( ) ; } sb . append ( ch ) ; } } else { if ( sb == null ) { sb = new StringBuffer ( ) ; } sb . append ( ch ) ; } i ++ ; } if ( sb != null ) { list . add ( sb . toString ( ) ) ; } if ( list . size ( ) == 0 ) { return null ; } String [ ] results = new String [ list . size ( ) ] ; return list . toArray ( results ) ; }
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 Exception ( "Could not generate the template " + velocityTemplate . getName ( ) + ": " + e . getMessage ( ) , e ) ; } finally { writer . close ( ) ; } }
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 = config . getMavenProject ( ) ; String encoding = config . getEncoding ( ) ; addPropertiesToContext ( mavenProject . getProperties ( ) , context ) ; addPropertiesToContext ( extraConfig . getProperties ( ) , context ) ; context . put ( "project" , mavenProject . getModel ( ) ) ; context . put ( "jnlpCodebase" , extraConfig . getJnlpCodeBase ( ) ) ; context . put ( "informationTitle" , mavenProject . getModel ( ) . getName ( ) ) ; context . put ( "informationDescription" , mavenProject . getModel ( ) . getDescription ( ) ) ; if ( mavenProject . getModel ( ) . getOrganization ( ) != null ) { context . put ( "informationVendor" , mavenProject . getModel ( ) . getOrganization ( ) . getName ( ) ) ; context . put ( "informationHomepage" , mavenProject . getModel ( ) . getOrganization ( ) . getUrl ( ) ) ; } Date timestamp = new Date ( ) ; context . put ( "explicitTimestamp" , dateToExplicitTimestamp ( timestamp ) ) ; context . put ( "explicitTimestampUTC" , dateToExplicitTimestampUTC ( timestamp ) ) ; context . put ( "outputFile" , config . getOutputFile ( ) . getName ( ) ) ; context . put ( "mainClass" , config . getMainClass ( ) ) ; context . put ( "encoding" , encoding ) ; context . put ( "input.encoding" , encoding ) ; context . put ( "output.encoding" , encoding ) ; context . put ( "allPermissions" , BooleanUtils . toBoolean ( extraConfig . getAllPermissions ( ) ) ) ; context . put ( "offlineAllowed" , BooleanUtils . toBoolean ( extraConfig . getOfflineAllowed ( ) ) ) ; context . put ( "jnlpspec" , extraConfig . getJnlpSpec ( ) ) ; context . put ( "j2seVersion" , extraConfig . getJ2seVersion ( ) ) ; context . put ( "iconHref" , extraConfig . getIconHref ( ) ) ; return context ; }
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 . getCurrentVersionId ( ) , res . getReturnVersionId ( ) , ! doJarDiffWorkAround ) ; JarDiffEntry entry = ( JarDiffEntry ) _jarDiffEntries . get ( key ) ; if ( entry == null ) { if ( _log . isInformationalLevel ( ) ) { _log . addInformational ( "servlet.log.info.jardiff.gen" , res . getName ( ) , dreq . getCurrentVersionId ( ) , res . getReturnVersionId ( ) ) ; } File f = generateJarDiff ( catalog , dreq , res , doJarDiffWorkAround ) ; if ( f == null ) { _log . addWarning ( "servlet.log.warning.jardiff.failed" , res . getName ( ) , dreq . getCurrentVersionId ( ) , res . getReturnVersionId ( ) ) ; } entry = new JarDiffEntry ( f ) ; _jarDiffEntries . put ( key , entry ) ; } if ( entry . getJarDiffFile ( ) == null ) { return null ; } else { return DownloadResponse . getFileDownloadResponse ( entry . getJarDiffFile ( ) , _jarDiffMimeType , entry . getJarDiffFile ( ) . lastModified ( ) , res . getReturnVersionId ( ) ) ; } }
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 ( new FileOutputStream ( file ) ) ; int read = 0 ; int totalRead = 0 ; byte [ ] buf = new byte [ BUF_SIZE ] ; while ( ( read = in . read ( buf ) ) != - 1 ) { out . write ( buf , 0 , read ) ; totalRead += read ; } _log . addDebug ( "total read: " + totalRead ) ; _log . addDebug ( "Wrote URL " + target . toString ( ) + " to file " + file ) ; } catch ( IOException ioe ) { _log . addDebug ( "Got exception while downloading resource: " + ioe ) ; ret = false ; if ( file != null ) { delete = true ; } } finally { try { in . close ( ) ; in = null ; } catch ( IOException ioe ) { _log . addDebug ( "Got exception while downloading resource: " + ioe ) ; } try { out . close ( ) ; out = null ; } catch ( IOException ioe ) { _log . addDebug ( "Got exception while downloading resource: " + ioe ) ; } if ( delete ) { file . delete ( ) ; } } return ret ; }
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 ( fileURL , newFile ) ) { String filePath = newFile . getPath ( ) ; return filePath ; } } return null ; }
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