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 ) ; case Types . TINYINT : return resultSet . getByte ( columnIndex ) ; case Types . SMALLINT : return resultSet . getShort ( columnIndex ) ; case Types . INTEGER : return resultSet . getInt ( columnIndex ) ; case Types . BIGINT : return resultSet . getLong ( columnIndex ) ; case Types . NUMERIC : case Types . DECIMAL : return resultSet . getBigDecimal ( columnIndex ) ; case Types . FLOAT : case Types . DOUBLE : return resultSet . getDouble ( columnIndex ) ; case Types . CHAR : case Types . VARCHAR : case Types . LONGVARCHAR : return resultSet . getString ( columnIndex ) ; case Types . BINARY : case Types . VARBINARY : case Types . LONGVARBINARY : return resultSet . getBytes ( columnIndex ) ; case Types . DATE : return resultSet . getDate ( columnIndex ) ; case Types . TIME : return resultSet . getTime ( columnIndex ) ; case Types . TIMESTAMP : return resultSet . getTimestamp ( columnIndex ) ; case Types . CLOB : return resultSet . getClob ( columnIndex ) ; case Types . BLOB : return resultSet . getBlob ( columnIndex ) ; default : return resultSet . getObject ( 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 . getDataSourceParameterMap ( dataSourceChangedEvent . getDataSourceConfigurations ( ) ) ) ; backendDataSource = new JDBCBackendDataSource ( dataSources ) ; } | 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 ( ) . getEndPosition ( ) - lexerEngine . getCurrentToken ( ) . getLiterals ( ) . length ( ) ) ; items . addAll ( selectStatement . getItems ( ) ) ; } | 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 ( ) ) { result = matcher . group ( 1 ) ; } return result ; } | 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 ( sql ) ; } } throw new UnsupportedOperationException ( String . format ( "Cannot support database type '%s'" , databaseType ) ) ; } | 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 ( each instanceof SchemaToken ) { appendSchemaPlaceholder ( originalSQL , result , ( SchemaToken ) each , count ) ; } count ++ ; } return result . toSQL ( masterSlaveRule , metaData . getDataSource ( ) ) ; } | 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 ( ) ) { result . put ( each , logicTableNames ) ; } } return result ; } | 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 columnExpression = String . class == columnValue . getClass ( ) ? new SQLTextExpression ( String . valueOf ( columnValue ) ) : new SQLNumberExpression ( ( Number ) columnValue ) ; values [ getColumnIndex ( columnName ) ] = columnExpression ; } } | 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 ) { return ( ( SQLTextExpression ) sqlExpression ) . getText ( ) ; } else { return ( ( SQLNumberExpression ) sqlExpression ) . getNumber ( ) ; } } | 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 new MySQLComQuitExecutor ( ) ; case COM_INIT_DB : return new MySQLComInitDbExecutor ( ( MySQLComInitDbPacket ) commandPacket , backendConnection ) ; case COM_FIELD_LIST : return new MySQLComFieldListPacketExecutor ( ( MySQLComFieldListPacket ) commandPacket , backendConnection ) ; case COM_QUERY : return new MySQLComQueryPacketExecutor ( ( MySQLComQueryPacket ) commandPacket , backendConnection ) ; case COM_STMT_PREPARE : return new MySQLComStmtPrepareExecutor ( ( MySQLComStmtPreparePacket ) commandPacket , backendConnection ) ; case COM_STMT_EXECUTE : return new MySQLComStmtExecuteExecutor ( ( MySQLComStmtExecutePacket ) commandPacket , backendConnection ) ; case COM_STMT_CLOSE : return new MySQLComStmtCloseExecutor ( ( MySQLComStmtClosePacket ) commandPacket ) ; case COM_PING : return new MySQLComPingExecutor ( ) ; default : return new MySQLUnsupportedCommandExecutor ( commandPacketType ) ; } } | 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 ( ) . equalsIgnoreCase ( logicTableName ) ) { result . add ( each . getActualTableName ( ) ) ; } } return result ; } | 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 ( ) ) ; } } return result ; } | 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 , parameters , generatedKey ) ; } if ( sqlStatement instanceof SelectStatement || sqlStatement instanceof DMLStatement ) { return new QueryOptimizeEngine ( sqlStatement . getRouteConditions ( ) . getOrCondition ( ) , parameters ) ; } return new QueryOptimizeEngine ( sqlStatement . getRouteConditions ( ) . getOrCondition ( ) , parameters ) ; } | 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 EncryptDefaultOptimizeEngine ( ) ; } | 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 each ; } } throw new UnsupportedOperationException ( String . format ( "Cannot support database type '%s'" , databaseType ) ) ; } | 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 = new File ( ShardingConfigurationLoader . class . getResource ( CONFIG_PATH ) . getFile ( ) ) ; Collection < YamlProxyRuleConfiguration > ruleConfigurations = new LinkedList < > ( ) ; for ( File each : findRuleConfigurationFiles ( configPath ) ) { Optional < YamlProxyRuleConfiguration > ruleConfig = loadRuleConfiguration ( each , serverConfig ) ; if ( ruleConfig . isPresent ( ) ) { Preconditions . checkState ( schemaNames . add ( ruleConfig . get ( ) . getSchemaName ( ) ) , "Schema name `%s` must unique at all rule configurations." , ruleConfig . get ( ) . getSchemaName ( ) ) ; ruleConfigurations . add ( ruleConfig . get ( ) ) ; } } Preconditions . checkState ( ! ruleConfigurations . isEmpty ( ) || null != serverConfig . getOrchestration ( ) , "Can not find any sharding rule configuration file in path `%s`." , configPath . getPath ( ) ) ; Map < String , YamlProxyRuleConfiguration > ruleConfigurationMap = new HashMap < > ( ruleConfigurations . size ( ) , 1 ) ; for ( YamlProxyRuleConfiguration each : ruleConfigurations ) { ruleConfigurationMap . put ( each . getSchemaName ( ) , each ) ; } return new ShardingConfiguration ( serverConfig , ruleConfigurationMap ) ; } | 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 ) Class . forName ( each . getFillerClass ( ) ) . newInstance ( ) ) ; } } | 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 OracleAliasExpressionParser ( lexerEngine ) ; case SQLServer : return new SQLServerAliasExpressionParser ( lexerEngine ) ; case PostgreSQL : return new PostgreSQLAliasExpressionParser ( lexerEngine ) ; default : throw new UnsupportedOperationException ( String . format ( "Cannot support database type: %s" , lexerEngine . getDatabaseType ( ) ) ) ; } } | Create alias parser instance . |
16,332 | private InputStream trustedCertificatesInputStream ( ) { String comodoRsaCertificationAuthority = "" + "-----BEGIN CERTIFICATE-----\n" + "MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\n" + "hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\n" + "A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV\n" + "BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5\n" + "MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT\n" + "EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR\n" + "Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh\n" + "dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR\n" + "6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X\n" + "pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC\n" + "9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV\n" + "/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf\n" + "Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z\n" + "+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w\n" + "qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah\n" + "SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC\n" + "u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf\n" + "Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq\n" + "crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E\n" + "FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB\n" + "/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl\n" + "wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM\n" + "4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV\n" + "2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna\n" + "FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ\n" + "CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK\n" + "boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke\n" + "jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL\n" + "S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb\n" + "QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl\n" + "0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB\n" + "NVOFBkpdn627G190\n" + "-----END CERTIFICATE-----\n" ; String entrustRootCertificateAuthority = "" + "-----BEGIN CERTIFICATE-----\n" + "MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC\n" + "VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0\n" + "Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW\n" + "KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl\n" + "cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw\n" + "NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw\n" + "NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy\n" + "ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV\n" + "BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ\n" + "KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo\n" + "Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4\n" + "4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9\n" + "KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI\n" + "rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi\n" + "94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB\n" + "sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi\n" + "gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo\n" + "kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE\n" + "vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA\n" + "A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t\n" + "O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua\n" + "AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP\n" + "9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/\n" + "eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m\n" + "0vdXcDazv/wor3ElhVsT/h5/WrQ8\n" + "-----END CERTIFICATE-----\n" ; return new Buffer ( ) . writeUtf8 ( comodoRsaCertificationAuthority ) . writeUtf8 ( entrustRootCertificateAuthority ) . inputStream ( ) ; } | 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 . getTrustManagers ( ) ; if ( trustManagers . length != 1 || ! ( trustManagers [ 0 ] instanceof X509TrustManager ) ) { throw new IllegalStateException ( "Unexpected default trust managers:" + Arrays . toString ( trustManagers ) ) ; } return ( X509TrustManager ) trustManagers [ 0 ] ; } | 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 - currentRunOffset ; if ( currentRunLength > longestRunLength && currentRunLength >= 4 ) { longestRunOffset = currentRunOffset ; longestRunLength = currentRunLength ; } } Buffer result = new Buffer ( ) ; for ( int i = 0 ; i < address . length ; ) { if ( i == longestRunOffset ) { result . writeByte ( ':' ) ; i += longestRunLength ; if ( i == 16 ) result . writeByte ( ':' ) ; } else { if ( i > 0 ) result . writeByte ( ':' ) ; int group = ( address [ i ] & 0xff ) << 8 | address [ i + 1 ] & 0xff ; result . writeHexadecimalUnsignedLong ( group ) ; i += 2 ; } } return result . readUtf8 ( ) ; } | 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 ( proxiesOrNull ) : Util . immutableList ( Proxy . NO_PROXY ) ; } nextProxyIndex = 0 ; } | 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 . url ( ) . port ( ) ; } else { SocketAddress proxyAddress = proxy . address ( ) ; if ( ! ( proxyAddress instanceof InetSocketAddress ) ) { throw new IllegalArgumentException ( "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress . getClass ( ) ) ; } InetSocketAddress proxySocketAddress = ( InetSocketAddress ) proxyAddress ; socketHost = getHostString ( proxySocketAddress ) ; socketPort = proxySocketAddress . getPort ( ) ; } if ( socketPort < 1 || socketPort > 65535 ) { throw new SocketException ( "No route to " + socketHost + ":" + socketPort + "; port is out of range" ) ; } if ( proxy . type ( ) == Proxy . Type . SOCKS ) { inetSocketAddresses . add ( InetSocketAddress . createUnresolved ( socketHost , socketPort ) ) ; } else { eventListener . dnsStart ( call , socketHost ) ; List < InetAddress > addresses = address . dns ( ) . lookup ( socketHost ) ; if ( addresses . isEmpty ( ) ) { throw new UnknownHostException ( address . dns ( ) + " returned no addresses for " + socketHost ) ; } eventListener . dnsEnd ( call , socketHost , addresses ) ; for ( int i = 0 , size = addresses . size ( ) ; i < size ; i ++ ) { InetAddress inetAddress = addresses . get ( i ) ; inetSocketAddresses . add ( new InetSocketAddress ( inetAddress , socketPort ) ) ; } } } | 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 suffix list" , e ) ; return ; } } } finally { if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } } } | 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 ) ; } payload = buffer . readByteString ( ) ; } try { writeControlFrame ( OPCODE_CONTROL_CLOSE , payload ) ; } finally { writerClosed = true ; } } | 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 = true ; frameSink . closed = false ; return frameSink ; } | 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 = inetSocketAddress ; if ( serverSocketFactory == null ) { serverSocketFactory = ServerSocketFactory . getDefault ( ) ; } serverSocket = serverSocketFactory . createServerSocket ( ) ; serverSocket . setReuseAddress ( inetSocketAddress . getPort ( ) != 0 ) ; serverSocket . bind ( inetSocketAddress , 50 ) ; port = serverSocket . getLocalPort ( ) ; executor . execute ( new NamedRunnable ( "MockWebServer %s" , port ) { protected void execute ( ) { try { logger . info ( MockWebServer . this + " starting to accept connections" ) ; acceptConnections ( ) ; } catch ( Throwable e ) { logger . log ( Level . WARNING , MockWebServer . this + " failed unexpectedly" , e ) ; } closeQuietly ( serverSocket ) ; for ( Iterator < Socket > s = openClientSockets . iterator ( ) ; s . hasNext ( ) ; ) { closeQuietly ( s . next ( ) ) ; s . remove ( ) ; } for ( Iterator < Http2Connection > s = openConnections . iterator ( ) ; s . hasNext ( ) ; ) { closeQuietly ( s . next ( ) ) ; s . remove ( ) ; } dispatcher . shutdown ( ) ; executor . shutdown ( ) ; } private void acceptConnections ( ) throws Exception { while ( true ) { Socket socket ; try { socket = serverSocket . accept ( ) ; } catch ( SocketException e ) { logger . info ( MockWebServer . this + " done accepting connections: " + e . getMessage ( ) ) ; return ; } SocketPolicy socketPolicy = dispatcher . peek ( ) . getSocketPolicy ( ) ; if ( socketPolicy == DISCONNECT_AT_START ) { dispatchBookkeepingRequest ( 0 , socket ) ; socket . close ( ) ; } else { openClientSockets . add ( socket ) ; serveConnection ( socket ) ; } } } } ) ; } | 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 . size ( ) - frameLength ) ; toggleMask ( maskCursor , maskKey ) ; maskCursor . close ( ) ; } } if ( isFinalFrame ) break ; readUntilNonControlFrame ( ) ; if ( opcode != OPCODE_CONTINUATION ) { throw new ProtocolException ( "Expected continuation opcode. Got: " + toHexString ( opcode ) ) ; } } } | 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 errorException != null ? errorException : new StreamResetException ( errorCode ) ; } | 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 IllegalStateException ( "too early; can't read the trailers yet" ) ; } return source . trailers != null ? source . trailers : Util . EMPTY_HEADERS ; } | 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 . hasResponseHeaders = true ; if ( outFinished ) { this . sink . finished = true ; } } if ( ! flushHeaders ) { synchronized ( connection ) { flushHeaders = connection . bytesLeftInWriteWindow == 0L ; } } connection . writeHeaders ( id , outFinished , responseHeaders ) ; if ( flushHeaders ) { connection . flush ( ) ; } } | 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 , writeTimeout , pingIntervalMillis , connectionRetryEnabled ) ; synchronized ( connectionPool ) { if ( candidate . successCount == 0 ) { return candidate ; } } if ( ! candidate . isHealthy ( doExtensiveHealthChecks ) ) { candidate . noNewExchanges ( ) ; continue ; } return candidate ; } } | 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 toClose ; synchronized ( connectionPool ) { if ( transmitter . isCanceled ( ) ) throw new IOException ( "Canceled" ) ; hasStreamFailure = false ; Route previousRoute = retryCurrentRoute ( ) ? transmitter . connection . route ( ) : null ; releasedConnection = transmitter . connection ; toClose = transmitter . connection != null && transmitter . connection . noNewExchanges ? transmitter . releaseConnectionNoEvents ( ) : null ; if ( transmitter . connection != null ) { result = transmitter . connection ; releasedConnection = null ; } if ( result == null ) { if ( connectionPool . transmitterAcquirePooledConnection ( address , transmitter , null , false ) ) { foundPooledConnection = true ; result = transmitter . connection ; } else { selectedRoute = previousRoute ; } } } closeQuietly ( toClose ) ; if ( releasedConnection != null ) { eventListener . connectionReleased ( call , releasedConnection ) ; } if ( foundPooledConnection ) { eventListener . connectionAcquired ( call , result ) ; } if ( result != null ) { return result ; } boolean newRouteSelection = false ; if ( selectedRoute == null && ( routeSelection == null || ! routeSelection . hasNext ( ) ) ) { newRouteSelection = true ; routeSelection = routeSelector . next ( ) ; } List < Route > routes = null ; synchronized ( connectionPool ) { if ( transmitter . isCanceled ( ) ) throw new IOException ( "Canceled" ) ; if ( newRouteSelection ) { routes = routeSelection . getAll ( ) ; if ( connectionPool . transmitterAcquirePooledConnection ( address , transmitter , routes , false ) ) { foundPooledConnection = true ; result = transmitter . connection ; } } if ( ! foundPooledConnection ) { if ( selectedRoute == null ) { selectedRoute = routeSelection . next ( ) ; } result = new RealConnection ( connectionPool , selectedRoute ) ; connectingConnection = result ; } } if ( foundPooledConnection ) { eventListener . connectionAcquired ( call , result ) ; return result ; } result . connect ( connectTimeout , readTimeout , writeTimeout , pingIntervalMillis , connectionRetryEnabled , call , eventListener ) ; connectionPool . getRouteDatabase ( ) . connected ( result . route ( ) ) ; Socket socket = null ; synchronized ( connectionPool ) { connectingConnection = null ; if ( connectionPool . transmitterAcquirePooledConnection ( address , transmitter , routes , true ) ) { result . noNewExchanges = true ; socket = result . socket ( ) ; result = transmitter . connection ; } else { connectionPool . put ( result ) ; transmitter . acquireConnectionNoEvents ( result ) ; } } closeQuietly ( socket ) ; eventListener . connectionAcquired ( call , result ) ; return result ; } | 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 ; pong = pongQueue . poll ( ) ; if ( pong == null ) { messageOrClose = messageAndCloseQueue . poll ( ) ; if ( messageOrClose instanceof Close ) { receivedCloseCode = this . receivedCloseCode ; receivedCloseReason = this . receivedCloseReason ; if ( receivedCloseCode != - 1 ) { streamsToClose = this . streams ; this . streams = null ; this . executor . shutdown ( ) ; } else { cancelFuture = executor . schedule ( new CancelRunnable ( ) , ( ( Close ) messageOrClose ) . cancelAfterCloseMillis , MILLISECONDS ) ; } } else if ( messageOrClose == null ) { return false ; } } } try { if ( pong != null ) { writer . writePong ( pong ) ; } else if ( messageOrClose instanceof Message ) { ByteString data = ( ( Message ) messageOrClose ) . data ; BufferedSink sink = Okio . buffer ( writer . newMessageSink ( ( ( Message ) messageOrClose ) . formatOpcode , data . size ( ) ) ) ; sink . write ( data ) ; sink . close ( ) ; synchronized ( this ) { queueSize -= data . size ( ) ; } } else if ( messageOrClose instanceof Close ) { Close close = ( Close ) messageOrClose ; writer . writeClose ( close . code , close . reason ) ; if ( streamsToClose != null ) { listener . onClosed ( this , receivedCloseCode , receivedCloseReason ) ; } } else { throw new AssertionError ( ) ; } return true ; } finally { closeQuietly ( streamsToClose ) ; } } | 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 enqueued . |
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" . equalsIgnoreCase ( fieldName ) && value . startsWith ( "1" ) ) { continue ; } if ( isContentSpecificHeader ( fieldName ) || ! isEndToEnd ( fieldName ) || networkHeaders . get ( fieldName ) == null ) { addHeaderLenient ( result , fieldName , value ) ; } } for ( int i = 0 , size = networkHeaders . size ( ) ; i < size ; i ++ ) { String fieldName = networkHeaders . name ( i ) ; if ( ! isContentSpecificHeader ( fieldName ) && isEndToEnd ( fieldName ) ) { addHeaderLenient ( result , fieldName , networkHeaders . value ( i ) ) ; } } return result . build ( ) ; } | 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 ( stateString ) : null ; Listener listener ; synchronized ( this ) { listener = listeners . get ( state ) ; } if ( code == null || listener == null ) { return new MockResponse ( ) . setResponseCode ( 404 ) . setBody ( "unexpected request" ) ; } try { OAuthSession session = slackApi . exchangeCode ( code , redirectUrl ( ) ) ; listener . sessionGranted ( session ) ; } catch ( IOException e ) { return new MockResponse ( ) . setResponseCode ( 400 ) . setBody ( "code exchange failed: " + e . getMessage ( ) ) ; } synchronized ( this ) { listeners . remove ( state ) ; } return new MockResponse ( ) . setResponseCode ( 302 ) . addHeader ( "Location" , "https://twitter.com/CuteEmergency/status/789457462864863232" ) ; } | 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 ) ; if ( result . isEmpty ( ) ) { result = new TreeSet < > ( String . CASE_INSENSITIVE_ORDER ) ; } for ( String varyField : value . split ( "," ) ) { result . add ( varyField . trim ( ) ) ; } } return result ; } | 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 ( ) . writeUtf8 ( responseHeaders . value ( h ) ) ; try { parseChallengeHeader ( result , header ) ; } catch ( EOFException e ) { Platform . get ( ) . log ( Platform . WARN , "Unable to parse challenge" , e ) ; } } } return result ; } | 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 { break ; } } return commaFound ; } | 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 ) ; System . out . printf ( "session granted: %s\n" , session ) ; } ) ; System . out . printf ( "open this URL in a browser: %s\n" , authorizeUrl ) ; } | 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 ( connectTimeout , readTimeout , call , eventListener ) ; tunnelRequest = createTunnel ( readTimeout , writeTimeout , tunnelRequest , url ) ; if ( tunnelRequest == null ) break ; closeQuietly ( rawSocket ) ; rawSocket = null ; sink = null ; source = null ; eventListener . connectEnd ( call , route . socketAddress ( ) , route . proxy ( ) , null ) ; } } | 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 . socketFactory ( ) . createSocket ( ) : new Socket ( proxy ) ; eventListener . connectStart ( call , route . socketAddress ( ) , proxy ) ; rawSocket . setSoTimeout ( readTimeout ) ; try { Platform . get ( ) . connectSocket ( rawSocket , route . socketAddress ( ) , connectTimeout ) ; } catch ( ConnectException e ) { ConnectException ce = new ConnectException ( "Failed to connect to " + route . socketAddress ( ) ) ; ce . initCause ( e ) ; throw ce ; } try { source = Okio . buffer ( Okio . source ( rawSocket ) ) ; sink = Okio . buffer ( Okio . sink ( rawSocket ) ) ; } catch ( NullPointerException npe ) { if ( NPE_THROW_WITH_NULL . equals ( npe . getMessage ( ) ) ) { throw new IOException ( npe ) ; } } } | 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 ) ; source . timeout ( ) . timeout ( readTimeout , MILLISECONDS ) ; sink . timeout ( ) . timeout ( writeTimeout , MILLISECONDS ) ; tunnelCodec . writeRequest ( tunnelRequest . headers ( ) , requestLine ) ; tunnelCodec . finishRequest ( ) ; Response response = tunnelCodec . readResponseHeaders ( false ) . request ( tunnelRequest ) . build ( ) ; tunnelCodec . skipConnectBody ( response ) ; switch ( response . code ( ) ) { case HTTP_OK : if ( ! source . getBuffer ( ) . exhausted ( ) || ! sink . buffer ( ) . exhausted ( ) ) { throw new IOException ( "TLS tunnel buffered too many bytes!" ) ; } return null ; case HTTP_PROXY_AUTH : tunnelRequest = route . address ( ) . proxyAuthenticator ( ) . authenticate ( route , response ) ; if ( tunnelRequest == null ) throw new IOException ( "Failed to authenticate with proxy" ) ; if ( "close" . equalsIgnoreCase ( response . header ( "Connection" ) ) ) { return tunnelRequest ; } break ; default : throw new IOException ( "Unexpected response code for CONNECT: " + response . code ( ) ) ; } } } | 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" ) . header ( "User-Agent" , Version . userAgent ) . build ( ) ; Response fakeAuthChallengeResponse = new Response . Builder ( ) . request ( proxyConnectRequest ) . protocol ( Protocol . HTTP_1_1 ) . code ( HttpURLConnection . HTTP_PROXY_AUTH ) . message ( "Preemptive Authenticate" ) . body ( Util . EMPTY_RESPONSE ) . sentRequestAtMillis ( - 1L ) . receivedResponseAtMillis ( - 1L ) . header ( "Proxy-Authenticate" , "OkHttp-Preemptive" ) . build ( ) ; Request authenticatedRequest = route . address ( ) . proxyAuthenticator ( ) . authenticate ( route , fakeAuthChallengeResponse ) ; return authenticatedRequest != null ? authenticatedRequest : proxyConnectRequest ; } | 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 . getSoTimeout ( ) ; try { socket . setSoTimeout ( 1 ) ; if ( source . exhausted ( ) ) { return false ; } return true ; } finally { socket . setSoTimeout ( readTimeout ) ; } } catch ( SocketTimeoutException ignored ) { } catch ( IOException e ) { return false ; } } return true ; } | 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 " + "is still open: please call response.close()" ) ; } } ExchangeCodec codec = exchangeFinder . find ( client , chain , doExtensiveHealthChecks ) ; Exchange result = new Exchange ( this , call , eventListener , exchangeFinder , codec ) ; synchronized ( connectionPool ) { this . exchange = result ; this . exchangeRequestDone = false ; this . exchangeResponseDone = false ; return result ; } } | 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 ( ) : connection ; } if ( exchangeToCancel != null ) { exchangeToCancel . cancel ( ) ; } else if ( connectionToCancel != null ) { connectionToCancel . cancel ( ) ; } } | 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 ( bytesLeftInWriteWindow <= 0 ) { if ( ! streams . containsKey ( streamId ) ) { throw new IOException ( "stream closed" ) ; } Http2Connection . this . wait ( ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new InterruptedIOException ( ) ; } toWrite = ( int ) Math . min ( byteCount , bytesLeftInWriteWindow ) ; toWrite = Math . min ( toWrite , writer . maxDataLength ( ) ) ; bytesLeftInWriteWindow -= toWrite ; } byteCount -= toWrite ; writer . data ( outFinished && byteCount == 0 , streamId , buffer , toWrite ) ; } } | 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 exception ; } | 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 . getConstructors ( ) ; for ( CtConstructor constructor : constructors ) { try { constructor . insertBefore ( "{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.notifyOfNetworkEvent(); }" ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed trying to wrap constructor of class: " + className , e ) ; } } } CtMethod [ ] methods = ctClazz . getDeclaredMethods ( ) ; for ( CtMethod method : methods ) { try { for ( String methodName : methodNames ) { if ( method . getName ( ) . equals ( methodName ) ) { method . insertBefore ( "{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.handleNetworkEvent(); }" ) ; } } } catch ( Exception e ) { throw new RuntimeException ( "Failed trying to wrap method [" + method . getName ( ) + "] of class: " + className , e ) ; } } return ctClazz . toBytecode ( ) ; } | 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 . fallbackIsolationSemaphoreMaxConcurrentRequests ( ) ) ) ; return fallbackSemaphorePerCircuit . get ( commandKey . name ( ) ) ; } else { return _s ; } } else { return fallbackSemaphoreOverride ; } } | 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 ) { executionSemaphorePerCircuit . putIfAbsent ( commandKey . name ( ) , new TryableSemaphoreActual ( properties . executionIsolationSemaphoreMaxConcurrentRequests ( ) ) ) ; return executionSemaphorePerCircuit . get ( commandKey . name ( ) ) ; } else { return _s ; } } else { return executionSemaphoreOverride ; } } else { return TryableSemaphoreNoOp . DEFAULT ; } } | 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 . getSimpleName ( ) ) ) ; } } | 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 ) ) { return Optional . of ( method ) ; } } Class < ? > superClass = type . getSuperclass ( ) ; if ( superClass != null && ! superClass . equals ( Object . class ) ) { return getMethod ( superClass , name , parameterTypes ) ; } else { return Optional . absent ( ) ; } } | 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 classReader = new ClassReader ( aClass . getName ( ) ) ; final MethodSignature methodSignature = new MethodSignature ( ) ; classReader . accept ( new ClassVisitor ( ASM5 ) { public MethodVisitor visitMethod ( int access , String name , String desc , String signature , String [ ] exceptions ) { boolean bridge = ( access & ACC_BRIDGE ) != 0 && ( access & ACC_SYNTHETIC ) != 0 ; if ( bridge && bridgeMethod . getName ( ) . equals ( name ) && getParameterCount ( desc ) == bridgeMethod . getParameterTypes ( ) . length ) { return new MethodFinder ( methodSignature ) ; } return super . visitMethod ( access , name , desc , signature , exceptions ) ; } } , 0 ) ; Method method = aClass . getDeclaredMethod ( methodSignature . name , methodSignature . getParameterTypes ( ) ) ; cache . put ( bridgeMethod , method ) ; return method ; } else { return bridgeMethod ; } } | 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 ( "Exception while creating the MetricsPoller task" ) ; ex . printStackTrace ( ) ; running . set ( false ) ; } } } | 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 ) ; } } catch ( NoSuchMethodException e ) { Class < ? > superclass = type . getSuperclass ( ) ; if ( superclass != null ) { method = getDeclaredMethod ( superclass , methodName , parameterTypes ) ; } } catch ( ClassNotFoundException e ) { Throwables . propagate ( e ) ; } catch ( IOException e ) { Throwables . propagate ( e ) ; } return method ; } | 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 < BatchReturnType , ResponseType , RequestArgumentType > b = batch . get ( ) ; if ( b == null ) { return Observable . error ( new IllegalStateException ( "Submitting requests after collapser is shutdown" ) ) ; } final Observable < ResponseType > response ; if ( arg != null ) { response = b . offer ( arg ) ; } else { response = b . offer ( ( RequestArgumentType ) NULL_SENTINEL ) ; } if ( response != null ) { return response ; } else { createNewBatchAndExecutePreviousIfNeeded ( b ) ; } } } | 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 . getClass ( ) . getMethod ( INVOKE_METHOD ) ; return new Closure ( closureMethod , closureObj ) ; } | 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_UNAVAILABLE ) . entity ( "MaxConcurrentConnections reached: " + maxNumberConnectionsAllowed ) ; } else { builder = Response . status ( Status . OK ) ; builder . header ( HttpHeaders . CONTENT_TYPE , "text/event-stream;charset=UTF-8" ) ; builder . header ( HttpHeaders . CACHE_CONTROL , "no-cache, no-store, max-age=0, must-revalidate" ) ; builder . header ( "Pragma" , "no-cache" ) ; getCurrentConnections ( ) . incrementAndGet ( ) ; builder . entity ( new HystrixStream ( sampleStream , pausePollerThreadDelayInMs , getCurrentConnections ( ) ) ) ; } return builder . build ( ) ; } | 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 can be used." ) ; } ConcurrentHashMap < HystrixRequestVariableDefault < ? > , LazyInitializer < ? > > variableMap = HystrixRequestContext . getContextForCurrentThread ( ) . state ; LazyInitializer < ? > v = variableMap . get ( this ) ; if ( v != null ) { return ( T ) v . get ( ) ; } LazyInitializer < T > l = new LazyInitializer < T > ( this ) ; LazyInitializer < ? > existing = variableMap . putIfAbsent ( this , l ) ; if ( existing == null ) { return l . get ( ) ; } else { return ( T ) existing . get ( ) ; } } | 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 ( "Request caching is not available. Maybe you need to initialize the HystrixRequestContext?" ) ; } cacheInstance . remove ( key ) ; } } | 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 ( ) ; try { int maxNumberConnectionsAllowed = getMaxNumberConcurrentConnectionsAllowed ( ) ; if ( numberConnections > maxNumberConnectionsAllowed ) { response . sendError ( 503 , "MaxConcurrentConnections reached: " + maxNumberConnectionsAllowed ) ; } else { response . setHeader ( "Content-Type" , "text/event-stream;charset=UTF-8" ) ; response . setHeader ( "Cache-Control" , "no-cache, no-store, max-age=0, must-revalidate" ) ; response . setHeader ( "Pragma" , "no-cache" ) ; final PrintWriter writer = response . getWriter ( ) ; sampleSubscription = sampleStream . observeOn ( Schedulers . io ( ) ) . subscribe ( new Subscriber < String > ( ) { public void onCompleted ( ) { logger . error ( "HystrixSampleSseServlet: ({}) received unexpected OnCompleted from sample stream" , getClass ( ) . getSimpleName ( ) ) ; moreDataWillBeSent . set ( false ) ; } public void onError ( Throwable e ) { moreDataWillBeSent . set ( false ) ; } public void onNext ( String sampleDataAsString ) { if ( sampleDataAsString != null ) { try { synchronized ( responseWriteLock ) { writer . print ( "data: " + sampleDataAsString + "\n\n" ) ; if ( writer . checkError ( ) ) { moreDataWillBeSent . set ( false ) ; } writer . flush ( ) ; } } catch ( Exception ex ) { moreDataWillBeSent . set ( false ) ; } } } } ) ; while ( moreDataWillBeSent . get ( ) && ! isDestroyed ) { try { Thread . sleep ( pausePollerThreadDelayInMs ) ; synchronized ( responseWriteLock ) { writer . print ( "ping: \n\n" ) ; if ( writer . checkError ( ) ) { moreDataWillBeSent . set ( false ) ; } writer . flush ( ) ; } } catch ( Exception ex ) { moreDataWillBeSent . set ( false ) ; } } } } finally { decrementCurrentConcurrentConnections ( ) ; if ( sampleSubscription != null && ! sampleSubscription . isUnsubscribed ( ) ) { sampleSubscription . unsubscribe ( ) ; } } } | - 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.