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 ( ) ) ; val parameters = new HashMap < String , String > ( ) ; if ( StringUtils . isBlank ( ticketId ) ) { parameters . put ( OpenIdProtocolConstants . OPENID_MODE , OpenIdProtocolConstants . CANCEL ) ; return buildRedirect ( service , parameters ) ; } val association = getAssociation ( serverManager , parameterList ) ; val associated = association != null ; val associationValid = isAssociationValid ( association ) ; var successFullAuthentication = true ; var assertion = ( Assertion ) null ; try { if ( associated && associationValid ) { assertion = centralAuthenticationService . validateServiceTicket ( ticketId , service ) ; LOGGER . debug ( "Validated openid ticket [{}] for [{}]" , ticketId , service ) ; } else if ( ! associated ) { LOGGER . debug ( "Responding to non-associated mode. Service ticket [{}] must be validated by the RP" , ticketId ) ; } else { LOGGER . warn ( "Association does not exist or is not valid" ) ; successFullAuthentication = false ; } } catch ( final AbstractTicketException e ) { LOGGER . error ( "Could not validate ticket : [{}]" , e . getMessage ( ) , e ) ; successFullAuthentication = false ; } val id = determineIdentity ( service , assertion ) ; return buildAuthenticationResponse ( service , parameters , successFullAuthentication , id , parameterList ) ; } | 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 will force the consumer to ask a verification which will validate the service ticket . |
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 ( ) . getId ( ) ; } return service . getIdentity ( ) ; } | 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 . isEmpty ( ) ) { val assocHandle = ( String ) parameterMap . get ( OpenIdProtocolConstants . OPENID_ASSOCHANDLE ) ; if ( assocHandle != null ) { return serverManager . getSharedAssociations ( ) . load ( assocHandle ) ; } } } catch ( final MessageException e ) { LOGGER . error ( "Message exception : [{}]" , e . getMessage ( ) , e ) ; } return null ; } | 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 BadRestRequestException ( "No credentials are provided or extracted to authenticate the REST request" ) ; } val service = this . serviceFactory . createService ( request ) ; val authenticationResult = authenticationSystemSupport . handleAndFinalizeSingleAuthenticationTransaction ( service , credential ) ; return centralAuthenticationService . createTicketGrantingTicket ( authenticationResult ) ; } | 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 , @ ShellOption ( value = { "provider" } , help = "Security provider to use to encrypt" ) final String provider , @ ShellOption ( value = { "password" } , help = "Password (encryption key) to encrypt" ) final String password , @ ShellOption ( value = { "iterations" } , help = "Key obtention iterations to encrypt" ) final String iterations ) { val cipher = new CasConfigurationJasyptCipherExecutor ( this . environment ) ; cipher . setAlgorithm ( alg ) ; cipher . setPassword ( password ) ; if ( Security . getProvider ( BouncyCastleProvider . PROVIDER_NAME ) == null ) { Security . addProvider ( new BouncyCastleProvider ( ) ) ; } cipher . setProviderName ( provider ) ; cipher . setKeyObtentionIterations ( iterations ) ; val encrypted = cipher . decryptValue ( value ) ; LOGGER . info ( "==== Decrypted Value ====\n{}" , encrypted ) ; } | 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 [{}] for [{}]" , this . passwordEncoder . getClass ( ) . getName ( ) , userPass . getUsername ( ) ) ; val transformedPsw = this . passwordEncoder . encode ( userPass . getPassword ( ) ) ; if ( StringUtils . isBlank ( transformedPsw ) ) { throw new AccountNotFoundException ( "Encoded password is null." ) ; } userPass . setPassword ( transformedPsw ) ; } | 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 . principalNameTransformer . getClass ( ) . getName ( ) ) ; val transformedUsername = this . principalNameTransformer . transform ( userPass . getUsername ( ) ) ; if ( StringUtils . isBlank ( transformedUsername ) ) { throw new AccountNotFoundException ( "Transformed username is null." ) ; } userPass . setUsername ( transformedUsername ) ; } | 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 = ClientStreamTracer . StreamInfo . newBuilder ( ) . setTransportAttrs ( transportAttrs ) . setCallOptions ( callOptions ) . build ( ) ; StreamTracer [ ] tracers = new StreamTracer [ factories . size ( ) ] ; for ( int i = 0 ; i < tracers . length ; i ++ ) { tracers [ i ] = factories . get ( i ) . newClientStreamTracer ( info , headers ) ; } return new StatsTraceContext ( tracers ) ; } | 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 ++ ) { tracers [ i ] = factories . get ( i ) . newServerStreamTracer ( fullMethodName , headers ) ; } return new StatsTraceContext ( tracers ) ; } | 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 = peerVersions . getMaxRpcVersion ( ) ; } else { maxCommonVersion = localVersions . getMaxRpcVersion ( ) ; } if ( isGreaterThanOrEqualTo ( localVersions . getMinRpcVersion ( ) , peerVersions . getMinRpcVersion ( ) ) ) { minCommonVersion = localVersions . getMinRpcVersion ( ) ; } else { minCommonVersion = peerVersions . getMinRpcVersion ( ) ; } if ( isGreaterThanOrEqualTo ( maxCommonVersion , minCommonVersion ) ) { return new RpcVersionsCheckResult . Builder ( ) . setResult ( true ) . setHighestCommonVersion ( maxCommonVersion ) . build ( ) ; } return new RpcVersionsCheckResult . Builder ( ) . setResult ( false ) . build ( ) ; } | 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 . REFUSED , true , new Metadata ( ) ) ; promise . setFailure ( lifecycleManager . getShutdownThrowable ( ) ) ; return ; } final int streamId ; try { streamId = incrementAndGetNextStreamId ( ) ; } catch ( StatusException e ) { command . stream ( ) . setNonExistent ( ) ; promise . setFailure ( e ) ; if ( ! connection ( ) . goAwaySent ( ) ) { logger . fine ( "Stream IDs have been exhausted for this connection. " + "Initiating graceful shutdown of the connection." ) ; lifecycleManager . notifyShutdown ( e . getStatus ( ) ) ; close ( ctx ( ) , ctx ( ) . newPromise ( ) ) ; } return ; } final NettyClientStream . TransportState stream = command . stream ( ) ; final Http2Headers headers = command . headers ( ) ; stream . setId ( streamId ) ; ChannelPromise tempPromise = ctx ( ) . newPromise ( ) ; encoder ( ) . writeHeaders ( ctx ( ) , streamId , headers , 0 , command . isGet ( ) , tempPromise ) . addListener ( new ChannelFutureListener ( ) { public void operationComplete ( ChannelFuture future ) throws Exception { if ( future . isSuccess ( ) ) { Http2Stream http2Stream = connection ( ) . stream ( streamId ) ; if ( http2Stream != null ) { stream . getStatsTraceContext ( ) . clientOutboundHeaders ( ) ; http2Stream . setProperty ( streamKey , stream ) ; if ( command . shouldBeCountedForInUse ( ) ) { inUseState . updateObjectInUse ( http2Stream , true ) ; } stream . setHttp2Stream ( http2Stream ) ; } promise . setSuccess ( ) ; } else { final Throwable cause = future . cause ( ) ; if ( cause instanceof StreamBufferingEncoder . Http2GoAwayException ) { StreamBufferingEncoder . Http2GoAwayException e = ( StreamBufferingEncoder . Http2GoAwayException ) cause ; lifecycleManager . notifyShutdown ( statusFromGoAway ( e . errorCode ( ) , e . debugData ( ) ) ) ; promise . setFailure ( lifecycleManager . getShutdownThrowable ( ) ) ; } else { promise . setFailure ( cause ) ; } } } } ) ; } | 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 . stream ( ) . isNonExistent ( ) ) { encoder ( ) . writeRstStream ( ctx , stream . id ( ) , Http2Error . CANCEL . code ( ) , promise ) ; } else { promise . setSuccess ( ) ; } } | 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 ( ) ; promise = ctx ( ) . newPromise ( ) ; long data = USER_PING_PAYLOAD ; Stopwatch stopwatch = stopwatchFactory . get ( ) ; stopwatch . start ( ) ; ping = new Http2Ping ( data , stopwatch ) ; ping . addCallback ( callback , executor ) ; encoder ( ) . writePing ( ctx , false , USER_PING_PAYLOAD , promise ) ; ctx . flush ( ) ; final Http2Ping finalPing = ping ; promise . addListener ( new ChannelFutureListener ( ) { public void operationComplete ( ChannelFuture future ) throws Exception { if ( future . isSuccess ( ) ) { transportTracer . reportKeepAliveSent ( ) ; } else { Throwable cause = future . cause ( ) ; if ( cause instanceof ClosedChannelException ) { cause = lifecycleManager . getShutdownThrowable ( ) ; if ( cause == null ) { cause = Status . UNKNOWN . withDescription ( "Ping failed but for unknown reason." ) . withCause ( future . cause ( ) ) . asException ( ) ; } } finalPing . failed ( cause ) ; if ( ping == finalPing ) { ping = null ; } } } } ) ; } | 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 ( ) { public boolean visit ( Http2Stream stream ) throws Http2Exception { if ( stream . id ( ) > lastKnownStream ) { NettyClientStream . TransportState clientStream = clientStream ( stream ) ; if ( clientStream != null ) { clientStream . transportReportStatus ( goAwayStatus , RpcProgress . REFUSED , false , new Metadata ( ) ) ; } stream . close ( ) ; } return true ; } } ) ; } catch ( Http2Exception e ) { throw new RuntimeException ( e ) ; } } | 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 ( keepAliveTimeoutInNanos ) ; if ( keepAliveTimeoutInNanos < MIN_KEEPALIVE_TIMEOUT_NANO ) { keepAliveTimeoutInNanos = MIN_KEEPALIVE_TIMEOUT_NANO ; } return this ; } | 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 on delegate builder" , e ) ; } } | 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 ) { throw new RuntimeException ( "Failed to invoke scheduledExecutorService on delegate builder" , 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 ) ; return SslProvider . JDK ; } logger . log ( Level . INFO , "netty-tcnative unavailable (this may be normal)" , OpenSsl . unavailabilityCause ( ) ) ; logger . log ( Level . INFO , "Conscrypt not found (this may be normal)" ) ; logger . log ( Level . INFO , "Jetty ALPN unavailable (this may be normal)" , JettyTlsUtil . getJettyAlpnUnavailabilityCause ( ) ) ; throw new IllegalStateException ( "Could not find TLS ALPN provider; " + "no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available" ) ; } | 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 . drain ( ) ; } } | 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 ( ) , "newAddressGroups is empty" ) ; newAddressGroups = Collections . unmodifiableList ( new ArrayList < > ( newAddressGroups ) ) ; ManagedClientTransport savedTransport = null ; try { synchronized ( lock ) { SocketAddress previousAddress = addressIndex . getCurrentAddress ( ) ; addressIndex . updateGroups ( newAddressGroups ) ; if ( state . getState ( ) == READY || state . getState ( ) == CONNECTING ) { if ( ! addressIndex . seekTo ( previousAddress ) ) { if ( state . getState ( ) == READY ) { savedTransport = activeTransport ; activeTransport = null ; addressIndex . reset ( ) ; gotoNonErrorState ( IDLE ) ; } else { savedTransport = pendingTransport ; pendingTransport = null ; addressIndex . reset ( ) ; startNewTransport ( ) ; } } } } } finally { syncContext . drain ( ) ; } if ( savedTransport != null ) { savedTransport . shutdown ( Status . UNAVAILABLE . withDescription ( "InternalSubchannel closed transport due to address change" ) ) ; } } | 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 ( "org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl" ) ; } catch ( ClassNotFoundException e2 ) { logger . log ( Level . FINE , "Unable to find any OpenSSLSocketImpl. Skipping" , e2 ) ; android = false ; } } return android ? new AndroidNegotiator ( DEFAULT_PLATFORM ) : new OkHttpProtocolNegotiator ( DEFAULT_PLATFORM ) ; } | 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 ( ) ) ) ; } holder . num ++ ; } } | 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 ) ) . setNumCallsFinishedWithClientFailedToSend ( callsFailedToSendUpdater . getAndSet ( this , 0 ) ) . setNumCallsFinishedKnownReceived ( callsFinishedKnownReceivedUpdater . getAndSet ( this , 0 ) ) ; Map < String , LongHolder > localCallsDroppedPerToken = Collections . emptyMap ( ) ; synchronized ( this ) { if ( ! callsDroppedPerToken . isEmpty ( ) ) { localCallsDroppedPerToken = callsDroppedPerToken ; callsDroppedPerToken = new HashMap < > ( localCallsDroppedPerToken . size ( ) ) ; } } for ( Entry < String , LongHolder > entry : localCallsDroppedPerToken . entrySet ( ) ) { statsBuilder . addCallsFinishedWithDrop ( ClientStatsPerToken . newBuilder ( ) . setLoadBalanceToken ( entry . getKey ( ) ) . setNumCalls ( entry . getValue ( ) . num ) . build ( ) ) ; } return statsBuilder . build ( ) ; } | 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 instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } throw new AssertionError ( t ) ; } | 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 , name ( readIdx ) ) ; value ( writeIdx , value ( readIdx ) ) ; writeIdx ++ ; } int newSize = writeIdx ; Arrays . fill ( namesAndValues , writeIdx * 2 , len ( ) , null ) ; size = newSize ; } | 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 . size ; } | 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 < other . size ; i ++ ) { ByteBuffer wrappedNamed = ByteBuffer . wrap ( other . name ( i ) ) ; if ( asciiKeys . containsKey ( wrappedNamed ) ) { maybeExpand ( ) ; name ( size , other . name ( i ) ) ; value ( size , other . value ( i ) ) ; size ++ ; } } } | 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 ; error = reason ; } } if ( delegateToRealStream ) { delayOrExecute ( new Runnable ( ) { public void run ( ) { realStream . cancel ( reason ) ; } } ) ; } else { if ( listenerToClose != null ) { listenerToClose . closed ( reason , new Metadata ( ) ) ; } drainPendingCalls ( ) ; } } | 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 ] ; byte [ ] value = serializedHeaders [ i + 1 ] ; if ( endsWith ( key , binaryHeaderSuffixBytes ) ) { serializedHeaders [ k ] = key ; serializedHeaders [ k + 1 ] = InternalMetadata . BASE64_ENCODING_OMIT_PADDING . encode ( value ) . getBytes ( US_ASCII ) ; k += 2 ; } else { if ( isSpecCompliantAscii ( value ) ) { serializedHeaders [ k ] = key ; serializedHeaders [ k + 1 ] = value ; k += 2 ; } else { String keyString = new String ( key , US_ASCII ) ; logger . warning ( "Metadata key=" + keyString + ", value=" + Arrays . toString ( value ) + " contains invalid ASCII characters" ) ; } } } if ( k == serializedHeaders . length ) { return serializedHeaders ; } return Arrays . copyOfRange ( serializedHeaders , 0 , k ) ; } | 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 . getDescription ( ) . length ( ) > 1000 || endOfStream ) { http2ProcessingFailed ( transportError , false , transportErrorMetadata ) ; } } else { if ( ! headersReceived ) { http2ProcessingFailed ( Status . INTERNAL . withDescription ( "headers not received before payload" ) , false , new Metadata ( ) ) ; return ; } inboundDataReceived ( frame ) ; if ( endOfStream ) { transportError = Status . INTERNAL . withDescription ( "Received unexpected EOS on DATA frame from server." ) ; transportErrorMetadata = new Metadata ( ) ; transportReportStatus ( transportError , false , transportErrorMetadata ) ; } } } | 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 ( transportError != null ) { transportError = transportError . augmentDescription ( "trailers: " + trailers ) ; http2ProcessingFailed ( transportError , false , transportErrorMetadata ) ; } else { Status status = statusFromTrailers ( trailers ) ; stripTransportDetails ( trailers ) ; inboundTrailersReceived ( trailers , status ) ; } } | 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 status in response" ) ; } Integer httpStatus = trailers . get ( HTTP2_STATUS ) ; if ( httpStatus != null ) { status = GrpcUtil . httpStatusToGrpcStatus ( httpStatus ) ; } else { status = Status . INTERNAL . withDescription ( "missing HTTP status code" ) ; } return status . augmentDescription ( "missing GRPC status, inferred error from HTTP status code" ) ; } | 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 ) { } } return Charsets . UTF_8 ; } | 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 Sublistener ( substream ) ) ; } } synchronized ( lock ) { state . buffer . add ( new StartEntry ( ) ) ; } Substream substream = createSubstream ( 0 ) ; checkState ( hedgingPolicy == null , "hedgingPolicy has been initialized unexpectedly" ) ; hedgingPolicy = hedgingPolicyProvider . get ( ) ; if ( ! HedgingPolicy . DEFAULT . equals ( hedgingPolicy ) ) { isHedging = true ; retryPolicy = RetryPolicy . DEFAULT ; FutureCanceller scheduledHedgingRef = null ; synchronized ( lock ) { state = state . addActiveHedge ( substream ) ; if ( hasPotentialHedging ( state ) && ( throttle == null || throttle . isAboveThreshold ( ) ) ) { scheduledHedging = scheduledHedgingRef = new FutureCanceller ( lock ) ; } } if ( scheduledHedgingRef != null ) { scheduledHedgingRef . setFuture ( scheduledExecutorService . schedule ( new HedgingRunnable ( scheduledHedgingRef ) , hedgingPolicy . hedgingDelayNanos , TimeUnit . NANOSECONDS ) ) ; } } drain ( substream ) ; } | 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 ( ) ) { continue ; } int prevPos = nioBuffer . position ( ) ; internalHandshaker . getBytesToSendToPeer ( nioBuffer ) ; bytesWritten += nioBuffer . position ( ) - prevPos ; if ( nioBuffer . position ( ) == prevPos ) { break ; } } out . writerIndex ( out . writerIndex ( ) + bytesWritten ) ; } } | 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 ( ! nioBuffer . hasRemaining ( ) ) { continue ; } int prevPos = nioBuffer . position ( ) ; done = internalHandshaker . processBytesFromPeer ( nioBuffer ) ; bytesRead += nioBuffer . position ( ) - prevPos ; if ( done ) { break ; } } data . readerIndex ( data . readerIndex ( ) + bytesRead ) ; return done ; } } | 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 . parseLong ( cacheTtlPropertyValue ) ; } catch ( NumberFormatException e ) { logger . log ( Level . WARNING , "Property({0}) valid is not valid number format({1}), fall back to default({2})" , new Object [ ] { NETWORKADDRESS_CACHE_TTL_PROPERTY , cacheTtlPropertyValue , cacheTtl } ) ; } } return cacheTtl > 0 ? TimeUnit . SECONDS . toNanos ( cacheTtl ) : cacheTtl ; } | 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 = getClientLanguagesFromChoice ( choice ) ; if ( clientLanguages != null && ! clientLanguages . isEmpty ( ) ) { boolean javaPresent = false ; for ( String lang : clientLanguages ) { if ( "java" . equalsIgnoreCase ( lang ) ) { javaPresent = true ; break ; } } if ( ! javaPresent ) { return null ; } } Double percentage = getPercentageFromChoice ( choice ) ; if ( percentage != null ) { int pct = percentage . intValue ( ) ; Verify . verify ( pct >= 0 && pct <= 100 , "Bad percentage: %s" , percentage ) ; if ( random . nextInt ( 100 ) >= pct ) { return null ; } } List < String > clientHostnames = getHostnamesFromChoice ( choice ) ; if ( clientHostnames != null && ! clientHostnames . isEmpty ( ) ) { boolean hostnamePresent = false ; for ( String clientHostname : clientHostnames ) { if ( clientHostname . equals ( hostname ) ) { hostnamePresent = true ; break ; } } if ( ! hostnamePresent ) { return null ; } } Map < String , ? > sc = ServiceConfigUtil . getObject ( choice , SERVICE_CONFIG_CHOICE_SERVICE_CONFIG_KEY ) ; if ( sc == null ) { throw new VerifyException ( String . format ( "key '%s' missing in '%s'" , choice , SERVICE_CONFIG_CHOICE_SERVICE_CONFIG_KEY ) ) ; } return sc ; } | 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 , trailersCapture ) ) ; } | 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 ( ) , promise ) ; } | 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 . CANCEL . code ( ) , promise ) ; return ; } if ( cmd . endOfStream ( ) ) { closeStreamWhenDone ( promise , streamId ) ; } encoder ( ) . writeHeaders ( ctx , streamId , cmd . headers ( ) , 0 , cmd . endOfStream ( ) , promise ) ; } | 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 [ pos ] ; default : return getUTF8 ( ) ; } } | 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 '"' : attValue = quotedAV ( ) ; break ; case '#' : attValue = hexAV ( ) ; break ; case '+' : case ',' : case ';' : break ; default : attValue = escapedAV ( ) ; } if ( attributeType . equalsIgnoreCase ( attType ) ) { return attValue ; } if ( pos >= length ) { return null ; } if ( chars [ pos ] == ',' || chars [ pos ] == ';' ) { } else if ( chars [ pos ] != '+' ) { throw new IllegalStateException ( "Malformed DN: " + dn ) ; } pos ++ ; attType = nextAT ( ) ; if ( attType == null ) { throw new IllegalStateException ( "Malformed DN: " + dn ) ; } } } | 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 { config = configBuilder . build ( args ) ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; configBuilder . printUsage ( ) ; return ; } OpenLoopClient client = new OpenLoopClient ( config ) ; client . run ( ) ; } | 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 . duration ) ; final long start = System . nanoTime ( ) ; Histogram histogram = worker . call ( ) ; final long end = System . nanoTime ( ) ; printStats ( histogram , end - start ) ; if ( config . histogramFile != null ) { saveHistogram ( histogram , config . histogramFile ) ; } ch . shutdown ( ) ; } | 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 ( contentType . length ( ) == CONTENT_TYPE_GRPC . length ( ) ) { return true ; } char nextChar = contentType . charAt ( CONTENT_TYPE_GRPC . length ( ) ) ; return nextChar == '+' || nextChar == ';' ; } | 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 defaultPort = 443 ; String path = "/" + method . getServiceName ( ) ; URI uri ; try { uri = new URI ( scheme , authority , path , null , null ) ; } catch ( URISyntaxException e ) { throw Status . UNAUTHENTICATED . withDescription ( "Unable to construct service URI for auth" ) . withCause ( e ) . asException ( ) ; } if ( uri . getPort ( ) == defaultPort ) { uri = removePort ( uri ) ; } return uri ; } | 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 ( ) ; ServerServiceDefinition . Builder serviceBuilder = ServerServiceDefinition . builder ( serviceName ) ; for ( int methodIndex = 0 ; methodIndex < methodCountPerService ; ++ methodIndex ) { String methodName = randomString ( ) ; MethodDescriptor < Void , Void > methodDescriptor = MethodDescriptor . < Void , Void > newBuilder ( ) . setType ( MethodDescriptor . MethodType . UNKNOWN ) . setFullMethodName ( MethodDescriptor . generateFullMethodName ( serviceName , methodName ) ) . setRequestMarshaller ( TestMethodDescriptors . voidMarshaller ( ) ) . setResponseMarshaller ( TestMethodDescriptors . voidMarshaller ( ) ) . build ( ) ; serviceBuilder . addMethod ( methodDescriptor , new ServerCallHandler < Void , Void > ( ) { public Listener < Void > startCall ( ServerCall < Void , Void > call , Metadata headers ) { return null ; } } ) ; fullMethodNames . add ( methodDescriptor . getFullMethodName ( ) ) ; } registry . addService ( serviceBuilder . build ( ) ) ; } } | 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 new RuntimeException ( e ) ; } } | 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 < ? > configs = getList ( serviceConfig , SERVICE_CONFIG_LOAD_BALANCING_CONFIG_KEY ) ; for ( Map < String , ? > config : checkObjectList ( configs ) ) { lbConfigs . add ( config ) ; } } if ( lbConfigs . isEmpty ( ) ) { if ( serviceConfig . containsKey ( SERVICE_CONFIG_LOAD_BALANCING_POLICY_KEY ) ) { String policy = getString ( serviceConfig , SERVICE_CONFIG_LOAD_BALANCING_POLICY_KEY ) ; policy = policy . toLowerCase ( Locale . ROOT ) ; Map < String , ? > fakeConfig = Collections . singletonMap ( policy , Collections . emptyMap ( ) ) ; lbConfigs . add ( fakeConfig ) ; } } return Collections . unmodifiableList ( lbConfigs ) ; } | 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 Collections . unmodifiableList ( result ) ; } | 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 ( rawChildPolicies ) ) ; } return null ; } | 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 ( checkObjectList ( rawFallbackPolicies ) ) ; } return null ; } | 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 '%s' in '%s' is not List" , value , key , obj ) ) ; } return ( List < ? > ) value ; } | 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 . currentThread ( ) , t ) ; } } } finally { drainingThread . set ( null ) ; } } while ( ! queue . isEmpty ( ) ) ; } | 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 ( "http" ) ; requestHeaders [ i ++ ] = AsciiString . of ( ":path" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "/google.pubsub.v2.PublisherService/CreateTopic" ) ; requestHeaders [ i ++ ] = AsciiString . of ( ":authority" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "pubsub.googleapis.com" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "te" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "trailers" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "grpc-timeout" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "1S" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "content-type" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "application/grpc+proto" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "grpc-encoding" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "gzip" ) ; requestHeaders [ i ++ ] = AsciiString . of ( "authorization" ) ; requestHeaders [ i ] = AsciiString . of ( "Bearer y235.wef315yfh138vh31hv93hv8h3v" ) ; } | 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 handshaker = handshakerFactory . newHandshaker ( grpcHandler . getAuthority ( ) ) ; return new BufferUntilAltsNegotiatedHandler ( grpcHandler , new TsiHandshakeHandler ( new NettyTsiHandshaker ( handshaker ) ) , new TsiFrameHandler ( ) ) ; } public void close ( ) { logger . finest ( "ALTS Client ProtocolNegotiator Closed" ) ; lazyHandshakerChannel . close ( ) ; } } return new ClientAltsProtocolNegotiator ( ) ; } | 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 handshaker = handshakerFactory . newHandshaker ( null ) ; return new BufferUntilAltsNegotiatedHandler ( grpcHandler , new TsiHandshakeHandler ( new NettyTsiHandshaker ( handshaker ) ) , new TsiFrameHandler ( ) ) ; } public void close ( ) { logger . finest ( "ALTS Server ProtocolNegotiator Closed" ) ; lazyHandshakerChannel . close ( ) ; } } return new ServerAltsProtocolNegotiator ( ) ; } | 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 , roundTripTimeNanos ) ; } doExecute ( executor , runnable ) ; } | 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 . callbacks ; this . callbacks = null ; } for ( Map . Entry < ClientTransport . PingCallback , Executor > entry : callbacks . entrySet ( ) ) { doExecute ( entry . getValue ( ) , asRunnable ( entry . getKey ( ) , roundTripTimeNanos ) ) ; } return true ; } | 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 . PingCallback , Executor > entry : callbacks . entrySet ( ) ) { notifyFailed ( entry . getKey ( ) , entry . getValue ( ) , failureCause ) ; } } | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.