idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
18,600 | private static Runnable asRunnable ( final ClientTransport . PingCallback callback , final Throwable failureCause ) { return new Runnable ( ) { public void run ( ) { callback . onFailure ( failureCause ) ; } } ; } | Returns a runnable that when run invokes the given callback providing the given cause of failure . |
18,601 | private boolean readRequiredBytes ( ) { int totalBytesRead = 0 ; int deflatedBytesRead = 0 ; try { if ( nextFrame == null ) { nextFrame = new CompositeReadableBuffer ( ) ; } int missingBytes ; while ( ( missingBytes = requiredLength - nextFrame . readableBytes ( ) ) > 0 ) { if ( fullStreamDecompressor != null ) { try {... | Attempts to read the required bytes into nextFrame . |
18,602 | private void processHeader ( ) { int type = nextFrame . readUnsignedByte ( ) ; if ( ( type & RESERVED_MASK ) != 0 ) { throw Status . INTERNAL . withDescription ( "gRPC frame header malformed: reserved bits not zero" ) . asRuntimeException ( ) ; } compressedFlag = ( type & COMPRESSED_FLAG_MASK ) != 0 ; requiredLength = ... | Processes the GRPC compression header which is composed of the compression flag and the outer frame length . |
18,603 | private void processBody ( ) { statsTraceCtx . inboundMessageRead ( currentMessageSeqNo , inboundBodyWireSize , - 1 ) ; inboundBodyWireSize = 0 ; InputStream stream = compressedFlag ? getCompressedBody ( ) : getUncompressedBody ( ) ; nextFrame = null ; listener . messagesAvailable ( new SingleMessageProducer ( stream )... | Processes the GRPC message body which depending on frame header flags may be compressed . |
18,604 | private static InetSocketAddress overrideProxy ( String proxyHostPort ) { if ( proxyHostPort == null ) { return null ; } String [ ] parts = proxyHostPort . split ( ":" , 2 ) ; int port = 80 ; if ( parts . length > 1 ) { port = Integer . parseInt ( parts [ 1 ] ) ; } log . warning ( "Detected GRPC_PROXY_EXP and will hono... | GRPC_PROXY_EXP is deprecated but let s maintain compatibility for now . |
18,605 | @ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , MessageSize . SMALL , FlowWindowSize . MEDIUM , ChannelType . NIO , 1 , 1 ) ; } | Setup with direct executors small payloads and the default flow control window . |
18,606 | public Object blockingUnary ( ) throws Exception { return ClientCalls . blockingUnaryCall ( channels [ 0 ] . newCall ( unaryMethod , CallOptions . DEFAULT ) , Unpooled . EMPTY_BUFFER ) ; } | Issue a unary call and wait for the response . |
18,607 | public ServerMethodDefinition < ReqT , RespT > withServerCallHandler ( ServerCallHandler < ReqT , RespT > handler ) { return new ServerMethodDefinition < > ( method , handler ) ; } | Create a new method definition with a different call handler . |
18,608 | private static List < Subchannel > filterNonFailingSubchannels ( Collection < Subchannel > subchannels ) { List < Subchannel > readySubchannels = new ArrayList < > ( subchannels . size ( ) ) ; for ( Subchannel subchannel : subchannels ) { if ( isReady ( subchannel ) ) { readySubchannels . add ( subchannel ) ; } } retur... | Filters out non - ready subchannels . |
18,609 | @ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , MessageSize . SMALL , FlowWindowSize . LARGE , ChannelType . NIO , maxConcurrentStreams , channelCount ) ; callCounter = new AtomicLong ( ) ; completed = new AtomicBoo... | Setup with direct executors small payloads and a large flow control window . |
18,610 | public CallOptions withoutWaitForReady ( ) { CallOptions newOptions = new CallOptions ( this ) ; newOptions . waitForReady = Boolean . FALSE ; return newOptions ; } | Disables wait for ready feature for the call . This method should be rarely used because the default is without wait for ready . |
18,611 | public < T > CallOptions withOption ( Key < T > key , T value ) { Preconditions . checkNotNull ( key , "key" ) ; Preconditions . checkNotNull ( value , "value" ) ; CallOptions newOptions = new CallOptions ( this ) ; int existingIdx = - 1 ; for ( int i = 0 ; i < customOptions . length ; i ++ ) { if ( key . equals ( cust... | Sets a custom option . Any existing value for the key is overwritten . |
18,612 | @ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1869" ) @ SuppressWarnings ( "unchecked" ) public < T > T getOption ( Key < T > key ) { Preconditions . checkNotNull ( key , "key" ) ; for ( int i = 0 ; i < customOptions . length ; i ++ ) { if ( key . equals ( customOptions [ i ] [ 0 ] ) ) { return ( T ) cu... | Get the value for a custom option or its inherent default . |
18,613 | @ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/2563" ) public CallOptions withMaxOutboundMessageSize ( int maxSize ) { checkArgument ( maxSize >= 0 , "invalid maxsize %s" , maxSize ) ; CallOptions newOptions = new CallOptions ( this ) ; newOptions . maxOutboundMessageSize = maxSize ; return newOptions ; ... | Sets the maximum allowed message size acceptable sent to the remote peer . |
18,614 | public boolean processBytesFromPeer ( ByteBuffer bytes ) throws GeneralSecurityException { if ( outputFrame == null && isClient ) { return true ; } if ( outputFrame != null && outputFrame . hasRemaining ( ) ) { return true ; } int remaining = bytes . remaining ( ) ; if ( outputFrame == null ) { checkState ( ! isClient ... | Process the bytes received from the peer . |
18,615 | public static TsiHandshaker newClient ( HandshakerServiceStub stub , AltsHandshakerOptions options ) { return new AltsTsiHandshaker ( true , stub , options ) ; } | Creates a new TsiHandshaker for use by the client . |
18,616 | public static TsiHandshaker newServer ( HandshakerServiceStub stub , AltsHandshakerOptions options ) { return new AltsTsiHandshaker ( false , stub , options ) ; } | Creates a new TsiHandshaker for use by the server . |
18,617 | public void getBytesToSendToPeer ( ByteBuffer bytes ) throws GeneralSecurityException { if ( outputFrame == null ) { if ( isClient ) { outputFrame = handshaker . startClientHandshake ( ) ; } else { return ; } } ByteBuffer outputFrameAlias = outputFrame ; if ( outputFrame . remaining ( ) > bytes . remaining ( ) ) { outp... | Gets bytes that need to be sent to the peer . |
18,618 | @ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , responseSize , clientInboundFlowWindow , ChannelType . NIO , maxConcurrentStreams , 1 ) ; callCounter = new AtomicLong ( ) ; completed = new AtomicBoolean ( ) ; record... | Setup with direct executors and one channel . |
18,619 | public void getServers ( GetServersRequest request , StreamObserver < GetServersResponse > responseObserver ) { ServerList servers = channelz . getServers ( request . getStartServerId ( ) , maxPageSize ) ; GetServersResponse resp ; try { resp = ChannelzProtoUtil . toGetServersResponse ( servers ) ; } catch ( StatusRunt... | Returns servers . |
18,620 | public void getSubchannel ( GetSubchannelRequest request , StreamObserver < GetSubchannelResponse > responseObserver ) { InternalInstrumented < ChannelStats > s = channelz . getSubchannel ( request . getSubchannelId ( ) ) ; if ( s == null ) { responseObserver . onError ( Status . NOT_FOUND . withDescription ( "Can't fi... | Returns a subchannel . |
18,621 | public synchronized void onDataReceived ( ) { stopwatch . reset ( ) . start ( ) ; if ( state == State . PING_SCHEDULED ) { state = State . PING_DELAYED ; } else if ( state == State . PING_SENT || state == State . IDLE_AND_PING_SENT ) { if ( shutdownFuture != null ) { shutdownFuture . cancel ( false ) ; } if ( state == ... | Transport has received some data so that we can delay sending keepalives . |
18,622 | public synchronized void onTransportActive ( ) { if ( state == State . IDLE ) { state = State . PING_SCHEDULED ; if ( pingFuture == null ) { pingFuture = scheduler . schedule ( sendPing , keepAliveTimeInNanos - stopwatch . elapsed ( TimeUnit . NANOSECONDS ) , TimeUnit . NANOSECONDS ) ; } } else if ( state == State . ID... | Transport has active streams . Start sending keepalives if necessary . |
18,623 | public synchronized void onTransportIdle ( ) { if ( keepAliveDuringTransportIdle ) { return ; } if ( state == State . PING_SCHEDULED || state == State . PING_DELAYED ) { state = State . IDLE ; } if ( state == State . PING_SENT ) { state = State . IDLE_AND_PING_SENT ; } } | Transport has finished all streams . |
18,624 | public synchronized void onTransportTermination ( ) { if ( state != State . DISCONNECTED ) { state = State . DISCONNECTED ; if ( shutdownFuture != null ) { shutdownFuture . cancel ( false ) ; } if ( pingFuture != null ) { pingFuture . cancel ( false ) ; pingFuture = null ; } } } | Transport is being terminated . We no longer need to do keepalives . |
18,625 | public void sendMessage ( View view ) { ( ( InputMethodManager ) getSystemService ( Context . INPUT_METHOD_SERVICE ) ) . hideSoftInputFromWindow ( hostEdit . getWindowToken ( ) , 0 ) ; sendButton . setEnabled ( false ) ; resultText . setText ( "" ) ; new GrpcTask ( this , cache ) . execute ( hostEdit . getText ( ) . to... | Sends RPC . Invoked when app button is pressed . |
18,626 | void notifyWhenStateChanged ( Runnable callback , Executor executor , ConnectivityState source ) { checkNotNull ( callback , "callback" ) ; checkNotNull ( executor , "executor" ) ; checkNotNull ( source , "source" ) ; Listener stateChangeListener = new Listener ( callback , executor ) ; if ( state != source ) { stateCh... | Adds a listener for state change event . |
18,627 | public static < T extends Message > Metadata . Key < T > keyForProto ( T instance ) { return Metadata . Key . of ( instance . getDescriptorForType ( ) . getFullName ( ) + Metadata . BINARY_HEADER_SUFFIX , metadataMarshaller ( instance ) ) ; } | Produce a metadata key for a generated protobuf type . |
18,628 | public HandshakerResp send ( HandshakerReq req ) throws InterruptedException , IOException { maybeThrowIoException ( ) ; if ( ! responseQueue . isEmpty ( ) ) { throw new IOException ( "Received an unexpected response." ) ; } writer . onNext ( req ) ; Optional < HandshakerResp > result = responseQueue . take ( ) ; if ( ... | Send a handshaker request and return the handshaker response . |
18,629 | private int writeKnownLengthUncompressed ( InputStream message , int messageLength ) throws IOException { if ( maxOutboundMessageSize >= 0 && messageLength > maxOutboundMessageSize ) { throw Status . RESOURCE_EXHAUSTED . withDescription ( String . format ( "message too large %d > %d" , messageLength , maxOutboundMessag... | Write an unserialized message with a known length uncompressed . |
18,630 | private void writeBufferChain ( BufferChainOutputStream bufferChain , boolean compressed ) { ByteBuffer header = ByteBuffer . wrap ( headerScratch ) ; header . put ( compressed ? COMPRESSED : UNCOMPRESSED ) ; int messageLength = bufferChain . readableBytes ( ) ; header . putInt ( messageLength ) ; WritableBuffer writea... | Write a message that has been serialized to a sequence of buffers . |
18,631 | public void close ( ) { if ( ! isClosed ( ) ) { closed = true ; if ( buffer != null && buffer . readableBytes ( ) == 0 ) { releaseBuffer ( ) ; } commitToSink ( true , true ) ; } } | Flushes and closes the framer and releases any buffers . After the framer is closed or disposed additional calls to this method will have no affect . |
18,632 | private void setStartClientFields ( HandshakerReq . Builder req ) { StartClientHandshakeReq . Builder startClientReq = StartClientHandshakeReq . newBuilder ( ) . setHandshakeSecurityProtocol ( HandshakeProtocol . ALTS ) . addApplicationProtocols ( APPLICATION_PROTOCOL ) . addRecordProtocols ( RECORD_PROTOCOL ) ; if ( h... | Sets the start client fields for the passed handshake request . |
18,633 | private void setStartServerFields ( HandshakerReq . Builder req , ByteBuffer inBytes ) { ServerHandshakeParameters serverParameters = ServerHandshakeParameters . newBuilder ( ) . addRecordProtocols ( RECORD_PROTOCOL ) . build ( ) ; StartServerHandshakeReq . Builder startServerReq = StartServerHandshakeReq . newBuilder ... | Sets the start server fields for the passed handshake request . |
18,634 | public boolean isFinished ( ) { if ( result != null ) { return true ; } if ( status != null && status . getCode ( ) != Status . Code . OK . value ( ) ) { return true ; } return false ; } | Returns true if the handshake is complete . |
18,635 | public byte [ ] getKey ( ) { if ( result == null ) { return null ; } if ( result . getKeyData ( ) . size ( ) < KEY_LENGTH ) { throw new IllegalStateException ( "Could not get enough key data from the handshake." ) ; } byte [ ] key = new byte [ KEY_LENGTH ] ; result . getKeyData ( ) . copyTo ( key , 0 , 0 , KEY_LENGTH )... | Returns the resulting key of the handshake if the handshake is completed . Note that the key data returned from the handshake may be more than the key length required for the record protocol thus we need to truncate to the right size . |
18,636 | private void handleResponse ( HandshakerResp resp ) throws GeneralSecurityException { status = resp . getStatus ( ) ; if ( resp . hasResult ( ) ) { result = resp . getResult ( ) ; close ( ) ; } if ( status . getCode ( ) != Status . Code . OK . value ( ) ) { String error = "Handshaker service error: " + status . getDeta... | Parses a handshake response setting the status result and closing the handshaker as needed . |
18,637 | public static CronetChannelBuilder forAddress ( String host , int port , CronetEngine cronetEngine ) { Preconditions . checkNotNull ( cronetEngine , "cronetEngine" ) ; return new CronetChannelBuilder ( host , port , cronetEngine ) ; } | Creates a new builder for the given server host port and CronetEngine . |
18,638 | public void start ( ) throws IOException { server . start ( ) ; logger . info ( "Server started, listening on " + port ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { System . err . println ( "*** shutting down gRPC server since JVM is shutting down" ) ; RouteGuideServer . this .... | Start serving requests . |
18,639 | public static void main ( String [ ] args ) throws Exception { RouteGuideServer server = new RouteGuideServer ( 8980 ) ; server . start ( ) ; server . blockUntilShutdown ( ) ; } | Main method . This comment makes the linter happy . |
18,640 | private NettyServerHandler createHandler ( ServerTransportListener transportListener , ChannelPromise channelUnused ) { return NettyServerHandler . newHandler ( transportListener , channelUnused , streamTracerFactories , transportTracer , maxStreams , flowControlWindow , maxHeaderListSize , maxMessageSize , keepAliveTi... | Creates the Netty handler to be used in the channel pipeline . |
18,641 | void recordDroppedRequest ( String category ) { AtomicLong counter = dropCounters . get ( category ) ; if ( counter == null ) { counter = dropCounters . putIfAbsent ( category , new AtomicLong ( ) ) ; if ( counter == null ) { counter = dropCounters . get ( category ) ; } } counter . getAndIncrement ( ) ; } | Record that a request has been dropped by drop overload policy with the provided category instructed by the remote balancer . |
18,642 | void handleAddresses ( List < LbAddressGroup > newLbAddressGroups , List < EquivalentAddressGroup > newBackendServers ) { if ( newLbAddressGroups . isEmpty ( ) ) { shutdownLbComm ( ) ; syncContext . execute ( new FallbackModeTask ( ) ) ; } else { LbAddressGroup newLbAddressGroup = flattenLbAddressGroups ( newLbAddressG... | Handle new addresses of the balancer and backends from the resolver and create connection if not yet connected . |
18,643 | private void useFallbackBackends ( ) { usingFallbackBackends = true ; logger . log ( ChannelLogLevel . INFO , "Using fallback backends" ) ; List < DropEntry > newDropList = new ArrayList < > ( ) ; List < BackendAddressGroup > newBackendAddrList = new ArrayList < > ( ) ; for ( EquivalentAddressGroup eag : fallbackBacken... | Populate the round - robin lists with the fallback backends . |
18,644 | private void maybeUpdatePicker ( ) { List < RoundRobinEntry > pickList ; ConnectivityState state ; switch ( mode ) { case ROUND_ROBIN : pickList = new ArrayList < > ( backendList . size ( ) ) ; Status error = null ; boolean hasIdle = false ; for ( BackendEntry entry : backendList ) { Subchannel subchannel = entry . sub... | Make and use a picker out of the current lists and the states of subchannels if they have changed since the last picker created . |
18,645 | private void maybeUpdatePicker ( ConnectivityState state , RoundRobinPicker picker ) { if ( picker . dropList . equals ( currentPicker . dropList ) && picker . pickList . equals ( currentPicker . pickList ) ) { return ; } currentPicker = picker ; logger . log ( ChannelLogLevel . INFO , "{0}: picks={1}, drops={2}" , sta... | Update the given picker to the helper if it s different from the current one . |
18,646 | private static EquivalentAddressGroup flattenEquivalentAddressGroup ( List < EquivalentAddressGroup > groupList , Attributes attrs ) { List < SocketAddress > addrs = new ArrayList < > ( ) ; for ( EquivalentAddressGroup group : groupList ) { addrs . addAll ( group . getAddresses ( ) ) ; } return new EquivalentAddressGro... | Flattens list of EquivalentAddressGroup objects into one EquivalentAddressGroup object . |
18,647 | void cancel ( boolean permanent ) { enabled = false ; if ( permanent && wakeUp != null ) { wakeUp . cancel ( false ) ; wakeUp = null ; } } | must be called from channel executor |
18,648 | private static InetAddress buildBenchmarkAddr ( ) { InetAddress tmp = null ; try { Enumeration < NetworkInterface > networkInterfaces = NetworkInterface . getNetworkInterfaces ( ) ; outer : while ( networkInterfaces . hasMoreElements ( ) ) { NetworkInterface networkInterface = networkInterfaces . nextElement ( ) ; if (... | Resolve the address bound to the benchmark interface . Currently we assume it s a child interface of the loopback interface with the term benchmark in its name . |
18,649 | protected void teardown ( ) throws Exception { logger . fine ( "shutting down channels" ) ; for ( ManagedChannel channel : channels ) { channel . shutdown ( ) ; } logger . fine ( "shutting down server" ) ; server . shutdown ( ) ; if ( ! server . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { logger . warning ( "Failed... | Shutdown all the client channels and then shutdown the server . |
18,650 | void onTransportIdle ( ) { isActive = false ; if ( shutdownFuture == null ) { return ; } if ( shutdownFuture . isDone ( ) ) { shutdownDelayed = false ; shutdownFuture = scheduler . schedule ( shutdownTask , maxConnectionIdleInNanos , TimeUnit . NANOSECONDS ) ; } else { nextIdleMonitorTime = ticker . nanoTime ( ) + maxC... | There are no outstanding RPCs on the transport . |
18,651 | public void start ( final Listener listener ) { if ( listener instanceof Observer ) { start ( ( Observer ) listener ) ; } else { start ( new Observer ( ) { public void onError ( Status error ) { listener . onError ( error ) ; } public void onResult ( ResolutionResult resolutionResult ) { listener . onAddresses ( resolu... | Starts the resolution . |
18,652 | public void addServer ( InternalInstrumented < ServerStats > server ) { ServerSocketMap prev = perServerSockets . put ( id ( server ) , new ServerSocketMap ( ) ) ; assert prev == null ; add ( servers , server ) ; } | Adds a server . |
18,653 | public void addServerSocket ( InternalInstrumented < ServerStats > server , InternalInstrumented < SocketStats > socket ) { ServerSocketMap serverSockets = perServerSockets . get ( id ( server ) ) ; assert serverSockets != null ; add ( serverSockets , socket ) ; } | Adds a server socket . |
18,654 | public void removeServer ( InternalInstrumented < ServerStats > server ) { remove ( servers , server ) ; ServerSocketMap prev = perServerSockets . remove ( id ( server ) ) ; assert prev != null ; assert prev . isEmpty ( ) ; } | Removes a server . |
18,655 | public void removeServerSocket ( InternalInstrumented < ServerStats > server , InternalInstrumented < SocketStats > socket ) { ServerSocketMap socketsOfServer = perServerSockets . get ( id ( server ) ) ; assert socketsOfServer != null ; remove ( socketsOfServer , socket ) ; } | Removes a server socket . |
18,656 | public ServerList getServers ( long fromId , int maxPageSize ) { List < InternalInstrumented < ServerStats > > serverList = new ArrayList < > ( maxPageSize ) ; Iterator < InternalInstrumented < ServerStats > > iterator = servers . tailMap ( fromId ) . values ( ) . iterator ( ) ; while ( iterator . hasNext ( ) && server... | Returns a server list . |
18,657 | public ServerSocketsList getServerSockets ( long serverId , long fromId , int maxPageSize ) { ServerSocketMap serverSockets = perServerSockets . get ( serverId ) ; if ( serverSockets == null ) { return null ; } List < InternalWithLogId > socketList = new ArrayList < > ( maxPageSize ) ; Iterator < InternalInstrumented <... | Returns socket refs for a server . |
18,658 | public PersistentHashArrayMappedTrie < K , V > put ( K key , V value ) { if ( root == null ) { return new PersistentHashArrayMappedTrie < > ( new Leaf < > ( key , value ) ) ; } else { return new PersistentHashArrayMappedTrie < > ( root . put ( key , value , key . hashCode ( ) , 0 ) ) ; } } | Returns a new trie where the key is set to the specified value . |
18,659 | public static String generateFullMethodName ( String fullServiceName , String methodName ) { return checkNotNull ( fullServiceName , "fullServiceName" ) + "/" + checkNotNull ( methodName , "methodName" ) ; } | Generate the fully qualified method name . This matches the name |
18,660 | public < NewReqT , NewRespT > Builder < NewReqT , NewRespT > toBuilder ( Marshaller < NewReqT > requestMarshaller , Marshaller < NewRespT > responseMarshaller ) { return MethodDescriptor . < NewReqT , NewRespT > newBuilder ( ) . setRequestMarshaller ( requestMarshaller ) . setResponseMarshaller ( responseMarshaller ) .... | Turns this descriptor into a builder replacing the request and response marshallers . |
18,661 | public static AltsServerBuilder forPort ( int port ) { NettyServerBuilder nettyDelegate = NettyServerBuilder . forAddress ( new InetSocketAddress ( port ) ) ; return new AltsServerBuilder ( nettyDelegate ) ; } | Creates a gRPC server builder for the given port . |
18,662 | static String makeTargetStringForDirectAddress ( SocketAddress address ) { try { return new URI ( DIRECT_ADDRESS_SCHEME , "" , "/" + address , null ) . toString ( ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; } } | Returns a target string for the SocketAddress . It is only used as a placeholder because DirectAddressNameResolverFactory will not actually try to use it . However it must be a valid URI . |
18,663 | ClientStream returnStream ( ) { synchronized ( lock ) { if ( returnedStream == null ) { delayedStream = new DelayedStream ( ) ; return returnedStream = delayedStream ; } else { return returnedStream ; } } } | Return a stream on which the RPC will run on . |
18,664 | @ Setup ( Level . Trial ) public void setup ( ) throws Exception { super . setup ( clientExecutor , ExecutorType . DIRECT , MessageSize . SMALL , responseSize , FlowWindowSize . MEDIUM , ChannelType . NIO , maxConcurrentStreams , channelCount ) ; callCounter = new AtomicLong ( ) ; completed = new AtomicBoolean ( ) ; re... | Setup with direct executors small payloads and the default flow - control window . |
18,665 | @ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1704" ) public Set < String > getAdvertisedMessageEncodings ( ) { Set < String > advertisedDecompressors = new HashSet < > ( decompressors . size ( ) ) ; for ( Entry < String , DecompressorInfo > entry : decompressors . entrySet ( ) ) { if ( entry . getValue... | Provides a list of all message encodings that have decompressors available and should be advertised . |
18,666 | @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public ByteBuf encodeClientHeaders ( ) throws Exception { scratchBuffer . clear ( ) ; Http2Headers headers = Utils . convertClientHeaders ( metadata , scheme , defaultPath , authority , Utils . HTTP_METHOD , userAgent ) ; headersEncoder .... | This will encode the random metadata fields and repeatedly lookup the default other headers . |
18,667 | private void sendInitialConnectionWindow ( ) throws Http2Exception { if ( ctx . channel ( ) . isActive ( ) && initialConnectionWindow > 0 ) { Http2Stream connectionStream = connection ( ) . connectionStream ( ) ; int currentSize = connection ( ) . local ( ) . flowController ( ) . windowSize ( connectionStream ) ; int d... | Sends initial connection window to the remote endpoint if necessary . |
18,668 | Stats . ClientStats getStats ( ) { Histogram intervalHistogram = recorder . getIntervalHistogram ( ) ; Stats . ClientStats . Builder statsBuilder = Stats . ClientStats . newBuilder ( ) ; Stats . HistogramData . Builder latenciesBuilder = statsBuilder . getLatenciesBuilder ( ) ; double resolution = 1.0 + Math . max ( co... | Take a snapshot of the statistics which can be returned to the driver . |
18,669 | void delay ( long alreadyElapsed ) { recorder . recordValue ( alreadyElapsed ) ; if ( distribution != null ) { long nextPermitted = Math . round ( distribution . sample ( ) * 1000000000.0 ) ; if ( nextPermitted > alreadyElapsed ) { LockSupport . parkNanos ( nextPermitted - alreadyElapsed ) ; } } } | Record the event elapsed time to the histogram and delay initiation of the next event based on the load distribution . |
18,670 | public void getFeature ( int lat , int lon ) { info ( "*** GetFeature: lat={0} lon={1}" , lat , lon ) ; Point request = Point . newBuilder ( ) . setLatitude ( lat ) . setLongitude ( lon ) . build ( ) ; Feature feature ; try { feature = blockingStub . getFeature ( request ) ; if ( testHelper != null ) { testHelper . onM... | Blocking unary call example . Calls getFeature and prints the response . |
18,671 | public void listFeatures ( int lowLat , int lowLon , int hiLat , int hiLon ) { info ( "*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}" , lowLat , lowLon , hiLat , hiLon ) ; Rectangle request = Rectangle . newBuilder ( ) . setLo ( Point . newBuilder ( ) . setLatitude ( lowLat ) . setLongitude ( lowLon ) . b... | Blocking server - streaming example . Calls listFeatures with a rectangle of interest . Prints each response feature as it arrives . |
18,672 | public CountDownLatch routeChat ( ) { info ( "*** RouteChat" ) ; final CountDownLatch finishLatch = new CountDownLatch ( 1 ) ; StreamObserver < RouteNote > requestObserver = asyncStub . routeChat ( new StreamObserver < RouteNote > ( ) { public void onNext ( RouteNote note ) { info ( "Got message \"{0}\" at {1}, {2}" , ... | Bi - directional example which can only be asynchronous . Send some chat messages and print any chat messages that are sent from the server . |
18,673 | public static void main ( String [ ] args ) throws InterruptedException { List < Feature > features ; try { features = RouteGuideUtil . parseFeatures ( RouteGuideUtil . getDefaultFeaturesFile ( ) ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; return ; } RouteGuideClient client = new RouteGuideClient ( "loc... | Issues several different requests and then exits . |
18,674 | private void handleServiceConfigUpdate ( ) { waitingForServiceConfig = false ; serviceConfigInterceptor . handleUpdate ( lastServiceConfig ) ; if ( retryEnabled ) { throttle = ServiceConfigUtil . getThrottlePolicy ( lastServiceConfig ) ; } } | May only be called in constructor or syncContext |
18,675 | public ManagedChannelImpl shutdown ( ) { channelLogger . log ( ChannelLogLevel . DEBUG , "shutdown() called" ) ; if ( ! shutdown . compareAndSet ( false , true ) ) { return this ; } final class Shutdown implements Runnable { public void run ( ) { channelLogger . log ( ChannelLogLevel . INFO , "Entering SHUTDOWN state" ... | Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately cancelled . |
18,676 | public static List < Feature > parseFeatures ( URL file ) throws IOException { InputStream input = file . openStream ( ) ; try { Reader reader = new InputStreamReader ( input , Charset . forName ( "UTF-8" ) ) ; try { FeatureDatabase . Builder database = FeatureDatabase . newBuilder ( ) ; JsonFormat . parser ( ) . merge... | Parses the JSON input file containing the list of features . |
18,677 | public TransportStats getStats ( ) { long localFlowControlWindow = flowControlWindowReader == null ? - 1 : flowControlWindowReader . read ( ) . localBytes ; long remoteFlowControlWindow = flowControlWindowReader == null ? - 1 : flowControlWindowReader . read ( ) . remoteBytes ; return new TransportStats ( streamsStarte... | Returns a read only set of current stats . |
18,678 | public static void main ( String [ ] args ) throws Exception { CustomHeaderClient client = new CustomHeaderClient ( "localhost" , 50051 ) ; try { String user = "world" ; if ( args . length > 0 ) { user = args [ 0 ] ; } client . greet ( user ) ; } finally { client . shutdown ( ) ; } } | Main start the client from the command line . |
18,679 | public static void asyncUnimplementedUnaryCall ( MethodDescriptor < ? , ? > methodDescriptor , StreamObserver < ? > responseObserver ) { checkNotNull ( methodDescriptor , "methodDescriptor" ) ; checkNotNull ( responseObserver , "responseObserver" ) ; responseObserver . onError ( Status . UNIMPLEMENTED . withDescription... | Sets unimplemented status for method on given response stream for unary call . |
18,680 | public static < T > StreamObserver < T > asyncUnimplementedStreamingCall ( MethodDescriptor < ? , ? > methodDescriptor , StreamObserver < ? > responseObserver ) { asyncUnimplementedUnaryCall ( methodDescriptor , responseObserver ) ; return new NoopStreamObserver < > ( ) ; } | Sets unimplemented status for streaming call . |
18,681 | public ScheduledFuture < ? > runOnExpiration ( Runnable task , ScheduledExecutorService scheduler ) { checkNotNull ( task , "task" ) ; checkNotNull ( scheduler , "scheduler" ) ; return scheduler . schedule ( task , deadlineNanos - ticker . read ( ) , TimeUnit . NANOSECONDS ) ; } | Schedule a task to be run when the deadline expires . |
18,682 | private void sendHandshake ( ChannelHandlerContext ctx ) { boolean needToFlush = false ; while ( true ) { buffer = getOrCreateBuffer ( ctx . alloc ( ) ) ; try { handshaker . getBytesToSendToPeer ( buffer ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( e ) ; } if ( ! buffer . isReadable ( ) ) {... | Sends as many bytes as are available from the handshaker to the remote peer . |
18,683 | public static < T > T release ( final Resource < T > resource , final T instance ) { return holder . releaseInternal ( resource , instance ) ; } | Releases an instance of the given resource . |
18,684 | public final OkHttpChannelBuilder enableKeepAlive ( boolean enable ) { if ( enable ) { return keepAliveTime ( DEFAULT_KEEPALIVE_TIME_NANOS , TimeUnit . NANOSECONDS ) ; } else { return keepAliveTime ( KEEPALIVE_TIME_NANOS_DISABLED , TimeUnit . NANOSECONDS ) ; } } | Enable keepalive with default delay and timeout . |
18,685 | public final OkHttpChannelBuilder connectionSpec ( com . squareup . okhttp . ConnectionSpec connectionSpec ) { Preconditions . checkArgument ( connectionSpec . isTls ( ) , "plaintext ConnectionSpec is not accepted" ) ; this . connectionSpec = Utils . convertSpec ( connectionSpec ) ; return this ; } | For secure connection provides a ConnectionSpec to specify Cipher suite and TLS versions . |
18,686 | void data ( boolean outFinished , int streamId , Buffer source , boolean flush ) { Preconditions . checkNotNull ( source , "source" ) ; OkHttpClientStream stream = transport . getStream ( streamId ) ; if ( stream == null ) { return ; } OutboundFlowState state = state ( stream ) ; int window = state . writableWindow ( )... | Must be called with holding transport lock . |
18,687 | void writeStreams ( ) { OkHttpClientStream [ ] streams = transport . getActiveStreams ( ) ; int connectionWindow = connectionState . window ( ) ; for ( int numStreams = streams . length ; numStreams > 0 && connectionWindow > 0 ; ) { int nextNumStreams = 0 ; int windowSlice = ( int ) ceil ( connectionWindow / ( float ) ... | Writes as much data for all the streams as possible given the current flow control windows . |
18,688 | static String generateTraceSpanName ( boolean isServer , String fullMethodName ) { String prefix = isServer ? "Recv" : "Sent" ; return prefix + "." + fullMethodName . replace ( '/' , '.' ) ; } | Convert a full method name to a tracing span name . |
18,689 | private void advanceBufferIfNecessary ( ) { ReadableBuffer buffer = buffers . peek ( ) ; if ( buffer . readableBytes ( ) == 0 ) { buffers . remove ( ) . close ( ) ; } } | If the current buffer is exhausted removes and closes it . |
18,690 | public ServerImpl start ( ) throws IOException { synchronized ( lock ) { checkState ( ! started , "Already started" ) ; checkState ( ! shutdown , "Shutting down" ) ; ServerListenerImpl listener = new ServerListenerImpl ( ) ; for ( InternalServer ts : transportServers ) { ts . start ( listener ) ; activeTransportServers... | Bind and start the server . |
18,691 | public ServerImpl shutdown ( ) { boolean shutdownTransportServers ; synchronized ( lock ) { if ( shutdown ) { return this ; } shutdown = true ; shutdownTransportServers = started ; if ( ! shutdownTransportServers ) { transportServersTerminated = true ; checkForTermination ( ) ; } } if ( shutdownTransportServers ) { for... | Initiates an orderly shutdown in which preexisting calls continue but new calls are rejected . |
18,692 | private void transportClosed ( ServerTransport transport ) { synchronized ( lock ) { if ( ! transports . remove ( transport ) ) { throw new AssertionError ( "Transport already removed" ) ; } channelz . removeServerSocket ( ServerImpl . this , transport ) ; checkForTermination ( ) ; } } | Remove transport service from accounting collection and notify of complete shutdown if necessary . |
18,693 | private void checkForTermination ( ) { synchronized ( lock ) { if ( shutdown && transports . isEmpty ( ) && transportServersTerminated ) { if ( terminated ) { throw new AssertionError ( "Server already terminated" ) ; } terminated = true ; channelz . removeServer ( this ) ; if ( executor != null ) { executor = executor... | Notify of complete shutdown if necessary . |
18,694 | public static ProtocolNegotiator serverPlaintext ( ) { return new ProtocolNegotiator ( ) { public ChannelHandler newHandler ( final GrpcHttp2ConnectionHandler handler ) { class PlaintextHandler extends ChannelHandlerAdapter { public void handlerAdded ( ChannelHandlerContext ctx ) throws Exception { handler . handleProt... | Create a server plaintext handler for gRPC . |
18,695 | void enqueue ( Runnable runnable , boolean flush ) { queue . add ( new RunnableCommand ( runnable ) ) ; if ( flush ) { scheduleFlush ( ) ; } } | Enqueue the runnable . It is not safe for another thread to queue an Runnable directly to the event loop because it will be out - of - order with writes . This method allows the Runnable to be processed in - order with writes . |
18,696 | private void flush ( ) { try { QueuedCommand cmd ; int i = 0 ; boolean flushedOnce = false ; while ( ( cmd = queue . poll ( ) ) != null ) { cmd . run ( channel ) ; if ( ++ i == DEQUE_CHUNK_SIZE ) { i = 0 ; channel . flush ( ) ; flushedOnce = true ; } } if ( i != 0 || ! flushedOnce ) { channel . flush ( ) ; } } finally ... | Process the queue of commands and dispatch them to the stream . This method is only called in the event loop |
18,697 | @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Context doWrite ( ContextState state , Blackhole bh ) { return state . context . withValues ( state . key1 , state . val , state . key2 , state . val , state . key3 , state . val , state . key4 , state . val ) ; } | Perform the write operation . |
18,698 | public void pingPong ( AdditionalCounters counters ) throws Exception { record . set ( true ) ; Thread . sleep ( 1001 ) ; record . set ( false ) ; } | Measure throughput of unary calls . The calls are already running we just observe a counter of received responses . |
18,699 | public final void shutdownNow ( Status status ) { shutdown ( status ) ; Collection < PendingStream > savedPendingStreams ; Runnable savedReportTransportTerminated ; synchronized ( lock ) { savedPendingStreams = pendingStreams ; savedReportTransportTerminated = reportTransportTerminated ; reportTransportTerminated = nul... | Shuts down this transport and cancels all streams that it owns hence immediately terminates this transport . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.