idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,700
protected void channelRead0 ( ChannelHandlerContext ctx , FullBinaryMemcacheResponse msg ) throws Exception { switch ( msg . getStatus ( ) ) { case SUCCESS : originalPromise . setSuccess ( ) ; ctx . pipeline ( ) . remove ( this ) ; ctx . fireChannelActive ( ) ; break ; case ACCESS_ERROR : originalPromise . setFailure ( new AuthenticationException ( "Authentication failure on Select Bucket command" ) ) ; break ; case NOTFOUND_ERROR : originalPromise . setFailure ( new AuthenticationException ( "Bucket not found on Select Bucket command" ) ) ; break ; default : originalPromise . setFailure ( new AuthenticationException ( "Unhandled select bucket status: " + msg . getStatus ( ) ) ) ; } }
Handles incoming Select bucket responses .
5,701
private static FullMemcacheMessage toFullMessage ( final MemcacheMessage msg ) { if ( msg instanceof FullMemcacheMessage ) { return ( ( FullMemcacheMessage ) msg ) . retain ( ) ; } FullMemcacheMessage fullMsg ; if ( msg instanceof BinaryMemcacheRequest ) { fullMsg = toFullRequest ( ( BinaryMemcacheRequest ) msg , Unpooled . EMPTY_BUFFER ) ; } else if ( msg instanceof BinaryMemcacheResponse ) { fullMsg = toFullResponse ( ( BinaryMemcacheResponse ) msg , Unpooled . EMPTY_BUFFER ) ; } else { throw new IllegalStateException ( ) ; } return fullMsg ; }
Convert a invalid message into a full message .
5,702
private void repeatConfigUntilUnsubscribed ( final String name , Observable < BucketStreamingResponse > response ) { response . flatMap ( new Func1 < BucketStreamingResponse , Observable < ProposedBucketConfigContext > > ( ) { public Observable < ProposedBucketConfigContext > call ( final BucketStreamingResponse response ) { LOGGER . debug ( "Config stream started for {} on {}." , name , response . host ( ) ) ; return response . configs ( ) . map ( new Func1 < String , ProposedBucketConfigContext > ( ) { public ProposedBucketConfigContext call ( String s ) { String raw = s . replace ( "$HOST" , response . host ( ) ) ; return new ProposedBucketConfigContext ( name , raw , NetworkAddress . create ( response . host ( ) ) ) ; } } ) . doOnCompleted ( new Action0 ( ) { public void call ( ) { LOGGER . debug ( "Config stream ended for {} on {}." , name , response . host ( ) ) ; } } ) ; } } ) . repeatWhen ( new Func1 < Observable < ? extends Void > , Observable < ? > > ( ) { public Observable < ? > call ( Observable < ? extends Void > observable ) { return observable . flatMap ( new Func1 < Void , Observable < ? > > ( ) { public Observable < ? > call ( Void aVoid ) { if ( HttpRefresher . this . registrations ( ) . containsKey ( name ) ) { LOGGER . debug ( "Resubscribing config stream for bucket {}, still registered." , name ) ; return Observable . just ( true ) ; } else { LOGGER . debug ( "Not resubscribing config stream for bucket {}, not registered." , name ) ; return Observable . empty ( ) ; } } } ) ; } } ) . subscribe ( new Subscriber < ProposedBucketConfigContext > ( ) { public void onCompleted ( ) { } public void onError ( Throwable e ) { LOGGER . error ( "Error while subscribing to Http refresh stream!" , e ) ; } public void onNext ( ProposedBucketConfigContext ctx ) { pushConfig ( ctx ) ; } } ) ; }
Helper method to push configs until unsubscribed even when a stream closes .
5,703
private static boolean isValidConfigNode ( final boolean sslEnabled , final NodeInfo nodeInfo ) { if ( sslEnabled && nodeInfo . sslServices ( ) . containsKey ( ServiceType . CONFIG ) ) { return true ; } else if ( nodeInfo . services ( ) . containsKey ( ServiceType . CONFIG ) ) { return true ; } return false ; }
Helper method to detect if the given node can actually perform http config refresh .
5,704
public void parse ( ) throws EOFException { if ( ! startedStreaming && levelStack . isEmpty ( ) ) { readNextChar ( null ) ; switch ( currentChar ) { case ( byte ) 0xEF : pushLevel ( Mode . BOM ) ; break ; case O_CURLY : pushLevel ( Mode . JSON_OBJECT ) ; break ; case O_SQUARE : pushLevel ( Mode . JSON_ARRAY ) ; break ; default : throw new IllegalStateException ( "Only UTF-8 is supported" ) ; } startedStreaming = true ; } while ( true ) { if ( levelStack . isEmpty ( ) ) { return ; } JsonLevel currentLevel = levelStack . peek ( ) ; switch ( currentLevel . peekMode ( ) ) { case BOM : readBOM ( ) ; break ; case JSON_OBJECT : readObject ( currentLevel ) ; break ; case JSON_ARRAY : readArray ( currentLevel ) ; break ; case JSON_OBJECT_VALUE : case JSON_ARRAY_VALUE : case JSON_STRING_HASH_KEY : case JSON_STRING_VALUE : case JSON_BOOLEAN_TRUE_VALUE : case JSON_BOOLEAN_FALSE_VALUE : case JSON_NUMBER_VALUE : case JSON_NULL_VALUE : readValue ( currentLevel ) ; break ; } } }
Instructs the parser to start parsing the current buffer .
5,705
private void popAndResetToOldLevel ( ) { this . levelStack . pop ( ) ; if ( ! this . levelStack . isEmpty ( ) ) { JsonLevel newTop = levelStack . peek ( ) ; if ( newTop != null ) { newTop . removeLastTokenFromJsonPointer ( ) ; } } }
Helper method to clean up after being done with the last stack so it removes the tokens that pointed to that object .
5,706
private void readArray ( final JsonLevel level ) throws EOFException { while ( true ) { readNextChar ( level ) ; if ( this . currentChar == JSON_ST ) { level . pushMode ( Mode . JSON_STRING_VALUE ) ; readValue ( level ) ; } else if ( this . currentChar == O_CURLY ) { if ( this . tree . isIntermediaryPath ( level . jsonPointer ( ) ) ) { this . pushLevel ( Mode . JSON_OBJECT ) ; return ; } level . pushMode ( Mode . JSON_OBJECT_VALUE ) ; readValue ( level ) ; } else if ( this . currentChar == O_SQUARE ) { if ( this . tree . isIntermediaryPath ( level . jsonPointer ( ) ) ) { this . pushLevel ( Mode . JSON_ARRAY ) ; return ; } else { level . pushMode ( Mode . JSON_ARRAY_VALUE ) ; readValue ( level ) ; } } else if ( this . currentChar == JSON_T ) { level . pushMode ( Mode . JSON_BOOLEAN_TRUE_VALUE ) ; readValue ( level ) ; } else if ( this . currentChar == JSON_F ) { level . pushMode ( Mode . JSON_BOOLEAN_FALSE_VALUE ) ; readValue ( level ) ; } else if ( this . currentChar == JSON_N ) { level . pushMode ( Mode . JSON_NULL_VALUE ) ; readValue ( level ) ; } else if ( isNumber ( this . currentChar ) ) { level . pushMode ( JSON_NUMBER_VALUE ) ; readValue ( level ) ; } else if ( this . currentChar == JSON_COMMA ) { level . updateIndex ( ) ; level . setArrayIndexOnJsonPointer ( ) ; } else if ( this . currentChar == C_SQUARE ) { popAndResetToOldLevel ( ) ; return ; } } }
Handle the logic for reading down a JSON Array .
5,707
private void readValue ( final JsonLevel level ) throws EOFException { int readerIndex = content . readerIndex ( ) ; ByteBufProcessor processor = null ; Mode mode = level . peekMode ( ) ; switch ( mode ) { case JSON_ARRAY_VALUE : arProcessor . reset ( ) ; processor = arProcessor ; break ; case JSON_OBJECT_VALUE : obProcessor . reset ( ) ; processor = obProcessor ; break ; case JSON_STRING_VALUE : case JSON_STRING_HASH_KEY : processor = stProcessor ; break ; case JSON_NULL_VALUE : nullProcessor . reset ( ) ; processor = nullProcessor ; break ; case JSON_BOOLEAN_TRUE_VALUE : processor = trueProcessor ; break ; case JSON_BOOLEAN_FALSE_VALUE : processor = falseProcessor ; break ; case JSON_NUMBER_VALUE : processor = numProcessor ; break ; } int length ; boolean shouldSaveValue = tree . isTerminalPath ( level . jsonPointer ( ) ) || mode == Mode . JSON_STRING_HASH_KEY ; int lastValidIndex = content . forEachByte ( processor ) ; if ( lastValidIndex == - 1 ) { if ( mode == Mode . JSON_NUMBER_VALUE && content . readableBytes ( ) > 2 ) { length = 1 ; level . setCurrentValue ( this . content . copy ( readerIndex - 1 , length ) , length ) ; this . content . discardReadBytes ( ) ; level . emitJsonPointerValue ( ) ; } else { throw NEED_MORE_DATA ; } } else { if ( mode == Mode . JSON_OBJECT_VALUE || mode == Mode . JSON_ARRAY_VALUE || mode == Mode . JSON_STRING_VALUE || mode == Mode . JSON_STRING_HASH_KEY || mode == Mode . JSON_NULL_VALUE || mode == Mode . JSON_BOOLEAN_TRUE_VALUE || mode == Mode . JSON_BOOLEAN_FALSE_VALUE ) { length = lastValidIndex - readerIndex + 1 ; if ( shouldSaveValue ) { level . setCurrentValue ( this . content . copy ( readerIndex - 1 , length + 1 ) , length ) ; level . emitJsonPointerValue ( ) ; } this . content . skipBytes ( length ) ; this . content . discardReadBytes ( ) ; } else { length = lastValidIndex - readerIndex ; if ( length > 0 ) { if ( shouldSaveValue ) { level . setCurrentValue ( this . content . copy ( readerIndex - 1 , length + 1 ) , length ) ; level . emitJsonPointerValue ( ) ; } this . content . skipBytes ( length ) ; this . content . discardReadBytes ( ) ; } else { length = 1 ; if ( shouldSaveValue ) { level . setCurrentValue ( this . content . copy ( readerIndex - 1 , length ) , length ) ; this . content . discardReadBytes ( ) ; level . emitJsonPointerValue ( ) ; } } } } if ( mode != Mode . JSON_STRING_HASH_KEY ) { level . removeLastTokenFromJsonPointer ( ) ; } level . popMode ( ) ; }
Handle the logic for reading down a JSON Value .
5,708
private void readBOM ( ) throws EOFException { int readerIndex = content . readerIndex ( ) ; int lastBOMIndex = content . forEachByte ( bomProcessor ) ; if ( lastBOMIndex == - 1 ) { throw NEED_MORE_DATA ; } if ( lastBOMIndex > readerIndex ) { this . content . skipBytes ( lastBOMIndex - readerIndex + 1 ) ; this . content . discardReadBytes ( ) ; } this . levelStack . pop ( ) ; }
Reads the UTF - 8 Byte Order Mark .
5,709
public Map < String , Object > export ( ) { Map < String , Object > result = new HashMap < String , Object > ( ) ; result . put ( "min" , min ( ) ) ; result . put ( "max" , max ( ) ) ; result . put ( "count" , count ( ) ) ; result . put ( "percentiles" , percentiles ( ) ) ; result . put ( "timeUnit" , timeUnit ( ) . toString ( ) ) ; return result ; }
Exports this object to a plain map structure which can be easily converted into other target formats .
5,710
@ SuppressWarnings ( "StatementWithEmptyBody" ) public static byte [ ] decode ( final String input ) { ByteArrayInputStream in = new ByteArrayInputStream ( input . getBytes ( ) ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try { while ( decodeChunk ( out , in ) ) { } } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } return out . toByteArray ( ) ; }
Decode a Base64 encoded string
5,711
private void handleSnappyCompression ( final ChannelHandlerContext ctx , final BinaryMemcacheRequest r ) { if ( ! ( r instanceof FullBinaryMemcacheRequest ) ) { return ; } FullBinaryMemcacheRequest request = ( FullBinaryMemcacheRequest ) r ; int uncompressedLength = request . content ( ) . readableBytes ( ) ; if ( uncompressedLength < minCompressionSize || uncompressedLength == 0 ) { return ; } ByteBuf compressedContent ; try { compressedContent = tryCompress ( request . content ( ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( "Could not snappy-compress value." , ex ) ; } if ( compressedContent != null ) { request . setDataType ( ( byte ) ( request . getDataType ( ) | DATATYPE_SNAPPY ) ) ; request . setContent ( compressedContent ) ; request . setTotalBodyLength ( request . getExtrasLength ( ) + request . getKeyLength ( ) + compressedContent . readableBytes ( ) ) ; } }
Helper method which performs snappy compression on the request path .
5,712
private void handleSnappyDecompression ( final ChannelHandlerContext ctx , final FullBinaryMemcacheResponse response ) { ByteBuf decompressed ; if ( response . content ( ) . readableBytes ( ) > 0 ) { byte [ ] compressed = Unpooled . copiedBuffer ( response . content ( ) ) . array ( ) ; try { decompressed = Unpooled . wrappedBuffer ( Snappy . uncompress ( compressed , 0 , compressed . length ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( "Could not decode snappy-compressed value." , ex ) ; } } else { decompressed = Unpooled . buffer ( 0 ) ; } response . content ( ) . release ( ) ; response . setContent ( decompressed ) ; response . setTotalBodyLength ( response . getExtrasLength ( ) + response . getKeyLength ( ) + decompressed . readableBytes ( ) ) ; response . setDataType ( ( byte ) ( response . getDataType ( ) & ~ DATATYPE_SNAPPY ) ) ; }
Helper method which performs decompression for snappy compressed values .
5,713
static long parseServerDurationFromFrame ( final ByteBuf frame ) { while ( frame . readableBytes ( ) > 0 ) { byte control = frame . readByte ( ) ; byte id = ( byte ) ( control & 0xF0 ) ; byte len = ( byte ) ( control & 0x0F ) ; if ( id == FRAMING_EXTRAS_TRACING ) { return Math . round ( Math . pow ( frame . readUnsignedShort ( ) , 1.74 ) / 2 ) ; } else { frame . skipBytes ( len ) ; } } return 0 ; }
Parses the server duration from the frame .
5,714
private static CouchbaseResponse handleCommonResponseMessages ( BinaryRequest request , FullBinaryMemcacheResponse msg , ResponseStatus status , boolean seqOnMutation ) { CouchbaseResponse response = null ; ByteBuf content = msg . content ( ) ; long cas = msg . getCAS ( ) ; short statusCode = msg . getStatus ( ) ; String bucket = request . bucket ( ) ; if ( request instanceof GetRequest || request instanceof ReplicaGetRequest ) { int flags = msg . getExtrasLength ( ) > 0 ? msg . getExtras ( ) . getInt ( 0 ) : 0 ; response = new GetResponse ( status , statusCode , cas , flags , bucket , content , request ) ; } else if ( request instanceof GetBucketConfigRequest ) { response = new GetBucketConfigResponse ( status , statusCode , bucket , content , ( ( GetBucketConfigRequest ) request ) . hostname ( ) ) ; } else if ( request instanceof InsertRequest ) { MutationToken descr = extractToken ( bucket , seqOnMutation , status . isSuccess ( ) , msg . getExtras ( ) , request . partition ( ) ) ; response = new InsertResponse ( status , statusCode , cas , bucket , content , descr , request ) ; } else if ( request instanceof UpsertRequest ) { MutationToken descr = extractToken ( bucket , seqOnMutation , status . isSuccess ( ) , msg . getExtras ( ) , request . partition ( ) ) ; response = new UpsertResponse ( status , statusCode , cas , bucket , content , descr , request ) ; } else if ( request instanceof ReplaceRequest ) { MutationToken descr = extractToken ( bucket , seqOnMutation , status . isSuccess ( ) , msg . getExtras ( ) , request . partition ( ) ) ; response = new ReplaceResponse ( status , statusCode , cas , bucket , content , descr , request ) ; } else if ( request instanceof RemoveRequest ) { MutationToken descr = extractToken ( bucket , seqOnMutation , status . isSuccess ( ) , msg . getExtras ( ) , request . partition ( ) ) ; response = new RemoveResponse ( status , statusCode , cas , bucket , content , descr , request ) ; } return response ; }
Helper method to decode all common response messages .
5,715
private static CouchbaseResponse handleSubdocumentResponseMessages ( BinaryRequest request , FullBinaryMemcacheResponse msg , ChannelHandlerContext ctx , ResponseStatus status , boolean seqOnMutation ) { if ( ! ( request instanceof BinarySubdocRequest ) ) return null ; BinarySubdocRequest subdocRequest = ( BinarySubdocRequest ) request ; long cas = msg . getCAS ( ) ; short statusCode = msg . getStatus ( ) ; String bucket = request . bucket ( ) ; MutationToken mutationToken = null ; if ( msg . getExtrasLength ( ) > 0 ) { mutationToken = extractToken ( bucket , seqOnMutation , status . isSuccess ( ) , msg . getExtras ( ) , request . partition ( ) ) ; } ByteBuf fragment ; if ( msg . content ( ) != null && msg . content ( ) . readableBytes ( ) > 0 ) { fragment = msg . content ( ) ; } else if ( msg . content ( ) != null ) { msg . content ( ) . release ( ) ; fragment = Unpooled . EMPTY_BUFFER ; } else { fragment = Unpooled . EMPTY_BUFFER ; } return new SimpleSubdocResponse ( status , statusCode , bucket , fragment , subdocRequest , cas , mutationToken ) ; }
Helper method to decode all simple subdocument response messages .
5,716
private static CouchbaseResponse handleSubdocumentMultiLookupResponseMessages ( BinaryRequest request , FullBinaryMemcacheResponse msg , ChannelHandlerContext ctx , ResponseStatus status ) { if ( ! ( request instanceof BinarySubdocMultiLookupRequest ) ) return null ; BinarySubdocMultiLookupRequest subdocRequest = ( BinarySubdocMultiLookupRequest ) request ; short statusCode = msg . getStatus ( ) ; long cas = msg . getCAS ( ) ; String bucket = request . bucket ( ) ; ByteBuf body = msg . content ( ) ; List < MultiResult < Lookup > > responses ; if ( status . isSuccess ( ) || ResponseStatus . SUBDOC_MULTI_PATH_FAILURE . equals ( status ) ) { long bodyLength = body . readableBytes ( ) ; List < LookupCommand > commands = subdocRequest . commands ( ) ; responses = new ArrayList < MultiResult < Lookup > > ( commands . size ( ) ) ; for ( LookupCommand cmd : commands ) { if ( msg . content ( ) . readableBytes ( ) < 6 ) { body . release ( ) ; throw new IllegalStateException ( "Expected " + commands . size ( ) + " lookup responses, only got " + responses . size ( ) + ", total of " + bodyLength + " bytes" ) ; } short cmdStatus = body . readShort ( ) ; int valueLength = body . readInt ( ) ; ByteBuf value = ctx . alloc ( ) . buffer ( valueLength , valueLength ) ; value . writeBytes ( body , valueLength ) ; responses . add ( MultiResult . create ( cmdStatus , ResponseStatusConverter . fromBinary ( cmdStatus ) , cmd . path ( ) , cmd . lookup ( ) , value ) ) ; } } else { responses = Collections . emptyList ( ) ; } body . release ( ) ; return new MultiLookupResponse ( status , statusCode , bucket , responses , subdocRequest , cas ) ; }
Helper method to decode all multi lookup response messages .
5,717
private static ByteBuf contentFromWriteRequest ( BinaryRequest request ) { ByteBuf content = null ; if ( request instanceof BinaryStoreRequest ) { content = ( ( BinaryStoreRequest ) request ) . content ( ) ; } else if ( request instanceof AppendRequest ) { content = ( ( AppendRequest ) request ) . content ( ) ; } else if ( request instanceof PrependRequest ) { content = ( ( PrependRequest ) request ) . content ( ) ; } else if ( request instanceof BinarySubdocRequest ) { content = ( ( BinarySubdocRequest ) request ) . content ( ) ; } else if ( request instanceof BinarySubdocMultiLookupRequest ) { content = ( ( BinarySubdocMultiLookupRequest ) request ) . content ( ) ; } else if ( request instanceof BinarySubdocMultiMutationRequest ) { content = ( ( BinarySubdocMultiMutationRequest ) request ) . content ( ) ; } return content ; }
Helper method to extract the content from requests .
5,718
protected void sideEffectRequestToCancel ( final BinaryRequest request ) { super . sideEffectRequestToCancel ( request ) ; if ( request instanceof BinaryStoreRequest ) { ( ( BinaryStoreRequest ) request ) . content ( ) . release ( ) ; } else if ( request instanceof AppendRequest ) { ( ( AppendRequest ) request ) . content ( ) . release ( ) ; } else if ( request instanceof PrependRequest ) { ( ( PrependRequest ) request ) . content ( ) . release ( ) ; } }
Releasing the content of requests that are to be cancelled .
5,719
protected Endpoint createEndpoint ( ) { return endpointFactory . create ( hostname , bucket , username , password , port , ctx ) ; }
Helper method to create a new endpoint .
5,720
protected static void whenState ( final Endpoint endpoint , final LifecycleState wanted , Action1 < LifecycleState > then ) { endpoint . states ( ) . filter ( new Func1 < LifecycleState , Boolean > ( ) { public Boolean call ( LifecycleState state ) { return state == wanted ; } } ) . take ( 1 ) . subscribe ( then ) ; }
Waits until the endpoint goes into the given state calls the action and then unsubscribes .
5,721
protected void cleanUpAndThrow ( RuntimeException e ) { if ( content != null && content . refCnt ( ) > 0 ) { content . release ( ) ; } throw e ; }
Utility method to ensure good cleanup when throwing an exception from a constructor .
5,722
protected void transitionState ( final S newState ) { if ( newState != currentState ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "State (" + getClass ( ) . getSimpleName ( ) + ") " + currentState + " -> " + newState ) ; } currentState = newState ; observable . onNext ( newState ) ; } }
Transition into a new state .
5,723
private void ensureMinimum ( ) { int belowMin = minEndpoints - endpoints . size ( ) ; if ( belowMin > 0 ) { LOGGER . debug ( logIdent ( hostname , this ) + "Service is {} below minimum, filling up." , belowMin ) ; synchronized ( epMutex ) { for ( int i = 0 ; i < belowMin ; i ++ ) { Endpoint endpoint = endpointFactory . create ( hostname , bucket , username , password , port , ctx ) ; endpoints . add ( endpoint ) ; endpointStates . register ( endpoint , endpoint ) ; endpoint . connect ( ) . subscribe ( new Subscriber < LifecycleState > ( ) { public void onCompleted ( ) { } public void onError ( Throwable e ) { LOGGER . warn ( logIdent ( hostname , PooledService . this ) + "Got an error while connecting endpoint!" , e ) ; } public void onNext ( LifecycleState state ) { } } ) ; } LOGGER . debug ( logIdent ( hostname , PooledService . this ) + "New number of endpoints is {}" , endpoints . size ( ) ) ; } } }
Helper method to ensure a minimum number of endpoints is enabled .
5,724
private void maybeOpenAndSend ( final CouchbaseRequest request ) { LOGGER . debug ( logIdent ( hostname , PooledService . this ) + "Need to open a new Endpoint (current size {})" , endpoints . size ( ) ) ; final Endpoint endpoint = endpointFactory . create ( hostname , bucket , username , password , port , ctx ) ; synchronized ( epMutex ) { endpoints . add ( endpoint ) ; endpointStates . register ( endpoint , endpoint ) ; } final Subscription subscription = whenState ( endpoint , LifecycleState . CONNECTED , new Action1 < LifecycleState > ( ) { public void call ( LifecycleState lifecycleState ) { if ( disconnect ) { RetryHelper . retryOrCancel ( env , request , responseBuffer ) ; } else { endpoint . send ( request ) ; endpoint . send ( SignalFlush . INSTANCE ) ; } } } ) ; endpoint . connect ( ) . subscribe ( new Subscriber < LifecycleState > ( ) { public void onCompleted ( ) { } public void onError ( Throwable e ) { unsubscribeAndRetry ( subscription , request ) ; } public void onNext ( LifecycleState state ) { if ( state == LifecycleState . DISCONNECTING || state == LifecycleState . DISCONNECTED ) { unsubscribeAndRetry ( subscription , request ) ; } } } ) ; }
Helper method to try and open new endpoints as needed and correctly integrate them into the state of the service .
5,725
private void unsubscribeAndRetry ( final Subscription subscription , final CouchbaseRequest request ) { if ( subscription != null && ! subscription . isUnsubscribed ( ) ) { subscription . unsubscribe ( ) ; } RetryHelper . retryOrCancel ( env , request , responseBuffer ) ; }
Helper method to unsubscribe from the subscription and send the request into retry .
5,726
private void sendFlush ( final SignalFlush signalFlush ) { for ( Endpoint endpoint : endpoints ) { if ( endpoint != null ) { endpoint . send ( signalFlush ) ; } } }
Helper method to send the flush signal to all endpoints .
5,727
public void channelInactive ( ChannelHandlerContext ctx ) throws Exception { super . channelInactive ( ctx ) ; if ( currentMessage != null && currentMessage . getExtras ( ) != null ) { if ( currentMessage . getExtras ( ) . refCnt ( ) > 0 ) { currentMessage . getExtras ( ) . release ( ) ; } } if ( currentMessage != null && currentMessage . getFramingExtras ( ) != null ) { if ( currentMessage . getFramingExtras ( ) . refCnt ( ) > 0 ) { currentMessage . getFramingExtras ( ) . release ( ) ; } } resetDecoder ( ) ; }
When the channel goes inactive release all frames to prevent data leaks .
5,728
private void transitionStateThroughZipper ( ) { Collection < S > currentStates = states . values ( ) ; if ( currentStates . isEmpty ( ) ) { transitionState ( initialState ) ; } else { transitionState ( zipWith ( currentStates ) ) ; } }
Ask the zip function to compute the states and then transition the state of the zipper .
5,729
public void report ( final ThresholdLogSpan span ) { if ( isOverThreshold ( span ) ) { if ( ! overThresholdQueue . offer ( span ) ) { LOGGER . debug ( "Could not enqueue span {} for over threshold reporting, discarding." , span ) ; } } }
Reports the given span but it doesn t have to be a potential slow .
5,730
private boolean isOverThreshold ( final ThresholdLogSpan span ) { String service = ( String ) span . tag ( Tags . PEER_SERVICE . getKey ( ) ) ; if ( SERVICE_KV . equals ( service ) ) { return span . durationMicros ( ) >= kvThreshold ; } else if ( SERVICE_N1QL . equals ( service ) ) { return span . durationMicros ( ) >= n1qlThreshold ; } else if ( SERVICE_VIEW . equals ( service ) ) { return span . durationMicros ( ) >= viewThreshold ; } else if ( SERVICE_FTS . equals ( service ) ) { return span . durationMicros ( ) >= ftsThreshold ; } else if ( SERVICE_ANALYTICS . equals ( service ) ) { return span . durationMicros ( ) >= analyticsThreshold ; } else { return false ; } }
Checks if the given span is over the threshold and eligible for being reported .
5,731
private static int calculateNodeId ( int partitionId , BinaryRequest request , CouchbaseBucketConfig config ) { boolean useFastForward = request . retryCount ( ) > 0 && config . hasFastForwardMap ( ) ; if ( request instanceof ReplicaGetRequest ) { return config . nodeIndexForReplica ( partitionId , ( ( ReplicaGetRequest ) request ) . replica ( ) - 1 , useFastForward ) ; } else if ( request instanceof ObserveRequest && ( ( ObserveRequest ) request ) . replica ( ) > 0 ) { return config . nodeIndexForReplica ( partitionId , ( ( ObserveRequest ) request ) . replica ( ) - 1 , useFastForward ) ; } else if ( request instanceof ObserveSeqnoRequest && ( ( ObserveSeqnoRequest ) request ) . replica ( ) > 0 ) { return config . nodeIndexForReplica ( partitionId , ( ( ObserveSeqnoRequest ) request ) . replica ( ) - 1 , useFastForward ) ; } else { return config . nodeIndexForMaster ( partitionId , useFastForward ) ; } }
Helper method to calculate the node if for the given partition and request type .
5,732
private static void errorObservables ( int nodeId , BinaryRequest request , String name , CoreEnvironment env , RingBuffer < ResponseEvent > responseBuffer ) { if ( nodeId == DefaultCouchbaseBucketConfig . PARTITION_NOT_EXISTENT ) { if ( request instanceof ReplicaGetRequest ) { request . observable ( ) . onError ( new ReplicaNotConfiguredException ( "Replica number " + ( ( ReplicaGetRequest ) request ) . replica ( ) + " not configured for bucket " + name , null ) ) ; return ; } else if ( request instanceof ObserveRequest ) { request . observable ( ) . onError ( new ReplicaNotConfiguredException ( "Replica number " + ( ( ObserveRequest ) request ) . replica ( ) + " not configured for bucket " + name , ( ( ObserveRequest ) request ) . cas ( ) ) ) ; return ; } else if ( request instanceof ObserveSeqnoRequest ) { request . observable ( ) . onError ( new ReplicaNotConfiguredException ( "Replica number " + ( ( ObserveSeqnoRequest ) request ) . replica ( ) + " not configured for bucket " + name , ( ( ObserveSeqnoRequest ) request ) . cas ( ) ) ) ; return ; } RetryHelper . retryOrCancel ( env , request , responseBuffer ) ; return ; } if ( nodeId == - 1 ) { if ( request instanceof ObserveRequest ) { request . observable ( ) . onError ( new ReplicaNotAvailableException ( "Replica number " + ( ( ObserveRequest ) request ) . replica ( ) + " not available for bucket " + name , ( ( ObserveRequest ) request ) . cas ( ) ) ) ; return ; } else if ( request instanceof ReplicaGetRequest ) { request . observable ( ) . onError ( new ReplicaNotAvailableException ( "Replica number " + ( ( ReplicaGetRequest ) request ) . replica ( ) + " not available for bucket " + name , null ) ) ; return ; } else if ( request instanceof ObserveSeqnoRequest ) { request . observable ( ) . onError ( new ReplicaNotAvailableException ( "Replica number " + ( ( ObserveSeqnoRequest ) request ) . replica ( ) + " not available for bucket " + name , ( ( ObserveSeqnoRequest ) request ) . cas ( ) ) ) ; return ; } RetryHelper . retryOrCancel ( env , request , responseBuffer ) ; return ; } throw new IllegalStateException ( "Unknown NodeId: " + nodeId + ", request: " + request ) ; }
Fail observables because the partitions do not match up .
5,733
private static int partitionForKey ( byte [ ] key , int numPartitions ) { CRC32 crc32 = new CRC32 ( ) ; crc32 . update ( key ) ; long rv = ( crc32 . getValue ( ) >> 16 ) & 0x7fff ; return ( int ) rv & numPartitions - 1 ; }
Calculate the vbucket for the given key .
5,734
private static boolean handleNotEqualNodeSizes ( int configNodeSize , int actualNodeSize ) { if ( configNodeSize != actualNodeSize ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Node list and configuration's partition hosts sizes : {} <> {}, rescheduling" , actualNodeSize , configNodeSize ) ; } return true ; } return false ; }
Helper method to handle potentially different node sizes in the actual list and in the config .
5,735
private static boolean keyIsValid ( final BinaryRequest request ) { if ( request . keyBytes ( ) == null || request . keyBytes ( ) . length < MIN_KEY_BYTES ) { request . observable ( ) . onError ( new IllegalArgumentException ( "The Document ID must not be null or empty." ) ) ; return false ; } if ( request . keyBytes ( ) . length > MAX_KEY_BYTES ) { request . observable ( ) . onError ( new IllegalArgumentException ( "The Document ID must not be longer than 250 bytes." ) ) ; return false ; } return true ; }
Helper method to check if the given request key is valid .
5,736
public void debug ( String msg ) { if ( logger . isLoggable ( Level . FINE ) ) { log ( SELF , Level . FINE , msg , null ) ; } }
Log a message object at level FINE .
5,737
private void signalConnected ( ) { if ( alternate != null ) { LOGGER . info ( "Connected to Node {} ({})" , system ( hostname . nameAndAddress ( ) ) , system ( alternate . nameAndAddress ( ) ) ) ; } else { LOGGER . info ( "Connected to Node {}" , system ( hostname . nameAndAddress ( ) ) ) ; } if ( eventBus != null && eventBus . hasSubscribers ( ) ) { eventBus . publish ( new NodeConnectedEvent ( hostname ) ) ; } }
Log that this node is now connected and also inform all susbcribers on the event bus .
5,738
private void signalDisconnected ( ) { if ( alternate != null ) { LOGGER . info ( "Disconnected from Node {} ({})" , system ( hostname . nameAndAddress ( ) ) , system ( alternate . nameAndAddress ( ) ) ) ; } else { LOGGER . info ( "Disconnected from Node {}" , system ( hostname . nameAndAddress ( ) ) ) ; } if ( eventBus != null && eventBus . hasSubscribers ( ) ) { eventBus . publish ( new NodeDisconnectedEvent ( hostname ) ) ; } }
Log that this node is now disconnected and also inform all susbcribers on the event bus .
5,739
public static < T > Observable < T > wrapColdWithAutoRelease ( final Observable < T > source ) { return Observable . create ( new Observable . OnSubscribe < T > ( ) { public void call ( final Subscriber < ? super T > subscriber ) { source . subscribe ( new Subscriber < T > ( ) { public void onCompleted ( ) { if ( ! subscriber . isUnsubscribed ( ) ) { subscriber . onCompleted ( ) ; } } public void onError ( Throwable e ) { if ( ! subscriber . isUnsubscribed ( ) ) { subscriber . onError ( e ) ; } } public void onNext ( T t ) { if ( ! subscriber . isUnsubscribed ( ) ) { subscriber . onNext ( t ) ; } else { ReferenceCountUtil . release ( t ) ; } } } ) ; } } ) ; }
Wrap an observable and free a reference counted item if unsubscribed in the meantime .
5,740
static void extractPorts ( final Map < String , Integer > input , final Map < ServiceType , Integer > ports , final Map < ServiceType , Integer > sslPorts ) { for ( Map . Entry < String , Integer > entry : input . entrySet ( ) ) { String service = entry . getKey ( ) ; int port = entry . getValue ( ) ; if ( service . equals ( "mgmt" ) ) { ports . put ( ServiceType . CONFIG , port ) ; } else if ( service . equals ( "capi" ) ) { ports . put ( ServiceType . VIEW , port ) ; } else if ( service . equals ( "kv" ) ) { ports . put ( ServiceType . BINARY , port ) ; } else if ( service . equals ( "kvSSL" ) ) { sslPorts . put ( ServiceType . BINARY , port ) ; } else if ( service . equals ( "capiSSL" ) ) { sslPorts . put ( ServiceType . VIEW , port ) ; } else if ( service . equals ( "mgmtSSL" ) ) { sslPorts . put ( ServiceType . CONFIG , port ) ; } else if ( service . equals ( "n1ql" ) ) { ports . put ( ServiceType . QUERY , port ) ; } else if ( service . equals ( "n1qlSSL" ) ) { sslPorts . put ( ServiceType . QUERY , port ) ; } else if ( service . equals ( "fts" ) ) { ports . put ( ServiceType . SEARCH , port ) ; } else if ( service . equals ( "ftsSSL" ) ) { sslPorts . put ( ServiceType . SEARCH , port ) ; } else if ( service . equals ( "cbas" ) ) { ports . put ( ServiceType . ANALYTICS , port ) ; } else if ( service . equals ( "cbasSSL" ) ) { sslPorts . put ( ServiceType . ANALYTICS , port ) ; } } }
Helper method to extract ports from the raw services port mapping .
5,741
public static String stringify ( final ResponseStatus status , final ResponseStatusDetails details ) { String result = status . toString ( ) ; if ( details != null ) { result = result + " (Context: " + details . context ( ) + ", Reference: " + details . reference ( ) + ")" ; } return result ; }
Stringify the status details and the status in a best effort manner .
5,742
static List < InetSocketAddress > tryResolveHosts ( final List < InetSocketAddress > hosts ) { List < InetSocketAddress > resolvableHosts = new ArrayList < InetSocketAddress > ( ) ; for ( InetSocketAddress node : hosts ) { try { node . getAddress ( ) . getHostAddress ( ) ; resolvableHosts . add ( node ) ; } catch ( NullPointerException ex ) { LOGGER . error ( "Unable to resolve address " + node . toString ( ) ) ; } } return resolvableHosts ; }
Make sure the address is resolvable
5,743
private static void sendAndFlushWhenConnected ( final Endpoint endpoint , final CouchbaseRequest request ) { whenState ( endpoint , LifecycleState . CONNECTED , new Action1 < LifecycleState > ( ) { public void call ( LifecycleState lifecycleState ) { endpoint . send ( request ) ; endpoint . send ( SignalFlush . INSTANCE ) ; } } ) ; }
Helper method to send the request and also a flush afterwards .
5,744
public Observable < Tuple2 < LoaderType , BucketConfig > > loadConfig ( final NetworkAddress seedNode , final String bucket , final String password ) { LOGGER . debug ( "Loading Config for bucket {}" , bucket ) ; return loadConfig ( seedNode , bucket , bucket , password ) ; }
Initiate the config loading process .
5,745
protected String replaceHostWildcard ( String input , NetworkAddress hostname ) { return input . replace ( "$HOST" , hostname . address ( ) ) ; }
Replaces the host wildcard from an incoming config with a proper hostname .
5,746
public InetAddress host ( ) { try { return InetAddress . getByName ( host . address ( ) ) ; } catch ( UnknownHostException e ) { throw new IllegalStateException ( e ) ; } }
The host address of the connected node .
5,747
private FullBinaryMemcacheRequest errorMapRequest ( ) { LOGGER . debug ( "Requesting error map in version {}" , MAP_VERSION ) ; ByteBuf content = Unpooled . buffer ( 2 ) . writeShort ( MAP_VERSION ) ; FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest ( new byte [ ] { } , Unpooled . EMPTY_BUFFER , content ) ; request . setOpcode ( GET_ERROR_MAP_CMD ) ; request . setTotalBodyLength ( content . readableBytes ( ) ) ; return request ; }
Creates the request to load the error map .
5,748
public ApiResponse getStreamingProfile ( String name , Map options ) throws Exception { if ( options == null ) options = ObjectUtils . emptyMap ( ) ; List < String > uri = Arrays . asList ( "streaming_profiles" , name ) ; return callApi ( HttpMethod . GET , uri , ObjectUtils . emptyMap ( ) , options ) ; }
Get a streaming profile information
5,749
public ApiResponse listStreamingProfiles ( Map options ) throws Exception { if ( options == null ) options = ObjectUtils . emptyMap ( ) ; List < String > uri = Collections . singletonList ( "streaming_profiles" ) ; return callApi ( HttpMethod . GET , uri , ObjectUtils . emptyMap ( ) , options ) ; }
List Streaming profiles
5,750
public ApiResponse deleteStreamingProfile ( String name , Map options ) throws Exception { if ( options == null ) options = ObjectUtils . emptyMap ( ) ; List < String > uri = Arrays . asList ( "streaming_profiles" , name ) ; return callApi ( HttpMethod . DELETE , uri , ObjectUtils . emptyMap ( ) , options ) ; }
Delete a streaming profile information . Predefined profiles are restored to the default setting .
5,751
public ApiResponse updateResourcesAccessModeByPrefix ( String accessMode , String prefix , Map options ) throws Exception { return updateResourcesAccessMode ( accessMode , "prefix" , prefix , options ) ; }
Update access mode of one or more resources by prefix
5,752
public ApiResponse updateResourcesAccessModeByTag ( String accessMode , String tag , Map options ) throws Exception { return updateResourcesAccessMode ( accessMode , "tag" , tag , options ) ; }
Update access mode of one or more resources by tag
5,753
public ApiResponse updateResourcesAccessModeByIds ( String accessMode , Iterable < String > publicIds , Map options ) throws Exception { return updateResourcesAccessMode ( accessMode , "public_ids" , publicIds , options ) ; }
Update access mode of one or more resources by publicIds
5,754
public String generate ( String url ) { long expiration = this . expiration ; if ( expiration == 0 ) { if ( duration > 0 ) { final long start = startTime > 0 ? startTime : Calendar . getInstance ( TimeZone . getTimeZone ( "UTC" ) ) . getTimeInMillis ( ) / 1000L ; expiration = start + duration ; } else { throw new IllegalArgumentException ( "Must provide either expiration or duration" ) ; } } ArrayList < String > tokenParts = new ArrayList < String > ( ) ; if ( ip != null ) { tokenParts . add ( "ip=" + ip ) ; } if ( startTime > 0 ) { tokenParts . add ( "st=" + startTime ) ; } tokenParts . add ( "exp=" + expiration ) ; if ( acl != null ) { tokenParts . add ( "acl=" + escapeToLower ( acl ) ) ; } ArrayList < String > toSign = new ArrayList < String > ( tokenParts ) ; if ( url != null && acl == null ) { toSign . add ( "url=" + escapeToLower ( url ) ) ; } String auth = digest ( StringUtils . join ( toSign , "~" ) ) ; tokenParts . add ( "hmac=" + auth ) ; return tokenName + "=" + StringUtils . join ( tokenParts , "~" ) ; }
Generate a URL token for the given URL .
5,755
private String escapeToLower ( String url ) { String encodedUrl = StringUtils . urlEncode ( url , UNSAFE_URL_CHARS_PATTERN , Charset . forName ( "UTF-8" ) ) ; return encodedUrl ; }
Escape url using lowercase hex code
5,756
public AuthToken copy ( ) { final AuthToken authToken = new AuthToken ( key ) ; authToken . tokenName = tokenName ; authToken . startTime = startTime ; authToken . expiration = expiration ; authToken . ip = ip ; authToken . acl = acl ; authToken . duration = duration ; return authToken ; }
Create a copy of this AuthToken
5,757
public static String normalize ( Object expression ) { if ( expression == null ) { return null ; } if ( expression instanceof Number ) { return String . valueOf ( expression ) ; } String replacement ; String conditionStr = StringUtils . mergeToSingleUnderscore ( String . valueOf ( expression ) ) ; Matcher matcher = PATTERN . matcher ( conditionStr ) ; StringBuffer result = new StringBuffer ( conditionStr . length ( ) ) ; while ( matcher . find ( ) ) { if ( OPERATORS . containsKey ( matcher . group ( ) ) ) { replacement = ( String ) OPERATORS . get ( matcher . group ( ) ) ; } else if ( PREDEFINED_VARS . containsKey ( matcher . group ( ) ) ) { replacement = ( String ) PREDEFINED_VARS . get ( matcher . group ( ) ) ; } else { replacement = matcher . group ( ) ; } matcher . appendReplacement ( result , replacement ) ; } matcher . appendTail ( result ) ; return result . toString ( ) ; }
Normalize an expression string replace nice names with their coded values and spaces with _ .
5,758
public static String join ( List < String > list , String separator ) { if ( list == null ) { return null ; } return join ( list . toArray ( ) , separator , 0 , list . size ( ) ) ; }
Join a list of Strings
5,759
public static String join ( Collection < String > collection , String separator ) { if ( collection == null ) { return null ; } return join ( collection . toArray ( new String [ collection . size ( ) ] ) , separator , 0 , collection . size ( ) ) ; }
Join a collection of Strings
5,760
public static String encodeHexString ( byte [ ] bytes ) { char [ ] hexChars = new char [ bytes . length * 2 ] ; for ( int j = 0 ; j < bytes . length ; j ++ ) { int v = bytes [ j ] & 0xFF ; hexChars [ j * 2 ] = hexArray [ v >>> 4 ] ; hexChars [ j * 2 + 1 ] = hexArray [ v & 0x0F ] ; } return new String ( hexChars ) ; }
Convert an array of bytes to a string of hex values
5,761
public static String read ( InputStream in ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int length = 0 ; while ( ( length = in . read ( buffer ) ) != - 1 ) { baos . write ( buffer , 0 , length ) ; } return new String ( baos . toByteArray ( ) ) ; }
Read the entire input stream in 1KB chunks
5,762
public static String replaceIfFirstChar ( String s , char c , String replacement ) { return s . charAt ( 0 ) == c ? replacement + s . substring ( 1 ) : s ; }
Replaces the char c in the string S if it s the first character in the string .
5,763
public static String removeStartingChars ( String s , char c ) { int lastToRemove = - 1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == c ) { lastToRemove = i ; continue ; } if ( s . charAt ( i ) != c ) { break ; } } if ( lastToRemove < 0 ) return s ; return s . substring ( lastToRemove + 1 ) ; }
Remove all consecutive chars c from the beginning of the string
5,764
public static String toISO8601 ( Date date ) { DateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssXXX" , Locale . US ) ; dateFormat . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; return dateFormat . format ( date ) ; }
Formats a Date as an ISO - 8601 string representation .
5,765
private boolean isValidAttrValue ( String value ) { final float parseFloat ; try { parseFloat = Float . parseFloat ( value ) ; } catch ( NumberFormatException e ) { return false ; } return parseFloat >= 1 ; }
Check if the value is a float > = 1
5,766
public static AccessControlRule anonymous ( Date start , Date end ) { return new AccessControlRule ( AccessType . anonymous , start , end ) ; }
Construct a new anonymous access rule
5,767
private HttpUriRequest prepareRequest ( HttpMethod method , String apiUrl , Map < String , ? > params , Map options ) throws URISyntaxException , UnsupportedEncodingException { URI apiUri ; HttpRequestBase request ; String contentType = ObjectUtils . asString ( options . get ( "content_type" ) , "urlencoded" ) ; URIBuilder apiUrlBuilder = new URIBuilder ( apiUrl ) ; HashMap < String , Object > unboxedParams = new HashMap < String , Object > ( params ) ; if ( method == HttpMethod . GET ) { apiUrlBuilder . setParameters ( prepareParams ( params ) ) ; apiUri = apiUrlBuilder . build ( ) ; request = new HttpGet ( apiUri ) ; } else { apiUri = apiUrlBuilder . build ( ) ; switch ( method ) { case PUT : request = new HttpPut ( apiUri ) ; break ; case DELETE : unboxedParams . put ( "_method" , "delete" ) ; case POST : request = new HttpPost ( apiUri ) ; break ; default : throw new IllegalArgumentException ( "Unknown HTTP method" ) ; } if ( contentType . equals ( "json" ) ) { JSONObject asJSON = ObjectUtils . toJSON ( unboxedParams ) ; StringEntity requestEntity = new StringEntity ( asJSON . toString ( ) , ContentType . APPLICATION_JSON ) ; ( ( HttpEntityEnclosingRequestBase ) request ) . setEntity ( requestEntity ) ; } else { ( ( HttpEntityEnclosingRequestBase ) request ) . setEntity ( new UrlEncodedFormEntity ( prepareParams ( unboxedParams ) , Consts . UTF_8 ) ) ; } } setTimeouts ( request , options ) ; return request ; }
Prepare a request with the URL and parameters based on the HTTP method used
5,768
private boolean isStatusCodeOK ( Response response , String uri ) { if ( response . getStatus ( ) == Status . OK . getStatusCode ( ) || response . getStatus ( ) == Status . CREATED . getStatusCode ( ) ) { return true ; } else if ( response . getStatus ( ) == Status . UNAUTHORIZED . getStatusCode ( ) ) { throw new NotAuthorizedException ( "UNAUTHORIZED: Your credentials are wrong. " + "Please check your username/password or the secret key." , response ) ; } else if ( response . getStatus ( ) == Status . CONFLICT . getStatusCode ( ) || response . getStatus ( ) == Status . NOT_FOUND . getStatusCode ( ) || response . getStatus ( ) == Status . FORBIDDEN . getStatusCode ( ) || response . getStatus ( ) == Status . BAD_REQUEST . getStatusCode ( ) ) { ErrorResponse errorResponse = response . readEntity ( ErrorResponse . class ) ; throw new ClientErrorException ( errorResponse . toString ( ) , response ) ; } else { throw new WebApplicationException ( "Unsupported status" , response ) ; } }
Checks if is status code ok .
5,769
private WebTarget createWebTarget ( String restPath , Map < String , String > queryParams ) { WebTarget webTarget ; try { URI u = new URI ( this . baseURI + "/plugins/restapi/v1/" + restPath ) ; Client client = createRestClient ( ) ; webTarget = client . target ( u ) ; if ( queryParams != null && ! queryParams . isEmpty ( ) ) { for ( Map . Entry < String , String > entry : queryParams . entrySet ( ) ) { if ( entry . getKey ( ) != null && entry . getValue ( ) != null ) { LOG . debug ( "PARAM: {} = {}" , entry . getKey ( ) , entry . getValue ( ) ) ; webTarget = webTarget . queryParam ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } } catch ( Exception e ) { throw new IllegalArgumentException ( "Something went wrong by creating the client: " + e ) ; } return webTarget ; }
Creates the web target .
5,770
private Client createRestClient ( ) throws KeyManagementException , NoSuchAlgorithmException { ClientConfig clientConfig = new ClientConfig ( ) ; if ( this . connectionTimeout != 0 ) { clientConfig . property ( ClientProperties . CONNECT_TIMEOUT , this . connectionTimeout ) ; clientConfig . property ( ClientProperties . READ_TIMEOUT , this . connectionTimeout ) ; } clientConfig . register ( MoxyJsonFeature . class ) . register ( MoxyXmlFeature . class ) . register ( createMoxyJsonResolver ( ) ) ; Client client = null ; if ( this . baseURI . startsWith ( "https" ) ) { client = createSLLClient ( clientConfig ) ; } else { client = ClientBuilder . newClient ( clientConfig ) ; } return client ; }
Creater rest client .
5,771
private Client createSLLClient ( ClientConfig clientConfig ) throws KeyManagementException , NoSuchAlgorithmException { TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } } } ; SSLContext sc = SSLContext . getInstance ( "TLS" ) ; sc . init ( null , trustAllCerts , new SecureRandom ( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sc . getSocketFactory ( ) ) ; ClientBuilder . newClient ( clientConfig ) ; Client client = ClientBuilder . newBuilder ( ) . sslContext ( sc ) . hostnameVerifier ( new HostnameVerifier ( ) { public boolean verify ( String s , SSLSession sslSession ) { return true ; } } ) . withConfig ( clientConfig ) . build ( ) ; return client ; }
Creates the sll client .
5,772
public UserEntity getUser ( String username ) { UserEntity userEntity = restClient . get ( "users/" + username , UserEntity . class , new HashMap < String , String > ( ) ) ; return userEntity ; }
Gets the user .
5,773
public Response createUser ( UserEntity userEntity ) { return restClient . post ( "users" , userEntity , new HashMap < String , String > ( ) ) ; }
Creates the user .
5,774
public Response deleteUser ( String username ) { return restClient . delete ( "users/" + username , new HashMap < String , String > ( ) ) ; }
Delete user .
5,775
public MUCRoomEntities getChatRooms ( Map < String , String > queryParams ) { return restClient . get ( "chatrooms" , MUCRoomEntities . class , queryParams ) ; }
Gets the chat rooms .
5,776
public MUCRoomEntity getChatRoom ( String roomName ) { return restClient . get ( "chatrooms/" + roomName , MUCRoomEntity . class , new HashMap < String , String > ( ) ) ; }
Gets the chat room .
5,777
public Response createChatRoom ( MUCRoomEntity chatRoom ) { return restClient . post ( "chatrooms" , chatRoom , new HashMap < String , String > ( ) ) ; }
Creates the chat room .
5,778
public Response updateChatRoom ( MUCRoomEntity chatRoom ) { return restClient . put ( "chatrooms/" + chatRoom . getRoomName ( ) , chatRoom , new HashMap < String , String > ( ) ) ; }
Update chat room .
5,779
public Response deleteChatRoom ( String roomName ) { return restClient . delete ( "chatrooms/" + roomName , new HashMap < String , String > ( ) ) ; }
Delete chat room .
5,780
public ParticipantEntities getChatRoomParticipants ( String roomName ) { return restClient . get ( "chatrooms/" + roomName + "/participants" , ParticipantEntities . class , new HashMap < String , String > ( ) ) ; }
Gets the chat room participants .
5,781
public Response deleteOwner ( String roomName , String jid ) { return restClient . delete ( "chatrooms/" + roomName + "/owners/" + jid , new HashMap < String , String > ( ) ) ; }
Delete owner from chatroom .
5,782
public Response deleteAdmin ( String roomName , String jid ) { return restClient . delete ( "chatrooms/" + roomName + "/admins/" + jid , new HashMap < String , String > ( ) ) ; }
Delete admin from chatroom .
5,783
public Response deleteMember ( String roomName , String jid ) { return restClient . delete ( "chatrooms/" + roomName + "/members/" + jid , new HashMap < String , String > ( ) ) ; }
Delete member from chatroom .
5,784
public Response addOutcast ( String roomName , String jid ) { return restClient . post ( "chatrooms/" + roomName + "/outcasts/" + jid , null , new HashMap < String , String > ( ) ) ; }
Adds the outcast .
5,785
public Response deleteOutcast ( String roomName , String jid ) { return restClient . delete ( "chatrooms/" + roomName + "/outcasts/" + jid , new HashMap < String , String > ( ) ) ; }
Delete outcast from chatroom .
5,786
public Response deleteOwnerGroup ( String roomName , String groupName ) { return restClient . delete ( "chatrooms/" + roomName + "/owners/group/" + groupName , new HashMap < String , String > ( ) ) ; }
Delete owner group from chatroom .
5,787
public Response deleteAdminGroup ( String roomName , String groupName ) { return restClient . delete ( "chatrooms/" + roomName + "/admins/group/" + groupName , new HashMap < String , String > ( ) ) ; }
Delete admin group from chatroom .
5,788
public Response deleteMemberGroup ( String roomName , String groupName ) { return restClient . delete ( "chatrooms/" + roomName + "/members/group/" + groupName , new HashMap < String , String > ( ) ) ; }
Delete member group from chatroom .
5,789
public Response addOutcastGroup ( String roomName , String groupName ) { return restClient . post ( "chatrooms/" + roomName + "/outcasts/group/" + groupName , null , new HashMap < String , String > ( ) ) ; }
Adds the group outcast .
5,790
public Response deleteOutcastGroup ( String roomName , String groupName ) { return restClient . delete ( "chatrooms/" + roomName + "/outcasts/group/" + groupName , new HashMap < String , String > ( ) ) ; }
Delete outcast group from chatroom .
5,791
public SessionEntities getSessions ( ) { SessionEntities sessionEntities = restClient . get ( "sessions" , SessionEntities . class , new HashMap < String , String > ( ) ) ; return sessionEntities ; }
Gets the sessions .
5,792
public Response deleteSessions ( String username ) { return restClient . delete ( "sessions/" + username , new HashMap < String , String > ( ) ) ; }
Close all user sessions .
5,793
public UserGroupsEntity getUserGroups ( String username ) { return restClient . get ( "users/" + username + "/groups" , UserGroupsEntity . class , new HashMap < String , String > ( ) ) ; }
Gets the user groups .
5,794
public Response addUserToGroups ( String username , UserGroupsEntity userGroupsEntity ) { return restClient . post ( "users/" + username + "/groups/" , userGroupsEntity , new HashMap < String , String > ( ) ) ; }
Adds the user to groups .
5,795
public Response addUserToGroup ( String username , String groupName ) { return restClient . post ( "users/" + username + "/groups/" + groupName , null , new HashMap < String , String > ( ) ) ; }
Adds the user to group .
5,796
public Response deleteUserFromGroup ( String username , String groupName ) { return restClient . delete ( "users/" + username + "/groups/" + groupName , new HashMap < String , String > ( ) ) ; }
Delete user from group .
5,797
public Response lockoutUser ( String username ) { return restClient . post ( "lockouts/" + username , null , new HashMap < String , String > ( ) ) ; }
Lockout user .
5,798
public Response unlockUser ( String username ) { return restClient . delete ( "lockouts/" + username , new HashMap < String , String > ( ) ) ; }
Unlock user .
5,799
public SystemProperty getSystemProperty ( String propertyName ) { return restClient . get ( "system/properties/" + propertyName , SystemProperty . class , new HashMap < String , String > ( ) ) ; }
Gets the system property .