idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
132,100
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 .
132,101
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 .
132,102
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 , f...
Dump the inter arrival times for examination if necessary .
132,103
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 .
132,104
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
132,105
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 ntzTab...
Returns number of trailing zeros in a 64 bit long value .
132,106
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 ] ...
Returns number of trailing zeros in a 32 bit int value .
132,107
public boolean intersects ( Iterable < Range < T > > ranges ) { for ( Range < T > range2 : ranges ) { if ( range2 . intersects ( this ) ) return true ; } return false ; }
return true if
132,108
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 ...
type provided separately to support recursive call for mixed command with each command type it is performing
132,109
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 .
132,110
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 .
132,111
public static void setup ( ) { if ( DatabaseDescriptor . getAuthenticator ( ) instanceof AllowAllAuthenticator ) return ; setupAuthKeyspace ( ) ; setupTable ( USERS_CF , USERS_CF_SCHEMA ) ; DatabaseDescriptor . getAuthenticator ( ) . setup ( ) ; DatabaseDescriptor . getAuthorizer ( ) . setup ( ) ; MigrationManager . in...
Sets up Authenticator and Authorizer .
132,112
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 .
132,113
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 ...
Set up table from given CREATE TABLE statement under system_auth keyspace if not already done so .
132,114
private Multimap < Range < Token > , InetAddress > getAllRangesWithSourcesFor ( String keyspaceName , Collection < Range < Token > > desiredRanges ) { AbstractReplicationStrategy strat = Keyspace . open ( keyspaceName ) . getReplicationStrategy ( ) ; Multimap < Range < Token > , InetAddress > rangeAddresses = strat . g...
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 .
132,115
private Multimap < Range < Token > , InetAddress > getAllRangesWithStrictSourcesFor ( String table , Collection < Range < Token > > desiredRanges ) { assert tokens != null ; AbstractReplicationStrategy strat = Keyspace . open ( table ) . getReplicationStrategy ( ) ; TokenMetadata metadataClone = metadata . cloneOnlyTok...
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 .
132,116
Multimap < String , Map . Entry < InetAddress , Collection < Range < Token > > > > toFetch ( ) { return toFetch ; }
For testing purposes
132,117
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" ) ; Abst...
Perform validation of parsed params
132,118
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 . getCommitLogL...
Perform recovery on commit logs located in the directory specified by the config file .
132,119
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 .
132,120
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 .
132,121
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 ( "...
Add a Mutation to the commit log .
132,122
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 ( ) ; ) { CommitLogSegmen...
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 .
132,123
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 .
132,124
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 .
132,125
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
132,126
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 .
132,127
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
132,128
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
132,129
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 .
132,130
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...
Returns IndexOperator from string representation
132,131
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 .
132,132
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
132,133
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 .
132,134
public MessageResponse sendMessage ( final Message message ) throws UnauthorizedException , GeneralException { return messageBirdService . sendPayLoad ( MESSAGESPATH , message , MessageResponse . class ) ; }
Send a message through the messagebird platform
132,135
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 . se...
Convenient function to send a simple flash message to a list of recipients
132,136
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
132,137
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
132,138
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...
List voice messages
132,139
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 .
132,140
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 .
132,141
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" , ...
Updates an existing contact . You only need to supply the unique id that was returned upon creation .
132,142
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 .
132,143
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 .
132,144
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 ( "Contac...
Removes a contact from group . You need to supply the IDs of the group and contact . Does not delete the contact .
132,145
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 .
132,146
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 .
132,147
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 . sendPayLo...
Updates an existing group . You only need to supply the unique ID that was returned upon creation .
132,148
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 .
132,149
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 , i...
Gets a single conversation .
132,150
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...
Updates a conversation .
132,151
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 .
132,152
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 .
132,153
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 m...
Gets a ConversationMessage listing with specified pagination options .
132,154
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 .
132,155
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 .
132,156
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 ...
Sends a message to an existing Conversation .
132,157
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 .
132,158
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 .
132,159
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 .
132,160
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 .
132,161
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 IllegalArgument...
Function for voice call to a number
132,162
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 ) , VoiceCallResponseLi...
Function to list all voice calls
132,163
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 m...
Function to view voice call by id
132,164
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 ...
Function to delete voice call by id
132,165
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...
Retrieves a listing of all legs .
132,166
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 n...
Retrieves a leg resource . The parameters are the unique ID of the call and of the leg that were returned upon their respective creation .
132,167
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 webho...
Function to create web hook
132,168
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 messageBirdServi...
Function to view webhook
132,169
private byte [ ] computeSignature ( Request request ) { String timestampAndQuery = request . getTimestamp ( ) + '\n' + request . getSortedQueryParameters ( ) + '\n' ; byte [ ] timestampAndQueryBytes = timestampAndQuery . getBytes ( CHARSET_UTF8 ) ; byte [ ] bodyHashBytes = getSha256Hash ( request . getData ( ) ) ; retu...
Computes the signature for a request instance .
132,170
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 .
132,171
< 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 , payloa...
Actually sends a HTTP request and returns its body and HTTP status code .
132,172
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 allowedMet...
Appends PATCH to the provided array .
132,173
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 .
132,174
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 .
132,175
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 ) ) ; }...
Create a HttpURLConnection connection object
132,176
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 [ ] ....
Get the MessageBird error report data .
132,177
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 ( ) , St...
Build a path variable for GET requests
132,178
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 ( "ta...
Setup premium SMS type
132,179
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 .
132,180
public static ConversationHsmLocalizableParameter currency ( final String defaultValue , final String code , final int amount ) { ConversationHsmLocalizableParameter parameter = new ConversationHsmLocalizableParameter ( ) ; parameter . defaultValue = defaultValue ; parameter . currency = new ConversationHsmLocalizableP...
Gets a parameter that localizes a currency .
132,181
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 lo...
Gets the Inet address for the GelfUDPAppender . remoteHost and gives a specialised error message if an exception is thrown
132,182
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 ) ) ; stackTraceF...
Creates a map of properties that represent the GELF message .
132,183
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 ( useThrea...
Converts the additional fields into proper GELF JSON
132,184
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 + "' inste...
Add an additional field . This is mainly here for compatibility with logback . xml
132,185
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)...
Add a staticAdditional field . This is mainly here for compatibility with logback . xml
132,186
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 .
132,187
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 .
132,188
public static ObjectComparatorFactory newInstance ( final String objectComparatorFactoryClassName , final ClassLoader classLoader ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { return ( ObjectComparatorFactory ) Class . forName ( objectComparatorFactoryClassName , true , classLoader...
Create a new instance of a the specified factory class by using the specified class loader .
132,189
public static Initializer defaultInitializer ( ) { return newInitializer ( ) . setCloseConcurrency ( 0 ) . setTestOnLogicalOpen ( false ) . setTestOnLogicalClose ( false ) . setIncompleteTransactionOnClosePolicy ( ConnectionPoolConnection . IncompleteTransactionPolicy . REPORT ) . setOpenStatementOnClosePolicy ( Connec...
Creates a segment initializer with default values .
132,190
private void reopen ( final ConnectionPoolConnection conn ) { if ( isActive ) { if ( conn . reopenAttempts == 0 ) { conn . reopenAttempts ++ ; reopenService . execute ( new Reopener ( conn ) ) ; } else { long delayMillis = 100L * conn . reopenAttempts ; if ( delayMillis > maxReconnectDelayMillis ) { delayMillis = maxRe...
Schedule connection reopen .
132,191
final void close ( final ConnectionPoolConnection conn ) { if ( closeQueue != null ) { closeQueue . add ( conn ) ; } else { closer . close ( conn ) ; } }
Adds a connection to the close queue .
132,192
final String getPassword ( ) { if ( passwordSource == null ) { return dbConnection . password ; } else { String usePassword = passwordSource . getPassword ( dbConnection . name ) ; if ( ! Strings . isNullOrEmpty ( usePassword ) ) { return usePassword ; } else { usePassword = passwordSource . getPassword ( dbConnection ...
Gets the password for connection creation .
132,193
private Connection createRealConnection ( final long timeoutMillis ) throws SQLException { if ( timeoutMillis < 1L ) { String usePassword = getPassword ( ) ; Connection conn = dbConnection . datasource == null ? DriverManager . getConnection ( dbConnection . connectionString , dbConnection . user , usePassword ) : dbCo...
Creates a real database connection failing if one is not obtained in the specified time .
132,194
final void activate ( ) throws SQLException { for ( ConnectionPoolConnection conn : connections ) { conn . forceRealClose ( ) ; conn . realOpen ( ) ; conn . logicalClose ( true ) ; } if ( closeQueue != null ) { closeQueue . clear ( ) ; } availableQueue . clear ( ) ; reopenExecutor . getQueue ( ) . clear ( ) ; List < Co...
Activates the segment by opening and testing all connections .
132,195
final boolean isIdle ( ) { for ( ConnectionPoolConnection conn : connections ) { if ( conn . state . get ( ) == ConnectionPoolConnection . STATE_OPEN ) { return false ; } } return true ; }
Determine if this segment is currently idle .
132,196
final void deactivateNow ( ) { isActive = false ; stats . deactivate ( ) ; availableQueue . clear ( ) ; reopenExecutor . getQueue ( ) . clear ( ) ; for ( ConnectionPoolConnection conn : connections ) { conn . forceRealClose ( ) ; conn . state . set ( ConnectionPoolConnection . STATE_DISCONNECTED ) ; } }
Deactivates the pool immediately - real - closing all connections out from under the logical connections .
132,197
public final int getActiveConnectionCount ( ) { if ( ! isActive ) { return 0 ; } int count = 0 ; for ( ConnectionPoolConnection conn : connections ) { if ( conn . state . get ( ) != ConnectionPoolConnection . STATE_AVAILABLE ) { count ++ ; } } return count ; }
Gets the number of active connections .
132,198
void logError ( final String message ) { if ( logger != null ) { try { StringBuilder buf = new StringBuilder ( name ) ; buf . append ( ":" ) ; buf . append ( message ) ; logger . error ( buf . toString ( ) ) ; } catch ( Throwable t ) { } } }
Logs an error message .
132,199
static final String getStack ( final boolean filter ) { StringBuilder buf = new StringBuilder ( ) ; StackTraceElement [ ] stack = Thread . currentThread ( ) . getStackTrace ( ) ; for ( int i = 2 ; i < stack . length ; i ++ ) { if ( ! filter ) { buf . append ( stack [ i ] . toString ( ) ) ; buf . append ( NEW_LINE ) ; }...
Gets the current stack as a string .