idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,500
public Response build ( final WebApplicationService webApplicationService , final String ticketId , final Authentication authentication ) { val service = ( OpenIdService ) webApplicationService ; val parameterList = new ParameterList ( HttpRequestUtils . getHttpServletRequestFromRequestAttributes ( ) . getParameterMap ...
Generates an Openid response . If no ticketId is found response is negative . If we have a ticket id then we check if we have an association . If so we ask OpenId server manager to generate the answer according with the existing association . If not we send back an answer with the ticket id as association handle . This...
18,501
protected String determineIdentity ( final OpenIdService service , final Assertion assertion ) { if ( assertion != null && OpenIdProtocolConstants . OPENID_IDENTIFIERSELECT . equals ( service . getIdentity ( ) ) ) { return this . openIdPrefixUrl + '/' + assertion . getPrimaryAuthentication ( ) . getPrincipal ( ) . getI...
Determine identity .
18,502
protected Association getAssociation ( final ServerManager serverManager , final ParameterList parameterList ) { try { val authReq = AuthRequest . createAuthRequest ( parameterList , serverManager . getRealmVerifier ( ) ) ; val parameterMap = authReq . getParameterMap ( ) ; if ( parameterMap != null && ! parameterMap ....
Gets association .
18,503
@ DeleteMapping ( value = "/v1/tickets/{tgtId:.+}" ) public ResponseEntity < String > deleteTicketGrantingTicket ( @ PathVariable ( "tgtId" ) final String tgtId ) { this . centralAuthenticationService . destroyTicketGrantingTicket ( tgtId ) ; return new ResponseEntity < > ( tgtId , HttpStatus . OK ) ; }
Destroy ticket granting ticket .
18,504
protected ResponseEntity < String > createResponseEntityForTicket ( final HttpServletRequest request , final TicketGrantingTicket tgtId ) throws Exception { return this . ticketGrantingTicketResourceEntityResponseFactory . build ( tgtId , request ) ; }
Create response entity for ticket response entity .
18,505
protected TicketGrantingTicket createTicketGrantingTicketForRequest ( final MultiValueMap < String , String > requestBody , final HttpServletRequest request ) { val credential = this . credentialFactory . fromRequest ( request , requestBody ) ; if ( credential == null || credential . isEmpty ( ) ) { throw new BadRestRe...
Create ticket granting ticket for request ticket granting ticket .
18,506
@ ShellMethod ( key = "decrypt-value" , value = "Encrypt a CAS property value/setting via Jasypt" ) public void decryptValue ( @ ShellOption ( value = { "value" } , help = "Value to encrypt" ) final String value , @ ShellOption ( value = { "alg" } , help = "Algorithm to use to encrypt" ) final String alg , @ ShellOptio...
Decrypt a value using Jasypt .
18,507
protected void transformPassword ( final UsernamePasswordCredential userPass ) throws FailedLoginException , AccountNotFoundException { if ( StringUtils . isBlank ( userPass . getPassword ( ) ) ) { throw new FailedLoginException ( "Password is null." ) ; } LOGGER . debug ( "Attempting to encode credential password via ...
Transform password .
18,508
protected void transformUsername ( final UsernamePasswordCredential userPass ) throws AccountNotFoundException { if ( StringUtils . isBlank ( userPass . getUsername ( ) ) ) { throw new AccountNotFoundException ( "Username is null." ) ; } LOGGER . debug ( "Transforming credential username via [{}]" , this . principalNam...
Transform username .
18,509
public void setStatus ( String service , ServingStatus status ) { checkNotNull ( status , "status" ) ; healthService . setStatus ( service , status ) ; }
Updates the status of the server .
18,510
public static StatsTraceContext newClientContext ( final CallOptions callOptions , final Attributes transportAttrs , Metadata headers ) { List < ClientStreamTracer . Factory > factories = callOptions . getStreamTracerFactories ( ) ; if ( factories . isEmpty ( ) ) { return NOOP ; } ClientStreamTracer . StreamInfo info =...
Factory method for the client - side .
18,511
public static StatsTraceContext newServerContext ( List < ? extends ServerStreamTracer . Factory > factories , String fullMethodName , Metadata headers ) { if ( factories . isEmpty ( ) ) { return NOOP ; } StreamTracer [ ] tracers = new StreamTracer [ factories . size ( ) ] ; for ( int i = 0 ; i < tracers . length ; i +...
Factory method for the server - side .
18,512
static boolean isGreaterThanOrEqualTo ( Version first , Version second ) { if ( ( first . getMajor ( ) > second . getMajor ( ) ) || ( first . getMajor ( ) == second . getMajor ( ) && first . getMinor ( ) >= second . getMinor ( ) ) ) { return true ; } return false ; }
Returns true if first Rpc Protocol Version is greater than or equal to the second one . Returns false otherwise .
18,513
static RpcVersionsCheckResult checkRpcProtocolVersions ( RpcProtocolVersions localVersions , RpcProtocolVersions peerVersions ) { Version maxCommonVersion ; Version minCommonVersion ; if ( isGreaterThanOrEqualTo ( localVersions . getMaxRpcVersion ( ) , peerVersions . getMaxRpcVersion ( ) ) ) { maxCommonVersion = peerVe...
Performs check between local and peer Rpc Protocol Versions . This function returns true and the highest common version if there exists a common Rpc Protocol Version to use and returns false and null otherwise .
18,514
private void createStream ( final CreateStreamCommand command , final ChannelPromise promise ) throws Exception { if ( lifecycleManager . getShutdownThrowable ( ) != null ) { command . stream ( ) . setNonExistent ( ) ; command . stream ( ) . transportReportStatus ( lifecycleManager . getShutdownStatus ( ) , RpcProgress...
Attempts to create a new stream from the given command . If there are too many active streams the creation request is queued .
18,515
private void cancelStream ( ChannelHandlerContext ctx , CancelClientStreamCommand cmd , ChannelPromise promise ) { NettyClientStream . TransportState stream = cmd . stream ( ) ; Status reason = cmd . reason ( ) ; if ( reason != null ) { stream . transportReportStatus ( reason , true , new Metadata ( ) ) ; } if ( ! cmd ...
Cancels this stream .
18,516
private void sendPingFrame ( ChannelHandlerContext ctx , SendPingCommand msg , ChannelPromise promise ) { PingCallback callback = msg . callback ( ) ; Executor executor = msg . executor ( ) ; if ( ping != null ) { promise . setSuccess ( ) ; ping . addCallback ( callback , executor ) ; return ; } promise . setSuccess ( ...
Sends a PING frame . If a ping operation is already outstanding the callback in the message is registered to be called when the existing operation completes and no new frame is sent .
18,517
private void goingAway ( Status status ) { lifecycleManager . notifyShutdown ( status ) ; final Status goAwayStatus = lifecycleManager . getShutdownStatus ( ) ; final int lastKnownStream = connection ( ) . local ( ) . lastStreamKnownByPeer ( ) ; try { connection ( ) . forEachActiveStream ( new Http2StreamVisitor ( ) { ...
Handler for a GOAWAY being received . Fails any streams created after the last known stream .
18,518
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public CallOptions withOption ( ) { CallOptions opts = CallOptions . DEFAULT ; for ( int i = 0 ; i < customOptions . size ( ) ; i ++ ) { opts = opts . withOption ( customOptions . get ( i ) , "value" ) ; } return opts ; }
Adding custom call options without duplicate keys .
18,519
@ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public CallOptions withOptionDuplicates ( ) { CallOptions opts = allOpts ; for ( int i = 1 ; i < shuffledCustomOptions . size ( ) ; i ++ ) { opts = opts . withOption ( shuffledCustomOptions . get ( i ) , "value2" ) ; } return opts ; }
Adding custom call options overwritting existing keys .
18,520
public NettyServerBuilder bossEventLoopGroup ( EventLoopGroup group ) { if ( group != null ) { return bossEventLoopGroupPool ( new FixedObjectPool < > ( group ) ) ; } return bossEventLoopGroupPool ( DEFAULT_BOSS_EVENT_LOOP_GROUP_POOL ) ; }
Provides the boss EventGroupLoop to the server .
18,521
public NettyServerBuilder workerEventLoopGroup ( EventLoopGroup group ) { if ( group != null ) { return workerEventLoopGroupPool ( new FixedObjectPool < > ( group ) ) ; } return workerEventLoopGroupPool ( DEFAULT_WORKER_EVENT_LOOP_GROUP_POOL ) ; }
Provides the worker EventGroupLoop to the server .
18,522
public NettyServerBuilder keepAliveTimeout ( long keepAliveTimeout , TimeUnit timeUnit ) { checkArgument ( keepAliveTimeout > 0L , "keepalive timeout must be positive" ) ; keepAliveTimeoutInNanos = timeUnit . toNanos ( keepAliveTimeout ) ; keepAliveTimeoutInNanos = KeepAliveManager . clampKeepAliveTimeoutInNanos ( keep...
Sets a custom keepalive timeout the timeout for keepalive ping requests . An unreasonably small value might be increased .
18,523
public NettyServerBuilder permitKeepAliveTime ( long keepAliveTime , TimeUnit timeUnit ) { checkArgument ( keepAliveTime >= 0 , "permit keepalive time must be non-negative" ) ; permitKeepAliveTimeInNanos = timeUnit . toNanos ( keepAliveTime ) ; return this ; }
Specify the most aggressive keep - alive time clients are permitted to configure . The server will try to detect clients exceeding this rate and when detected will forcefully close the connection . The default is 5 minutes .
18,524
public AndroidChannelBuilder sslSocketFactory ( SSLSocketFactory factory ) { try { OKHTTP_CHANNEL_BUILDER_CLASS . getMethod ( "sslSocketFactory" , SSLSocketFactory . class ) . invoke ( delegateBuilder , factory ) ; return this ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to invoke sslSocketFactory o...
Set the delegate channel builder s sslSocketFactory .
18,525
public AndroidChannelBuilder scheduledExecutorService ( ScheduledExecutorService scheduledExecutorService ) { try { OKHTTP_CHANNEL_BUILDER_CLASS . getMethod ( "scheduledExecutorService" , ScheduledExecutorService . class ) . invoke ( delegateBuilder , scheduledExecutorService ) ; return this ; } catch ( Exception e ) {...
Set the delegate channel builder s scheduledExecutorService .
18,526
private static SslProvider defaultSslProvider ( ) { if ( OpenSsl . isAvailable ( ) ) { logger . log ( Level . FINE , "Selecting OPENSSL" ) ; return SslProvider . OPENSSL ; } Provider provider = findJdkProvider ( ) ; if ( provider != null ) { logger . log ( Level . FINE , "Selecting JDK with provider {0}" , provider ) ;...
Returns OpenSSL if available otherwise returns the JDK provider .
18,527
void resetConnectBackoff ( ) { try { synchronized ( lock ) { if ( state . getState ( ) != TRANSIENT_FAILURE ) { return ; } cancelReconnectTask ( ) ; channelLogger . log ( ChannelLogLevel . INFO , "CONNECTING; backoff interrupted" ) ; gotoNonErrorState ( CONNECTING ) ; startNewTransport ( ) ; } } finally { syncContext ....
Immediately attempt to reconnect if the current state is TRANSIENT_FAILURE . Otherwise this method has no effect .
18,528
public void updateAddresses ( List < EquivalentAddressGroup > newAddressGroups ) { Preconditions . checkNotNull ( newAddressGroups , "newAddressGroups" ) ; checkListHasNoNulls ( newAddressGroups , "newAddressGroups contains null entry" ) ; Preconditions . checkArgument ( ! newAddressGroups . isEmpty ( ) , "newAddressGr...
Replaces the existing addresses avoiding unnecessary reconnects .
18,529
static OkHttpProtocolNegotiator createNegotiator ( ClassLoader loader ) { boolean android = true ; try { loader . loadClass ( "com.android.org.conscrypt.OpenSSLSocketImpl" ) ; } catch ( ClassNotFoundException e1 ) { logger . log ( Level . FINE , "Unable to find Conscrypt. Skipping" , e1 ) ; try { loader . loadClass ( "...
Creates corresponding negotiator according to whether on Android .
18,530
protected void configureTlsExtensions ( SSLSocket sslSocket , String hostname , List < Protocol > protocols ) { platform . configureTlsExtensions ( sslSocket , hostname , protocols ) ; }
Configure TLS extensions .
18,531
void recordDroppedRequest ( String token ) { callsStartedUpdater . getAndIncrement ( this ) ; callsFinishedUpdater . getAndIncrement ( this ) ; synchronized ( this ) { LongHolder holder ; if ( ( holder = callsDroppedPerToken . get ( token ) ) == null ) { callsDroppedPerToken . put ( token , ( holder = new LongHolder ( ...
Records that a request has been dropped as instructed by the remote balancer .
18,532
ClientStats generateLoadReport ( ) { ClientStats . Builder statsBuilder = ClientStats . newBuilder ( ) . setTimestamp ( Timestamps . fromNanos ( time . currentTimeNanos ( ) ) ) . setNumCallsStarted ( callsStartedUpdater . getAndSet ( this , 0 ) ) . setNumCallsFinished ( callsFinishedUpdater . getAndSet ( this , 0 ) ) ....
Generate the report with the data recorded this LB stream since the last report .
18,533
private static RuntimeException cancelThrow ( ClientCall < ? , ? > call , Throwable t ) { try { call . cancel ( null , t ) ; } catch ( Throwable e ) { assert e instanceof RuntimeException || e instanceof Error ; logger . log ( Level . SEVERE , "RuntimeException encountered while closing call" , e ) ; } if ( t instanceo...
Cancels a call and throws the exception .
18,534
public void register ( Compressor c ) { String encoding = c . getMessageEncoding ( ) ; checkArgument ( ! encoding . contains ( "," ) , "Comma is currently not allowed in message encoding" ) ; compressors . put ( encoding , c ) ; }
Registers a compressor for both decompression and message encoding negotiation .
18,535
public boolean containsKey ( Key < ? > key ) { for ( int i = 0 ; i < size ; i ++ ) { if ( bytesEqual ( key . asciiName ( ) , name ( i ) ) ) { return true ; } } return false ; }
Returns true if a value is defined for the given key .
18,536
public < T > T get ( Key < T > key ) { for ( int i = size - 1 ; i >= 0 ; i -- ) { if ( bytesEqual ( key . asciiName ( ) , name ( i ) ) ) { return key . parseBytes ( value ( i ) ) ; } } return null ; }
Returns the last metadata entry added with the name name parsed as T .
18,537
public < T > Iterable < T > getAll ( final Key < T > key ) { for ( int i = 0 ; i < size ; i ++ ) { if ( bytesEqual ( key . asciiName ( ) , name ( i ) ) ) { return new IterableAt < > ( key , i ) ; } } return null ; }
Returns all the metadata entries named name in the order they were received parsed as T or null if there are none . The iterator is not guaranteed to be live . It may or may not be accurate if Metadata is mutated .
18,538
@ SuppressWarnings ( "deprecation" ) public Set < String > keys ( ) { if ( isEmpty ( ) ) { return Collections . emptySet ( ) ; } Set < String > ks = new HashSet < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { ks . add ( new String ( name ( i ) , 0 ) ) ; } return Collections . unmodifiableSet ( ks ) ; }
Returns set of all keys in store .
18,539
private void expand ( int newCapacity ) { byte [ ] [ ] newNamesAndValues = new byte [ newCapacity ] [ ] ; if ( ! isEmpty ( ) ) { System . arraycopy ( namesAndValues , 0 , newNamesAndValues , 0 , len ( ) ) ; } namesAndValues = newNamesAndValues ; }
Expands to exactly the desired capacity .
18,540
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/4691" ) public < T > void discardAll ( Key < T > key ) { if ( isEmpty ( ) ) { return ; } int writeIdx = 0 ; int readIdx = 0 ; for ( ; readIdx < size ; readIdx ++ ) { if ( bytesEqual ( key . asciiName ( ) , name ( readIdx ) ) ) { continue ; } name ( writeIdx ...
Remove all values for the given key without returning them . This is a minor performance optimization if you do not need the previous values .
18,541
public void merge ( Metadata other ) { if ( other . isEmpty ( ) ) { return ; } int remaining = cap ( ) - len ( ) ; if ( isEmpty ( ) || remaining < other . len ( ) ) { expand ( len ( ) + other . len ( ) ) ; } System . arraycopy ( other . namesAndValues , 0 , namesAndValues , len ( ) , other . len ( ) ) ; size += other ....
Perform a simple merge of two sets of metadata .
18,542
public void merge ( Metadata other , Set < Key < ? > > keys ) { Preconditions . checkNotNull ( other , "other" ) ; Map < ByteBuffer , Key < ? > > asciiKeys = new HashMap < > ( keys . size ( ) ) ; for ( Key < ? > key : keys ) { asciiKeys . put ( ByteBuffer . wrap ( key . asciiName ( ) ) , key ) ; } for ( int i = 0 ; i <...
Merge values from the given set of keys into this set of metadata . If a key is present in keys then all of the associated values will be copied over .
18,543
public void cancel ( final Status reason ) { checkNotNull ( reason , "reason" ) ; boolean delegateToRealStream = true ; ClientStreamListener listenerToClose = null ; synchronized ( this ) { if ( realStream == null ) { realStream = NoopClientStream . INSTANCE ; delegateToRealStream = false ; listenerToClose = listener ;...
When this method returns passThrough is guaranteed to be true
18,544
public static byte [ ] [ ] toHttp2Headers ( Metadata headers ) { byte [ ] [ ] serializedHeaders = InternalMetadata . serialize ( headers ) ; if ( serializedHeaders == null ) { return new byte [ ] [ ] { } ; } int k = 0 ; for ( int i = 0 ; i < serializedHeaders . length ; i += 2 ) { byte [ ] key = serializedHeaders [ i ]...
Transform the given headers to a format where only spec - compliant ASCII characters are allowed . Binary header values are encoded by Base64 in the result . It is safe to modify the returned array but not to modify any of the underlying byte arrays .
18,545
protected void transportDataReceived ( ReadableBuffer frame , boolean endOfStream ) { if ( transportError != null ) { transportError = transportError . augmentDescription ( "DATA-----------------------------\n" + ReadableBuffers . readAsString ( frame , errorCharset ) ) ; frame . close ( ) ; if ( transportError . getDe...
Called by subclasses whenever a data frame is received from the transport .
18,546
protected void transportTrailersReceived ( Metadata trailers ) { Preconditions . checkNotNull ( trailers , "trailers" ) ; if ( transportError == null && ! headersReceived ) { transportError = validateInitialMetadata ( trailers ) ; if ( transportError != null ) { transportErrorMetadata = trailers ; } } if ( transportErr...
Called by subclasses for the terminal trailer metadata on a stream .
18,547
private Status statusFromTrailers ( Metadata trailers ) { Status status = trailers . get ( InternalStatus . CODE_KEY ) ; if ( status != null ) { return status . withDescription ( trailers . get ( InternalStatus . MESSAGE_KEY ) ) ; } if ( headersReceived ) { return Status . UNKNOWN . withDescription ( "missing GRPC stat...
Extract the response status from trailers .
18,548
private static Charset extractCharset ( Metadata headers ) { String contentType = headers . get ( GrpcUtil . CONTENT_TYPE_KEY ) ; if ( contentType != null ) { String [ ] split = contentType . split ( "charset=" , 2 ) ; try { return Charset . forName ( split [ split . length - 1 ] . trim ( ) ) ; } catch ( Exception t ) ...
Inspect the raw metadata and figure out what charset is being used .
18,549
private static void stripTransportDetails ( Metadata metadata ) { metadata . discardAll ( HTTP2_STATUS ) ; metadata . discardAll ( InternalStatus . CODE_KEY ) ; metadata . discardAll ( InternalStatus . MESSAGE_KEY ) ; }
Strip HTTP transport implementation details so they don t leak via metadata into the application layer .
18,550
public final void start ( ClientStreamListener listener ) { masterListener = listener ; Status shutdownStatus = prestart ( ) ; if ( shutdownStatus != null ) { cancel ( shutdownStatus ) ; return ; } class StartEntry implements BufferEntry { public void runWith ( Substream substream ) { substream . stream . start ( new S...
Starts the first PRC attempt .
18,551
@ GuardedBy ( "lock" ) private boolean hasPotentialHedging ( State state ) { return state . winningSubstream == null && state . hedgingAttemptCount < hedgingPolicy . maxAttempts && ! state . hedgingFrozen ; }
only called when isHedging is true
18,552
void getBytesToSendToPeer ( ByteBuf out ) throws GeneralSecurityException { checkState ( unwrapper != null , "protector already created" ) ; try ( BufUnwrapper unwrapper = this . unwrapper ) { int bytesWritten = 0 ; for ( ByteBuffer nioBuffer : unwrapper . writableNioBuffers ( out ) ) { if ( ! nioBuffer . hasRemaining ...
Gets data that is ready to be sent to the to the remote peer . This should be called in a loop until no bytes are written to the output buffer .
18,553
boolean processBytesFromPeer ( ByteBuf data ) throws GeneralSecurityException { checkState ( unwrapper != null , "protector already created" ) ; try ( BufUnwrapper unwrapper = this . unwrapper ) { int bytesRead = 0 ; boolean done = false ; for ( ByteBuffer nioBuffer : unwrapper . readableNioBuffers ( data ) ) { if ( ! ...
Process handshake data received from the remote peer .
18,554
public static ManagedChannelBuilder < ? > forAddress ( String name , int port ) { return ManagedChannelProvider . provider ( ) . builderForAddress ( name , port ) ; }
Creates a channel with the target s address and port number .
18,555
private static long getNetworkAddressCacheTtlNanos ( boolean isAndroid ) { if ( isAndroid ) { return 0 ; } String cacheTtlPropertyValue = System . getProperty ( NETWORKADDRESS_CACHE_TTL_PROPERTY ) ; long cacheTtl = DEFAULT_NETWORK_CACHE_TTL_SECONDS ; if ( cacheTtlPropertyValue != null ) { try { cacheTtl = Long . parseL...
Returns value of network address cache ttl property if not Android environment . For android DnsNameResolver does not cache the dns lookup result .
18,556
static Map < String , ? > maybeChooseServiceConfig ( Map < String , ? > choice , Random random , String hostname ) { for ( Entry < String , ? > entry : choice . entrySet ( ) ) { Verify . verify ( SERVICE_CONFIG_CHOICE_KEYS . contains ( entry . getKey ( ) ) , "Bad key: %s" , entry ) ; } List < String > clientLanguages =...
Determines if a given Service Config choice applies and if so returns it .
18,557
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1789" ) public static < T extends AbstractStub < T > > T attachHeaders ( T stub , Metadata extraHeaders ) { return stub . withInterceptors ( newAttachHeadersInterceptor ( extraHeaders ) ) ; }
Attaches a set of request headers to a stub .
18,558
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1789" ) public static < T extends AbstractStub < T > > T captureMetadata ( T stub , AtomicReference < Metadata > headersCapture , AtomicReference < Metadata > trailersCapture ) { return stub . withInterceptors ( newCaptureMetadataInterceptor ( headersCapture...
Captures the last received metadata for a stub . Useful for testing
18,559
public static ClientInterceptor newCaptureMetadataInterceptor ( AtomicReference < Metadata > headersCapture , AtomicReference < Metadata > trailersCapture ) { return new MetadataCapturingClientInterceptor ( headersCapture , trailersCapture ) ; }
Captures the last received metadata on a channel . Useful for testing .
18,560
public WritableBuffer allocate ( int capacityHint ) { capacityHint = Math . min ( MAX_BUFFER , Math . max ( MIN_BUFFER , capacityHint ) ) ; return new OkHttpWritableBuffer ( new Buffer ( ) , capacityHint ) ; }
For OkHttp we will often return a buffer smaller than the requested capacity as this is the mechanism for chunking a large GRPC message over many DATA frames .
18,561
void returnProcessedBytes ( Http2Stream http2Stream , int bytes ) { try { decoder ( ) . flowController ( ) . consumeBytes ( http2Stream , bytes ) ; } catch ( Http2Exception e ) { throw new RuntimeException ( e ) ; } }
Returns the given processed bytes back to inbound flow control .
18,562
private void sendGrpcFrame ( ChannelHandlerContext ctx , SendGrpcFrameCommand cmd , ChannelPromise promise ) throws Http2Exception { if ( cmd . endStream ( ) ) { closeStreamWhenDone ( promise , cmd . streamId ( ) ) ; } encoder ( ) . writeData ( ctx , cmd . streamId ( ) , cmd . content ( ) , 0 , cmd . endStream ( ) , pr...
Sends the given gRPC frame to the client .
18,563
private void sendResponseHeaders ( ChannelHandlerContext ctx , SendResponseHeadersCommand cmd , ChannelPromise promise ) throws Http2Exception { int streamId = cmd . stream ( ) . id ( ) ; Http2Stream stream = connection ( ) . stream ( streamId ) ; if ( stream == null ) { resetStream ( ctx , streamId , Http2Error . CANC...
Sends the response headers to the client .
18,564
private char getEscaped ( ) { pos ++ ; if ( pos == length ) { throw new IllegalStateException ( "Unexpected end of DN: " + dn ) ; } switch ( chars [ pos ] ) { case '"' : case '\\' : case ',' : case '=' : case '+' : case '<' : case '>' : case '#' : case ';' : case ' ' : case '*' : case '%' : case '_' : return chars [ po...
returns escaped char
18,565
public String findMostSpecific ( String attributeType ) { pos = 0 ; beg = 0 ; end = 0 ; cur = 0 ; chars = dn . toCharArray ( ) ; String attType = nextAT ( ) ; if ( attType == null ) { return null ; } while ( true ) { String attValue = "" ; if ( pos == length ) { return null ; } switch ( chars [ pos ] ) { case '"' : att...
Parses the DN and returns the most significant attribute value for an attribute type or null if none found .
18,566
public static void main ( String ... args ) throws Exception { ClientConfiguration . Builder configBuilder = ClientConfiguration . newBuilder ( ADDRESS , TARGET_QPS , CLIENT_PAYLOAD , SERVER_PAYLOAD , TLS , TESTCA , TRANSPORT , DURATION , SAVE_HISTOGRAM , FLOW_CONTROL_WINDOW ) ; ClientConfiguration config ; try { confi...
Comment for checkstyle .
18,567
public void run ( ) throws Exception { if ( config == null ) { return ; } config . channels = 1 ; config . directExecutor = true ; ManagedChannel ch = config . newChannel ( ) ; SimpleRequest req = config . newRequest ( ) ; LoadGenerationWorker worker = new LoadGenerationWorker ( ch , req , config . targetQps , config ....
Start the open loop client .
18,568
private static Provider getAppEngineProvider ( ) { try { return ( Provider ) Class . forName ( "org.conscrypt.OpenSSLProvider" ) . getConstructor ( ) . newInstance ( ) ; } catch ( Throwable t ) { throw new RuntimeException ( "Unable to load conscrypt security provider" , t ) ; } }
Forcibly load the conscrypt security provider on AppEngine if it s available . If not fail .
18,569
public static boolean isGrpcContentType ( String contentType ) { if ( contentType == null ) { return false ; } if ( CONTENT_TYPE_GRPC . length ( ) > contentType . length ( ) ) { return false ; } contentType = contentType . toLowerCase ( ) ; if ( ! contentType . startsWith ( CONTENT_TYPE_GRPC ) ) { return false ; } if (...
Indicates whether or not the given value is a valid gRPC content - type .
18,570
public static URI authorityToUri ( String authority ) { Preconditions . checkNotNull ( authority , "authority" ) ; URI uri ; try { uri = new URI ( null , authority , null , null , null ) ; } catch ( URISyntaxException ex ) { throw new IllegalArgumentException ( "Invalid authority: " + authority , ex ) ; } return uri ; ...
Parse an authority into a URI for retrieving the host and port .
18,571
public static String authorityFromHostAndPort ( String host , int port ) { try { return new URI ( null , null , host , port , null , null , null ) . getAuthority ( ) ; } catch ( URISyntaxException ex ) { throw new IllegalArgumentException ( "Invalid host or port: " + host + " " + port , ex ) ; } }
Combine a host and port into an authority string .
18,572
static void closeQuietly ( MessageProducer producer ) { InputStream message ; while ( ( message = producer . next ( ) ) != null ) { closeQuietly ( message ) ; } }
Quietly closes all messages in MessageProducer .
18,573
private URI serviceUri ( Channel channel , MethodDescriptor < ? , ? > method ) throws StatusException { String authority = channel . authority ( ) ; if ( authority == null ) { throw Status . UNAUTHENTICATED . withDescription ( "Channel has no authority" ) . asException ( ) ; } final String scheme = "https" ; final int ...
Generate a JWT - specific service URI . The URI is simply an identifier with enough information for a service to know that the JWT was intended for it . The URI will commonly be verified with a simple string equality check .
18,574
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { registry = new MutableHandlerRegistry ( ) ; fullMethodNames = new ArrayList < > ( serviceCount * methodCountPerService ) ; for ( int serviceIndex = 0 ; serviceIndex < serviceCount ; ++ serviceIndex ) { String serviceName = randomString ( ) ; ServerServi...
Set up the registry .
18,575
static Long getTimeoutFromMethodConfig ( Map < String , ? > methodConfig ) { if ( ! methodConfig . containsKey ( METHOD_CONFIG_TIMEOUT_KEY ) ) { return null ; } String rawTimeout = getString ( methodConfig , METHOD_CONFIG_TIMEOUT_KEY ) ; try { return parseDuration ( rawTimeout ) ; } catch ( ParseException e ) { throw n...
Returns the number of nanoseconds of timeout for the given method config .
18,576
@ SuppressWarnings ( "unchecked" ) public static List < Map < String , ? > > getLoadBalancingConfigsFromServiceConfig ( Map < String , ? > serviceConfig ) { List < Map < String , ? > > lbConfigs = new ArrayList < > ( ) ; if ( serviceConfig . containsKey ( SERVICE_CONFIG_LOAD_BALANCING_CONFIG_KEY ) ) { List < ? > config...
Extracts load balancing configs from a service config .
18,577
@ SuppressWarnings ( "unchecked" ) public static List < LbConfig > unwrapLoadBalancingConfigList ( List < Map < String , ? > > list ) { ArrayList < LbConfig > result = new ArrayList < > ( ) ; for ( Map < String , ? > rawChildPolicy : list ) { result . add ( unwrapLoadBalancingConfig ( rawChildPolicy ) ) ; } return Coll...
Given a JSON list of LoadBalancingConfigs and convert it into a list of LbConfig .
18,578
public static String getBalancerNameFromXdsConfig ( LbConfig xdsConfig ) { Map < String , ? > map = xdsConfig . getRawConfigValue ( ) ; return getString ( map , XDS_CONFIG_BALANCER_NAME_KEY ) ; }
Extracts the loadbalancer name from xds loadbalancer config .
18,579
public static List < LbConfig > getChildPolicyFromXdsConfig ( LbConfig xdsConfig ) { Map < String , ? > map = xdsConfig . getRawConfigValue ( ) ; List < ? > rawChildPolicies = getList ( map , XDS_CONFIG_CHILD_POLICY_KEY ) ; if ( rawChildPolicies != null ) { return unwrapLoadBalancingConfigList ( checkObjectList ( rawCh...
Extracts list of child policies from xds loadbalancer config .
18,580
public static List < LbConfig > getFallbackPolicyFromXdsConfig ( LbConfig xdsConfig ) { Map < String , ? > map = xdsConfig . getRawConfigValue ( ) ; List < ? > rawFallbackPolicies = getList ( map , XDS_CONFIG_FALLBACK_POLICY_KEY ) ; if ( rawFallbackPolicies != null ) { return unwrapLoadBalancingConfigList ( checkObject...
Extracts list of fallback policies from xds loadbalancer config .
18,581
@ SuppressWarnings ( "unchecked" ) static List < ? > getList ( Map < String , ? > obj , String key ) { assert key != null ; if ( ! obj . containsKey ( key ) ) { return null ; } Object value = obj . get ( key ) ; if ( ! ( value instanceof List ) ) { throw new ClassCastException ( String . format ( "value '%s' for key '%...
Gets a list from an object for the given key . If the key is not present this returns null . If the value is not a List throws an exception .
18,582
static synchronized boolean isJettyAlpnConfigured ( ) { try { Class . forName ( "org.eclipse.jetty.alpn.ALPN" , true , null ) ; return true ; } catch ( ClassNotFoundException e ) { jettyAlpnUnavailabilityCause = e ; return false ; } }
Indicates whether or not the Jetty ALPN jar is installed in the boot classloader .
18,583
static synchronized boolean isJettyNpnConfigured ( ) { try { Class . forName ( "org.eclipse.jetty.npn.NextProtoNego" , true , null ) ; return true ; } catch ( ClassNotFoundException e ) { jettyNpnUnavailabilityCause = e ; return false ; } }
Indicates whether or not the Jetty NPN jar is installed in the boot classloader .
18,584
public final void drain ( ) { do { if ( ! drainingThread . compareAndSet ( null , Thread . currentThread ( ) ) ) { return ; } try { Runnable runnable ; while ( ( runnable = queue . poll ( ) ) != null ) { try { runnable . run ( ) ; } catch ( Throwable t ) { uncaughtExceptionHandler . uncaughtException ( Thread . current...
Run all tasks in the queue in the current thread if no other thread is running this method . Otherwise do nothing .
18,585
public final S withInterceptors ( ClientInterceptor ... interceptors ) { return build ( ClientInterceptors . intercept ( channel , interceptors ) , callOptions ) ; }
Returns a new stub that has the given interceptors attached to the underlying channel .
18,586
private static void setupRequestHeaders ( ) { requestHeaders = new AsciiString [ 18 ] ; int i = 0 ; requestHeaders [ i ++ ] = AsciiString . of ( ":method" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "POST" ) ; requestHeaders [ i ++ ] = AsciiString . of ( ":scheme" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "...
Headers taken from the gRPC spec .
18,587
@ GuardedBy ( "lock" ) private boolean startPendingStreams ( ) { boolean hasStreamStarted = false ; while ( ! pendingStreams . isEmpty ( ) && streams . size ( ) < maxConcurrentStreams ) { OkHttpClientStream stream = pendingStreams . poll ( ) ; startStream ( stream ) ; hasStreamStarted = true ; } return hasStreamStarted...
Starts pending streams returns true if at least one pending stream is started .
18,588
public void onException ( Throwable failureCause ) { Preconditions . checkNotNull ( failureCause , "failureCause" ) ; Status status = Status . UNAVAILABLE . withCause ( failureCause ) ; startGoAway ( 0 , ErrorCode . INTERNAL_ERROR , status ) ; }
Finish all active streams due to an IOException then close the transport .
18,589
private void onError ( ErrorCode errorCode , String moreDetail ) { startGoAway ( 0 , errorCode , toGrpcStatus ( errorCode ) . augmentDescription ( moreDetail ) ) ; }
Send GOAWAY to the server then finish all active streams and close the transport .
18,590
static Status toGrpcStatus ( ErrorCode code ) { Status status = ERROR_CODE_TO_STATUS . get ( code ) ; return status != null ? status : Status . UNKNOWN . withDescription ( "Unknown http2 error code: " + code . httpCode ) ; }
Returns a Grpc status corresponding to the given ErrorCode .
18,591
public final void updateObjectInUse ( T object , boolean inUse ) { int origSize = inUseObjects . size ( ) ; if ( inUse ) { inUseObjects . add ( object ) ; if ( origSize == 0 ) { handleInUse ( ) ; } } else { boolean removed = inUseObjects . remove ( object ) ; if ( removed && origSize == 1 ) { handleNotInUse ( ) ; } } }
Update the in - use state of an object . Initially no object is in use .
18,592
public static AltsProtocolNegotiator createClientNegotiator ( final TsiHandshakerFactory handshakerFactory , final LazyChannel lazyHandshakerChannel ) { final class ClientAltsProtocolNegotiator extends AltsProtocolNegotiator { public ChannelHandler newHandler ( GrpcHttp2ConnectionHandler grpcHandler ) { TsiHandshaker h...
Creates a negotiator used for ALTS client .
18,593
public static AltsProtocolNegotiator createServerNegotiator ( final TsiHandshakerFactory handshakerFactory , final LazyChannel lazyHandshakerChannel ) { final class ServerAltsProtocolNegotiator extends AltsProtocolNegotiator { public ChannelHandler newHandler ( GrpcHttp2ConnectionHandler grpcHandler ) { TsiHandshaker h...
Creates a negotiator used for ALTS server .
18,594
public void addCallback ( final ClientTransport . PingCallback callback , Executor executor ) { Runnable runnable ; synchronized ( this ) { if ( ! completed ) { callbacks . put ( callback , executor ) ; return ; } runnable = this . failureCause != null ? asRunnable ( callback , failureCause ) : asRunnable ( callback , ...
Registers a callback that is invoked when the ping operation completes . If this ping operation is already completed the callback is invoked immediately .
18,595
public boolean complete ( ) { Map < ClientTransport . PingCallback , Executor > callbacks ; long roundTripTimeNanos ; synchronized ( this ) { if ( completed ) { return false ; } completed = true ; roundTripTimeNanos = this . roundTripTimeNanos = stopwatch . elapsed ( TimeUnit . NANOSECONDS ) ; callbacks = this . callba...
Completes this operation successfully . The stopwatch given during construction is used to measure the elapsed time . Registered callbacks are invoked and provided the measured elapsed time .
18,596
public void failed ( Throwable failureCause ) { Map < ClientTransport . PingCallback , Executor > callbacks ; synchronized ( this ) { if ( completed ) { return ; } completed = true ; this . failureCause = failureCause ; callbacks = this . callbacks ; this . callbacks = null ; } for ( Map . Entry < ClientTransport . Pin...
Completes this operation exceptionally . Registered callbacks are invoked and provided the given throwable as the cause of failure .
18,597
public static void notifyFailed ( PingCallback callback , Executor executor , Throwable cause ) { doExecute ( executor , asRunnable ( callback , cause ) ) ; }
Notifies the given callback that the ping operation failed .
18,598
private static void doExecute ( Executor executor , Runnable runnable ) { try { executor . execute ( runnable ) ; } catch ( Throwable th ) { log . log ( Level . SEVERE , "Failed to execute PingCallback" , th ) ; } }
Executes the given runnable . This prevents exceptions from propagating so that an exception thrown by one callback won t prevent subsequent callbacks from being executed .
18,599
private static Runnable asRunnable ( final ClientTransport . PingCallback callback , final long roundTripTimeNanos ) { return new Runnable ( ) { public void run ( ) { callback . onSuccess ( roundTripTimeNanos ) ; } } ; }
Returns a runnable that when run invokes the given callback providing the given round - trip duration .