Example usage for java.net SocketTimeoutException SocketTimeoutException

List of usage examples for java.net SocketTimeoutException SocketTimeoutException

Introduction

In this page you can find the example usage for java.net SocketTimeoutException SocketTimeoutException.

Prototype

public SocketTimeoutException() 

Source Link

Document

Construct a new SocketTimeoutException with no detailed message.

Usage

From source file:com.aliyun.oss.common.utils.ExceptionFactoryTest.java

@Test
public void testCreateNetworkException() {
    SocketTimeoutException ste = new SocketTimeoutException();
    ClientException ex = ExceptionFactory.createNetworkException(ste);
    assertEquals(ex.getErrorCode(), ClientErrorCode.SOCKET_TIMEOUT);
    ConnectTimeoutException cte = new ConnectTimeoutException();
    ex = ExceptionFactory.createNetworkException(cte);
    assertEquals(ex.getErrorCode(), ClientErrorCode.CONNECTION_TIMEOUT);
    IOException ioe = new IOException();
    ex = ExceptionFactory.createNetworkException(ioe);
    assertEquals(ex.getErrorCode(), ClientErrorCode.UNKNOWN);
}

From source file:bad.robot.http.apache.ApacheExceptionWrappingExecutorTest.java

@Test
public void wrapsSocketTimeoutException() {
    exception.expect(HttpSocketTimeoutException.class);
    exception.expect(new ThrowableCauseMatcher(SocketTimeoutException.class));
    wrapper.submit(throwsException(new SocketTimeoutException()));
}

From source file:com.sharethis.loopy.test.NetworkStateTest.java

public void testShortenReturnsWhenNoNetwork() throws InterruptedException, IOException {

    Session.getInstance().waitForStart();

    final String url = "foobar";
    final Holder<Item> result = new Holder<Item>();
    final Holder<Throwable> resultThrowable = new Holder<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);

    HttpClientFactory httpClientFactory = Mockito.mock(HttpClientFactory.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    final LoopyState state = Mockito.mock(LoopyState.class);

    ApiClient client = new ApiClient() {
        @Override// ww w. j ava2 s.  co  m
        public LoopyState getState() {
            return state;
        }
    };

    Mockito.when(state.hasSTDID()).thenReturn(true);
    Mockito.when(state.getSTDID()).thenReturn("foobar_stdid");

    Mockito.when(httpClientFactory.getClient()).thenReturn(httpClient);
    Mockito.when(httpClient.execute((HttpPost) Mockito.any())).thenThrow(new SocketTimeoutException());

    LoopyAccess.setApiClient(client);
    LoopyAccess.setHttpClientFactory(httpClientFactory);

    Loopy.shorten(url, new ShareCallback() {
        @Override
        public void onResult(Item item, Throwable error) {
            result.set(item);
            resultThrowable.set(error);
            latch.countDown();
        }
    });

    assertTrue(latch.await(2, TimeUnit.SECONDS));

    Item after = result.get();
    Throwable error = resultThrowable.get();

    assertNotNull(after);

    // We expect an error because the network is down
    assertNotNull(error);

    assertTrue(error instanceof LoopyException);

    LoopyException le = (LoopyException) error;

    assertEquals(LoopyException.CLIENT_TIMEOUT, le.getCode());

    assertEquals(url, after.getUrl());
    assertNull(after.getShortlink());

    Mockito.verify(httpClient).execute((HttpPost) Mockito.any());
}

From source file:idgs.client.TcpClient.java

private synchronized void select() throws IOException {
    if (timeout > 0) {
        if (selector.select(timeout) == 0) {
            throw new SocketTimeoutException();
        }/*w ww.  j av a 2s .  c o m*/
    } else {
        selector.select();
    }

    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
        SelectionKey key = it.next();
        // handle connect
        if (key.isConnectable()) {
            processConnect(key);
        }
        // handle read
        else if (key.isReadable()) {
            processRead(key);
        }
        // handle write
        else if (key.isWritable()) {
            processWrite(key);
        }
        it.remove();
    }
}

From source file:ch.cyberduck.core.SingleTransferWorkerTest.java

@Test
public void testTransferredSizeRepeat() throws Exception {
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new byte[62768];
    new Random().nextBytes(content);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);/*from  w  w  w.  j a  v  a2 s . c  om*/
    out.close();
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final AtomicBoolean failed = new AtomicBoolean();
    final DAVSession session = new DAVSession(host) {
        final DAVUploadFeature upload = new DAVUploadFeature(this) {
            @Override
            protected InputStream decorate(final InputStream in, final MessageDigest digest)
                    throws IOException {
                if (failed.get()) {
                    // Second attempt successful
                    return in;
                }
                return new CountingInputStream(in) {
                    @Override
                    protected void beforeRead(final int n) throws IOException {
                        super.beforeRead(n);
                        if (this.getByteCount() >= 32768L) {
                            failed.set(true);
                            throw new SocketTimeoutException();
                        }
                    }
                };
            }
        };

        @Override
        @SuppressWarnings("unchecked")
        public <T> T getFeature(final Class<T> type) {
            if (type == Upload.class) {
                return (T) upload;
            }
            return super.getFeature(type);
        }
    };
    session.open(new DisabledHostKeyCallback(), new DisabledTranscriptListener());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local);
    final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener());
    assertTrue(new SingleTransferWorker(session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledTransferItemCallback(),
            new DisabledProgressListener(), counter, new DisabledLoginCallback(), TransferItemCache.empty()) {

    }.run(session));
    local.delete();
    assertEquals(62768L, counter.getSent(), 0L);
    assertEquals(62768L, new DAVAttributesFeature(session).find(test).getSize());
    assertTrue(failed.get());
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:co.elastic.tealess.SSLChecker.java

