@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage()); } if (executionCount >= _maxRetryCount) { // Do not retry if over max retry count return false; } else if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } else if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); // Retry if the request is considered idempotent return idempotent; }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }
private HttpEngine() { this.mDefaultHttpClient = null; this.mDefaultHttpClient = createHttpClient(); this.mDefaultHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (DataStatistics.getInstance().isDebug()) { Log.d(DataStatistics.TAG, exception.getClass() + NetworkUtils.DELIMITER_COLON + exception.getMessage() + ",executionCount:" + executionCount); } if (executionCount >= 3) { return false; } if (exception instanceof NoHttpResponseException) { return true; } if (exception instanceof ClientProtocolException) { return true; } return false; } }); }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) {// 如果已经重试了3次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return true; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }
private String findFaultClassifier(final String id) { if (registry.isRegistered(id, FaultClassifier.class)) { return generateBeanName(id, FaultClassifier.class); } else if (registry.isRegistered(FaultClassifier.class)) { return generateBeanName(FaultClassifier.class); } else { return registry.registerIfAbsent(FaultClassifier.class, () -> { final List<Predicate<Throwable>> predicates = list(); predicates.addAll(FaultClassifier.defaults()); predicates.add(ConnectionClosedException.class::isInstance); predicates.add(NoHttpResponseException.class::isInstance); return genericBeanDefinition(FaultClassifier.class) .setFactoryMethod("create") .addConstructorArgValue(predicates); }); } }
@Test public void testHttpPlainFail() throws Exception { thrown.expect(NoHttpResponseException.class); enableHTTPClientSSL = false; trustHTTPServerCertificate = true; sendHTTPClientCertificate = false; final Settings settings = Settings.builder().put("searchguard.ssl.transport.enabled", false) .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL) .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_ALIAS, "node-0").put("searchguard.ssl.http.enabled", true) .put("searchguard.ssl.http.clientauth_mode", "OPTIONAL") .put("searchguard.ssl.http.keystore_filepath", getAbsoluteFilePathFromClassPath("node-0-keystore.jks")) .put("searchguard.ssl.http.truststore_filepath", getAbsoluteFilePathFromClassPath("truststore.jks")).build(); startES(settings); Assert.assertTrue(executeSimpleRequest("_searchguard/sslinfo?pretty").length() > 0); Assert.assertTrue(executeSimpleRequest("_nodes/settings?pretty").contains(clustername)); Assert.assertTrue(executeSimpleRequest("_searchguard/sslinfo?pretty").contains("CN=node-0.example.com,OU=SSL,O=Test,L=Test,C=DE")); }
protected static int resOf(Exception e) { if (e instanceof NoConnectionException || e instanceof ConnectException) { return R.string.exception_no_connection; } if (e instanceof ConnectTimeoutException || e instanceof SocketException || e instanceof SocketTimeoutException) { return R.string.exception_timeout; } if (e instanceof NoHttpResponseException || e instanceof FileNotFoundException || e instanceof EOFException || e instanceof UnknownHostException || e instanceof SSLException) { return R.string.exception_no_response; } if (e instanceof HttpStatusException) { return R.string.exception_http_status; } if (e instanceof ErrorCodeException) { try { String name = "exception_" + ((ErrorCodeException) e).getCode(); return R.string.class.getField(name).getInt(null); } catch (Exception ex) { return 0; } } return 0; }
private String sendQ(String query, int timeout) throws ClientProtocolException, IOException, NoHttpResponseException { logger.trace("Send query (timeout={}): {}", timeout, query); postReq.setEntity(new StringEntity(query, "UTF-8")); postReq.addHeader("content-type", "text/xml"); final RequestConfig params = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setSocketTimeout(timeout).build(); postReq.setConfig(params); // Execute POST HttpResponse response = client.execute(postReq, IhcConnectionPool .getInstance().getHttpContext()); String resp = EntityUtils.toString(response.getEntity()); logger.trace("Received response: {}", resp); return resp; }
public String getHTMLContent(String target) { log.info(">>> start get html context from url <" + target + "> <<<"); get = new HttpGet(target); try { resp = hc.execute(get); if (resp == null) { return null; } if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK ) { entity = resp.getEntity(); if (entity != null) { log.info(">>> end get html context from url <" + target + "> <<<"); return IOUtils.getString(entity.getContent(), encoding); } } return null; } catch (Exception e) { if (e instanceof NoHttpResponseException) { log.warn("*********** The target server failed to respond ***********"); return null; } log.error("get target " + target + " html content occurrence error", e); return null; } }
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试3次 if (executionCount >= 3) { // 如果连接次数超过了最大值则停止重试 return false; } if (exception instanceof NoHttpResponseException) { // 如果服务器连接失败重试 return true; } if (exception instanceof SSLHandshakeException) { // 不要重试ssl连接异常 return false; } HttpRequest request = (HttpRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // 重试,如果请求是考虑幂等 return true; } return false; }
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试errorRetryCount次 if (executionCount >= errorRetryCount) { // Do not retry if over max retry count System.out.println("errors"); return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // Retry if the request is considered idempotent return true; } return false; }
@Test(expected = NoHttpResponseException.class) public void testHttpsOnly() throws Exception { TestMetricsReporter.reset(); Properties props = new Properties(); String uri = "https://localhost:8080"; props.put(RestConfig.LISTENERS_CONFIG, uri); props.put(RestConfig.METRICS_REPORTER_CLASSES_CONFIG, "io.confluent.rest.TestMetricsReporter"); configServerKeystore(props); TestRestConfig config = new TestRestConfig(props); SslTestApplication app = new SslTestApplication(config); try { app.start(); int statusCode = makeGetRequest(uri + "/test", clientKeystore.getAbsolutePath(), SSL_PASSWORD, SSL_PASSWORD); assertEquals(EXPECTED_200_MSG, 200, statusCode); assertMetricsCollected(); makeGetRequest("http://localhost:8080/test"); } finally { app.stop(); } }
private String sendQ(String query, int timeout) throws ClientProtocolException, IOException, NoHttpResponseException { logger.trace("Send query (timeout={}): {}", timeout, query); postReq.setEntity(new StringEntity(query, "UTF-8")); postReq.addHeader("content-type", "text/xml"); final RequestConfig params = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeout) .build(); postReq.setConfig(params); // Execute POST HttpResponse response = client.execute(postReq, IhcConnectionPool.getInstance().getHttpContext()); String resp = EntityUtils.toString(response.getEntity()); logger.trace("Received response: {}", resp); return resp; }
private boolean shouldRetry(RequestMessage request, Exception exception, int statusCode, int retries) { if (retries >= this.config.getMaxErrorRetry()) { return false; } if (!request.isRepeatable()) { return false; } if (((exception instanceof SocketException)) || ((exception instanceof SocketTimeoutException)) || ((exception instanceof NoHttpResponseException))) { log.debug("Retrying on " + exception.getClass().getName() + ": " + exception.getMessage()); return true; } if ((statusCode == 500) || (statusCode == 503)) { log.debug("Retrying on " + exception.getClass().getName() + ": " + exception.getMessage()); return true; } return false; }
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 重试1次,从1开始 if (executionCount > 1) { return false; } if (exception instanceof NoHttpResponseException) { return false; } else if (exception instanceof SocketException) { return false; } return false; }
/** * Validate the given response as contained in the HttpPost object, * throwing an exception if it does not correspond to a successful HTTP response. * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid * parsing the response body and trying to deserialize from a corrupted stream. * @param config the HTTP invoker configuration that specifies the target service * @param response the resulting HttpResponse to validate * @throws java.io.IOException if validation failed */ protected void validateResponse(HttpInvokerClientConfiguration config, HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 300) { throw new NoHttpResponseException( "Did not receive successful HTTP response: status code = " + status.getStatusCode() + ", status message = [" + status.getReasonPhrase() + "]"); } }
@Override protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new NoHttpResponseException("The target server failed to respond"); } //create the status line from the status string ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); return this.responseFactory.newHttpResponse(statusline, null); }
@Override protected HttpResponse parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new NoHttpResponseException("The target server failed to respond"); } //create the status line from the status string ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); return this.responseFactory.newHttpResponse(statusline, null); }
protected BackgroundException wrap(final T failure, final String title, final StringBuilder buffer) { if(buffer.toString().isEmpty()) { log.warn(String.format("No message for failure %s", failure)); this.append(buffer, LocaleFactory.localizedString("Interoperability failure", "Error")); } for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof InterruptedIOException) { // Handling socket timeouts return new ConnectionTimeoutException(buffer.toString(), failure); } if(cause instanceof TimeoutException) { // return new ConnectionTimeoutException(buffer.toString(), failure); } if(cause instanceof SocketException) { return new DefaultSocketExceptionMappingService().map((SocketException) cause); } if(cause instanceof EOFException) { return new ConnectionRefusedException(buffer.toString(), failure); } if(cause instanceof UnknownHostException) { return new ResolveFailedException(buffer.toString(), failure); } if(cause instanceof NoHttpResponseException) { return new ConnectionRefusedException(buffer.toString(), failure); } } return new BackgroundException(title, buffer.toString(), failure); }
@Override public Type determine(final BackgroundException failure) { if(log.isDebugEnabled()) { log.debug(String.format("Determine cause for failure %s", failure)); } if(failure instanceof ConnectionTimeoutException) { return Type.network; } if(failure instanceof ConnectionRefusedException) { return Type.network; } if(failure instanceof ResolveFailedException) { return Type.network; } if(failure instanceof SSLNegotiateException) { return Type.application; } for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof SSLException) { return Type.network; } if(cause instanceof NoHttpResponseException) { return Type.network; } if(cause instanceof ConnectTimeoutException) { return Type.network; } if(cause instanceof SocketException || cause instanceof TimeoutException // Used in Promise#retrieve || cause instanceof SocketTimeoutException || cause instanceof UnknownHostException) { return Type.network; } } return Type.application; }
public boolean retryRequest(IOException iOException, int i, HttpContext httpContext) { if (i >= 3) { return false; } String str; if (iOException instanceof NoHttpResponseException) { str = a; return true; } else if ((!(iOException instanceof SocketException) && !(iOException instanceof SSLException)) || iOException.getMessage() == null || !iOException.getMessage().contains("Broken pipe")) { return false; } else { str = a; return true; } }
@Test public void testRetryOnMissingHttpResponse() throws Exception { final byte[] requestBytes = "fake_request".getBytes(UTF_8); final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class); final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class); final StatusLine badStatusLine = mock(StatusLine.class); final StatusLine goodStatusLine = mock(StatusLine.class); final StringEntity responseEntity = new StringEntity("success"); final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() { private int iteration = 0; @Override public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable { iteration++; if (1 == iteration) { throw new NoHttpResponseException("The server didn't respond!"); } else { return goodResponse; } } }; final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class); when(client.send(any(byte[].class))).thenCallRealMethod(); when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed); when(badResponse.getStatusLine()).thenReturn(badStatusLine); when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE); when(goodResponse.getStatusLine()).thenReturn(goodStatusLine); when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK); when(goodResponse.getEntity()).thenReturn(responseEntity); byte[] responseBytes = client.send(requestBytes); assertEquals("success", new String(responseBytes, UTF_8)); }
public static CloseableHttpClient createHttpClient() { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); ConnectionSocketFactory sslsf = new EasySSLConnectionSocketFactory(); //SSLConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); // 将最大连接数增加到200 cm.setMaxTotal(200); // 将每个路由基础的连接增加到20 cm.setDefaultMaxPerRoute(20); //请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; }
@Override protected HttpResponse parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); final int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new NoHttpResponseException("The target server failed to respond"); } //create the status line from the status string final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); return this.responseFactory.newHttpResponse(statusline, null); }
@Test(expectedExceptions = CloudApiIOException.class) public void canHandleNoResponseException() throws IOException { final CloudApiConnectionContext mockContext = mock(CloudApiConnectionContext.class); when(mockContext.getHttpContext()).thenReturn(new HttpClientContext()); final HttpClient mockClient = mock(HttpClient.class); when(mockContext.getHttpClient()).thenReturn(mockClient); when(mockClient.execute( isA(HttpUriRequest.class), (ResponseHandler<?>)isA(ResponseHandler.class), isA(HttpContext.class) )).thenThrow(new NoHttpResponseException("No Response Simulation")); instanceApi.findById(mockContext, new UUID(0L, 0L)); }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { boolean retry = super.retryRequest(exception, executionCount, context); if (!retry && exception instanceof NoHttpResponseException && executionCount < 5) { return true; } else { return retry; } }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) {// 如果已经重试了3次,就放弃 logger.info("executionCount:" + executionCount); return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof SocketException) { logger.info("SocketException retry request." ); return true; } if (exception instanceof UnknownHostException) { return true; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }
@Test( expected = NoHttpResponseException.class ) // This test exists for demonstration purpose only, it do not test usefull things but it's on purpose public void testNoSSL() throws IOException { HttpGet get = new HttpGet( "http://127.0.0.1:" + httpsPort + "/hello" ); defaultHttpClient.execute( get ); fail( "We could reach the HTTPS connector using a HTTP url, that's no good" ); }
public boolean retryRequest(IOException exception, int executionCount, HttpContext context){ // 设置恢复策略,在发生异常时候将自动重试DEFAULT_MAX_RETRIES次 if (executionCount >= DEFAULT_MAX_RETRIES){ // 如果超过最大重试次数,那么就不要继续了 AbLogUtil.d(mContext, "超过最大重试次数,不重试"); return false; } if (exception instanceof NoHttpResponseException){ // 如果服务器丢掉了连接,那么就重试 AbLogUtil.d(mContext, "服务器丢掉了连接,重试"); return true; } if (exception instanceof SSLHandshakeException){ // SSL握手异常,不重试 AbLogUtil.d(mContext, "ssl 异常 不重试"); return false; } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent){ // 如果请求被认为是幂等的,那么就重试 AbLogUtil.d(mContext, "请求被认为是幂等的,重试"); return true; } if (exception != null){ return true; } return false; }
@Bean public Http exampleHttp(final AsyncClientHttpRequestFactory requestFactory, final ClientHttpMessageConverters converters, final GaugeService gaugeService, final ScheduledExecutorService scheduler) { return Http.builder() .baseUrl("https://www.example.com") .urlResolution(UrlResolution.RFC) .requestFactory(requestFactory) .converters(converters.getConverters()) .plugin(new MetricsPlugin(gaugeService, new ZMONMetricsNameGenerator())) .plugin(new TransientFaultPlugin( FaultClassifier.create(ImmutableList.<Predicate<Throwable>>builder() .addAll(FaultClassifier.defaults()) .add(ConnectionClosedException.class::isInstance) .add(NoHttpResponseException.class::isInstance) .build()))) .plugin(new FailsafePlugin(scheduler) .withRetryPolicy(new RetryPolicy() .retryOn(TransientFaultException.class) .withBackoff(50, 2000, MILLISECONDS) .withMaxRetries(10) .withMaxDuration(2, SECONDS) .withJitter(0.2)) .withCircuitBreaker(new CircuitBreaker() .withFailureThreshold(5, 5) .withDelay(30, SECONDS) .withSuccessThreshold(3, 5) .withTimeout(3, SECONDS))) .plugin(new BackupRequestPlugin(scheduler, 10, MILLISECONDS)) .plugin(new TimeoutPlugin(scheduler, 3, SECONDS)) .plugin(new OriginalStackTracePlugin()) .plugin(new CustomPlugin()) .build(); }
@Test public void testHttpsFail() throws Exception { thrown.expect(NoHttpResponseException.class); enableSSL = false; final Settings settings = Settings .settingsBuilder() .putArray("armor.authentication.authorization.settingsdb.roles.jacksonm", "ceo") .put("armor.authentication.settingsdb.user.jacksonm", "secret") .put("armor.authentication.authorizer.impl", "com.petalmd.armor.authorization.simple.SettingsBasedAuthorizator") .put("armor.authentication.authorizer.cache.enable", "false") .put("armor.authentication.authentication_backend.impl", "com.petalmd.armor.authentication.backend.simple.SettingsBasedAuthenticationBackend") .put("armor.authentication.authentication_backend.cache.enable", "false") .put("armor.ssl.transport.http.enabled", true) .put("armor.ssl.transport.http.enforce_clientauth", true) .put("armor.ssl.transport.http.keystore_filepath", SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")) .put("armor.ssl.transport.http.truststore_filepath", SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")).build(); username = "jacksonm"; password = "secret"; searchOnlyAllowed(settings, false); }
/** * Returns true if a failed request should be retried. * * @param method The current HTTP method being executed. * @param t The throwable from the failed request. * @param retries The number of times the current request has been attempted. * @return True if the failed request should be retried. */ private boolean shouldRetry(HttpRequestBase method, Throwable t, int retries) { if (retries > this.numRetries) { return false; } if (method instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) method).getEntity(); if (entity != null && !entity.isRepeatable()) { return false; } } if (t instanceof NoHttpResponseException || t instanceof SocketException || t instanceof SocketTimeoutException || t instanceof ConnectTimeoutException) { log.debug("Retrying on {}: {}", t.getClass().getName(), t.getMessage()); return true; } if (t instanceof RestException) { RestException re = (RestException) t; /* * Throttling is reported as a 429 error. To try * and smooth out an occasional throttling error, we'll pause and * retry, hoping that the pause is long enough for the request to * get through the next time. */ if (isThrottlingException(re)) return true; } return false; }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { System.out.println("$$$###MyHttpRequestRetryHandler retryRequest"); if (executionCount >= MAX_RETRY_TIMES) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotentreturn true; return true; } return false; }
/** * Determine if a request to Solr failed due to a communication error, * which is generally retry-able. */ public static boolean checkCommunicationError(Exception exc) { Throwable rootCause = SolrException.getRootCause(exc); boolean wasCommError = (rootCause instanceof ConnectException || rootCause instanceof ConnectTimeoutException || rootCause instanceof NoHttpResponseException || rootCause instanceof SocketException); return wasCommError; }
@Test public void httpClientIsRefused() { Client client = new JerseyClientBuilder(USER_INFO_APP_RULE.getEnvironment()).build("http client"); try { client.target(String.format("http://localhost:%d/users", 8443)) .request() .header("Authorization", "Bearer " + adminJWT) .get(new GenericType<List<UserInfo>>() { }); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { assertThat(e).hasCauseExactlyInstanceOf(NoHttpResponseException.class); } }