idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
16,300 | public Authentication loadAuthentication ( ) { return new AuthenticationYamlSwapper ( ) . swap ( YamlEngine . unmarshal ( regCenter . getDirectly ( configNode . getAuthenticationPath ( ) ) , YamlAuthenticationConfiguration . class ) ) ; } | Load authentication . |
16,301 | public void setDatabaseShardingValue ( final Comparable < ? > value ) { databaseShardingValues . clear ( ) ; databaseShardingValues . put ( "" , value ) ; databaseShardingOnly = true ; } | Set sharding value for database sharding only . |
16,302 | public void addDatabaseShardingValue ( final String logicTable , final Comparable < ? > value ) { databaseShardingValues . put ( logicTable , value ) ; databaseShardingOnly = false ; } | Add sharding value for database . |
16,303 | public void addTableShardingValue ( final String logicTable , final Comparable < ? > value ) { tableShardingValues . put ( logicTable , value ) ; databaseShardingOnly = false ; } | Add sharding value for table . |
16,304 | public static Collection < Comparable < ? > > getDatabaseShardingValues ( final String logicTable ) { return null == HINT_MANAGER_HOLDER . get ( ) ? Collections . < Comparable < ? > > emptyList ( ) : HINT_MANAGER_HOLDER . get ( ) . databaseShardingValues . get ( logicTable ) ; } | Get database sharding values . |
16,305 | public static Collection < Comparable < ? > > getTableShardingValues ( final String logicTable ) { return null == HINT_MANAGER_HOLDER . get ( ) ? Collections . < Comparable < ? > > emptyList ( ) : HINT_MANAGER_HOLDER . get ( ) . tableShardingValues . get ( logicTable ) ; } | Get table sharding values . |
16,306 | public void parse ( final DMLStatement updateStatement ) { lexerEngine . accept ( DefaultKeyword . SET ) ; do { parseSetItem ( updateStatement ) ; } while ( lexerEngine . skipIfEqual ( Symbol . COMMA ) ) ; } | Parse set items . |
16,307 | public static Object getValueByColumnType ( final ResultSet resultSet , final int columnIndex ) throws SQLException { ResultSetMetaData metaData = resultSet . getMetaData ( ) ; switch ( metaData . getColumnType ( columnIndex ) ) { case Types . BIT : case Types . BOOLEAN : return resultSet . getBoolean ( columnIndex ) ;... | Get value by column type . |
16,308 | public final synchronized void renew ( final DataSourceChangedEvent dataSourceChangedEvent ) throws Exception { if ( ! name . equals ( dataSourceChangedEvent . getShardingSchemaName ( ) ) ) { return ; } backendDataSource . close ( ) ; dataSources . clear ( ) ; dataSources . putAll ( DataSourceConverter . getDataSourceP... | Renew data source configuration . |
16,309 | public int getLength ( ) { return ownerLength + tableName . length ( ) + quoteCharacter . getStartDelimiter ( ) . length ( ) + quoteCharacter . getEndDelimiter ( ) . length ( ) ; } | Get table token length . |
16,310 | public void parse ( final SelectStatement selectStatement , final List < SelectItem > items ) { do { selectStatement . getItems ( ) . addAll ( parseSelectItems ( selectStatement ) ) ; } while ( lexerEngine . skipIfEqual ( Symbol . COMMA ) ) ; selectStatement . setSelectListStopIndex ( lexerEngine . getCurrentToken ( ) ... | Parse select list . |
16,311 | public String getSchemaName ( final String configurationNodeFullPath ) { String result = "" ; Pattern pattern = Pattern . compile ( getSchemaPath ( ) + "/(\\w+)" + "(/datasource|/rule)?" , Pattern . CASE_INSENSITIVE ) ; Matcher matcher = pattern . matcher ( configurationNodeFullPath ) ; if ( matcher . find ( ) ) { resu... | Get schema name . |
16,312 | public static MySQLCommandPacketType getCommandPacketType ( final MySQLPacketPayload payload ) { Preconditions . checkArgument ( 0 == payload . readInt1 ( ) , "Sequence ID of MySQL command packet must be `0`." ) ; return MySQLCommandPacketType . valueOf ( payload . readInt1 ( ) ) ; } | Get command packet type . |
16,313 | public static SQLParser newInstance ( final DatabaseType databaseType , final String sql ) { for ( ShardingParseEngine each : NewInstanceServiceLoader . newServiceInstances ( ShardingParseEngine . class ) ) { if ( DatabaseType . valueOf ( each . getDatabaseType ( ) ) == databaseType ) { return each . createSQLParser ( ... | New instance of SQL parser . |
16,314 | public String rewrite ( ) { if ( sqlTokens . isEmpty ( ) ) { return originalSQL ; } SQLBuilder result = new SQLBuilder ( Collections . emptyList ( ) ) ; int count = 0 ; for ( SQLToken each : sqlTokens ) { if ( 0 == count ) { result . appendLiterals ( originalSQL . substring ( 0 , each . getStartIndex ( ) ) ) ; } if ( e... | Rewrite SQL . |
16,315 | public Collection < String > getDataSourceNames ( ) { Collection < String > result = new HashSet < > ( tableUnits . size ( ) , 1 ) ; for ( TableUnit each : tableUnits ) { result . add ( each . getDataSourceName ( ) ) ; } return result ; } | Get all data source names . |
16,316 | public Map < String , Set < String > > getDataSourceLogicTablesMap ( final Collection < String > dataSourceNames ) { Map < String , Set < String > > result = new HashMap < > ( ) ; for ( String each : dataSourceNames ) { Set < String > logicTableNames = getLogicTableNames ( each ) ; if ( ! logicTableNames . isEmpty ( ) ... | Get map relationship between data source and logic tables via data sources names . |
16,317 | public final void setColumnValue ( final String columnName , final Object columnValue ) { SQLExpression sqlExpression = values [ getColumnIndex ( columnName ) ] ; if ( sqlExpression instanceof SQLParameterMarkerExpression ) { parameters [ getParameterIndex ( sqlExpression ) ] = columnValue ; } else { SQLExpression colu... | Set column value . |
16,318 | public final Object getColumnValue ( final String columnName ) { SQLExpression sqlExpression = values [ getColumnIndex ( columnName ) ] ; if ( sqlExpression instanceof SQLParameterMarkerExpression ) { return parameters [ getParameterIndex ( sqlExpression ) ] ; } else if ( sqlExpression instanceof SQLTextExpression ) { ... | Get column value . |
16,319 | public static CommandExecutor newInstance ( final MySQLCommandPacketType commandPacketType , final CommandPacket commandPacket , final BackendConnection backendConnection ) { log . debug ( "Execute packet type: {}, value: {}" , commandPacketType , commandPacket ) ; switch ( commandPacketType ) { case COM_QUIT : return ... | Create new instance of packet executor . |
16,320 | public Set < String > getActualTableNames ( final String dataSourceName , final String logicTableName ) { Set < String > result = new HashSet < > ( routingTables . size ( ) , 1 ) ; for ( RoutingTable each : routingTables ) { if ( dataSourceName . equalsIgnoreCase ( this . dataSourceName ) && each . getLogicTableName ( ... | Get actual tables names via data source name . |
16,321 | public Set < String > getLogicTableNames ( final String dataSourceName ) { Set < String > result = new HashSet < > ( routingTables . size ( ) , 1 ) ; for ( RoutingTable each : routingTables ) { if ( dataSourceName . equalsIgnoreCase ( this . dataSourceName ) ) { result . add ( each . getLogicTableName ( ) ) ; } } retur... | Get logic tables names via data source name . |
16,322 | public final void recordMethodInvocation ( final Class < ? > targetClass , final String methodName , final Class < ? > [ ] argumentTypes , final Object [ ] arguments ) { jdbcMethodInvocations . add ( new JdbcMethodInvocation ( targetClass . getMethod ( methodName , argumentTypes ) , arguments ) ) ; } | record method invocation . |
16,323 | public boolean next ( ) throws SQLException { boolean result = queryResult . next ( ) ; orderValues = result ? getOrderValues ( ) : Collections . < Comparable < ? > > emptyList ( ) ; return result ; } | iterate next data . |
16,324 | public byte [ ] generateRandomBytes ( final int length ) { byte [ ] result = new byte [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { result [ i ] = SEED [ random . nextInt ( SEED . length ) ] ; } return result ; } | Generate random bytes . |
16,325 | public Map < String , TableMetaData > load ( final ShardingRule shardingRule ) { Map < String , TableMetaData > result = new HashMap < > ( ) ; result . putAll ( loadShardingTables ( shardingRule ) ) ; result . putAll ( loadDefaultTables ( shardingRule ) ) ; return result ; } | Load all table meta data . |
16,326 | public static OptimizeEngine newInstance ( final ShardingRule shardingRule , final SQLStatement sqlStatement , final List < Object > parameters , final GeneratedKey generatedKey ) { if ( sqlStatement instanceof InsertStatement ) { return new InsertOptimizeEngine ( shardingRule , ( InsertStatement ) sqlStatement , param... | Create optimize engine instance . |
16,327 | public static OptimizeEngine newInstance ( final EncryptRule encryptRule , final SQLStatement sqlStatement , final List < Object > parameters ) { if ( sqlStatement instanceof InsertStatement ) { return new EncryptInsertOptimizeEngine ( encryptRule , ( InsertStatement ) sqlStatement , parameters ) ; } return new Encrypt... | Create encrypt optimize engine instance . |
16,328 | public static DatabaseProtocolFrontendEngine newInstance ( final DatabaseType databaseType ) { for ( DatabaseProtocolFrontendEngine each : NewInstanceServiceLoader . newServiceInstances ( DatabaseProtocolFrontendEngine . class ) ) { if ( DatabaseType . valueFrom ( each . getDatabaseType ( ) ) == databaseType ) { return... | Create new instance of database protocol frontend engine . |
16,329 | public ShardingConfiguration load ( ) throws IOException { Collection < String > schemaNames = new HashSet < > ( ) ; YamlProxyServerConfiguration serverConfig = loadServerConfiguration ( new File ( ShardingConfigurationLoader . class . getResource ( CONFIG_PATH + SERVER_CONFIG_FILE ) . getFile ( ) ) ) ; File configPath... | Load configuration of Sharding - Proxy . |
16,330 | @ SuppressWarnings ( "unchecked" ) public void init ( final FillerRuleDefinitionEntity fillerRuleDefinitionEntity ) { for ( FillerRuleEntity each : fillerRuleDefinitionEntity . getRules ( ) ) { rules . put ( ( Class < ? extends SQLSegment > ) Class . forName ( each . getSqlSegmentClass ( ) ) , ( SQLSegmentFiller ) Clas... | Initialize filler rule definition . |
16,331 | public static AliasExpressionParser createAliasExpressionParser ( final LexerEngine lexerEngine ) { switch ( lexerEngine . getDatabaseType ( ) ) { case H2 : return new MySQLAliasExpressionParser ( lexerEngine ) ; case MySQL : return new MySQLAliasExpressionParser ( lexerEngine ) ; case Oracle : return new OracleAliasEx... | Create alias parser instance . |
16,332 | private InputStream trustedCertificatesInputStream ( ) { String comodoRsaCertificationAuthority = "" + "-----BEGIN CERTIFICATE-----\n" + "MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\n" + "hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\n" + "A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RP... | Returns an input stream containing one or more certificate PEM files . This implementation just embeds the PEM files in Java strings ; most applications will instead read this from a resource file that gets bundled with the application . |
16,333 | private X509TrustManager defaultTrustManager ( ) throws GeneralSecurityException { TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( ( KeyStore ) null ) ; TrustManager [ ] trustManagers = trustManagerFactory . get... | Returns a trust manager that trusts the VM s default certificate authorities . |
16,334 | private static String inet6AddressToAscii ( byte [ ] address ) { int longestRunOffset = - 1 ; int longestRunLength = 0 ; for ( int i = 0 ; i < address . length ; i += 2 ) { int currentRunOffset = i ; while ( i < 16 && address [ i ] == 0 && address [ i + 1 ] == 0 ) { i += 2 ; } int currentRunLength = i - currentRunOffse... | Encodes an IPv6 address in canonical form according to RFC 5952 . |
16,335 | public synchronized void onOpen ( WebSocket webSocket , Response response ) { System . out . println ( "onOpen: " + response ) ; } | the body from slack is a 0 - byte - buffer |
16,336 | private void resetNextProxy ( HttpUrl url , Proxy proxy ) { if ( proxy != null ) { proxies = Collections . singletonList ( proxy ) ; } else { List < Proxy > proxiesOrNull = address . proxySelector ( ) . select ( url . uri ( ) ) ; proxies = proxiesOrNull != null && ! proxiesOrNull . isEmpty ( ) ? Util . immutableList ( ... | Prepares the proxy servers to try . |
16,337 | private Proxy nextProxy ( ) throws IOException { if ( ! hasNextProxy ( ) ) { throw new SocketException ( "No route to " + address . url ( ) . host ( ) + "; exhausted proxy configurations: " + proxies ) ; } Proxy result = proxies . get ( nextProxyIndex ++ ) ; resetNextInetSocketAddress ( result ) ; return result ; } | Returns the next proxy to try . May be PROXY . NO_PROXY but never null . |
16,338 | private void resetNextInetSocketAddress ( Proxy proxy ) throws IOException { inetSocketAddresses = new ArrayList < > ( ) ; String socketHost ; int socketPort ; if ( proxy . type ( ) == Proxy . Type . DIRECT || proxy . type ( ) == Proxy . Type . SOCKS ) { socketHost = address . url ( ) . host ( ) ; socketPort = address ... | Prepares the socket addresses to attempt for the current proxy or host . |
16,339 | public void awaitSuccess ( ) throws Exception { FutureTask < Void > futureTask = results . poll ( 5 , TimeUnit . SECONDS ) ; if ( futureTask == null ) throw new AssertionError ( "no onRequest call received" ) ; futureTask . get ( 5 , TimeUnit . SECONDS ) ; } | Returns once the duplex conversation completes successfully . |
16,340 | private void readTheListUninterruptibly ( ) { boolean interrupted = false ; try { while ( true ) { try { readTheList ( ) ; return ; } catch ( InterruptedIOException e ) { Thread . interrupted ( ) ; interrupted = true ; } catch ( IOException e ) { Platform . get ( ) . log ( Platform . WARN , "Failed to read public suffi... | Reads the public suffix list treating the operation as uninterruptible . We always want to read the list otherwise we ll be left in a bad state . If the thread was interrupted prior to this operation it will be re - interrupted after the list is read . |
16,341 | void writeClose ( int code , ByteString reason ) throws IOException { ByteString payload = ByteString . EMPTY ; if ( code != 0 || reason != null ) { if ( code != 0 ) { validateCloseCode ( code ) ; } Buffer buffer = new Buffer ( ) ; buffer . writeShort ( code ) ; if ( reason != null ) { buffer . write ( reason ) ; } pay... | Send a close frame with optional code and reason . |
16,342 | Sink newMessageSink ( int formatOpcode , long contentLength ) { if ( activeWriter ) { throw new IllegalStateException ( "Another message writer is active. Did you call close()?" ) ; } activeWriter = true ; frameSink . formatOpcode = formatOpcode ; frameSink . contentLength = contentLength ; frameSink . isFirstFrame = t... | Stream a message payload as a series of frames . This allows control frames to be interleaved between parts of the message . |
16,343 | private synchronized void start ( InetSocketAddress inetSocketAddress ) throws IOException { if ( started ) throw new IllegalStateException ( "start() already called" ) ; started = true ; executor = Executors . newCachedThreadPool ( Util . threadFactory ( "MockWebServer" , false ) ) ; this . inetSocketAddress = inetSoc... | Starts the server and binds to the given socket address . |
16,344 | private void readMessage ( ) throws IOException { while ( true ) { if ( closed ) throw new IOException ( "closed" ) ; if ( frameLength > 0 ) { source . readFully ( messageFrameBuffer , frameLength ) ; if ( ! isClient ) { messageFrameBuffer . readAndWriteUnsafe ( maskCursor ) ; maskCursor . seek ( messageFrameBuffer . s... | Reads a message body into across one or more frames . Control frames that occur between fragments will be processed . If the message payload is masked this will unmask as it s being processed . |
16,345 | public synchronized Headers takeHeaders ( ) throws IOException { readTimeout . enter ( ) ; try { while ( headersQueue . isEmpty ( ) && errorCode == null ) { waitForIo ( ) ; } } finally { readTimeout . exitAndThrowIfTimedOut ( ) ; } if ( ! headersQueue . isEmpty ( ) ) { return headersQueue . removeFirst ( ) ; } throw er... | Removes and returns the stream s received response headers blocking if necessary until headers have been received . If the returned list contains multiple blocks of headers the blocks will be delimited by null . |
16,346 | public synchronized Headers trailers ( ) throws IOException { if ( errorCode != null ) { throw errorException != null ? errorException : new StreamResetException ( errorCode ) ; } if ( ! source . finished || ! source . receiveBuffer . exhausted ( ) || ! source . readBuffer . exhausted ( ) ) { throw new IllegalStateExce... | Returns the trailers . It is only safe to call this once the source stream has been completely exhausted . |
16,347 | public void writeHeaders ( List < Header > responseHeaders , boolean outFinished , boolean flushHeaders ) throws IOException { assert ( ! Thread . holdsLock ( Http2Stream . this ) ) ; if ( responseHeaders == null ) { throw new NullPointerException ( "headers == null" ) ; } synchronized ( this ) { this . hasResponseHead... | Sends a reply to an incoming stream . |
16,348 | private RealConnection findHealthyConnection ( int connectTimeout , int readTimeout , int writeTimeout , int pingIntervalMillis , boolean connectionRetryEnabled , boolean doExtensiveHealthChecks ) throws IOException { while ( true ) { RealConnection candidate = findConnection ( connectTimeout , readTimeout , writeTimeo... | Finds a connection and returns it if it is healthy . If it is unhealthy the process is repeated until a healthy connection is found . |
16,349 | private RealConnection findConnection ( int connectTimeout , int readTimeout , int writeTimeout , int pingIntervalMillis , boolean connectionRetryEnabled ) throws IOException { boolean foundPooledConnection = false ; RealConnection result = null ; Route selectedRoute = null ; RealConnection releasedConnection ; Socket ... | Returns a connection to host a new stream . This prefers the existing connection if it exists then the pool finally building a new connection . |
16,350 | private boolean retryCurrentRoute ( ) { return transmitter . connection != null && transmitter . connection . routeFailureCount == 0 && Util . sameConnection ( transmitter . connection . route ( ) . address ( ) . url ( ) , address . url ( ) ) ; } | Return true if the route used for the current connection should be retried even if the connection itself is unhealthy . The biggest gotcha here is that we shouldn t reuse routes from coalesced connections . |
16,351 | public boolean send ( String text ) { if ( text == null ) throw new NullPointerException ( "text == null" ) ; return send ( ByteString . encodeUtf8 ( text ) , OPCODE_TEXT ) ; } | Writer methods to enqueue frames . They ll be sent asynchronously by the writer thread . |
16,352 | boolean writeOneFrame ( ) throws IOException { WebSocketWriter writer ; ByteString pong ; Object messageOrClose = null ; int receivedCloseCode = - 1 ; String receivedCloseReason = null ; Streams streamsToClose = null ; synchronized ( RealWebSocket . this ) { if ( failed ) { return false ; } writer = this . writer ; pon... | Attempts to remove a single frame from a queue and send it . This prefers to write urgent pongs before less urgent messages and close frames . For example it s possible that a caller will enqueue messages followed by pongs but this sends pongs followed by messages . Pongs are always written in the order they were enque... |
16,353 | private static Headers combine ( Headers cachedHeaders , Headers networkHeaders ) { Headers . Builder result = new Headers . Builder ( ) ; for ( int i = 0 , size = cachedHeaders . size ( ) ; i < size ; i ++ ) { String fieldName = cachedHeaders . name ( i ) ; String value = cachedHeaders . value ( i ) ; if ( "Warning" .... | Combines cached headers with a network headers as defined by RFC 7234 4 . 3 . 4 . |
16,354 | public MockResponse dispatch ( RecordedRequest request ) { HttpUrl requestUrl = mockWebServer . url ( request . getPath ( ) ) ; String code = requestUrl . queryParameter ( "code" ) ; String stateString = requestUrl . queryParameter ( "state" ) ; ByteString state = stateString != null ? ByteString . decodeBase64 ( state... | When the browser hits the redirect URL use the provided code to ask Slack for a session . |
16,355 | public MockResponse withWebSocketUpgrade ( WebSocketListener listener ) { setStatus ( "HTTP/1.1 101 Switching Protocols" ) ; setHeader ( "Connection" , "Upgrade" ) ; setHeader ( "Upgrade" , "websocket" ) ; body = null ; webSocketListener = listener ; return this ; } | Attempts to perform a web socket upgrade on the connection . This will overwrite any previously set status or body . |
16,356 | public static Set < String > varyFields ( Headers responseHeaders ) { Set < String > result = Collections . emptySet ( ) ; for ( int i = 0 , size = responseHeaders . size ( ) ; i < size ; i ++ ) { if ( ! "Vary" . equalsIgnoreCase ( responseHeaders . name ( i ) ) ) continue ; String value = responseHeaders . value ( i )... | Returns the names of the request headers that need to be checked for equality when caching . |
16,357 | public static List < Challenge > parseChallenges ( Headers responseHeaders , String headerName ) { List < Challenge > result = new ArrayList < > ( ) ; for ( int h = 0 ; h < responseHeaders . size ( ) ; h ++ ) { if ( headerName . equalsIgnoreCase ( responseHeaders . name ( h ) ) ) { Buffer header = new Buffer ( ) . writ... | Parse RFC 7235 challenges . This is awkward because we need to look ahead to know how to interpret a token . |
16,358 | private static boolean skipWhitespaceAndCommas ( Buffer buffer ) throws EOFException { boolean commaFound = false ; while ( ! buffer . exhausted ( ) ) { byte b = buffer . getByte ( 0 ) ; if ( b == ',' ) { buffer . readByte ( ) ; commaFound = true ; } else if ( b == ' ' || b == '\t' ) { buffer . readByte ( ) ; } else { ... | Returns true if any commas were skipped . |
16,359 | public void requestOauthSession ( String scopes , String team ) throws Exception { if ( sessionFactory == null ) { sessionFactory = new OAuthSessionFactory ( slackApi ) ; sessionFactory . start ( ) ; } HttpUrl authorizeUrl = sessionFactory . newAuthorizeUrl ( scopes , team , session -> { initOauthSession ( session ) ; ... | Shows a browser URL to authorize this app to act as this user . |
16,360 | public void startRtm ( ) throws IOException { String accessToken ; synchronized ( this ) { accessToken = session . access_token ; } RtmSession rtmSession = new RtmSession ( slackApi ) ; rtmSession . open ( accessToken ) ; } | Starts a real time messaging session . |
16,361 | private void connectTunnel ( int connectTimeout , int readTimeout , int writeTimeout , Call call , EventListener eventListener ) throws IOException { Request tunnelRequest = createTunnelRequest ( ) ; HttpUrl url = tunnelRequest . url ( ) ; for ( int i = 0 ; i < MAX_TUNNEL_ATTEMPTS ; i ++ ) { connectSocket ( connectTime... | Does all the work to build an HTTPS connection over a proxy tunnel . The catch here is that a proxy server can issue an auth challenge and then close the connection . |
16,362 | private void connectSocket ( int connectTimeout , int readTimeout , Call call , EventListener eventListener ) throws IOException { Proxy proxy = route . proxy ( ) ; Address address = route . address ( ) ; rawSocket = proxy . type ( ) == Proxy . Type . DIRECT || proxy . type ( ) == Proxy . Type . HTTP ? address . socket... | Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket . |
16,363 | private Request createTunnel ( int readTimeout , int writeTimeout , Request tunnelRequest , HttpUrl url ) throws IOException { String requestLine = "CONNECT " + Util . hostHeader ( url , true ) + " HTTP/1.1" ; while ( true ) { Http1ExchangeCodec tunnelCodec = new Http1ExchangeCodec ( null , null , source , sink ) ; sou... | To make an HTTPS connection over an HTTP proxy send an unencrypted CONNECT request to create the proxy connection . This may need to be retried if the proxy requires authorization . |
16,364 | private Request createTunnelRequest ( ) throws IOException { Request proxyConnectRequest = new Request . Builder ( ) . url ( route . address ( ) . url ( ) ) . method ( "CONNECT" , null ) . header ( "Host" , Util . hostHeader ( route . address ( ) . url ( ) , true ) ) . header ( "Proxy-Connection" , "Keep-Alive" ) . hea... | Returns a request that creates a TLS tunnel via an HTTP proxy . Everything in the tunnel request is sent unencrypted to the proxy server so tunnels include only the minimum set of headers . This avoids sending potentially sensitive data like HTTP cookies to the proxy unencrypted . |
16,365 | public boolean isHealthy ( boolean doExtensiveChecks ) { if ( socket . isClosed ( ) || socket . isInputShutdown ( ) || socket . isOutputShutdown ( ) ) { return false ; } if ( http2Connection != null ) { return ! http2Connection . isShutdown ( ) ; } if ( doExtensiveChecks ) { try { int readTimeout = socket . getSoTimeou... | Returns true if this connection is ready to host new streams . |
16,366 | public void onStream ( Http2Stream stream ) throws IOException { stream . close ( ErrorCode . REFUSED_STREAM , null ) ; } | Refuse incoming streams . |
16,367 | Exchange newExchange ( Interceptor . Chain chain , boolean doExtensiveHealthChecks ) { synchronized ( connectionPool ) { if ( noMoreExchanges ) { throw new IllegalStateException ( "released" ) ; } if ( exchange != null ) { throw new IllegalStateException ( "cannot make a new request because the previous response " + "i... | Returns a new exchange to carry a new request and response . |
16,368 | public void cancel ( ) { Exchange exchangeToCancel ; RealConnection connectionToCancel ; synchronized ( connectionPool ) { canceled = true ; exchangeToCancel = exchange ; connectionToCancel = exchangeFinder != null && exchangeFinder . connectingConnection ( ) != null ? exchangeFinder . connectingConnection ( ) : connec... | Immediately closes the socket connection if it s currently held . Use this to interrupt an in - flight request from any thread . It s the caller s responsibility to close the request body and response body streams ; otherwise resources may be leaked . |
16,369 | public Http2Stream pushStream ( int associatedStreamId , List < Header > requestHeaders , boolean out ) throws IOException { if ( client ) throw new IllegalStateException ( "Client cannot push requests." ) ; return newStream ( associatedStreamId , requestHeaders , out ) ; } | Returns a new server - initiated stream . |
16,370 | public Http2Stream newStream ( List < Header > requestHeaders , boolean out ) throws IOException { return newStream ( 0 , requestHeaders , out ) ; } | Returns a new locally - initiated stream . |
16,371 | public void writeData ( int streamId , boolean outFinished , Buffer buffer , long byteCount ) throws IOException { if ( byteCount == 0 ) { writer . data ( outFinished , streamId , buffer , 0 ) ; return ; } while ( byteCount > 0 ) { int toWrite ; synchronized ( Http2Connection . this ) { try { while ( bytesLeftInWriteWi... | Callers of this method are not thread safe and sometimes on application threads . Most often this method will be called to send a buffer worth of data to the peer . |
16,372 | public void shutdown ( ErrorCode statusCode ) throws IOException { synchronized ( writer ) { int lastGoodStreamId ; synchronized ( this ) { if ( shutdown ) { return ; } shutdown = true ; lastGoodStreamId = this . lastGoodStreamId ; } writer . goAway ( lastGoodStreamId , statusCode , Util . EMPTY_BYTE_ARRAY ) ; } } | Degrades this connection such that new streams can neither be created locally nor accepted from the remote peer . Existing streams are not impacted . This is intended to permit an endpoint to gracefully stop accepting new requests without harming previously established streams . |
16,373 | public void emitResponse ( T response ) { if ( ! isTerminated ( ) ) { subject . onNext ( response ) ; valueSet . set ( true ) ; } else { throw new IllegalStateException ( "Response has already terminated so response can not be set : " + response ) ; } } | Emit a response that should be OnNexted to an Observer |
16,374 | public Exception setExceptionIfResponseNotReceived ( Exception e , String exceptionMessage ) { Exception exception = e ; if ( ! valueSet . get ( ) && ! isTerminated ( ) ) { if ( e == null ) { exception = new IllegalStateException ( exceptionMessage ) ; } setExceptionIfResponseNotReceived ( exception ) ; } return except... | Set an ISE if a response is not yet received otherwise skip it |
16,375 | private byte [ ] wrapClass ( String className , boolean wrapConstructors , String ... methodNames ) throws NotFoundException , IOException , CannotCompileException { ClassPool cp = ClassPool . getDefault ( ) ; CtClass ctClazz = cp . get ( className ) ; if ( wrapConstructors ) { CtConstructor [ ] constructors = ctClazz ... | Wrap all signatures of a given method name . |
16,376 | protected TryableSemaphore getFallbackSemaphore ( ) { if ( fallbackSemaphoreOverride == null ) { TryableSemaphore _s = fallbackSemaphorePerCircuit . get ( commandKey . name ( ) ) ; if ( _s == null ) { fallbackSemaphorePerCircuit . putIfAbsent ( commandKey . name ( ) , new TryableSemaphoreActual ( properties . fallbackI... | Get the TryableSemaphore this HystrixCommand should use if a fallback occurs . |
16,377 | protected TryableSemaphore getExecutionSemaphore ( ) { if ( properties . executionIsolationStrategy ( ) . get ( ) == ExecutionIsolationStrategy . SEMAPHORE ) { if ( executionSemaphoreOverride == null ) { TryableSemaphore _s = executionSemaphorePerCircuit . get ( commandKey . name ( ) ) ; if ( _s == null ) { executionSe... | Get the TryableSemaphore this HystrixCommand should use for execution if not running in a separate thread . |
16,378 | private void validateCompletableReturnType ( Method commandMethod , Class < ? > callbackReturnType ) { if ( Void . TYPE == callbackReturnType ) { throw new FallbackDefinitionException ( createErrorMsg ( commandMethod , method , "fallback cannot return 'void' if command return type is " + Completable . class . getSimple... | everything can be wrapped into completable except void |
16,379 | public FallbackMethod getFallbackMethod ( Class < ? > enclosingType , Method commandMethod , boolean extended ) { if ( commandMethod . isAnnotationPresent ( HystrixCommand . class ) ) { return FALLBACK_METHOD_FINDER . find ( enclosingType , commandMethod , extended ) ; } return FallbackMethod . ABSENT ; } | Gets fallback method for command method . |
16,380 | public static Optional < Method > getMethod ( Class < ? > type , String name , Class < ? > ... parameterTypes ) { Method [ ] methods = type . getDeclaredMethods ( ) ; for ( Method method : methods ) { if ( method . getName ( ) . equals ( name ) && Arrays . equals ( method . getParameterTypes ( ) , parameterTypes ) ) { ... | Gets method by name and parameters types using reflection if the given type doesn t contain required method then continue applying this method for all super classes up to Object class . |
16,381 | public Method unbride ( final Method bridgeMethod , Class < ? > aClass ) throws IOException , NoSuchMethodException , ClassNotFoundException { if ( bridgeMethod . isBridge ( ) && bridgeMethod . isSynthetic ( ) ) { if ( cache . containsKey ( bridgeMethod ) ) { return cache . get ( bridgeMethod ) ; } ClassReader classRea... | Finds generic method for the given bridge method . |
16,382 | public R execute ( ) { try { return queue ( ) . get ( ) ; } catch ( Exception e ) { throw Exceptions . sneakyThrow ( decomposeException ( e ) ) ; } } | Used for synchronous execution of command . |
16,383 | public synchronized void start ( ) { if ( running . compareAndSet ( false , true ) ) { logger . debug ( "Starting HystrixMetricsPoller" ) ; try { scheduledTask = executor . scheduleWithFixedDelay ( new MetricsPoller ( listener ) , 0 , delay , TimeUnit . MILLISECONDS ) ; } catch ( Throwable ex ) { logger . error ( "Exce... | Start polling . |
16,384 | public static Class [ ] getParameterTypes ( JoinPoint joinPoint ) { MethodSignature signature = ( MethodSignature ) joinPoint . getSignature ( ) ; Method method = signature . getMethod ( ) ; return method . getParameterTypes ( ) ; } | Gets parameter types of the join point . |
16,385 | public static Method getDeclaredMethod ( Class < ? > type , String methodName , Class < ? > ... parameterTypes ) { Method method = null ; try { method = type . getDeclaredMethod ( methodName , parameterTypes ) ; if ( method . isBridge ( ) ) { method = MethodProvider . getInstance ( ) . unbride ( method , type ) ; } } c... | Gets declared method from specified type by mame and parameters types . |
16,386 | protected HystrixCommand < List < Object > > createCommand ( Collection < CollapsedRequest < Object , Object > > collapsedRequests ) { return new BatchHystrixCommand ( HystrixCommandBuilderFactory . getInstance ( ) . create ( metaHolder , collapsedRequests ) ) ; } | Creates batch command . |
16,387 | public Observable < ResponseType > submitRequest ( final RequestArgumentType arg ) { if ( ! timerListenerRegistered . get ( ) && timerListenerRegistered . compareAndSet ( false , true ) ) { timerListenerReference . set ( timer . addListener ( new CollapsedTask ( ) ) ) ; } while ( true ) { final RequestBatch < BatchRetu... | Submit a request to a batch . If the batch maxSize is hit trigger the batch immediately . |
16,388 | public ExecutionResult addEvent ( HystrixEventType eventType ) { return new ExecutionResult ( eventCounts . plus ( eventType ) , startTimestamp , executionLatency , userThreadLatency , failedExecutionException , executionException , executionOccurred , isExecutedInThread , collapserKey ) ; } | Creates a new ExecutionResult by adding the defined event to the ones on the current instance . |
16,389 | Closure createClosure ( String rootMethodName , final Object closureObj ) throws Exception { if ( ! isClosureCommand ( closureObj ) ) { throw new RuntimeException ( format ( ERROR_TYPE_MESSAGE , rootMethodName , getClosureCommandType ( ) . getName ( ) ) . getMessage ( ) ) ; } Method closureMethod = closureObj . getClas... | Creates closure . |
16,390 | protected UserAccount getFallback ( ) { return new UserAccount ( userCookie . userId , userCookie . name , userCookie . accountType , true , true , true ) ; } | Fallback that will use data from the UserCookie and stubbed defaults to create a UserAccount if the network call failed . |
16,391 | protected Response handleRequest ( ) { ResponseBuilder builder = null ; int numberConnections = getCurrentConnections ( ) . get ( ) ; int maxNumberConnectionsAllowed = getMaxNumberConcurrentConnectionsAllowed ( ) ; if ( numberConnections >= maxNumberConnectionsAllowed ) { builder = Response . status ( Status . SERVICE_... | Maintain an open connection with the client . On initial connection send latest data of each requested event type and subsequently send all changes for each requested event type . |
16,392 | public static HystrixCommandProperties . Setter initializeCommandProperties ( List < HystrixProperty > properties ) throws IllegalArgumentException { return initializeProperties ( HystrixCommandProperties . Setter ( ) , properties , CMD_PROP_MAP , "command" ) ; } | Creates and sets Hystrix command properties . |
16,393 | public static HystrixThreadPoolProperties . Setter initializeThreadPoolProperties ( List < HystrixProperty > properties ) throws IllegalArgumentException { return initializeProperties ( HystrixThreadPoolProperties . Setter ( ) , properties , TP_PROP_MAP , "thread pool" ) ; } | Creates and sets Hystrix thread pool properties . |
16,394 | public static HystrixCollapserProperties . Setter initializeCollapserProperties ( List < HystrixProperty > properties ) { return initializeProperties ( HystrixCollapserProperties . Setter ( ) , properties , COLLAPSER_PROP_MAP , "collapser" ) ; } | Creates and sets Hystrix collapser properties . |
16,395 | @ SuppressWarnings ( "unchecked" ) public T get ( ) { if ( HystrixRequestContext . getContextForCurrentThread ( ) == null ) { throw new IllegalStateException ( HystrixRequestContext . class . getSimpleName ( ) + ".initializeContext() must be called at the beginning of each request before RequestVariable functionality c... | Get the current value for this variable for the current request context . |
16,396 | public void clear ( String cacheKey ) { ValueCacheKey key = getRequestCacheKey ( cacheKey ) ; if ( key != null ) { ConcurrentHashMap < ValueCacheKey , HystrixCachedObservable < ? > > cacheInstance = requestVariableForCache . get ( concurrencyStrategy ) ; if ( cacheInstance == null ) { throw new IllegalStateException ( ... | Clear the cache for a given cacheKey . |
16,397 | boolean isIgnorable ( Throwable throwable ) { if ( ignoreExceptions == null || ignoreExceptions . isEmpty ( ) ) { return false ; } for ( Class < ? extends Throwable > ignoreException : ignoreExceptions ) { if ( ignoreException . isAssignableFrom ( throwable . getClass ( ) ) ) { return true ; } } return false ; } | Check whether triggered exception is ignorable . |
16,398 | protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { if ( isDestroyed ) { response . sendError ( 503 , "Service has been shut down." ) ; } else { handleRequest ( request , response ) ; } } | Handle incoming GETs |
16,399 | private void handleRequest ( HttpServletRequest request , final HttpServletResponse response ) throws ServletException , IOException { final AtomicBoolean moreDataWillBeSent = new AtomicBoolean ( true ) ; Subscription sampleSubscription = null ; int numberConnections = incrementAndGetCurrentConcurrentConnections ( ) ; ... | - maintain an open connection with the client - on initial connection send latest data of each requested event type - subsequently send all changes for each requested event type |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.