private void checkConnect(SSLReport sslReport, SocketChannel socket, long timeout) {
    final InetSocketAddress address = sslReport.getAddress();
    try {/* w  w w. j a va  2s. com*/
        logger.trace("Connecting to {}", address);
        Selector selector = Selector.open();
        SelectionKey sk = socket.register(selector, SelectionKey.OP_CONNECT);
        socket.connect(address);
        selector.select(timeout);
        if (!sk.isConnectable()) {
            sslReport.setFailed(new SocketTimeoutException());
            return;
        }
        if (socket.isConnectionPending()) {
            socket.finishConnect();
        }
    } catch (ConnectException e) {
        logger.debug("Connection failed to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    } catch (IOException e) {
        logger.error("Failed connecting to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    }

    logger.debug("Connection successful to {}", address);
}

From source file:ch.cyberduck.core.worker.SingleTransferWorkerTest.java

@Test
public void testTransferredSizeRepeat() throws Exception {
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new byte[62768];
    new Random().nextBytes(content);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);/*from   ww w  .  ja va2s .  c o  m*/
    out.close();
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final AtomicBoolean failed = new AtomicBoolean();
    final DAVSession session = new DAVSession(host) {
        final DAVUploadFeature upload = new DAVUploadFeature(new DAVWriteFeature(this)) {
            @Override
            protected InputStream decorate(final InputStream in, final MessageDigest digest)
                    throws IOException {
                if (failed.get()) {
                    // Second attempt successful
                    return in;
                }
                return new CountingInputStream(in) {
                    @Override
                    protected void beforeRead(final int n) throws IOException {
                        super.beforeRead(n);
                        if (this.getByteCount() >= 32768L) {
                            failed.set(true);
                            throw new SocketTimeoutException();
                        }
                    }
                };
            }
        };

        @Override
        @SuppressWarnings("unchecked")
        public <T> T _getFeature(final Class<T> type) {
            if (type == Upload.class) {
                return (T) upload;
            }
            return super._getFeature(type);
        }
    };
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local);
    final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener());
    assertTrue(new SingleTransferWorker(session, session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledProgressListener(), counter,
            new DisabledLoginCallback(), new DisabledPasswordCallback(), TransferItemCache.empty()) {

    }.run(session, session));
    local.delete();
    assertEquals(62768L, counter.getSent(), 0L);
    assertEquals(62768L, new DAVAttributesFinderFeature(session).find(test).getSize());
    assertTrue(failed.get());
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:org.elasticsearch.client.RestHighLevelClientTests.java

public void testPingSocketTimeout() throws IOException {
    Header[] headers = RestClientTestUtil.randomHeaders(random(), "Header");
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(),
            anyVararg())).thenThrow(new SocketTimeoutException());
    expectThrows(SocketTimeoutException.class, () -> restHighLevelClient.ping(headers));
    verify(restClient).performRequest(eq("HEAD"), eq("/"), eq(Collections.emptyMap()),
            Matchers.isNull(HttpEntity.class), argThat(new HeadersVarargMatcher(headers)));
}

From source file:org.elasticsearch.client.RestClientSingleHostTests.java

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    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];
                            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
                            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
                            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock
                                    .getArguments()[3];
                            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
                            //return the desired status code or exception depending on the path
                            if (request.getURI().getPath().equals("/soe")) {
                                futureCallback.failed(new SocketTimeoutException());
                            } else if (request.getURI().getPath().equals("/coe")) {
                                futureCallback.failed(new ConnectTimeoutException());
                            } else {
                                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1),
                                        statusCode, "");

                                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                                //return the same body that was sent
                                if (request instanceof HttpEntityEnclosingRequest) {
                                    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                                    if (entity != null) {
                                        assertTrue(
                                                "the entity is not repeatable, cannot set it to the response directly",
                                                entity.isRepeatable());
                                        httpResponse.setEntity(entity);
                                    }//from w  ww. jav  a  2s  .co m
                                }
                                //return the same headers that were sent
                                httpResponse.setHeaders(request.getAllHeaders());
                                futureCallback.completed(httpResponse);
                            }
                            return null;
                        }
                    });

    defaultHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header-default");
    httpHost = new HttpHost("localhost", 9200);
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, defaultHeaders, new HttpHost[] { httpHost }, null,
            failureListener);
}

From source file:net.lightbody.bmp.proxy.jetty.http.nio.ByteBufferInputStream.java

private synchronized boolean waitForContent() throws InterruptedIOException {
    if (_buffer != null) {
        if (_buffer.hasRemaining())
            return true;

        // recycle buffer
        recycle(_buffer);/* w w w  . j  a va  2  s .  c  o m*/
        _buffer = null;
    }

    while (!_closed && LazyList.size(_buffers) == 0) {
        try {
            this.wait(_timeout);
        } catch (InterruptedException e) {
            log.debug(e);
            throw new InterruptedIOException(e.toString());
        }
    }

    if (_closed)
        return false;

    if (LazyList.size(_buffers) == 0)
        throw new SocketTimeoutException();

    _buffer = (ByteBuffer) LazyList.get(_buffers, 0);
    _buffers = LazyList.remove(_buffers, 0);

    return true;
}