idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
8,400
private void initSocket ( ) { socket = new Socket ( ) ; try { socket . setSoLinger ( false , 0 ) ; socket . setTcpNoDelay ( true ) ; socket . setSoTimeout ( timeout ) ; } catch ( SocketException sx ) { LOGGER . error ( "Could not configure socket." , sx ) ; } }
Initializes the socket object
8,401
public void setTimeout ( int timeout ) { this . timeout = timeout ; try { socket . setSoTimeout ( timeout ) ; } catch ( SocketException sx ) { LOGGER . warn ( "Could not set socket timeout." , sx ) ; } }
Sets the socket timeout
8,402
public void open ( ) throws TTransportException { if ( isOpen ( ) ) { throw new TTransportException ( TTransportException . ALREADY_OPEN , "Socket already connected." ) ; } if ( host . length ( ) == 0 ) { throw new TTransportException ( TTransportException . NOT_OPEN , "Cannot open null host." ) ; } if ( port <= 0 ) { throw new TTransportException ( TTransportException . NOT_OPEN , "Cannot open without port." ) ; } if ( socket == null ) { initSocket ( ) ; } try { socket . connect ( new InetSocketAddress ( host , port ) , timeout ) ; inputStream_ = new BufferedInputStream ( socket . getInputStream ( ) , 1024 ) ; outputStream_ = new BufferedOutputStream ( socket . getOutputStream ( ) , 1024 ) ; } catch ( IOException iox ) { close ( ) ; throw new TTransportException ( TTransportException . NOT_OPEN , iox ) ; } }
Connects the socket creating a new socket object if necessary .
8,403
public ByteBuffer [ ] split ( ByteBuffer name ) { List < ByteBuffer > l = new ArrayList < ByteBuffer > ( ) ; ByteBuffer bb = name . duplicate ( ) ; readIsStatic ( bb ) ; int i = 0 ; while ( bb . remaining ( ) > 0 ) { getComparator ( i ++ , bb ) ; l . add ( ByteBufferUtil . readBytesWithShortLength ( bb ) ) ; bb . get ( ) ; } return l . toArray ( new ByteBuffer [ l . size ( ) ] ) ; }
Split a composite column names into it s components .
8,404
public static < K extends IMeasurableMemory , V extends IMeasurableMemory > ConcurrentLinkedHashCache < K , V > create ( long weightedCapacity , EntryWeigher < K , V > entryWeiger ) { ConcurrentLinkedHashMap < K , V > map = new ConcurrentLinkedHashMap . Builder < K , V > ( ) . weigher ( entryWeiger ) . maximumWeightedCapacity ( weightedCapacity ) . concurrencyLevel ( DEFAULT_CONCURENCY_LEVEL ) . build ( ) ; return new ConcurrentLinkedHashCache < K , V > ( map ) ; }
Initialize a cache with initial capacity with weightedCapacity
8,405
public void onSuccess ( StreamState state ) { logger . info ( String . format ( "[repair #%s] streaming task succeed, returning response to %s" , desc . sessionId , request . initiator ) ) ; MessagingService . instance ( ) . sendOneWay ( new SyncComplete ( desc , request . src , request . dst , true ) . createMessage ( ) , request . initiator ) ; }
If we succeeded on both stream in and out reply back to the initiator .
8,406
public void onFailure ( Throwable t ) { MessagingService . instance ( ) . sendOneWay ( new SyncComplete ( desc , request . src , request . dst , false ) . createMessage ( ) , request . initiator ) ; }
If we failed on either stream in or out reply fail to the initiator .
8,407
public ByteBuffer createLocal ( long count ) { ContextState state = ContextState . allocate ( 0 , 1 , 0 ) ; state . writeLocal ( CounterId . getLocalId ( ) , 1L , count ) ; return state . context ; }
Creates a counter context with a single local shard . For use by tests of compatibility with pre - 2 . 1 counters only .
8,408
public ByteBuffer createRemote ( CounterId id , long clock , long count ) { ContextState state = ContextState . allocate ( 0 , 0 , 1 ) ; state . writeRemote ( id , clock , count ) ; return state . context ; }
Creates a counter context with a single remote shard . For use by tests of compatibility with pre - 2 . 1 counters only .
8,409
public Relationship diff ( ByteBuffer left , ByteBuffer right ) { Relationship relationship = Relationship . EQUAL ; ContextState leftState = ContextState . wrap ( left ) ; ContextState rightState = ContextState . wrap ( right ) ; while ( leftState . hasRemaining ( ) && rightState . hasRemaining ( ) ) { int compareId = leftState . compareIdTo ( rightState ) ; if ( compareId == 0 ) { long leftClock = leftState . getClock ( ) ; long rightClock = rightState . getClock ( ) ; long leftCount = leftState . getCount ( ) ; long rightCount = rightState . getCount ( ) ; leftState . moveToNext ( ) ; rightState . moveToNext ( ) ; if ( leftClock == rightClock ) { if ( leftCount != rightCount ) { return Relationship . DISJOINT ; } } else if ( ( leftClock >= 0 && rightClock > 0 && leftClock > rightClock ) || ( leftClock < 0 && ( rightClock > 0 || leftClock < rightClock ) ) ) { if ( relationship == Relationship . EQUAL ) relationship = Relationship . GREATER_THAN ; else if ( relationship == Relationship . LESS_THAN ) return Relationship . DISJOINT ; } else { if ( relationship == Relationship . EQUAL ) relationship = Relationship . LESS_THAN ; else if ( relationship == Relationship . GREATER_THAN ) return Relationship . DISJOINT ; } } else if ( compareId > 0 ) { rightState . moveToNext ( ) ; if ( relationship == Relationship . EQUAL ) relationship = Relationship . LESS_THAN ; else if ( relationship == Relationship . GREATER_THAN ) return Relationship . DISJOINT ; } else { leftState . moveToNext ( ) ; if ( relationship == Relationship . EQUAL ) relationship = Relationship . GREATER_THAN ; else if ( relationship == Relationship . LESS_THAN ) return Relationship . DISJOINT ; } } if ( leftState . hasRemaining ( ) ) { if ( relationship == Relationship . EQUAL ) return Relationship . GREATER_THAN ; else if ( relationship == Relationship . LESS_THAN ) return Relationship . DISJOINT ; } if ( rightState . hasRemaining ( ) ) { if ( relationship == Relationship . EQUAL ) return Relationship . LESS_THAN ; else if ( relationship == Relationship . GREATER_THAN ) return Relationship . DISJOINT ; } return relationship ; }
Determine the count relationship between two contexts .
8,410
public long total ( ByteBuffer context ) { long total = 0L ; for ( int offset = context . position ( ) + headerLength ( context ) ; offset < context . limit ( ) ; offset += STEP_LENGTH ) total += context . getLong ( offset + CounterId . LENGTH + CLOCK_LENGTH ) ; return total ; }
Returns the aggregated count across all counter ids .
8,411
public static List < ? extends IResource > chain ( IResource resource ) { List < IResource > chain = new ArrayList < IResource > ( ) ; while ( true ) { chain . add ( resource ) ; if ( ! resource . hasParent ( ) ) break ; resource = resource . getParent ( ) ; } return chain ; }
Construct a chain of resource parents starting with the resource and ending with the root .
8,412
public void dumpInterArrivalTimes ( ) { File file = FileUtils . createTempFile ( "failuredetector-" , ".dat" ) ; OutputStream os = null ; try { os = new BufferedOutputStream ( new FileOutputStream ( file , true ) ) ; os . write ( toString ( ) . getBytes ( ) ) ; } catch ( IOException e ) { throw new FSWriteError ( e , file ) ; } finally { FileUtils . closeQuietly ( os ) ; } }
Dump the inter arrival times for examination if necessary .
8,413
double phi ( long tnow ) { assert arrivalIntervals . size ( ) > 0 && tLast > 0 ; long t = tnow - tLast ; return t / mean ( ) ; }
see CASSANDRA - 2597 for an explanation of the math at work here .
8,414
public static int pop ( long x ) { x = x - ( ( x >>> 1 ) & 0x5555555555555555L ) ; x = ( x & 0x3333333333333333L ) + ( ( x >>> 2 ) & 0x3333333333333333L ) ; x = ( x + ( x >>> 4 ) ) & 0x0F0F0F0F0F0F0F0FL ; x = x + ( x >>> 8 ) ; x = x + ( x >>> 16 ) ; x = x + ( x >>> 32 ) ; return ( ( int ) x ) & 0x7F ; }
Returns the number of bits set in the long
8,415
public static int ntz ( long val ) { int lower = ( int ) val ; int lowByte = lower & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] ; if ( lower != 0 ) { lowByte = ( lower >>> 8 ) & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 8 ; lowByte = ( lower >>> 16 ) & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 16 ; return ntzTable [ lower >>> 24 ] + 24 ; } else { int upper = ( int ) ( val >> 32 ) ; lowByte = upper & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 32 ; lowByte = ( upper >>> 8 ) & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 40 ; lowByte = ( upper >>> 16 ) & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 48 ; return ntzTable [ upper >>> 24 ] + 56 ; } }
Returns number of trailing zeros in a 64 bit long value .
8,416
public static int ntz ( int val ) { int lowByte = val & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] ; lowByte = ( val >>> 8 ) & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 8 ; lowByte = ( val >>> 16 ) & 0xff ; if ( lowByte != 0 ) return ntzTable [ lowByte ] + 16 ; return ntzTable [ val >>> 24 ] + 24 ; }
Returns number of trailing zeros in a 32 bit int value .
8,417
public boolean intersects ( Iterable < Range < T > > ranges ) { for ( Range < T > range2 : ranges ) { if ( range2 . intersects ( this ) ) return true ; } return false ; }
return true if
8,418
private void warmup ( OpDistributionFactory operations ) { PrintStream warmupOutput = new PrintStream ( new OutputStream ( ) { public void write ( int b ) throws IOException { } } ) ; int iterations = 50000 * settings . node . nodes . size ( ) ; int threads = 20 ; if ( settings . rate . maxThreads > 0 ) threads = Math . min ( threads , settings . rate . maxThreads ) ; if ( settings . rate . threadCount > 0 ) threads = Math . min ( threads , settings . rate . threadCount ) ; for ( OpDistributionFactory single : operations . each ( ) ) { output . println ( String . format ( "Warming up %s with %d iterations..." , single . desc ( ) , iterations ) ) ; run ( single , threads , iterations , 0 , null , null , warmupOutput ) ; } }
type provided separately to support recursive call for mixed command with each command type it is performing
8,419
public static boolean isSuperuser ( String username ) { UntypedResultSet result = selectUser ( username ) ; return ! result . isEmpty ( ) && result . one ( ) . getBoolean ( "super" ) ; }
Checks if the user is a known superuser .
8,420
public static void deleteUser ( String username ) throws RequestExecutionException { QueryProcessor . process ( String . format ( "DELETE FROM %s.%s WHERE name = '%s'" , AUTH_KS , USERS_CF , escape ( username ) ) , consistencyForUser ( username ) ) ; }
Deletes the user from AUTH_KS . USERS_CF .
8,421
public static void setup ( ) { if ( DatabaseDescriptor . getAuthenticator ( ) instanceof AllowAllAuthenticator ) return ; setupAuthKeyspace ( ) ; setupTable ( USERS_CF , USERS_CF_SCHEMA ) ; DatabaseDescriptor . getAuthenticator ( ) . setup ( ) ; DatabaseDescriptor . getAuthorizer ( ) . setup ( ) ; MigrationManager . instance . register ( new AuthMigrationListener ( ) ) ; ScheduledExecutors . nonPeriodicTasks . schedule ( new Runnable ( ) { public void run ( ) { setupDefaultSuperuser ( ) ; } } , SUPERUSER_SETUP_DELAY , TimeUnit . MILLISECONDS ) ; try { String query = String . format ( "SELECT * FROM %s.%s WHERE name = ?" , AUTH_KS , USERS_CF ) ; selectUserStatement = ( SelectStatement ) QueryProcessor . parseStatement ( query ) . prepare ( ) . statement ; } catch ( RequestValidationException e ) { throw new AssertionError ( e ) ; } }
Sets up Authenticator and Authorizer .
8,422
private static ConsistencyLevel consistencyForUser ( String username ) { if ( username . equals ( DEFAULT_SUPERUSER_NAME ) ) return ConsistencyLevel . QUORUM ; else return ConsistencyLevel . LOCAL_ONE ; }
Only use QUORUM cl for the default superuser .
8,423
public static void setupTable ( String name , String cql ) { if ( Schema . instance . getCFMetaData ( AUTH_KS , name ) == null ) { try { CFStatement parsed = ( CFStatement ) QueryProcessor . parseStatement ( cql ) ; parsed . prepareKeyspace ( AUTH_KS ) ; CreateTableStatement statement = ( CreateTableStatement ) parsed . prepare ( ) . statement ; CFMetaData cfm = statement . getCFMetaData ( ) . copy ( CFMetaData . generateLegacyCfId ( AUTH_KS , name ) ) ; assert cfm . cfName . equals ( name ) ; MigrationManager . announceNewColumnFamily ( cfm ) ; } catch ( Exception e ) { throw new AssertionError ( e ) ; } } }
Set up table from given CREATE TABLE statement under system_auth keyspace if not already done so .
8,424
private Multimap < Range < Token > , InetAddress > getAllRangesWithSourcesFor ( String keyspaceName , Collection < Range < Token > > desiredRanges ) { AbstractReplicationStrategy strat = Keyspace . open ( keyspaceName ) . getReplicationStrategy ( ) ; Multimap < Range < Token > , InetAddress > rangeAddresses = strat . getRangeAddresses ( metadata . cloneOnlyTokenMap ( ) ) ; Multimap < Range < Token > , InetAddress > rangeSources = ArrayListMultimap . create ( ) ; for ( Range < Token > desiredRange : desiredRanges ) { for ( Range < Token > range : rangeAddresses . keySet ( ) ) { if ( range . contains ( desiredRange ) ) { List < InetAddress > preferred = DatabaseDescriptor . getEndpointSnitch ( ) . getSortedListByProximity ( address , rangeAddresses . get ( range ) ) ; rangeSources . putAll ( desiredRange , preferred ) ; break ; } } if ( ! rangeSources . keySet ( ) . contains ( desiredRange ) ) throw new IllegalStateException ( "No sources found for " + desiredRange ) ; } return rangeSources ; }
Get a map of all ranges and their respective sources that are candidates for streaming the given ranges to us . For each range the list of sources is sorted by proximity relative to the given destAddress .
8,425
private Multimap < Range < Token > , InetAddress > getAllRangesWithStrictSourcesFor ( String table , Collection < Range < Token > > desiredRanges ) { assert tokens != null ; AbstractReplicationStrategy strat = Keyspace . open ( table ) . getReplicationStrategy ( ) ; TokenMetadata metadataClone = metadata . cloneOnlyTokenMap ( ) ; Multimap < Range < Token > , InetAddress > addressRanges = strat . getRangeAddresses ( metadataClone ) ; metadataClone . updateNormalTokens ( tokens , address ) ; Multimap < Range < Token > , InetAddress > pendingRangeAddresses = strat . getRangeAddresses ( metadataClone ) ; Multimap < Range < Token > , InetAddress > rangeSources = ArrayListMultimap . create ( ) ; for ( Range < Token > desiredRange : desiredRanges ) { for ( Map . Entry < Range < Token > , Collection < InetAddress > > preEntry : addressRanges . asMap ( ) . entrySet ( ) ) { if ( preEntry . getKey ( ) . contains ( desiredRange ) ) { Set < InetAddress > oldEndpoints = Sets . newHashSet ( preEntry . getValue ( ) ) ; Set < InetAddress > newEndpoints = Sets . newHashSet ( pendingRangeAddresses . get ( desiredRange ) ) ; if ( oldEndpoints . size ( ) == strat . getReplicationFactor ( ) ) { oldEndpoints . removeAll ( newEndpoints ) ; assert oldEndpoints . size ( ) == 1 : "Expected 1 endpoint but found " + oldEndpoints . size ( ) ; } rangeSources . put ( desiredRange , oldEndpoints . iterator ( ) . next ( ) ) ; } } Collection < InetAddress > addressList = rangeSources . get ( desiredRange ) ; if ( addressList == null || addressList . isEmpty ( ) ) throw new IllegalStateException ( "No sources found for " + desiredRange ) ; if ( addressList . size ( ) > 1 ) throw new IllegalStateException ( "Multiple endpoints found for " + desiredRange ) ; InetAddress sourceIp = addressList . iterator ( ) . next ( ) ; EndpointState sourceState = Gossiper . instance . getEndpointStateForEndpoint ( sourceIp ) ; if ( Gossiper . instance . isEnabled ( ) && ( sourceState == null || ! sourceState . isAlive ( ) ) ) throw new RuntimeException ( "A node required to move the data consistently is down (" + sourceIp + "). If you wish to move the data from a potentially inconsistent replica, restart the node with -Dcassandra.consistent.rangemovement=false" ) ; } return rangeSources ; }
Get a map of all ranges and the source that will be cleaned up once this bootstrapped node is added for the given ranges . For each range the list should only contain a single source . This allows us to consistently migrate data without violating consistency .
8,426
Multimap < String , Map . Entry < InetAddress , Collection < Range < Token > > > > toFetch ( ) { return toFetch ; }
For testing purposes
8,427
private void validate ( List < ByteBuffer > variables ) throws InvalidRequestException { if ( keyValidator . size ( ) < 1 ) throw new InvalidRequestException ( "You must specify a PRIMARY KEY" ) ; else if ( keyValidator . size ( ) > 1 ) throw new InvalidRequestException ( "You may only specify one PRIMARY KEY" ) ; AbstractType < ? > comparator ; try { cfProps . validate ( ) ; comparator = cfProps . getComparator ( ) ; } catch ( ConfigurationException e ) { throw new InvalidRequestException ( e . toString ( ) ) ; } catch ( SyntaxException e ) { throw new InvalidRequestException ( e . toString ( ) ) ; } for ( Map . Entry < Term , String > column : columns . entrySet ( ) ) { ByteBuffer name = column . getKey ( ) . getByteBuffer ( comparator , variables ) ; if ( keyAlias != null && keyAlias . equals ( name ) ) throw new InvalidRequestException ( "Invalid column name: " + column . getKey ( ) . getText ( ) + ", because it equals to the key_alias." ) ; } }
Perform validation of parsed params
8,428
public int recover ( ) throws IOException { FilenameFilter unmanagedFilesFilter = new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return CommitLogDescriptor . isValid ( name ) && ! instance . allocator . manages ( name ) ; } } ; for ( File file : new File ( DatabaseDescriptor . getCommitLogLocation ( ) ) . listFiles ( unmanagedFilesFilter ) ) { archiver . maybeArchive ( file . getPath ( ) , file . getName ( ) ) ; archiver . maybeWaitForArchiving ( file . getName ( ) ) ; } assert archiver . archivePending . isEmpty ( ) : "Not all commit log archive tasks were completed before restore" ; archiver . maybeRestoreArchive ( ) ; File [ ] files = new File ( DatabaseDescriptor . getCommitLogLocation ( ) ) . listFiles ( unmanagedFilesFilter ) ; int replayed = 0 ; if ( files . length == 0 ) { logger . info ( "No commitlog files found; skipping replay" ) ; } else { Arrays . sort ( files , new CommitLogSegmentFileComparator ( ) ) ; logger . info ( "Replaying {}" , StringUtils . join ( files , ", " ) ) ; replayed = recover ( files ) ; logger . info ( "Log replay complete, {} replayed mutations" , replayed ) ; for ( File f : files ) CommitLog . instance . allocator . recycleSegment ( f ) ; } allocator . enableReserveSegmentCreation ( ) ; return replayed ; }
Perform recovery on commit logs located in the directory specified by the config file .
8,429
public int recover ( File ... clogs ) throws IOException { CommitLogReplayer recovery = new CommitLogReplayer ( ) ; recovery . recover ( clogs ) ; return recovery . blockForWrites ( ) ; }
Perform recovery on a list of commit log files .
8,430
public void sync ( boolean syncAllSegments ) { CommitLogSegment current = allocator . allocatingFrom ( ) ; for ( CommitLogSegment segment : allocator . getActiveSegments ( ) ) { if ( ! syncAllSegments && segment . id > current . id ) return ; segment . sync ( ) ; } }
Forces a disk flush on the commit log files that need it . Blocking .
8,431
public ReplayPosition add ( Mutation mutation ) { assert mutation != null ; long size = Mutation . serializer . serializedSize ( mutation , MessagingService . current_version ) ; long totalSize = size + ENTRY_OVERHEAD_SIZE ; if ( totalSize > MAX_MUTATION_SIZE ) { throw new IllegalArgumentException ( String . format ( "Mutation of %s bytes is too large for the maxiumum size of %s" , totalSize , MAX_MUTATION_SIZE ) ) ; } Allocation alloc = allocator . allocate ( mutation , ( int ) totalSize ) ; try { PureJavaCrc32 checksum = new PureJavaCrc32 ( ) ; final ByteBuffer buffer = alloc . getBuffer ( ) ; DataOutputByteBuffer dos = new DataOutputByteBuffer ( buffer ) ; dos . writeInt ( ( int ) size ) ; checksum . update ( buffer , buffer . position ( ) - 4 , 4 ) ; buffer . putInt ( checksum . getCrc ( ) ) ; int start = buffer . position ( ) ; Mutation . serializer . serialize ( mutation , dos , MessagingService . current_version ) ; checksum . update ( buffer , start , ( int ) size ) ; buffer . putInt ( checksum . getCrc ( ) ) ; } catch ( IOException e ) { throw new FSWriteError ( e , alloc . getSegment ( ) . getPath ( ) ) ; } finally { alloc . markWritten ( ) ; } executor . finishWriteFor ( alloc ) ; return alloc . getReplayPosition ( ) ; }
Add a Mutation to the commit log .
8,432
public void discardCompletedSegments ( final UUID cfId , final ReplayPosition context ) { logger . debug ( "discard completed log segments for {}, column family {}" , context , cfId ) ; for ( Iterator < CommitLogSegment > iter = allocator . getActiveSegments ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { CommitLogSegment segment = iter . next ( ) ; segment . markClean ( cfId , context ) ; if ( segment . isUnused ( ) ) { logger . debug ( "Commit log segment {} is unused" , segment ) ; allocator . recycleSegment ( segment ) ; } else { logger . debug ( "Not safe to delete{} commit log segment {}; dirty is {}" , ( iter . hasNext ( ) ? "" : " active" ) , segment , segment . dirtyString ( ) ) ; } if ( segment . contains ( context ) ) break ; } }
Modifies the per - CF dirty cursors of any commit log segments for the column family according to the position given . Discards any commit log segments that are no longer used .
8,433
public void shutdownBlocking ( ) throws InterruptedException { executor . shutdown ( ) ; executor . awaitTermination ( ) ; allocator . shutdown ( ) ; allocator . awaitTermination ( ) ; }
Shuts down the threads used by the commit log blocking until completion .
8,434
public static Bounds < RowPosition > makeRowBounds ( Token left , Token right , IPartitioner partitioner ) { return new Bounds < RowPosition > ( left . minKeyBound ( partitioner ) , right . maxKeyBound ( partitioner ) , partitioner ) ; }
Compute a bounds of keys corresponding to a given bounds of token .
8,435
public double rankLatency ( float rank ) { if ( sample . length == 0 ) return 0 ; int index = ( int ) ( rank * sample . length ) ; if ( index >= sample . length ) index = sample . length - 1 ; return sample [ index ] * 0.000001d ; }
0 < rank < 1
8,436
private double maxScore ( List < InetAddress > endpoints ) { double maxScore = - 1.0 ; for ( InetAddress endpoint : endpoints ) { Double score = scores . get ( endpoint ) ; if ( score == null ) continue ; if ( score > maxScore ) maxScore = score ; } return maxScore ; }
Return the max score for the endpoint in the provided list or - 1 . 0 if no node have a score .
8,437
public static FSError findNested ( Throwable top ) { for ( Throwable t = top ; t != null ; t = t . getCause ( ) ) { if ( t instanceof FSError ) return ( FSError ) t ; } return null ; }
Unwraps the Throwable cause chain looking for an FSError instance
8,438
private static double hotness ( SSTableReader sstr ) { return sstr . getReadMeter ( ) == null ? 0.0 : sstr . getReadMeter ( ) . twoHourRate ( ) / sstr . estimatedKeys ( ) ; }
Returns the reads per second per key for this sstable or 0 . 0 if the sstable has no read meter
8,439
public static String unescapeSQLString ( String b ) { if ( b . charAt ( 0 ) == '\'' && b . charAt ( b . length ( ) - 1 ) == '\'' ) b = b . substring ( 1 , b . length ( ) - 1 ) ; return StringEscapeUtils . unescapeJava ( b ) ; }
Strips leading and trailing characters and handles and escaped characters such as \ n \ r etc .
8,440
public static IndexOperator getIndexOperator ( String operator ) { if ( operator . equals ( "=" ) ) { return IndexOperator . EQ ; } else if ( operator . equals ( ">=" ) ) { return IndexOperator . GTE ; } else if ( operator . equals ( ">" ) ) { return IndexOperator . GT ; } else if ( operator . equals ( "<" ) ) { return IndexOperator . LT ; } else if ( operator . equals ( "<=" ) ) { return IndexOperator . LTE ; } return null ; }
Returns IndexOperator from string representation
8,441
public static Set < String > getCfNamesByKeySpace ( KsDef keySpace ) { Set < String > names = new LinkedHashSet < String > ( ) ; for ( CfDef cfDef : keySpace . getCf_defs ( ) ) { names . add ( cfDef . getName ( ) ) ; } return names ; }
Returns set of column family names in specified keySpace .
8,442
public static KsDef getKeySpaceDef ( String keyspaceName , List < KsDef > keyspaces ) { keyspaceName = keyspaceName . toUpperCase ( ) ; for ( KsDef ksDef : keyspaces ) { if ( ksDef . name . toUpperCase ( ) . equals ( keyspaceName ) ) return ksDef ; } return null ; }
Parse the statement from cli and return KsDef
8,443
public Hlr getViewHlr ( final String hlrId ) throws GeneralException , UnauthorizedException , NotFoundException { if ( hlrId == null ) { throw new IllegalArgumentException ( "Hrl ID must be specified." ) ; } return messageBirdService . requestByID ( HLRPATH , hlrId , Hlr . class ) ; }
Retrieves the information of an existing HLR . You only need to supply the unique message id that was returned upon creation or receiving .
8,444
public MessageResponse sendMessage ( final Message message ) throws UnauthorizedException , GeneralException { return messageBirdService . sendPayLoad ( MESSAGESPATH , message , MessageResponse . class ) ; }
Send a message through the messagebird platform
8,445
public MessageResponse sendFlashMessage ( final String originator , final String body , final List < BigInteger > recipients ) throws UnauthorizedException , GeneralException { final Message message = new Message ( originator , body , recipients ) ; message . setType ( MsgType . flash ) ; return messageBirdService . sendPayLoad ( MESSAGESPATH , message , MessageResponse . class ) ; }
Convenient function to send a simple flash message to a list of recipients
8,446
public void deleteMessage ( final String id ) throws UnauthorizedException , GeneralException , NotFoundException { if ( id == null ) { throw new IllegalArgumentException ( "Message ID must be specified." ) ; } messageBirdService . deleteByID ( MESSAGESPATH , id ) ; }
Delete a message from the Messagebird server
8,447
public void deleteVoiceMessage ( final String id ) throws UnauthorizedException , GeneralException , NotFoundException { if ( id == null ) { throw new IllegalArgumentException ( "Message ID must be specified." ) ; } messageBirdService . deleteByID ( VOICEMESSAGESPATH , id ) ; }
Delete a voice message from the Messagebird server
8,448
public VoiceMessageList listVoiceMessages ( final Integer offset , final Integer limit ) throws UnauthorizedException , GeneralException { if ( offset != null && offset < 0 ) { throw new IllegalArgumentException ( "Offset must be > 0" ) ; } if ( limit != null && limit < 0 ) { throw new IllegalArgumentException ( "Limit must be > 0" ) ; } return messageBirdService . requestList ( VOICEMESSAGESPATH , offset , limit , VoiceMessageList . class ) ; }
List voice messages
8,449
void deleteContact ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Contact ID must be specified." ) ; } messageBirdService . deleteByID ( CONTACTPATH , id ) ; }
Deletes an existing contact . You only need to supply the unique id that was returned upon creation .
8,450
public Contact sendContact ( final ContactRequest contactRequest ) throws UnauthorizedException , GeneralException { return messageBirdService . sendPayLoad ( CONTACTPATH , contactRequest , Contact . class ) ; }
Creates a new contact object . MessageBird returns the created contact object with each request .
8,451
public Contact updateContact ( final String id , ContactRequest contactRequest ) throws UnauthorizedException , GeneralException { if ( id == null ) { throw new IllegalArgumentException ( "Contact ID must be specified." ) ; } String request = CONTACTPATH + "/" + id ; return messageBirdService . sendPayLoad ( "PATCH" , request , contactRequest , Contact . class ) ; }
Updates an existing contact . You only need to supply the unique id that was returned upon creation .
8,452
public Contact viewContact ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Contact ID must be specified." ) ; } return messageBirdService . requestByID ( CONTACTPATH , id , Contact . class ) ; }
Retrieves the information of an existing contact . You only need to supply the unique contact ID that was returned upon creation or receiving .
8,453
public void deleteGroup ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Group ID must be specified." ) ; } messageBirdService . deleteByID ( GROUPPATH , id ) ; }
Deletes an existing group . You only need to supply the unique id that was returned upon creation .
8,454
public void deleteGroupContact ( final String groupId , final String contactId ) throws NotFoundException , GeneralException , UnauthorizedException { if ( groupId == null ) { throw new IllegalArgumentException ( "Group ID must be specified." ) ; } if ( contactId == null ) { throw new IllegalArgumentException ( "Contact ID must be specified." ) ; } String id = String . format ( "%s%s/%s" , groupId , CONTACTPATH , contactId ) ; messageBirdService . deleteByID ( GROUPPATH , id ) ; }
Removes a contact from group . You need to supply the IDs of the group and contact . Does not delete the contact .
8,455
public Group sendGroup ( final GroupRequest groupRequest ) throws UnauthorizedException , GeneralException { return messageBirdService . sendPayLoad ( GROUPPATH , groupRequest , Group . class ) ; }
Creates a new group object . MessageBird returns the created group object with each request .
8,456
public void sendGroupContact ( final String groupId , final String [ ] contactIds ) throws NotFoundException , GeneralException , UnauthorizedException { String path = String . format ( "%s%s?%s" , groupId , CONTACTPATH , getQueryString ( contactIds ) ) ; messageBirdService . requestByID ( GROUPPATH , path , null ) ; }
Adds contact to group . You need to supply the IDs of the group and contact .
8,457
public Group updateGroup ( final String id , final GroupRequest groupRequest ) throws UnauthorizedException , GeneralException { if ( id == null ) { throw new IllegalArgumentException ( "Group ID must be specified." ) ; } String path = String . format ( "%s/%s" , GROUPPATH , id ) ; return messageBirdService . sendPayLoad ( "PATCH" , path , groupRequest , Group . class ) ; }
Updates an existing group . You only need to supply the unique ID that was returned upon creation .
8,458
public Group viewGroup ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Group ID must be specified." ) ; } return messageBirdService . requestByID ( GROUPPATH , id , Group . class ) ; }
Retrieves the information of an existing group . You only need to supply the unique group ID that was returned upon creation or receiving .
8,459
public Conversation viewConversation ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Id must be specified" ) ; } String url = CONVERSATIONS_BASE_URL + CONVERSATION_PATH ; return messageBirdService . requestByID ( url , id , Conversation . class ) ; }
Gets a single conversation .
8,460
public Conversation updateConversation ( final String id , final ConversationStatus status ) throws UnauthorizedException , GeneralException { if ( id == null ) { throw new IllegalArgumentException ( "Id must be specified." ) ; } String url = String . format ( "%s%s/%s" , CONVERSATIONS_BASE_URL , CONVERSATION_PATH , id ) ; return messageBirdService . sendPayLoad ( "PATCH" , url , status , Conversation . class ) ; }
Updates a conversation .
8,461
public ConversationList listConversations ( final int offset , final int limit ) throws UnauthorizedException , GeneralException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_PATH ; return messageBirdService . requestList ( url , offset , limit , ConversationList . class ) ; }
Gets a Conversation listing with specified pagination options .
8,462
public Conversation startConversation ( ConversationStartRequest request ) throws UnauthorizedException , GeneralException { String url = String . format ( "%s%s/start" , CONVERSATIONS_BASE_URL , CONVERSATION_PATH ) ; return messageBirdService . sendPayLoad ( url , request , Conversation . class ) ; }
Starts a conversation by sending an initial message .
8,463
public ConversationMessageList listConversationMessages ( final String conversationId , final int offset , final int limit ) throws UnauthorizedException , GeneralException { String url = String . format ( "%s%s/%s%s" , CONVERSATIONS_BASE_URL , CONVERSATION_PATH , conversationId , CONVERSATION_MESSAGE_PATH ) ; return messageBirdService . requestList ( url , offset , limit , ConversationMessageList . class ) ; }
Gets a ConversationMessage listing with specified pagination options .
8,464
public ConversationMessageList listConversationMessages ( final String conversationId ) throws UnauthorizedException , GeneralException { final int offset = 0 ; final int limit = 10 ; return listConversationMessages ( conversationId , offset , limit ) ; }
Gets a ConversationMessage listing with default pagination options .
8,465
public ConversationMessage viewConversationMessage ( final String messageId ) throws NotFoundException , GeneralException , UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_MESSAGE_PATH ; return messageBirdService . requestByID ( url , messageId , ConversationMessage . class ) ; }
Gets a single message .
8,466
public ConversationMessage sendConversationMessage ( final String conversationId , final ConversationMessageRequest request ) throws UnauthorizedException , GeneralException { String url = String . format ( "%s%s/%s%s" , CONVERSATIONS_BASE_URL , CONVERSATION_PATH , conversationId , CONVERSATION_MESSAGE_PATH ) ; return messageBirdService . sendPayLoad ( url , request , ConversationMessage . class ) ; }
Sends a message to an existing Conversation .
8,467
public void deleteConversationWebhook ( final String webhookId ) throws NotFoundException , GeneralException , UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH ; messageBirdService . deleteByID ( url , webhookId ) ; }
Deletes a webhook .
8,468
public ConversationWebhook sendConversationWebhook ( final ConversationWebhookRequest request ) throws UnauthorizedException , GeneralException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH ; return messageBirdService . sendPayLoad ( url , request , ConversationWebhook . class ) ; }
Creates a new webhook .
8,469
public ConversationWebhook viewConversationWebhook ( final String webhookId ) throws NotFoundException , GeneralException , UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH ; return messageBirdService . requestByID ( url , webhookId , ConversationWebhook . class ) ; }
Gets a single webhook .
8,470
ConversationWebhookList listConversationWebhooks ( final int offset , final int limit ) throws UnauthorizedException , GeneralException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_WEBHOOK_PATH ; return messageBirdService . requestList ( url , offset , limit , ConversationWebhookList . class ) ; }
Gets a ConversationWebhook listing with the specified pagination options .
8,471
public VoiceCallResponse sendVoiceCall ( final VoiceCall voiceCall ) throws UnauthorizedException , GeneralException { if ( voiceCall . getSource ( ) == null ) { throw new IllegalArgumentException ( "Source of voice call must be specified." ) ; } if ( voiceCall . getDestination ( ) == null ) { throw new IllegalArgumentException ( "Destination of voice call must be specified." ) ; } if ( voiceCall . getCallFlow ( ) == null ) { throw new IllegalArgumentException ( "Call flow of voice call must be specified." ) ; } String url = String . format ( "%s%s" , VOICE_CALLS_BASE_URL , VOICECALLSPATH ) ; return messageBirdService . sendPayLoad ( url , voiceCall , VoiceCallResponse . class ) ; }
Function for voice call to a number
8,472
public VoiceCallResponseList listAllVoiceCalls ( Integer page , Integer pageSize ) throws GeneralException , UnauthorizedException { String url = String . format ( "%s%s" , VOICE_CALLS_BASE_URL , VOICECALLSPATH ) ; return messageBirdService . requestList ( url , new PagedPaging ( page , pageSize ) , VoiceCallResponseList . class ) ; }
Function to list all voice calls
8,473
public VoiceCallResponse viewVoiceCall ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Voice Message ID must be specified." ) ; } String url = String . format ( "%s%s" , VOICE_CALLS_BASE_URL , VOICECALLSPATH ) ; return messageBirdService . requestByID ( url , id , VoiceCallResponse . class ) ; }
Function to view voice call by id
8,474
public void deleteVoiceCall ( final String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Voice Message ID must be specified." ) ; } String url = String . format ( "%s%s" , VOICE_CALLS_BASE_URL , VOICECALLSPATH ) ; messageBirdService . deleteByID ( url , id ) ; }
Function to delete voice call by id
8,475
public VoiceCallLegResponse viewCallLegsByCallId ( String callId , Integer page , Integer pageSize ) throws UnsupportedEncodingException , UnauthorizedException , GeneralException { if ( callId == null ) { throw new IllegalArgumentException ( "Voice call ID must be specified." ) ; } String url = String . format ( "%s%s/%s%s" , VOICE_CALLS_BASE_URL , VOICECALLSPATH , urlEncode ( callId ) , VOICELEGS_SUFFIX_PATH ) ; return messageBirdService . requestList ( url , new PagedPaging ( page , pageSize ) , VoiceCallLegResponse . class ) ; }
Retrieves a listing of all legs .
8,476
public VoiceCallLeg viewCallLegByCallIdAndLegId ( final String callId , String legId ) throws UnsupportedEncodingException , NotFoundException , GeneralException , UnauthorizedException { if ( callId == null ) { throw new IllegalArgumentException ( "Voice call ID must be specified." ) ; } if ( legId == null ) { throw new IllegalArgumentException ( "Leg ID must be specified." ) ; } String url = String . format ( "%s%s/%s%s" , VOICE_CALLS_BASE_URL , VOICECALLSPATH , urlEncode ( callId ) , VOICELEGS_SUFFIX_PATH ) ; VoiceCallLegResponse response = messageBirdService . requestByID ( url , legId , VoiceCallLegResponse . class ) ; if ( response . getData ( ) . size ( ) == 1 ) { return response . getData ( ) . get ( 0 ) ; } else { throw new NotFoundException ( "No such leg" , new LinkedList < ErrorReport > ( ) ) ; } }
Retrieves a leg resource . The parameters are the unique ID of the call and of the leg that were returned upon their respective creation .
8,477
public WebhookResponseData createWebHook ( Webhook webhook ) throws UnauthorizedException , GeneralException { if ( webhook . getTitle ( ) == null ) { throw new IllegalArgumentException ( "Title of webhook must be specified." ) ; } if ( webhook . getUrl ( ) == null ) { throw new IllegalArgumentException ( "URL of webhook must be specified." ) ; } String url = String . format ( "%s%s" , VOICE_CALLS_BASE_URL , WEBHOOKS ) ; return messageBirdService . sendPayLoad ( url , webhook , WebhookResponseData . class ) ; }
Function to create web hook
8,478
public WebhookResponseData viewWebHook ( String id ) throws NotFoundException , GeneralException , UnauthorizedException { if ( id == null ) { throw new IllegalArgumentException ( "Id of webHook must be specified." ) ; } String url = String . format ( "%s%s" , VOICE_CALLS_BASE_URL , WEBHOOKS ) ; return messageBirdService . requestByID ( url , id , WebhookResponseData . class ) ; }
Function to view webhook
8,479
private byte [ ] computeSignature ( Request request ) { String timestampAndQuery = request . getTimestamp ( ) + '\n' + request . getSortedQueryParameters ( ) + '\n' ; byte [ ] timestampAndQueryBytes = timestampAndQuery . getBytes ( CHARSET_UTF8 ) ; byte [ ] bodyHashBytes = getSha256Hash ( request . getData ( ) ) ; return getHmacSha256Signature ( appendArrays ( timestampAndQueryBytes , bodyHashBytes ) ) ; }
Computes the signature for a request instance .
8,480
private byte [ ] appendArrays ( byte [ ] first , byte [ ] second ) { byte [ ] result = new byte [ first . length + second . length ] ; System . arraycopy ( first , 0 , result , 0 , first . length ) ; System . arraycopy ( second , 0 , result , first . length , second . length ) ; return result ; }
Stitches the two arrays together and returns a new one .
8,481
< P > APIResponse doRequest ( final String method , final String url , final P payload ) throws GeneralException { HttpURLConnection connection = null ; InputStream inputStream = null ; if ( METHOD_PATCH . equalsIgnoreCase ( method ) ) { allowPatchRequestsIfNeeded ( ) ; } try { connection = getConnection ( url , payload , method ) ; int status = connection . getResponseCode ( ) ; if ( APIResponse . isSuccessStatus ( status ) ) { inputStream = connection . getInputStream ( ) ; } else { inputStream = connection . getErrorStream ( ) ; } return new APIResponse ( readToEnd ( inputStream ) , status ) ; } catch ( IOException ioe ) { throw new GeneralException ( ioe ) ; } finally { saveClose ( inputStream ) ; if ( connection != null ) { connection . disconnect ( ) ; } } }
Actually sends a HTTP request and returns its body and HTTP status code .
8,482
private static String [ ] getAllowedMethods ( String [ ] existingMethods ) { int listCapacity = existingMethods . length + 1 ; List < String > allowedMethods = new ArrayList < > ( listCapacity ) ; allowedMethods . addAll ( Arrays . asList ( existingMethods ) ) ; allowedMethods . add ( METHOD_PATCH ) ; return allowedMethods . toArray ( new String [ 0 ] ) ; }
Appends PATCH to the provided array .
8,483
private String readToEnd ( InputStream inputStream ) { Scanner scanner = new Scanner ( inputStream ) . useDelimiter ( "\\A" ) ; return scanner . hasNext ( ) ? scanner . next ( ) : "" ; }
Reads the stream until it has no more bytes and returns a UTF - 8 encoded string representation .
8,484
private boolean isURLAbsolute ( String url ) { for ( String protocol : PROTOCOLS ) { if ( url . startsWith ( protocol ) ) { return true ; } } return false ; }
Attempts determining whether the provided URL is an absolute one based on the scheme .
8,485
public < P > HttpURLConnection getConnection ( final String serviceUrl , final P postData , final String requestType ) throws IOException { if ( requestType == null || ! REQUEST_METHODS . contains ( requestType ) ) { throw new IllegalArgumentException ( String . format ( REQUEST_METHOD_NOT_ALLOWED , requestType ) ) ; } if ( postData == null && "POST" . equals ( requestType ) ) { throw new IllegalArgumentException ( "POST detected without a payload, please supply a payload with a POST request" ) ; } final URL restService = new URL ( serviceUrl ) ; final HttpURLConnection connection ; if ( proxy != null ) { connection = ( HttpURLConnection ) restService . openConnection ( proxy ) ; } else { connection = ( HttpURLConnection ) restService . openConnection ( ) ; } connection . setDoInput ( true ) ; connection . setRequestProperty ( "Accept" , "application/json" ) ; connection . setUseCaches ( false ) ; connection . setRequestProperty ( "charset" , "utf-8" ) ; connection . setRequestProperty ( "Connection" , "close" ) ; connection . setRequestProperty ( "Authorization" , "AccessKey " + accessKey ) ; connection . setRequestProperty ( "User-agent" , userAgentString ) ; if ( "POST" . equals ( requestType ) || "PATCH" . equals ( requestType ) ) { connection . setRequestMethod ( requestType ) ; connection . setDoOutput ( true ) ; connection . setRequestProperty ( "Content-Type" , "application/json" ) ; ObjectMapper mapper = new ObjectMapper ( ) ; mapper . setSerializationInclusion ( Include . NON_NULL ) ; DateFormat df = getDateFormat ( ) ; mapper . setDateFormat ( df ) ; final String json = mapper . writeValueAsString ( postData ) ; connection . getOutputStream ( ) . write ( json . getBytes ( String . valueOf ( StandardCharsets . UTF_8 ) ) ) ; } else if ( "DELETE" . equals ( requestType ) ) { connection . setDoOutput ( false ) ; connection . setRequestMethod ( "DELETE" ) ; connection . setRequestProperty ( "Content-Type" , "text/plain" ) ; } else { connection . setDoOutput ( false ) ; connection . setRequestMethod ( "GET" ) ; connection . setRequestProperty ( "Content-Type" , "text/plain" ) ; } return connection ; }
Create a HttpURLConnection connection object
8,486
private List < ErrorReport > getErrorReportOrNull ( final String body ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; try { JsonNode jsonNode = objectMapper . readValue ( body , JsonNode . class ) ; ErrorReport [ ] errors = objectMapper . readValue ( jsonNode . get ( "errors" ) . toString ( ) , ErrorReport [ ] . class ) ; List < ErrorReport > result = Arrays . asList ( errors ) ; if ( result . isEmpty ( ) ) { return null ; } return result ; } catch ( IOException e ) { return null ; } }
Get the MessageBird error report data .
8,487
private String getPathVariables ( final Map < String , Object > map ) { final StringBuilder bpath = new StringBuilder ( ) ; for ( Map . Entry < String , Object > param : map . entrySet ( ) ) { if ( bpath . length ( ) > 1 ) { bpath . append ( "&" ) ; } try { bpath . append ( URLEncoder . encode ( param . getKey ( ) , String . valueOf ( StandardCharsets . UTF_8 ) ) ) . append ( "=" ) . append ( URLEncoder . encode ( String . valueOf ( param . getValue ( ) ) , String . valueOf ( StandardCharsets . UTF_8 ) ) ) ; } catch ( UnsupportedEncodingException exception ) { } } return bpath . toString ( ) ; }
Build a path variable for GET requests
8,488
public void setPremiumSMS ( Object shortcode , Object keyword , Object tariff , Object mid ) { final Map < String , Object > premiumSMSConfig = new LinkedHashMap < String , Object > ( 4 ) ; premiumSMSConfig . put ( "shortcode" , shortcode ) ; premiumSMSConfig . put ( "keyword" , keyword ) ; premiumSMSConfig . put ( "tariff" , tariff ) ; premiumSMSConfig . put ( "mid" , mid ) ; this . typeDetails = premiumSMSConfig ; this . type = MsgType . premium ; }
Setup premium SMS type
8,489
public static ConversationHsmLocalizableParameter defaultValue ( final String defaultValue ) { ConversationHsmLocalizableParameter parameter = new ConversationHsmLocalizableParameter ( ) ; parameter . defaultValue = defaultValue ; return parameter ; }
Gets a parameter that does a simple replacement without localization .
8,490
public static ConversationHsmLocalizableParameter currency ( final String defaultValue , final String code , final int amount ) { ConversationHsmLocalizableParameter parameter = new ConversationHsmLocalizableParameter ( ) ; parameter . defaultValue = defaultValue ; parameter . currency = new ConversationHsmLocalizableParameterCurrency ( code , amount ) ; return parameter ; }
Gets a parameter that localizes a currency .
8,491
public static InetAddress getInetAddress ( String hostName ) { try { return InetAddress . getByName ( hostName ) ; } catch ( UnknownHostException e ) { throw new IllegalStateException ( "Unknown host: " + e . getMessage ( ) + ". Make sure you have specified the 'GelfUDPAppender.remoteHost' property correctly in your logback.xml'" ) ; } }
Gets the Inet address for the GelfUDPAppender . remoteHost and gives a specialised error message if an exception is thrown
8,492
private Map < String , Object > mapFields ( E logEvent ) { Map < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( "host" , host ) ; map . put ( "full_message" , fullMessageLayout . doLayout ( logEvent ) ) ; map . put ( "short_message" , shortMessageLayout . doLayout ( logEvent ) ) ; stackTraceField ( map , logEvent ) ; map . put ( "timestamp" , logEvent . getTimeStamp ( ) / 1000.0 ) ; map . put ( "version" , "1.1" ) ; map . put ( "level" , LevelToSyslogSeverity . convert ( logEvent ) ) ; additionalFields ( map , logEvent ) ; staticAdditionalFields ( map ) ; return map ; }
Creates a map of properties that represent the GELF message .
8,493
private void additionalFields ( Map < String , Object > map , ILoggingEvent eventObject ) { if ( useLoggerName ) { map . put ( "_loggerName" , eventObject . getLoggerName ( ) ) ; } if ( useMarker && eventHasMarker ( eventObject ) ) { map . put ( "_marker" , eventObject . getMarker ( ) . toString ( ) ) ; } if ( useThreadName ) { map . put ( "_threadName" , eventObject . getThreadName ( ) ) ; } Map < String , String > mdc = eventObject . getMDCPropertyMap ( ) ; if ( mdc != null ) { if ( includeFullMDC ) { for ( Entry < String , String > e : mdc . entrySet ( ) ) { if ( additionalFields . containsKey ( e . getKey ( ) ) ) { map . put ( additionalFields . get ( e . getKey ( ) ) , convertFieldType ( e . getValue ( ) , additionalFields . get ( e . getKey ( ) ) ) ) ; } else { map . put ( "_" + e . getKey ( ) , convertFieldType ( e . getValue ( ) , "_" + e . getKey ( ) ) ) ; } } } else { for ( String key : additionalFields . keySet ( ) ) { String field = mdc . get ( key ) ; if ( field != null ) { map . put ( additionalFields . get ( key ) , convertFieldType ( field , key ) ) ; } } } } }
Converts the additional fields into proper GELF JSON
8,494
public void addAdditionalField ( String keyValue ) { String [ ] splitted = keyValue . split ( ":" ) ; if ( splitted . length != 2 ) { throw new IllegalArgumentException ( "additionalField must be of the format key:value, where key is the MDC " + "key, and value is the GELF field name. But found '" + keyValue + "' instead." ) ; } additionalFields . put ( splitted [ 0 ] , splitted [ 1 ] ) ; }
Add an additional field . This is mainly here for compatibility with logback . xml
8,495
public void addStaticAdditionalField ( String keyValue ) { String [ ] splitted = keyValue . split ( ":" ) ; if ( splitted . length != 2 ) { throw new IllegalArgumentException ( "staticAdditionalField must be of the format key:value, where key is the " + "additional field key (therefore should have a leading underscore), and value is a static string. " + "e.g. _node_name:www013" ) ; } staticFields . put ( splitted [ 0 ] , splitted [ 1 ] ) ; }
Add a staticAdditional field . This is mainly here for compatibility with logback . xml
8,496
public byte [ ] get ( ) { String timestamp = String . valueOf ( System . nanoTime ( ) ) ; byte [ ] digestString = ( hostname + timestamp ) . getBytes ( ) ; return Arrays . copyOf ( messageDigest . digest ( digestString ) , messageIdLength ) ; }
Creates a message id that should be unique on every call . The message ID needs to be unique for every message . If a message is chunked then each chunk in a message needs the same message ID .
8,497
public static ObjectComparatorFactory newInstance ( final String objectComparatorFactoryClassName ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { return ( ObjectComparatorFactory ) Class . forName ( objectComparatorFactoryClassName ) . newInstance ( ) ; }
Create a new instance of a the specified factory class .
8,498
public static ObjectComparatorFactory newInstance ( final String objectComparatorFactoryClassName , final ClassLoader classLoader ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { return ( ObjectComparatorFactory ) Class . forName ( objectComparatorFactoryClassName , true , classLoader ) . newInstance ( ) ; }
Create a new instance of a the specified factory class by using the specified class loader .
8,499
public static Initializer defaultInitializer ( ) { return newInitializer ( ) . setCloseConcurrency ( 0 ) . setTestOnLogicalOpen ( false ) . setTestOnLogicalClose ( false ) . setIncompleteTransactionOnClosePolicy ( ConnectionPoolConnection . IncompleteTransactionPolicy . REPORT ) . setOpenStatementOnClosePolicy ( ConnectionPoolConnection . OpenStatementPolicy . REPORT ) . setForceRealClosePolicy ( ConnectionPoolConnection . ForceRealClosePolicy . CONNECTION_WITH_LIMIT ) . setActivityTimeoutPolicy ( ConnectionPoolConnection . ActivityTimeoutPolicy . LOG ) . setCloseTimeLimitMillis ( 10 * 1000L ) . setActiveTimeout ( 60 , TimeUnit . SECONDS ) . setConnectionLifetime ( 15 , TimeUnit . MINUTES ) . setMaxConcurrentReconnects ( 2 ) . setMaxReconnectDelay ( 1 , TimeUnit . MINUTES ) . setActiveTimeoutMonitorFrequency ( 30 , TimeUnit . SECONDS ) ; }
Creates a segment initializer with default values .