List of usage examples for java.net SocketTimeoutException SocketTimeoutException
public SocketTimeoutException(String msg)
From source file:fr.xebia.monitoring.demo.payment.TimeoutPaymentException.java
public TimeoutPaymentException(String message, PaymentTransaction paymentTransaction) { super(message, paymentTransaction); initCause(new SocketTimeoutException("Something bad happened on the network")); }
From source file:com.android.volley.toolbox.AdaptedHttpStack.java
@Override public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { org.apache.http.HttpResponse apacheResp; try {//from w ww . j a v a2 s. co m apacheResp = mHttpStack.performRequest(request, additionalHeaders); } catch (ConnectTimeoutException e) { // BasicNetwork won't know that this exception should be retried like a timeout, since // it's an Apache-specific error, so wrap it in a standard timeout exception. throw new SocketTimeoutException(e.getMessage()); } int statusCode = apacheResp.getStatusLine().getStatusCode(); org.apache.http.Header[] headers = apacheResp.getAllHeaders(); List<Header> headerList = new ArrayList<>(headers.length); for (org.apache.http.Header header : headers) { headerList.add(new Header(header.getName(), header.getValue())); } if (apacheResp.getEntity() == null) { return new HttpResponse(statusCode, headerList); } long contentLength = apacheResp.getEntity().getContentLength(); if ((int) contentLength != contentLength) { throw new IOException("Response too large: " + contentLength); } return new HttpResponse(statusCode, headerList, (int) apacheResp.getEntity().getContentLength(), apacheResp.getEntity().getContent()); }
From source file:org.myframe.http.Network.java
/** * /*from w ww . j a v a 2s. co m*/ * * @param request * * @return ?null? * @throws KJHttpException */ public NetworkResponse performRequest(Request<?> request) throws KJHttpException { while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try { // Http?Cachetag Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // 304 return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders, true); } if (httpResponse.getEntity() != null) { if (request instanceof FileRequest) { responseContents = ((FileRequest) request).handleResponse(httpResponse); } else { responseContents = entityToBytes(httpResponse.getEntity()); } } else { responseContents = new byte[0]; } if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { throw new KJHttpException(new SocketTimeoutException("socket timeout")); } catch (ConnectTimeoutException e) { throw new KJHttpException(new SocketTimeoutException("socket timeout")); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new KJHttpException("NoConnection error", e); } MLoger.debug("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { throw new KJHttpException("auth error"); } else { throw new KJHttpException("server error, Only throw ServerError for 5xx status codes.", networkResponse); } } else { throw new KJHttpException(networkResponse); } } } }
From source file:org.kymjs.kjframe.http.Network.java
/** * //w ww.j av a 2s.c o m * * @param request * * @return ?null? * @throws KJHttpException */ public NetworkResponse performRequest(Request<?> request) throws KJHttpException { while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try { // Http?Cachetag Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // 304 return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders, true); } if (httpResponse.getEntity() != null) { if (request instanceof FileRequest) { responseContents = ((FileRequest) request).handleResponse(httpResponse); } else { responseContents = entityToBytes(httpResponse.getEntity()); } } else { responseContents = new byte[0]; } if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { throw new KJHttpException(new SocketTimeoutException("socket timeout")); } catch (ConnectTimeoutException e) { throw new KJHttpException(new SocketTimeoutException("socket timeout")); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new KJHttpException("NoConnection error", e); } KJLoger.debug("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { throw new KJHttpException("auth error"); } else { throw new KJHttpException("server error, Only throw ServerError for 5xx status codes.", networkResponse); } } else { throw new KJHttpException(networkResponse); } } } }
From source file:com.scut.easyfe.network.kjFrame.http.Network.java
/** * //from www . java2 s .c o m * * @param request * * @return ?null? * @throws KJHttpException */ public NetworkResponse performRequest(Request<?> request) throws KJHttpException { while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try { // Http?Cachetag Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // 304 return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders, true); } if (httpResponse.getEntity() != null) { if (request instanceof FileRequest) { responseContents = ((FileRequest) request).handleResponse(httpResponse); } else { responseContents = entityToBytes(httpResponse.getEntity()); } } else { responseContents = new byte[0]; } if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { throw new KJHttpException(new SocketTimeoutException("socket timeout")); } catch (ConnectTimeoutException e) { throw new KJHttpException(new SocketTimeoutException("socket timeout")); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new KJHttpException("NoConnection error", e); } KJLoger.debug("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { throw new KJHttpException("auth error", networkResponse); } else { throw new KJHttpException("server error, Only throw ServerError for 5xx status codes.", networkResponse); } } else { throw new KJHttpException(networkResponse); } } } }
From source file:com.alibaba.wasp.client.ServerCallable.java
public void shouldRetry(Throwable throwable) throws IOException { if (this.callTimeout != FConstants.DEFAULT_WASP_CLIENT_OPERATION_TIMEOUT) if (throwable instanceof SocketTimeoutException || (this.endTime - this.startTime > this.callTimeout)) { throw (SocketTimeoutException) (SocketTimeoutException) new SocketTimeoutException( "Call to access row '" + Bytes.toString(row) + "' on table '" + Bytes.toString(tableName) + "' failed on socket timeout exception: " + throwable).initCause(throwable); } else {/*from w w w . ja v a 2 s. c o m*/ this.callTimeout = ((int) (this.endTime - this.startTime)); } }
From source file:org.elasticsearch.client.RestClientMultipleHostsTests.java
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))) .thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock .getArguments()[0]; HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest(); HttpHost httpHost = requestProducer.getTarget(); HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock .getArguments()[3]; //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/ioe")) { futureCallback.failed(new IOException(httpHost.toString())); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); futureCallback.completed(new BasicHttpResponse(statusLine)); }//from w w w . j av a 2s. c o m return null; } }); int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5); httpHosts = new HttpHost[numHosts]; for (int i = 0; i < numHosts; i++) { httpHosts[i] = new HttpHost("localhost", 9200 + i); } failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener); }
From source file:com.cyberway.issue.crawler.fetcher.HeritrixProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit.//from w w w . ja v a2 s. c o m * <p> * This method employs several techniques to circumvent the limitations * of older JREs that do not support connect timeout. When running in * JRE 1.4 or above reflection is used to call * Socket#connect(SocketAddress endpoint, int timeout) method. When * executing in older JREs a controller thread is executed. The * controller thread attempts to create a new socket within the given * limit of time. If socket constructor does not return until the * timeout expires, the controller terminates and throws an * {@link ConnectTimeoutException} * </p> * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * * @since 3.0 */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { socket = new Socket(); ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY); InetAddress hostAddress = (cache != null) ? getHostAddress(cache, host) : null; InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:com.cyberway.issue.crawler.fetcher.HeritrixSSLProtocolSocketFactory.java
public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); }// w ww . j a v a 2s . co m Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY); SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory; socket = f.createSocket(); ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY); InetAddress hostAddress = (cache != null) ? HeritrixProtocolSocketFactory.getHostAddress(cache, host) : null; InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:com.buaa.cfs.net.SocketIOWithTimeout.java
/** * Performs one IO and returns number of bytes read or written. It waits up to the specified timeout. If the channel * is not read before the timeout, SocketTimeoutException is thrown. * * @param buf buffer for IO//w ww.j a v a 2 s . c om * @param ops Selection Ops used for waiting. Suggested values: SelectionKey.OP_READ while reading and * SelectionKey.OP_WRITE while writing. * * @return number of bytes read or written. negative implies end of stream. * * @throws IOException */ int doIO(ByteBuffer buf, int ops) throws IOException { /* For now only one thread is allowed. If user want to read or write * from multiple threads, multiple streams could be created. In that * case multiple threads work as well as underlying channel supports it. */ if (!buf.hasRemaining()) { throw new IllegalArgumentException("Buffer has no data left."); //or should we just return 0? } while (buf.hasRemaining()) { if (closed) { return -1; } try { int n = performIO(buf); if (n != 0) { // successful io or an error. return n; } } catch (IOException e) { if (!channel.isOpen()) { closed = true; } throw e; } //now wait for socket to be ready. int count = 0; try { count = selector.select(channel, ops, timeout); } catch (IOException e) { //unexpected IOException. closed = true; throw e; } if (count == 0) { throw new SocketTimeoutException(timeoutExceptionString(channel, timeout, ops)); } // otherwise the socket should be ready for io. } return 0; // does not reach here. }